#version 150 core

uniform sampler2D texColors;
uniform sampler2D texDepth;
uniform mat4 matVP;
uniform mat4 prevMatVP;

in vec2 ex_texcoord;

out vec4 out_color;

void main(void)
{
    float zOverW = texture2D(texDepth, ex_texcoord).r;
    vec4 H = vec4(ex_texcoord.x * 2.0 - 1.0,
                  (1.0 - ex_texcoord.y) * 2.0 - 1.0,
                  zOverW, 1.0);
    vec4 D = H * inverse(matVP);
    vec4 worldPos = D / D.w;

    vec4 currentPos = H;
    vec4 previousPos = worldPos * prevMatVP;
    previousPos /= previousPos.w;
    vec2 velocity = (currentPos - previousPos).xy / 2.0;

    vec4 color = texture2D(texColors, ex_texcoord);
    vec2 texcoord = ex_texcoord + velocity;
    int numSamples = 5;
    for (int i = 1; i < numSamples; ++i, texcoord += velocity)
    {
        vec4 currentColor = texture2D(texColors, texcoord);
        color += currentColor;
    }
    vec4 finalColor = color / float(numSamples);
    out_color = finalColor;
}
