
in vec2 uv;
in vec4 col;
uniform int font_tex;
in vec4 outline;
in vec4 bg_col;


layout(blend_support_all_equations) out;
layout (location = 0) out vec4 C;


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

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

float screenPxRange() {
    const float pxRange = 2.0; // set to distance field's pixel range
    vec2 unitRange = vec2(pxRange)/vec2(textureSize(textures[font_tex], 0));
    vec2 screenTexSize = vec2(1.0)/fwidth(uv);
    return max(0.5*dot(unitRange, screenTexSize), 1.0);
}

void main() {
//    vec4 albedo = texture(textures[font_tex], vec2(uv.x,1.-uv.y));
    vec4 albedo = texture(textures[font_tex], vec2(uv.x,uv.y));
    

    float sigDist = median(albedo.r, albedo.g, albedo.b);

    float screen_px_dist = screenPxRange() * (sigDist - 0.5);
    float opacity = clamp(screen_px_dist + 0.5, 0.0, 1.0);
    
//    opacity = smoothstep(-0.1,0.2,(sigDist));
    
    
    


//    float uStrokeInsetWidth = 0.5;
//    float uStrokeOutsetWidth = 0.5;
//
//    sigDist -= 0.5;
//
//    // Strokes
//    // Outset
//    float sigDistOutset = sigDist + uStrokeOutsetWidth * 0.5;
//
//    // Inset
//    float sigDistInset = sigDist - uStrokeInsetWidth * 0.5;
//
//    float rng = 0.5/screenPxRange();
//    float outset = clamp(sigDistOutset / rng + 0.5, 0.0, 1.0);
//    float inset = 1.0 - clamp(sigDistInset / rng + 0.5, 0.0, 1.0);
//
//    // Border
//    float border = outset * inset;
//
//
//    // Output: Strokes
//    vec4 strokedFragColor = vec4(0,0,0, border);


    //    float sigDistOutline = screen_px_dist;

//    float w = 0.5 * screenPxRange() ;
//    float _outline = smoothstep(w,1.5,(sigDistOutline) );
//    float _outline = smoothstep(0.1, 4.,median(albedo.r, albedo.g, albedo.b) );
//    float _outline = smoothstep(0.1, 4.,median(albedo.r, albedo.g, albedo.b) );
//    float _outline = screenPxRange() * (abs(sigDist - 0.5 ) - 0.1 ) - screenPxRange() * 0.;

//    _outline = clamp(_outline + 0., 0.0, 1.0);
//    float _outline = smoothstep(
////        screenPxRange(),
//        2.0,
//        0.0,
//        abs(sigDist - 0. )
//    );


//    float wi = fwidth(sigDist);
//    _outline = smoothstep(0.5 - wi, 0.5 + wi, abs(sigDist) - 0.);


    C = mix(bg_col, vec4(col.xyz,opacity*col.w), opacity*col.w);
    
//    C.w = 1.0;
//    C.xy = fract(uv.xy*9.4);
//    C.z = 1.;
//    if(strokedFragColor.a > 0.0001){
//        C = mix(C, strokedFragColor/vec4(1,1,1,strokedFragColor.a), strokedFragColor.a);
//    }

//    C.x += sin(albedo.w*1000.0);
//    C.xyz -= _outline;
}
