[[vertex]]

uniform mat4 mvp;

in vec4 pos;
in vec2 uvs;
out vec2 uv;

void main()
{
    uv = uvs;
    gl_Position = mvp * vec4(pos.xyz, 1.0);
}

[[fragment]]

#include "include/blur.glsl"
#include "include/blend.glsl"
#include "include/blend-stroke.glsl"
#include "include/color.glsl"

uniform sampler2D tex;
uniform sampler2D tex_stroke;
uniform sampler2D tex_mask;
uniform highp float alpha;
uniform int blend_mode;
uniform highp vec2 resolution;
uniform bool lock;
uniform bool mask;
uniform bool use_fragcoord;

uniform bool use_dual;
uniform sampler2D tex_dual;
uniform highp float dual_alpha;
uniform int dual_blend_mode;

uniform bool use_pattern;
uniform sampler2D tex_pattern;
uniform highp vec2 pattern_scale;
uniform highp float pattern_bright;
uniform highp float pattern_contr;
uniform highp float pattern_depth;
uniform highp vec2 pattern_offset;
uniform bool pattern_invert;
uniform int patt_blend_mode;

in highp vec2 uv;
out highp vec4 frag;

void main()
{
    highp vec2 uv_base = use_fragcoord ? (gl_FragCoord.st / resolution) : uv;
    highp vec4 base = texture(tex, uv_base);
    highp vec4 stroke = texture(tex_stroke, uv);

    if (base.a == 0.0)
        base.rgb = stroke.rgb;
    
    // if (stroke.a == 0.0)
    // {
    //     frag = base * vec4(1.0, 1.0, 1.0, alpha);
    //     return;
    // }

    if (use_pattern)
    {
        highp vec2 rscale = resolution / vec2(512.0);
        highp float patt = texture(tex_pattern, uv * (1.0 / pattern_scale) * rscale + pattern_offset).r;
        if (pattern_invert)
            patt = 1.0 - patt;
        if (pattern_bright != 0.5)
            patt = brightness1(patt, 1.0 - pattern_bright);
        if (pattern_contr != 0.5)
            patt = contrast1(patt, pattern_contr);
        stroke.a = clamp(blend_stroke(stroke.a, patt, pattern_depth, patt_blend_mode), 0.0, 1.0);
    }

    if (use_dual)
    {
        highp vec4 dual = texture(tex_dual, uv);
        stroke.a = clamp(blend_stroke(stroke.a, dual.a, dual_alpha, dual_blend_mode), 0.0, 1.0);
    }

    // Don't use blur to sample the mask
    // it breaks blend_mode value MacBook with Intel HD Graphics 6000
    if (mask)
        stroke.a = stroke.a * texture(tex_mask, uv).r;
    
    if (!lock && base.a == 0.0)
    {
        frag = stroke * vec4(1.0, 1.0, 1.0, alpha);
        return;
    }

    highp vec4 blended = blend(base, stroke, blend_mode);
    frag = vec4(blended.rgb, (lock ? base.a : blended.a) * alpha);
}
