When I calculate and use my mesh's vertex normals my mesh gets rendered with flat shading. Same exact results as if I use face normals. I'm using the CML library for my vector structures and math. The problem might be in how I'm using CML so I have also posted on the CML forums. But I was wondering if you guys could give it a quick look and see if I'm making a stupid mistake somewhere...
Here is my code for calculating both face and vertex normals:
void Mesh::computeNormals() {
Vector3f vector1 = Vector3f(0, 0, 0);
Vector3f vector2 = Vector3f(0, 0, 0);
Vector3f sum = Vector3f(0, 0, 0);
int shared = 0;
for(int i = 0; i < numSubMeshes; i++) {
// Face Normals.
for(int j = 0; j < subMeshes.numTriangles; j++) {
vector1 = subMeshes.vertices[subMeshes.triangles[j].vertexIndices[2]].pos - subMeshes.vertices[subMeshes.triangles[j].vertexIndices[0]].pos;
vector2 = subMeshes.vertices[subMeshes.triangles[j].vertexIndices[1]].pos - subMeshes.vertices[subMeshes.triangles[j].vertexIndices[0]].pos;
subMeshes.triangles[j].normal = cml::cross(vector2, vector1);
}
// Vertex Normals.
shared = 0;
sum.set(0, 0, 0);
for(int j = 0; j < subMeshes.numVertices; j++) {
for(int k = 0; k < subMeshes.numTriangles; k++) {
if(subMeshes.triangles[k].vertexIndices[0] == j ||
subMeshes.triangles[k].vertexIndices[1] == j ||
subMeshes.triangles[k].vertexIndices[2] == j) {
sum += subMeshes.triangles[k].normal;
shared++;
}
}
subMeshes.vertices[j].normal = sum/(float)shared;
shared = 0;
sum.set(0, 0, 0);
}
// Normalize Both normals.
for(int j = 0; j < subMeshes.numTriangles; j++)
subMeshes.triangles[j].normal.normalize();
for(int j = 0; j < subMeshes.numVertices; j++)
subMeshes.vertices[j].normal.normalize();
}
}
And here for rendering (OpenGL):
void Renderer::preRenderSubMesh(const SubMesh& subMesh) {
glBegin(GL_TRIANGLES);
for(int j = 0; j < subMesh.numTriangles; j++) {
//glNormal3fv(subMesh.triangles[j].normal.data());
for(int k = 0; k < 3; k++) {
glNormal3fv(subMesh.vertices[subMesh.triangles[j].vertexIndices[k]].normal.data());
glTexCoord2fv(subMesh.vertices[subMesh.triangles[j].vertexIndices[k]].uv.data());
glVertex3fv(subMesh.vertices[subMesh.triangles[j].vertexIndices[k]].pos.data());
}
}
glEnd();
}