美文网首页
单张纹理_01

单张纹理_01

作者: Rayson | 来源:发表于2020-06-08 10:22 被阅读0次

A.单张纹理应用
通常使用一张纹理来代替物体的漫反射颜色
纹理名_ST表示声明某个纹理的属性,name##_ST.xy 存储缩放值,name##_ST.zw存储偏移值。
结合之前的光照模型的单张纹理应用:

Shader "Single_Texture"{
    Properties{
    _Color ("Color Tint", Color) = (1, 1, 1, 1)
    //_Maintex("Main Tex",2D)="white"{}
    _MainTex ("Main Tex", 2D) = "white" {}
    _Specular ("Specular",Color)=(1,1,1,1) 
    _Gloss("Gloss",Range(8.0,256)) = 20
    }
        SubShader{
            Tags {"LightMode"="ForwardBase"}
          Pass{

           CGPROGRAM

           #pragma vertex vert
           #pragma fragment frag

           #include "Lighting.cginc"


        fixed4 _Color;
            sampler2D _MainTex;
            float4 _MainTex_ST;
            fixed4 _Specular;
            float _Gloss;


        struct a2v
        {
              float4 vertex :POSITION;
              float3 normal :NORMAL;
              float4 texcoord:TEXCOORD0;
              
        };


        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);
                
                o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
                
                o.uv = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;
                    return o;
                }

                fixed4 frag (v2f i):SV_Target
                {
                    fixed3 worldNormal = normalize(i.worldNormal);
                fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
                
                // Use the texture to sample the diffuse color
                fixed3 albedo = tex2D(_MainTex, i.uv).rgb * _Color.rgb;
                
                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
                
                fixed3 diffuse = _LightColor0.rgb * albedo * max(0, dot(worldNormal, worldLightDir));
                
                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);
                }
            ENDCG
    }
    
    }
        Fallback "Specular "
}

要点1:tex2D函数表示对纹理进行采样,param1是需要被采样的纹理,param2是float2类型的纹理坐标,返回计算得到的纹素值。
要点2:TRASFORM_TEX实在UnityCG.cginc中定义的:

//Transform 2D UV by scale/bias property
//param1是顶点的纹理坐标
//param2是纹理的名称
#define TRANSFORM_TEX(tex,name)(tex.xy * name##_ST.xy + name##_ST.zw)

相关文章

网友评论

      本文标题:单张纹理_01

      本文链接:https://www.haomeiwen.com/subject/msqltktx.html