Shader "Custom/3"
{
Properties
{
_Color("Color",Color) = (1,1,1,1)
_MainTex("Main Tex",2D) = "white"{}
_RampTex("Ramp Tex",2D) = "white"{}
_Specular("Specular",Color) = (1,1,1,1)
_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;
sampler2D _RampTex;
float4 _RampTex_ST;
float _Gloss;
fixed4 _Specular;
struct a2v
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 texcoord : TEXCOORD0;
};
struct v2f
{
float4 pos : SV_POSITION;
float3 worldPos : TEXCOORD0;
float3 worldNormal : TEXCOORD1;
float4 uv : TEXCOORD2;
};
v2f vert(a2v v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.worldPos = mul(unity_ObjectToWorld,v.vertex).xyz;
o.worldNormal = UnityObjectToWorldNormal(v.normal);
o.uv.xy = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;
o.uv.zw = v.texcoord.xy * _RampTex_ST.xy + _RampTex_ST.zw;
return o;
}
fixed4 frag(v2f i) : SV_Target
{
fixed3 worldNormal = normalize(i.worldNormal);
fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
// Use the texture to sample the diffuse color
//半lambert模型使阴影有过渡
fixed halfLambert = 0.5 * dot(worldNormal,worldLightDir) + 0.5;
//书本:使用halfLambert来构建一个纹理坐标
//_RampTex其实是一个一维纹理,所以uv方向上都使用RampTex来采样
fixed3 Ramp = tex2D(_RampTex, fixed2(halfLambert, halfLambert)).rgb;
fixed3 albedo = tex2D(_MainTex,i.uv.xy).rgb * _Color.rgb;
fixed3 diffuse = _LightColor0.rgb * Ramp * albedo;
fixed3 viewDir = normalize(UnityWorldSpaceViewDir(i.worldPos));
fixed3 halfDir = normalize(worldLightDir + viewDir);
fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(max(0, dot(worldNormal, halfDir)), _Gloss);
return fixed4(ambient + diffuse + specular, 1.0);
}
ENDCG
}
}
FallBack "Specular"
}
配合上纹理贴图使用效果更明显。
注意渐变纹理wrap mode要设置成Clamp模式,由于浮点精度,半兰伯特模型可能会取到1.0001
Repeat会取小数所以该亮的地方反而很黑
主要是在halfLambert模型上采样那一句需要理解。
fixed halfLambert = 0.5 * dot(worldNormal,worldLightDir) + 0.5;
fixed3 Ramp = tex2D(_RampTex, fixed2(halfLambert, halfLambert)).rgb;
效果如下图