遮罩纹理(mask texture),允许保护某些区域,免于某些修改。
类似PhotoShop的蒙板,用于控制部分区域的纹理,值越大越白越用于受影响。配合法线纹理使用。这里控制的是高光反射的值。
通过采样得到遮罩纹理的纹素值,然后使用其中某个通道的值来与某个表面属性进行相乘,这样当通道的值为0时,可以保护表面不受该属性的影响。总而言之,使用遮罩可以让美术人员更加精确地(像素级)的控制模型表面的各个性质。
Shader "MyShader/maskTex"
{
Properties
{
_SpecularMask("specular mask",2D)="white"{}///
_SpecularScale("specular scale",float)=1///
_Specular("specular",Color)=(1,1,1,1)
_Gloss("gloss",Range(1,256))=20
_Diffuse("diffuse",Color)=(1,1,1,1)
_MainTex ("Texture", 2D) = "white" {}
_BumpMap("Normal Map",2D)="bump"{}
_BumpScale("BumpScale",float) = 1
}
SubShader
{
Tags { "RenderType" = "Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "UnityLightingCommon.cginc"
sampler2D _SpecularMask;///
float4 _SpecularMask_ST;///
float _SpecularScale;///
sampler2D _MainTex;
float4 _MainTex_ST;
sampler2D _BumpMap;
float4 _BumpMap_ST;
float _BumpScale;
fixed4 _Diffuse;
fixed4 _Specular;
float _Gloss;
struct v2f
{
float4 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float2 maskUv : TEXCOORD1;///
float3 lightDir : TEXCOORD2;
float3 viewDir : TEXCOORD3;
};
v2f vert (appdata_tan v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv.xy = TRANSFORM_TEX(v.texcoord, _MainTex);
o.uv.zw = TRANSFORM_TEX(v.texcoord, _BumpMap);
o.maskUv= TRANSFORM_TEX(v.texcoord, _SpecularMask);///
TANGENT_SPACE_ROTATION;
o.lightDir = mul(rotation, ObjSpaceLightDir(v.vertex)).xyz;
o.viewDir = mul(rotation, ObjSpaceViewDir(v.vertex)).xyz;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed3 tangentLight = normalize(i.lightDir);
fixed3 tangentView = normalize(i.viewDir);
//环境光
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.rgb;
//贴图采样
fixed3 col = tex2D(_MainTex, i.uv.xy).rgb;
fixed4 packedNormal = tex2D(_BumpMap, i.uv.zw);
fixed3 tangentNormal = UnpackNormal(packedNormal);
tangentNormal.xy *= _BumpScale;
//漫反射
fixed3 diffuse = _LightColor0.rgb*col*_Diffuse.rgb*(saturate(dot(tangentLight, tangentNormal))*0.5+0.5);
fixed specularMask = tex2D(_SpecularMask, i.maskUv).r*_SpecularScale;///取得r通道的掩码值
//高光反射
fixed3 halfDir = normalize(tangentLight + tangentView);
fixed3 specular = _LightColor0.rgb*_Specular*pow(saturate(dot(tangentNormal, halfDir)), _Gloss)*specularMask;///
fixed3 color = diffuse+ambient+specular;
return fixed4(color,1);
}
ENDCG
}
}
}