// inspired by https://github.com/libgdx/libgdx/wiki/Distance-field-fonts and https://github.com/Chlumsky/msdfgen

#version 450 core

// inputs
in vec2 texCoord;

// outputs
layout (location = 0) out vec4 outColor;

// samplers
uniform sampler2D t_fontAtlas;

// uniforms
uniform float g_thickness;
uniform vec4 g_color;
uniform bool g_outline; 
uniform float g_outlineThickness;       // - = thick outline, 0.5 - no outline
uniform vec4 g_outlineColor;
uniform float g_smoothness;
uniform float g_pxRange; // set to distance field's pixel range

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

void main() {    
    /*
    float distance = texture2D(t_fontAtlas, texCoord).r;
    float alpha = smoothstep(0.5 - g_smoothness, 0.5 + g_smoothness, distance);
    outColor = vec4(g_color.rgb, g_color.a * alpha);
    */

    vec3 msd = texture(t_fontAtlas, texCoord).rgb;
    float distance = median(msd);

    //float distance = texture2D(t_fontAtlas, texCoord).r;
    float outlineFactor = smoothstep(0.5 - g_smoothness, 0.5 + g_smoothness, distance);
    vec4 color = mix(g_outlineColor, g_color, outlineFactor);
    float alpha = smoothstep(g_outlineThickness - g_smoothness, g_outlineThickness + g_smoothness, distance);
    outColor = vec4(color.rgb, color.a * alpha);
    
} 