Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Is it possible for a shader to clear the depth buffer as it draws?

Discussion in 'Shaders' started by JoeStrout, Jun 3, 2019.

  1. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    I'm working on a portal system using a stencil shader. This shader is applied to the portal itself (a quad in the portal doorway), and it writes the stencil that defines where stuff from the other dimension is allowed to draw.

    But I need to also clear the depth buffer for those same pixels. Otherwise, stuff in this dimension that's closer than the stuff in the other dimension will still appear inside the portal, and that's not the correct effect.

    I know how to make a "depth-clearing" shader that I can put on some plane way at the back of the scene. It doesn't actually clear the depth buffer, but rather writes the depth of its own geometry (using "ZTest Always" to make it ignore previous depth data). But that's an extra step, and also doesn't limit itself to the area of the stencil (though I suppose I could update it to do so).

    Is there any way I can make my stencil shader also clear the depth of the pixels it's writing to, so this happens all in one step?
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,329
    Nope.

    Like you said, you can have a shader output a depth value from the fragment shader, but doing so in the same pass as the stencil write may change how it renders as it'll see the depth comparison using that output depth. That means you need to do it as a second pass that uses ZTest Always, in which case you shouldn't use the fragment shader depth output, but instead set the clip pos z to just inside the far plane.
     
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    OK, thanks.

    As it happened, I found an easier solution that works for my needs... but this is one more little step on the path towards shader enlightenment. I will probably never reach it, but I enjoy the journey!