Unity Shader TRANSFORM_TEX () method analysis

Analysis of TRANSFORM_TEX method

foreword

In the template code of the vertex shader, we can often see the figure of the TRANSFORM_TEX() method, such as the following code

            v2f vert(a2v v)
            {
    
    
                v2f o;
                o.pos = UnityObjectToClipPos(v.pos);
                o.uv = TRANSFORM_TEX(v.uv,_MainTex);
                return o;
            }

So what does this TRANSFORM_TEX(v.uv_MainTex) mean?

analyze

Let's leave TRANSFORM_TEX aside. See how Tiling & Offset works. If you are careful, you should find that when we declare a texture with sampler2D _MainTex, we can see that the 4 components of Tiling & Offset will be automatically generated for us in the Inspector panel.
insert image description here

So how do we use the 4 components of Tiling & Offset in the code:

Answer: Define a float4 variable, and the name must be the name of the texture plus the suffix '_ST' ,

  • For example, the texture is called _MainTex, then this variable is called _MainTex_ST;
  • These 4 components will be automatically attached to _MainTex_ST. Such as the following code
  • We can use _MainTex_ST.xy to get Tiling; use _MainTex_ST.zw to get Offset
            sampler2D _MainTex;
            float4 _MainTex_ST;//Tiling & Offset会自动附在这个变量里

The function of Tiling & Offset is to scale and offset UV, and map the original UV range (0 ~ 1) to (0 ~ 5) or any range you think of. How does it map.

We know that float4 _MainTex_ST has 4 components, so multiply our original UV by its first two components _MainTex_ST.xy, and add the last two components _MainTex_ST.zw, isn’t this the scaling and offset? . Such as the following code.

            v2f vert(a2v v)
            {
    
    
                v2f o;
                o.pos = UnityObjectToClipPos(v.pos);            
                o.uv = v.uv * _MainTex_ST.xy + _MainTex_ST.zw;//对uv进行重映射
                return o;
            }

Having said so much, what is the relationship with TRANSFORM_TEX:
We know that the effect achieved by using v.uv * _MainTex_ST.xy + _MainTex_ST.zw above is actually the same as the effect achieved by TRANSFORM_TEX(v.uv,_MainTex).

And in fact their final code is the same .
We can see the definition of the TRANSFORM_TEX method in UnityCG.cginc

define TRANSFORM_TEX(tex,name) (tex.xy * name##_ST.xy + name##_ST.zw)

In fact, this is a macro definition, name## represents the variable name we pass in, assuming we pass in the two parameters v.uv and _MainTex,
then the expanded code is:
TRANSFORM_TEX(v.uv,_MainTex) = v.uv .xy * _MainTex_ST.xy + _MainTex_ST.zw
You can see that this is actually the same as the code we used to implement Tiling&Offset.

So you understand now, TRANSFORM_TEX is actually a shorthand.
When we want to use Tiling&Offset, we can implement it ourselves, or we can directly use this shorthand method.

Guess you like

Origin blog.csdn.net/aaa27987/article/details/121349830