//
// Outline edges
//

#version 330

uniform sampler2DRect inputTex;
uniform sampler2DRect maskTex;
uniform float outlineAmount;
uniform float colorLevel;
uniform float uBlendValue=1.0;
in vec2 fsTexture;
in vec2 fsMaskTexture;

out vec4 outColor;

float coeffs_fx[9] = float[](-1.0, 0.0, 1.0,-2.0, 0.0, 2.0,-1.0, 0.0, 1.0);

uniform float coeffs_fy[9] = float[9](+1.0f, +2.0f, +1.0f,
                                      +0.0f, +0.0f, +0.0f,
                                      -1.0f, -2.0f, -1.0f);

uniform vec2 offset[9] = vec2[9](vec2(-1.0f, +1.0f), vec2(+0.0f, +1.0f), vec2(+1.0f, +1.0f),
                                 vec2(-1.0f, +0.0f), vec2(+0.0f, +0.0f), vec2(+1.0f, +0.0f),
                                 vec2(-1.0f, -1.0f), vec2(+0.0f, -1.0f), vec2(+1.0f, -1.0f));

void main(void)
{
    vec2 pos;
    float theta;
    float y = 0.0f, gx = 0.0f, gy = 0.0f;
    vec2 current = fsTexture;
    for (int i = 0; i < offset.length(); i++)
    {
        pos.x = current.x+offset[i].x;
        pos.y = current.y+offset[i].y;
        vec4 color = texture(inputTex, pos);
        y=dot(color.rgb, vec3(0.299, 0.587, 0.114));
        gx += (y*coeffs_fx[i]);
        gy += (y*coeffs_fy[i]);
    }
    y = sqrt((gx*gx)+(gy*gy))*outlineAmount;
    

    vec4 texel=texture(inputTex,fsTexture);
    outColor = texel*vec4(colorLevel,colorLevel,colorLevel,1.);

    outColor.r+=y;
    outColor.r=min(255.,outColor.r);
    outColor.g+=y;
    outColor.g=min(255.,outColor.g);
    outColor.b+=y;
    outColor.b=min(255.,outColor.b);
    float blendValue=uBlendValue;
#ifdef USE_MASK
    blendValue*=texture(maskTex,fsMaskTexture).a;
#endif
    outColor.rgb=mix(texel.rgb,outColor.rgb,blendValue);
}


