上次說到很簡單的shader,這次來用顏色可視化模擬和頂點相關(guān)的數(shù)據(jù),代碼如下:
Shader "Unity Shaders Book/Chapter 5/False Color" {
SubShader {
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f {
float4 pos : SV_POSITION;
fixed4 color : COLOR0;
};
v2f vert(appdata_full v) {
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
// Visualize normal
o.color = fixed4(v.normal * 0.5 + fixed3(0.5, 0.5, 0.5), 1.0);
// Visualize tangent
o.color = fixed4(v.tangent.xyz * 0.5 + fixed3(0.5, 0.5, 0.5), 1.0);
// Visualize binormal
fixed3 binormal = cross(v.normal, v.tangent.xyz) * v.tangent.w;
o.color = fixed4(binormal * 0.5 + fixed3(0.5, 0.5, 0.5), 1.0);
// Visualize the first set texcoord
o.color = fixed4(v.texcoord.xy, 0.0, 1.0);
// Visualize the second set texcoord
o.color = fixed4(v.texcoord1.xy, 0.0, 1.0);
// Visualize fractional part of the first set texcoord
o.color = frac(v.texcoord);
if (any(saturate(v.texcoord) - v.texcoord)) {
o.color.b = 0.5;
}
o.color.a = 1.0;
// Visualize fractional part of the second set texcoord
o.color = frac(v.texcoord1);
if (any(saturate(v.texcoord1) - v.texcoord1)) {
o.color.b = 0.5;
}
o.color.a = 1.0;
// Visualize vertex color
// o.color = v.color;
return o;
}
fixed4 frag(v2f i) : SV_Target {
return i.color;
}
ENDCG
}
}
}
從#include "UnityCG.cginc"說起,它是包含了unity的一個內(nèi)置文件UnityCG.cginc,在unity的安裝目錄 /Data/CGIncludes/UnityCG.cginc下面能夠找到。而appdata_full 結(jié)構(gòu)體就在其中定義了
v2f和fixed4決定了vert和fragment函數(shù)的輸出類型
vert函數(shù)具體代碼中,v.normal 可以通過加權(quán)平均共享該頂點的所有三角形面法線得到,因為v.normal 的各個分量范圍是[-1,1],而顏色RGB的分量范圍是[01,],于是就要解決這個范圍映射問題,所以就有了o.color = fixed4(v.normal * 0.5 + fixed3(0.5, 0.5, 0.5), 1.0);這樣的代碼,切線可視化類似,但需要主要的是切線是四維向量,具體可在Sahder筆記中查看,切線和副切線如何計算的可參照這個。
o.color = fixed4(v.texcoord.xy, 0.0, 1.0);是把頂點的第一組紋理坐標存到color中
o.color = frac(v.texcoord1);則是計算頂點第二組紋理各分量的小數(shù)部分,saturate意為返回一個[0, 1]范圍內(nèi)的數(shù),如果x<0則返回0,如果x>1則返回1,否則返回x。
相信通過添加注釋不同位置的代碼,就能更直觀的看到結(jié)果了。