游戏里的动态阴影-ShadowMap实现原理

ShadowMap是比较流行的实时阴影实现方案,原理比较简单,但真正实现起来还是会遇到很多问题的,我这里主要记录下实现方式

先看效果

实现原理

ShadowMap技术是从灯光空间用相机渲染一张RenderTexture,把深度值写入其中所以称之为 深度图 ,在把接受阴影的物体从模型空间转换到灯光空间中,获取深度图里的深度进行比较,如果深度值比深度图中取出的值大就说明该点为阴影。

《Cg教程_可编程实时图形权威指南》书上说的原理
阴影映射是一个双过程的技术:
1、 首先,场景以光源的位置为视点被渲染。每个渲染图像的像素的深度被记录在一个“深度纹理”中(这个纹理通常被称为阴影贴图)。
2、 然后,场景从眼睛的位置渲染,但是用标准的阴影纹理把阴影贴图从灯的位置投影到场景中。在每个像素,深度采样(从被投影的阴影贴图纹理)与片段到灯的距离进行比较。如果后者大,该像素就不是最靠近灯源的表面。这意味着这个片段是阴影,它在着色过程中不应该接受光照。

第一步:生成深度图shader####

把视点空间的Z值深度传入片段找色器里除以w转换为其次坐标,为啥要传入片段找色器处理呢?因为GPU会对片段找色器传入的参数进行插值计算,这样才能更精确的计算出深度。

计算出深度之后,要转换到一张图片里存储起来,如何把一个float存入图片中呢?
float是4个字节的,刚好可以对应RGBA4个分量,把一个float转换成颜色值就可以存为图片了,Unity中提供了一个内置函数:EncodeFloatRGBA帮助我们转换

Shader "lijia/DeapthTextureShader"
{
	Properties
	{
		_MainTex ("Texture", 2D) = "white" {}
	}
	SubShader
	{
		Tags { "RenderType"="Opaque" }
		LOD 100

		Pass
		{
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag

			#include "UnityCG.cginc"

			struct appdata
			{
				float4 vertex : POSITION;
				float2 uv : TEXCOORD0;
			};

			struct v2f
			{
				float2 uv : TEXCOORD0;
				float4 vertex : SV_POSITION;
				float2 depth : TEXCOORD1;
			};

			sampler2D _MainTex;
			float4 _MainTex_ST;
			
			v2f vert (appdata v)
			{
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.uv = TRANSFORM_TEX(v.uv, _MainTex);
				o.depth = o.vertex.zw;
				return o;
			}
			
			fixed4 frag (v2f i) : SV_Target
			{
				float depth = i.depth.x/i.depth.y;
				fixed4 col = EncodeFloatRGBA(depth);
				return col;
			}
			ENDCG
		}
	}
}

第二步:接受阴影的Shader

假如有一块地板作为接受阴影的物体,在这个物体上运行该Shader

  1. 把深度值传入片段着色器里,在片段着色器中除以w转换为其次坐标的深度值(跟生成深度图的Shader一样处理)
  2. 把顶点转换到灯光的视点空间,这里是传入一个lijia_ProjectionMatrix 矩阵计算的
  3. 取出该像素对应深度图上的颜色值,转换成深度值
  4. 把该像素的深度值跟深度图里取出来的值进行比较,如果比深度图里的大,该点就为阴影
Shader "swan/ShadowMap/ShadowMapNormal"
{
	Properties
	{
		_MainTex("Texture", 2D) = "white" {}
	}
	SubShader
	{
		Pass
		{
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag

			#pragma multi_compile_fog

			#include "UnityCG.cginc"

			sampler2D _MainTex;
			float4 _MainTex_ST;

		
			// sampler2D unity_Lightmap;//若开启光照贴图,系统默认填值
			// float4 unity_LightmapST;//与上unity_Lightmap同理

			struct v2f {
				float4 pos:SV_POSITION;
				float2 uv:TEXCOORD0;
				float2 uv2:TEXCOORD1;
				UNITY_FOG_COORDS(2)
				float4 proj : TEXCOORD3;
				float2 depth : TEXCOORD4;
			};


			float4x4 lijia_ProjectionMatrix;
			sampler2D lijia_DepthTexture;

			v2f vert(appdata_full v)
			{
				v2f o;
				o.pos = mul(UNITY_MATRIX_MVP, v.vertex);

				//动态阴影
				o.depth = o.pos.zw;
				lijia_ProjectionMatrix = mul(lijia_ProjectionMatrix, unity_ObjectToWorld);
				o.proj = mul(lijia_ProjectionMatrix, v.vertex);
				//--------------------------------------------------
				o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
				o.uv2 = v.texcoord1.xy * unity_LightmapST.xy + unity_LightmapST.zw;
				UNITY_TRANSFER_FOG(o, o.pos);

				return o;
			}

			fixed4 frag(v2f v) : COLOR
			{
				//解密光照贴图计算公式
				float3 lightmapColor = DecodeLightmap(UNITY_SAMPLE_TEX2D(unity_Lightmap,v.uv2));
				fixed4 col = tex2D(_MainTex, v.uv);

				col.rgb *= lightmapColor;

				UNITY_APPLY_FOG(v.fogCoord, col);

				float depth = v.depth.x / v.depth.y;
				fixed4 dcol = tex2Dproj(lijia_DepthTexture, v.proj);
				float d = DecodeFloatRGBA(dcol);
				float shadowScale = 1;
				if(depth > d)
				{
					shadowScale = 0.55;
				}
				return col*shadowScale;
			}
			ENDCG
		}
	}
}

第三步:写一个脚本调用上面的2个Shader####

上面我们已经创建好了2个Shader

  1. 生成深度图的DeapthTextureShader.shader
  2. 接受阴影的ShadowMapNormal(我这里把T4M跟接收光照贴图的处理都写进去了)

脚本主要做的事情

  1. 创建一个相机把角度设置的跟灯光一样,渲染出一张深度图传入给接受阴影的Shader(像素越高阴影的精度越高,但是消耗也就越大)
  2. 计算好顶点转换到灯光空间的矩阵传入给接受阴影的shader
using UnityEngine;
using System.Collections;
namespace SwanEngine.Core
{
    /// <summary>
    /// 创建depth相机
    /// by lijia
    /// </summary>
    public class DepthTextureCamera : MonoBehaviour
    {
        Camera _camera;

        RenderTexture _rt;
        /// <summary>
        /// 光照的角度
        /// </summary>
        public Transform lightTrans;

        Matrix4x4 sm = new Matrix4x4();

        void Start()
        {
            _camera = new GameObject().AddComponent<Camera>();
            _camera.name = "DepthCamera";
            _camera.depth = 2;
            _camera.clearFlags = CameraClearFlags.SolidColor;
            _camera.backgroundColor = new Color(1, 1, 1, 0);

            _camera.cullingMask = LayerMask.GetMask("Player");
            _camera.aspect = 1;
            _camera.transform.position = this.transform.position;
            _camera.transform.rotation = this.transform.rotation;
            _camera.transform.parent = this.transform;

            _camera.orthographic = true;
            _camera.orthographicSize = 10;

            sm.m00 = 0.5f;
            sm.m11 = 0.5f;
            sm.m22 = 0.5f;
            sm.m03 = 0.5f;
            sm.m13 = 0.5f;
            sm.m23 = 0.5f;
            sm.m33 = 1;

            _rt = new RenderTexture(1024, 1024, 0);
            _rt.wrapMode = TextureWrapMode.Clamp;
            _camera.targetTexture = _rt;
            _camera.SetReplacementShader(Shader.Find("lijia/DeapthTextureShader"), "RenderType");
        }

        void Update()
        {
            this.transform.eulerAngles = new Vector3(37.2f, -46.109f, -90.489f);
            _camera.Render();
            Matrix4x4 tm = GL.GetGPUProjectionMatrix(_camera.projectionMatrix, false) * _camera.worldToCameraMatrix;

            tm = sm * tm;

            Shader.SetGlobalMatrix("lijia_ProjectionMatrix", tm);
            Shader.SetGlobalTexture("lijia_DepthTexture", _rt);
        }


    }
}

后面的话

几乎所有的代码我都贴上来了,有一些Shader基础的话应该是可以实现出效果的,希望能够帮助到你们理解ShadowMap

在Unity里动态阴影的实现方式还有很多,这里有个大合集
https://blog.uwa4d.com/archives/sparkle_shadow.html

posted @ 2017-07-24 22:39  李嘉的博客  阅读(16416)  评论(0编辑  收藏  举报