[[vertex]]

uniform mat4 mvp;

in vec4 pos;
in vec2 uvs;
out vec2 uv;

void main()
{
    gl_Position = mvp * vec4(pos.xy, 0.0, 1.0);
    uv = uvs;
}

[[fragment]]

uniform sampler2D tex_bg;

in highp vec2 uv;
out highp vec4 frag;

void main()
{
    highp vec4 bg = texture(tex_bg, uv);
    if (bg.a == 0.0)
    {
        highp ivec2 sz = textureSize(tex_bg, 0);
        highp ivec2 uv_raster = ivec2(uv * vec2(sz));
        highp vec4 sum = vec4(0.0);
        highp vec4 c;
        c = texelFetch(tex_bg, uv_raster + ivec2(-1, -1), 0); sum += vec4(c.rgb * c.a, c.a);
        c = texelFetch(tex_bg, uv_raster + ivec2(-1,  0), 0); sum += vec4(c.rgb * c.a, c.a);
        c = texelFetch(tex_bg, uv_raster + ivec2(-1,  1), 0); sum += vec4(c.rgb * c.a, c.a);

        c = texelFetch(tex_bg, uv_raster + ivec2( 0, -1), 0); sum += vec4(c.rgb * c.a, c.a);
        c = texelFetch(tex_bg, uv_raster + ivec2( 0,  1), 0); sum += vec4(c.rgb * c.a, c.a);

        c = texelFetch(tex_bg, uv_raster + ivec2( 1, -1), 0); sum += vec4(c.rgb * c.a, c.a);
        c = texelFetch(tex_bg, uv_raster + ivec2( 1,  0), 0); sum += vec4(c.rgb * c.a, c.a);
        c = texelFetch(tex_bg, uv_raster + ivec2( 1,  1), 0); sum += vec4(c.rgb * c.a, c.a);
        
        frag = sum.a > 0.0 ? vec4(sum.rgb / sum.a, 0.0) : bg;
    }
    else
    {
        frag = bg;
    }
}
