Shader Specified Stencil Reference Value (Direct3D 11 Graphics)

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 shader specified value replaces the API-specified Stencil Reference Value for that invocation, which means the change affects both the stencil test, and when stencil op D3D11_STENCIL_OP_REPLACE (one member of D3D11_STENCIL_OP) is used to write the reference value to the stencil buffer.

In earlier versions of D3D11, the Stencil Reference Value can only be specified by the ID3D11DeviceContext::OMSetDepthStencilState method. This means that this value can only be defined on a per-draw granularity. This D3D11.3 feature enables developers to read and use the Stencil Reference Value (SV_StencilRef) that is output from a pixel shader, meaning that it can be specified on a per-pixel or per-sample granularity.

This feature is optional in D3D11.3. To test for its support, check the PSSpecifiedStencilRefSupported boolean field of D3D11_FEATURE_DATA_D3D11_OPTIONS2 using ID3D11Device::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);
}

Direct3D 11.3 Features

Shader Model 5.1