Unity中写GLSL(八)—— 方向光 + Normal Map + Diffuse Map + AO Map

先上图:
Unity中写GLSL(八)—— 方向光 + Normal Map + Diffuse Map + AO Map_第1张图片

下面是代码

Shader "Custom/ShaderExample5"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}   //diffuse
        _BumpMap("Normal Map", 2D) = "bump" {}  //normal
        _OcclusionMap("Occlusion", 2D) = "white" {} //AO
    }

    SubShader
    {
        Pass
        {
            Tags {"LightMode"="ForwardBase"}

            GLSLPROGRAM

            uniform sampler2D _MainTex;
            uniform sampler2D _BumpMap;
            uniform sampler2D _OcclusionMap;

            uniform vec4 _BumpMap_ST;   //代表Tiling和Offset

            uniform mat4 _Object2World;
            uniform mat4 _World2Object;
            uniform vec4 _WorldSpaceLightPos0;  //light的位置
            uniform vec4 _LightColor0;  //light的颜色

            #ifdef VERTEX
            //顶点着色器

            attribute vec4 Tangent; //切线

            out vec4 texUvCoord;

            //tangent basis
            out mat3 localSurface2World;

            void main()
            {
                mat4 modelMatrix = _Object2World;
                mat4 modelMatrixInverse = _World2Object;

                //tangent转世界
                localSurface2World[0] = normalize(vec3(modelMatrix * vec4(vec3(Tangent), 0.0)));
                //normal转世界
                localSurface2World[2] = normalize(vec3(vec4(gl_Normal, 0.0) * modelMatrixInverse));
                //计算副法线(世界空间内)
                localSurface2World[1] = normalize(cross(localSurface2World[2], localSurface2World[0]) * Tangent.w);

                texUvCoord = gl_MultiTexCoord0;
                gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
            }

            #endif

            #ifdef FRAGMENT
            //片元着色器

            in vec4 texUvCoord;

            //tangent basis
            in mat3 localSurface2World;
            in vec4 worldPos;

            void main()
            {
                //从normal map里读取normal
                vec4 encodedNormal = texture2D(_BumpMap, _BumpMap_ST.xy * texUvCoord.xy + _BumpMap_ST.zw);

                //normal转到世界tangent坐标系中
                vec3 normalDirection = normalize(localSurface2World * vec3(encodedNormal));

                //light和normal的夹角cos
                float nl = max(0, dot(normalDirection, _WorldSpaceLightPos0.xyz));
                //光的颜色
                vec4 lightDiffuse = nl * _LightColor0;

                lightDiffuse += 0.3;

                //diffuse map的颜色
                vec4 diffuseColor = texture2D(_MainTex, vec2(texUvCoord));
                //AO map的颜色
                vec4 aoColor = texture2D(_OcclusionMap, vec2(texUvCoord));

                gl_FragColor = diffuseColor * lightDiffuse * aoColor * 1.5;
            }

            #endif

            ENDGLSL
        }
    }
}

你可能感兴趣的:(Shader)