본문 바로가기
셰이더 (Shader)/유니티 쉐이더 스타트업 - 정종필

[Unity/Shader] 파트13-2 : Blinn Phong 스펙큘러 만들기

by Minkyu Lee 2023. 8. 18.

 

코드

Shader "Custom/Part13-2"
{
    Properties
    {
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _BumpMap ("NormalMap", 2D) = "bump" {}
        _SpecCol ("Specular Color", Color) = (1,1,1,1) // _SpecColor라고 쓰면 안된다. 유니티 내장 쉐이더에서 이미 쓰고 있는 용어다.
        _SpecPow ("Specular Power", Range(10,200)) = 100
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Test

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        sampler2D _MainTex;
        sampler2D _BumpMap;
        float4 _SpecCol;
        float _SpecPow;

        struct Input
        {
            float2 uv_MainTex;
            float2 uv_BumpMap;
        };

        UNITY_INSTANCING_BUFFER_START(Props)
            // put more per-instance properties here
        UNITY_INSTANCING_BUFFER_END(Props)

        void surf (Input IN, inout SurfaceOutput o)
        {
            fixed4 c = tex2D (_MainTex, IN.uv_MainTex);
            o.Albedo = c.rgb;
            o.Normal = UnpackNormal(tex2D(_BumpMap,IN.uv_BumpMap));
            o.Alpha = c.a;
        }

        float4 LightingTest(SurfaceOutput s, float3 lightDir, float3 viewDir, float atten) // viewDir 추가. 순서도 이대로 해야한다.
        {
            float4 final;

            // Lambert term
            float3 DiffColor;
            float ndot1 = saturate(dot(s.Normal, lightDir));
            DiffColor = ndot1 * s.Albedo * _LightColor0.rgb * atten;

            // Spec term
            float3 SpecColor;
            float3 H = normalize(lightDir + viewDir);
            float spec = saturate(dot(H,s.Normal));
            spec = pow(spec, 100); // 범위를 많이 좁혀줘야한다.
            SpecColor = spec * _SpecCol.rgb; // 프로퍼티에서 받은 컬러를 적용.

            // final term
            final.rgb = DiffColor.rgb + SpecColor.rgb;
            final.a = s.Alpha;
            return final;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

댓글