Unity shader学习之遮罩纹理
什么是遮罩?
遮罩允许我们可以保护某些区域,使它们奂于某些修改。
例如下面的例子,使用遮罩来控制高光反射。
转载请注明出处:http://www.cnblogs.com/jietian331/p/7149182.html
使用的贴图,法线,遮罩纹理如下:
shader如下:
// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)' Shader "Custom/Mask Texture" { Properties { _MainTexture("Main Texture", 2D) = "white" {} _NormalMap("Normal Map", 2D) = "bump" {} _MaskTexture("Mask Texture", 2D) = "white" {} _Specular("Specular", Color) = (1, 1, 1, 1) _Gloss("Gloss", Range(8, 256)) = 20 } SubShader { Pass { Tags { "LightMode" = "ForwardBase" } CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" #include "Lighting.cginc" struct appdata { float4 vertex : POSITION; float4 uv : TEXCOORD0; float3 normal : NORMAL; float4 tangent : TANGENT; float4 color : COLOR; }; struct v2f { float4 pos : SV_POSITION; float4 color : COLOR; float4 uv : TEXCOORD0; float3 tangentLight : TEXCOORD1; float3 tangentView : TEXCOORD2; }; v2f vert(appdata v) { v2f o; o.pos = UnityObjectToClipPos(v.vertex); o.uv = v.uv; o.color = v.color; float3 objLightDir = ObjSpaceLightDir(v.vertex); float3 objViewDir = ObjSpaceViewDir(v.vertex); TANGENT_SPACE_ROTATION; o.tangentLight = mul(rotation, objLightDir); o.tangentView = mul(rotation, objViewDir); return o; } sampler2D _MainTexture; sampler2D _NormalMap; sampler2D _MaskTexture; float4 _Specular; float _Gloss; fixed4 frag(v2f i) : SV_TARGET { fixed3 tangentNormal = UnpackNormal(tex2D(_NormalMap, i.uv)); fixed3 albedo = tex2D(_MainTexture, i.uv).rgb * i.color; fixed3 ambient = albedo * UNITY_LIGHTMODEL_AMBIENT.rgb; fixed3 diff = albedo * _LightColor0.rgb * max(0, dot(tangentNormal, i.tangentLight)); fixed4 mask = tex2D(_MaskTexture, i.uv); fixed3 halfDir = normalize(i.tangentView + i.tangentLight); fixed3 spec = _Specular.rgb * _LightColor0.rgb * pow(max(0, dot(halfDir, tangentNormal)), _Gloss) * mask.r; fixed3 col = ambient + diff + spec; return fixed4(col, 1); } ENDCG } } Fallback "Specular" }
使用和不使用遮罩的效果对比图如下:
使用遮罩:
不使用遮罩:
资源如下: