1.模版测试:符合条件的 通过 不符合条件的 像素 丢弃
比较公式:
if((referenceValue&readMask) comparisonFunction (stencilBufferValue&readMask))
通过像素
else
抛弃像素
(1)referenceValue:用Ref命令设定,这个值将用来与模版缓冲中的值进行比较,referenceValue是一个取值范围 0-255 的整数
(2)readMask:从字面意思的理解就是读遮罩,readMask将和referenceValue以及stencilBufferValue 进行按位与(&)操作,readMask的取值范围也是 0-255 的整数,默认值为255,二进制位11111111,即读取的时候不对referenceValue和stencilBufferValue 产生效果,读取的还是原始值。通过命令ReadMask设定
(3)comparisonFunction:判断条件
Greater GEqual Less Always Never
(4)stencilBufferValue:Gbuffer里面存的模版值
(5)更新操作:三个命令
Keep : 保持原来的值不变 。
Zero : 0
Replace : 设置的ref value 替换 模板缓存的值 。
IncrSat : 自动增加1 。 255 永远是 255.
IncrWrap :自动增加1 。 达到 255 变成 0
DecrSat : 每通过一次 减一 ,0 永远是 0.
DecrWrap :每通过一次 减一 ,变成0了 在减一就变成 255
Pass
是定义当模板测试(和深度测试)通过时,则根据(stencilOperation值)对模板缓冲值(stencilBufferValue)进行处理,默认值:keep
Fail是定义当模板测试(和深度测试)失败时,则根据(stencilOperation值)对模板缓冲值(stencilBufferValue)进行处理,默认值:keep
ZFail是定义当模板测试通过而深度测试失败时,则根据(stencilOperation值)对模板缓冲值(stencilBufferValue)进行处理,默认值:keep
(6)墙穿透的效果演示:
Shader "Hidden/Front"
{Properties{_MainTex ("Texture", 2D) = "white" {}}SubShader{// No culling or depth//Cull Off ZWrite Off ZTest AlwaysZWrite OffPass{Stencil {Ref 2Comp alwaysPass replace}CGPROGRAM#pragma vertex vert#pragma fragment frag#include "UnityCG.cginc"struct appdata{float4 vertex : POSITION;float2 uv : TEXCOORD0;};struct v2f{float2 uv : TEXCOORD0;float4 vertex : SV_POSITION;};v2f vert (appdata v){v2f o;o.vertex = UnityObjectToClipPos(v.vertex);o.uv = v.uv;return o;}sampler2D _MainTex;fixed4 frag (v2f i) : SV_Target{fixed4 col = tex2D(_MainTex, i.uv);// just invert the colors//col.rgb = 1 - col.rgb;return col;}ENDCG}}
}
Shader "Hidden/Middle"
{Properties{_MainTex ("Texture", 2D) = "white" {}}SubShader{// No culling or depth//Cull Off ZWrite Off ZTest AlwaysPass{Stencil {Ref 2Comp NotEqual}CGPROGRAM#pragma vertex vert#pragma fragment frag#include "UnityCG.cginc"struct appdata{float4 vertex : POSITION;float2 uv : TEXCOORD0;};struct v2f{float2 uv : TEXCOORD0;float4 vertex : SV_POSITION;};v2f vert (appdata v){v2f o;o.vertex = UnityObjectToClipPos(v.vertex);o.uv = v.uv;return o;}sampler2D _MainTex;fixed4 frag (v2f i) : SV_Target{fixed4 col = tex2D(_MainTex, i.uv);// just invert the colors//col.rgb = 1 - col.rgb;return col;}ENDCG}}
}
Shader "Hidden/Back"
{Properties{_MainTex ("Texture", 2D) = "white" {}}SubShader{// No culling or depth//Cull Off ZWrite Off ZTest AlwaysPass{Stencil {Ref 2Comp Equal}CGPROGRAM#pragma vertex vert#pragma fragment frag#include "UnityCG.cginc"struct appdata{float4 vertex : POSITION;float2 uv : TEXCOORD0;};struct v2f{float2 uv : TEXCOORD0;float4 vertex : SV_POSITION;};v2f vert (appdata v){v2f o;o.vertex = UnityObjectToClipPos(v.vertex);o.uv = v.uv;return o;}sampler2D _MainTex;fixed4 frag (v2f i) : SV_Target{fixed4 col = tex2D(_MainTex, i.uv);// just invert the colors//col.rgb = 1 - col.rgb;return col;}ENDCG}}
}