Shader "Unlit/WorldSpaceNormals"
{
// no Properties block this time!
SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// include file that contains UnityObjectToWorldNormal helper function
#include "UnityCG.cginc"
struct v2f {
// we'll output world space normal as one of regular ("texcoord") interpolators
half3 worldNormal : TEXCOORD0;
float4 pos : SV_POSITION;
};
// vertex shader: takes object space normal as input too
v2f vert (float4 vertex : POSITION, float3 normal : NORMAL)
{
v2f o;
o.pos = UnityObjectToClipPos(vertex);
// UnityCG.cginc file contains function to transform
// normal from object to world space, use that
o.worldNormal = UnityObjectToWorldNormal(normal);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 c = 0;
// normal is a 3D vector with xyz components; in -1..1
// range. To display it as color, bring the range into 0..1
// and put into red, green, blue components
c.rgb = i.worldNormal*0.5+0.5;
return c;
}
ENDCG
}
}
}
美しい色の効果に加え、法線はライティング、反射、輪郭線、その他のグラフィックス効果すべてで利用されます。
上記のシェーダーでは、Unity のビルトインシェーダーインクルードファイルの 1つを使い始めました。ここでは、便利な関数 UnityObjectToWorldNormal を含む UnityCG.cginc を使用しました。また、頂点をオブジェクト空間から画面へ変換するユーティリティー関数 UnityObjectToClipPos も使用しました。これは単に、コードの読み込みを簡単にして、ある環境下でより効率的にするためのものです。
データは、頂点からいわゆる “補間” (または “変化” とも呼ばれる) でフラグメントシェーダーに渡せることを確認しました。HLSL シェーディング言語では通常、TEXCOORDn セマンティックでラベル付けされており、それぞれは最大 4 つのコンポーネントのベクトルになります (詳細はシェーダーへの頂点データの入力を参照してください)。
また、正規化されたベクトル (–1.0 から +1.0 の範囲) を色として可視化する簡単なテクニックも学びました。ベクトルを半分に掛け、半分を加算します。頂点データ可視化の例については、頂点データの可視化を参照してください。