0
\$\begingroup\$

I am currently trying to get the Depth Buffer as a texture to use it for edge detection algorithms. Since XNA4 does not allow direct access to the Depth Buffer as texture i have to render it into a texture. The effect i currently use looks like this:

float4x4 World;
float4x4 View;
float4x4 Projection;

struct DEPTH_VS_OUTPUT
{
    float4 Position : POSITION;
    float2 Depth : TEXCOORD;
};

DEPTH_VS_OUTPUT DepthTextureVS(float4 Position : POSITION)
{
    DEPTH_VS_OUTPUT output;

    float4 worldPosition = mul(Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);
    output.Depth = output.Position.zw;

    return output;
}

float4 DepthTexturePS(DEPTH_VS_OUTPUT input) : COLOR0
{
    float4 result;
    result.rgb = input.Depth.x / input.Depth.y;
    result.a = 1.0;
    return result;
}

technique DepthTextureRender
{
    pass P0
    {
        CullMode = NONE;
        ZEnable = TRUE;
        ZWriteEnable = TRUE;
        AlphaBlendEnable = FALSE;

        VertexShader = compile vs_2_0 DepthTextureVS();
        PixelShader = compile ps_2_0 DepthTexturePS();
    }
}

It looks like this: Image of the wrong effect

The cubes in this scene are 1x1x1 the projection matrix is made like this:

var projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 16f / 9f, 0.1f, 1000f);

As far as I understood the Depth Buffer concept z/w should give me the distance from the camera position to the pixel as value between 0-1 where 0 would be the Near-plane and 1 the Far-plane but since the cubes in this scene are only about 5 Units away they shouldn't be white.

\$\endgroup\$
0
\$\begingroup\$

I really doubt that the depth Buffer is inaccurate, the issue is much more likely the the boxes are further than the far pane or your shader is calculating something incorrectly.

Anyways XNA has built in functionality for generating a Depth Texture.

RenderTarget2D shadowRenderTarget;

shadowRenderTarget = new RenderTarget2D(GraphicsDevice, 
    graphics.GraphicsDevice.Viewport.Width, 
    graphics.GraphicsDevice.Viewport.Height);

DepthStencilState depthStencilState = new DepthStencilState();

depthStencilState.DepthBufferFunction = CompareFunction.LessEqual;
GraphicsDevice.DepthStencilState = depthStencilState;

GraphicsDevice.SetRenderTarget(shadowRenderTarget);

// Render the depth texture
Rectangle rect = new Rectangle(
    graphics.GraphicsDevice.Viewport.X, 
    graphics.GraphicsDevice.Viewport.Y, 
    graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);

spriteBatch.Begin();
spriteBatch.Draw(map, rect, Color.White);
spriteBatch.End();

GraphicsDevice.SetRenderTarget(null);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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