Calculating Depth Value

Started by
3 comments, last by karwosts 13 years, 1 month ago
Hi I have a simple question.

How can i calculate the Depth value of a fragment, having the vertex position, the projection matrix and the modelview matrix?

thanks in advance
Advertisement
Transform the model space vertex (Pmodel) by the modelviewprojection matrix, gives you the position in clip space (Pclip).

P[sub]clip[/sub] = proj*view*model*P[sub]model[/sub];

Clip space is divided by the W coordinate to get normalized device coordinates, which has xyz values from -1 (near plane) to 1 (far plane)

P[sub]ndc[/sub] = P[sub]clip[/sub] / P[sub]clip[/sub].w;

Then scale this depth value from [-1,1] to [0,1].

Depth = (P[sub]ndc[/sub].z * 0.5) + 0.5;
[size=2]My Projects:
[size=2]Portfolio Map for Android - Free Visual Portfolio Tracker
[size=2]Electron Flux for Android - Free Puzzle/Logic Game
Hello,

First of all, you will need to apply the matrices to get your point into eye space, and then into projection space.
Assuming v as the vertex position in world space, P as the projection matrix and M as the modelview matrix:
p = P (M v)
where p is the vertex in clip space. This uses multiplication of matrices and vectors, as defined by linear algebra. You could multiply the matrices first, so that you only need to apply one matrix for the next computation. For a single point, however, this method is faster.

The next step is normalization of the point. This means you need to divide the x, y and z components by the w component. Since you only want the depth, I will only show the z here.
z = p.z / p.w

The last step you need is the conversion to window coordinates. This transforms the coordinates from a range of [-1, 1] to [0, 1].
depth = 0.5 * z + 0.5

And you're done. :)

Regards,
Ignifex
wow that was easier than i thought. Thank you guys
Also if you're using GLSL, the depth value is available in the pixel shader as gl_FragCoord.z
[size=2]My Projects:
[size=2]Portfolio Map for Android - Free Visual Portfolio Tracker
[size=2]Electron Flux for Android - Free Puzzle/Logic Game

This topic is closed to new replies.

Advertisement