您的位置:首页 > 移动开发 > Unity3D

unity shader学习笔记(七)——Unity中的基础纹理之遮罩纹理

2017-11-20 23:33 357 查看

遮罩纹理

  遮罩纹理(Mask Texture)一般是通过采样得到遮罩纹理的纹素值,使用其中一个或多个通道的值与需要遮罩处理的表面属性相乘,这样可以在像素级别控制模型的表面属性。下面是一个高光遮罩纹理的实现,shader代码如下:

Shader "Custom/Texture/SpecularVertexShader" {
Properties
{
_Color("Diffuse", Color) = (1.0, 1.0, 1.0, 1.0)
_MainTex("Main Tex", 2D) = "white" {}
_BumpMap("Normal Map", 2D) = "bump" {}
_BumpScale("Bump Scale", Float) = 1.0
_SpecularMask("Specular Mask", 2D) = "white" {}
_SpecularScale("Specular Scale", Float) = 1.0
_Specular("Specular", Color) = (1.0, 1.0, 1.0, 1.0)
_Gloss("Gloss", Range(8.0, 256)) = 20
}
SubShader
{
Pass
{
Tags{ "LightMode" = "ForwardBase" }

CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"

fixed4 _Color;
sampler2D _MainTex;
float4 _MainTex_ST;           //_MainTex、_BumpMap、_SpecularMask 共同使用一个纹理属性变量
sampler2D _BumpMap;
float _BumpScale;
sampler2D _SpecularMask;
float _SpecularScale;
fixed4 _Specular;
float _Gloss;

struct a2v
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
float4 texcoord : TEXCOORD;
};

struct v2f
{
float4 position : SV_POSITION;
float2 uv : TEXCOORD0;
float3 lightDir : TEXCOORD1;
float3 viewDir : TEXCOORD2;
};

v2f vert(a2v v)
{
v2f a;
a.position = UnityObjectToClipPos(v.vertex);

//映射纹理属性
a.uv.xy = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;

//获得世界空间到切线空间的转换矩阵
TANGENT_SPACE_ROTATION;
//计算副法线, v.tangent.w代表了副法线的方向
//float3 binormal = cross(normalize(a.normal), normalize(a.tangent.xyz)) * a.tangent.w;
//按行排列得到世界空间到切线空间的变换矩阵
//float3x3 rotation = float3x3(a.tangent.xyz, binormal, a.normal);

//把光照方向转化为切下空间下的法线
a.lightDir = mul(rotation, ObjSpaceLightDir(v.vertex)).xyz;

//把视角方向转化为切下空间下的法线
a.viewDir = mul(rotation, ObjSpaceViewDir(v.vertex)).xyz;

return a;
}

fixed4 frag(v2f a) : SV_Target
{
//归一
fixed3 tangentLightDir = normalize(a.lightDir);
fixed3 tangentViewDir = normalize(a.viewDir);

//计算法线纹理
fixed3 tangentNormal = UnpackNormal(tex2D(_BumpMap, a.uv));
tangentNormal.xy *= _BumpScale;
tangentNormal.z = sqrt(1.0 - saturate(dot(tangentNormal.xy, tangentNormal.xy)));

//纹理颜色
fixed3 albedo = tex2D(_MainTex, a.uv).rgb * _Color.rgb;

//环境光
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;

//漫反射光
fixed3 diffuse = _LightColor0.rgb * albedo * saturate(dot(tangentNormal, tangentLightDir));

//入射光和摄像机方向的中间向量
fixed3 halfDir = normalize(tangentLightDir + tangentViewDir);

//获取高光遮罩纹理
fixed specularMask = tex2D(_SpecularMask, a.uv).r * _SpecularScale;

//高光反射
fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(max(0, dot(tangentNormal, halfDir)), _Gloss) * specularMask;

//颜色
fixed3 color = ambient + diffuse + specular;

return fixed4(color, 1.0);
}
ENDCG
}
}
FallBack "Specular"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity