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

Can I sample the stencil buffer in a fragment shader?

Discussion in 'Universal Render Pipeline' started by RicardoDaForce, Sep 13, 2021.

  1. RicardoDaForce

    RicardoDaForce

    Joined:
    Jan 5, 2014
    Posts:
    3
    Hi there,

    I'm using URP with a Forward Renderer.

    I want to use data in the stencil buffer in the fragment shader.

    I have already drawn some meshes, and I'm writing the shader for an overlay that I want to display differently when over the top of those meshes.

    So my thinking is, draw the object with a stencil value. Let's say 2 for example.
    Now afterwards, when I draw the overlay object, in that shader I want to sample the stencil buffer, and if it comes back as 2, then draw my effect with a slightly lower alpha.

    Sort of like this...

    Code (CSharp):
    1. float stencilValue = tex2D( _StencilBuffer, screenSpaceUV );
    2.  
    3. float alpha = 1.0;
    4. if ( stencilValue == 2 )
    5.    alpha = 0.7;
    Is that possible to do in Unity URP?

    As the Stencil is part of the Depth buffer, I expect I would have to get the Depth buffer somehow and filter out the stencil part?

    Any pointers would be much appreciated.

    - Rich