#version 330 core

// inputz
in vec2 UV;

uniform vec2 iResolution;
uniform float iTime;
uniform sampler2D iChannel0;


// outputz
out vec4 fragColor;

const float W = 4.0;
const float T = 0.05;
float filmic_reinhard_curve (float x) {
    float q = (T + 1.0)*x*x;    
    return q / (q + x + T);
}

vec3 filmic_reinhard(vec3 x) {
    float w = filmic_reinhard_curve(W);
    return vec3(
        filmic_reinhard_curve(x.r),
        filmic_reinhard_curve(x.g),
        filmic_reinhard_curve(x.b)) / w;
}

void main()
{
    vec2 uv = UV;
    vec4 data = texture( iChannel0, uv );
    //fragColor.rgb = data.rgb;
    //return;
    vec3 col = vec3(0.0);
    // decompress velocity vector
    float ss = mod(data.w,256.0)/255.0;
    float st = floor(data.w/256.0)/255.0;

    // motion blur (linear blur across velocity vectors
    vec2 dir = (-1.0 + 2.0*vec2( ss, st ))*0.15;
    col = vec3(0.0);
    for( int i=0; i<32; i++ )
    {
        float h = float(i)/31.0;
        vec2 pos = uv + dir*h*0.8;
        col += texture( iChannel0, pos ).xyz;
    }
    
    col /= 32.0;
    
    // vignette
    float rf = sqrt(dot(uv, uv)) * 0.3;
    float rf2_1 = rf * rf + 1.0;
    col *= 1.0 / (rf2_1 * rf2_1);
    // tonemap
    col = filmic_reinhard(col);
    col = smoothstep(-0.1, 1.1, col);
    
    fragColor.rgb = pow(col, vec3(0.4545));
    fragColor.a = 1.0;
    //fragColor.rgb = mix(col, (6.0*vec3(dir,0)), iMouse.y/iResolution.y);
}
