셰이더 (Shader)/유니티 쉐이더 스타트업 - 정종필

[Unity/Shader] 파트18-1 : 2Pass를 이용한 깨끗한 알파 블렌딩 (뒷면이 안보이게)

Minkyu Lee 2023. 9. 4. 23:14

z버퍼에 그리는 것과,

화면에 그리는 것을 별도로 분리해 계산한다.

이를 통해 반투명의 뒷면이 안보이게 하는 방법이다.

 

코드

Shader "Custom/part18-1"
{
    Properties
    {
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 200

        // 1st pass : Z 버퍼에는 그리되, 화면엔 그리지 않는다.
        zwrite on
        ColorMask 0 // 화면에 그리지 않게 한다.
        CGPROGRAM
        #pragma surface surf nolight noambient noforwardadd nolightmap novertexlights noshadow
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input
        {
            float4 color:COLOR;
        };

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

        void surf (Input IN, inout SurfaceOutput o)
        {
        }
        float4 Lightingnolight(SurfaceOutput s, float3 lightDir, float atten) {
            return float4(0,0,0,0);
        }
        ENDCG

        // 2nd pass : 평범한 반투명이다. z버퍼를 쓰지 않는다. 이러면 이미 존재하는 z버퍼에 가려진 부분이 그려지지 않는다.
        zwrite off
        CGPROGRAM
        #pragma surface surf Lambert alpha:fade
        #pragma target 3.0

        sampler2D _MainTex;

        struct Input
        {
            float2 uv_MainTex;
        };

        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.Alpha = 0.5;
        }
        ENDCG
    }
    FallBack "Diffuse"
}