#version 330

#define MAX_KERNEL_RADIUS 16
#define MAX_KERNEL_COEFFS 2*MAX_KERNEL_RADIUS + 1

// Input vertex attributes (from vertex shader)
in vec2 fragTexCoord;
in vec4 fragColor;

// Input uniform values
uniform sampler2D texture0;
uniform vec4 colDiffuse;

uniform vec2 textureSize;

uniform float coeffs[MAX_KERNEL_COEFFS];
uniform int kernelRadius;
uniform vec2 kernelDirection;

// Output fragment color
out vec4 finalColor;

void main()
{
    vec2 texel = 1.0 / textureSize;

    vec4 texelColor = vec4(0);
    float alphaCorrection = 0;

    for (int i = 0; i < 2*kernelRadius + 1; i++)
    {
        vec2 offset = kernelDirection * vec2(i - kernelRadius, i - kernelRadius) * texel;
        vec2 sampleCoord = fragTexCoord + offset;

        if ((0 <= sampleCoord.x && sampleCoord.x <= 1) && (0 <= sampleCoord.y && sampleCoord.y <= 1)) {
            vec4 sample = texture(texture0, sampleCoord);
            texelColor += sample * coeffs[i];
            alphaCorrection += sample.a * coeffs[i];
        }
    }

    texelColor /= alphaCorrection;

    finalColor = texelColor * colDiffuse * fragColor;
}
