in vec2 uv;

out vec4 C;

uniform float u_t;
uniform int tex_typo;
uniform int tex_prev;
uniform float u_kickProg;
uniform float u_kickId;
uniform float u_subDist;
uniform float u_subId;

#include scene_jyrevis25/common.glsl

bool getText(vec2 p, vec2 ind, vec2 range) {
    if (abs(p.x)>range.x/2.0 || abs(p.y)>range.y/2.0) return false;
    return 0.5<texture(textures[tex_typo], (p+ind+4.0+vec2(0.5)*(fract(range/2.0)*2.0))/8.0).r;
}

float bell(float x) {
    return abs(x)>PI?0.0:cos(x)*0.5+0.5;
}

void main() {
    vec2 UV=vec2(uv.x*R.x/R.y, uv.y);
    vec4 prevFrame = texture(textures[tex_prev], uv/2.0+0.5);

    vec3 col = c_yellow;

    float musicT = u_t/BEAT_DUR;

    float totalProg = (musicT/7.0/4.0 - 14.0)*1.2/2.0;
    float segPauseStart = musicT/7.0/4.0 - 14.0 - 6.0/7.0;
    float segPauseEnd = musicT/7.0/4.0 - 15.0 - 0.0/7.0;
    float segEnd = musicT/7.0/4.0 - 15.0 - 5.0/7.0;

    float droneT = musicT*0.8 + u_kickId;
    droneT -= (musicT-segPauseStart)*step(0.0,segPauseStart)*step(segPauseEnd,0.0)*0.9;
    float swing = 0.4+(1.0-expease(u_kickProg,0.5))*0.4;
    float speed = 2.0;
    float angle = mix(3.0, 1.5, expease(u_subDist, 4.0));

    vec2 p = UV*(1.0+length(UV)+pow(UV.y+1.0, 2.0)*angle);
    p *= rot(sin(droneT)*swing) * mix(1.0, 0.5, expease(u_subDist, 8.0));
    p += vec2(sin(droneT)*swing*3.0,droneT*speed);
    bool text = getText(fract(p/8.0)*8.0-4.0, vec2(0), vec2(8));
    float nois = step(-totalProg*2.0+1.0,noise(vec3(floor(p)*3.0,droneT)).x);
    if( noise(vec3(floor(p)*2.0,0.0)).x < mix(-1.0,1.0,pow(clamp(segEnd,-1.0,0.0)+1.0,3.0)) ) {
        text = false;
    }
    col = text?mix(c_blue,c_beige,nois):mix(c_yellow,c_red,nois);

    col = mix(col, c_beige, 
        step(1.0, -UV.y+bell((UV.x+
            mix(0.2,0.5,fract(u_subId*79.9))+expease(u_kickProg,10.0)
        )*6.0)*expease(u_subDist, 12.0))
    );

    float brightness = col.r*0.3+col.g*0.1+col.b*0.5;
    col = mix(prevFrame.rgb, col, 
        step(-0.3-brightness, noise(vec3(UV*999.99,u_t*29.99)).x));

    C = vec4(col, 1.0);
}
