Repository navigation
Expand file tree
/
Copy pathvisualizer.html
More file actions
1465 lines (1239 loc) · 63.1 KB
/
Copy pathvisualizer.html
File metadata and controls
1465 lines (1239 loc) · 63.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0">
<title>3D Particle Master Control</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.8.49/Tone.min.js"></script>
<style>
/* --- CSS Custom Properties for Theming --- */
:root {
--primary-color: #4f46e5;
--primary-color-dark: #4338ca;
--primary-color-shadow: rgba(79, 70, 229, 0.5);
}
/* Custom CSS to match the Control Panel screenshot style */
body {
font-family: 'Inter', sans-serif;
margin: 0;
overflow: hidden;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #0d0e13;
cursor: default; /* Start with default cursor */
}
#visualizer-container {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 0;
}
#controls-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
z-index: 10;
transition: opacity 0.5s ease-in-out, visibility 0.5s;
}
#controls {
width: 90vw;
max-width: 400px;
/* Solid white background */
background: #ffffff;
border-radius: 20px;
/* Neumorphic Shadow: Only dark shadow remains for lift */
box-shadow:
0px 8px 30px rgba(0, 0, 0, 0.6);
padding: 1rem;
color: #333;
}
.hidden-controls {
opacity: 0;
visibility: hidden;
pointer-events: none;
}
.quick-setting-item {
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
padding: 0.5rem 0.25rem;
cursor: pointer;
border-radius: 12px;
transition: background 0.2s;
}
.quick-setting-item:hover {
background: rgba(0, 0, 0, 0.05);
}
.quick-setting-icon {
width: 44px;
height: 44px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 0.25rem;
transition: background 0.2s, transform 0.1s;
}
.quick-setting-icon:active {
transform: scale(0.95);
}
/* Active state styles now use the custom property */
.active-icon {
background: var(--primary-color);
color: white;
}
.inactive-icon {
background: rgba(0, 0, 0, 0.1);
color: var(--primary-color);
}
/* UPDATED START BUTTON STYLING (Pill Shape) */
.control-button {
width: 100%;
padding: 0.85rem;
font-size: 0.9rem;
font-weight: 700;
color: #ffffff;
/* Use custom properties for gradient background */
background: linear-gradient(135deg, var(--primary-color-dark), var(--primary-color));
border: none;
border-radius: 9999px; /* PILL SHAPE */
cursor: pointer;
box-shadow: 0 6px 15px var(--primary-color-shadow);
transition: all 0.2s ease;
}
.control-button:hover {
background: linear-gradient(135deg, var(--primary-color), var(--primary-color-dark));
box-shadow: 0 8px 20px var(--primary-color-shadow);
transform: translateY(-2px);
}
.control-button:active {
transform: translateY(1px);
box-shadow: 0 2px 5px var(--primary-color-shadow);
}
/* New Range Slider Styling for a Fresh Look */
input[type="range"] {
-webkit-appearance: none;
width: 100%;
height: 6px;
background: rgba(0, 0, 0, 0.1);
border-radius: 3px;
outline: none;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 18px;
height: 18px;
border-radius: 50%;
/* Use custom property for thumb color */
background: var(--primary-color);
cursor: pointer;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
transition: background 0.1s;
}
input[type="range"]::-webkit-slider-thumb:hover {
/* Use custom property for hover color */
background: var(--primary-color-dark);
}
/* Styling for the canvas cursor when interactive */
#visualizer-container canvas {
cursor: grab;
}
#visualizer-container canvas.grabbing {
cursor: grabbing;
}
/* Styling for the hidden file input */
#audioFile {
display: none;
}
/* UPDATED FILE UPLOAD BUTTON STYLING (Ghost Button, Pill Shape) */
.file-input-label {
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
width: 100%;
padding: 0.85rem 1rem;
background-color: transparent;
/* Use custom property for border/text color */
border: 2px solid var(--primary-color);
border-radius: 9999px; /* PILL SHAPE */
cursor: pointer;
font-weight: 600;
color: var(--primary-color);
font-size: 0.9rem;
transition: background-color 0.2s, color 0.2s, border-color 0.2s;
}
.file-input-label:hover {
background-color: #eef2ff;
color: var(--primary-color-dark);
border-color: var(--primary-color-dark);
}
/* Central toggle button style */
#toggleControlsButton {
position: absolute;
top: -24px;
left: 50%;
transform: translateX(-50%);
width: 48px;
height: 48px;
border-radius: 50%;
background: #e0e0e0;
border: 4px solid rgba(255, 255, 255, 1.0);
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
transition: transform 0.2s, background 0.2s;
}
#toggleControlsButton:hover {
background: #dadada;
}
#toggleControlsButton svg {
color: var(--primary-color); /* Use custom property for toggle icon */
width: 24px;
height: 24px;
transition: transform 0.3s;
}
/* CHROME OS STYLE STATUS BAR */
#status-bar {
background: rgba(255, 255, 255, 1.0);
color: #374151;
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border-radius: 24px 24px 0 0;
box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.3);
position: fixed;
bottom: 0;
left: 0;
right: 0;
width: 100%;
height: 56px;
padding: 0 1.5rem;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.9rem;
font-weight: 500;
z-index: 20;
}
/* Battery Status styles */
.status-text {
font-weight: 500;
font-size: 0.9rem;
transition: color 0.3s ease;
}
#battery-status {
display: flex;
align-items: center;
padding: 0.3rem 0.6rem;
border-radius: 8px;
cursor: default;
transition: background 0.2s;
}
.battery-icon-ring {
width: 28px;
height: 28px;
margin-right: 0.5rem;
display: block;
}
#battery-level-text {
font-size: 0.9rem;
font-weight: 700;
color: #374151;
line-height: 1;
transition: color 0.3s ease;
}
/* Custom Header accent */
#controls-header {
border-radius: 0 0 4px 4px;
padding-bottom: 1rem;
margin-bottom: 1rem;
}
/* Style for the music icon in the status bar */
#music-status-icon {
transition: transform 0.2s ease-out;
}
#music-status-icon.playing {
/* Small continuous pulse/animation to indicate activity */
animation: pulse-ring 1s infinite;
}
@keyframes pulse-ring {
0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4); }
70% { box-shadow: 0 0 0 5px rgba(16, 185, 129, 0); }
100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
}
</style>
</head>
<body>
<div id="visualizer-container"></div>
<div id="controls-overlay">
<div id="controls">
<div id="controls-header" class="flex justify-start items-center">
<!-- No content here -->
</div>
<!-- SLIDERS MOVED TO THE TOP -->
<div class="space-y-4 mb-6">
<div class="flex items-center space-x-3">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 text-gray-600" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 8a5 5 0 0 1 0 8"/><path d="M17.66 6.34a9 9 0 0 1 0 11.32"/><path d="M2 10h3l5-5v14l-5-5H2z"/></svg>
<input type="range" min="-30" max="0" value="-6" step="1" id="volumeSlider" class="flex-grow">
<span class="text-sm font-semibold text-gray-700 w-8 text-right">Vol</span>
</div>
<div class="flex items-center space-x-3">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 text-gray-600" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M20 12h2M2 12h2"/></svg>
<input type="range" min="1" max="5" value="2" step="0.1" id="sizeSlider" class="flex-grow">
<span class="text-sm font-semibold text-gray-700 w-8 text-right">Size</span>
</div>
</div>
<!-- Quick Settings: Removed the border-t and pt-4 classes -->
<div class="grid grid-cols-4 gap-y-3 mb-6 text-sm">
<div class="quick-setting-item" id="toggleMotion">
<div class="quick-setting-icon active-icon" id="iconMotion">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 12a2.49 2.49 0 0 1 2.5-2.5c2.5 0 2.5 5 5 5s2.5-5 5-5 2.5 5 5 5 2.5-2.5 2.5-2.5"/></svg>
</div>
<span class="font-medium text-gray-800">Motion</span>
<span class="text-xs text-green-600 font-semibold" id="statusMotion">Active</span>
</div>
<div class="quick-setting-item" id="toggleHighFreq">
<div class="quick-setting-icon active-icon" id="iconHighFreq">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2l-3 8h5l-6 12l2-8h-5z"/></svg>
</div>
<span class="font-medium text-gray-800">High Freq</span>
<span class="text-xs text-green-600 font-semibold" id="statusHighFreq">Pulse ON</span>
</div>
<div class="quick-setting-item" id="toggleBass">
<div class="quick-setting-icon active-icon" id="iconBass">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 8a5 5 0 0 1 0 8"/><path d="M17.66 6.34a9 9 0 0 1 0 11.32"/><path d="M2 10h3l5-5v14l-5-5H2z"/></svg>
</div>
<span class="font-medium text-gray-800">Bass React</span>
<span class="text-xs text-green-600 font-semibold" id="statusBass">Active</span>
</div>
<!-- PARTICLE DESIGN TOGGLE -->
<div class="quick-setting-item" id="cycleDesign">
<div class="quick-setting-icon active-icon" id="iconDesign">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="m18 8-5 4 4 5L7 12"/></svg>
</div>
<span class="font-medium text-gray-800">Design</span>
<span class="text-xs text-green-600 font-semibold" id="statusDesign">Swarm</span>
</div>
<div class="quick-setting-item" id="cycleTheme">
<!-- Icon color will be set dynamically in JS to match theme.primary -->
<div class="quick-setting-icon inactive-icon" id="iconTheme">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 7c-4.4 0-8 3.6-8 8s3.6 8 8 8c3 0 5.6-1.7 6.9-4.2M12 7V4M12 21v-3"/><path d="M12 7a8 8 0 0 1 8 8c0 3-1.7 5.6-4.2 6.9"/><path d="M12 7a8 8 0 0 0-8 8c0 3 1.7 5.6 4.2 6.9"/></svg>
</div>
<span class="font-medium text-gray-800">Theme</span>
<span class="text-xs text-gray-600 font-semibold" id="statusTheme">Indigo/Pink</span>
</div>
<div class="quick-setting-item" id="toggleBackground">
<div class="quick-setting-icon inactive-icon text-gray-600" id="iconBackground">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/></svg>
</div>
<span class="font-medium text-gray-800">Night Mode</span>
<span class="text-xs text-gray-600 font-semibold" id="statusBackground">OFF (Dark)</span>
</div>
</div>
<!-- MODIFIED BUTTON LAYOUT: Pill shapes and new icons applied -->
<div class="flex space-x-3 mb-4">
<label for="audioFile" class="file-input-label flex-1">
<!-- NEW CLEAN UPLOAD ICON (Upload Cloud) -->
<svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"/><path d="M12 12v9"/><path d="m16 16-4-4-4 4"/></svg>
<span id="fileNameDisplay" class="text-sm">Tap to Upload Music</span>
</label>
<button id="startButton" class="control-button flex-1 flex items-center justify-center space-x-2">
<!-- UPDATED CLEAN START ICON (Play Circle) -->
<svg id="startPauseIcon" xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"/>
<!-- Refined Play Triangle for a fresh look -->
<polygon fill="white" stroke="none" points="9.5 8 16.5 12 9.5 16"/>
</svg>
<span id="startButtonText">Start Synthetic Beat</span>
</button>
</div>
<!-- Hidden file input is placed outside the flex container -->
<input type="file" accept="audio/*" id="audioFile">
<div class="text-center text-xs mt-3 text-gray-500">
Tap the screen to rotate and pinch/scroll to zoom.
</div>
</div>
</div>
<div id="status-bar">
<button id="toggleControlsButton" aria-label="Toggle Control Panel">
<svg id="toggleIcon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
<div id="status-left">
<div id="battery-status">
<svg id="batteryIconRing" class="battery-icon-ring" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
</svg>
<span id="battery-level-text">--%</span>
</div>
</div>
<!-- UPDATED RIGHT-SIDE STATUS: Includes Music Icon and Time -->
<div class="flex items-center space-x-4">
<div id="music-status-icon" class="text-white bg-green-600 rounded-full p-1 shadow-md hidden">
<!-- Speaker/Music Icon (Clean Stroke-based update) -->
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>
<path d="M15.54 8.46a5 5 0 0 1 0 7.07"></path>
<path d="M19.07 4.93a10 10 0 0 1 0 14.14"></path>
</svg>
</div>
<span id="status-time" class="status-text">--:--:--</span>
</div>
</div>
<script>
// Global variables for Firebase access (required by the environment, though not used here)
const appId = typeof __app_id !== 'undefined' ? __app_id : 'default-app-id';
const firebaseConfig = typeof __firebase_config !== 'undefined' ? JSON.parse(__firebase_config) : {};
const initialAuthToken = typeof __initial_auth_token !== 'undefined' ? __initial_auth_token : null;
// --- Three.js Setup ---
let scene, camera, renderer, particles, geometry, material;
let positions, velocities, colors;
let PARTICLE_COUNT; // Now dynamic based on mode
const MAX_RANGE = 200;
const DRAG = 0.98;
const REPEL_STRENGTH = 0.005;
// --- Particle Mode Configurations ---
const PARTICLE_MODES = [
// Mode 0: Default Swarm
{ name: "Swarm", count: 10000, size: 2.0, repulsionFactor: 1.0, initialSpread: 0.1, movementSpeed: 0.0001 },
// Mode 1: Spherical Shell
{ name: "Sphere", count: 3000, size: 3.5, repulsionFactor: 1.5, initialSpread: 0.2, movementSpeed: 0.001 },
// Mode 2: Cubic Grid
{ name: "Matrix", count: 5000, size: 1.5, repulsionFactor: 0.8, initialSpread: 0.3, movementSpeed: 0.0005 }
];
// --- FPS Tracking (variables kept for time tracking) ---
let lastTime = 0;
// --- Control State ---
const controlsState = {
motion: true,
highFreq: true,
bass: true,
backgroundDark: true,
themeIndex: 0,
particleSize: 2,
controlsVisible: true,
particleModeIndex: 0 // NEW: Track particle design mode
};
// --- UPDATED COLOR THEMES with CSS variable values ---
const COLOR_THEMES = [
// Indigo/Pink (Default)
{
name: "Indigo/Pink",
initial: [0.6, 0.8, 0.5], high: [0.95, 0.9, 0.7],
primary: '#4f46e5', primaryDark: '#4338ca', primaryShadow: 'rgba(79, 70, 229, 0.5)',
highColor: '#fb7185'
},
// Fire (Orange/Yellow)
{
name: "Fire",
initial: [0.1, 0.8, 0.5], high: [0.0, 1.0, 0.9],
primary: '#ea580c', primaryDark: '#c2410c', primaryShadow: 'rgba(234, 88, 12, 0.5)',
highColor: '#fef3c7'
},
// Ocean (Blue/Cyan)
{
name: "Ocean",
initial: [0.55, 0.9, 0.5], high: [0.35, 0.9, 0.8],
primary: '#2563eb', primaryDark: '#1e40af', primaryShadow: 'rgba(37, 99, 235, 0.5)',
highColor: '#a7f3d0'
},
];
// --- Camera Controls ---
let cameraRadius = 150;
const MIN_ZOOM = 50;
const MAX_ZOOM = 400;
let isDragging = false;
let previousMousePosition = { x: 0, y: 0 };
const rotateSpeed = 0.005;
let cameraAngle = { x: 0, y: 0.5 }; // Set initial view angle for 3D effect
let initialTouchDistance = null;
// --- Tone.js Setup ---
let fft, source, masterVolume;
let isPlaying = false;
let noise, kick;
let customFileLoaded = false;
// NEW: UI references for status
let musicStatusIcon;
let startPauseIcon;
const AUDIO_PARAMS = {
fftSize: 512,
bassRange: [20, 150],
midRange: [150, 2000],
highRange: [2000, 10000]
};
let audioData = { bass: 0, mid: 0, high: 0 };
/**
* Converts frequency range to FFT bin indices.
*/
function freqToBin(startHz, endHz, sampleRate, fftSize) {
const binWidth = sampleRate / fftSize;
return [
Math.floor(startHz / binWidth),
Math.min(fftSize / 2 - 1, Math.ceil(endHz / binWidth))
];
}
/**
* Initializes the Tone.js audio context, master volume, and FFT analyzer.
*/
function initAudio() {
// Master Volume control node
masterVolume = new Tone.Volume(document.getElementById('volumeSlider').value).toDestination();
// Create the FFT analyzer and connect it
fft = new Tone.FFT(AUDIO_PARAMS.fftSize).connect(masterVolume);
// Setup synthetic fallback components
noise = new Tone.Noise("pink");
kick = new Tone.MembraneSynth({
envelope: { attack: 0.005, decay: 0.8, sustain: 0.0, release: 0.0 }
});
// Define a simple looping beat for the fallback
Tone.Transport.scheduleRepeat(time => {
kick.triggerAttackRelease("C1", "8n", time);
noise.volume.setValueAtTime(Math.random() > 0.6 ? -15 : -10, time, 0.01);
}, "4n");
Tone.Transport.bpm.value = 120;
// CONNECT KICK AND NOISE TO FFT/MASTER VOLUME CHAIN
const synthMix = new Tone.Channel();
kick.connect(synthMix);
noise.connect(synthMix);
source = synthMix;
// Initial button text setup
document.getElementById('startButtonText').textContent = 'Start Synthetic Beat';
}
/**
* Loads and sets up the user's uploaded audio file.
*/
function setupAudioFile(file) {
// Clean up existing source if it's a Tone.Player
if (source instanceof Tone.Player) {
if (source.state === 'started') source.stop();
source.dispose();
}
// If the synthetic beat is running, stop the transport to prepare for the player
if (isPlaying && !(source instanceof Tone.Player)) {
Tone.Transport.stop();
noise.stop();
}
const url = URL.createObjectURL(file);
const player = new Tone.Player(url, () => {
console.log("Audio file loaded successfully.");
// Text simplified for better fit in the two-column layout
document.getElementById('fileNameDisplay').textContent = `Loaded: ${file.name.substring(0, 15)}...`;
});
player.loop = true;
source = player;
customFileLoaded = true;
document.getElementById('startButtonText').textContent = isPlaying ? 'Pause Visualization' : 'Visualize Track';
}
/**
* Analyzes the raw FFT data and aggregates energy into specific bands.
*/
function analyzeAudio() {
if (!fft) return;
const spectrum = fft.getValue();
const numBins = spectrum.length;
const sampleRate = Tone.context.sampleRate;
// Helper function to calculate average gain for a bin range
const avg = (arr, start, end) => {
let sum = 0;
for (let i = start; i < end; i++) {
// Use Tone.dbToGain to convert decibel values to linear gain
sum += Tone.dbToGain(spectrum[i]);
}
return sum / (end - start);
};
// Calculate bin indices for audio ranges
const [bStart, bEnd] = freqToBin(AUDIO_PARAMS.bassRange[0], AUDIO_PARAMS.bassRange[1], sampleRate, numBins * 2);
const [mStart, mEnd] = freqToBin(AUDIO_PARAMS.midRange[0], AUDIO_PARAMS.midRange[1], sampleRate, numBins * 2);
const [hStart, hEnd] = freqToBin(AUDIO_PARAMS.highRange[0], AUDIO_PARAMS.highRange[1], sampleRate, numBins * 2);
let bassEnergy = avg(spectrum, bStart, bEnd);
let midEnergy = avg(spectrum, mStart, mEnd);
let highEnergy = avg(spectrum, hStart, hEnd);
// Mapping and clamping for visualization scale
// Using smoothing filter to prevent overly rapid jitter
audioData.bass = (audioData.bass * 0.8) + (Math.min(10, Math.max(0, bassEnergy * 5)) * 0.2);
audioData.mid = (audioData.mid * 0.8) + (Math.min(5, Math.max(0, midEnergy * 3)) * 0.2);
audioData.high = (audioData.high * 0.8) + (Math.min(3, Math.max(0, highEnergy * 2)) * 0.2);
}
/**
* Initializes the Three.js scene and camera.
*/
function initScene() {
const container = document.getElementById('visualizer-container');
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = cameraRadius;
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(controlsState.backgroundDark ? 0x0d0e13 : 0xc0d7ff, 1);
container.appendChild(renderer.domElement);
// Initialize particles with the default mode
setParticleMode(controlsState.particleModeIndex);
// --- Attach Control Listeners ---
window.addEventListener('resize', onWindowResize);
renderer.domElement.addEventListener('mousedown', onPointerDown);
document.addEventListener('mouseup', onPointerUp);
document.addEventListener('mousemove', onPointerMove);
renderer.domElement.addEventListener('wheel', onMouseWheel);
// Mobile/Touch Support
renderer.domElement.addEventListener('touchstart', onPointerDown, { passive: false });
document.addEventListener('touchend', onPointerUp);
document.addEventListener('touchmove', onPointerMove, { passive: false });
}
/**
* Sets up the particle system based on the current mode configuration.
*/
function setParticleMode(index) {
controlsState.particleModeIndex = index;
const mode = PARTICLE_MODES[index];
PARTICLE_COUNT = mode.count;
// 1. Remove old particles
if (particles) {
scene.remove(particles);
particles.geometry.dispose();
particles.material.dispose();
}
// 2. Setup new arrays
positions = new Float32Array(PARTICLE_COUNT * 3);
velocities = new Float32Array(PARTICLE_COUNT * 3);
colors = new Float32Array(PARTICLE_COUNT * 3);
// 3. Initialize positions and colors
initializeParticlePositions(mode.name, mode.initialSpread);
updateParticleColors();
// 4. Create new geometry and material
geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
material = new THREE.PointsMaterial({
size: controlsState.particleSize, // Use current slider size
vertexColors: true,
transparent: true,
blending: THREE.AdditiveBlending,
sizeAttenuation: true,
});
// 5. Create and add new particles
particles = new THREE.Points(geometry, material);
scene.add(particles);
// Update UI status
document.getElementById('statusDesign').textContent = mode.name;
}
/**
* Initializes particle positions and resets velocities based on the selected mode.
*/
function initializeParticlePositions(modeName, initialSpreadFactor) {
const initialSpread = MAX_RANGE * initialSpreadFactor;
for (let i = 0; i < PARTICLE_COUNT; i++) {
const i3 = i * 3;
// Reset velocities
velocities[i3] = 0;
velocities[i3 + 1] = 0;
velocities[i3 + 2] = 0;
if (modeName === 'Sphere') {
// Place particles on a sphere surface using Fibonacci sphere mapping
const radius = initialSpread * 0.9;
const N = PARTICLE_COUNT;
const goldenRatio = (1 + Math.sqrt(5)) / 2;
const iNormalized = i / goldenRatio;
const theta = 2 * Math.PI * (iNormalized - Math.floor(iNormalized));
const phi = Math.acos(1 - 2 * i / N);
positions[i3] = radius * Math.sin(phi) * Math.cos(theta);
positions[i3 + 1] = radius * Math.cos(phi);
positions[i3 + 2] = radius * Math.sin(phi) * Math.sin(theta);
} else if (modeName === 'Matrix') {
// Place particles in a cubic grid
const grid = Math.ceil(Math.cbrt(PARTICLE_COUNT));
const xIndex = i % grid;
const yIndex = Math.floor((i / grid) % grid);
const zIndex = Math.floor(i / (grid * grid));
// Calculate spacing to fill the initial spread volume
const spacing = initialSpread / grid;
const offset = initialSpread / 2;
positions[i3] = (xIndex * spacing) - offset;
positions[i3 + 1] = (yIndex * spacing) - offset;
positions[i3 + 2] = (zIndex * spacing) - offset;
} else { // Swarm (Default)
// Random positions within a small cube
positions[i3] = (Math.random() - 0.5) * initialSpread;
positions[i3 + 1] = (Math.random() - 0.5) * initialSpread;
positions[i3 + 2] = (Math.random() - 0.5) * initialSpread;
}
}
}
/**
* Sets particle colors based on the current theme index.
* Called on theme change or mode change.
*/
function updateParticleColors() {
const color = new THREE.Color();
const theme = COLOR_THEMES[controlsState.themeIndex];
const initialH = theme.initial[0];
const initialS = theme.initial[1];
const initialL = theme.initial[2];
for (let i = 0; i < PARTICLE_COUNT; i++) {
const i3 = i * 3;
// Set color based on current theme, adding slight randomness to lightness
color.setHSL(initialH + Math.random() * 0.05, initialS, initialL + Math.random() * 0.2);
colors[i3] = color.r;
colors[i3 + 1] = color.g;
colors[i3 + 2] = color.b;
}
if (particles) {
particles.geometry.attributes.color.needsUpdate = true;
}
}
/**
* Handles window resizing for responsiveness.
*/
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
/**
* Updates camera position based on user drag input (spherical coordinates).
*/
function updateCameraControls() {
// Clamp vertical rotation to prevent flipping
cameraAngle.x = Math.max(-Math.PI / 2 + 0.01, Math.min(Math.PI / 2 - 0.01, cameraAngle.x));
const radius = cameraRadius;
// Convert spherical angles to Cartesian coordinates
camera.position.x = radius * Math.sin(cameraAngle.y) * Math.cos(cameraAngle.x);
camera.position.y = radius * Math.sin(cameraAngle.x);
camera.position.z = radius * Math.cos(cameraAngle.y) * Math.cos(cameraAngle.x);
camera.lookAt(scene.position);
}
/**
* The core logic for particle "intelligence" and movement.
*/
function updateParticles() {
const positionsArray = particles.geometry.attributes.position.array;
const colorArray = particles.geometry.attributes.color.array;
const { bass, mid, high } = audioData;
const theme = COLOR_THEMES[controlsState.themeIndex];
const mode = PARTICLE_MODES[controlsState.particleModeIndex];
// Apply size change from slider
material.size = controlsState.particleSize;
material.needsUpdate = true;
const currentRepelStrength = REPEL_STRENGTH * mode.repulsionFactor;
const timeFactor = Date.now() * mode.movementSpeed;
for (let i = 0; i < PARTICLE_COUNT; i++) {
const i3 = i * 3;
let x = positionsArray[i3];
let y = positionsArray[i3 + 1];
let z = positionsArray[i3 + 2];
let vx = velocities[i3];
let vy = velocities[i3 + 1];
let vz = velocities[i3 + 2];
if (controlsState.motion) {
// 1. Central Repulsion / Cohesion
const distanceSq = x * x + y * y + z * z;
const distance = Math.sqrt(distanceSq);
let repelForce = currentRepelStrength * (1 + bass * 0.5);
if (distance > MAX_RANGE * 0.8) {
repelForce *= -0.5; // Pull back if too far (cohesion)
}
vx += x * repelForce;
vy += y * repelForce;
vz += z * repelForce;
// Mode-specific base motion
if (mode.name === 'Matrix') {
// Gentle wave effect to maintain structure but allow flow
const noiseVal = Math.sin(timeFactor * 10 + i * 0.01) * 0.005;
vx += (z * noiseVal);
vy += (x * noiseVal);
vz += (y * noiseVal);
} else if (mode.name === 'Sphere') {
// Gentle rotation and outward breath
const rotationSpeed = 0.0001;
vx += z * rotationSpeed;
vz -= x * rotationSpeed;
// Add a subtle outward breath based on bass
const breath = bass * 0.01;
vx += (x / distance) * breath;
vy += (y / distance) * breath;
vz += (z / distance) * breath;
}
// 2. Music Reaction (Intelligence)
// Bass reaction: Outward push/Explosion (Controlled by toggle)
if (controlsState.bass && bass > 0.5) {
if (i % 100 < bass * 50) {
// Strong, directed push
const push = bass * 0.8;
vx += (x / distance) * push;
vy += (y / distance) * push;
vz += (z / distance) * push;
}
}
// Mid reaction: Turbulence/Jitter
const jitter = (mid * 0.08) * (Math.random() - 0.5);
vx += jitter;
vy += jitter;
vz += jitter;
// High reaction: Speed and Color Pulse (Controlled by toggle)
if (controlsState.highFreq) {
if (high > 0.1) {
// Increase velocity based on high frequency energy
vx *= (1 + high * 0.02);
vy *= (1 + high * 0.02);
vz *= (1 + high * 0.02);
// Change color towards the theme's 'high' color (simple color shift)
colorArray[i3] = Math.min(1.0, colorArray[i3] + high * 0.05 * theme.high[0]);
colorArray[i3 + 1] = Math.min(1.0, colorArray[i3 + 1] + high * 0.05 * theme.high[1]);
colorArray[i3 + 2] = Math.min(1.0, colorArray[i3 + 2] + high * 0.05 * theme.high[2]);
} else {
// Smoothly fade colors back towards the initial theme color
const initialColor = new THREE.Color().setHSL(theme.initial[0], theme.initial[1], theme.initial[2]);
colorArray[i3] = (colorArray[i3] * 0.99) + (initialColor.r * 0.01);
colorArray[i3 + 1] = (colorArray[i3 + 1] * 0.99) + (initialColor.g * 0.01);
colorArray[i3 + 2] = (colorArray[i3 + 2] * 0.99) + (initialColor.b * 0.01);
}
}
// 3. Update Position & Apply Drag
vx *= DRAG;
vy *= DRAG;
vz *= DRAG;
// Cap velocity (increased max velocity for more action)
const maxVel = 8;
vx = Math.min(maxVel, Math.max(-maxVel, vx));
vy = Math.min(maxVel, Math.max(-maxVel, vy));
vz = Math.min(maxVel, Math.max(-maxVel, vz));
positionsArray[i3] += vx;
positionsArray[i3 + 1] += vy;
positionsArray[i3 + 2] += vz;
velocities[i3] = vx;
velocities[i3 + 1] = vy;
velocities[i3 + 2] = vz;
} else {
// If motion is off, dampen velocity completely (particles settle)
velocities[i3] *= 0.9;
velocities[i3 + 1] *= 0.9;
velocities[i3 + 2] *= 0.9;
positionsArray[i3] += velocities[i3];
positionsArray[i3 + 1] += velocities[i3 + 1];
positionsArray[i3 + 2] += velocities[i3 + 2];
}
}
particles.geometry.attributes.position.needsUpdate = true;
particles.geometry.attributes.color.needsUpdate = true;
}
/**
* Updates the current time display in the status bar.
*/
function updateTime() {
const now = new Date();
const timeString = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
document.getElementById('status-time').textContent = timeString;
}
/**
* Sets the visual status of the battery (circular ring and percentage text).
* @param {number} level - Battery percentage (0-100).
* @param {boolean} charging - True if the device is currently charging.
*/
function setBatteryStatusUI(level, charging) {
const batteryIconSvg = document.getElementById('batteryIconRing');
const batteryText = document.getElementById('battery-level-text');
const timeText = document.getElementById('status-time');
batteryText.textContent = `${level}%`;
// Default colors
const darkColor = '#374151'; // Main text/ring color
const lowColor = '#ef4444'; // Red for low battery
const chargeColor = '#10b981'; // Green for charging
const defaultTrackColor = darkColor;
let ringColor = darkColor;
let centerFillColor = darkColor;
let trackColor = defaultTrackColor;
let trackOpacity = 0.25;
let currentTextColor = darkColor; // Default color for all text
if (level < 20 && !charging) {
ringColor = lowColor;