1. 程式人生 > >適合手機上用的實時光照shader,移動平臺上著色器的優化

適合手機上用的實時光照shader,移動平臺上著色器的優化

Shader "LT/NoLightmap/MobileBlinnPhongr" {
Properties {
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGB)", 2D) = "white" {}    //A通道儲存高光
_NormalMap ("Normal Map", 2D) = "bump" {}    
_SpecIntensity ("Specular Width", Range(0.01,1)) = 0.5
}
SubShader {
Tags { "RenderType"="Opaque" }
LOD 200

CGPROGRAM
// Physically based Standard lighting model, and enable shadows on all light types
//忽略延遲光照,不支援光照貼圖,noforwardadd只接受一個單一的平行光光源作為逐畫素光源,其他燈光強制轉為逐頂點的光照
//最後,使用halfasview宣告告訴Unity,我們使用一個介於光照方向和觀察方向之間的half vector來代替真正的觀察方向viewDir來計算光照函式。
//這將加速Shader的處理時間,因為這是基於逐頂點而非逐畫素計算而得的。雖然這樣得到的結果是近似值,但對於移動平臺來說足夠了。
#pragma surface surf MobileBlinnPhong exclude_path:prepass nolightmap noforwardadd  halfasview
#pragma exclude_renderers flash d3d11

// Use shader model 3.0 target, to get nicer looking lighting
#pragma target 2.0


sampler2D _MainTex;
sampler2D _NormalMap;
half _SpecIntensity;
fixed4 _Color;

//前面還一個頂點函式給出IN

//IN相當於是 frag的輸入
struct Input {
half2 uv_MainTex;
};

void surf (Input IN, inout SurfaceOutput o) {
// Albedo comes from a texture tinted by color
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
o.Albedo = c.rgb;
o.Gloss = c.a;
o.Alpha = 0;
o.Specular = _SpecIntensity;
o.Normal = UnpackNormal(tex2D(_NormalMap, IN.uv_MainTex));
o.Alpha = c.a;
}

inline fixed4 LightingMobileBlinnPhong(SurfaceOutput s, fixed3 lightDir, fixed3 halfDir,fixed atten)
{
fixed diff= max(0,dot(s.Normal,lightDir));
fixed nh= max(0,dot(s.Normal,halfDir));
fixed spec= pow(nh,s.Specular*128) * s.Gloss;

fixed4 c;
c.rgb = (s.Albedo * _LightColor0.rgb * diff + _LightColor0.rgb *spec) * (atten * 2);
c.a = 0;
return c;
}
ENDCG
}
FallBack "Diffuse"
}