GrabPass 是一个特殊的pass类型 - 它抓取对象将要绘制的屏幕内容写入一个纹理中。 该纹理可以被后来的pass使用,来实现高级的基于图像的效果。
GrabPass 属于subshader中。 它可以使用两种形式:
单纯的 GrabPass { } 抓取当前屏幕内容进纹理。该纹理可以被后来的pass通过名字 _GrabTexture 取用。Note: 这种形式的 grab pass 会为每个使用它的对象做耗时的屏幕抓取。GrabPass { "TextureName" } 抓取当前屏幕内容进纹理,但是每帧只会为第一个使用给定纹理名称的对象,抓取一次。该纹理可以通过给定名称来访问。当你场景中有多个对象使用 GrabPass 时,这会很有效。此外, GrabPass 可以使用 Name 和 Tags 命令。
这是一个低效率的方法,在渲染前反转颜色:
Shader "GrabPassInvert" { SubShader { // Draw ourselves after all opaque geometry Tags { "Queue" = "Transparent" } // Grab the screen behind the object into _BackgroundTexture GrabPass { "_BackgroundTexture" } // Render the object with the texture generated above, and invert the colors Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct v2f { float4 grabPos : TEXCOORD0; float4 pos : SV_POSITION; }; v2f vert(appdata_base v) { v2f o; // use UnityObjectToClipPos from UnityCG.cginc to calculate // the clip-space of the vertex o.pos = UnityObjectToClipPos(v.vertex); // use ComputeGrabScreenPos function from UnityCG.cginc // to get the correct texture coordinate o.grabPos = ComputeGrabScreenPos(o.pos); return o; } sampler2D _BackgroundTexture; half4 frag(v2f i) : SV_Target { half4 bgcolor = tex2Dproj(_BackgroundTexture, i.grabPos); return 1 - bgcolor; } ENDCG } } }该shader有两个pass:第一个 pass 抓取任何该对象后的此时被渲染的对象,然后提供给第二个pass。注意,使用 invert blend mode 可以更高效的实现相同的效果。