Reputation: 23
I'm trying to draw a model and this is what I ran into, the code below works like 2d, although there should be a perspective
Code # 1
mat4 Proj = glFrustum(left, right, bottom, top, zNear, zFar);
mat4 View = gluLookAt(position, direction, up);
mat4 World = mat4(1);
glBegin(GL_TRIANGLES);
for (auto& t : mesh)
{
norm = Proj * View * World * vec4(t.norm, 0);
dot1 = Proj * View * World * vec4(t.dot1, 1);
dot2 = Proj * View * World * vec4(t.dot2, 1);
dot3 = Proj * View * World * vec4(t.dot3, 1);
glNormal3f(norm);
glVertex3f(dot1.x, dot1.y, dot1.z);
glVertex3f(dot2.x, dot2.y, dot3.z);
glVertex3f(dot3.x, dot3.y, dot3.z);
}
glEnd();
And so the perspective appears:
Code # 2
mat4 Proj = glFrustum(left, right, bottom, top, zNear, zFar);
mat4 View = gluLookAt(position, direction, up);
mat4 World = mat4(1);
glMatrixMode(GL_PROJECTION);
glLoadMatrix(Proj);
glBegin(GL_TRIANGLES);
for (auto& t : mesh)
{
norm = View * World * vec4(t.norm, 0);
dot1 = View * World * vec4(t.dot1, 1);
dot2 = View * World * vec4(t.dot2, 1);
dot3 = View * World * vec4(t.dot3, 1);
glNormal3f(norm);
glVertex3f(dot1.x, dot1.y, dot1.z);
glVertex3f(dot2.x, dot2.y, dot3.z);
glVertex3f(dot3.x, dot3.y, dot3.z);
}
glEnd();
From which the question arose: why code 2 and code 3 get the same result, but code 1 and code 2 are different?
Code # 3
mat4 Proj = glFrustum(left, right, bottom, top, zNear, zFar);
mat4 View = gluLookAt(position, direction, up);
mat4 World = mat4(1);
glMatrixMode(GL_PROJECTION);
glLoadMatrix(Proj);
*glMatrixMode(GL_MODELVIEW);
glLoadMatrix(View);*
glBegin(GL_TRIANGLES);
for (auto& t : mesh)
{
norm = World * vec4(t.norm, 0);
dot1 = World * vec4(t.dot1, 1);
dot2 = World * vec4(t.dot2, 1);
dot3 = World * vec4(t.dot3, 1);
glNormal3f(norm);
glVertex3f(dot1.x, dot1.y, dot1.z);
glVertex3f(dot2.x, dot2.y, dot3.z);
glVertex3f(dot3.x, dot3.y, dot3.z);
}
glEnd();
Tell me what am I doing wrong? How can I calculate the vertex multiplied by the projection matrix correctly?
Upvotes: 1
Views: 137
Reputation: 210968
The transformation with the projection matrix generates Homogeneous coordinates. A Homogeneous coordinate has 4 components, but you just pass 3 components to the vertex coordinate. Use all 4 components to specify the vertex coordinate. e.g:
glVertex3f(dot1.x, dot1.y, dot1.z);
glVertex4f(dot1.x, dot1.y, dot1.z, dot1.w);
or
glVertex4fv(glm::value_ptr(dot1));
Upvotes: 1