BlinnPhong补充

2020-06-16  本文已影响0人  Rayson
            Shader "Davia/09_Specular Fragment-BlinnPhong"{

    Properties{
        _DiffuseColor("Diffuse Color",color) = (1,1,1,1)
        _SpecularColor("Specular Color",color) = (1,1,1,1)
        _SpecularPow("Specular Pow",Range(1,20)) = 1.0
    }

    SubShader
    {
        Pass
        {
            Tags{"Lightmode" = "ForwardBase"}
            CGPROGRAM
            #include"Lighting.cginc"
            #pragma vertex vert
            #pragma fragment frag

            fixed4 _DiffuseColor;
            fixed4 _SpecularColor;
            fixed  _SpecularPow;


            //application to vertex
            struct a2v{
                float4 vertex:POSITION;
                fixed3 normal:NORMAL;

            };
            //vertex to fragment
            struct v2f{
                float4 position:SV_POSITION;
                float3 worldnormal:TEXCOORD0;
                float3 worldvertex:TEXCOORD1;
            };

            //将计算过程放在顶点中:逐顶点光照
            v2f vert(a2v v) { 
                v2f f;
                //顶点位置从模型空间转换到裁减空间 也叫投影空间
                f.position = mul(UNITY_MATRIX_MVP,v.vertex);
                //法线、顶点在世界空间中的位置 放在顶点函数中计算
                f.worldnormal = mul(v.normal, (float3x3)_World2Object);
                f.worldvertex = mul(v.vertex, _World2Object).xyz;
                return f;
            } 

             //将计算过程放在片元中:逐像素光照
            fixed4 frag(v2f f):SV_Target
            {
                //光方向
                fixed3 lightDir = normalize(_WorldSpaceLightPos0.xyz);
                //法线方向
                fixed3 normalDir = normalize(f.worldnormal);
                //漫反射光
                fixed3 diffuse = _LightColor0.rgb * max(dot(lightDir,normalDir),0) * _DiffuseColor.rgb;
                //环境光
                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.rgb;
                //反射光方向 - 在BlinnPhong光照中不需要计算反射光方向 故屏蔽
                //fixed3 reflectDir = normalize(reflect(-lightDir, normalDir));
                //观察方向
                fixed3 viewDir = normalize(_WorldSpaceCameraPos.xyz - f.worldvertex);
                //中间方向(入射光方向与观察方向中间方向)
                fixed3 helfDir = normalize(lightDir + viewDir);
                //反射高光计算
                fixed3 specular = _SpecularColor * _LightColor0.rgb * pow(max(dot(normalDir, helfDir ), 0), _SpecularPow);
                //颜色的叠加-通过相加
                fixed3 tempcolor = diffuse + ambient + specular;
                    return fixed4(tempcolor,0.5);
            }
            ENDCG
        }
    }

    Fallback"Unlit/Diffuse"
}

上一篇 下一篇

猜你喜欢

热点阅读