#version 430

in vec2 uv;

layout(location = 0) out vec4 frag;

uniform float g_time;

/*
float rand(vec2 co){
    return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
*/

uniform float flip=1.0;

uniform float overlayAlpha=1.0;


layout(binding=0) uniform sampler2D tex;
layout(binding=1) uniform sampler2D texPrev;

uniform float pixelSize = 1.0;
uniform float smoothEnabled = 0.0;

uniform float pixSizeVarAmp = 0.0;
uniform float pixSizeVarFreqX = 1.0;
uniform float pixSizeVarFreqY = 1.0;
uniform float pixSizeVarOfsX = 0.0;
uniform float pixSizeVarOfsY = 0.0;

void main() {

    vec2 uvS = uv;
    uvS.y = 1.0-uvS.y;

    ivec2 texSize = textureSize(tex, 0);

//    vec2 oo = vec2(pixSize, 1.5);

    vec2 ct = gl_FragCoord.xy-vec2(texSize)*0.5+smoothstep(0.0, 1.0, clamp((pixelSize-128.0)*1.25, 0.0, pixelSize)/pixelSize)*pixelSize*vec2(0.5, 0.5);

    ivec2 pk = ivec2(ct/pixelSize);

    // float pixSize = pixelSize*(1.0+0.1*(sin(uvS.x*12.0+g_time)+cos(uvS.y*0.0)));
    float pixSize = pixelSize*(1.0+pixSizeVarAmp*(sin(pk.x*pixSizeVarFreqX+pixSizeVarOfsX)+cos(pk.y*pixSizeVarFreqY+pixSizeVarOfsY)));



    if (ct.x >= 0.0) {
        ct.x += pixSize;
    }
    if (ct.y >= 0.0) {
        ct.y += pixSize;
    }
  //  vec4 screen = texelFetch(tex, ivec2(vec2(ivec2(ct/pixSize))*pixSize+vec2(texSize)*0.5), 0);
    vec2 tp = vec2(ivec2(ct/pixSize))*pixSize+vec2(texSize)*0.5-pixelSize*vec2(0.5, 0.5);
    vec2 tpo = ivec2(pixSize);

    vec2 to = vec2(-0.5, -0.5)*pixSize*1.0;

    vec4 screen;


    if (smoothEnabled < 0.5) {
        // pixelate
        screen = texture2D(tex, (vec2(ivec2(ct/pixSize))*pixSize+vec2(texSize)*0.5-pixelSize*vec2(0.5, 0.5))/vec2(texSize));
        //screen = texelFetch(tex, ivec2(vec2(ivec2(ct/pixSize))*pixSize+vec2(texSize)*0.5-pixSize*vec2(0.5, 0.5)), 0);
    } else {
        // bilinear
        vec2 ctf = smoothstep(0.0, 1.0, fract(ct/pixSize));
        //vec2 ctf = fract(ct/pixSize);
        vec4 sa = texture2D(tex, vec2(tp+to)/vec2(texSize));
        vec4 sb = texture2D(tex, vec2(tp+to+vec2(tpo.x, 0.0))/vec2(texSize));
        vec4 sc = texture2D(tex, vec2(tp+to+vec2(0.0, tpo.y))/vec2(texSize));
        vec4 sd = texture2D(tex, vec2(tp+to+vec2(tpo.x, tpo.y))/vec2(texSize));
        vec4 sab = mix(sa, sb, ctf.x);
        vec4 scd = mix(sc, sd, ctf.x);
        screen.rgb = mix(sab.rgb, scd.rgb, ctf.y);
    }

    screen.a = 1.0;
    frag = screen;
}

