Figure: Write one first, then compare against one in a later draw. Writer and reader states differ.
Figure: Write one first, then compare against one in a later draw. Writer and reader states differ.

Cause and mechanism

Stencil stores a numerical marker at each screen location and uses comparisons with that marker to decide where to draw. If a mask fails, check that the marking pass runs first and that the later comparison matches it. Inspect Shader passes, draw order, reference values, masks, and whether both operations share the same stencil buffer.

Check and correct the setup

  1. Execute the writer before the reader. Configure writer Ref/WriteMask and operations separately from reader Ref/ReadMask and comparison; the two states need not be identical.
    Testing and writing are separate settings
    Testing and writing are separate settings
  2. If the graph does not expose stencil state, use Render Objects overrides or a suitable handwritten shader.
    Testing and writing are separate settings
    Testing and writing are separate settings
  3. Inspect layers/queues, duplicate draws, and depth/stencil clears in Frame Debugger.
    Testing and writing are separate settings
    Testing and writing are separate settings

Separate writing from testing

For a shared stencil buffer initially cleared to zero, a writer can use Ref 1 / WriteMask 1 / Comp Always / Pass Replace. A later reader can use Ref 1 / ReadMask 1 / Comp Equal / Pass Keep, passing only where bit 0 is one without changing it. These examples assume the fragments also pass the depth test.

WriteMask 0 means no bits are written, rather than writing zero. Check the shared depth/stencil target, execution order, clear, depth test, and pipeline-reserved bits.

Limits and verification

Stencil is not automatically shared between different targets. Check conflicts with pipeline-reserved bits.

A focused diagnostic setup

Use two passes: write bit zero in a region, then color only that region. Remove unrelated masking/features.

Test in this order

  1. Verify write-before-test ordering.
    Testing and writing are separate settings
    Testing and writing are separate settings
  2. Check reference, read/write masks and depth-test success.
    Testing and writing are separate settings
    Testing and writing are separate settings
  3. Inspect target switches, clears and reserved-bit conflicts.
    Testing and writing are separate settings
    Testing and writing are separate settings

Interpret the result

No initial value suggests writing/depth; disappearing values suggest clears/targets; all-pixel acceptance suggests comparison/masks. Switching to a target without stencil cannot preserve it.

Related explanations

References