原創文章如需轉載請註明:轉載自風宇沖Unity3D教程學院
Shader第十六講 自訂光照模型
十四講我們實現了基本的Surface Shader,十五講講了光照模型的基礎知識。這一講說的是如何寫光照模型。自訂光照模型主要分為4步:(0)架設架構,填寫需要的參數(1)計算漫反射強度(2)計算鏡面反射強度(3)結合漫反射光與鏡面反射光
代碼配有中文注釋,配合上上講的光照公式,一步一步實現即可。
- // Author: 風宇沖
- Shader "Custom/T_customLightModel" {
- Properties
- {
- _MainTex ("Texture", 2D) = "white" {}
- }
-
- Subshader
- {
- //alpha測試,配合surf中的o.Alpha = c.a;
- AlphaTest Greater 0.4
- CGPROGRAM
- #pragma surface surf lsyLightModel
-
- //命名規則:Lighting接#pragma suface之後起的名字
- //lightDir :點到光源的單位向量 viewDir:點到攝像機的單位向量 atten:衰減係數
- float4 LightinglsyLightModel(SurfaceOutput s, float3 lightDir,half3 viewDir, half atten)
- {
- float4 c;
-
- //(1)漫反射強度
- float diffuseF = max(0,dot(s.Normal,lightDir));
-
- //(2)鏡面反射強度
- float specF;
- float3 H = normalize(lightDir+viewDir);
- float specBase = max(0,dot(s.Normal,H));
- // shininess 鏡面強度係數,這裡設定為8
- specF = pow(specBase,8);
-
- //(3)結合漫反射光與鏡面反射光
- c.rgb = s.Albedo * _LightColor0 * diffuseF *atten + _LightColor0*specF;
- c.a = s.Alpha;
- return c;
- }
-
- struct Input
- {
- float2 uv_MainTex;
- };
-
- void vert(inout appdata_full v)
- {
- //這裡可以做特殊位置上的處理
- }
- sampler2D _MainTex;
-
- void surf(Input IN,inout SurfaceOutput o)
- {
- half4 c = tex2D(_MainTex, IN.uv_MainTex);
- o.Albedo = c.rgb;
- o.Alpha = c.a;
- }
- ENDCG
- }
- }