Hi!
I’m implementing my own OpenGL library.
When I multiply vertex coordinates on modelview matrix and projection matrix I get homogenous coordinates, then if I divide them on w I get Normalized Device Coordinates (NDC).
If vertex coordinates(NDC) is inside clipping frustum it should be in [-1, 1] interval for x,y and z. Using this rule I implemented 3D Cohen-Sutherland algorithm.
But this approach do not work in some cases.
When I draw triangle in front of near plane, absolute value of NDC are more then one but they sometime have different signs and triangle is visible(it intersects clipping frustum) but it should not.
Example:
glViewport(0, 0, WIDTH, HEIGHT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)WIDTH/(GLfloat)HEIGHT, 5.0f , 10.0f);
glBegin(GL_TRIANGLES);
glVertex3f(0, 1, 0);
glVertex3f(-1, -1, - 4 );
glVertex3f(1, -1, 0);
glEnd();
NDC:
x1 = 0 y1 = 2.4 z1 = -20
x2 = -0.2 y2 = -0.6 z2 = -2
x3 = 1.8 y3 = -2.4 z3 = -20
in front of near plane
clip all triangle
move
glTranslatef(0, 0, 0.5);
NDC:
x1 = 0 y1 = -4.8 z1 = 43
x2 = -0.5 y2 = -0.6 z2 = -2.7
x3 = -3.6 y3 = 4.8 z3 = 43
triangle intersect frustum and partialy visible
why z1 and z2 changed signs???
triangle is in front of near plane and invisible.
I get strange artifacts in my scene.
I thoroughly check my matrix math - it is Ok.
May be I do not understand how homogenous coordinates work?
Please help.