Hi folks this should be an easy task but for some reason I do not get it worked out...
I just want to get a visualization of the depth in my scene using a shader:
float4x4 matViewProjection;
float4x4 matWorld;
float4 eyePos;
struct VS_OUTPUT
{
float4 position : POSITION0;
float depth : TEXCOORD0;
};
VS_OUTPUT vs_main( VS_INPUT input )
{
VS_OUTPUT output;
output.position = mul( input.position, matViewProjection );
float3 posWorld = mul(input.position, matWorld);
output.depth = distance(posWorld, eyePos);
return( output );
}
To get the depth value (or so I thought) I calculate the distance between the position in world space and the view position.
And the corresponding pixel shader
float4 ps_main(VS_OUTPUT input) : COLOR0
{
float depth = input.depth;
return float4(depth, depth, depth, 1.0f);
}
Which results nothing but a white color
So I started trial & error multiplying a value to depth:
float depth = input.depth * 0.005f;
which gives a satisfying result depending on the distance to the object. So if I get closer to the object I will have to adjust the value again.
So theres something very wrong...
Thanks for reading!
Well your problem is that you aren't normalising the depth value at any point. It can be anywhere in the range of ZNear to ZFar.
Try the following for your vert shader:
VS_OUTPUT vs_main( VS_INPUT input )
{
VS_OUTPUT output;
output.position = mul( input.position, matViewProjection );
output.depth = output.position.z / output.position.w;
return( output );
}
After w divide any valid Z-value will be in the range 0 to 1. Any Z-Value that is not in this range is outside the frustum (ie in front of the near clipping plane or behind the far clipping plane) and hence won't get to the pixel shader anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With