Shader "UdonChipsHat/DistanceFadeAdditive"
{
    Properties
    {
        _Color("Color", Color) = (1,1,1,1)
        _FadeStart("Fade Start Distance", Float) = 0
        _FadeEnd("Fade End Distance", Float) = 10
    }

    SubShader
    {
        Tags
        {
            "Queue" = "Transparent"
            "RenderType" = "Transparent"
            "IgnoreProjector" = "True"
        }

        Blend One One
        Cull Off
        Lighting Off
        ZWrite Off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
                float3 worldPos : TEXCOORD0;
            };

            fixed4 _Color;
            float _FadeStart;
            float _FadeEnd;

            // 4x4 Bayer dither matrix — thresholds offset by +0.5 so they
            // range (0.5 .. 15.5)/16, never hitting exactly 0.
            // clip() only discards on strictly-negative, so a zero threshold
            // would leave 1-in-16 pixels visible forever.
            static const float bayer[16] =
            {
                 0.5/16.0,  8.5/16.0,  2.5/16.0, 10.5/16.0,
                12.5/16.0,  4.5/16.0, 14.5/16.0,  6.5/16.0,
                 3.5/16.0, 11.5/16.0,  1.5/16.0,  9.5/16.0,
                15.5/16.0,  7.5/16.0, 13.5/16.0,  5.5/16.0
            };

            v2f vert(appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                // Distance from camera to fragment in world space
                float dist = distance(_WorldSpaceCameraPos, i.worldPos);

                // Fade factor: 1 = fully visible (near), 0 = fully gone (far)
                float fade = 1.0 - smoothstep(_FadeStart, _FadeEnd, dist);

                // Screen-space Bayer dither threshold
                int2 screenCoord = int2(i.pos.xy) % 4;
                int bayerIndex = screenCoord.y * 4 + screenCoord.x;
                float threshold = bayer[bayerIndex];

                // Discard pixels where the dither threshold exceeds the fade factor
                clip(fade - threshold);

                return _Color;
            }
            ENDCG
        }
    }
}