c++ - OpenGL .obj Loader: Model only lit correctly with incorrect normal vectors? -
i'm trying write program loads .obj files. reason, model lights incorrectly calculated normal vectors. haven't been able find online explains anomaly.
this how calculating normals, believe correct way.
vector<float> vertex::findnormal(vertex v2, vertex v3) { float va[3], vb[3], vr[3], val; /* calculate 1st vector */ va[0] = v2.getx() - x; va[1] = v2.gety() - y; va[2] = v2.getz() - z; /* calculate 2nd vector */ vb[0] = v3.getx() - v2.getx(); vb[1] = v3.gety() - v2.gety(); vb[2] = v3.getz() - v2.getz(); /* cross product */ vr[0] = va[1] * vb[2] - vb[1] * va[2]; vr[1] = vb[0] * va[2] - va[0] * vb[2]; vr[2] = va[0] * vb[1] - vb[0] * va[1]; /* normalization factor */ val = sqrt(vr[0]*vr[0] + vr[1]*vr[1] + vr[2]*vr[2]); normal.push_back(vr[0]/val); normal.push_back(vr[1]/val); normal.push_back(vr[2]/val); return normal; }
but result : correct normals
angel data set courtesy of u.c. berkeley computer animation , modeling group.
(won't let me post images because <10 reputation)
if switch direction of 1 of vectors, like:
/* calculate 1st vector */ va[0] = x - v2.getx(); va[1] = y - v2.gety(); va[2] = z - v2.getz();
then renders correctly:
but shouldn't, because orientation of vertices counter clockwise. right hand rule, first calculation should produce correct, outward facing normal vector.
i have tried reverse winding via,
glfrontface(gl_cw);
i've unit tested code ensure vertices being read in counter clockwise order file, i've made countless modifications lighting settings no avail.
can explain why happening? there error in vertex calculations missing? or other ideas going wrong?
the problem how calculating , b vectors. take @ image showing right-hand-rule:
vectors , b both originate same point , point off in different directions. vector b not start tip of vector a.
however in code, it's if base of middle finger (vector b) starts tip of index finger (vector a), because going around triangle instead of choosing 2 vectors emanating same vertex. equivalent using tip of vector common vertex, vector pointing wrong way
picture triangle overlaid on image clockwise numbered vertices:
(you number vertices in 3 different ways, i've chosen numbering matches working version of code.)
to vector a, goes vertex 2 vertex 1, subtract vertex 2 vertex 1:
/* calculate 1st vector */ va[0] = x - v2.getx(); va[1] = y - v2.gety(); va[2] = z - v2.getz();
to vector b, goes vertex 2 vertex 3, subtract vertex 2 vertex 3:
/* calculate 2nd vector */ vb[0] = v3.getx() - v2.getx(); vb[1] = v3.gety() - v2.gety(); vb[2] = v3.getz() - v2.getz();
Comments
Post a Comment