Am I able to read depth from a texture in a shader?

I’m trying to figure out how to read the depth buffer from a render texture in a shader. I’ve tried looking around for the answer, but it’s never been clear enough, at least to me.

This is what I have in my code at the moment.

Texture2D Texture : register(t0);

sampler Texture_Sampler = sampler_state {
Texture = (Texture);
MagFilter = Point;
MinFilter = Point;
AddressU = Clamp;
AddressV = Clamp;
};

float4 PixelShader(VSOutput input) : SV_Target
{
return tex2D(Texture_Sampler, input.uv);
}

You can’t access the depth buffer directly. You need to render depth manually into a separate texture and read it from there.

You can use MRT (multiple render targets) to render to multiple textures simultaneously. That can save you from needing a separate render pass just for depth.

If you don’t need the alpha channel of your main render target for anything else, you could put your depth there. You would need to use a 16 or 32 bit floating point surface format though. The 8 bit of the standard color format are almost never enough precision for depth.

1 Like

I’ve tried MRT, but the depth buffer wasn’t written to at all for some reason. I might’ve done something wrong though. I can try alpha channel, though I’m not 100% sure that will be compatible with how it’s set up.

Make that a “I did something wrong”. :slight_smile:
MRT definitely works.

Okay sure, but how do I do it right? I don’t see anything wrong here

graphics.SetRenderTarget(renderTargetMain);
graphics.Clear(Color.Transparent);
graphics.SetRenderTarget(positionTarget);
graphics.Clear(Color.Black);

graphics.SetRenderTargets(renderTargetMain, positionTarget);
Draw.DepthPass();

graphics.SetRenderTarget(renderTargetMain);
Draw.ColorPass();

graphics.SetRenderTarget(positionTarget);
Draw.PositionPass(cam.Position.XZ());

First set RT in MTR must have Depth Buffer