in vec2 uv;

out vec4 C;

const float SPLIT_GATE = 0.6;

uniform float u_t;
uniform int tex_typo;

#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 freckle(vec2 p, float t, float amp) {
    vec2 q = p*mat2(1.0,0.8,0.0,1.25);

    vec2 i_p = floor(p*8.0),
         f_q = fract(q*8.0);

    float wave = clamp(pow(1.0-abs(p.y+sin(p.x-t*4.0)*0.3+0.2), 1.4),0.0,1.0);
    
    return step(length(f_q*mat2(1.0,-0.8,0.0,0.8)-0.3), wave*amp*0.37);
}

float truchet(vec2 p, float percA, float percB) {
    float musicT = u_t/BEAT_DUR;
    float segStart = musicT/7.0/4.0 - 9.0;

    return step(min(
        abs(length(p-1.0)-1.0)+max(0.0,atan(p.y-1.0,p.x-1.0)-percA*PI*0.6+PI +0.3), 
        abs(length(p+1.0)-1.0)+max(0.0,atan(p.y+1.0,p.x+1.0)-percB*PI*0.6    +0.3)
    ), 0.3+(1.0-expease(segStart,16.0))*1.4);
}

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

    vec3 col = c_beige;

    float musicT = u_t/BEAT_DUR;

    float segStart = musicT/7.0/4.0 - 9.0;
    float segGateStart = musicT/7.0/4.0 - 9.0 - 5.25/7.0;

    float timeKick = expease(fract(musicT/7.0)*7.0,2.0)+
                     expease(max(0.0,fract(musicT/7.0)*7.0-4.25),2.0)+
                     expease(max(0.0,fract(musicT/7.0)*7.0-6.0),2.0);
    float deltaKick = (
        step(0.0,fract(musicT/7.0)*7.0)+
        step(4.25,fract(musicT/7.0)*7.0)+
        step(6.0,fract(musicT/7.0)*7.0)
    )-timeKick;
    timeKick += floor(musicT/7.0)*3.0;

    float timeSnare = expease(max(0.0,fract(musicT/7.0)*7.0-3.0),4.0);
    float deltaSnare = step(3.0,fract(musicT/7.0)*7.0)-timeSnare;
    timeSnare += floor(musicT/7.0)*1.0;

    float timeKnock;
    for(float i=0.25; i<6.0; i+=1.25){ timeKnock += expease(max(0.0,fract(musicT/7.0)*7.0-i),8.0); }
    float deltaKnock;
    for(float i=0.25; i<6.0; i+=1.25){ deltaKnock += step(i,fract(musicT/7.0)*7.0); }
    deltaKnock -= timeKnock;
    timeKnock += floor(musicT/7.0)*5.0;
    
    vec2 p = UV*mix(2.0, 18.0, clamp(pow((musicT/7.0/4.0 - 9.0)*1.3,5.0),0.0,1.0));
    vec2 off = vec2(0,timeSnare*1.2+u_t);
    vec2 i_uv = floor(p + off),
         f_uv = fract(p + off)*2.0-1.0;
    seed = uint(67461.+i_uv.y*462.312+i_uv.x*95.2);

    vec2 percs = vec2(cos(timeKick*PI)*0.5+0.5, cos(timeKick*PI+PI)*0.5+0.5);

    if(segGateStart>0.0) {
        if(!getText(floor(p + fract(off))/36.0,vec2(1,timeKnock),vec2(3,1))) {
            percs*=0.0;
        }
    }

    float tru = truchet(f_uv*rot(round(hash_f())*PI), percs.x, percs.y);

    vec3 bg = mix(c_beige, c_yellow, tru);
    vec3 fr = mix(c_pink, c_red, tru);

    // camera shake
    UV += sin(u_t*99.9)*pow(deltaKick,3.0)*0.05;

    col = mix(bg, fr, freckle(UV, timeSnare+u_t*0.3, mix(0.4,1.0,deltaKick)*expease(segStart,8.0)));
    
    C = vec4(col, 1.0);
}
