Radar's picture

Tangent calculation

Hi all,

I am stuck with tangents. For some reason the just don't work perfectly. They are like 90% correct...
I really tried to get the hang of it for the past view days. But i guess i am too stupid for that.

I use the code below that i found on the internet. Is that one correct?
I get very strange lightning results when i have discontinous UV-Maps. And i am also not sure what to do with that.
If the surface is smoothed the vertex-normal is the sum of all surrounding surface-normals. Is is the same for tangents? Do i sum them too?

public static Vector4 CalculateTangentBinormal(Vector3 surfaceNormal, Vector3 v1Pos, Vector3 v2Pos, Vector3 v3Pos, Vector2 v1UV, Vector2 v2UV, Vector2 v3UV)
        {
            Vector4 tangent = new Vector4();
 
            Vector3 side_0 = v1Pos - v2Pos;
            Vector3 side_1 = v3Pos - v2Pos;
 
            float delta_U_0 = v1UV.X - v2UV.X;
            float delta_U_1 = v3UV.X - v2UV.X;
            float delta_V_0 = v1UV.Y - v2UV.Y;
            float delta_V_1 = v3UV.Y - v2UV.Y;
            tangent = new Vector4( new Vector3(delta_V_1 * side_0 - delta_V_0 * side_1), 0f);
            Vector3 biNormal = Vector3.Normalize(delta_U_1 * side_0 - delta_U_0 * side_1);
            Vector3 tangentCross = Vector3.Cross(tangent.Xyz, biNormal);
            tangent.Normalize();
            //wind the tangent into the other direction if necassary
            if (Vector3.Dot(tangentCross, surfaceNormal) < 0.0f)
            {
                biNormal  = -biNormal;
                tangent  *= -1.0f;
                tangent.W = -1.0f;
            }
            else
                tangent.W = 1.0f;
            return tangent;
 
            //binormal not stored atm.
        }

If you need other code (like shaders) to help me with the problem please tell me.

Thank you very much!!!