this logo: 245 b

← INFALL v1

index.html

<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>INFALL</title>
<meta name=viewport content="width=device-width,initial-scale=1">
<style>html,body{margin:0;height:100%;background:#000;overflow:hidden}canvas{display:block;width:100vw;height:100vh;cursor:pointer}</style>
</head>
<body>
<canvas id=c></canvas>
<script>
/* INFALL - two minutes falling into a black hole.
   Every pixel is a light ray integrated backwards through Schwarzschild space: the bending, the
   photon ring, the far side of the disk folded over the top, Doppler beaming and redshift all fall
   out of the same loop. The soundtrack is synthesised in real time; its tempo climbs all the way
   down, collapses at the horizon, and its FFT drives the disk. No assets, no dependencies.
   Keys: F fullscreen. Drop an audio file to use your own music. */
(()=>{
'use strict';

/* ---------------- tempo map (shared by the synth and the camera) ---------------- */
// start time in seconds of every 16th note: the tempo climbs for 40 bars, collapses at the horizon, and keeps slowing
function TMAP(){
const P=[0,70,8,84,16,110,24,140,40,178,44,58,50,40],t=new Float64Array(801);let a=0;
for(let i=0;i<800;i++){t[i]=a;const x=i/16;let j=0;while(x>=P[j+2])j+=2;a+=15/(P[j+1]+(P[j+3]-P[j+1])*(x-P[j])/(P[j+2]-P[j]))}
t[800]=a;for(let i=0;i<=800;i++)t[i]*=120/a;return t}

/* ---------------- synth (runs inside an AudioWorklet) ---------------- */
function SYN(sr,tm){
const TAU=6.283185307179586,T=1/sr,mf=n=>440*2**((n-69)/12),dc=s=>Math.exp(-1/(sr*s)),G=f=>Math.tan(Math.PI*Math.min(f,sr*.45)*T);
let rs=22222;const rnd=()=>{rs^=rs<<13;rs^=rs>>>17;rs^=rs<<5;return(rs>>>0)/2147483648-1};
// TPT state variable filter (g = tan(pi fc/sr)): returns low-pass, leaves band-pass in s[2]
const svf=(s,x,g,k)=>{const h=1/(1+g*(g+k)),v3=x-s[1],v1=h*s[0]+g*h*v3,v2=s[1]+g*h*s[0]+g*g*h*v3;s[0]=2*v1-s[0];s[1]=2*v2-s[1];s[2]=v1;return v2};
const saw=(p,d)=>{let v=2*p-1;if(p<d){const t=p/d;v-=t+t-t*t-1}else if(p>1-d){const t=(p-1)/d;v-=t*t+t+t+1}return v};
const X=(a,b,p)=>a*(b/a)**p;
// D minor, two bars each of Dm, Bbm, G#dim, A. OS: the low string ostinato, SC: the violin cluster, BP: bass filter pulse
const RT=[0,-4,-6,-5],CH=[[50,53,57],[46,49,53],[44,47,50],[45,49,52]],OS=[38,0,38,38,45,38,38,44,38,0,38,38,41,38,39,37],SC=[86,87,92,93],BP='x..x..x.x..x..x.';
let pos=0,nx=0,ls=0,st=-1,gp=1,
 kt=-1,kp=0,kl=0,kd=5,kf=46,kb=130,kc=400,bo=-1,bop=0,
 d1=0,d2=.3,d3=.6,dl=0,dl2=0,dk=.02,dlv=0,dlt=0,
 b1=0,b2=.3,b3=.7,bf=36,bt=36,be=0,bl=0,blv=0,bcut=200,bg=.01,
 o1=0,o2=.5,of=73,oe=0,oa=0,ocut=300,og=.01,olv=0,oo=.2,
 pl=0,pr=0,pl2=0,pr2=0,pc=.01,pct=.01,plv=0,plt=0,
 sa=0,sk=.001,sg=1,se=0,sj=0,
 sx=0,shl=0,sht=0,
 he=0,hd=.99,hl=0,ce=-1,clv=0,cre=0,crl=0,ris=0,ri=0,rg=.01,
 di=0,dlp=0,drp=0;
const F=n=>new Float64Array(n),bs=F(3),os=F(3),cs=F(3),rz=F(3),z1=F(3),z2=F(3),
 pph=F(6).map(()=>rnd()*.5+.5),pfr=F(6),sph=F(4),sf=F(4).fill(1e3),shp=F(7),shf=F(7),shw=F(7);
const bdc=dc(.12),odc=dc(.06),crd=dc(.7),hdo=dc(.07),hdc=dc(.015),cg=G(1700),z1g=G(2300),z2g=G(4100);
// stereo ping-pong delay and a long Freeverb-style reverb
const DN=Math.round(sr*.31),dL=new Float32Array(DN),dR=new Float32Array(DN);
const mk=(a,o)=>a.map(n=>new Float32Array(Math.round((n+o)*sr/44100)));
const cl=[1116,1188,1277,1356,1422,1491,1557,1617],al=[556,441,341,225];
const cL=mk(cl,0),cR=mk(cl,23),aL=mk(al,0),aR=mk(al,23),ci=new Int32Array(16),ai=new Int32Array(8),cf=F(16);
const verb=(x,C,A,o)=>{let y=0;
 for(let j=0;j<8;j++){const b=C[j],q=o*8+j,i=ci[q],v=b[i];cf[q]=v*.75+cf[q]*.25;b[i]=x+cf[q]*.9;ci[q]=i+1==b.length?0:i+1;y+=v}
 for(let j=0;j<4;j++){const b=A[j],q=o*4+j,i=ai[q],v=b[i];b[i]=y+v*.5;ai[q]=i+1==b.length?0:i+1;y=v-y}
 return y};
const scr=(sh,gl)=>{for(let j=0;j<4;j++)sf[j]=mf(SC[j]+sh);sg=2**(gl/12*T)};   // violins: cluster shifted by sh, sliding gl semitones a second
const kick=(l,f,b,c,d)=>{kt=0;kp=0;kl=l;kf=f;kb=b;kc=c;kd=d};
const trig=()=>{
 // sections: 0 void, 1 pulse, 2 build, 3 drop (16 bars), 4 the horizon (everything winds down an octave), 5 inside
 const s=st&15,bar=st>>4,k=bar<8?0:bar<16?1:bar<24?2:bar<40?3:bar<44?4:5,
  sp=((bar-[0,8,16,24,40,44][k])*16+s)/([8,8,8,16,4,6][k]*16),c=k?(bar>>1)&3:0,root=RT[c],w=.5-.5*Math.cos(TAU*(s+.5)/16);
 gp=k==4?.5**sp:k==5?.5:1;
 for(let j=0;j<6;j++)pfr[j]=mf(CH[c][j>>1])*(j&1?1.004:.996);
 pct=1-Math.exp(-TAU*[X(150,500,sp),X(500,900,sp),X(900,2600,sp),X(2600,3400,sp),X(3400,300,sp),X(300,180,sp)][k]*T);
 plt=[.9*Math.min(1,sp*4),.8,.8,.55,.7,.8*Math.min(1,(1-sp)*5)][k];
 dlt=[Math.min(1,sp*8),.8,.6,.3,.7,Math.min(1,(1-sp)*5)][k];
 // a heartbeat outside and inside, a kick in between
 if(k==0||k==5){if(!s)kick(.55,36,50,0,4);if(s==3)kick(.35,34,40,0,5)}
 else if(k==1){if(!(s&7)||(bar&1)&&s==10)kick(.75,44,110,200,5)}
 else if(k==2){if(!(s&3))kick(.8,46,130,300,5)}
 else if(k==3){if(!(s&3)||(bar&1)&&s==14)kick(.85,46,130,400,5)}
 else if(!(s&7))kick(.85*(1-sp),46*gp,130,300,4);
 if(k==3&&(s==4||s==12)){ce=0;clv=.6}
 if(k==2&&bar>21&&(bar>22||!(s&1))){ce=0;clv=.08+.5*(((bar-22)*16+s)/32)**2}
 if(k==3&&(bar&3)==3&&s>11){ce=0;clv=.35+.08*(s-12)}
 if(k==1&&sp>.5&&!(s&1)){he=.22;hd=hdc}
 if(k==2){he=(s&1?.15:.35)*(.4+.6*sp);hd=hdc}
 if(k==3){he=s&1?.2:s&2?.55:.35;hd=(s&3)==2?hdo:hdc}
 // low strings
 olv=[0,.7,.9,1,(1-sp)**2,0][k];ocut=[300,X(250,700,sp),X(700,2200,sp),2600,X(2600,300,sp),300][k];oo=k==3?.7:.2;
 if(olv>0&&OS[s]){of=mf(OS[s]+root);oe=1}
 // bass
 blv=k==3?1:k==4?(1-sp)**2:0;bcut=k==3?X(260,520,sp):X(400,120,sp);
 if(blv>0){bt=mf(26+root+(k==3&&(bar&1)&&s>11?12:0));if(k==3?BP[s]=='x':!(s&7))be=1}
 // violins: distant swells, a rising shriek into the drop, stabs through it, one long fall at the horizon, wails inside
 sa=0;sk=.02;
 if(k==0&&bar>1&&!(bar&1)){if(!s)scr(bar,1.2);sa=.28*w;sk=.0004}
 if(k==1&&(bar==11||bar==15)){if(!s)scr(3,2.5);sa=.45*w;sk=.0006}
 if(k==2&&bar==19){if(!s)scr(1,-2);sa=.5*w;sk=.0006}
 if(k==2&&bar>21){if(bar==22&&!s)scr(-7,4);sa=.85*(((bar-22)*16+s)/32)**1.5;sk=.001}
 if(k==3&&bar==39){if(!s)scr(-2,9);sa=.9;sk=.002}
 else if(k==3&&(bar&3)>1&&!(s&1)){scr((bar&4?3:0)-(s>>1)*.5,-8);sa=.9}
 if(k==4){if(bar==40&&!s)scr(7,-2.4);sa=.8*(1-sp)**2;sk=.0006}
 if(k==5&&!(bar&1)){if(!s)scr(-10-bar%3,-1.5);sa=.3*w*Math.min(1,(1-sp)*4);sk=.0004}
 // the endless fall (a descending Shepard tone), riser, impacts
 sht=k==4?sp*.6:k==5?.75*Math.min(1,(1-sp)*4):0;
 ris=k==2&&bar>19?((bar-20)*16+s)/64:bar==39?s/16:0;
 if(!s&&(bar==8||bar==16||bar==24||bar==32||bar==40||bar==44)){cre=1;crl=bar>16?.5:.3;if(bar>16){bo=0;bop=0}}
};
return(L,R)=>{
 for(let i=0;i<L.length;i++){
  if(pos>=nx){if(++st==800){st=0;ls+=tm[800]*sr}nx=ls+tm[st+1]*sr;trig()}
  if(!(pos&15)){ // control rate
   og=G(ocut*(.6+1.6*oe));bg=G(bcut*(1+3*be));rg=G(300*2**(ri*5));dk=.02+.012*Math.sin(pos*T*.5);
   if(shl>1e-3||sht>0){sx-=2*T;if(sx<0)sx+=7;for(let j=0;j<7;j++){const o=(j+sx)%7;shf[j]=55*2**o*T;shw[j]=Math.exp(-((o-3)**2)/2.5)}}
  }
  pos++;
  let m=0,l=0,r=0,duck=1,dly=0,rv=0;
  // kick / heartbeat, and the long boom on impacts
  if(kt>=0){kp+=(kf+kb*Math.exp(-kt*22)+kc*Math.exp(-kt*150))*T;m+=Math.tanh(Math.sin(TAU*kp)*Math.exp(-kt*kd)*2.5)*kl;duck=1-.8*kl*Math.exp(-kt*8);kt+=T;if(kt>1.3)kt=-1}
  if(bo>=0){bop+=(30+45*Math.exp(-bo*5))*T;const c=Math.tanh(Math.sin(TAU*bop)*Math.exp(-bo*1.6)*3)*.5;m+=c;rv+=c*.3;bo+=T;if(bo>3.5)bo=-1}
  // drone
  dlv+=(dlt-dlv)*.00005;
  if(dlv>1e-3){const f=mf(26)*gp*T;d1+=f;if(d1>=1)d1-=1;d2+=f*2.006;if(d2>=1)d2-=1;d3+=f*3.01;if(d3>=1)d3-=1;
   dl+=(saw(d1,f)+saw(d2,f*2.006)+.5*saw(d3,f*3.01)-dl)*dk;dl2+=(dl-dl2)*dk;m+=(dl2*1.6+Math.sin(TAU*d1)*.25)*dlv*.4*(.5+.5*duck)}
  // bass: three saws beating against each other, driven
  bl+=(blv-bl)*.001;
  if(bl>1e-3){bf+=(bt-bf)*.003;be*=bdc;const f=bf*gp*T;b1+=f;if(b1>=1)b1-=1;b2+=f*1.009;if(b2>=1)b2-=1;b3+=f*1.988;if(b3>=1)b3-=1;
   m+=Math.tanh(svf(bs,saw(b1,f)+saw(b2,f*1.009)+saw(b3,f*1.988),bg,.4)*1.8)*.4*bl*duck}
  // hats, snare, crash, riser share one noise source
  const n=rnd();hl+=(n-hl)*.4;const hh=n-hl;he*=hd;l+=hh*he*.2;r+=hh*he*.24;
  if(ce>=0){svf(cs,n,cg,.6);const c=(cs[2]*(ce<.03?1-(ce%.01)*70:Math.exp(-(ce-.03)*13))*1.5+Math.sin(TAU*(180*ce+1.5*(1-Math.exp(-ce*40))))*Math.exp(-ce*16)*.6)*clv;m+=c;rv+=c*.5;ce+=T;if(ce>.6)ce=-1}
  cre*=crd;{const c=hh*cre*crl;l+=c;r+=c;rv+=c*.6}
  ri+=(ris-ri)*.001;if(ri>.001){svf(rz,n,rg,.4);const c=rz[2]*ri*ri*.3;m+=c;rv+=c*.3}
  // low strings, short bows
  if(oa>1e-4||oe>1e-4){oe*=odc;oa+=(oe-oa)*.03;const f=of*gp*T;o1+=f;if(o1>=1)o1-=1;o2+=f*2.004;if(o2>=1)o2-=1;
   const y=Math.tanh(svf(os,(saw(o1,f)+saw(o2,f*2.004)*oo)*oa,og,.5)*1.5)*.34*olv;l+=y;r+=y;dly+=y*.25;rv+=y*.3}
  // pad
  plv+=(plt-plv)*.0001;pc+=(pct-pc)*.001;
  {let a=0,b=0;for(let j=0;j<6;j++){let p=pph[j]+pfr[j]*gp*T;if(p>=1)p-=1;pph[j]=p;if(j&1)b+=p;else a+=p}
   pl+=((2*a-3)*.14-pl)*pc;pl2+=(pl-pl2)*pc;pr+=((2*b-3)*.14-pr)*pc;pr2+=(pr-pr2)*pc;
   const g=plv*(.4+.6*duck);l+=pl2*g;r+=pr2*g;rv+=(pl2+pr2)*g*.3}
  // violins: four saws a semitone apart, pitch and bow pressure shaken by noise, through two narrow resonances
  if(se>1e-4||sa>0){se+=(sa-se)*sk;sj+=(rnd()-sj)*.03;let x=0;const vb=(1+.15*sj+.006*Math.sin(pos*T*44))*T;
   for(let j=0;j<4;j++){const f=(sf[j]=Math.min(sf[j]*sg,9e3))*vb*(1+j*.0007);let p=sph[j]+f;if(p>=1)p-=1;sph[j]=p;x+=saw(p,f)}
   svf(z1,x,z1g,.3);svf(z2,x,z2g,.25);
   const y=Math.tanh((z1[2]+z2[2]*.8+x*.1)*(1+4*sj))*se*.2;l+=y*.9;r+=y*.7;dly+=y*.35;rv+=y*.7}
  // Shepard tone: seven octaves of sines sliding down under a fixed bell, so it falls forever
  shl+=(sht-shl)*.0001;
  if(shl>1e-3){let y=0;for(let j=0;j<7;j++){let p=shp[j]+shf[j];if(p>=1)p-=1;shp[j]=p;y+=Math.sin(TAU*p)*shw[j]}y=Math.tanh(y*1.3)*shl;m+=y*.14;rv+=y*.2}
  // delay
  {const a=dL[di],b=dR[di];dlp+=(b-dlp)*.4;drp+=(a-drp)*.4;dL[di]=dly+dlp*.5;dR[di]=drp*.5;if(++di==DN)di=0;l+=a*.5;r+=b*.5;rv+=(a+b)*.15}
  // reverb + soft clip
  l+=verb(rv*.02+1e-18,cL,aL,0)*1.2;r+=verb(rv*.02+1e-18,cR,aR,1)*1.2;
  L[i]=Math.tanh((m+l)*.9);R[i]=Math.tanh((m+r)*.9);
 }
 return pos};
}

/* ---------------- shaders ---------------- */
const VS=`#version 300 es
void main(){gl_Position=vec4(vec2(gl_VertexID&1,gl_VertexID>>1)*4.-1.,0,1);}`;

const SCN=`#version 300 es
precision highp float;precision highp sampler2D;
uniform vec2 uR;uniform float uT,uRow,uH,uIn,uHot,uDk,uFo,uRg,uE;uniform vec4 uA,uK;uniform float uHw,uJ;uniform vec4 uSp;uniform vec2 uPt;uniform vec3 uO;uniform mat3 uM;uniform sampler2D uS;out vec4 O;
// units: Schwarzschild radius = 1.  uA: bass, low-mid, mid, high (FFT bands)   uK: kick env, hat env
#define RI 3.
#define RO 14.
#define sat(x) clamp(x,0.,1.)
mat2 rot(float a){float c=cos(a),s=sin(a);return mat2(c,-s,s,c);}
float h31(vec3 p){p=fract(p*.3183099+.1);p*=17.;return fract(p.x*p.y*p.z*(p.x+p.y+p.z));}
vec3 h33(vec3 p){p=fract(p*vec3(.1031,.1030,.0973));p+=dot(p,p.yxz+33.33);return fract((p.xxy+p.yxx)*p.zyx);}
float ns(vec3 x){vec3 i=floor(x),f=fract(x);f=f*f*(3.-2.*f);
  return mix(mix(mix(h31(i),h31(i+vec3(1,0,0)),f.x),mix(h31(i+vec3(0,1,0)),h31(i+vec3(1,1,0)),f.x),f.y),
             mix(mix(h31(i+vec3(0,0,1)),h31(i+vec3(1,0,1)),f.x),mix(h31(i+vec3(0,1,1)),h31(i+vec3(1,1,1)),f.x),f.y),f.z);}
float fbm(vec3 p){float a=.5,s=0.;for(int i=0;i<4;i++){s+=a*ns(p);p=p*2.03+7.1;a*=.5;}return s;}
float fth(float x,float a){return textureLod(uS,vec2(x,uRow-a*.98),0.).r;}   // spectrum a*2 seconds ago, x = log frequency
vec3 bb(float t){return vec3(t,t*t*.62,t*t*t*.38);}                           // a black-body-ish ramp: red, orange, white, blue-white

// stars in three layers and a band of dust, looked up by the direction a ray finally escapes in
vec3 sky(vec3 d){
  vec3 c=vec3(0);
  for(int i=0;i<3;i++){
    vec3 q=d*(22.+float(i)*31.),id=floor(q),h=h33(id+float(i)*17.);
    float e=length(q-id-.5-(h.yzx-.5)*.7);
    c+=step(.82,h.x)*(.3+.7*h.z*h.z)*mix(vec3(1.,.72,.5),vec3(.6,.8,1.),h.y)*exp(-e*e*260.)*(4.+6.*uA.w*h.z)/(1.+float(i));
  }
  c+=vec3(1.,.9,.7)*exp((dot(d,normalize(vec3(-.86,-.19,-.47)))-1.)*9000.)*7.;   // one bright star: when the hole passes in front of it, it becomes a ring
  float b=dot(d,normalize(vec3(.35,.8,.48))),n=fbm(d*3.+2.);
  c+=(vec3(.11,.05,.17)*n*n+vec3(.02,.05,.07)*fbm(d*7.))*exp(-b*b*9.);
  return c;
}

// the accretion disk where a ray crosses its plane: colour and opacity
float dn(vec3 q,float r,float a){return fbm(vec3(rot(a)*q.xz*1.1,r*.35+uDk*.02));}
vec4 disk(vec3 q,vec3 v){
  float r=length(q.xz);
  if(r<RI||r>RO)return vec4(0);
  float x=(r-RI)/(RO-RI),w=3.*inversesqrt(r*r*r),w0=3.*inversesqrt(RO*RO*RO);
  // Keplerian shear, in two phases cross-faded so the winding never piles up
  float ta=mod(uDk,24.),tb=mod(uDk+12.,24.);
  float d=mix(dn(q,r,(w-w0)*ta+w0*uDk),dn(q,r+9.,(w-w0)*tb+w0*uDk),abs(ta-12.)/12.);
  float rg=ns(vec3(r*6.,1.3,0.))*.6+ns(vec3(r*19.,7.,0.))*.4;
  d=smoothstep(.22,.72,d)*(.3+.7*rg)*smoothstep(RI,RI+.35,r)*pow(1.-x,1.4);
  // sound falls inward: the spectrum's history is laid out along the radius
  float e=.75+1.5*fth(.07,(1.-x)*.45)+1.1*fth(.55,(1.-x)*.45)*rg;
  // Doppler beaming from the orbital velocity, and gravitational redshift
  float be=sqrt(.5/r);vec3 vd=vec3(-q.z,0.,q.x)/r*be;
  float D=sqrt(1.-be*be)/(1.+dot(vd,v))*sqrt(1.-1./r);
  float t=uHot*1.5*pow(RI/r,.75)*D;
  return vec4(bb(t)*D*D*sqrt(D)*d*e*uE*.9,sat(d*1.3)*.92);
}

// a planet thrown at the hole. uSp = angle and radius of where it is, how far gone it is (0..1), on/off. uPt = kind, size.
// It follows an inward spiral r = r0 exp(-.18 angle); what is torn off runs ahead of it down the same spiral.
vec3 LP;
vec3 tc(){return uPt.x<1.5?vec3(1.,.3,.05):uPt.x<2.5?vec3(1.,.6,.25):uPt.x<3.5?vec3(.45,.8,1.):vec3(.15,.5,1.);}   // what its debris looks like
float pl(vec3 p){
  float c=cos(uSp.x),s=sin(uSp.x),D=uSp.z,a=uPt.y;
  vec3 d=p-vec3(uSp.y*c,a*1.1,uSp.y*s);
  float bd=length(d)-a*4.9;
  if(bd>.2)return bd;
  // the planet is cut into shards (a tilted grid, each block sliced by a plane of its own); each drifts off, fastest along the orbit, and wears down
  const mat3 G=mat3(.36,.48,-.8,-.8,.6,0.,.48,.64,.6);
  vec3 x=vec3(d.z*c-d.x*s,d.x*c+d.z*s,d.y)/a,E=vec3(3.5,.9,.6)*D*D,b=floor(G*(x/(1.+E))/.46-.5);
  float m=1e3;
  for(int i=0;i<8;i++){
    vec3 g=b+vec3(i&1,i>>1&1,i>>2),h=h33(g+uPt.x*7.),o=(g+.5)*.46,ow=o*G;
    vec3 q=x-ow*E-(h-.5)*D*.5,u=G*q-o;                           // q: where this point sat in the whole planet
    vec3 w=abs(u)-.18*(1.-D*(.3+.55*h.x));
    float e=max(length(q)-1.,length(max(w,0.))+min(max(w.x,max(w.y,w.z)),0.)-.05);
    e=max(e,dot(u,normalize(h-.5))-.03-.1*h.y*(1.-D));
    if(e<m){m=e;LP=q;}
  }
  return m*a*.7;
}
vec4 strm(vec3 p,out float sd){
  float r=length(p.xz),a=mod(atan(p.z,p.x)-uSp.x+1.5,6.2832)-1.5,dm=log(uSp.y)/.18,g=0.,ht=0.;sd=abs(p.y)-uPt.y*2.-.3;
  if(sd>0.)return vec4(0);
  sd=1e3;
  for(int k=0;k<2;k++){
    float aa=a+6.2832*float(k);
    if(aa<dm){
      float rs=uSp.y*exp(-.18*aa),w=.03+uPt.y*(.2+.5*uSp.z)*(aa<0.?exp(aa*1.5):1./(1.+aa*.3));
      float dd=length(vec2(r-rs,p.y-uPt.y*1.1*exp(-max(aa,0.)*.6)));
      float e=exp(-dd*dd/(w*w))*(aa<0.?exp(aa*2.)*uSp.z:sqrt(uSp.z)*(1.-aa/dm)*smoothstep(0.,1.,uSp.z*1.4*dm+.5-aa));
      if(e>g){g=e;ht=sat(2.2/rs-.9);}
      sd=min(sd,dd-w*1.5);
    }
  }
  if(g<.002)return vec4(0);
  g*=.5+ns(vec3(a*5.-uT*1.5,r*6.,p.y*6.));
  return vec4(mix(tc(),vec3(1.3,1.,.75),ht)*g*(2.2+2.*ht)/(.6+uPt.y),g);       // whatever it was made of, it ends up white hot
}

void main(){
  vec2 uv=(gl_FragCoord.xy*2.-uR)/uR.y;
  // inside the horizon the whole view is wound into a spiral
  uv*=rot(uIn*(1.2*log(length(uv)+.06)+uT*.15));
  vec3 v=normalize(uM*vec3(uv,uFo)),p=uO;
  vec3 c=cross(p,v);float h2=dot(c,c),tr=1.,gl=0.,mn=1e3,hw=0.,jt=0.;bool out_=false;
  vec3 col=vec3(0);
  for(int i=0;i<300;i++){
    float r2=dot(p,p);
    if(r2<uH*uH){col+=tr*uHw*vec3(.5,.7,1.)*pow(h31(floor(normalize(p)*150.)+floor(uT*10.)),50.)*2.;break;}   // the horizon itself flickers
    if(r2>900.&&dot(p,v)>0.){out_=true;break;}
    float r=sqrt(r2),dt=r*(.05+.05*sat(r*.2));
    if(uHw>0.&&r<2.2){   // Hawking radiation, exaggerated beyond all reason: quanta appear at the horizon and leak outward
      vec3 dq=p/r*17.,f=fract(dq)-.5;float h=h31(floor(dq)),ph=fract(h*7.+uT*(.25+.3*h)),e=(r-1.02-ph*1.1)*14.;
      hw+=dt*exp(-dot(f,f)*22.-e*e)*(1.-ph)*(1.-ph)*tr;
    }
    if(uJ>0.){   // jets along the axis (a real hole needs spin and magnetic fields for these)
      float ay=abs(p.y),rh=length(p.xz),wj=.12+.1*ay,e=exp(-rh*rh/(wj*wj));
      dt=min(dt,.08+.5*rh);
      if(e>.003)jt+=dt*e*smoothstep(.9,1.6,ay)*exp(-ay*.06)*(.5+ns(vec3(p.xz*4.,ay*2.-uT*5.)))*tr;
    }
    if(uSp.w>.5){   // the planet is sphere-traced along the same bent ray, so it is lensed like everything else
      float ds=pl(p);
      if(ds<.004){
        vec3 q=LP,w=normalize(v);vec2 e=vec2(1,-1)*.003;float m=uPt.x,D=uSp.z;
        vec3 n=normalize(e.xyy*pl(p+e.xyy)+e.yyx*pl(p+e.yyx)+e.yxy*pl(p+e.yxy)+e.xxx*pl(p+e.xxx)),al,em=vec3(0);
        if(m<1.5){float f=fbm(q*2.5);al=vec3(.09,.07,.06);em=vec3(1.,.3,.05)*smoothstep(.07,0.,abs(f-.47))*(1.5+6.*D);}            // rock, lava in the cracks
        else if(m<2.5)al=mix(vec3(.85,.66,.42),vec3(.55,.28,.14),.5+.5*sin(q.z*13.+fbm(q*2.5)*5.));                               // gas giant, banded
        else if(m<3.5)al=vec3(.6,.85,1.)*(.7+.6*fbm(q*4.));                                                                     // ice
        else{al=mix(vec3(.02,.16,.6),vec3(.12,.45,.1),smoothstep(.47,.52,fbm(q*2.2+3.)));al=mix(al,vec3(.9),smoothstep(.5,.68,fbm(q*4.5+9.)));}   // oceans, land, cloud
        float df=max(dot(n,-normalize(p)),0.),nv=max(dot(n,-w),0.);     // lit by the inner disk
        float in_=smoothstep(.97,.9,length(q));al=mix(al,m<1.5?vec3(.1):m<2.5?vec3(1.,.85,.6):m<3.5?vec3(.75,.95,1.):vec3(.25,.1,.05),in_);em=em*(1.-in_)+(m>1.5&&m<3.5?tc()*.25:vec3(1.,.3,.05)*(.5+.6*fbm(q*5.)))*in_;   // broken faces show what is inside    // glowing where it tears
        col+=tr*(al*(.3+1.4*df)+em+vec3(.5,.6,1.)*pow(1.-nv,3.)*(m>2.5?.3:.15));tr=0.;break;
      }
      float sd;vec4 sg=strm(p,sd);
      dt=min(dt,max(min(ds,.16+.4*max(sd,0.)),.01));
      col+=tr*sg.rgb*dt;tr*=exp(-sg.a*dt*1.2);
    }
    mn=min(mn,abs(r-1.5));
    v-=1.5*h2*p/(r2*r2*r)*dt;                 // null geodesics of the Schwarzschild metric as a force law
    vec3 pn=p+v*dt;
    if(p.y*pn.y<0.){vec4 d=disk(mix(p,pn,p.y/(p.y-pn.y)),normalize(v));col+=tr*d.rgb;tr*=1.-d.a;if(tr<.01)break;}
    float rr=length(p.xz);
    gl+=dt*exp(-abs(p.y)*1.4)*smoothstep(RO+2.,RI,rr)*smoothstep(RI-.8,RI+.4,rr)/(1.+rr)*tr;
    p=pn;
  }
  col+=bb(uHot*1.15)*gl*.035*(1.+1.5*uA.x)*uE+vec3(.5,.7,1.)*hw*uHw*9.+vec3(.4,.6,1.)*jt*uJ*(1.+uA.x+2.*uK.x);
  if(out_){
    col+=tr*sky(normalize(v))*mix(vec3(1),vec3(.9,1.3,2.6)*2.5,uIn);
    col+=tr*vec3(.35,.55,1.)*.0025/(mn*mn+.003)*uRg*(1.+3.*uK.x);   // light that has circled the photon sphere
  }
  O=vec4(max(col,0.),1.);
}`;

const PRE=`#version 300 es
precision highp float;uniform sampler2D uC;uniform vec2 uR,uI;uniform float uTh;out vec4 O;
`;
// dual-filter bloom: 5-tap downsample (soft threshold on the first pass), 8-tap tent upsample
const DOWN=PRE+`void main(){vec2 v=gl_FragCoord.xy/uR;
vec3 s=texture(uC,v).rgb*4.+texture(uC,v+uI).rgb+texture(uC,v-uI).rgb+texture(uC,v+uI*vec2(1,-1)).rgb+texture(uC,v+uI*vec2(-1,1)).rgb;s*=.125;
if(uTh>0.){s=min(s,vec3(24.));s*=smoothstep(.4,1.6,max(s.r,max(s.g,s.b)));}
O=vec4(s,1);}`;
const UP=PRE+`void main(){vec2 v=gl_FragCoord.xy/uR;vec3 e=vec3(uI,0.);
vec3 s=texture(uC,v+e.xz).rgb+texture(uC,v-e.xz).rgb+texture(uC,v+e.zy).rgb+texture(uC,v-e.zy).rgb
+2.*(texture(uC,v+uI*.5).rgb+texture(uC,v-uI*.5).rgb+texture(uC,v+uI*vec2(.5,-.5)).rgb+texture(uC,v+uI*vec2(-.5,.5)).rgb);
O=vec4(s/12.,1);}`;
const COMP=`#version 300 es
precision highp float;uniform sampler2D uC,uB,uX,uS;uniform vec2 uR;uniform float uT,uF,uXa,uRow,uFl,uCa;out vec4 O;
vec3 aces(vec3 x){return clamp((x*(2.51*x+.03))/(x*(2.43*x+.59)+.14),0.,1.);}
void main(){
  vec2 v=gl_FragCoord.xy/uR,c=v-.5;float r2=dot(c,c);
  vec2 o=c*r2*(.012+.05*uCa+.03*uFl);
  vec3 col=vec3(texture(uC,v-o).r,texture(uC,v).g,texture(uC,v+o).b);
  col+=texture(uB,v).rgb*.22;
  col*=1.-1.2*r2;
  col+=uFl*vec3(.3,.26,.22);
  col=pow(aces(col*1.1),vec3(.4545));
  float sp=texture(uS,vec2(abs(c.x)*2.,uRow)).r;
  col+=.22*step(v.y,.002+.03*sp)*vec3(1.,.7,.45);
  col=mix(col,vec3(1),texture(uX,vec2(v.x,1.-v.y)).a*uXa);
  col+=(fract(sin(dot(gl_FragCoord.xy+uT*61.,vec2(12.9898,78.233)))*43758.5453)-.5)*.03;
  O=vec4(col*uF,1);
}`;

/* ---------------- GL setup ---------------- */
const C=document.getElementById('c'),gl=C.getContext('webgl2',{antialias:false,alpha:false,powerPreference:'high-performance'});
if(!gl){document.body.innerHTML='<p style="color:#fff;font:16px sans-serif;padding:2em">This demo needs WebGL2.</p>';return}
const HF=gl.getExtension('EXT_color_buffer_float')||gl.getExtension('EXT_color_buffer_half_float');
gl.getExtension('KHR_parallel_shader_compile');
const TQ=gl.getExtension('EXT_disjoint_timer_query_webgl2'),tq=TQ&&gl.createQuery();let qp=0,gms=8;
const IF=HF?gl.RGBA16F:gl.RGBA8,TY=HF?gl.HALF_FLOAT:gl.UNSIGNED_BYTE;
gl.bindVertexArray(gl.createVertexArray());
const tex=(unit,wrapT)=>{const t=gl.createTexture();gl.activeTexture(gl.TEXTURE0+unit);gl.bindTexture(gl.TEXTURE_2D,t);
 gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);
 gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,wrapT||gl.CLAMP_TO_EDGE);return t};
const target=(w,h)=>{const t=tex(1);gl.texImage2D(gl.TEXTURE_2D,0,IF,w,h,0,gl.RGBA,TY,null);
 const f=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,f);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,t,0);return{t,f,w,h}};
const prog=fs=>{const p=gl.createProgram(),sh=[];
 for(const[ty,src]of[[gl.VERTEX_SHADER,VS],[gl.FRAGMENT_SHADER,fs]]){const s=gl.createShader(ty);gl.shaderSource(s,src);gl.compileShader(s);gl.attachShader(p,s);sh.push(s)}
 gl.linkProgram(p);return{p,sh,u:null}};
const errs=[];
const use=o=>{
 if(!o.u){o.u={};
  if(!gl.getProgramParameter(o.p,gl.LINK_STATUS)){const e=gl.getProgramInfoLog(o.p)+'\n'+gl.getShaderInfoLog(o.sh[1]);errs.push(e);console.error('shader',e)}
  for(let i=0,n=gl.getProgramParameter(o.p,gl.ACTIVE_UNIFORMS);i<n;i++){const a=gl.getActiveUniform(o.p,i);o.u[a.name]=gl.getUniformLocation(o.p,a.name)}}
 gl.useProgram(o.p);return o.u};
const PS=prog(SCN),PD=prog(DOWN),PU=prog(UP),PC=prog(COMP);

// spectrogram texture: 256 log-frequency bins x 128 rows of history (ring buffer)
const NB=256,HR=128,cur=new Float32Array(NB),row8=new Uint8Array(NB);
const TS=tex(0,gl.REPEAT);gl.pixelStorei(gl.UNPACK_ALIGNMENT,1);
gl.texImage2D(gl.TEXTURE_2D,0,gl.R8,NB,HR,0,gl.RED,gl.UNSIGNED_BYTE,new Uint8Array(NB*HR));
// text overlay
const TX=tex(3),XC=document.createElement('canvas'),X=XC.getContext('2d');
let W=0,H=0,sc=1,scMax=1,S=null,B=[],txt=['','',''],txtDirty=1;
const free=o=>{if(o){gl.deleteTexture(o.t);gl.deleteFramebuffer(o.f)}};
const alloc=()=>{free(S);B.forEach(free);B=[];
 let w=Math.max(2,W*sc|0),h=Math.max(2,H*sc|0);S=target(w,h);
 for(let i=0;i<6;i++){w=Math.max(1,w>>1);h=Math.max(1,h>>1);B.push(target(w,h))}};
const resize=()=>{const d=Math.min(devicePixelRatio||1,2);W=C.width=Math.max(2,innerWidth*d|0);H=C.height=Math.max(2,innerHeight*d|0);
 scMax=sc=Math.min(1,Math.sqrt(1.4e6/(W*H)));alloc();txtDirty=1};
addEventListener('resize',resize);resize();
const drawText=()=>{txtDirty=0;
 const w=XC.width=Math.min(W,1600),h=XC.height=Math.max(1,Math.round(w*H/W));X.clearRect(0,0,w,h);X.fillStyle='#fff';X.textBaseline='middle';
 const sans='"Helvetica Neue",Helvetica,Arial,sans-serif',mono='ui-monospace,Menlo,Consolas,monospace';
 if(txt[0]){X.textAlign='center';X.font=`200 ${h*.13}px ${sans}`;try{X.letterSpacing=h*.06+'px'}catch(e){}X.fillText(txt[0],w/2+h*.03,h*.2)}
 try{X.letterSpacing=h*.008+'px'}catch(e){}
 if(txt[1]){X.textAlign='center';X.font=`400 ${h*.026}px ${mono}`;X.fillText(txt[1],w/2,h*.82)}
 if(txt[2]){X.textAlign='left';X.font=`400 ${h*.022}px ${mono}`;X.fillText(txt[2],h*.06,h*.92)}
 gl.activeTexture(gl.TEXTURE3);gl.bindTexture(gl.TEXTURE_2D,TX);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,XC)};

/* ---------------- audio + FFT ---------------- */
const TM=TMAP();
let ctx=null,an=null,node=null,t0=null,ext=null,extT=0,fb=null,lo=null,hi=null,mode='';
const start=async()=>{
 if(ctx){ctx.resume();return}
 ctx=new(window.AudioContext||window.webkitAudioContext)({latencyHint:'playback'});ctx.resume();
 an=ctx.createAnalyser();an.fftSize=2048;an.smoothingTimeConstant=.35;an.minDecibels=-85;an.maxDecibels=-18;an.connect(ctx.destination);
 fb=new Uint8Array(1024);
 const hz=ctx.sampleRate/2048;lo=new Float32Array(NB);hi=new Float32Array(NB);
 for(let i=0;i<NB;i++){lo[i]=35*2**(i/NB*8.8)/hz;hi[i]=35*2**((i+1)/NB*8.8)/hz}
 try{ // data: URL, because Blob URL worklets fail to load from file:// in Chrome
  await ctx.audioWorklet.addModule('data:text/javascript;charset=utf-8,'+encodeURIComponent(TMAP+';'+SYN+';registerProcessor("s",class extends AudioWorkletProcessor{constructor(){super();this.f=SYN(sampleRate,TMAP());this.n=0}process(i,o){const p=this.f(o[0][0],o[0][1]);if(!(this.n++&31))this.port.postMessage([p,currentTime]);return true}})'));
  node=new AudioWorkletNode(ctx,'s',{numberOfInputs:0,outputChannelCount:[2]});
  node.port.onmessage=e=>{t0=e.data[1]-(e.data[0]-128)/ctx.sampleRate};mode='worklet';
 }catch(e){ // no worklet: same synth on the main thread
  const f=SYN(ctx.sampleRate,TM);node=ctx.createScriptProcessor(2048,0,2);
  node.onaudioprocess=e=>{const b=e.outputBuffer,p=f(b.getChannelData(0),b.getChannelData(1));t0=e.playbackTime-(p-2048)/ctx.sampleRate};mode='scriptprocessor: '+e;
 }
 if(!ext)node.connect(an);
};
// your own music: drop a file, the FFT does the rest
const play=async file=>{
 await start();
 const buf=await ctx.decodeAudioData(await file.arrayBuffer());
 if(ext)ext.stop();else node.disconnect();
 ext=ctx.createBufferSource();ext.buffer=buf;ext.loop=true;ext.connect(an);ext.start();extT=ctx.currentTime;
};
addEventListener('dragover',e=>e.preventDefault());
addEventListener('drop',e=>{e.preventDefault();const f=e.dataTransfer.files[0];if(f)play(f).catch(e=>console.error(e))});
addEventListener('pointerdown',start);
addEventListener('keydown',e=>{
 if(e.key=='f'||e.key=='F'){try{(document.fullscreenElement?document.exitFullscreen():document.documentElement.requestFullscreen()).catch(()=>{})}catch(e){}}
 start()});

const band=[0,0,0,0],peak=[.2,.2,.2,.2],A=[0,0,0,0],K=[0,0,0,0],RG=[0,52,116,186,256];
let pb=0,ph=0,row=0,racc=0;
const analyse=dt=>{
 if(an&&ctx.state=='running'){
  an.getByteFrequencyData(fb);
  for(let i=0;i<NB;i++){
   const a=lo[i],b=hi[i];let v=0,k=a|0;
   if(b-a<1)v=fb[k]+(fb[k+1]-fb[k])*(a-k);else for(;k<b;k++)v=Math.max(v,fb[k]);
   {const x=i/NB;v=Math.max(0,v/255-.3+.14*x)/.7*(.8+1.2*x)}v=Math.min(1,v*v*1.3);
   cur[i]+=(v-cur[i])*(v>cur[i]?.7:1-Math.exp(-dt*9));
  }
 }else for(let i=0;i<NB;i++)cur[i]*=.9;
 for(let j=0;j<4;j++){
  let s=0;for(let i=RG[j];i<RG[j+1];i++)s+=cur[i];s/=RG[j+1]-RG[j];
  band[j]=s;peak[j]=Math.max(peak[j]*Math.exp(-dt*.05),s,.12);
  A[j]+=(Math.min(1,s/peak[j])-A[j])*.5;
 }
 const d=Math.exp(-dt*5);
 K[0]=Math.max(K[0]*d,Math.min(1,Math.max(0,band[0]-pb)*7));pb=band[0];
 K[1]=Math.max(K[1]*d,Math.min(1,Math.max(0,band[3]-ph)*9));ph=band[3];
 racc+=dt;
 if(racc>=1/61){racc=Math.min(racc-1/60,.02);row=(row+1)%HR;
  for(let i=0;i<NB;i++)row8[i]=cur[i]*255;
  gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,TS);gl.texSubImage2D(gl.TEXTURE_2D,0,0,row,NB,1,gl.RED,gl.UNSIGNED_BYTE,row8)}
};

/* ---------------- the fall ---------------- */
// camera keys every four bars: radius (in Schwarzschild radii), elevation over the disk (degrees), azimuth, lens, roll.
// Bars are not equally long: the tempo map makes the same path run faster and faster, then almost stop.
const KEY=[[46,14,0,1.9,0],[36,11,.5,1.9,.1],[27,8,1.1,1.8,.15],[19,16,1.9,1.6,.1],[13,26,2.9,1.5,-.1],[10,12,4.1,1.4,-.25],
 [7.5,3,5.3,1.2,0],[6,-5,7.3,1,.35],[4.6,7,9.9,.9,-.3],[3.3,-4,13.2,.8,.4],[2,2,17.5,.75,0],[1,5,20,.7,.5],[.45,20,21.6,.6,1.6],[.2,35,22.6,.55,3]];
const cr=(a,b,c,d,t)=>.5*(2*b+(c-a)*t+(2*a-5*b+4*c-d)*t*t+(3*b-a-3*c+d)*t*t*t);
const camAt=bp=>{const x=Math.min(Math.max(bp,0)/4,12.999),i=x|0,t=x-i,n=KEY.length-1,o=[];
 for(let j=0;j<5;j++)o[j]=cr(KEY[Math.max(i-1,0)][j],KEY[i][j],KEY[Math.min(i+1,n)][j],KEY[Math.min(i+2,n)][j],t);return o};
const ss=(a,b,x)=>{x=Math.min(1,Math.max(0,(x-a)/(b-a)));return x*x*(3-2*x)};
const HOT=[.8,.9,.98,1.05,.95,.75],EXP=[.8,.85,.9,.95,.9,.9];
let flash=0,fade=0,lt=0,ft=1/60,hold=0,frames=0,lbar=-1,lscn=-1,dk=0,dbg=-1,cap='',capN=0,capS=0,Rnow=46,bpNow=0;
const M=new Float32Array(9);
const frame=now=>{
 requestAnimationFrame(frame);frames++;
 const t=now/1e3,dt=Math.min(.1,Math.max(.001,t-lt));lt=t;
 analyse(dt);
 // where are we in the song?
 let bp=0,run=0,mt=0;
 if(ext){mt=(ctx.currentTime-extT)%120;run=1}
 else if(t0!=null&&ctx.state=='running'){mt=Math.max(0,ctx.currentTime-t0-(ctx.outputLatency||0))%120;run=1}
 if(run){let a=0,b=800;while(b-a>1){const m=a+b>>1;if(TM[m]<=mt)a=m;else b=m}bp=(a+(mt-TM[a])/(TM[a+1]-TM[a]))/16}
 if(dbg>=0){bp=dbg;run=1;mt=60}
 bpNow=bp;
 const bar=bp|0,k=bar<8?0:bar<16?1:bar<24?2:bar<40?3:bar<44?4:5;
 if(bar!=lbar){if(run&&lbar>=0&&(bar==8||bar==16||bar==24||bar==32||bar==40||bar==44))flash=1;lbar=bar}
 // camera: the fall, or one of four cut-aways during the drop
 const scn=!run?0:bar>=26&&bar<29?1:bar>=30&&bar<33?2:bar>=34&&bar<37?3:bar>=38&&bar<40?4:0,x=bp-[0,26,30,34,38][scn];
 if(scn!=lscn){if(run&&lscn>=0)flash=.7;lscn=scn}
 let R,fv,rl=0,px,py,pz,fx,fy,fz,vx=0,vy=1,vz=0,sp=[0,5,0,0],pt=[0,1];
 if(scn){
  // one planet per cut-away, thrown in along a spiral from 5.5 rs to 2.2 rs while it comes apart
  const u=x/(scn==4?2:3),a=1+u*5.1,r=5.5*Math.exp(-.918*u),pol=(r,a,y)=>[r*Math.cos(a),y,r*Math.sin(a)];
  sp=[a,r,u,1];pt=[scn,[.5,.9,.55,.62][scn-1]];
  [px,py,pz]=pol(r+1.1+pt[1],a-.45,1.3+.5*u);const[tx,ty,tz]=pol(r*.85,a+.12,pt[1]*.6);
  fx=tx-px;fy=ty-py;fz=tz-pz;R=Math.hypot(px,py,pz);fv=1.3;
 }else{
  let el,az0;[R,el,az0,fv,rl]=camAt(bp);
  const az=az0+(run?0:t*.03),e=el*Math.PI/180,ce=Math.cos(e),nx=ce*Math.cos(az),ny=Math.sin(e),nz=ce*Math.sin(az);
  // look at the hole on the way down, along the orbit at the horizon, and back out at the sky from inside
  const s1=ss(3.2,1.6,R),s2=ss(1.8,.6,R),wi=1-s1,wt=s1*(1-s2),wo=s1*(.35+.65*s2),
   ox=.1*Math.sin(bp*.9+1)*wi,oy=.05*Math.sin(bp*.7)*wi+.012*K[0]*(k==3);
  px=nx*R;py=ny*R;pz=nz*R;
  fx=-nx*wi-Math.sin(az)*wt+nx*wo+Math.sin(az)*ox;fy=-ny*wi+ny*wo+oy;fz=-nz*wi+Math.cos(az)*wt+nz*wo-Math.cos(az)*ox;
 }
 Rnow=R;
 let l=Math.hypot(fx,fy,fz);fx/=l;fy/=l;fz/=l;
 let rx=vy*fz-vz*fy,ry=vz*fx-vx*fz,rz=vx*fy-vy*fx;l=Math.hypot(rx,ry,rz)||1;rx/=l;ry/=l;rz/=l;   // right = up x forward
 let ux=fy*rz-fz*ry,uy=fz*rx-fx*rz,uz=fx*ry-fy*rx;                                               // up = forward x right
 const ra=rl+.03*Math.sin(t*.4),cr_=Math.cos(ra),sr_=Math.sin(ra);
 M[0]=rx*cr_+ux*sr_;M[1]=ry*cr_+uy*sr_;M[2]=rz*cr_+uz*sr_;M[3]=ux*cr_-rx*sr_;M[4]=uy*cr_-ry*sr_;M[5]=uz*cr_-rz*sr_;M[6]=fx;M[7]=fy;M[8]=fz;
 dk+=dt*(run?.5+bp*.05:.5);
 // text
 let big='',sub='';
 if(!run){big='INFALL';sub='click to start'}
 else if(bar<2){big='INFALL';sub='nothing gets out'}
 else if(k==4)sub='event horizon';
 else if(bar>45&&bar<49)sub='the fall never ends';
 if(scn)sub=['','it cracks, then it pours','it unwinds like a ribbon','it boils before it breaks','the tide comes in once'][scn];
 if(!(capN++%6)||scn!=capS){capS=scn;const rr=scn?sp[1]:R;   // radius, how fast a clock hovering there would run, and what is on show
  cap=!run?'':(scn?['','a world of rock','a gas giant','a world of ice','a world with oceans'][scn]+'   ':'')+'r = '+rr.toFixed(2)+' rs   time ×'+(rr>1?Math.sqrt(1-1/rr):0).toFixed(2)+'   '+
   (scn?'tidal disruption':bar<2?'':bar<8?'gravitational lensing · einstein ring':bar<16?'doppler beaming · redshift':bar<24?'photon ring':bar<40?'relativistic jets':bar<44?'hawking radiation':'no way out')}
 if(txt[0]!=big||txt[1]!=sub||txt[2]!=cap){txt=[big,sub,cap];txtDirty=1}
 if(txtDirty)drawText();
 flash*=Math.exp(-dt*4);fade=Math.min(1,fade+dt*.8);
 const xa=run?.85:.75+.25*Math.sin(t*3),fo=run&&dbg<0?Math.min(1,(120-mt)/4,mt/1.5+.3):1;

 // adaptive resolution: GPU time of the scene pass where the timer extension exists, frame time otherwise
 ft+=(dt-ft)*.05;
 if(TQ){if(qp&&gl.getQueryParameter(tq,gl.QUERY_RESULT_AVAILABLE)){if(!gl.getParameter(TQ.GPU_DISJOINT_EXT))gms+=(gl.getQueryParameter(tq,gl.QUERY_RESULT)/1e6-gms)*.2;qp=0}}
 else if(dt<.05)gms+=(dt*600-gms)*.05;
 hold-=dt;
 if(hold<0&&t>2){hold=.5;if(gms>11&&sc>.3){sc*=.88;alloc();gms=8}else if(gms<6&&sc<scMax){sc=Math.min(scMax,sc*1.08);alloc();hold=2}}

 // scene into the HDR target
 let u=use(PS);
 gl.disable(gl.BLEND);
 gl.bindFramebuffer(gl.FRAMEBUFFER,S.f);gl.viewport(0,0,S.w,S.h);
 gl.uniform2f(u.uR,S.w,S.h);gl.uniform1f(u.uT,t%1e3);gl.uniform1f(u.uRow,(row+.5)/HR);
 gl.uniform3f(u.uO,px,py,pz);gl.uniform4fv(u.uSp,sp);gl.uniform2fv(u.uPt,pt);gl.uniform1f(u.uHw,run?ss(39.5,41,bp)*ss(1.05,1.3,R):0);gl.uniform1f(u.uJ,run?ss(24,24.4,bp)*(1-ss(39,40,bp)):0);gl.uniformMatrix3fv(u.uM,false,M);
 gl.uniform1f(u.uFo,fv*(1-.05*K[0]));gl.uniform1f(u.uH,Math.min(1,.72*R));gl.uniform1f(u.uIn,ss(1.3,.5,R));gl.uniform1f(u.uRg,ss(1.7,2.6,R));
 gl.uniform1f(u.uHot,HOT[k]+.12*A[0]);gl.uniform1f(u.uE,EXP[k]*(1+.35*K[0]));gl.uniform1f(u.uDk,dk);
 gl.uniform4fv(u.uA,A);gl.uniform4fv(u.uK,K);gl.uniform1i(u.uS,0);
 const q=TQ&&!qp;if(q)gl.beginQuery(TQ.TIME_ELAPSED_EXT,tq);
 gl.drawArrays(gl.TRIANGLES,0,3);
 if(q){gl.endQuery(TQ.TIME_ELAPSED_EXT);qp=1}
 // bloom down
 gl.activeTexture(gl.TEXTURE1);
 u=use(PD);gl.uniform1i(u.uC,1);
 let src=S;
 for(let i=0;i<B.length;i++){const d=B[i];gl.bindFramebuffer(gl.FRAMEBUFFER,d.f);gl.viewport(0,0,d.w,d.h);gl.bindTexture(gl.TEXTURE_2D,src.t);
  gl.uniform2f(u.uR,d.w,d.h);gl.uniform2f(u.uI,1/src.w,1/src.h);gl.uniform1f(u.uTh,i?0:1);gl.drawArrays(gl.TRIANGLES,0,3);src=d}
 // bloom up (additive)
 u=use(PU);gl.uniform1i(u.uC,1);gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE);
 for(let i=B.length-1;i>0;i--){const d=B[i-1];src=B[i];gl.bindFramebuffer(gl.FRAMEBUFFER,d.f);gl.viewport(0,0,d.w,d.h);gl.bindTexture(gl.TEXTURE_2D,src.t);
  gl.uniform2f(u.uR,d.w,d.h);gl.uniform2f(u.uI,1/src.w,1/src.h);gl.drawArrays(gl.TRIANGLES,0,3)}
 gl.disable(gl.BLEND);
 // composite
 u=use(PC);gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.viewport(0,0,W,H);
 gl.bindTexture(gl.TEXTURE_2D,S.t);gl.activeTexture(gl.TEXTURE2);gl.bindTexture(gl.TEXTURE_2D,B[0].t);
 gl.uniform1i(u.uC,1);gl.uniform1i(u.uB,2);gl.uniform1i(u.uX,3);gl.uniform1i(u.uS,0);
 gl.uniform2f(u.uR,W,H);gl.uniform1f(u.uT,t%100);gl.uniform1f(u.uF,fade*fo);gl.uniform1f(u.uXa,xa);gl.uniform1f(u.uRow,(row+.5)/HR);gl.uniform1f(u.uFl,flash);gl.uniform1f(u.uCa,A[3]);
 gl.drawArrays(gl.TRIANGLES,0,3);
};
requestAnimationFrame(frame);
// if this page was opened by a press (a host's start screen) audio may already be allowed: try now, else wait for a click
start().catch(()=>{});
// inspection hook
window.INFALL={SYN,TMAP,errs,get state(){return{scn:lscn,bp:bpNow,R:Rnow,sc,ft,gms,tq:!!TQ,frames,mode,A:[...A],K:[...K],t0,W,H,ctx:ctx&&ctx.state}},set seek(v){dbg=v}};
})();
</script>
</body>
</html>