1. Texture for Diffuse
step 1 : prepare resources
Load the texture in your shader:
// Properties
_MainTex ("Main Tex", 2D) = "while" {}
// Pass in the first SubShader
sampler2D _MainTex;
float4 _MainTex_ST; // Scale:Tiling Trans:Offset
step 2 : prepare containers
Notice how the uv coordinates are stored.
struct a2v {
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 texcoord : TEXCOORD0;
// The TEXCOORD0 in a2v tells you where a vertex are on the given texture
// The UV coordinate will be saved in v2f, in a container TEXCOORDn.
};
struct v2f {
float4 pos : SV_POSITION;
float3 worldNormal : TEXCOORD0;
float3 worldPos : TEXCOORD1;
float2 uv : TEXCOORD2;
};
v2f vert(a2v v) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.worldNormal = UnityObjectToWorldNormal(v.normal);
// if there's Non-uniform Scale, you must pay attention to normal transformation.
// o.worldNormal = mul(v.normal, (float3x3)unity_WorldToObject);
o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
o.uv = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;
// o.uv = TRANSFORM_TEX(v.texcoord, _MainTex)
// up to now it's just a set of uv coordinate, no rgba information.
return o;
}
step 3 : sample the picture and calculate the color
tex2D(Texture from sampler2D, uv coordinate) returns rgba(fixed4) per coordinate.
fixed4 frag(v2f i) : SV_Target {
fixed3 worldNormal = normalize(i.worldNormal);
fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
fixed3 albedo = tex2D(_MainTex, i.uv).rgb * _Color.rgb; // TexColor and MaterialColor
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
fixed3 diffuse = _LightColor0.rgb * albedo * max(0, dot(worldNormal, worldLightDir));
// Blinn-Phong
fixed3 viewDir = normalize(UnityWorldSpaceViewDir(i.worldPos));
fixed3 halfDir = normalize(worldLightDir + viewDir);
fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(max(0, dot(worldNormal, halfDir)), _Gloss);
return fixed4(ambient + diffuse + specular, 1.0);
}
2. Bump Mapping (the MOST IMPORTANT !!!)
0.1 . Why bump mapping?
We calculate light and shadow by dot(lightDir, normalDir). Imagine that the normals o