I'm trying to render a triangle mesh with Phong shading using GLSL, here is my method to assign normals.
void renderWireframe(Mesh *mesh)
{
glDepthMask(GL_TRUE);
glBegin(GL_TRIANGLES);
for(int i=0; i<mesh->nt; i++) { //nv is the mesh's number of triangles
int i0 = mesh->triangles[i].vInds[0];
int i1 = mesh->triangles[i].vInds[1];
int i2 = mesh->triangles[i].vInds[2];
//Calculate normals for each vertex
Vector fv0 = getvertexnormal(mesh, i0);
Vector fv1 = getvertexnormal(mesh, i1);
Vector fv2 = getvertexnormal(mesh, i2);
glNormal3dv((double *)&fv0);
glVertex3dv((double *)&mesh->vertices[i0]);
glNormal3dv((double *)&fv1);
glVertex3dv((double *)&mesh->vertices[i1]);
glNormal3dv((double *)&fv2);
glVertex3dv((double *)&mesh->vertices[i2]);
}
glEnd();
}
The getvertexnormal code looks like this:
Vector getvertexnormal(Mesh *mesh, int vertex){
int i = mesh->nt; //nt is the mesh's number of triangles
int *adjface;
adjface = new int[i]; //array to store adjacent faces
//Store each triangle which has an intersection with the vertex'th vertex
int nadjface = 0;
Triangle *t = mesh->triangles;
for (int ix = 0; ix < mesh->nt; ix++){
if(t[ix].vInds[0] == vertex){
adjface[nadjface++] = ix;
}
else
if (t[ix].vInds[1] == vertex)
adjface[nadjface++] = ix;
else
if (t[ix].vInds[2] == vertex)
adjface[nadjface++] = ix;
}
// Average all adjacent triangles normals to get the vertex normal
Vector norm = {0.0, 0.0, 0.0};
for (int jx = 0; jx < nadjface; jx++){
int ixFace = adjface[jx];
norm.x += mesh->triangles[ixFace].vInds[0];
norm.y += mesh->triangles[ixFace].vInds[1];
norm.z += mesh->triangles[ixFace].vInds[2];
}
norm.x /= nadjface;
norm.y /= nadjface;
norm.z /= nadjface;
return Normalize(norm);
}
Everytime I run this it looks like it starts rendering and then after one second it crashes and gives me an exception:
"Unhandled exception at at 0x7562B727 in glutglsl.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0028F1C8."
The program works fine if I comment out the getvertexnomral() parts and instead of
glNormal3dv((double *)&fv0);
glVertex3dv((double *)&mesh->vertices[i0]);
glNormal3dv((double *)&fv1);
glVertex3dv((double *)&mesh->vertices[i1]);
glNormal3dv((double *)&fv2);
glVertex3dv((double *)&mesh->vertices[i2]);
I write
glNormal3dv((double *)&Normalize(mesh->vertices[i0]));
glVertex3dv((double *)&mesh->vertices[i2]);
glNormal3dv((double *)&Normalize(mesh->vertices[i1]));
glVertex3dv((double *)&mesh->vertices[i1]);
glNormal3dv((double *)&Normalize(mesh->vertices[i2]));
glVertex3dv((double *)&mesh->vertices[i2]);
but then it doesn't look right (https://i.stack.imgur.com/eJthY.jpg)
so I'm thinking there's a problem with getvertexnormal().
By the way I'm a complete novice at this stuff. I have all my phong calculation in my fragment shader (GLSL). To achieve phong shading on a large triangle mesh this is the way to go right?