# Visualize Z-buffer with HLSL

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

## Recommended Posts

I am trying to visualize my Z-buffer with HLSL. I am working in ATI RenderMonkey to make sure my shaders are good. I wrote what I thought would show the Z-buffer as white being the furthest and black being the closest, but when tested on a sphere, I get a solid white circle on a black background (which in a real application, I would clear to white). I expected a gray gradient sphere. What am I doing wrong? Here is my vertex shader:
float4x4 matViewProjection;

struct VS_INPUT
{
float4 Position : POSITION0;

};

struct VS_OUTPUT
{
float4 Position : POSITION0;
float2 PositionZW : TEXCOORD0;
};

VS_OUTPUT vs_main( VS_INPUT Input )
{
VS_OUTPUT Output;

Output.Position = mul( matViewProjection, Input.Position );
Output.PositionZW = Output.Position.zw;

return Output;

}


float4 ps_main(float2 PositionZW : TEXCOORD0) : COLOR0
{
float depth = PositionZW.x / PositionZW.y;
return float4( depth, depth, depth, 1.0f );
}


Thanks!

##### Share on other sites
What are your near/far Z values in the projection matrix?

You may want to put the near Z at the front of the sphere and the far at the back (or at the center) of the sphere.

Other than that you could scale / normalize your values before writing them into the frame buffer.

##### Share on other sites
Hovering over the viewProjection in RenderMonkey shows the following matrix:

2.228505 0 0 0
0 2.414213 0 0
0 0 1 199.199188
0 0 1 200

I'm not really sure how to interprete that.

I'm clearly a dumb ass though: I simply zoomed in and the sphere faded to gray. I had it right all along, I guess I really just need a better value for my near and far planes.

I don't think I'd have bothered to zoom in as far as I did had you not said anything, thanks.

Side question: I based this off the Direct3D SDK shadow mapping example where they pass Z and W and perform Z/W in the pixel shader. I tried it with Z/W in the vertex shader and passed that to the pixel shader and it seems to be the same. Is there any reason I wouldnt want to do that?

##### Share on other sites
You may find this is due to the almost all the precision in the z-buffer being at the front of the z range. Unless your sphere is very close to the near clip plane it is likely to have a z value close to 1.0 which will be truncated to colour value of 255.

M

##### Share on other sites
Btw this would be easy to test by multiplying the depth by some fraction of 1.0 before returning and see if the gradient appears.

M

• 9
• 13
• 41
• 15
• 13