- Unity 2018 Shaders and Effects Cookbook
- John P. Doran Alan Zucconi
- 286字
- 2025-04-04 16:34:20
How it works...
When the Standard Shader is used from the Inspector of a material, the process behind texture mapping is completely transparent to developers. If we want to understand how it works, it's necessary to take a closer look at TexturedShader. From the Properties section, we can see that the Albedo (RGB) texture is actually referred to in the code as _MainTex:
_MainTex ("Albedo (RGB)", 2D) = "white" {}
In the CGPROGRAM section, this texture is defined as sampler2D, the standard type for 2D textures:
sampler2D _MainTex;
The following line shows a struct called Input. This is the input parameter for the surface function and contains a packed array called uv_MainTex:
struct Input { float2 uv_MainTex; };
Every time the surf() function is called, the Input structure will contain the UV of _MainTex for the specific point of the 3D model that needs to be rendered. The Standard Shader recognizes that the name uv_MainTex refers to _MainTex and initializes it automatically. If you are interested in understanding how the UV is actually mapped from a 3D space to a 2D texture, you can check out Chapter 5, Understanding Lighting Models.
Finally, the UV data is used to sample the texture in the first line of the surface function:
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
This is done using the tex2D() function of Cg; it takes a texture and UV and returns the color of the pixel at that position.
The U and V coordinates go from 0 to 1, where (0,0) and (1,1) correspond to two opposite corners. Different implementations associate UV with different corners; if your texture happens to appear reversed, try inverting the V component.