////////////////////////////////////////////////
//
// anti-aliasing
//
////////////////////////////////////////////////

lazyshader 0 "tqaaresolve" [
    in vec4 vvertex;
    @(screentexcoord 0)
    out vec2 texcoord0;
    out vec2 texcoord1;
    void main(void)
    {
        gl_Position = vvertex;
        texcoord0 = vtexcoord0; 
        texcoord1 = vtexcoord0 - 0.5;
    }
] [
    @(gfetchdefs tex2)
    uniform vec4 quincunx;
    uniform sampler2DRect tex0, tex1;
    uniform mat4 reprojectmatrix;
    uniform vec2 maxvelocity;
    uniform vec2 colorweight;
    in vec2 texcoord0;
    in vec2 texcoord1;
    layout(location = 0) out vec4 fragcolor;
    void main(void)
    {
        @(gdepthunpack depth [gfetch(tex2, texcoord0)] [
            vec4 prevtc = reprojectmatrix * vec4(depth*texcoord0, depth, 1.0);
        ] [
            vec4 prevtc = reprojectmatrix * vec4(texcoord0, depth, 1.0);
        ])

        vec2 vel = prevtc.xy/prevtc.w - texcoord0;
        float scale = clamp(maxvelocity.x*inversesqrt(dot(vel, vel) + 1e-6), 0.0, 1.0);

        float mask = 1.0 - textureRect(tex0, texcoord0 + quincunx.xy).a;
        vec4 color = textureRect(tex0, texcoord0 + mask*quincunx.xy); 
        vec4 prevcolor = textureRect(tex1, texcoord0 + mask*(quincunx.zw + vel*scale));

        vec4 l0 = textureGather(tex0, texcoord1, 1);
        vec4 l1 = textureGatherOffset(tex0, texcoord1, ivec2(1, 1), 1);
        float l2 = textureRectOffset(tex0, texcoord0, ivec2(1, -1)).g;
        float l3 = textureRectOffset(tex0, texcoord0, ivec2(-1, 1)).g;
        vec4 l01min = min(l0, l1), l01max = max(l0, l1);
        l01min.xy = min(l01min.xy, l01min.zw);
        l01max.xy = max(l01max.xy, l01max.zw);
        float lmin = min(min(l01min.x, l01min.y), min(l2, l3));
        float lmax = max(max(l01max.x, l01max.y), max(l2, l3));

        float weight = 0.5 - 0.5*clamp((colorweight.x*max(prevcolor.g - lmax, lmin - prevcolor.g) + colorweight.y) / (lmax - lmin + 1e-4), 0.0, 1.0);
        weight *= clamp(1.0 - 2.0*(prevcolor.a - color.a), 0.0, 1.0);
        fragcolor.rgb = mix(color.rgb, prevcolor.rgb, weight);
        fragcolor.a = color.a;
    }
]

smaaopt = [ >= (strstr $smaaopts $arg1) 0 ]
smaashaders = [
    smaapreset = $arg1   
    smaaopts = $arg2
    exec "config/glsl/smaa.cfg"
]

fxaaopt = [ >= (strstr $fxaaopts $arg1) 0 ]
fxaashaders = [
    fxaapreset = $arg1
    fxaaopts = $arg2
    exec "config/glsl/fxaa.cfg"
]

