
void file_3ds::calculate_normals(void)
{
int i, j;
// Set all vertex normals to 0
for (i = 0; i < object->vertices_qty; i++)
{
for (j = 0; j < 3; j++)
{
object->vertex.norm[j] = 0.0;
}
}
// Loop through all faces
for(i = 0; i < object->polygons_qty; i++)
{
vector vec1;
vec1.x = object->vertex[object->face.b].x - object->vertex[object->face.a].x;
vec1.y = object->vertex[object->face.b].y - object->vertex[object->face.a].y;
vec1.z = object->vertex[object->face.b].z - object->vertex[object->face.a].z;
vector vec2;
vec2.x = object->vertex[object->face.c].x - object->vertex[object->face.a].x;
vec2.y = object->vertex[object->face.c].y - object->vertex[object->face.a].y;
vec2.z = object->vertex[object->face.c].z - object->vertex[object->face.a].z;
float x, y, z;
x = vec1.y * vec2.z - vec1.z * vec2.y;
y = vec1.z * vec2.x - vec1.x * vec2.z;
z = vec1.x * vec2.y - vec1.y * vec2.x;
float mag = sqrt(x*x + y*y + z*z);
/*
The following lines have been replaced
since they could cause errors
*/
// object->polygon.norm[0] = x / mag;
// object->polygon.norm[1] = y / mag;
// object->polygon.norm[2] = z / mag;
/*
This is the new code. It prevents
division of zero, which would cause an
error
*/
if(x != 0)
object->face.norm[0] = x / mag;
else
object->face.norm[0] = 0;
if(y != 0)
object->face.norm[1] = y / mag;
else
object->face.norm[1] = 0;
if(z != 0)
object->face.norm[2] = z / mag;
else
object->face.norm[2] = 0;
// Now we calculate the vertex normals
for (j = 0; j < 3; j++)
{
object->vertex[object->face.a].norm[j] += object->face.norm[j];
object->vertex[object->face.b].norm[j] += object->face.norm[j];
object->vertex[object->face.c].norm[j] += object->face.norm[j];
}
}
}
</pre>
Though I get proper lighting, Im suspecting its not 100% acurate, since it looks strange to me. One thing I noticed is that some areas can get very bright, and I think sometimes a surface is lit up when it shouldnt be, but im not sure… Is this code proper for calculating the normals? And if it is, should I render my faces by setting the normal of the face, and then for each vertex set the normal of that vertex as well?
Tx in advance </i>