2
votes

I'm trying to implement a simple 3d render. I have implemented a perspective projection matrix similar to glm::perspective. I have read that a perspective projection matrix transforms vertices such that after the perspective division, visible region, i.e., objects that lie inside the specified frustum fall in the range [-1,1], but when I tested some values with a matrix returned by glm::perspective results are not similar to my understanding.

float nearPlane = 0.1f;
float farPlane = 100.0f;

auto per =
    glm::perspective(45.0f, (float)(window_width * 1.0 / window_height),
                        nearPlane, farPlane);
// z=nearplane
print(per * glm::vec4(1, -1, -0.1, 1));
// z=farplane
print(per * glm::vec4(1, -1, -100, 1));
// z between nearplane and farplane
print(per * glm::vec4(1, -1, -5, 1));
// z beyond far plane
print(per * glm::vec4(1, -1, -200, 1));
// z behind the camera
print(per * glm::vec4(1, -1, 0.1, 1));
// z between camera and near plane
print(per * glm::vec4(1, -1, -0.09, 1));

As per my understanding, if vertices have a z coordinate which lies towards positive z-direction from nearPlane then after perspective divide z/w value should be <-1 but as shown in the picture below it is not the case. what am I missing?

output of above print statements

1
Shouldn't you be using positive z-values as input? - BDL
@BDL i dont think thats an issue, because when i give nearPlane and far plane as input it is giving -1 and 1 respectively, also if that was the case second last print statement should have resulted is z-value in range [-1,1] but cleary that is not the case above - Aayush Neupane
Sorry, you are right. But I probably don't understand your question then: In the three cases where the depth is between near and far, the z/w value is in range [-1, 1] (which is correct. In the other cases, the z/w value is outside of [-1, 1]. Which value exactly are you confused with? - BDL

1 Answers

3
votes

as per my understanding if vertices has z coordinate which is lies towards positive z direction from nearPlane then after perspective divide z/w value should be <-1 but as shown in picture below it is not the case. what am i missing?

That's simply not the case. There is a singularity at z=0 (camera plane), and the sign of the function flips (camera is looking to the left; blue vertical line is the near clipping plane):

graph

Those values are still outside the [-1,1] range, telling us that they are outside the camera frustum and should be clipped accordingly.

You might be confused because you're thinking that "smaller z/w values mean that the point is closer to the camera". But that's true only in-front of the camera. In fact the depth buffer values matter only if the fragment isn't clipped -- i.e. in the [-1,1] range, where that relation happens to be correct.