#version 450

layout(location = 1) in vec2 texCoord;

layout(location = 0) out vec4 outColor;

layout(set = 2, binding = 0) uniform sampler2D texSampler;

layout(set = 3, binding = 0) uniform TextConfig
{
    vec4 textColor;
    vec4 borderColor;
    vec4 backgroundColor;
    float threshold;
	float borderSize;
	float smoothing;
	bool applyBorder;
} textConfig;

float median(float r, float g, float b) {
    return max(min(r, g), min(max(r, g), b));
}

// this parameter should be same as FontAtlasGeneratorConfig::pixelRange
const float pxRange = 3;

float screenPxRange() {
    vec2 unitRange = vec2(pxRange)/vec2(textureSize(texSampler, 0));
    vec2 screenTexSize = vec2(1.0)/fwidth(texCoord);
    return max(0.5*dot(unitRange, screenTexSize), 1.0);
}

void main()
{
    vec3 msd = texture(texSampler, texCoord).rgb;
    float sd = median(msd.r, msd.g, msd.b);
    float screenPxDistance = screenPxRange()*(sd - 0.5);
    float opacity = clamp(screenPxDistance + 0.5, 0.0, 1.0);
    if (textConfig.backgroundColor.a != 0)
    {
       outColor = mix(textConfig.backgroundColor, textConfig.textColor, opacity);
    }
    else
    {
       outColor = vec4(vec3(textConfig.textColor), opacity);
    }
}
