Shader "Custom/DitherShader" {
    Properties{
        _MainTex("Texture", 2D) = "white" {}
        _DitherMap3D("Dither Map 3D", 3D) = "" {}
        _DitherPalette("Dither Palette", 2D) = "" {}
    }

        SubShader{
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            sampler3D _DitherMap3D;
            sampler2D _DitherPalette;
            float4 _DitherPalette_TexelSize;

            v2f vert(appdata v) {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            fixed4 frag(v2f i) : SV_Target {
                // Sample the source texture
                float3 sourcePixelColor = tex2D(_MainTex, i.uv).rgb;

                // Calculate the coordinates in the dither map 3D texture
                float3 dithermapUV = float3(
                    sourcePixelColor.r,
                    1 - sourcePixelColor.g, // Y-Axis flipped
                    sourcePixelColor.b
                );

                // Sample the dither map 3D texture
                float3 ditherMapSample = tex3D(_DitherMap3D, dithermapUV).rgb * 255;

                // Calculate the screen-space coordinates
                float2 screenCoords = i.uv * _ScreenParams.xy;

                // Calculate the dithered palette coordinates
                float2 paletteUV = float2(
                    (ditherMapSample.r * 8 + fmod(screenCoords.x, 8)) * _DitherPalette_TexelSize.x,
                    1 - ((ditherMapSample.g * 8 + fmod(screenCoords.y, 8)) * _DitherPalette_TexelSize.y) // Y-Axis flipped
                );

                // Sample the dithered palette texture
                fixed4 col = tex2D(_DitherPalette, paletteUV);

                return col;
            }
            ENDCG
        }
    }
}