#version 450 core
// Purpose: Engine presentation fragment shader; applies compact FXAA while copying to the window.

in vec2 vUv;
layout(location = 0) out vec4 FragColor;

uniform sampler2D uTex;
uniform vec2 uInvTextureSize;

// Compact FXAA-style resolve for final presentation.
// This is intentionally a present-pass AA fallback after disabling implicit MSAA.
// It reduces high-contrast road/line shimmer without touching the render target path.
void main()
{
    vec3 rgbM  = texture(uTex, vUv).rgb;
    vec3 rgbNW = texture(uTex, vUv + vec2(-1.0, -1.0) * uInvTextureSize).rgb;
    vec3 rgbNE = texture(uTex, vUv + vec2( 1.0, -1.0) * uInvTextureSize).rgb;
    vec3 rgbSW = texture(uTex, vUv + vec2(-1.0,  1.0) * uInvTextureSize).rgb;
    vec3 rgbSE = texture(uTex, vUv + vec2( 1.0,  1.0) * uInvTextureSize).rgb;

    const vec3 lumaWeights = vec3(0.299, 0.587, 0.114);
    float lumaM  = dot(rgbM,  lumaWeights);
    float lumaNW = dot(rgbNW, lumaWeights);
    float lumaNE = dot(rgbNE, lumaWeights);
    float lumaSW = dot(rgbSW, lumaWeights);
    float lumaSE = dot(rgbSE, lumaWeights);

    float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
    float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));
    float contrast = lumaMax - lumaMin;

    // Avoid blurring already-flat regions.
    if (contrast < max(0.0312, lumaMax * 0.125)) {
        FragColor = vec4(rgbM, 1.0);
        return;
    }

    vec2 dir;
    dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));
    dir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));

    float dirReduce = max(
        (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * 0.125),
        1.0 / 128.0
    );

    float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);
    dir = clamp(dir * rcpDirMin, vec2(-8.0), vec2(8.0)) * uInvTextureSize;

    vec3 rgbA = 0.5 * (
        texture(uTex, vUv + dir * (1.0 / 3.0 - 0.5)).rgb +
        texture(uTex, vUv + dir * (2.0 / 3.0 - 0.5)).rgb
    );

    vec3 rgbB = rgbA * 0.5 + 0.25 * (
        texture(uTex, vUv + dir * -0.5).rgb +
        texture(uTex, vUv + dir *  0.5).rgb
    );

    float lumaB = dot(rgbB, lumaWeights);
    vec3 resolved = (lumaB < lumaMin || lumaB > lumaMax) ? rgbA : rgbB;

    FragColor = vec4(resolved, 1.0);
}