# Why divide by w makes the pixel shader look better?

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!

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.