天天看點

unity shader (5)--實作逐像素光照

摘自馮樂樂的《unity shader 入門精要》

直接給列出代碼,有注釋:

Shader "Custom/DiffusePixelLevelMat" {
	Properties
	{
		_Diffuse("Diffuse",Color)=(1,1,1,1)
	}

	SubShader
	{
		Pass
		{
			Tags{"LightMode"="ForwardBase"}
			
			CGPROGRAM

			#pragma vertex vert
			#pragma fragment frag

			#include "Lighting.cginc"

			fixed4 _Diffuse;

			struct a2v
			{
				float4 vertex:POSITION;
				float4 normal:NORMAL;
			};

			struct v2f
			{
				float4 pos:SV_POSITION;
				//這裡與前面的相比做了更改
				fixed3 worldNormal:TEXCOORDO;
			};

			v2f vert(a2v v)
			{
				v2f o;

				//Transform the vertex from object space to projection space
				//變換對象空間的頂點投影空間
				o.pos=mul(UNITY_MATRIX_MVP,v.vertex);

				// Transform the normal from object space to world space
				//把局部法線轉換成空間法線
				o.worldNormal = mul(v.normal, (float3x3)_World2Object);

				return o;
			}

			fixed4 frag(v2f i):SV_Target
			{
				//get ambient term
				//擷取局部法線
				fixed3 ambient =UNITY_LIGHTMODEL_AMBIENT.xyz;

				//get the normal in world space
				//擷取空間法線
				fixed3 worldNormal=normalize(i.worldNormal);

				//get the light direction in world space
				//擷取空間光照
				fixed3 worldLightDir=normalize(_WorldSpaceLightPos0.xyz);

				//compute diffuse term
				//計算漫反射
				fixed3 diffuse=_LightColor0.rgb*_Diffuse.rgb*saturate(dot(worldNormal,worldLightDir));

				fixed3 color=ambient+diffuse;

				return fixed4(color,1.0);
			}

			ENDCG
		}		
	}
	FallBack "Diffuse"
}
           
unity shader (5)--實作逐像素光照

左邊為逐像素光照,右邊為漫反射模型

漫反射模型和逐像素光照的對比,在光暗的交彙處有很明顯的差别

繼續閱讀