# Calculating Depth Value

This topic is 2709 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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?

##### Share on other sites
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;

##### Share on other sites
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

##### Share on other sites
wow that was easier than i thought. Thank you guys

##### Share on other sites
Also if you're using GLSL, the depth value is available in the pixel shader as gl_FragCoord.z

1. 1
2. 2
3. 3
Rutin
22
4. 4
JoeJ
17
5. 5

• 14
• 30
• 13
• 11
• 11
• ### Forum Statistics

• Total Topics
631774
• Total Posts
3002297
×