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

转载地址: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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值