Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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.

share|improve this answer

Your Answer


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.