Shader "Custom/FlipnoteShader"
{
    Properties{
        _DisplacementAmount("Displacement Amount", Range(0, 0.01)) = 0.0001
    }
        SubShader{
            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 _DitherTex;
                sampler2D _EdgeTex;
                float _DisplacementAmount;

                // Courtesy of https://stackoverflow.com/questions/12964279/whats-the-origin-of-this-glsl-rand-one-liner
                float rand(float2 co)
                {
                    return frac(sin(dot(co.xy ,float2(12.9898,78.233))) * 43758.5453);
                }

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

                fixed4 frag(v2f i) : SV_Target{
                    // Add some displacement to the UV coordinates for the edge texture based on noise
                    float2 displacedUV = i.uv;
                    float noiseX = rand(i.uv * 10.0) - 0.5;
                    float noiseY = rand(i.uv * 10.0 + 1.0) - 0.5;
                    // Apply a quartic function to the noise to make it disperse slower when the property is changed
                    noiseX = noiseX * abs(noiseX) * abs(noiseX) * abs(noiseX);
                    noiseY = noiseY * abs(noiseY) * abs(noiseY) * abs(noiseY);
                    displacedUV.x += noiseX * _DisplacementAmount;
                    displacedUV.y += noiseY * _DisplacementAmount;

                    // Sample both textures
                    fixed4 ditherColor = tex2D(_DitherTex, i.uv);
                    fixed4 edgeColor = tex2D(_EdgeTex, displacedUV);

                    // If the edge color is transparent, use the dither color. Otherwise, use the edge color.
                    if (edgeColor.a == 0) {
                        return ditherColor;
                    }
                    else {
                        return edgeColor;
                    }
                }
                ENDCG
            }
    }
}
