#extension GL_ARB_texture_rectangle : enable

uniform sampler2DRect u_texture;          // input texture at finer level ('fixed' flag at w-component)
uniform int u_isGradient;

void main() {
    vec2 coord = gl_TexCoord[0].xy;
    gl_FragColor = vec4(0);
    int cnt = 0;
    for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) {
        vec4 p = texture2DRect(u_texture, coord + vec2(-0.5 + i, -0.5 + j));
        if (p.w == 1.0) {
            gl_FragColor += p;
            ++cnt;
        }
    }
    if (0 < cnt) {
        gl_FragColor /= float(cnt);
        if (u_isGradient)
            gl_FragColor *= 2.0;  // to account for the change in the grid spacing
        gl_FragColor.w = 1.0;
    }
}
