阴影生成原理
以平行光为例,把相机移动到光源位置,计算阴影映射纹理(shadowmap),这张shadowmap本质上是一张深度图,它记录了从该光源的位置出发、能看到的场景中距离它最近的表面位置(深度信息)。渲染时中把顶点位置变换到光源空间下,得到它在光源空间中的三维位置信息。然后,我们使用xy分量对shadowmap进行采样,得到shadowmap中该位置的深度信息。如果该深度值小于该顶点的深度值(通常由z分量得到),那么说明该点位于阴影中。如图,将顶点P转换到光源空间,得到(Px, Py, Pz),Pz = 0.9,用(Px, Py)对shadowmap采样,得到C点的深度0.4,0.4 < 0.9,所以P点在阴影中
需要注意的细节
使用内置阴影的shader大致框架如下,这里略去一些不重要的部分
Shader "MyCustom/BuildinShadow"
{
Properties{}
SubShader
{
Tags { "RenderType"="Opaque" }
Pass
{
Tags {"LightMode"="ForwardBase"}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fwdbase
#include "UnityCG.cginc"
#include "Lighting.cginc"
#include "AutoLight.cginc"
struct appdata
{
float4 vertex : POSITION;
};
struct v2f
{
float4 pos : SV_POSITION;
SHADOW_COORDS(x) //x表示第几个纹理
};
v2f vert (appdata v)
{
v2f o;
//...
TRANSFER_SHADOW(o);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
//...
//fixed atten = 1.0;
//fixed shadow = SHADOW_ATTENUATION(i);
//return fixed4(ambient + (diffuse + specular) * atten * shadow, 1.0);
UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos);
return fixed4(ambient + (diffuse + specular) * atten, 1.0);
}
ENDCG
}
Pass
{
Tags {"LightMode"="ForwardAdd"}
Blend One One
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fwdadd
// #pragma multi_compile_fwdadd_fullshadows
#include "UnityCG.cginc"
#include "Lighting.cginc"
#include "AutoLight.cginc"
struct appdata
{
float4 vertex : POSITION;
};
struct v2f
{
float4 pos : SV_POSITION;
SHADOW_COORDS(x) //x表示第几个纹理
};
v2f vert (appdata v)
{
v2f o;
//...
TRANSFER_SHADOW(o);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
//...
UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos);
return fixed4((diffuse + specular) * atten, 1.0);
}
ENDCG
}
// 自己实现阴影,额外添加一个Pass,这个Pass是为了更新光源的阴影映射纹理
//Pass
//{
// Tags {"LightMode"="ShadowCaster"}
//}
}
Fallback "Specular"
}
需要注意的细节
- 光源设置阴影类型,Hard Shadows或者Soft Shadows
- 物体的Mesh Renderer上设置Cast Shadows和Receive Shadoes,Plane或一些半透明物体需要设置双面投射阴影,即Cast Shadows设置为Two Sided
- 使用内置阴影需要在shader结尾加上 Fallback “Specular”,Specular的Fallback调用了VertexLit,VertexLit中有个Pass渲染光源的阴影映射纹理,或是摄像机的深度纹理。如果要自己实现阴影,需要额外写一个Pass,并把LightMode设置为ShadowCaster
- Base Pass计算平行光和环境光,申明编译指令#pragma multi_compile_fwdbase,Additional Pass计算其他类型的光源,如果点光源或聚光灯也要计算阴影,需要申明编译指令#pragma multi_compile_fwdadd_fullshadows 代替 #pragma multi_compile_fwdadd
- Additional Pass需要设置混合 Blend One One
- 引用内置文件 #include “AutoLight.cginc”,计算阴影时所用的宏都是在这个文件中声明的
- SHADOW_COORDS,TRANSFER_SHADOW和SHADOW_ATTENUATION这三个宏是计算阴影时的“三剑客”,SHADOW_COORDS就是声明一个用于对阴影纹理采样的坐标,TRANSFER_SHADOW将顶点从模型空间转换到光源空间后存储到_ShadowCoord中,SHADOW_ATTENUATION使用阴影坐标采样阴影贴图,也可以使用UNITY_LIGHT_ATTENUATION代替SHADOW_ATTENUATION,它用于计算光照衰减和阴影,接受3个参数,将光照衰减和阴影值相乘后的结果存储到第一个参数中,使用UNITY_LIGHT_ATTENUATION,使得Base Pass和Additional Pass的代码得以统一
- 这些宏中会使用上下文变量来进行计算,所以变量名称需要和宏中使用的名称一致,a2v(或appdata)结构体中的顶点坐标变量名必须是vertex,顶点着色器的输入结构体a2v(或appdata)必须命名为v,v2f中的顶点位置变量必须命名为pos
完整的Shader
Shader "MyCustom/BuildinShadow"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Diffuse ("Diffuse", Color) = (0.5, 0.5, 0.5, 1)
_Specular ("Specular", Color) = (1, 1, 1, 1)
_SpecularPower ("SpecularPower", Range(0, 150)) = 20
_SpecularIntensity ("SpecularIntensity", Range(0, 10)) = 1.5
}
SubShader
{
CGINCLUDE
float _specular(float3 worldViewDir, float3 worldLightDir, float3 worldNormal, float power, float intensity)
{
float3 halfVector = normalize(worldLightDir + worldViewDir);
float hdotn = max(0, dot(halfVector, worldNormal));
float specular = pow(hdotn, power) * intensity;
return specular;
}
ENDCG
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
Tags {"LightMode"="ForwardBase"}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fwdbase
#include "UnityCG.cginc"
#include "Lighting.cginc"
#include "AutoLight.cginc"
struct appdata
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
float3 worldNormal : TEXCOORD1;
float3 worldPos : TEXCOORD2;
SHADOW_COORDS(3)
};
sampler2D _MainTex;
float4 _MainTex_ST;
float4 _Diffuse;
float4 _Specular;
float _SpecularPower;
float _SpecularIntensity;
v2f vert (appdata v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.worldNormal = UnityObjectToWorldNormal(v.normal);
o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
TRANSFER_SHADOW(o);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
float3 worldLightDir = UnityWorldSpaceLightDir(i.worldPos);
float3 worldViewDir = normalize(UnityWorldSpaceViewDir(i.worldPos));
fixed4 texColor = tex2D(_MainTex, i.uv);
fixed3 albedo = texColor.rgb * _Diffuse.rgb;
// 环境光
float3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
// 漫反射
float3 diffuse = _LightColor0.rgb * albedo * max(0, dot(i.worldNormal, worldLightDir));
// 高光
float3 specular = _LightColor0.rgb * _Specular.rgb * _specular(worldViewDir, worldLightDir, i.worldNormal, _SpecularPower, _SpecularIntensity);
// atten为阴影和衰减的乘积,UNITY_LIGHT_ATTENUATION针对不同类型的光源进行计算
UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos);
float4 finalColor = 1;
finalColor.rgb = ambient + (diffuse + specular) * atten;
return finalColor;
}
ENDCG
}
Pass
{
Tags {"LightMode"="ForwardAdd"}
Blend One One
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fwdadd
// 其他光源使用阴影,使用下面的指令替换掉 multi_compile_fwdadd
// #pragma multi_compile_fwdadd_fullshadows
#include "UnityCG.cginc"
#include "Lighting.cginc"
#include "AutoLight.cginc"
struct appdata
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
float3 worldNormal : TEXCOORD1;
float3 worldPos : TEXCOORD2;
SHADOW_COORDS(3)
};
sampler2D _MainTex;
float4 _MainTex_ST;
float4 _Diffuse;
float4 _Specular;
float _SpecularPower;
float _SpecularIntensity;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.worldNormal = UnityObjectToWorldNormal(v.normal);
o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
TRANSFER_SHADOW(o);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
float3 worldLightDir = UnityWorldSpaceLightDir(i.worldPos);
float3 worldViewDir = normalize(UnityWorldSpaceViewDir(i.worldPos));
// 漫反射
float3 diffuse = _LightColor0.rgb * _Diffuse.rgb * max(0, dot(i.worldNormal, worldLightDir));
// 高光
float3 specular = _LightColor0.rgb * _Specular.rgb * _specular(worldViewDir, worldLightDir, i.worldNormal, _SpecularPower, _SpecularIntensity);
UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos);
float4 finalColor = 1;
finalColor.rgb = (diffuse + specular) * atten;
return finalColor;
}
ENDCG
}
}
Fallback "Specular"
}
通过Frame Debug观察阴影的渲染过程,UpdateDepthTexture,即更新摄像机的深度纹理;RenderShadowmap,即渲染得到平行光的阴影映射纹理;CollectShadows,即根据深度纹理和阴影映射纹理得到屏幕空间的阴影图;最后绘制渲染结果
透明物体的阴影
需要注意的细节
- Tags设置 “Queue”=“AlphaTest” ,“RenderType”=“TransparentCutout”
- Cull Off 关闭剔除
- FallBack “Transparent/Cutout/VertexLit” 它含有透明度测试功能的ShadowCaster Pass
- 为了保证命名统一,必须使用_Cutoff来命名透明度阈值
- Mesh Renderer组件中的Cast Shadows属性设置为Two Sided,强制Unity在计算阴影映射纹理时计算所有面的深度信息
完整的shader
Shader "MyCustom/AlphaTestShadow"
{
Properties
{
_MainTex ("Main Tex", 2D) = "white" {}
_Color ("Color Color", Color) = (1, 1, 1, 1)
_Cutoff ("Alpha Cutoff", Range(0, 1)) = 0.5
}
SubShader
{
Tags { "Queue"="AlphaTest" "IgnoreProjector"="True" "RenderType"="TransparentCutout" }
Pass
{
Tags { "LightMode"="ForwardBase" }
Cull Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fwdbase
#include "Lighting.cginc"
#include "AutoLight.cginc"
sampler2D _MainTex;
float4 _MainTex_ST;
fixed4 _Color;
fixed _Cutoff;
struct a2v
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 uv : TEXCOORD0;
};
struct v2f
{
float4 pos : SV_POSITION;
float3 worldNormal : TEXCOORD0;
float3 worldPos : TEXCOORD1;
float2 uv : TEXCOORD2;
SHADOW_COORDS(3)
};
v2f vert(a2v v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.worldNormal = UnityObjectToWorldNormal(v.normal);
o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
TRANSFER_SHADOW(o);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
fixed4 texColor = tex2D(_MainTex, i.uv);
clip(texColor.a - _Cutoff);
fixed3 albedo = texColor.rgb * _Color.rgb;
// 环境光
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
// 漫反射
fixed3 diffuse = _LightColor0.rgb * albedo * max(0, dot(i.worldNormal, worldLightDir));
UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos);
return fixed4(ambient + diffuse * atten, 1.0);
}
ENDCG
}
}
FallBack "Transparent/Cutout/VertexLit"
}
参考
《Shader 入门精要》
查看Build-in Shaders 需要科学上网