in vec2 uv;

out vec4 C;

uniform float u_t;
uniform int tex_typo;

#include scene_jyrevis25/common.glsl

float box(vec3 p){vec3 q=abs(p); return max(q.x,max(q.y,q.z));}

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;
}

void main() {
    vec2 UV=vec2(uv.x*R.x/R.y, uv.y);

    float t = u_t/BEAT_DUR;

    float timeKick = expease(fract(t/7.0)*7.0,2.0)+
                     expease(max(0.0,fract(t/7.0)*7.0-2.5),2.0)+
                     expease(max(0.0,fract(t/7.0)*7.0-4.0),2.0)+
                     expease(max(0.0,fract(t/7.0)*7.0-6.5),2.0);
    float deltaKick = (
        step(0.0,fract(t/7.0)*7.0)+
        step(2.5,fract(t/7.0)*7.0)+
        step(4.0,fract(t/7.0)*7.0)+
        step(6.5,fract(t/7.0)*7.0)
    )-timeKick;
    timeKick += floor(t/7.0)*4.0;

    vec3 col = c_beige;

    float progBoxRam = t/7.0/4.0 - 1.75; progBoxRam=clamp(progBoxRam*7.0*8.0,0.0,1.0); progBoxRam=expease(progBoxRam, 4.0);

    vec3 po = vec3(UV,1.0),
         rd = normalize(-po),
         ro = po;

    float td, ld;
    for(int i=0; i<99; i++){
        po = ro+rd*td;

        float progBar = t/7.0/4.0; progBar=min(1.0,progBar); progBar=sinease(progBar);

        float bump = deltaKick*step(1.0, t/7.0/4.0);
        ld = box(po*vec3(0.4/progBar,1.3-bump*0.2,1)-vec3(-1.5+progBar*1.5,0,-3.0+progBoxRam*0.25))-1.0;
        td += ld;
        if (ld<.00015) {
            col = c_blue;
            break;
        }
        if (td>999.) {
            break;
        }
    }

    float typoProg = t/7.0/4.0 - 1.0; typoProg=clamp(typoProg,0.0,1.0); typoProg=1.0-sinease(typoProg);
    float typoz = 2.0;
    for(int i=0; i<4; i++){
        vec2 off = vec2(float(i), 0.0);
        vec2 midpoint = vec2(1.5,0.0);

        const float charFillScreen = 1.0/16.0;
        vec3 typoPos = vec3(UV, typoz);
        
        float flyProg = t/7.0/4.0 - 1.75; flyProg -= 0.25/7.0; flyProg -= off.x*1.0/3.0/7.0;
        flyProg=clamp(flyProg*7.0*8.0,0.0,1.0); 
        flyProg=expease(flyProg, 8.0);
        float amt = (3.0-float(i))/4.0;

        if (i==3) {
            typoPos.xy *= mix(1.0, charFillScreen, flyProg);
        }
        
        typoPos.z = mix(typoPos.z, 0.0, flyProg-flyProg*amt);

        vec2 nuv = vec2(typoPos.xy)*length(vec2(length(vec2(typoPos.xy)),typoPos.z));
        bool samp = getText(nuv*vec2(1.5)/typoz-(off-midpoint)*(1.0-flyProg), off, vec2(1.0,1.0));
        if(samp && abs(nuv.x+typoProg*6.6)<typoz*2.0){
            col = c_yellow;
        }
    }

    C = vec4(col, 1.0);
}
