I am trying to calculate the surface normal of a triangle in C++ (and OpenGL) based on the 3 vertices of the triangle. I am getting correct results for a non rotated triangle, however I am getting semi-correct result for a rotated triangle. Not sure what I am doing wrong. The expected result should be returning a vector (1, 0, 0) for triangle 1 (non rotated) and (0, 0, -1) for triangle 2 (rotated 90 degrees on Y axis), however I get (1, 0, 0) for triangle 1 and (-4.15243e-08, 1.82413e-08, -1)
As you can see, the first vector and the Z component of the second normal vector is correct, however the X and Y components of the second vector are largely inaccurate as they should both be zero
My code is a very simple function making use of GLM:
void CalcSurfaceNormal(glm::vec3 tri1, glm::vec3 tri2, glm::vec3 tri3)
{
//tri1 tri2 and tri3 are the triangles 3 vertices
//Simple algorithm followed from another stack overflow article
glm::vec3 u = tri2 - tri1;
glm::vec3 v = tri3 - tri1;
glm::vec3 nrmcross = glm::cross(u, v);
nrmcross = glm::normalize(nrmcross);
std::cout << "NormalCrs " << nrmcross.x << " " << nrmcross.y << " " << nrmcross.z << "\n";
}
Additional info: The triangle arguments go unchanged as of right now so I can get it working
The first correct call has these vec3s passed in: (0.970976, -0.0246142, -0.0621899) (0.970976, 0.0553858, 0.0178101)' (0.970976, -0.0246142, 0.117237)
The second call which has the last z component correct has these vec3s passed in: (1.93781, 0.0246142, 0.0290235) (2.01781, 0.0553858, 0.0290235) (2.11724, -0.0246142, 0.0290235)