Version: Unity 6.0 (6000.0)
语言 : 中文
在着色器中禁用写入深度缓冲区
在着色器中设置混合模式

在着色器中检查或写入模板缓冲区

模板缓冲区为帧缓冲区中的每个像素存储一个 8 位整数值。为给定像素执行片元着色器之前,GPU 可以将模板缓冲区中的当前值与给定参考值进行比较。这称为模板测试。如果模板测试通过,则 GPU 会执行深度测试。如果模板测试失败,则 GPU 会跳过对该像素的其余处理。这意味着可以使用模板缓冲区作为遮罩来告知 GPU 要绘制的像素以及要丢弃的像素。

通常会将模板缓冲区用于特殊效果,例如门户或镜子。此外,在渲染硬阴影或者构造型实体几何 (CSG) 时,有时也会使用模板缓冲区。

可以使用 Stencil 命令执行两种不同操作:配置模板测试,以及配置 GPU 写入模板缓冲区的内容。可以在同一个命令中执行这两种操作,但最常见的用例是创建一个 Shader 对象,该对象会遮罩其他 Shader 对象无法绘制到的屏幕区域。为此,需要将第一个 Shader 对象配置为始终通过模板测试并写入模板缓冲区,并将其他对象配置为执行模板测试而不写入模板缓冲区。

使用 RefReadMaskComp 参数可配置模板测试。使用 RefWriteMaskPassFailZFail 参数可配置模板写入操作。

此命令会更改渲染状态。在 Pass 代码块中使用它可为该通道设置渲染状态,或者在 SubShader 代码块中使用它可为该子着色器中的所有通道设置渲染状态。

模板测试方程为:

(ref & readMask) comparisonFunction (stencilBufferValue & readMask)

示例

Shader "Examples/CommandExample"
{
    SubShader
    {
         // The rest of the code that defines the SubShader goes here.

        Pass
        {    
             // All pixels in this Pass will pass the stencil test and write a value of 2 to the stencil buffer
             // You would typically do this if you wanted to prevent subsequent shaders from drawing to this area of the render target or restrict them to render to this area only
             Stencil
             {
                 Ref 2
                 Comp Always
                 Pass Replace
             }            

             // The rest of the code that defines the Pass goes here.
        }
    }
}

此示例代码演示在 SubShader 代码块中使用此命令的语法。

Shader "Examples/CommandExample"
{
    SubShader
    {
             // All pixels in this SubShader pass the stencil test only if the current value of the stencil buffer is less than 2
             // You would typically do this if you wanted to only draw to areas of the render target that were not "masked out"
             Stencil
             {
                 Ref 2
                 Comp Less
             }  

         // The rest of the code that defines the SubShader goes here.        

        Pass
        {    
              // The rest of the code that defines the Pass goes here.
        }
    }
}

其他资源

在着色器中禁用写入深度缓冲区
在着色器中设置混合模式