-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjukebox-hq.js
More file actions
1541 lines (1496 loc) · 104 KB
/
Copy pathjukebox-hq.js
File metadata and controls
1541 lines (1496 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ============================================================
JUKEBOX — ambient audio-reactive player for Suno tracks
Three.js centerpiece (PBR + dynamic lights + bloom),
shape/spin/backdrop controls, 10 party modes.
============================================================ */
import * as THREE from 'three';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
const $ = s => document.querySelector(s);
let meterLvl=null;
const lerp=(a,b,t)=>a+(b-a)*t;
const uid=()=>Math.random().toString(36).slice(2,9);
function hashHue(s){let h=0;for(let i=0;i<s.length;i++)h=(h*31+s.charCodeAt(i))>>>0;return h%360;}
/* ---------------- persistent state ---------------- */
const LS="jukebox.v2";
const defaultCfg={bloom:1,glow:1,lights:1,ambient:1,reflect:1,spin:1,particles:1,artSize:1,exposure:1,drift:1};
let state={ queue:[], current:0, shuffle:false, loop:true, volume:0.85,
mode:0, shape:"disc", spin:"record", bg:"nebula", bg2:"void", mix:0,
bg3:"void", bg4:"void", mix2:0, mix3:0, bgPreset:6, viz:[],
bgPattern:1, bgColA:"#20104a", bgColB:"#04060f", bgColC:"#b060ff",
bgIntensity:1, accentBoost:1, quality:"hq",
vizColor:"#ffcf6b", vizBassHue:false, border:0,
bgHue:0, bgMedia:null, bgMediaType:null, radio:false,
sensitivity:1.0, autoGain:true, cfg:Object.assign({},defaultCfg) };
let needBgMigrate=false;
try{const s=JSON.parse(localStorage.getItem(LS));if(s){const savedCfg=s.cfg;
if(s.bgPattern===undefined && s.bgPreset!==undefined) needBgMigrate=true; // old palette×pattern save
state=Object.assign(state,s);
state.cfg=Object.assign({},defaultCfg,savedCfg||{});}}catch(e){}
// Visualizers were once 60 colour×variant presets; now they're 14 TYPES + a free
// colour wheel. Old saved ids (0..59) map to their factory via %14, which is the
// identity for the new 0..13 type-ids — so this is safe either way. Dedupe, cap 3.
state.viz=[...new Set((state.viz||[]).map(id=>(((id|0)%14)+14)%14))].slice(0,3);
if(!(state.border>=0&&state.border<20))state.border=0;
function save(){
const q=state.queue.map(t=>({id:t.id,title:t.title,artist:t.artist,mood:t.mood,kind:t.kind,
src:t.kind==='file'?null:t.src,accent:t.accent,missing:t.kind==='file'}));
localStorage.setItem(LS,JSON.stringify({queue:q,current:state.current,shuffle:state.shuffle,
loop:state.loop,volume:state.volume,mode:state.mode,shape:state.shape,spin:state.spin,bg:state.bg,
bg2:state.bg2,mix:state.mix,bg3:state.bg3,bg4:state.bg4,mix2:state.mix2,mix3:state.mix3,
bgPreset:state.bgPreset,viz:state.viz,
bgPattern:state.bgPattern,bgColA:state.bgColA,bgColB:state.bgColB,bgColC:state.bgColC,
bgIntensity:state.bgIntensity,accentBoost:state.accentBoost,quality:state.quality,
vizColor:state.vizColor,vizBassHue:state.vizBassHue,border:state.border,
bgHue:state.bgHue,bgMedia:state.bgMedia,bgMediaType:state.bgMediaType,radio:state.radio,
sensitivity:state.sensitivity,autoGain:state.autoGain,cfg:state.cfg}));
}
/* ---------------- audio graph ---------------- */
let audioCtx,analyser,masterGain,freq,srcReal;
const elReal=new Audio(), elSim=new Audio();
elReal.crossOrigin="anonymous"; elReal.preload="auto"; elSim.preload="auto";
let activeEl=elReal, mode="real", audioReady=false;
function initAudio(){
if(audioReady)return;
audioCtx=new (window.AudioContext||window.webkitAudioContext)();
analyser=audioCtx.createAnalyser(); analyser.fftSize=4096; analyser.smoothingTimeConstant=0.6;
freq=new Uint8Array(analyser.frequencyBinCount);
masterGain=audioCtx.createGain(); masterGain.gain.value=state.volume;
srcReal=audioCtx.createMediaElementSource(elReal);
srcReal.connect(analyser); analyser.connect(masterGain); masterGain.connect(audioCtx.destination);
audioReady=true;
}
const A={bass:0,mid:0,high:0,energy:0,slow:0,warmth:0,beat:0,beatAvg:0,lastBeat:0,peak:0,agc:1};
const binHz=()=>audioCtx?audioCtx.sampleRate/analyser.fftSize:10.7;
function bandAvg(lo,hi){const hz=binHz();let a=Math.max(1,(lo/hz)|0),b=Math.min(freq.length-1,(hi/hz)|0),s=0;
for(let i=a;i<=b;i++)s+=freq[i];return (s/(b-a+1))/255;}
function analyseReal(){analyser.getByteFrequencyData(freq);
return {bass:Math.min(1,bandAvg(20,160)*1.15),mid:bandAvg(160,2000)*1.25,high:bandAvg(2000,11000)*1.7};}
let simT=0;
function analyseSim(dt,playing){
simT+=dt*(playing?1:0.25);
const bpm=112,bl=60/bpm,ph=(simT%bl)/bl,kick=Math.pow(1-ph,3.2),swell=0.5+0.5*Math.sin(simT*0.13),
shimmer=0.5+0.5*Math.sin(simT*1.9+Math.sin(simT*0.4)*2),e=playing?1:0.32;
return {bass:(0.18+0.6*kick*swell)*e,mid:(0.16+0.4*shimmer*swell)*e,
high:(0.10+0.5*Math.max(0,Math.sin(simT*7.3))*shimmer)*e};
}
/* ---------------- playback ---------------- */
let isPlaying=false,started=false,swap={active:false,t:0};
const fmt=s=>{s=Math.max(0,s|0);return (s/60|0)+":"+("0"+(s%60)).slice(-2);};
function softThunk(){if(!audioReady)return;const t=audioCtx.currentTime,o=audioCtx.createOscillator(),g=audioCtx.createGain();
o.type="sine";o.frequency.setValueAtTime(120,t);o.frequency.exponentialRampToValueAtTime(42,t+.12);
g.gain.setValueAtTime(.0001,t);g.gain.exponentialRampToValueAtTime(.16,t+.01);g.gain.exponentialRampToValueAtTime(.0001,t+.22);
o.connect(g);g.connect(masterGain);o.start(t);o.stop(t+.25);}
function setVolume(v){state.volume=Math.max(0,Math.min(1,v));if(audioReady)masterGain.gain.value=state.volume;elSim.volume=state.volume;save();drawVol();}
function loadReal(src){return new Promise((res,rej)=>{let done=false;
const ok=()=>{if(done)return;done=true;cl();res();},err=()=>{if(done)return;done=true;cl();rej();};
const cl=()=>{elReal.removeEventListener("canplay",ok);elReal.removeEventListener("error",err);clearTimeout(to);};
const to=setTimeout(err,7000);elReal.addEventListener("canplay",ok);elReal.addEventListener("error",err);
elReal.src=src;elReal.load();});}
async function playTrack(i){
if(!state.queue.length)return;
i=((i%state.queue.length)+state.queue.length)%state.queue.length;
const prev=state.current; state.current=i; const t=state.queue[i];
if(i!==prev){swap.active=true;swap.t=0;softThunk();}
initAudio(); if(audioCtx.state==="suspended")await audioCtx.resume();
ensureTex(t); applyTex(t); buildFace(t); renderRows();
try{elReal.pause();}catch(e){} try{elSim.pause();}catch(e){}
if(t.missing){t.mood="re-add file";updateNowPlaying();return;}
if(t.kind==="file"){activeEl=elReal;mode="real";t.mode="real";elReal.src=t.src;
try{await elReal.play();isPlaying=true;}catch(e){isPlaying=false;}}
else{ try{await loadReal(t.src);activeEl=elReal;mode="real";t.mode="real";await elReal.play();isPlaying=true;}
catch(e){activeEl=elSim;mode="sim";t.mode="sim";elSim.src=t.src;elSim.volume=state.volume;
try{await elSim.play();isPlaying=true;}catch(e2){isPlaying=false;t.mood="unreachable";}}}
started=true;updatePlayIcon();updateNowPlaying();renderRows();save();
}
function togglePlay(){if(!started){gateOpen();return;}
if(isPlaying){activeEl.pause();isPlaying=false;}else{initAudio();audioCtx.resume();activeEl.play();isPlaying=true;}updatePlayIcon();}
function nextTrack(){if(!state.queue.length)return;maybeTopUp();let n;
if(state.shuffle&&state.queue.length>1){do{n=Math.random()*state.queue.length|0;}while(n===state.current);}else n=state.current+1;
if(n>=state.queue.length&&!state.loop&&!state.shuffle){
if(state.radio){fetchFeedBatch(12).then(a=>{if(a)playTrack(n);else{activeEl.pause();isPlaying=false;updatePlayIcon();}});return;}
activeEl.pause();isPlaying=false;updatePlayIcon();return;}playTrack(n);}
function prevTrack(){if(activeEl.currentTime>3){activeEl.currentTime=0;return;}playTrack(state.current-1);}
elReal.addEventListener("ended",()=>{if(mode==="real")nextTrack();});
elSim.addEventListener("ended",()=>{if(mode==="sim")nextTrack();});
/* ---------------- artwork: thumbnail (disc) + 3D texture ---------------- */
const SRGB=THREE.SRGBColorSpace;
const hsl=(h,s,l)=>{h=((h%360)+360)%360/360;const q=l<.5?l*(1+s):l+s-l*s,p=2*l-q;
const f=t=>{t=(t+1)%1;return t<1/6?p+(q-p)*6*t:t<.5?q:t<2/3?p+(q-p)*(2/3-t)*6:p;};
return [f(h+1/3)*255,f(h)*255,f(h-1/3)*255];};
const rgba=(c,a)=>`rgba(${c[0]|0},${c[1]|0},${c[2]|0},${a})`;
function buildFace(t){ if(t._face)return;
const S=256,cv=document.createElement("canvas");cv.width=cv.height=S;const c=cv.getContext("2d");
const cx=S/2,cy=S/2,R=S/2-3;
const g=c.createRadialGradient(cx,cy,8,cx,cy,R);g.addColorStop(0,"#15161c");g.addColorStop(.7,"#0c0d12");g.addColorStop(1,"#050507");
c.beginPath();c.arc(cx,cy,R,0,7);c.fillStyle=g;c.fill();
for(let r=R-5;r>R*0.32;r-=3){c.beginPath();c.arc(cx,cy,r,0,7);c.strokeStyle="rgba(217,164,65,"+(0.02+Math.random()*0.03)+")";c.lineWidth=1;c.stroke();}
c.beginPath();c.arc(cx,cy,R,0,7);c.lineWidth=3;c.strokeStyle=rgba(hsl(t.accent,0.5,0.55),0.85);c.stroke();
const lr=R*0.3,lg=c.createRadialGradient(cx,cy,2,cx,cy,lr);
lg.addColorStop(0,rgba(hsl(t.accent,0.55,0.45),1));lg.addColorStop(1,rgba(hsl(t.accent,0.6,0.22),1));
c.beginPath();c.arc(cx,cy,lr,0,7);c.fillStyle=lg;c.fill();
c.beginPath();c.arc(cx,cy,4,0,7);c.fillStyle="#070708";c.fill();
t._face=cv; t._thumb=cv.toDataURL("image/png");
}
function drawArt(t,S=512){
const cv=document.createElement("canvas");cv.width=cv.height=S;const c=cv.getContext("2d");
const g=c.createLinearGradient(0,0,S,S);
g.addColorStop(0,rgba(hsl(t.accent,0.55,0.30),1));g.addColorStop(.55,rgba(hsl(t.accent+18,0.6,0.13),1));g.addColorStop(1,rgba(hsl(t.accent-20,0.5,0.06),1));
c.fillStyle=g;c.fillRect(0,0,S,S);
c.globalCompositeOperation="lighter";
for(let i=0;i<5;i++){const rg=c.createRadialGradient(S*Math.random(),S*Math.random(),0,S/2,S/2,S*0.7);
rg.addColorStop(0,rgba(hsl(t.accent+i*30,0.6,0.5),0.05));rg.addColorStop(1,"rgba(0,0,0,0)");c.fillStyle=rg;c.fillRect(0,0,S,S);}
c.globalCompositeOperation="source-over";
const vg=c.createRadialGradient(S/2,S/2,S*0.2,S/2,S/2,S*0.72);vg.addColorStop(0,"rgba(0,0,0,0)");vg.addColorStop(1,"rgba(0,0,0,.6)");
c.fillStyle=vg;c.fillRect(0,0,S,S);
const txt=(t.title||"").toUpperCase(),words=txt.split(" ");let lines=[],cur="";
c.font="600 46px Georgia,serif";
for(const w of words){const tn=cur?cur+" "+w:w;if(c.measureText(tn).width>S*0.8&&cur){lines.push(cur);cur=w;}else cur=tn;}
if(cur)lines.push(cur);lines=lines.slice(0,3);
c.textAlign="center";c.textBaseline="middle";c.fillStyle="rgba(245,238,222,.95)";
c.shadowColor=rgba(hsl(t.accent,0.7,0.5),0.8);c.shadowBlur=24;
const lh=54,y0=S/2-(lines.length-1)*lh/2;lines.forEach((l,i)=>c.fillText(l,S/2,y0+i*lh));
c.shadowBlur=0;
if(t.artist){c.font="italic 26px Georgia,serif";c.fillStyle=rgba(hsl(t.accent,0.55,0.66),0.9);
c.fillText(t.artist.toUpperCase(),S/2,y0+lines.length*lh+6);}
c.font="600 18px Georgia,serif";c.fillStyle=rgba(hsl(t.accent,0.6,0.6),0.7);
c.fillText((t.mood||"SUNO").toUpperCase(),S/2,S*0.86);
return cv;
}
const texLoader=new THREE.TextureLoader();texLoader.crossOrigin="anonymous";
// Suno cover-art lives at predictable URLs keyed by the song uuid (prefix varies, so try a few).
const sunoArt=id=>["https://cdn2.suno.ai/image_large_"+id+".jpeg",
"https://cdn2.suno.ai/image_"+id+".jpeg",
"https://cdn1.suno.ai/image_"+id+".png"];
function artCandidates(t){ if(t.art)return t.art; if(t.img)return (t.art=[t.img]);
const m=(t.src||"").match(UUID); return (t.art=m?sunoArt(m[0]):[]); }
function tryArt(t,list,i){ if(i>=list.length)return; // exhausted → keep procedural art
texLoader.load(list[i],tx=>{tx.colorSpace=SRGB;tx.anisotropy=MAXANISO;t._tex=tx;t._artUrl=list[i];
if(state.queue[state.current]===t)applyTex(t);},undefined,()=>tryArt(t,list,i+1)); }
function ensureTex(t){ if(t._tex)return t._tex;
// start with procedural art immediately, then swap in real cover art when/if it loads (CORS-permitting)
t._tex=new THREE.CanvasTexture(drawArt(t)); t._tex.colorSpace=SRGB; t._tex.anisotropy=MAXANISO;
const cands=artCandidates(t); if(cands.length)tryArt(t,cands,0);
return t._tex;
}
// Eagerly resolve a track's REAL cover art (Suno CDN) for the lobby thumbnail — runs for every
// queued track, not just the playing one, so the actual album art shows in the list. Uses a plain
// <img> probe (no WebGL needed) that walks the candidate list and caches the first that loads.
function prefetchArt(t){
if(t._artUrl||t._artTried)return;
const cands=artCandidates(t); if(!cands.length)return;
t._artTried=true;
(function next(i){ if(i>=cands.length)return;
const im=new Image(); im.crossOrigin="anonymous";
im.onload=()=>{ t._artUrl=t._thumb=cands[i];
const el=rowsEl&&rowsEl.querySelector('.row[data-id="'+t.id+'"] .thumb img'); if(el)el.src=cands[i];
if(state.queue[state.current]===t&&artMat&&!t._tex3d){ t._tex3d=true;
texLoader.load(cands[i],tx=>{tx.colorSpace=SRGB;tx.anisotropy=MAXANISO;t._tex=tx;applyTex(t);}); } };
im.onerror=()=>next(i+1);
im.src=cands[i];
})(0);
}
/* ---------------- queue building ---------------- */
const UUID=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
function parseLink(raw){const url=raw.trim();if(!url)return null;
if(/suno\.(com|ai)/i.test(url)){
if(/\/playlist\//i.test(url))return {error:"Suno playlists can't expand in-browser — paste each song link, or import a saved set."};
const m=url.match(UUID);if(m)return {kind:"suno",src:"https://cdn1.suno.ai/"+m[0]+".mp3",title:"Suno • "+m[0].slice(0,6)};
const sm=url.match(/\/s\/([A-Za-z0-9_-]{6,})/)||url.match(/[?&]sh=([A-Za-z0-9_-]{6,})/);
if(sm)return {kind:"suno-short",code:sm[1]};
return {error:"Couldn't read a song id from that Suno link — use the /song/ link."};}
if(/^https?:\/\/.+\.(mp3|wav|ogg|m4a|aac|flac)(\?.*)?$/i.test(url)||/audiopipe\.suno|cdn\d*\.suno/i.test(url)){
const m=url.match(UUID);return {kind:"url",src:url,title:m?("Suno • "+m[0].slice(0,6)):decodeURIComponent(url.split("/").pop().split("?")[0].replace(/\.\w+$/,"")).slice(0,40)||"Track"};}
if(/^https?:\/\//i.test(url))return {kind:"url",src:url,title:"Track"};
return {error:"Not a recognized link: "+url.slice(0,40)};}
function addTrack(o){const t={id:uid(),title:o.title||"Track",artist:o.artist||"",mood:o.mood||"",kind:o.kind,src:o.src,img:o.img||null,
accent:o.accent!=null?o.accent:hashHue((o.title||"")+o.src),mode:"unknown",missing:!!o.missing};state.queue.push(t);return t;}
// Resolve a Suno /s/{code} share link to its song UUID. Suno's redirect has no CORS
// headers, so the browser can't read it directly — we first ask our own local server
// (serve.py /resolve endpoint) to follow the redirect server-side. Falls back to a
// best-effort direct fetch (works only if the page happens to allow it), then null.
async function resolveSunoShort(code){
try{const r=await fetch(location.origin+"/resolve?code="+encodeURIComponent(code));
if(r.ok){const j=await r.json();if(j&&j.uuid&&UUID.test(j.uuid))return j.uuid.match(UUID)[0];}
}catch(e){/* server hop unavailable (e.g. not running via serve.py) — fall through */}
const urls=["https://suno.com/s/"+code,"https://suno.com/song/"+code];
for(const u of urls){
try{const r=await fetch(u,{redirect:"follow"});
let m=(r.url||"").match(UUID);if(m)return m[0];
const txt=await r.text();m=txt.match(UUID);if(m)return m[0];
}catch(e){/* CORS or network — fall through */}
}
return null;
}
// Each pasted line may carry a label before the URL: "Title | Artist | <url>" (or "Title — Artist <url>", "Title <url>").
async function addLinks(text){const lines=text.split(/\n+/).map(s=>s.trim()).filter(Boolean);let added=0,errs=[];
for(const line of lines){const um=line.match(/https?:\/\/\S+/);const url=um?um[0]:line;
const label=um?line.slice(0,um.index).trim().replace(/[|\-–—:]+$/,"").trim():"";
const p=parseLink(url);if(!p)continue;if(p.error){errs.push(p.error);continue;}
if(p.kind==="suno-short"){
flash("Resolving Suno share link…");
const uuid=await resolveSunoShort(p.code);
if(!uuid){errs.push("Suno /s/ link couldn't be resolved in-browser — open it once and paste the /song/… URL it lands on.");continue;}
p.kind="suno";p.src="https://cdn1.suno.ai/"+uuid+".mp3";p.title="Suno • "+uuid.slice(0,6);delete p.code;}
if(label){const parts=label.split(/\s*[|–—]\s*|\s+-\s+/).map(s=>s.trim()).filter(Boolean);
p.title=parts[0]||p.title;if(parts.length>1)p.artist=parts.slice(1).join(" ");}
addTrack(p);added++;}
if(added){renderRows();save();}$("#links").value="";if(errs.length)flash(errs[0]);if(added)flash(added+" added to the set");return added;}
function addFiles(list){let audio=0;
for(const f of list){if(f.type.startsWith("audio/")){addTrack({kind:"file",src:URL.createObjectURL(f),title:f.name.replace(/\.\w+$/,"").slice(0,40)});audio++;}
else if(f.type.startsWith("image/"))setUserBg(URL.createObjectURL(f),"image");
else if(f.type.startsWith("video/"))setUserBg(URL.createObjectURL(f),"video");}
if(audio){renderRows();save();flash(audio+" file"+(audio>1?"s":"")+" added");}}
function removeTrack(id){const i=state.queue.findIndex(t=>t.id===id);if(i<0)return;const wasCur=i===state.current;
state.queue.splice(i,1);if(i<state.current)state.current--;if(state.current>=state.queue.length)state.current=Math.max(0,state.queue.length-1);
renderRows();save();if(wasCur&&state.queue.length)playTrack(state.current);
if(!state.queue.length){activeEl.pause();isPlaying=false;updatePlayIcon();updateNowPlaying();}}
function exportQueue(){const data={name:"Jukebox set",exported:new Date().toISOString(),
tracks:state.queue.filter(t=>t.kind!=="file").map(t=>({title:t.title,artist:t.artist,mood:t.mood,kind:t.kind,src:t.src,accent:t.accent}))};
const b=new Blob([JSON.stringify(data,null,2)],{type:"application/json"});const a=document.createElement("a");
a.href=URL.createObjectURL(b);a.download="jukebox-set.json";a.click();flash("Set exported ("+data.tracks.length+" tracks)");}
function importQueue(file){const r=new FileReader();r.onload=()=>{try{const d=JSON.parse(r.result);const arr=Array.isArray(d)?d:d.tracks||[];
let n=0;for(const t of arr){if(t.src){addTrack({kind:t.kind||"url",src:t.src,title:t.title,artist:t.artist,mood:t.mood,accent:t.accent});n++;}}
renderRows();save();flash(n+" imported");}catch(e){flash("Couldn't read that file");}};r.readAsText(file);}
/* ---------------- favourites (saved across sessions, own storage key) ---------------- */
const FAVS="jukebox.favs";
let favs=[]; try{favs=JSON.parse(localStorage.getItem(FAVS))||[];}catch(e){favs=[];}
const favKey=t=>t.src||t.id||t.title;
function isFav(t){const k=favKey(t);return favs.some(f=>favKey(f)===k);}
function saveFavs(){try{localStorage.setItem(FAVS,JSON.stringify(favs));}catch(e){}updateFavCount();}
function toggleFav(t){if(!t)return;const k=favKey(t);const i=favs.findIndex(f=>favKey(f)===k);
if(i>=0){favs.splice(i,1);flash("Removed from favourites");}
else{favs.push({title:t.title,artist:t.artist,mood:t.mood,kind:t.kind==="file"?"url":(t.kind||"url"),
src:t.src,img:t.img||null,accent:t.accent});flash("♥ Saved to favourites");}
saveFavs();renderRows();updateFavBtn();}
function loadFavs(){if(!favs.length){flash("No favourites yet — tap ♥ on a song");return;}
let n=0;for(const f of favs){if(f.src){addTrack({kind:f.kind||"url",src:f.src,title:f.title,artist:f.artist,mood:f.mood,img:f.img,accent:f.accent});n++;}}
renderRows();save();flash(n+" favourite"+(n>1?"s":"")+" queued");
if(!isPlaying&&state.queue.length)playTrack(state.queue.length-n);}
function updateFavCount(){const e=$("#favCount");if(e)e.textContent=favs.length;}
function updateFavBtn(){const b=$("#favBtn");if(!b)return;const t=state.queue[state.current];const on=t&&isFav(t);
b.classList.toggle("on",!!on);b.title=on?"Remove from favourites":"Save to favourites";}
/* ---------------- Suno discover feed + radio (idle auto-fill) ---------------- */
// Songs come from serve.py's /feed proxy (Suno's CORS blocks a direct browser call).
let feedCursor="", feedBusy=false; const feedName="new_songs";
async function fetchFeedBatch(n){n=n||12;
if(feedBusy)return 0; feedBusy=true;
try{
const u=location.origin+"/feed?feed="+feedName+"&n="+n+(feedCursor?"&cursor="+encodeURIComponent(feedCursor):"");
const r=await fetch(u); if(!r.ok)throw new Error("feed "+r.status);
const j=await r.json();
if(j.error||!j.items||!j.items.length){flash(j.error?"Feed needs serve.py (launch via the .bat)":"No more new songs right now");return 0;}
feedCursor=j.next_cursor||"";
let added=0;for(const it of j.items){if(!it.src)continue;
addTrack({kind:"url",src:it.src,title:it.title,artist:it.artist,mood:it.mood,img:it.img,accent:hashHue((it.title||"")+it.src)});added++;}
if(added){renderRows();save();}
return added;
}catch(e){flash("Couldn't reach the Suno feed — launch with start-jukebox-hq.bat");return 0;}
finally{feedBusy=false;}
}
async function discoverNew(){const wasEmpty=!state.queue.length;flash("Fetching new songs from Suno…");
const n=await fetchFeedBatch(12);if(n){flash(n+" new songs added");if(wasEmpty)playTrack(0);}}
function maybeTopUp(){ // idle radio: keep the queue fed so playback never runs dry
if(state.radio&&!feedBusy&&(state.queue.length-state.current)<=2)fetchFeedBatch(12);}
function updateRadioBtn(){const b=$("#radioBtn");if(b)b.classList.toggle("on",!!state.radio);}
function toggleRadio(){state.radio=!state.radio;save();updateRadioBtn();
if(state.radio){flash("Radio on — streaming fresh Suno songs");
if(!state.queue.length)discoverNew();
else maybeTopUp();
}else flash("Radio off");}
/* ---------------- DOM render ---------------- */
const rowsEl=$("#rows");
const esc=s=>(s||"").replace(/[&<>"]/g,c=>({"&":"&","<":"<",">":">",'"':"""}[c]));
function renderRows(){
$("#count").textContent=state.queue.length; rowsEl.innerHTML="";
state.queue.forEach((t,i)=>{ if(!t._face)buildFace(t); prefetchArt(t);
const row=document.createElement("div");row.className="row"+(i===state.current?" active":"");
row.draggable=true;row.dataset.id=t.id;
const cls=t.missing?"missing":(t.mode==="sim"?"sim":"");
row.innerHTML=`${i===state.current?'<span class="glowbar"></span>':''}<span class="dot ${cls}"></span>
<span class="thumb"><img src="${t._artUrl||t._thumb||''}" data-fallback="${t._thumb||''}" alt="" onerror="if(this.dataset.fallback&&this.src!==this.dataset.fallback){this.src=this.dataset.fallback;}"></span>
<span class="meta"><span class="title">${esc(t.title)}</span><span class="tag" title="Double-click to set artist">${esc(t.artist||(t.missing?'re-add file':(t.mood||(t.kind==='file'?'local':'suno'))))}</span></span>
<span class="heart${isFav(t)?' on':''}" title="Favourite">♥</span>
<span class="x" title="Remove">×</span>`;
row.addEventListener("click",e=>{if(e.target.classList.contains("x")){removeTrack(t.id);return;}
if(e.target.classList.contains("heart")){e.stopPropagation();toggleFav(t);return;}playTrack(i);});
const refreshArt=()=>{t._face=null;t._tex=null;buildFace(t);renderRows();save();if(i===state.current){ensureTex(t);applyTex(t);updateNowPlaying();}};
row.querySelector(".title").addEventListener("dblclick",e=>{e.stopPropagation();const n=prompt("Track name:",t.title);
if(n){t.title=n.trim();refreshArt();}});
row.querySelector(".tag").addEventListener("dblclick",e=>{e.stopPropagation();const n=prompt("Artist:",t.artist||"");
if(n!==null){t.artist=n.trim();refreshArt();}});
row.addEventListener("dragstart",e=>{e.dataTransfer.setData("id",t.id);row.style.opacity=".4";});
row.addEventListener("dragend",()=>row.style.opacity="");
row.addEventListener("dragover",e=>e.preventDefault());
row.addEventListener("drop",e=>{e.preventDefault();e.stopPropagation();const id=e.dataTransfer.getData("id");if(!id||id===t.id)return;
const from=state.queue.findIndex(x=>x.id===id),cur=state.queue[state.current].id,[m]=state.queue.splice(from,1);
state.queue.splice(i,0,m);state.current=state.queue.findIndex(x=>x.id===cur);renderRows();save();});
rowsEl.appendChild(row);
});
}
function updatePlayIcon(){$("#play").innerHTML=isPlaying?"❚❚":"►";}
function updateNowPlaying(){const t=state.queue[state.current],np=$("#nowp");if(!t){np.classList.remove("show");return;}
$("#npTitle").textContent=t.title;
const a=$("#npArtist");a.textContent=t.artist||"";a.style.display=t.artist?"":"none";
$("#npMood").textContent=t.mood||(t.mode==="sim"?"ambient sync":"now playing");
np.classList.add("show");clearTimeout(np._h);np._h=setTimeout(()=>np.classList.remove("show"),4500);
updateFavBtn();}
let toast,toastH;
function flash(msg){if(!toast){toast=document.createElement("div");toast.style.cssText=
"position:absolute;left:50%;top:24px;transform:translateX(-50%);z-index:60;padding:9px 18px;border-radius:20px;background:rgba(14,15,20,.85);border:1px solid var(--line);color:var(--gold-soft);font-size:13px;letter-spacing:.1em;backdrop-filter:blur(8px);opacity:0;transition:opacity .3s;pointer-events:none;max-width:80vw;text-align:center";
$("#stage").appendChild(toast);}
toast.textContent=msg;toast.style.opacity="1";clearTimeout(toastH);toastH=setTimeout(()=>toast.style.opacity="0",2600);}
function drawVol(){$("#volFill").style.width=(state.volume*100)+"%";$("#volKnob").style.left=(state.volume*100)+"%";}
/* ================= THREE.JS SCENE ================= */
const canvas=$("#scene");
const renderer=new THREE.WebGLRenderer({canvas,antialias:true,alpha:false,powerPreference:"high-performance"});
const MAXANISO=renderer.capabilities.getMaxAnisotropy();
function qualityPR(){const d=window.devicePixelRatio||1,q=state.quality||"hq";
return q==="hq"?Math.min(2,d):q==="balanced"?Math.min(1.5,d):1;}
renderer.setPixelRatio(qualityPR());
renderer.toneMapping=THREE.ACESFilmicToneMapping; renderer.toneMappingExposure=1.0;
const scene=new THREE.Scene();
const camera=new THREE.PerspectiveCamera(45,1,0.1,200); camera.position.set(0,0,4.6);
const pmrem=new THREE.PMREMGenerator(renderer);
scene.environment=pmrem.fromScene(new RoomEnvironment(),0.04).texture;
const ENV=0.4; // global reflection scale — lower = less "turbo" env reflection on the centerpiece
/* postprocessing */
const composer=new EffectComposer(renderer);
composer.addPass(new RenderPass(scene,camera));
const bloom=new UnrealBloomPass(new THREE.Vector2(1,1),0.8,0.6,0.8);
composer.addPass(bloom);
composer.addPass(new OutputPass());
/* ----- backdrop sphere (shader: void/nebula/aurora/grid) ----- */
const bgUniforms={uTime:{value:0},uEnergy:{value:0},uMode:{value:1},uMode2:{value:0},uMode3:{value:0},uMode4:{value:0},
uMix:{value:0},uMix2:{value:0},uMix3:{value:0},uBgInt:{value:1},
uMedia:{value:null},uMediaOn:{value:0},uHue:{value:0},uMediaAspect:{value:1.777},uRes:{value:new THREE.Vector2(1,1)},
uColA:{value:new THREE.Color(0x20104a)},uColB:{value:new THREE.Color(0x04060f)},uColC:{value:new THREE.Color(0xb060ff)}};
const backdrop=new THREE.Mesh(new THREE.SphereGeometry(80,96,64),new THREE.ShaderMaterial({
side:THREE.BackSide,depthWrite:false,uniforms:bgUniforms,
vertexShader:`varying vec3 vDir;void main(){vDir=normalize(position);gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);}`,
fragmentShader:`precision highp float;varying vec3 vDir;uniform float uTime,uEnergy,uMode,uMode2,uMode3,uMode4,uMix,uMix2,uMix3,uBgInt;uniform vec3 uColA,uColB,uColC;
uniform sampler2D uMedia;uniform float uMediaOn,uHue,uMediaAspect;uniform vec2 uRes;
vec3 hueShift(vec3 c,float a){const vec3 k=vec3(0.57735);float ca=cos(a),sa=sin(a);return c*ca+cross(k,c)*sa+k*dot(k,c)*(1.0-ca);}
float hash(vec3 p){p=fract(p*0.3183+0.1);p*=17.0;return fract(p.x*p.y*p.z*(p.x+p.y+p.z));}
float noise(vec3 x){vec3 i=floor(x),f=fract(x);f=f*f*(3.0-2.0*f);
return mix(mix(mix(hash(i),hash(i+vec3(1,0,0)),f.x),mix(hash(i+vec3(0,1,0)),hash(i+vec3(1,1,0)),f.x),f.y),
mix(mix(hash(i+vec3(0,0,1)),hash(i+vec3(1,0,1)),f.x),mix(hash(i+vec3(0,1,1)),hash(i+vec3(1,1,1)),f.x),f.y),f.z);}
float fbm(vec3 p){float v=0.0,a=0.5;for(int i=0;i<5;i++){v+=a*noise(p);p*=2.02;a*=0.5;}return v;}
vec3 bg(vec3 d, float uMode){float t=uTime;vec3 col=vec3(0.0);
if(uMode<0.5){float g=smoothstep(-0.6,0.8,d.y);col=mix(uColB*0.5,uColA*0.5,g)+uColA*0.04;}
else if(uMode<1.5){float n=fbm(d*2.5+vec3(t*0.02,t*0.012,0.0));float n2=fbm(d*5.0-vec3(0.0,t*0.03,t*0.02));
col=mix(uColB*0.18,uColA,n*n)*(0.55+0.7*uEnergy);col+=uColC*pow(n2,3.0)*1.3;
col*=0.45+0.55*smoothstep(-0.8,0.6,d.y);col+=0.012;}
else if(uMode<2.5){float band=fbm(vec3(d.x*2.0+t*0.06,d.z*2.0,t*0.05));
float curtain=smoothstep(0.2,0.9,band)*smoothstep(0.95,-0.2,d.y);
col=mix(uColA,uColC,sin(d.x*3.0+t*0.3)*0.5+0.5)*curtain*(0.7+uEnergy);col+=uColB*0.05*smoothstep(-0.4,0.7,d.y);}
else if(uMode<3.5){float horizon=smoothstep(0.02,-0.02,d.y);vec3 sky=mix(uColB,uColA,smoothstep(0.0,0.7,d.y));
float sun=smoothstep(0.17,0.15,length(vec2(d.x,d.y-0.18)));sky+=uColC*sun*1.4;
vec2 gp=vec2(d.x,d.z)/max(0.04,-d.y);vec2 g2=abs(fract(gp*4.0+vec2(0.0,t*0.6))-0.5);
float line=smoothstep(0.46,0.5,max(g2.x,g2.y));vec3 fl=mix(uColB*0.25,uColC,line)*smoothstep(0.0,-0.04,d.y);
col=mix(sky,fl,horizon);}
else if(uMode<4.5){vec3 cell=floor(d*70.0);float h=hash(cell);
float star=smoothstep(0.985,1.0,h)*(0.6+0.4*sin(t*3.0+h*40.0));
vec3 base=mix(uColB*0.35,uColA*0.25,smoothstep(-0.6,0.7,d.y));
base+=uColC*fbm(d*1.4+vec3(0.0,0.0,t*0.01))*0.05;
col=base+vec3(star*(1.0+uEnergy*1.5));}
else if(uMode<5.5){float p=fbm(d*3.0+vec3(t*0.09,t*0.05,t*0.03));
float q=fbm(d*6.5-vec3(t*0.06,0.0,t*0.045));
col=mix(uColB,uColA,p)+uColC*pow(q,2.0)*1.3;col*=0.45+0.85*uEnergy;col+=0.02;}
else if(uMode<6.5){float rad=length(d.xy)+0.02;float a=atan(d.y,d.x);
float rings=sin((1.0/rad)*7.0-t*1.6);float v=smoothstep(0.1,1.0,rings*0.5+0.5);
float swirl=0.5+0.5*sin(a*6.0+t*0.5);
col=mix(uColB*0.15,uColC,v*swirl)*(0.5+uEnergy)+uColA*0.06;}
else if(uMode<7.5){float w=sin(d.x*4.0+t*0.4+fbm(d*2.0+vec3(0.0,t*0.05,0.0))*4.0);
float r=smoothstep(0.55,1.0,w);float w2=sin(d.z*5.0-t*0.3+fbm(d*3.0)*3.0);
float r2=smoothstep(0.7,1.0,w2);
col=mix(uColB*0.12,uColA,r)+uColC*r2*0.7;col*=0.55+0.7*uEnergy;}
else if(uMode<8.5){vec2 p=d.xy/(abs(d.z)+0.25);float r=length(p)+1e-4;float a=atan(p.y,p.x);
float zoom=log2(r)*2.0-t*0.5;float ring=fract(zoom);float ringId=floor(zoom);
float sectors=16.0;float ang=a*0.1591549+0.5;float cellA=fract(ang*sectors);float sectId=floor(ang*sectors);
vec2 cuv=vec2(cellA,ring)*2.0-1.0;
float seam=smoothstep(0.72,0.98,max(abs(cuv.x),abs(cuv.y)));
float thread=smoothstep(0.16,0.0,abs(abs(cuv.x)-abs(cuv.y)));
float chk=mod(ringId+sectId,2.0);
vec3 quiltc=mix(uColB*0.6,uColA,0.2+0.6*chk);quiltc=mix(quiltc,uColC,0.25*thread);
col=quiltc*(0.4+0.7*uEnergy)+uColC*seam*0.55;col*=smoothstep(2.6,0.15,r);}
else if(uMode<9.5){vec2 p=d.xy/(abs(d.z)+0.3);float a=atan(p.y,p.x),r=length(p);
float seg=0.785398;a=abs(mod(a,2.0*seg)-seg);vec2 q=vec2(cos(a),sin(a))*r;
float pat=fbm(vec3(q*3.0,t*0.1));
col=mix(uColB,uColA,pat)+uColC*pow(fbm(vec3(q*6.0,t*0.2)),2.0)*1.2;col*=0.5+0.7*uEnergy;}
else if(uMode<10.5){float n=fbm(d*2.0+vec3(0.0,t*0.12,0.0));
float blob=smoothstep(0.45,0.75,n+0.15*sin(t*0.4));
col=mix(uColB*0.2,uColA,blob)+uColC*smoothstep(0.6,0.8,n)*1.4;col*=0.5+0.7*uEnergy;}
else if(uMode<11.5){float r=length(d.xy)/(abs(d.z)+0.3);
float pulse=sin(r*10.0-t*3.0-uEnergy*6.0);float v=smoothstep(0.3,1.0,pulse*0.5+0.5);
col=mix(uColB*0.15,uColC,v)+uColA*0.05;}
else if(uMode<12.5){vec2 p=d.xy/(abs(d.z)+0.3);float a=atan(p.y,p.x);float r=length(p);
float bars=fbm(vec3(a*4.0,t*0.5,0.0));float lvl=bars*(0.5+uEnergy*1.5);
float on=smoothstep(lvl+0.02,lvl-0.02,r*0.5);
col=mix(uColB*0.1,mix(uColA,uColC,r*0.5),on)*(0.6+uEnergy);}
else if(uMode<13.5){vec3 q=d*4.0;float c=0.0;
for(int i=0;i<3;i++){float fi=float(i);
c+=abs(sin(q.x*1.5+t*0.6+fi)+sin(q.y*1.5+t*0.5+fi)+sin(q.z*1.5+t*0.4+fi));q*=1.3;}
c=pow(max(0.0,3.0-c)*0.5,2.0);
col=mix(uColB*0.15,uColA,c)+uColC*c*0.8;col*=0.6+0.6*uEnergy;}
else if(uMode<14.5){vec2 p=d.xy/(abs(d.z)+0.3)*4.0;
p.x*=1.1547;p.y+=mod(floor(p.x),2.0)*0.5;vec2 f=fract(p)-0.5;
float hex=smoothstep(0.35,0.5,max(abs(f.x)*0.866+abs(f.y)*0.5,abs(f.y)));
float gl2=0.5+0.5*sin(t*1.5+hash(vec3(floor(p),0.0))*30.0);
col=mix(uColA*0.4,uColB*0.1,hex)+uColC*(1.0-hex)*gl2*(0.5+uEnergy);}
else if(uMode<15.5){vec2 p=d.xy/(abs(d.z)+0.3);
float w=sin(length(p-vec2(0.4,0.0))*9.0-t*2.0)+sin(length(p+vec2(0.4,0.0))*9.0-t*2.2);
float v=smoothstep(0.0,1.5,w+1.0);
col=mix(uColB*0.12,uColC,v)+uColA*0.06;col*=0.6+0.7*uEnergy;}
else if(uMode<16.5){vec2 p=d.xy/(abs(d.z)+0.3);float a=atan(p.y,p.x),r=length(p);
float arms=sin(a*2.0+log(r+0.1)*6.0-t*0.4);
float v=smoothstep(0.1,1.0,arms*0.5+0.5)*smoothstep(1.6,0.1,r);float core=smoothstep(0.25,0.0,r);
col=mix(uColB*0.1,uColA,v)+uColC*(v*0.7+core*1.5);col*=0.6+0.6*uEnergy;}
else if(uMode<17.5){vec2 p=d.xy/(abs(d.z)+0.2);float r=length(p)+1e-4;float a=atan(p.y,p.x);
float z=1.0/r+t*0.8;float tex=fbm(vec3(a*1.5,z,z*0.5));float v=smoothstep(0.3,0.8,tex);
col=mix(uColB*0.1,uColC,v)*smoothstep(2.2,0.1,r)+uColA*0.05;col*=0.5+0.8*uEnergy;}
else if(uMode<18.5){vec2 p=d.xy/(abs(d.z)+0.3)*vec2(14.0,10.0);
float ci=floor(p.x);float spd=0.5+hash(vec3(ci,0.0,0.0));float yy=fract(p.y*0.1-t*spd*0.3);
float head=smoothstep(0.0,0.08,yy)*smoothstep(0.5,0.0,yy);
float ch=step(0.5,hash(vec3(ci,floor(p.y),floor(t*4.0))));
col=uColC*head*ch*(0.6+uEnergy)+uColB*0.04;}
else if(uMode<19.5){vec3 q=d*3.0;float m2=0.0;
for(int i=0;i<4;i++){float fi=float(i+1);
vec3 pp=q+vec3(0.0,t*0.3*fi,0.0);float n=hash(floor(pp*3.0));
m2+=smoothstep(0.96,1.0,n)*fract(pp.y);}
col=uColB*0.08+uColC*m2*(0.8+uEnergy)+uColA*0.04*smoothstep(-0.5,0.8,d.y);}
else if(uMode<20.5){vec2 p=d.xy/(abs(d.z)+0.3)*2.0;float m=0.0;
for(int i=0;i<4;i++){float fi=float(i);vec2 c=vec2(sin(t*0.5+fi*1.7),cos(t*0.4+fi*2.3))*1.1;
m+=0.18/(length(p-c)+0.05);}
float v=smoothstep(1.0,2.2,m);
col=mix(uColB*0.15,uColA,v)+uColC*smoothstep(1.8,2.7,m)*1.2;col*=0.5+0.7*uEnergy;}
else if(uMode<21.5){vec2 p=d.xy/(abs(d.z)+0.3);
vec3 sky=mix(uColB*0.15,uColA*0.6,smoothstep(-0.4,0.8,p.y));
float sun=smoothstep(0.55,0.5,length(p-vec2(0.0,0.25)));
float scan=step(0.0,sin(p.y*40.0+t*2.0));
vec3 cc=sky+uColC*sun*scan*1.3;
if(p.y<-0.05){float hp=-p.y+0.05;float gx=abs(fract(p.x/hp*1.5)-0.5);float gz=abs(fract(1.0/hp+t*0.6)-0.5);
float gg=smoothstep(0.06,0.0,min(gx,gz)*hp);cc+=uColC*gg*(0.5+uEnergy);}
col=cc;}
else if(uMode<22.5){vec2 p=d.xy/(abs(d.z)+0.3);float a=atan(p.y,p.x),r=length(p);
float sym=12.0;a=mod(a,6.28318/sym);a=abs(a-3.14159/sym);
float ring=sin(r*14.0-t)*0.5+0.5;
float v=smoothstep(0.3,0.9,ring)*smoothstep(1.4,0.1,r);
col=mix(uColB*0.12,uColA,v)+uColC*pow(ring,3.0)*smoothstep(1.2,0.0,r)*(0.6+uEnergy);}
else if(uMode<23.5){float n=fbm(d*2.5+vec3(t*0.08,t*0.05,0.0));
float n2=fbm(d*5.0+vec3(0.0,-t*0.1,t*0.04)+n);
col=mix(uColB*0.2,uColA,n)+uColC*pow(n2,2.0)*0.9;col*=0.5+0.6*uEnergy;}
else if(uMode<24.5){vec2 p=d.xy/(abs(d.z)+0.2)*3.0;vec2 g=floor(p);vec2 f=fract(p)-0.5;
float star=0.0;
for(int j=-1;j<=1;j++)for(int i=-1;i<=1;i++){vec2 o=vec2(float(i),float(j));
vec2 pos=o+vec2(hash(vec3(g+o,1.0)),hash(vec3(g+o,2.0)))-0.5;
star+=smoothstep(0.12,0.0,length(f-pos));}
col=uColB*0.06+uColC*star*(0.8+uEnergy)+uColA*0.04;}
else if(uMode<25.5){vec2 p=d.xy/(abs(d.z)+0.3);
float curt=smoothstep(0.2,0.0,abs(p.y-fbm(vec3(p.x*2.0,t*0.2,0.0))*0.5+0.1));
float curt2=smoothstep(0.25,0.0,abs(p.y-fbm(vec3(p.x*3.0+5.0,t*0.15,0.0))*0.6-0.2));
col=uColB*0.1+uColA*curt*(0.7+uEnergy)+uColC*curt2*(0.6+uEnergy);}
else if(uMode<26.5){vec2 p=d.xy/(abs(d.z)+0.3);float a=atan(p.y,p.x),r=length(p);
float sw=sin(a*3.0+1.0/(r+0.1)*2.0-t*2.0);float v=smoothstep(0.0,1.0,sw*0.5+0.5);
col=mix(uColB*0.12,uColA,v)+uColC*pow(v,2.0)*smoothstep(1.6,0.0,r)*(0.6+uEnergy);}
else if(uMode<27.5){vec2 p=d.xy/(abs(d.z)+0.3);float a=atan(p.y,p.x),r=length(p);
float petals=abs(cos(a*5.0+t*0.3))*0.6+0.3;
float v=smoothstep(petals+0.05,petals-0.05,r);
col=mix(uColB*0.12,uColA,v)+uColC*smoothstep(0.2,0.0,r)*1.2*(0.6+uEnergy);}
else if(uMode<28.5){vec2 p=d.xy/(abs(d.z)+0.3)*6.0;vec2 g=floor(p);vec2 f=fract(p);
float h=hash(vec3(g,0.0));
float line=h<0.5?smoothstep(0.06,0.0,abs(f.x-0.5)):smoothstep(0.06,0.0,abs(f.y-0.5));
float node=smoothstep(0.12,0.0,length(f-0.5));
float pulse=0.5+0.5*sin(t*3.0+h*20.0);
col=uColB*0.06+uColA*line*0.4+uColC*node*pulse*(0.6+uEnergy);}
else if(uMode<29.5){vec2 p=d.xy/(abs(d.z)+0.3);
float w=0.0;for(int i=0;i<4;i++){float fi=float(i+1);w+=sin(p.x*fi*3.0+t*fi*0.5)*sin(p.y*fi*2.0-t*fi*0.3)/fi;}
float v=smoothstep(-0.2,0.6,w)*smoothstep(1.0,-0.3,p.y);
col=mix(uColB*0.15,uColA,v)+uColC*smoothstep(0.5,0.9,w)*0.8;col*=0.5+0.6*uEnergy;}
else if(uMode<30.5){float band=fbm(vec3(d.x*1.5+t*0.05,d.z*1.5+t*0.03,t*0.04));
float c1=smoothstep(0.3,0.9,band)*smoothstep(0.95,-0.1,d.y);
float c2=smoothstep(0.4,0.95,fbm(vec3(d.x*2.5-3.0,d.z*2.0,t*0.06)))*smoothstep(0.9,0.0,d.y);
col=uColC*c1*(0.7+uEnergy)+uColA*c2*(0.6+uEnergy)+uColB*0.04;}
else if(uMode<31.5){float n=fbm(d*1.8+vec3(t*0.015,0.0,t*0.02));
float n2=fbm(d*4.0+n*1.5-vec3(0.0,t*0.04,0.0));
col=mix(uColB*0.15,uColA,n*n)+uColC*pow(n2,3.0)*1.5;col*=0.5+0.6*uEnergy;col+=0.01;}
else if(uMode<32.5){vec2 p=d.xy/(abs(d.z)+0.25)*3.0;vec2 g=floor(p);float h=hash(vec3(g,1.0));
float ph=fract(h*7.0-t*(0.3+h*0.6));
float st=smoothstep(0.5,0.0,length(fract(p)-0.5))*smoothstep(0.0,0.1,ph)*smoothstep(1.0,0.3,ph);
col=uColB*0.05+uColC*st*(0.8+uEnergy)+uColA*0.03;}
else if(uMode<33.5){vec2 p=d.xy/(abs(d.z)+0.3);float c=0.0;
for(int i=0;i<4;i++){float fi=float(i+1);c+=smoothstep(0.02,0.0,abs(p.y+0.3-sin(p.x*fi+t*0.2*fi)*0.15/fi-float(i)*0.18))*(1.0-float(i)*0.2);}
col=mix(uColB*0.2,uColA,smoothstep(-0.3,0.8,d.y))+uColC*c*(0.6+uEnergy);}
else if(uMode<34.5){vec2 p=d.xy/(abs(d.z)+0.3)*3.0;float m=0.0;
for(int i=0;i<5;i++){float fi=float(i);vec2 c=vec2(sin(t*0.2+fi*2.1),cos(t*0.17+fi*1.3))*2.0;
float r2=0.4+0.3*sin(fi*3.0);m+=smoothstep(r2,r2*0.3,length(p-c))*(0.4+0.3*sin(t+fi));}
col=uColB*0.08+mix(uColA,uColC,0.5)*m*(0.5+uEnergy*0.6);}
else if(uMode<35.5){vec2 p=d.xy/(abs(d.z)+0.3)*4.0;vec2 g=floor(p),f=fract(p)-0.5;float glw=0.0;
for(int j=-1;j<=1;j++)for(int i=-1;i<=1;i++){vec2 o=vec2(float(i),float(j));
vec2 pos=o+0.4*vec2(sin(t*0.8+hash(vec3(g+o,3.0))*20.0),cos(t*0.7+hash(vec3(g+o,4.0))*20.0));
float fl=0.5+0.5*sin(t*2.0+hash(vec3(g+o,5.0))*30.0);
glw+=smoothstep(0.18,0.0,length(f-pos))*fl;}
col=uColB*0.05+uColC*glw*(0.8+uEnergy)+uColA*0.03;}
else if(uMode<36.5){vec2 p=d.xy/(abs(d.z)+0.3);float c=0.0;
for(int i=0;i<3;i++){float fi=float(i);float y=sin(p.x*2.0+t*0.5+fi*2.0)*0.4;
c+=smoothstep(0.05,0.0,abs(p.y-y))*(0.6+0.4*sin(t+fi));}
col=mix(uColB*0.12,uColA,c)+uColC*c*0.6*(0.6+uEnergy);}
else if(uMode<37.5){vec2 p=d.xy/(abs(d.z)+0.2)*4.0;vec2 g=floor(p),f=fract(p);float md=1.0;
for(int j=-1;j<=1;j++)for(int i=-1;i<=1;i++){vec2 o=vec2(float(i),float(j));
vec2 pos=o+vec2(hash(vec3(g+o,1.0)),hash(vec3(g+o,2.0)));md=min(md,length(f-pos));}
float e=smoothstep(0.0,0.08,md);
col=mix(uColC,uColB*0.1,e)*(0.5+uEnergy)+uColA*0.05;}
else if(uMode<38.5){vec2 p=d.xy/(abs(d.z)+0.3)*5.0+vec2(t*0.2,0.0);vec2 f=abs(fract(p)-0.5);
float line=smoothstep(0.45,0.5,max(f.x,f.y));
float node=smoothstep(0.12,0.0,length(fract(p)-0.5))*(0.5+0.5*sin(t*2.0+floor(p.x)+floor(p.y)));
col=uColB*0.06+uColA*line*0.3+uColC*node*(0.6+uEnergy);}
else if(uMode<39.5){vec2 p=d.xy/(abs(d.z)+0.25)*3.0;float m=0.0;
for(int i=0;i<4;i++){float fi=float(i);float ph=fract(t*(0.2+fi*0.05)+fi*0.3);
vec2 st=vec2(2.0-ph*4.0,1.5-ph*3.0)+vec2(fi*0.7,fi*0.3);
vec2 dd=p-st;m+=smoothstep(0.06,0.0,abs(dd.y-dd.x*0.6))*smoothstep(0.6,0.0,length(dd));}
col=uColB*0.05+uColC*m*(0.9+uEnergy)+uColA*0.04*smoothstep(-0.5,0.8,d.y);}
else if(uMode<40.5){vec2 p=d.xy/(abs(d.z)+0.3)*3.0;
float v=sin(p.x+t)+sin(p.y+t*0.8)+sin((p.x+p.y)*0.7+t*1.2)+sin(length(p)*2.0-t);
float c=v*0.25+0.5;
col=mix(uColB,uColA,c)+uColC*pow(c,2.0)*0.8;col*=0.5+0.7*uEnergy;}
else if(uMode<41.5){vec2 p=d.xy/(abs(d.z)+0.2);float r=length(p)+1e-4;float a=atan(p.y,p.x);
float u2=a*1.5+t*0.4;float v2=1.0/r+t*1.2;
float pat=smoothstep(0.4,0.6,sin(u2*3.0)*0.5+0.5)*smoothstep(0.4,0.6,sin(v2*4.0)*0.5+0.5);
col=mix(uColB*0.1,uColC,pat)*smoothstep(2.5,0.1,r)+uColA*0.05;col*=0.6+0.6*uEnergy;}
else if(uMode<42.5){vec2 p=d.xy/(abs(d.z)+0.3);float r=length(p);float a=atan(p.y,p.x);
float corona=fbm(vec3(cos(a)*2.0,sin(a)*2.0,t*0.3));
float disc=smoothstep(0.55+corona*0.1,0.5,r);float flare=smoothstep(0.9,0.0,r)*corona;
col=uColA*disc*1.2+uColC*flare*(0.8+uEnergy)+uColB*0.05;}
else if(uMode<43.5){float n=fbm(d*3.0+vec3(0.0,t*0.05,0.0));float ink=smoothstep(0.45,0.55,n);
col=mix(uColA*0.8,uColB*0.1,ink)+uColC*smoothstep(0.5,0.52,n)*0.4;}
else if(uMode<44.5){vec2 p=d.xy/(abs(d.z)+0.3);float a=atan(p.y,p.x);
float seg=mod(a*1.9099+t*0.2,1.0);
vec3 spec=0.5+0.5*cos(6.2831*(seg+vec3(0.0,0.33,0.67)));
float v=smoothstep(1.2,0.2,length(p));
col=spec*v*(0.4+uEnergy*0.7)*mix(uColC,vec3(1.0),0.4)+uColB*0.04;}
else if(uMode<45.5){vec2 p=d.xy/(abs(d.z)+0.3);float r=length(p);float a=atan(p.y,p.x);
float s=sin(a*3.0+r*8.0-t*1.5)*0.5+0.5;
float v=smoothstep(0.4,0.8,s)*smoothstep(1.5,0.1,r);
col=mix(uColB*0.1,uColA,v)+uColC*pow(s,3.0)*smoothstep(1.2,0.0,r)*(0.6+uEnergy);}
else if(uMode<46.5){vec2 p=d.xy/(abs(d.z)+0.3);float a=atan(p.y,p.x),r=length(p);
float pet=abs(cos(a*6.0+t*0.2))*0.4+0.25;float fl=smoothstep(pet+0.04,pet-0.04,r);
float core=smoothstep(0.12,0.0,r);
col=mix(uColB*0.1,uColA,fl)+uColC*(fl*0.5+core)*(0.6+uEnergy);}
else if(uMode<47.5){vec2 p=d.xy/(abs(d.z)+0.3);
float sl=0.5+0.5*sin(p.y*60.0+t*3.0);float glow=fbm(vec3(p*2.0,t*0.2));
col=mix(uColB*0.1,uColC,glow*0.6)*sl*(0.6+uEnergy)+uColA*0.04;}
else if(uMode<48.5){float n=fbm(d*2.0+vec3(t*0.03,0.0,t*0.02));float n2=fbm(d*4.5+n);
float sky=smoothstep(-0.5,0.8,d.y);
col=mix(uColB*0.3,uColA*0.7,sky)+uColC*smoothstep(0.5,0.8,n2)*0.6*(0.5+uEnergy);}
else{float dep=smoothstep(0.6,-0.7,d.y);float n=fbm(d*3.0+vec3(0.0,t*0.04,0.0));
float caustic=pow(0.5+0.5*sin(n*8.0+t),3.0);
col=mix(uColA*0.3,uColB*0.05,dep)+uColC*caustic*0.4*(0.5+uEnergy)*dep;}
return col;}
void main(){vec3 d=normalize(vDir);vec3 col;
if(uMediaOn>0.5){
// cover-fit: keep media filling the screen without stretching, regardless of aspect
vec2 uv=gl_FragCoord.xy/uRes;
float sAspect=uRes.x/max(uRes.y,1.0);
vec2 c=vec2(0.5);
if(uMediaAspect>sAspect){ // media wider than screen -> crop sides
float sc=sAspect/uMediaAspect; uv.x=(uv.x-0.5)*sc+0.5;
}else{ // media taller -> crop top/bottom
float sc=uMediaAspect/sAspect; uv.y=(uv.y-0.5)*sc+0.5;
}
vec3 m=texture2D(uMedia,uv).rgb;
m=hueShift(m,uHue);
// audio-reactive flare: brighten + slight saturation push with energy
m*=0.78+0.55*uEnergy;
col=m*uBgInt;
}else{
col=bg(d,uMode)*uBgInt;
}
// subtle ordered dither kills visible banding on dark gradients (HQ)
float dth=fract(sin(dot(gl_FragCoord.xy,vec2(12.9898,78.233)))*43758.5453);
col+=(dth-0.5)/255.0;
gl_FragColor=vec4(max(col,0.0),1.0);}`
}));
backdrop.frustumCulled=false; scene.add(backdrop);
/* ----- lights ----- */
const ambient=new THREE.AmbientLight(0xffffff,0.18); scene.add(ambient);
const lightGroup=new THREE.Group(); scene.add(lightGroup);
const L={key:null,rim:null,orbits:[]};
function buildLights(mp){
lightGroup.clear(); L.orbits.length=0;
L.key=new THREE.PointLight(0xffffff,18,40); L.key.position.set(3,3,4); lightGroup.add(L.key);
L.rim=new THREE.PointLight(0xffffff,12,40); L.rim.position.set(-4,-2,-3); lightGroup.add(L.rim);
for(let i=0;i<mp.orbitCount;i++){const p=new THREE.PointLight(0xffffff,8,30);lightGroup.add(p);L.orbits.push({light:p,band:i%3});}
}
/* ----- centerpiece ----- */
const center=new THREE.Group(); scene.add(center);
let centerMesh=null, artMat=null;
// Re-map a faceted solid's UVs so the album art sits FLAT and centred on each
// face instead of being smeared/wrapped by the default spherical projection.
// Triangles are grouped by their plane (so a pentagon's 3 tris share one mapping);
// each face's bounding box is fit, aspect-preserved, into the 0..1 unit square.
function flatFaceUVs(geo){
if(geo.index)geo=geo.toNonIndexed();
const pos=geo.attributes.position, N=pos.count;
const A=new THREE.Vector3(),B=new THREE.Vector3(),C=new THREE.Vector3(),
e1=new THREE.Vector3(),e2=new THREE.Vector3(),nrm=new THREE.Vector3(),p=new THREE.Vector3();
const groups=new Map();
for(let i=0;i<N;i+=3){
A.fromBufferAttribute(pos,i);B.fromBufferAttribute(pos,i+1);C.fromBufferAttribute(pos,i+2);
e1.subVectors(B,A);e2.subVectors(C,A);nrm.crossVectors(e1,e2).normalize();
const d=nrm.dot(A);
const key=[Math.round(nrm.x*50),Math.round(nrm.y*50),Math.round(nrm.z*50),Math.round(d*50)].join(",");
let g=groups.get(key); if(!g){g={n:nrm.clone(),tris:[]};groups.set(key,g);} g.tris.push(i);
}
const uv=new Float32Array(N*2), u=new THREE.Vector3(), v=new THREE.Vector3();
for(const g of groups.values()){
const n=g.n;
// Orient each face so the art's "up" follows world-up projected into the
// face plane — keeps the cover upright instead of randomly rotated per face.
v.set(0,1,0).addScaledVector(n,-n.y); // world-up projected onto plane
if(v.lengthSq()<1e-6)v.set(0,0,1).addScaledVector(n,-n.z); // horizontal face: use +Z
v.normalize();
u.crossVectors(v,n).normalize(); // u×v=n → upright AND not mirrored
let minS=1e9,maxS=-1e9,minT=1e9,maxT=-1e9; const st=[];
for(const i of g.tris)for(let k=0;k<3;k++){
p.fromBufferAttribute(pos,i+k); const s=p.dot(u),t=p.dot(v);
st.push(s,t); if(s<minS)minS=s; if(s>maxS)maxS=s; if(t<minT)minT=t; if(t>maxT)maxT=t;
}
const w=maxS-minS||1,h=maxT-minT||1,sc=1/Math.max(w,h),offU=(1-w*sc)/2,offV=(1-h*sc)/2;
let j=0;
for(const i of g.tris)for(let k=0;k<3;k++){
const s=st[j++],t=st[j++];
uv[(i+k)*2]=(s-minS)*sc+offU; uv[(i+k)*2+1]=(t-minT)*sc+offV;
}
}
geo.setAttribute("uv",new THREE.Float32BufferAttribute(uv,2));
return geo;
}
function makeGeometry(shape){
switch(shape){
case"card":return new THREE.BoxGeometry(2.6,2.6,0.18);
case"sphere":return new THREE.SphereGeometry(1.25,64,48);
case"cube":return flatFaceUVs(new THREE.BoxGeometry(1.7,1.7,1.7));
case"diamond":return flatFaceUVs(new THREE.OctahedronGeometry(1.45,0));
case"poly":return flatFaceUVs(new THREE.DodecahedronGeometry(1.4,0));
default:return new THREE.CylinderGeometry(1.3,1.3,0.16,72,1);
}
}
function buildCenter(){
if(centerMesh){center.remove(centerMesh);centerMesh.geometry.dispose();
(Array.isArray(centerMesh.material)?centerMesh.material:[centerMesh.material]).forEach(m=>m.dispose());}
const mp=MODES[state.mode], geo=makeGeometry(state.shape);
const t=state.queue[state.current]; const tex=t?ensureTex(t):null;
const flat=!!mp.mat.flat && state.shape!=="sphere" && state.shape!=="disc";
const hasArt=!!tex;
// When art is present: drop metalness (metals hide their albedo map) and self-light it via emissiveMap
// so the cover/label is ALWAYS clearly visible in the dark scene regardless of party mode.
artMat=new THREE.MeshPhysicalMaterial({map:tex,emissiveMap:hasArt?tex:null,
metalness:hasArt?Math.min(mp.mat.metalness,0.2):mp.mat.metalness,
roughness:hasArt?Math.max(mp.mat.roughness,0.42):mp.mat.roughness,
clearcoat:mp.mat.clearcoat||0,clearcoatRoughness:mp.mat.clearcoatRoughness||0.3,
iridescence:mp.mat.iridescence||0,iridescenceIOR:1.3,envMapIntensity:(mp.mat.env||1.0)*ENV,
emissive:new THREE.Color(0xffffff),emissiveIntensity:0,flatShading:flat,toneMapped:true});
if(state.shape==="diamond"||mp.mat.transmission){artMat.transmission=mp.mat.transmission||0.9;
artMat.ior=mp.mat.ior||2.2;artMat.thickness=1.6;artMat.transparent=true;artMat.roughness=Math.min(artMat.roughness,0.08);artMat.metalness=0;}
if(state.shape==="card"){
// Full cover on the two large flat faces (+Z/-Z), dark metal frame on the four thin edges.
const frame=new THREE.MeshPhysicalMaterial({color:0x0c0c12,metalness:0.7,roughness:0.38,clearcoat:0.5,envMapIntensity:1.0*ENV});
centerMesh=new THREE.Mesh(geo,[frame,frame,frame,frame,artMat,artMat]);
} else if(state.shape==="disc"){
const side=new THREE.MeshPhysicalMaterial({color:0x1a1206,metalness:1,roughness:0.22,clearcoat:0.5,envMapIntensity:1.5*ENV});
centerMesh=new THREE.Mesh(geo,[side,artMat,artMat]); centerMesh.rotation.x=Math.PI/2;
} else centerMesh=new THREE.Mesh(geo,artMat);
centerMesh.scale.set(1,state.shape==="diamond"?1.35:1,1);
center.add(centerMesh);
buildBorder();
}
function applyTex(t){ if(!artMat)return; artMat.map=t._tex||null; artMat.emissiveMap=t._tex||null; artMat.needsUpdate=true; }
/* ---------------- corner-accent borders ---------------- */
// Selectable decorative accents that sit on the centerpiece's bounding-box CORNERS
// (so they frame/accent the object). Built as a child of centerMesh → they inherit
// its spin + scale automatically. All glow additively so scene bloom lights them.
let borderObj=null;
const _BADD={blending:THREE.AdditiveBlending,transparent:true,depthWrite:false};
const _Y=new THREE.Vector3(0,1,0),_Z=new THREE.Vector3(0,0,1);
function _blineMat(col,op){return new THREE.LineBasicMaterial(Object.assign({color:col,opacity:op==null?0.95:op},_BADD));}
// black-body material that only shows its EMISSIVE colour (pushes >1 → bloom glow)
function _bemMat(col,inten){return new THREE.MeshStandardMaterial({color:0x000000,emissive:col,
emissiveIntensity:inten==null?1.5:inten,metalness:0.2,roughness:0.45,toneMapped:true});}
// the 8 corners of a Box3, with inward-sign for each axis
function _corners(bb){const c=[];for(const sx of[-1,1])for(const sy of[-1,1])for(const sz of[-1,1])
c.push({x:sx<0?bb.min.x:bb.max.x,y:sy<0?bb.min.y:bb.max.y,z:sz<0?bb.min.z:bb.max.z,sx,sy,sz});return c;}
function _pushSeg(a,ax,ay,az,bx,by,bz){a.push(ax,ay,az,bx,by,bz);}
function _addBar(g,col,ax,ay,az,bx,by,bz,r){const A=new THREE.Vector3(ax,ay,az),B=new THREE.Vector3(bx,by,bz),
d=new THREE.Vector3().subVectors(B,A),len=d.length();if(len<1e-5)return;
const m=new THREE.Mesh(new THREE.CylinderGeometry(r||0.04,r||0.04,len,8),_bemMat(col,1.6));
m.position.copy(A).addScaledVector(d,0.5);m.quaternion.setFromUnitVectors(_Y,d.normalize());g.add(m);}
// L-shaped corner brackets along the three edges meeting at each corner
function bBrackets(bb,col,frac,thick){const g=new THREE.Group();
const lx=(bb.max.x-bb.min.x)*frac,ly=(bb.max.y-bb.min.y)*frac,lz=(bb.max.z-bb.min.z)*frac;
if(thick){for(const c of _corners(bb)){
_addBar(g,col,c.x,c.y,c.z,c.x-c.sx*lx,c.y,c.z);_addBar(g,col,c.x,c.y,c.z,c.x,c.y-c.sy*ly,c.z);
_addBar(g,col,c.x,c.y,c.z,c.x,c.y,c.z-c.sz*lz);}}
else{const pos=[];for(const c of _corners(bb)){
_pushSeg(pos,c.x,c.y,c.z,c.x-c.sx*lx,c.y,c.z);_pushSeg(pos,c.x,c.y,c.z,c.x,c.y-c.sy*ly,c.z);
_pushSeg(pos,c.x,c.y,c.z,c.x,c.y,c.z-c.sz*lz);}
const geo=new THREE.BufferGeometry();geo.setAttribute("position",new THREE.Float32BufferAttribute(pos,3));
g.add(new THREE.LineSegments(geo,_blineMat(col)));}
return g;}
// full bounding-box wireframe outline
function bEdges(bb,col){const sz=new THREE.Vector3(),ce=new THREE.Vector3();bb.getSize(sz);bb.getCenter(ce);
const ls=new THREE.LineSegments(new THREE.EdgesGeometry(new THREE.BoxGeometry(sz.x,sz.y,sz.z)),_blineMat(col));
ls.position.copy(ce);const g=new THREE.Group();g.add(ls);return g;}
// soft glowing sprite dots at the corners
function bDots(bb,col,size){const g=new THREE.Group();for(const c of _corners(bb)){
const m=new THREE.Sprite(new THREE.SpriteMaterial(Object.assign({map:SPRITE,color:col},_BADD)));
m.position.set(c.x,c.y,c.z);m.scale.setScalar(size);g.add(m);}return g;}
// small solid emissive cubes (studs) at the corners
function bStuds(bb,col,size){const g=new THREE.Group(),geo=new THREE.BoxGeometry(size,size,size);
for(const c of _corners(bb)){const m=new THREE.Mesh(geo,_bemMat(col,1.6));m.position.set(c.x,c.y,c.z);g.add(m);}return g;}
// elongated octahedra pointing outward along the corner diagonal
function bSpikes(bb,col,size){const g=new THREE.Group(),geo=new THREE.OctahedronGeometry(size,0);
for(const c of _corners(bb)){const m=new THREE.Mesh(geo,_bemMat(col,1.5));m.position.set(c.x,c.y,c.z);
m.scale.set(0.65,1.5,0.65);m.quaternion.setFromUnitVectors(_Y,new THREE.Vector3(c.sx,c.sy,c.sz).normalize());g.add(m);}return g;}
// small torus rings facing outward at each corner
function bRings(bb,col,r){const g=new THREE.Group(),geo=new THREE.TorusGeometry(r,r*0.2,8,20);
for(const c of _corners(bb)){const m=new THREE.Mesh(geo,_bemMat(col,1.4));m.position.set(c.x,c.y,c.z);
m.quaternion.setFromUnitVectors(_Z,new THREE.Vector3(c.sx,c.sy,c.sz).normalize());g.add(m);}return g;}
const _BC={gold:0xffcf6b,cyan:0x66e0ff,rose:0xff6bbf,violet:0xb060ff,white:0xfff4d8,
emerald:0x57e08a,amber:0xffb24d,ice:0x9fd8ff,crimson:0xff5a5a,magenta:0xff5cf0};
// [name, builder(bb)->Object3D, swatchHex] — index 0 is "None". 20 entries total.
const BORDERS=[
["None",null,null],
["Gold Brackets",bb=>bBrackets(bb,_BC.gold,0.26,false),"#ffcf6b"],
["Cyan Brackets",bb=>bBrackets(bb,_BC.cyan,0.26,false),"#66e0ff"],
["Rose Brackets",bb=>bBrackets(bb,_BC.rose,0.26,false),"#ff6bbf"],
["Gold Brackets Bold",bb=>bBrackets(bb,_BC.gold,0.3,true),"#ffcf6b"],
["Ice Brackets Bold",bb=>bBrackets(bb,_BC.ice,0.3,true),"#9fd8ff"],
["Gold Wireframe",bb=>bEdges(bb,_BC.gold),"#ffcf6b"],
["Violet Wireframe",bb=>bEdges(bb,_BC.violet),"#b060ff"],
["White Wireframe",bb=>bEdges(bb,_BC.white),"#fff4d8"],
["Gold Dots",bb=>bDots(bb,_BC.gold,0.42),"#ffcf6b"],
["Cyan Dots",bb=>bDots(bb,_BC.cyan,0.42),"#66e0ff"],
["White Dots",bb=>bDots(bb,_BC.white,0.36),"#fff4d8"],
["Gold Studs",bb=>bStuds(bb,_BC.gold,0.17),"#ffcf6b"],
["Crimson Studs",bb=>bStuds(bb,_BC.crimson,0.17),"#ff5a5a"],
["Emerald Studs",bb=>bStuds(bb,_BC.emerald,0.17),"#57e08a"],
["Gold Spikes",bb=>bSpikes(bb,_BC.gold,0.16),"#ffcf6b"],
["Amber Spikes",bb=>bSpikes(bb,_BC.amber,0.16),"#ffb24d"],
["Gold Rings",bb=>bRings(bb,_BC.gold,0.2),"#ffcf6b"],
["Magenta Rings",bb=>bRings(bb,_BC.magenta,0.2),"#ff5cf0"],
["Gold Deluxe",bb=>{const g=new THREE.Group();g.add(bBrackets(bb,_BC.gold,0.28,true));g.add(bStuds(bb,_BC.gold,0.12));return g;},"#ffcf6b"],
];
function buildBorder(){
if(borderObj){if(borderObj.parent)borderObj.parent.remove(borderObj);disposeObj(borderObj);borderObj=null;}
const def=BORDERS[state.border|0];
if(!def||!def[1]||!centerMesh)return;
const geo=centerMesh.geometry;if(!geo.boundingBox)geo.computeBoundingBox();
// pad outward a touch so accents sit just OUTSIDE the surface
const bb=geo.boundingBox.clone();const pad=0.07;bb.min.subScalar(pad);bb.max.addScalar(pad);
borderObj=def[1](bb);borderObj.renderOrder=3;
centerMesh.add(borderObj);
}
/* ----- particles (highs) ----- */
const MAXP=240, pPos=new Float32Array(MAXP*3), pCol=new Float32Array(MAXP*3),
pLife=new Float32Array(MAXP), pSize=new Float32Array(MAXP), pVel=new Float32Array(MAXP*3);
const pGeo=new THREE.BufferGeometry();
pGeo.setAttribute("position",new THREE.BufferAttribute(pPos,3));
pGeo.setAttribute("aColor",new THREE.BufferAttribute(pCol,3));
pGeo.setAttribute("aLife",new THREE.BufferAttribute(pLife,1));
pGeo.setAttribute("aSize",new THREE.BufferAttribute(pSize,1));
const pMat=new THREE.ShaderMaterial({transparent:true,depthWrite:false,blending:THREE.AdditiveBlending,
vertexShader:`attribute vec3 aColor;attribute float aLife;attribute float aSize;varying vec3 vC;varying float vL;
void main(){vC=aColor;vL=aLife;vec4 mv=modelViewMatrix*vec4(position,1.0);gl_PointSize=aSize*vL*(260.0/-mv.z);gl_Position=projectionMatrix*mv;}`,
fragmentShader:`varying vec3 vC;varying float vL;void main(){float d=length(gl_PointCoord-0.5);if(d>0.5)discard;float a=smoothstep(0.5,0.0,d)*vL;gl_FragColor=vec4(vC*a,a);}`});
const points=new THREE.Points(pGeo,pMat); points.frustumCulled=false; scene.add(points);
let pHead=0;
function spawnParticle(col,style){
const i=pHead;pHead=(pHead+1)%MAXP;const a=Math.random()*7,b=Math.acos(2*Math.random()-1),r=1.4;
const dx=Math.sin(b)*Math.cos(a),dy=Math.cos(b),dz=Math.sin(b)*Math.sin(a);
pPos[i*3]=dx*r;pPos[i*3+1]=dy*r;pPos[i*3+2]=dz*r;
const sp=style==="ember"?0.4:1.0;
pVel[i*3]=dx*sp*(0.6+Math.random());pVel[i*3+1]=dy*sp*(0.6+Math.random())+(style==="ember"?0.6:0);pVel[i*3+2]=dz*sp*(0.6+Math.random());
pCol[i*3]=col.r;pCol[i*3+1]=col.g;pCol[i*3+2]=col.b;pLife[i]=1;pSize[i]=18+Math.random()*26;
}
/* ================= VISUALIZERS (foreground reactive elements) ================= */
// vizGroup sits at the origin facing the camera; visualizers are additive glow overlays.
const vizGroup=new THREE.Group(); scene.add(vizGroup);
// soft round sprite for point-based visualizers
const _sprC=document.createElement("canvas");_sprC.width=_sprC.height=64;
{const g=_sprC.getContext("2d");const grd=g.createRadialGradient(32,32,0,32,32,32);
grd.addColorStop(0,"rgba(255,255,255,1)");grd.addColorStop(0.35,"rgba(255,255,255,0.6)");grd.addColorStop(1,"rgba(255,255,255,0)");
g.fillStyle=grd;g.fillRect(0,0,64,64);}
const SPRITE=new THREE.CanvasTexture(_sprC);SPRITE.colorSpace=SRGB;
const vHSL=(h,s,l)=>new THREE.Color().setHSL(((h%1)+1)%1,s,l);
function disposeObj(o){o.traverse(n=>{if(n.geometry)n.geometry.dispose();
if(n.material){(Array.isArray(n.material)?n.material:[n.material]).forEach(m=>m.dispose());}});}
// per-bin reactive level: real FFT when available, else synthesized from smoothed bands
function vizSpectrum(i,n){
if(audioReady&&freq&&mode==="real"){
const lo=30*Math.pow(420,i/n),hi=30*Math.pow(420,(i+1)/n);
return Math.min(1,bandAvg(lo,Math.max(lo+1,hi))*1.55);
}
const f=i/n,band=f<0.34?A.bass:(f<0.67?A.mid:A.high);
return Math.min(1,band*(0.55+0.45*Math.sin(i*1.7+performance.now()*0.0045)));
}
const _ADD={blending:THREE.AdditiveBlending,depthWrite:false,transparent:true};
function lineMat(h){return new THREE.LineBasicMaterial(Object.assign({color:vHSL(h,0.85,0.6),opacity:0.92},_ADD));}
function ptMat(h,size){return new THREE.PointsMaterial(Object.assign({color:vHSL(h,0.85,0.62),size:size||0.12,map:SPRITE,sizeAttenuation:true,opacity:0.95},_ADD));}
function segGeo(n){const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.BufferAttribute(new Float32Array(n*6),3));return g;}
function setSeg(pos,i,ax,ay,az,bx,by,bz){const o=i*6;pos[o]=ax;pos[o+1]=ay;pos[o+2]=az;pos[o+3]=bx;pos[o+4]=by;pos[o+5]=bz;}
// ---- 14 visualizer factories. Each returns {root, update(time,dt)} reading global A. ----
function ringBars(p){const n=40+(p.variant%4)*16,rad=1.95,geo=segGeo(n),pos=geo.attributes.position.array;
const root=new THREE.LineSegments(geo,lineMat(p.hue));root.frustumCulled=false;
return {root,update:(t,dt)=>{for(let i=0;i<n;i++){const a=i/n*Math.PI*2,m=vizSpectrum(i,n),r1=rad+0.12+m*1.7;
setSeg(pos,i,Math.cos(a)*rad,Math.sin(a)*rad,0,Math.cos(a)*r1,Math.sin(a)*r1,0);}
geo.attributes.position.needsUpdate=true;root.rotation.z+=dt*0.12;root.material.opacity=0.55+0.45*Math.min(1,A.energy);}};}
function barsBottom(p){const n=28+(p.variant%4)*12,W=4.2,geo=segGeo(n),pos=geo.attributes.position.array;
const root=new THREE.LineSegments(geo,lineMat(p.hue));root.frustumCulled=false;root.position.set(0,-1.7,0);
return {root,update:(t,dt)=>{for(let i=0;i<n;i++){const x=(i/(n-1)-0.5)*W,m=vizSpectrum(i,n);
setSeg(pos,i,x,0,0,x,0.08+m*2.4,0);}geo.attributes.position.needsUpdate=true;
root.material.color.setHSL(((p.hue+t*0.03)%1),0.85,0.6);}};}
function waveform(p){const n=96,W=4.6,geo=new THREE.BufferGeometry();const pos=new Float32Array(n*3);
geo.setAttribute('position',new THREE.BufferAttribute(pos,3));const root=new THREE.Line(geo,lineMat(p.hue));root.frustumCulled=false;
const off=(p.variant%4)*0.5;
return {root,update:(t,dt)=>{for(let i=0;i<n;i++){const x=(i/(n-1)-0.5)*W,m=vizSpectrum(i,n)-0.4;
pos[i*3]=x;pos[i*3+1]=Math.sin(i*0.4+t*2+off)*0.3+m*1.6;pos[i*3+2]=0;}
geo.attributes.position.needsUpdate=true;root.material.opacity=0.6+0.4*Math.min(1,A.energy);}};}
function orbitDots(p){const n=80+(p.variant%3)*40,geo=new THREE.BufferGeometry();const pos=new Float32Array(n*3);
geo.setAttribute('position',new THREE.BufferAttribute(pos,3));const root=new THREE.Points(geo,ptMat(p.hue,0.1));root.frustumCulled=false;
const seed=[];for(let i=0;i<n;i++)seed.push({r:1.6+Math.random()*1.6,a:Math.random()*7,s:0.2+Math.random()*0.8,b:i%3});
return {root,update:(t,dt)=>{const bands=[A.bass,A.mid,A.high];for(let i=0;i<n;i++){const o=seed[i];o.a+=dt*o.s*(0.4+bands[o.b]);
const r=o.r*(1+bands[o.b]*0.4);pos[i*3]=Math.cos(o.a)*r;pos[i*3+1]=Math.sin(o.a)*r;pos[i*3+2]=Math.sin(o.a*2+i)*0.4;}
geo.attributes.position.needsUpdate=true;root.material.size=0.08+A.high*0.12;}};}
function pulseRings(p){const rings=3+(p.variant%3),segs=64,geo=segGeo(rings*segs),pos=geo.attributes.position.array;
const root=new THREE.LineSegments(geo,lineMat(p.hue));root.frustumCulled=false;const phase=[];for(let r=0;r<rings;r++)phase.push(r/rings);
return {root,update:(t,dt)=>{let idx=0;for(let r=0;r<rings;r++){phase[r]+=dt*(0.25+A.energy*0.5);if(phase[r]>1)phase[r]-=1;
const rad=0.4+phase[r]*2.8;for(let s=0;s<segs;s++){const a0=s/segs*Math.PI*2,a1=(s+1)/segs*Math.PI*2;
setSeg(pos,idx++,Math.cos(a0)*rad,Math.sin(a0)*rad,0,Math.cos(a1)*rad,Math.sin(a1)*rad,0);}}
geo.attributes.position.needsUpdate=true;root.material.opacity=0.4+0.5*Math.min(1,A.beat+A.energy*0.5);}};}
function starburst(p){const n=60+(p.variant%4)*24,geo=segGeo(n),pos=geo.attributes.position.array;
const root=new THREE.LineSegments(geo,lineMat(p.hue));root.frustumCulled=false;
return {root,update:(t,dt)=>{for(let i=0;i<n;i++){const a=i/n*Math.PI*2,m=vizSpectrum(i,n),r1=0.3+m*2.6+A.beat*0.6;
setSeg(pos,i,0,0,0,Math.cos(a)*r1,Math.sin(a)*r1,0);}geo.attributes.position.needsUpdate=true;
root.rotation.z-=dt*0.08;root.material.color.setHSL(((p.hue+A.energy*0.2)%1),0.9,0.6);}};}
function lissajous(p){const n=180,geo=new THREE.BufferGeometry();const pos=new Float32Array(n*3);
geo.setAttribute('position',new THREE.BufferAttribute(pos,3));const root=new THREE.Line(geo,lineMat(p.hue));root.frustumCulled=false;
const fa=2+(p.variant%3),fb=3+((p.variant>>1)%3);
return {root,update:(t,dt)=>{const A1=1.6+A.bass*0.8;for(let i=0;i<n;i++){const u=i/(n-1)*Math.PI*2;
pos[i*3]=Math.sin(u*fa+t*0.6)*A1;pos[i*3+1]=Math.sin(u*fb)*A1;pos[i*3+2]=Math.cos(u*2)*0.3;}
geo.attributes.position.needsUpdate=true;root.material.opacity=0.6+0.4*Math.min(1,A.energy);}};}
function helix(p){const n=120,geo=new THREE.BufferGeometry();const pos=new Float32Array(n*2*3);
geo.setAttribute('position',new THREE.BufferAttribute(pos,3));const root=new THREE.Points(geo,ptMat(p.hue,0.09));root.frustumCulled=false;
const turns=2+(p.variant%3);
return {root,update:(t,dt)=>{for(let i=0;i<n;i++){const u=i/n,y=(u-0.5)*3.4,ang=u*Math.PI*2*turns+t*1.2;
const r=1.3+A.mid*0.5;pos[i*6]=Math.cos(ang)*r;pos[i*6+1]=y;pos[i*6+2]=Math.sin(ang)*r;
pos[i*6+3]=Math.cos(ang+Math.PI)*r;pos[i*6+4]=y;pos[i*6+5]=Math.sin(ang+Math.PI)*r;}
geo.attributes.position.needsUpdate=true;root.rotation.y+=dt*0.3;root.material.size=0.07+A.high*0.1;}};}
function spiralViz(p){const n=160,geo=new THREE.BufferGeometry();const pos=new Float32Array(n*3);
geo.setAttribute('position',new THREE.BufferAttribute(pos,3));const root=new THREE.Line(geo,lineMat(p.hue));root.frustumCulled=false;
const arms=1+(p.variant%3);
return {root,update:(t,dt)=>{for(let i=0;i<n;i++){const u=i/n,ang=u*Math.PI*2*4*arms+t*0.8,r=u*3*(1+A.bass*0.3);
pos[i*3]=Math.cos(ang)*r;pos[i*3+1]=Math.sin(ang)*r;pos[i*3+2]=0;}geo.attributes.position.needsUpdate=true;
root.material.opacity=0.55+0.45*Math.min(1,A.energy);}};}
function gridViz(p){const N=8+(p.variant%4)*2,geo=new THREE.BufferGeometry();const cells=N*N;const pos=new Float32Array(cells*3);
geo.setAttribute('position',new THREE.BufferAttribute(pos,3));const root=new THREE.Points(geo,ptMat(p.hue,0.12));root.frustumCulled=false;
return {root,update:(t,dt)=>{let i=0;for(let x=0;x<N;x++)for(let y=0;y<N;y++){const fx=(x/(N-1)-0.5)*4,fy=(y/(N-1)-0.5)*4;
const m=vizSpectrum((x+y)%N,N);pos[i*3]=fx;pos[i*3+1]=fy;pos[i*3+2]=Math.sin(t*2+x*0.6+y*0.6)*0.3+m*0.8;i++;}
geo.attributes.position.needsUpdate=true;root.material.size=0.08+A.energy*0.12;}};}
function sphereWire(p){const rings=6+(p.variant%3)*2,segs=40,geo=segGeo(rings*segs),pos=geo.attributes.position.array;
const root=new THREE.LineSegments(geo,lineMat(p.hue));root.frustumCulled=false;
return {root,update:(t,dt)=>{let idx=0;const R=1.7*(1+A.bass*0.25);for(let r=0;r<rings;r++){const lat=(r/(rings-1)-0.5)*Math.PI,y=Math.sin(lat)*R,rr=Math.cos(lat)*R;
for(let s=0;s<segs;s++){const a0=s/segs*Math.PI*2,a1=(s+1)/segs*Math.PI*2;
setSeg(pos,idx++,Math.cos(a0)*rr,y,Math.sin(a0)*rr,Math.cos(a1)*rr,y,Math.sin(a1)*rr);}}
geo.attributes.position.needsUpdate=true;root.rotation.y+=dt*0.25;root.rotation.x=Math.sin(t*0.3)*0.3;
root.material.opacity=0.4+0.5*Math.min(1,A.energy);}};}
function tunnelRings(p){const rings=10+(p.variant%3)*4,segs=32,geo=segGeo(rings*segs),pos=geo.attributes.position.array;
const root=new THREE.LineSegments(geo,lineMat(p.hue));root.frustumCulled=false;const z=[];for(let r=0;r<rings;r++)z.push(r/rings);
return {root,update:(t,dt)=>{let idx=0;for(let r=0;r<rings;r++){z[r]+=dt*(0.3+A.energy*0.7);if(z[r]>1)z[r]-=1;
const zz=-4+z[r]*8,rad=1.0+z[r]*1.8;for(let s=0;s<segs;s++){const a0=s/segs*Math.PI*2,a1=(s+1)/segs*Math.PI*2;
setSeg(pos,idx++,Math.cos(a0)*rad,Math.sin(a0)*rad,zz,Math.cos(a1)*rad,Math.sin(a1)*rad,zz);}}
geo.attributes.position.needsUpdate=true;root.material.color.setHSL(((p.hue+t*0.04)%1),0.85,0.6);}};}
function ribbonViz(p){const n=120,geo=new THREE.BufferGeometry();const pos=new Float32Array(n*3);
geo.setAttribute('position',new THREE.BufferAttribute(pos,3));const root=new THREE.Line(geo,lineMat(p.hue));root.frustumCulled=false;
const w=(p.variant%3)+1;
return {root,update:(t,dt)=>{for(let i=0;i<n;i++){const u=i/(n-1),x=(u-0.5)*4.6;
pos[i*3]=x;pos[i*3+1]=Math.sin(u*Math.PI*2*w+t*1.5)*(0.8+A.mid)+Math.sin(t*0.7)*0.2;pos[i*3+2]=Math.cos(u*Math.PI*3+t)*0.6;}
geo.attributes.position.needsUpdate=true;root.material.opacity=0.6+0.4*Math.min(1,A.energy);}};}
function confettiViz(p){const n=140,geo=new THREE.BufferGeometry();const pos=new Float32Array(n*3);const col=new Float32Array(n*3);
geo.setAttribute('position',new THREE.BufferAttribute(pos,3));geo.setAttribute('color',new THREE.BufferAttribute(col,3));
const mat=new THREE.PointsMaterial(Object.assign({size:0.12,map:SPRITE,vertexColors:true,sizeAttenuation:true,opacity:0.95},_ADD));
const root=new THREE.Points(geo,mat);root.frustumCulled=false;const st=[];
for(let i=0;i<n;i++){st.push({x:(Math.random()-0.5)*5,y:Math.random()*4-2,z:(Math.random()-0.5)*2,v:0.3+Math.random()*0.7,h:Math.random()});}
return {root,update:(t,dt)=>{for(let i=0;i<n;i++){const o=st[i];o.y-=dt*o.v*(0.5+A.energy);if(o.y<-2.2){o.y=2.2;o.x=(Math.random()-0.5)*5;}
pos[i*3]=o.x+Math.sin(t+i)*0.1;pos[i*3+1]=o.y;pos[i*3+2]=o.z;const c=vHSL(p.hue+o.h*0.25,0.85,0.6);col[i*3]=c.r;col[i*3+1]=c.g;col[i*3+2]=c.b;}
geo.attributes.position.needsUpdate=true;geo.attributes.color.needsUpdate=true;root.material.size=0.09+A.high*0.14;}};}
const VFAC=[["Ring Bars",ringBars],["Spectrum Bars",barsBottom],["Waveform",waveform],["Orbit Dots",orbitDots],
["Pulse Rings",pulseRings],["Starburst",starburst],["Lissajous",lissajous],["Helix",helix],["Spiral",spiralViz],
["Grid Field",gridViz],["Sphere Wire",sphereWire],["Tunnel",tunnelRings],["Ribbon",ribbonViz],["Confetti",confettiViz]];
const VHUE=[["Gold",0.11],["Amber",0.07],["Rose",0.93],["Violet",0.76],["Indigo",0.66],["Cyan",0.52],["Aqua",0.46],
["Emerald",0.38],["Lime",0.28],["Ice",0.58],["Crimson",0.99],["Magenta",0.86]];
// DECOUPLED like the backdrop stack: pick a visualizer TYPE (one entry per factory),
// and colour comes from a single free wheel (state.vizColor) shared by all active viz —
// instead of 60 near-duplicate presets that only differed by hue.
const VIZ_TYPES=VFAC.map((f,i)=>({id:i,fac:f[1],name:f[0],variant:i}));
let vizActive=[]; // [{id, inst, prm}] prm.hue is mutated live by the wheel / bass-shift
let vizHuePhase=0; // accumulates bass energy → rotating hue when vizBassHue is on
// current wheel hue (0..1) pulled from the chosen colour; sat/light fixed for the glow look
function vizBaseHue(){const c=new THREE.Color(state.vizColor||"#ffcf6b"),o={};c.getHSL(o);return o.h;}
// retint every material on a visualizer (skips per-vertex confetti, which colours itself)
function tintViz(root,h){const col=vHSL(h,0.85,0.6);
root.traverse(o=>{const m=o.material;if(!m)return;(Array.isArray(m)?m:[m]).forEach(mm=>{
if(mm&&mm.color&&!mm.vertexColors)mm.color.copy(col);});});}
function rebuildViz(){
vizActive.forEach(v=>{vizGroup.remove(v.inst.root);disposeObj(v.inst.root);});
vizActive=[];
const h=vizBaseHue();
state.viz.forEach(id=>{const ty=VIZ_TYPES[id];if(!ty)return;
const prm={hue:h,variant:ty.variant}; // shared, mutable → live recolour
const inst=ty.fac(prm);vizGroup.add(inst.root);vizActive.push({id,inst,prm});});
}
// push the current wheel colour onto every active visualizer (used on wheel change)
function applyVizColor(){const h=vizBaseHue();for(const v of vizActive){v.prm.hue=h;tintViz(v.inst.root,h);}}
function toggleViz(id){
const i=state.viz.indexOf(id);
if(i>=0)state.viz.splice(i,1);
else{if(state.viz.length>=3){flash("Max 3 visualizers");return;}state.viz.push(id);}
rebuildViz();save();updateVizPills();
flash(state.viz.length?"Visualizers · "+state.viz.length+"/3":"Visualizers off");
}
function updateViz(t,dt){
// "Bass hue": rotate the whole stack's hue, accelerated by bass — a cool live effect.
if(state.vizBassHue){
vizHuePhase=(vizHuePhase+dt*(0.03+A.bass*1.25))%1;
const h=vizBaseHue()+vizHuePhase;
for(const v of vizActive){v.prm.hue=h;tintViz(v.inst.root,h);}
}
// global beat punch — every visualizer pops a touch on the beat.
const s=1+Math.min(0.5,A.beat*0.12+A.energy*0.04);
vizGroup.scale.setScalar(s);
for(const v of vizActive)v.inst.update(t,dt);
}
/* ================= PARTY MODES ================= */
const MODES=[
{name:"Speakeasy",shape:"disc",spin:"record",bg:"nebula",exposure:1.0,bloom:{s:0.7,r:0.5,t:0.85},
mat:{metalness:1,roughness:0.3,clearcoat:0.6,clearcoatRoughness:0.2,emissiveBoost:0.4,env:1.4},
palette:"gold",orbitCount:3,strobe:false,particle:"spark",colA:0x2a1c08,colB:0x0a0712,colC:0xd9a441},