#version 330 core
in vec2 vTex;
out vec4 FragColor;

uniform vec3 iResolution;
uniform float iTime;
uniform sampler2D iChannel0;
uniform float uAlpha;
uniform int uUseChannel0;

void mainImage(out vec4 c, vec2 P) {
    // start fully transparent background
    c = vec4(0.0, 0.0, 0.0, 0.0);
    P = P / iResolution.xy * 4.0 - 2.0;

    float T = iTime;
    float a = P.y * sin(T) + T * 2.0 + sin(P.y + T);

    for (int n = 0; n < 4; n++) {
        float A = cos(a);
        float B = sin(a);

        if (P.x > A && P.x < -B) {
            vec2 uv = vec2((P.x - A)/(-B - A), P.y * 0.5 + 0.5);
            vec4 tex = texture(iChannel0, uv);
            float factor = - (B + A) * (uv.x < 0.02 ? 1.5 : 1.0);
            // avoid negative contribution and clamp
            factor = max(factor, 0.0);
            c = clamp(tex * factor, 0.0, 1.0);
        }

        a += 1.5707;
    }
}

void main() {
    vec2 fragCoord = vTex * iResolution.xy;
    vec4 col = vec4(0.0);
    mainImage(col, fragCoord);
    col.a *= uAlpha;
    FragColor = col;
}
