I am trying to generate vertex normals for a given triangles/vertices list with the following code:
**BASE METHOD:**
private void CalculateNormals()
{
for (Int32 i = 0; i < m_Meshes.Count; ++i)
{
Mesh mesh = m_Meshes[i];
List<Point3D> vertices = mesh.GetVertices();
List<Triangle> triangles = mesh.GetTriangles();
List<Point3D> normals = new List<Point3D>(vertices.Count);
for (Int32 y = 0; y < vertices.Count; ++y)
normals.Add(new Point3D(0.0f, 0.0f, 0.0f));
for (Int32 y = 0; y < triangles.Count; ++y)
{
Triangle triangle = triangles[y];
UInt16 index1 = triangle.Index1;
UInt16 index2 = triangle.Index2;
UInt16 index3 = triangle.Index3;
Point3D vertex1 = vertices[index1];
Point3D vertex2 = vertices[index2];
Point3D vertex3 = vertices[index3];
Point3D a = vertex2 - vertex1;
Point3D b = vertex3 - vertex1;
Point3D normal = a % b;
normals[index1] += normal;
normals[index2] += normal;
normals[index3] += normal;
}
for (Int32 y = 0; y < normals.Count; ++y)
normals[y] = normals[y].Normalize();
mesh.AddNormals(normals);
}
}
**POINT3D METHODS & OPERATORS:**
public static Point3D operator +(Point3D left, Point3D right)
{
Single x = left.X + right.X;
Single y = left.Y + right.Y;
Single z = left.Z + right.Z;
return (new Point3D(x, y, z));
}
public static Point3D operator -(Point3D left, Point3D right)
{
Single x = left.X - right.X;
Single y = left.Y - right.Y;
Single z = left.Z - right.Z;
return (new Point3D(x, y, z));
}
public static Point3D operator /(Point3D point, Single value)
{
Single x = point.X / value;
Single y = point.Y / value;
Single z = point.Z / value;
return (new Point3D(x, y, z));
}
// Crossed Product
public static Point3D operator %(Point3D left, Point3D right)
{
Single x = (left.Y * right.Z) - (left.Z * right.Y);
Single y = (left.Z * right.X) - (left.X * right.Z);
Single z = (left.X * right.Y) - (left.Y * right.X);
return (new Point3D(x, y, z));
}
public Point3D Normalize()
{
Single magnitude = (Single)Math.Sqrt((m_X * m_X) + (m_Y * m_Y) + (m_Z * m_Z));
if (magnitude == 0.0f)
return (new Point3D(0.0f, 0.0f, 0.0f));
return (this / magnitude);
}
This is what I get:
What am I doing wrong? Can someone help me please?
EDIT:
I tried to do this process with a single mesh containing a single triangle to have a better control over what's going on in my algorithm. Here are the triangle vertices values:
Here are the values I get:
And here are the correct values automatically calculated by a plugin tool: