#version 430

layout(binding=0) uniform sampler2D texScreen;
layout(binding=1) uniform sampler2D texOverlay;
layout(binding=2) uniform sampler2D texThr;
layout(binding=3) uniform sampler2D texPalette;

in vec2 uv;

layout(location = 0) out vec4 frag;
layout(location = 1) out vec4 frag2;

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

vec3 tonemapUC2(vec3 x) {
    float A = 0.15;
    float B = 0.50;
    float C = 0.10;
    float D = 0.20;
    float E = 0.02;
    float F = 0.30;
    return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;
}
*/


uniform float flip=1.0;

uniform float overlayAlpha=1.0;

uniform float g_posX = 0.0;
uniform float g_posY = 0.0;

uniform float g_overlayScale = 1.0;

uniform float g_scaleCX = 0.0;
uniform float g_scaleCY = 0.0;


uniform float g_scaleX=1.0;
uniform float g_scaleY=1.0;
uniform float g_rot=0.0;


uniform float g_thrWidth=0.1;
uniform float g_thrBias=0.0;
uniform float g_thrGain=0.0;
uniform float g_thrAmount=0.0;
uniform float g_thrAboveGain=0.0;
uniform float g_thrBelowGain=0.0;


vec2 rotateXY(vec2 p, float a) {
vec2 r = p;
r.x = cos(a)*p.x - sin(a)*p.y;
r.y = sin(a)*p.x + cos(a)*p.y;
return r;
}


uniform float g_paletteOn = 0.0;
uniform float g_paletteFade = 0.0;
uniform float g_paletteScale = 1.0;
uniform float g_paletteThrFade = 0.0;
void applyPalette(inout vec4 c, float thr) {
    if (g_paletteOn < 0.5) {
        return;
    }
    vec4 paletteColor = texture2D(texPalette, vec2(g_paletteFade+thr*g_paletteThrFade, 0.0)*g_paletteScale);
    c.rgb *= paletteColor.rgb;
}


void main() {

    vec2 uvS = uv;
    vec2 uvO = uv+vec2(g_posX, g_posY);
    if (flip > 0.5) {
        uvS.y = 1.0-uvS.y;
    }

    uvO -= vec2(g_scaleCX, g_scaleCY);
    uvO *= g_overlayScale;
    uvO.x *= g_scaleX;
    uvO.y *= g_scaleY;
    uvO.x *= 1.667;
    uvO = rotateXY(uvO, g_rot/360.0*2.0*3.141592);
    uvO.x /= 1.667;
    uvO += vec2(g_scaleCX, g_scaleCY);

    vec4 screen = texture2D(texScreen, uvS+vec2(0.0, 0.0));
    vec4 color = texture2D(texOverlay, uvO);

    vec4 colorThr = texture2D(texThr, uvO);
    float br = dot(colorThr.rgb, vec3(1.0));
    float kb = smoothstep(0.0, 1.0,1.0-(br-g_thrBias)*g_thrAboveGain/g_thrWidth);
    kb *= smoothstep(0.0, 1.0, 1.0+(br-g_thrBias)*g_thrBelowGain/g_thrWidth);
    kb *= g_thrGain;
    kb = clamp(kb, 0.0, 1.0);
    applyPalette(color, kb);
    color.rgb *= g_thrAmount*kb+(1.0-g_thrAmount);


    color = screen - color*overlayAlpha*color.a;
    color.a = 1.0;

    frag = color;
	frag2 = vec4(0.0, 0.0, 0.0, 0.0);	
}

