Search Unity

How to Use Depth Buffer in Custom SRP

Discussion in 'Shaders' started by Sluggy, Nov 5, 2021.

  1. Sluggy

    Sluggy

    Joined:
    Nov 27, 2012
    Posts:
    989
    Hello,

    I've been playing around with a custom and super lightweight SRP and I'm to a point where I need to make use of the Depth Buffer so that I can eventually implement some kind of decal rendering. While I understand the basic gist of what a depth buffer is and what they are used for I never realized just how insanely complicated it can all get (doesn't help that there are a hundred different examples online of how to read from the buffer and they all differ based on the RP being used as well as the intended goal).

    I'm now to the point where I'm just trying to prove some basic concepts to myself so that I can build from there. So I want to render the scene as normal and then, in a second pass, use a replacement shader that simply draws the depth buffer in greyscale. However, it appears that everything is being drawn as a single middling shade of grey. Looking at the depth buffer in the frame debugger, it seems that there isn't anything even IN the depth buffer. This is despite the fact that I am obviously using some kind of z-buffer since the first pass renders front-to-back and appears in the proper order. So I guess the first thing I need to figure out is how to even determine if I'm properly using the depth buffer correctly!

    I've seen several old non-SRP tutorials suggest that I need to set the camera's depthTextureMode to include the flag DepthTextureMode.Depth. This has not seemed to make and difference and I'm not even sure what it does (I'm guessing maybe it creates a depth texture when set?). I also considered that perhaps Unity itself does not bind the depth texture to the shader and instead my SRP needs to do that so I manually call

    Code (CSharp):
    1. CmdBuffer.SetGlobalTexture(Shader.PropertyToID("_CameraDepthTexture"), camera.targetTexture, RenderTextureSubElement.Depth);
    But it still seems to have no effect. Though as I said before, I really think that I'm not doing something else correctly since I can't even see a preview of the scene depth in the frame debugger.

    I'm definitely not too slick on the internals of Unity's rendering systems or shaders in general so perhaps it's just something really dumb and simple I'm missing. Does anyone have any experience with custom SRPs in general that could help? Or perhaps just a basic knowledge of rendering in Unity that they'd have some leads I could follow?

    Here are a few snips of the frame debugger and what is in the camera -

    First pass as normal
    srp debug (1).jpg


    The first pass's depth
    srp debug (2).jpg


    Second depth-draw pass
    srp debug (3).jpg
     
    daneobyrd likes this.