Shader Specified Stencil Reference Value

Enabling pixel shaders to output the Stencil Reference Value, rather than using the API-specified one, enables a very fine granular control over stencil operations.

The Stencil Reference Value is normally specified by the ID3D12GraphicsCommandList::OMSetStencilRef method. This method sets the stencil reference value on a per-draw granularity. However, this value can be overwritten by the pixel shader.

This D3D12 (and D3D11.3) feature enables developers to read and use the Stencil Reference Value (SV_StencilRef) that is output from a pixel shader, enabling a per-pixel or per-sample granularity.

The shader specified value replaces the API-specified reference value for that invocation, which means the change affects both the stencil test, and when the stencil operation D3D12_STENCIL_OP_REPLACE (one member of D3D12_STENCIL_OP) is used to write the reference value to the stencil buffer.

This feature is optional in both D3D12 and D3D11.3. To test for its support, check the PSSpecifiedStencilRefSupported boolean field of D3D12_FEATURE_DATA_D3D12_OPTIONS using CheckFeatureSupport.

Here is an example of the use of SV_StencilRef in a pixel shader:

uint main2(float4 c : COORD) : SV_StencilRef
    return uint(c.x);


Resource Binding in HLSL

Shader Model 5.1

Specifying Root Signatures in HLSL