《Unity Shader入門精要》自學筆記(一)
Properties {
_Diffuse("Diffuse",color) = (1,1,1,1)
//用於顏色設定
}
SubShader {
pass{
tags{"LightMode" = "ForwardBase"}
CGPROGRAM
float4 _Diffuse;
//取用設定中的顏色資訊
#pragma vertex vert#pragma fragment frag
#include "Lighting.cginc"
struct a2v {
float4 vertex:POSITION;
float3 normal :NORMAL;
};
struct v2f{
float4 pos :SV_POSITION;
float3 color :color;
};
v2f vert(a2v i){
v2f o;
o.pos = mul(UNITY_MATRIX_MVP,i.vertex);
//將頂點座標變換到世界座標系
float3 worldNormal = normalize(mul(i.normal,(float3x3)unity_WorldToObject));
//把頂點法線變換到世界座標系
float3 ambient = UNITY_LIGHTMODEL_AMBIENT.rgb;
//取得環境光的顏色資訊
float3 worldLight = normalize(_WorldSpaceLightPos0.xyz);
//獲得世界中光的入射資訊
float3 diffuse = _LightColor0.rgb*_Diffuse.rgb*saturate(dot(worldNormal,worldLight));
//進行計算。公式為 :入射光資訊*自身反射資訊*(法線和入射光的點積)
o.color = ambient + diffuse;
//加入環境光
return o;}
fixed4 frag(v2f i):SV_Target{
return float4(i.color,1.0);
}
ENDCG
}
}
FallBack "Diffuse"
}
以上為逐頂點計算,為非線性,過度較為不均勻
增加:逐畫素計算也貼上
Shader "Custom/zhuxiangsu" {
Properties {
_Diffuse("Diffuse",color) = (1,1,1,1)
}
SubShader {
pass{
tags{"LightMode" = "ForwardBase"}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
float4 _Diffuse;
struct a2v{
float4 vertex :POSITION;
float3 normal :NORMAL;
};
struct v2f{
float4 pos:SV_POSITION;
fixed3 worldNormal:TEXCOORD0;
};
v2f vert(a2v i){
v2f o;
o.pos = mul(UNITY_MATRIX_MVP,i.vertex);
o.worldNormal = mul(i.normal,(float3x3)unity_WorldToObject);
return o;
}
fixed4 frag(v2f i):SV_Target{
float3 worldNormal = normalize(i.worldNormal);
float3 ambient = UNITY_LIGHTMODEL_AMBIENT.rgb;
float3 worldLight = normalize(_WorldSpaceLightPos0.xyz);
fixed3 diffuse = _LightColor0.rgb*_Diffuse.rgb*saturate(dot(worldNormal,worldLight));
fixed3 color = diffuse + ambient;
return fixed4(color,1.0);
}
ENDCG
}
}
FallBack "Diffuse"
}
逐畫素過度較為均勻,但是消耗增加