修改Shader让NGUI支持灰色滤镜 [Unity3D]

来源:互联网 发布:现在做淘宝还有前途吗 编辑:程序博客网 时间:2024/06/06 00:28

转载地址:http://chengduyi.com/blog/?post=43

之前有人做过,不过效率不高: http://blog.csdn.net/onerain88/article/details/12197277  
他的代码:

fixed4 frag (v2f i) : COLOR{    fixed4 col;    if (i.color.r < 0.001)      {         col = tex2D(_MainTex, i.texcoord);         float grey = dot(col.rgb, float3(0.299, 0.587, 0.114));         col.rgb = float3(grey, grey, grey);     }     else     {         col = tex2D(_MainTex, i.texcoord) * i.color;     }     return col;}

通过修改后效率明显大幅提升:

struct v2f {     float4 vertex : SV_POSITION;     half2 texcoord : TEXCOORD0;     fixed4 color : COLOR;     fixed gray : TEXCOORD1; }; sampler2D _MainTex; float4 _MainTex_ST; v2f vert (appdata_t v) {     v2f o;     o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);     o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);     o.color = v.color;     o.gray = dot(v.color, fixed4(1,1,1,0));     return o; } fixed4 frag (v2f i) : COLOR {     fixed4 col;     if (i.gray == 0)     {         col = tex2D(_MainTex, i.texcoord);         col.rgb = dot(col.rgb, fixed3(.222,.707,.071));     }     else     {         col = tex2D(_MainTex, i.texcoord) * i.color;     }     return col; }

设置UISprite.color = Color.black;就能使用了。

原理是在v2f中申请一个寄存器TEXCOORD1放置数据gray,并在顶点程序vert中计算是否灰色,在片段程序frag中用i.gray == 0做if判断。

第一段代码效率低的原因是if (i.color.r < 0.001)这里访问了color的分量r,但在官方文档中明确说了这样做效率低,除非必要情况时才使用。

另外在PC中(fixed gray : TEXCOORD1;)可以改成(bool gray : TEXCOORD1;),但在移动设备(android和ios)中都会有问题,求解。


0 0
原创粉丝点击