
uniform sampler2D g_color;
uniform sampler2D g_position;
uniform float time;
uniform mat4 view_matrix_inv;
uniform ivec4 focused_area;

layout (location = 0) out vec4 frag_color;

float rect_distance(vec2 point, vec2 top_left, vec2 bottom_right) {
    vec2 d = max(top_left - point, point - bottom_right);
    return length(
        max(vec2(0.0), d))
        + max(0.0, max(d.x, d.y)
    );
}

void main() {
    vec2 size = textureSize(g_color, 0).xy;
    vec3 col = texelFetch(g_color, ivec2(gl_FragCoord.xy), 0).rgb;
    vec3 pos = (view_matrix_inv * vec4(texelFetch(g_position, ivec2(gl_FragCoord.xy), 0).rgb, 1.0)).xyz;

    float dist = rect_distance(pos.xz, vec2(focused_area.xy), vec2(focused_area.zw) + vec2(1.0));
    float dc = clamp(1.0 - dist * (0.4 + abs(sin(time * 0.004)) * 0.1) , 0.0, 1.0);

    vec3 gray = vec3(dot(col, vec3(0.299, 0.587, 0.114))) * 0.6;

    frag_color = vec4(col * dc + gray * (1.0 - dc), 1.0);
}
