[Unity]用Enlighten生成lightmap用作模型光照贴图

Enlighten一般都被我们用来生成场景lightmap用,其实也可以用它来生成一张针对某单个模型的光照贴图。

具体做法是:场景中只摆放这一个物体,然后用Enlighten渲出lightmap贴图(当然也可以多个物体一起渲,只要调整每个物体在生成的lightmap中的比例,保证每个物体对应一整张exr就行了。这个我没自己试过,美术说的).然后自己写shader来对光照贴图采样。

这样,就不是仅仅静态模型才能使用lightmap了,动态生成的物体也可以用自己对应的lightmap来保留光照信息(比如实时随机生成的场景).

下面是一个自己改写的Linear Space下的简单Diffuse + Lightmap贴图shader.主要改动在改写了Unity内置的DecodeLightMap函数部分.该函数在Unity5中有bug,对LDR格式的lightmap并没有针对Linear Space进行处理,因此在移动设备上的采样需要自己重写.

Shader "Custom/LightmappedTexture"
 {  
	Properties 
	{  
		_MainTex ("Base (RGB)", 2D) = "white" {}  
		_LightMap ("Lightmap (RGB)", 2D) = "black" {}
	}  
	
	SubShader
	{  
		Tags { "RenderType"="Opaque" }  
		LOD 100  
		
		Pass 
		{    
			CGPROGRAM  
			#pragma vertex vert  
			#pragma fragment frag  
			#pragma multi_compile_fog  

			#include "UnityCG.cginc"  

			struct appdata_t 
			{  
				float4 vertex : POSITION;  
				float2 texcoord : TEXCOORD0;  
				float2 texcoord1 : TEXCOORD1;  
			};  

			struct v2f {  
				float4 vertex : SV_POSITION;  
				half2 texcoord : TEXCOORD0;  
				half2 uvLM : TEXCOORD1;  
				UNITY_FOG_COORDS(2)  
			};  

			sampler2D _MainTex;  
			float4 _MainTex_ST;  
			UNITY_DECLARE_TEX2D(_LightMap);
			float4 _LightMap_ST;  			
			
			half3 DecodeLightmapCustom(fixed4 data)
			{				
				#if defined(UNITY_NO_RGBM)
     			  	return data.rgb * pow(data.a * 2, 2.2) * 8;//主要修改在这句,Linear空间下要进行一次Gamma Correction所以要pow 2.2
				#else
					return (2 * data.a) * sqrt(data.rgb);//PC上是RGBM格式的,走这里
				#endif
			}

			v2f vert (appdata_t v)  
			{  
				v2f o;  
				o.vertex = UnityObjectToClipPos(v.vertex);  
				o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);  
				o.uvLM = v.texcoord1.xy * _LightMap_ST.xy + _LightMap_ST.zw;  
				UNITY_TRANSFER_FOG(o,o.vertex);  
				return o;  
			}  
			
			fixed4 frag (v2f i) : SV_Target  
			{  
				fixed4 col = tex2D(_MainTex, i.texcoord);  
				UNITY_APPLY_FOG(i.fogCoord, col);  
				fixed3 lm = DecodeLightmapCustom(UNITY_SAMPLE_TEX2D(_LightMap, i.uvLM.xy));
				col.rgb*=lm;  

				return col;  
			}  
			ENDCG  
		}  
	}  
  
}  

参考链接:

1. https://www.jianshu.com/p/b8231ed43c8c

2. https://docs.unity3d.com/ScriptReference/TextureImporterSettings-rgbm.html

猜你喜欢

转载自blog.csdn.net/tlrainty/article/details/80583263