#include "core.fsh"
#include "idioms.sh"

in vec2 UV_f;
layout(location = 0) out half3 fs_color;

uniform mediump sampler2D LitColorTexture;

const float2 _Dither2x2PositionMap[4] = float2[4](
    float2(0.0, 0.0),
    float2(1.0, 1.0),
    float2(0.0, 1.0),
    float2(1.0, 0.0)
 );

 const int2 _KawaseFilterOffsets[4] = int2[4](
    int2(-1, -1),
    int2(1, -1),
    int2(-1, 1),
    int2(1, 1)
 );

 half3 ApplyDitheringFilter(float2 uv, float4 texSizeParams) {

    float2 texPos = uv * texSizeParams.xy;
    int2 indexBits = int2(greaterThan(fract(texPos * 0.5), float2(0.25)));
    float2 offset = _Dither2x2PositionMap[indexBits.x + indexBits.y * 2];
    uv += offset * texSizeParams.zw;

    float2 tapU = uv.xx + float2(-1.5, 0.5) * texSizeParams.zz;
    float2 tapV = uv.yy + float2(-1.5, 0.5) * texSizeParams.ww;

    half3 result;
    result  = texture(LitColorTexture, float2(tapU.x, tapV.x)).rgb;
    result += texture(LitColorTexture, float2(tapU.y, tapV.x)).rgb;
    result += texture(LitColorTexture, float2(tapU.x, tapV.y)).rgb;
    result += texture(LitColorTexture, float2(tapU.y, tapV.y)).rgb;

    return result * inl_half(float3(0.25));
}

half4 ApplyKawaseFilter(sampler2D map, float2 uv) {
    half4 result = texture(map, uv);

    result += textureOffset(map, uv, _KawaseFilterOffsets[0]);
    result += textureOffset(map, uv, _KawaseFilterOffsets[1]);
    result += textureOffset(map, uv, _KawaseFilterOffsets[2]);
    result += textureOffset(map, uv, _KawaseFilterOffsets[3]);

    result *= inl_half(0.2);

    return result;
}

void main() {
#if 0
    fs_color = ApplyKawaseFilter(LitColorTexture, UV_f).rgb;
#else
    float2 texSize = float2(textureSize(LitColorTexture, 0));
    float4 texSizeParams = float4(texSize, rcp(texSize));
    fs_color = ApplyDitheringFilter(UV_f, texSizeParams);
#endif
}
