核心内容
1.Planar Projected Shadow
2.衰减
第一点原理其实就是很简单的相似三角形
第二点是我结合了光的多次项衰减公式,并且为了调高性能,去掉了一次项的衰减。这样做的好处就是好比下面的函数图,根部的阴影会比较黑,越远渐变越小,并非一个一成不变的线性变化。
/*
formula of similar triangles
-Ly/My-h = Lx/Px-Mx
=>Px = Mx - Lx(My - h) /Ly && Py = h
*/
float3 worldPos = mul(_Object2World, v.vertex).xyz;
float3 lightDir = normalize(_LightDir.xyz);
float3 shadowPos;
shadowPos.y = _LightDir.w;
shadowPos.xz = worldPos.xz - lightDir.xz * max(0, worldPos.y - _LightDir.w) / lightDir.y;
//wolrd to clip
o.vertex = mul(UNITY_MATRIX_VP, float4(shadowPos, 1.0));
//center of world
float3 center = float3(_Object2World[0].w , _LightDir.w, _Object2World[2].w);
//shadow attenuation of linear
//float attenuation = 1 - saturate(distance(shadowPos , center) * _ShadowFalloff);
/*
formula of polynomial attenuation
atten = 1 / Kc + Kl*d + Kq * d^2
=>optimize
atten = 1 / Kc + Kq * d^2
*/
float centerDistance = distance(shadowPos, center);
float attenuation = max(0, 1.0 / (_ShadowAtten.x + _ShadowAtten.z * (centerDistance * centerDistance)));
o.color = _ShadowColor;
o.color.a *= attenuation;
看下面的两个效果图,是不是感觉右下角(没有hud)的更加自然,更加舒服。