Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm writing a shader in HLSL (Direct3D11 with SharpDX) and after some computations I was trying to make a test and print the depth z of a specific point in my pixel shader, like this:

myZ = input.p.z;
color = float4(myZ, myZ, myZ, 1.0f);
return color;

The result of this is the one I expect, but though I see what I expect (pixels darker as I get closer and lighter when they are far away), I have to move the camera quite close to the model to start seeing some darker pixels. If not, everything is white.

The thing is, if I do this instead, as I read in some forum:

myZ = input.p.z/input.p.w;
color = float4(myZ, myZ, myZ, 1.0f);
return color;

then I can see everything from the beginning much finer. The problem is I don't understand the logic behind this. Why would this help and why would it make sense.

Any help appreciated, thanks!

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

The depth buffer is not linear. More bits of precision are available closer to the camera and so changes in depth close up end up being very tiny changes that don't convert to color differences you could actually see. Dividing by w linearizes the depth buffer such that small changes in depth result in visible changes in color.

http://www.gamedev.net/topic/539378-why-non-linear-depth-buffer/ http://mynameismjp.wordpress.com/2010/03/22/attack-of-the-depth-buffer/ http://www.mvps.org/directx/articles/linear_z/linearz.htm

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.