#version 430

layout(binding=0) uniform sampler2D texBg;
layout(binding=1) uniform sampler2D texScr;
layout(binding=2) uniform sampler2D texDepth;

in vec2 uv;

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

uniform float g_time;
uniform float windowWidth = 1280.0;
uniform float windowHeight = 720.0;

/*
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;

float zn = 0.0;
float zf = 1.0;
uniform mat4 projectionMatrix;
uniform mat4 projectionInvMatrix;

uniform float fogStartZ = 1.0;
uniform float fogEndZ = 300.0;
uniform float fogBgMulZ = 50.0;


vec4 CalcEyeFromWindow(in vec3 windowSpace) {
    vec3 ndcPos;
    vec4 viewport = vec4(0.0, 0.0, windowWidth, windowHeight);
    ndcPos.xy = ((2.0 * windowSpace.xy) - (2.0 * viewport.xy)) / (viewport.zw) - 1;
    ndcPos.z = (2.0 * windowSpace.z - zn - zf) / (zf - zn);
    vec4 clipPos;
    clipPos.w = projectionMatrix[3][2]/(ndcPos.z-(projectionMatrix[2][2]/projectionMatrix[2][3]));
    clipPos.xyz = ndcPos * clipPos.w;
    return projectionInvMatrix * clipPos;
}

void main() {

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


    float dep = texelFetch(texDepth, ivec2(gl_FragCoord.xy), 0).r;
    vec4 colBg = texelFetch(texBg, ivec2(gl_FragCoord.xy), 0); //texture2D(texBg, uvS);
    vec4 colScr = texelFetch(texScr, ivec2(gl_FragCoord.xy), 0);//texture2D(texScr, uvS);

    float bgBright = dot(vec3(0.299, 0.587, 0.114), colBg.rgb); // regular luminance calc...

    vec4 pos3D = CalcEyeFromWindow(vec3(gl_FragCoord.xy, dep));

    float foggyness; //  = smoothstep(0.0, fogEndZ-fogStartZ, pos3D.z+bgBright*fogBgMulZ-fogStartZ);

    foggyness = clamp((-pos3D.z+bgBright*fogBgMulZ-fogStartZ)/(fogEndZ-fogStartZ), 0.0, 1.0);
    vec4 screen = (1.0-foggyness)*colScr+foggyness*colBg;
//    screen = colScr+vec4(foggyness);
    screen.a = 1.0;

    frag = screen;
}

