Introduction to the stencil buffer
Understand what the stencil buffer is, how the stencil test works, and what to consider when you use stencils in URP.
Read time 2 minutesLast updated 2 days ago
The stencil buffer stores an 8-bit integer value for each pixel in the frame buffer. The GPU can use these values as a mask, to decide which pixels to draw and which pixels to discard.
Uses for the stencil buffer
Common uses for the stencil buffer include the following:
- Portals
- Mirrors
- Hard shadows
- Constructive solid geometry (CSG)
How the stencil test works
For each pixel, the GPU can perform a stencil test, which compares the current value in the stencil buffer against a reference value.
The GPU performs both the stencil test and the depth test. If either test fails, the GPU doesn't draw the pixel.
The stencil test uses the following equation:
(ref & readMask) comparisonFunction (stencilBufferValue & readMask)
The GPU applies the read mask to both the reference value and the stencil buffer value, then compares the two results using the comparison function.
Stencil values you can use in URP
The Universal Render Pipeline (URP) reserves part of the stencil buffer for its own use. To avoid conflicts with URP, use only reference values and masks from 0 to 15. Shader Graph limits Stencil Ref, Read Mask, and Write Mask to this range automatically.
If you set LOD Cross Fade Dithering Type to 2x2 Stencil in the URP asset, URP reserves more of the stencil buffer. In this case, use only values from 0 to 3. For more information, refer to Universal Render Pipeline asset reference for URP.
Stencils and batching
Unity speeds up rendering by grouping objects that use the same render state, so that it updates the render state less often. For example, batching combines meshes that use the same render state and draws them together. Stencil settings are part of the render state, so objects that use different stencil settings can reduce batching. For more information, refer to Introduction to optimizing draw calls.
Stencils in Shader Graph
In URP, you can set stencil options in a shader graph instead of writing ShaderLab code. Stencil options are available in Lit and Unlit shader graphs. For more information, refer to Set stencil options in Shader Graph.