#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);
}


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

layout(binding=3) uniform sampler2D texAlpha;

uniform float g_currentAmount = 1.0;
uniform float g_prevAmount = 1.0;

uniform float g_darkenAmp = 0.0;
uniform float g_darkenPow = 1.0;

void main() {
    vec4 screen = texelFetch(tex, ivec2(gl_FragCoord.xy), 0);
    vec4 screenAlpha = texelFetch(texAlpha, ivec2(gl_FragCoord.xy), 0);
    vec4 prev = texelFetch(texPrev, ivec2(gl_FragCoord.xy), 0);
    vec4 bg = texelFetch(texBg, ivec2(gl_FragCoord.xy), 0);

    screen.rgb *= screen.rgb;
//    screenAlpha.rgb *= screenAlpha.rgb;
    prev.rgb *= prev.rgb;
    bg.rgb *= bg.rgb;

    float alp = 1.0; // screenAlpha.a;
    screen.rgb = alp*screen.rgb*g_currentAmount+(1.0-alp)*bg.rgb;

    prev.rgb *= g_prevAmount;
    float colorAlpha = dot(vec3(1.0), prev.rgb);
    float darken = g_darkenAmp*pow(colorAlpha, abs(g_darkenPow)+0.01);
    screen.rgb = clamp(screen.rgb*(1.0-darken)+vec3(0.0)*darken, 0.0, 10.0);


    screen.rgb += prev.rgb;
    screen.rgb = pow(screen.rgb, vec3(0.5));

    frag = screen;
}
