-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsketch.js
More file actions
1040 lines (903 loc) · 31.3 KB
/
sketch.js
File metadata and controls
1040 lines (903 loc) · 31.3 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
let fonts = {}
let builtInFonts = {
'Compagnon Roman': { file: 'fonts/Compagnon-Roman.otf', credit: 'Juliette Duhé & Léa Pradine' },
'Interlope': { file: 'fonts/Interlope-Regular.otf', credit: 'Gabriel Dubourg' },
'Karrik': { file: 'fonts/Karrik-Regular.otf', credit: 'Jean-Baptiste Morizot & Lucas Le Bihan' },
'Mess': { file: 'fonts/Mess.otf', credit: 'Tezzo Suzuki' },
'Basteleur': { file: 'fonts/Basteleur-Bold.otf', credit: 'Keussel' },
'Kaeru Kaeru': { file: 'fonts/kaerukaeru-Regular.otf', credit: 'Isabel Motz' }
}
let font, points = []
let sliders = {}
let labels = {}
let song, analyzeSong, fft
let bass, mid, treble
let uiElements = []
let uiVisible = true
let uiContainer
let textInput, currentText
let peakDetect
let audioReactiveStrokeCheckbox, audioReactiveSizeCheckbox
let colorWaveOffsetCheckbox, filledCirclesCheckbox, transparentBgCheckbox
let seekSlider, isSeeking = false
let panX = 0, panY = 0, zoomLevel = 1
let isDragging = false, lastMouseX, lastMouseY
let isRecording = false, recordStartFrame = 0
let recordButton
let fontSelect
let paletteSelect
let audioNameLabel
let playButton, fontUploadTrigger, audioUploadTrigger
let helpButton, infoBox, toggleButton
let colorPalettes = {
'RGB': [[255, 0, 0], [0, 255, 0], [0, 0, 255]], // #FF0000 #00FF00 #0000FF
'Monochrome': [[255, 255, 255], [150, 150, 150], [75, 75, 75]], // #FFFFFF #969696 #4B4B4B
'Neon': [[255, 0, 255], [0, 255, 255], [255, 255, 0]], // #FF00FF #00FFFF #FFFF00
'Retro': [[255, 111, 97], [255, 209, 102], [6, 214, 160]], // #FF6F61 #FFD166 #06D6A0
'Pastel': [[255, 179, 186], [255, 223, 186], [186, 255, 201]], // #FFB3BA #FFDFBA #BAFFC9
'Vaporwave': [[255, 113, 206], [1, 247, 161], [127, 199, 255]], // #FF71CE #01F7A1 #7FC7FF
'Candy': [[255, 20, 147], [0, 255, 127], [255, 165, 0]], // #FF1493 #00FF7F #FFA500
'Electric': [[148, 0, 211], [255, 0, 0], [0, 255, 0]], // #9400D3 #FF0000 #00FF00
'Miami': [[255, 0, 128], [0, 255, 255], [255, 215, 0]], // #FF0080 #00FFFF #FFD700
'Twilight': [[72, 61, 139], [255, 105, 180], [255, 215, 0]], // #483D8B #FF69B4 #FFD700
'Arctic': [[0, 191, 255], [230, 230, 250], [255, 0, 255]], // #00BFFF #E6E6FA #FF00FF
'Desert': [[255, 69, 0], [255, 215, 0], [138, 43, 226]], // #FF4500 #FFD700 #8A2BE2
'Toxic': [[0, 255, 0], [255, 255, 0], [255, 0, 255]] // #00FF00 #FFFF00 #FF00FF
}
function preload() {
// Load all built-in fonts
for (let name in builtInFonts) {
fonts[name] = loadFont(builtInFonts[name].file);
}
// Load saved font or default to compagnon
let savedFont = getItem('selectedFont');
let fontName = savedFont !== null ? savedFont : 'Compagnon Roman';
// If the saved font is not one of the preloaded ones, fallback to compagnon
// The custom font will be loaded in setup() via loadSavedFont()
if (!fonts[fontName]) {
fontName = 'Compagnon Roman';
}
font = fonts[fontName];
}
function setup() {
// Create WebGL canvas for GPU-accelerated rendering
createCanvas(windowWidth, windowHeight, WEBGL)
// WebGL rendering optimizations
smooth();
frameRate(30); // Set to 30fps for consistent GIF recording
noFill()
stroke(255)
strokeWeight(1)
// Load saved pan and zoom values
let savedPanX = getItem('panX');
let savedPanY = getItem('panY');
let savedZoom = getItem('zoomLevel');
if (savedPanX !== null) panX = parseFloat(savedPanX);
if (savedPanY !== null) panY = parseFloat(savedPanY);
if (savedZoom !== null) zoomLevel = parseFloat(savedZoom);
// Use body as container for UI styling (all p5 elements are children of body)
uiContainer = select('body');
uiContainer.addClass('ui-container');
// Add toggle button for UI visibility
toggleButton = createButton('▼');
toggleButton.position(10, 10);
toggleButton.addClass('ui-toggle');
toggleButton.mousePressed(() => toggleUI(toggleButton));
// Add help button in top right
helpButton = createButton('?');
helpButton.position(windowWidth - 30, 10);
helpButton.addClass('ui-help');
// Create info box (hidden by default)
// Generate font credits from builtInFonts
let fontCredits = Object.entries(builtInFonts)
.map(([name, data]) => `${name.charAt(0).toUpperCase() + name.slice(1)} by ${data.credit}`)
.join(' • ');
infoBox = createDiv(`
<h3>Audiotype</h3>
<p>Audio-reactive tricolor typography</p>
<hr>
<p><b>Controls:</b></p>
<ul>
<li>Drag to pan</li>
<li>Scroll to zoom</li>
<li>Mess with the values</li>
</ul>
<p><b>Tips:</b></p>
<ul>
<li>Upload MP3 for audio reactivity</li>
<li>Upload custom OTF/TTF fonts</li>
</ul>
(both stay on your computer)
<hr>
<p><small>Fonts distributed by <a href="https://velvetyne.fr/">Velvetyne</a>:<br/>
${fontCredits}</small></p>
<hr>
<p><small>by ilesinge · <a href="https://github.com/ilesinge/audiotype">source</a></small></p>
`);
infoBox.position(windowWidth - 290, 45);
infoBox.addClass('ui-infobox');
helpButton.mousePressed(() => {
if (infoBox.style('display') === 'none') {
infoBox.style('display', 'block');
} else {
infoBox.style('display', 'none');
}
});
// Add color palette selector
let savedPalette = getItem('selectedPalette');
let paletteName = savedPalette !== null ? savedPalette : 'Vaporwave';
paletteSelect = createSelect();
for (let name in colorPalettes) {
paletteSelect.option(name);
}
paletteSelect.selected(paletteName);
paletteSelect.position(50, 10);
paletteSelect.addClass('ui-control');
paletteSelect.changed(() => {
storeItem('selectedPalette', paletteSelect.value());
});
// Add font selector
let savedFont = getItem('selectedFont');
let fontName = savedFont !== null ? savedFont : 'compagnon';
fontSelect = createSelect();
// Add built-in fonts
for (let name in builtInFonts) {
fontSelect.option(name);
}
// Add any custom fonts that were uploaded previously
for (let name in fonts) {
if (!(name in builtInFonts)) {
fontSelect.option(name);
}
}
fontSelect.selected(fontName);
fontSelect.position(170, 10);
fontSelect.addClass('ui-control');
fontSelect.changed(() => {
font = fonts[fontSelect.value()];
storeItem('selectedFont', fontSelect.value());
genType();
});
// Add Record GIF button below selects for easy access
recordButton = createButton('Record GIF');
recordButton.position(10, 40);
recordButton.addClass('ui-control');
recordButton.mousePressed(() => {
if (!isRecording) {
startRecording();
}
});
// Add font upload button
let fontUploadButton = createFileInput(handleFontFile);
fontUploadButton.addClass('ui-hidden');
uiElements.push(fontUploadButton);
fontUploadTrigger = createButton('Upload Font');
fontUploadTrigger.position(10, 70);
fontUploadTrigger.addClass('ui-control');
fontUploadTrigger.mousePressed(() => fontUploadButton.elt.click());
uiElements.push(fontUploadTrigger);
// Add text input box (below Upload Font button)
textInput = createElement('textarea', 'play\nground');
textInput.position(10, 100);
textInput.size(180, 32);
textInput.addClass('ui-textarea');
textInput.input(() => {
currentText = textInput.value();
storeItem('textContent', currentText);
genType();
});
// Load saved text or use default
let savedText = getItem('textContent');
if (savedText !== null) {
textInput.value(savedText);
currentText = savedText;
} else {
currentText = textInput.value();
}
// Create sliders with saved values
let yPos = 150;
createSliderWithLabel('factor', 'Amount', 0, 1, 0.4, 0.01, yPos, genType);
yPos += 25;
createSliderWithLabel('size', 'Circle Size', 0, 800, 100, 1, yPos);
yPos += 25;
createSliderWithLabel('sinsize', 'Wave Size', 0, 50, 10, 1, yPos);
yPos += 25;
createSliderWithLabel('sinwidth', 'Wave Frequency', 0.01, 2, 0.1, 0.01, yPos);
yPos += 25;
createSliderWithLabel('sinspeed', 'Wave Speed', 0, 0.4, 0.05, 0.01, yPos);
yPos += 25;
createSliderWithLabel('textsize', 'Text Size', 1, 20, 2, 0.1, yPos, genType);
yPos += 25;
createSliderWithLabel('lineheight', 'Line Height', 0.5, 2, 0.9, 0.01, yPos, genType);
yPos += 25;
createSliderWithLabel('colorsep', 'Color Separation', 0.1, 20, 4, 0.1, yPos);
yPos += 25;
createSliderWithLabel('strokeweight', 'Stroke Weight', 0.1, 5, 1, 0.1, yPos);
yPos += 25;
createSliderWithLabel('audiosmooth', 'Audio Smooth', 0, 0.99, 0.1, 0.01, yPos);
yPos += 25;
createSliderWithLabel('timeoffset', 'Time Offset (ms)', -100, 100, -40, 1, yPos);
yPos += 25;
createSliderWithLabel('strokepower', 'Stroke Reactivity', 0.5, 10, 2, 0.1, yPos);
yPos += 25;
createSliderWithLabel('sizepower', 'Size Reactivity', 0.5, 10, 2, 0.1, yPos);
yPos += 25;
createSliderWithLabel('quantize', 'Quantize Audio (0=off)', 0, 20, 4, 1, yPos);
yPos += 25;
createSliderWithLabel('alpha', 'Alpha', 0, 1, 0.5, 0.01, yPos);
// Initialize FFT for frequency analysis (128 bins for lower latency)
fft = new p5.FFT(sliders.audiosmooth.value(), 128);
yPos += 30;
// Add file upload button for audio
let audioUploadButton = createFileInput(handleAudioFile);
audioUploadButton.addClass('ui-hidden');
audioUploadButton.attribute('accept', '.mp3,.wav,.ogg');
uiElements.push(audioUploadButton);
audioUploadTrigger = createButton('Upload MP3');
audioUploadTrigger.position(10, yPos);
audioUploadTrigger.addClass('ui-control');
audioUploadTrigger.mousePressed(() => audioUploadButton.elt.click());
uiElements.push(audioUploadTrigger);
yPos += 25;
// Add play/pause button
playButton = createButton('▶');
playButton.position(10, yPos);
playButton.addClass('ui-play');
playButton.mousePressed(togglePlayPause);
// Add label for audio filename
audioNameLabel = createDiv('');
audioNameLabel.position(60, yPos + 2);
audioNameLabel.addClass('ui-label');
yPos += 25;
// Add seek slider for audio navigation (below play button)
seekSlider = createSlider(0, 100, 0, 0.1);
seekSlider.position(10, yPos);
seekSlider.addClass('ui-slider ui-seekbar');
seekSlider.input(() => {
if (song && song.isLoaded()) {
let seekTime = (seekSlider.value() / 100) * song.duration();
song.jump(seekTime);
if (analyzeSong && analyzeSong.isLoaded()) {
analyzeSong.jump(seekTime);
}
}
});
yPos += 25;
// Add audio reactive stroke checkbox
let savedStrokeReactive = getItem('audioReactiveStroke');
let defaultStrokeReactive = savedStrokeReactive !== null ? savedStrokeReactive === 'true' : false;
audioReactiveStrokeCheckbox = createCheckbox('Audio Reactive Stroke', defaultStrokeReactive);
audioReactiveStrokeCheckbox.position(10, yPos);
audioReactiveStrokeCheckbox.addClass('ui-checkbox');
audioReactiveStrokeCheckbox.changed(() => {
storeItem('audioReactiveStroke', audioReactiveStrokeCheckbox.checked().toString());
});
yPos += 20;
// Add audio reactive size checkbox
let savedSizeReactive = getItem('audioReactiveSize');
let defaultSizeReactive = savedSizeReactive !== null ? savedSizeReactive === 'true' : true;
audioReactiveSizeCheckbox = createCheckbox('Audio Reactive Size', defaultSizeReactive);
audioReactiveSizeCheckbox.position(10, yPos);
audioReactiveSizeCheckbox.addClass('ui-checkbox');
audioReactiveSizeCheckbox.changed(() => {
storeItem('audioReactiveSize', audioReactiveSizeCheckbox.checked().toString());
});
yPos += 20;
// Add color wave offset checkbox
let savedWaveOffset = getItem('colorWaveOffset');
let defaultWaveOffset = savedWaveOffset !== null ? savedWaveOffset === 'true' : true;
colorWaveOffsetCheckbox = createCheckbox('Color Wave Offset', defaultWaveOffset);
colorWaveOffsetCheckbox.position(10, yPos);
colorWaveOffsetCheckbox.addClass('ui-checkbox');
colorWaveOffsetCheckbox.changed(() => {
storeItem('colorWaveOffset', colorWaveOffsetCheckbox.checked().toString());
});
yPos += 20;
// Add filled circles checkbox
let savedFilledCircles = getItem('filledCircles');
let defaultFilledCircles = savedFilledCircles !== null ? savedFilledCircles === 'true' : false;
filledCirclesCheckbox = createCheckbox('Filled Circles', defaultFilledCircles);
filledCirclesCheckbox.position(10, yPos);
filledCirclesCheckbox.addClass('ui-checkbox');
filledCirclesCheckbox.changed(() => {
storeItem('filledCircles', filledCirclesCheckbox.checked().toString());
});
yPos += 20;
// Add transparent background checkbox
let savedTransparentBg = getItem('transparentBg');
let defaultTransparentBg = savedTransparentBg !== null ? savedTransparentBg === 'true' : false;
transparentBgCheckbox = createCheckbox('Day Mode', defaultTransparentBg);
transparentBgCheckbox.position(10, yPos);
transparentBgCheckbox.addClass('ui-checkbox');
transparentBgCheckbox.changed(() => {
storeItem('transparentBg', transparentBgCheckbox.checked().toString());
updateUIColors();
});
// Store all UI elements for toggling
uiElements.push(fontSelect);
uiElements.push(paletteSelect);
uiElements.push(audioNameLabel);
uiElements.push(playButton);
uiElements.push(textInput);
uiElements.push(audioReactiveStrokeCheckbox);
uiElements.push(audioReactiveSizeCheckbox);
uiElements.push(colorWaveOffsetCheckbox);
uiElements.push(filledCirclesCheckbox);
uiElements.push(transparentBgCheckbox);
uiElements.push(seekSlider);
uiElements.push(recordButton);
for (let name in sliders) {
uiElements.push(sliders[name]);
uiElements.push(labels[name]);
}
genType()
// Check for saved audio and font
loadSavedAudio();
loadSavedFont();
// Apply initial UI colors based on transparent background setting
updateUIColors();
}
function draw() {
if (transparentBgCheckbox.checked()) {
clear();
} else {
background(0);
}
// Apply pan and zoom transformations
push();
translate(panX, panY);
scale(zoomLevel);
// Cache checkbox states
let isAudioReactiveStroke = audioReactiveStrokeCheckbox.checked();
let isAudioReactiveSize = audioReactiveSizeCheckbox.checked();
let isColorWaveOffset = colorWaveOffsetCheckbox.checked();
let isFilledCircles = filledCirclesCheckbox.checked();
// Update seek slider position if not actively seeking
if (song && song.isLoaded() && !isSeeking) {
let progress = (song.currentTime() / song.duration()) * 100;
seekSlider.value(progress);
}
// Analyze audio frequencies
if (song && song.isLoaded() && song.isPlaying() &&
(isAudioReactiveStroke || isAudioReactiveSize)
) {
// Sync analyzeSong with playback song + time offset
let offsetSeconds = sliders.timeoffset.value() / 1000;
let targetTime = song.currentTime() + offsetSeconds;
if (analyzeSong && analyzeSong.isLoaded()) {
// Keep analyzeSong synchronized with offset
if (!analyzeSong.isPlaying()) {
analyzeSong.play();
}
// Sync position with offset
let timeDiff = Math.abs(analyzeSong.currentTime() - targetTime);
if (timeDiff > 0.05 && targetTime >= 0 && targetTime <= analyzeSong.duration()) {
analyzeSong.jump(targetTime);
}
}
// Set smoothing from slider (0 = no smoothing, 0.99 = max smoothing)
fft.smooth(sliders.audiosmooth.value());
fft.analyze();
// Use getEnergy for frequency bins (more accurate than manual binning)
// getEnergy returns 0-255 for the specified frequency range
// Custom frequency ranges for electronic music
// Bass: 20-140Hz (Kick & Sub)
bass = fft.getEnergy(20, 199);
// Mid: 200-3000Hz (Snare, Synths, Vocals)
mid = fft.getEnergy(200, 2000);
// Treble: 3000-14000Hz (Hi-hats, Cymbals)
treble = fft.getEnergy(2000, 14000);
// Map values to desired range
bass = map(bass, 50, 255, 0, 255);
mid = map(mid, 50, 255, 0, 255);
// Boost high frequencies as they tend to have lower energy
treble = map(treble, 50, 180, 0, 255);
// Apply quantization if enabled
let quantizeBins = sliders.quantize.value();
if (quantizeBins > 0) {
bass = quantizeValue(bass, 0, 255, quantizeBins);
mid = quantizeValue(mid, 0, 255, quantizeBins);
treble = quantizeValue(treble, 0, 255, quantizeBins);
}
} else {
// Default colors when audio is not playing or checkbox unchecked
bass = 255;
mid = 255;
treble = 255;
}
// WebGL is already centered, just apply the vertical offset
translate(0, -200)
// Cache slider values outside the loop
let baseStrokeWeight = sliders.strokeweight.value();
let baseSize = sliders.size.value() / 10;
let sep = sliders.colorsep.value();
let sinWidth = sliders.sinwidth.value();
let sinSpeed = sliders.sinspeed.value();
let sinSize = sliders.sinsize.value();
let strokePower = sliders.strokepower.value();
let sizePower = sliders.sizepower.value();
let alphaValue = sliders.alpha.value();
// Get current color palette
let palette = colorPalettes[paletteSelect.value()];
// Pre-compute colors with alpha
let alpha255 = 255 * alphaValue;
let color0 = color(palette[0][0], palette[0][1], palette[0][2], alpha255);
let color1 = color(palette[1][0], palette[1][1], palette[1][2], alpha255);
let color2 = color(palette[2][0], palette[2][1], palette[2][2], alpha255);
// Phase offset: one third of a wavelength (2π/3) for each color (if enabled)
let phaseOffset = isColorWaveOffset ? TWO_PI / 3 : 0;
// Pre-compute frame-based sin component
let framePhase = frameCount * sinSpeed;
// Shared draw params object
let params = {
baseStrokeWeight,
isAudioReactiveStroke,
isAudioReactiveSize,
isFilledCircles,
isAudioPlaying: song && song.isPlaying(),
strokePower,
sizePower
};
// Draw all points
let numPoints = points.length;
for(let i = 0; i < numPoints; i++) {
let p = points[i]
push()
// Draw three colored circles with frequency-based modulation
// Blue/Color3 from treble
s1 = baseSize + sin(i * sinWidth + framePhase) * sinSize
drawCircle(p.x, p.y, s1, treble, color2, params);
translate(-sep, 0)
// Red/Color1 from bass (phase offset: +2π/3 if enabled)
s2 = baseSize + sin(i * sinWidth + framePhase + phaseOffset) * sinSize
drawCircle(p.x, p.y, s2, bass, color0, params);
translate(0, -sep)
// Green/Color2 from mid (phase offset: +4π/3 if enabled)
s3 = baseSize + sin(i * sinWidth + framePhase + phaseOffset * 2) * sinSize
drawCircle(p.x, p.y, s3, mid, color1, params);
pop()
}
// End pan/zoom transformation
pop();
}
// Draw a single colored circle with pre-computed values
function drawCircle(x, y, baseSize, freqValue, c, p) {
// Apply audio-reactive stroke weight
if (p.isAudioReactiveStroke && p.isAudioPlaying) {
strokeWeight(map(freqValue, 50, 255, 0.1, p.baseStrokeWeight * p.strokePower));
} else {
strokeWeight(p.baseStrokeWeight);
}
// Apply audio-reactive size
let circleSize = baseSize;
if (p.isAudioReactiveSize && p.isAudioPlaying) {
circleSize = baseSize * map(freqValue, 50, 255, 0.5, p.sizePower);
}
stroke(c);
if (p.isFilledCircles) {
fill(c);
} else {
noFill();
}
circle(x, y, circleSize);
}
function genType() {
if (!font) return;
txtSize = width / 16 * sliders.textsize.value()
let lineSpacing = txtSize * sliders.lineheight.value();
// Split text by actual newlines (from textarea)
let texts = currentText.split('\n');
//let texts = [currentText];
textLeading(lineSpacing);
textAlign(RIGHT);
// Combine all points with spacing
points = [];
let yOffset = 0;
for (let i = 0; i < texts.length; i++) {
let bounds = font.textBounds(texts[i], 0, 0, txtSize)
let textPoints = font.textToPoints(texts[i], -bounds.w / 2, bounds.h / 2 + yOffset, txtSize, {
sampleFactor: map(sliders.factor.value(), 0, 1, 0, 0.8),
simplifyThreshold: 0
})
points = points.concat(textPoints);
yOffset += lineSpacing;
}
}
// Handle uploaded audio file
function handleAudioFile(file) {
if (file.type === 'audio') {
// Update label
if (audioNameLabel) audioNameLabel.html(file.name);
// Save to DB if file object is available
if (file.file) {
saveAudioToDB(file.file);
}
loadAudioFromSource(file.data);
} else {
console.error('Please upload an audio file');
}
}
// Handle uploaded font file
function handleFontFile(file) {
if (file.type === 'font' || file.name.endsWith('.otf') || file.name.endsWith('.ttf')) {
// Create a custom name from the filename (remove extension)
let customName = file.name.replace(/\.(otf|ttf)$/i, '');
// Save to DB if file object is available
if (file.file) {
saveFontToDB(file.file, customName);
}
// Load the font
loadFont(file.data, (loadedFont) => {
console.log('Custom font loaded successfully:', customName);
// Store the font
fonts[customName] = loadedFont;
// Add to selector if not already there
let optionExists = false;
for (let i = 0; i < fontSelect.elt.options.length; i++) {
if (fontSelect.elt.options[i].value === customName) {
optionExists = true;
break;
}
}
if (!optionExists) {
fontSelect.option(customName);
}
// Select and use the new font
fontSelect.selected(customName);
font = loadedFont;
storeItem('selectedFont', customName);
genType();
}, (error) => {
console.error('Error loading font:', error);
alert('Error loading font. Please make sure it is a valid .otf or .ttf file.');
});
} else {
console.error('Please upload a font file (.otf or .ttf)');
alert('Please upload a font file (.otf or .ttf)');
}
}
// Toggle UI visibility
function toggleUI(btn) {
uiVisible = !uiVisible;
for (let element of uiElements) {
if (uiVisible && element.elt.type !== 'file') {
console.log(element);
element.show();
} else {
element.hide();
}
}
// Update button text
btn.html(uiVisible ? '▼' : '▲');
}
// Update UI colors based on transparent background setting
function updateUIColors() {
let isTransparent = transparentBgCheckbox.checked();
// Toggle transparent-mode class on parent container
if (isTransparent) {
uiContainer.addClass('transparent-mode');
} else {
uiContainer.removeClass('transparent-mode');
}
}
// Create slider with label - generalized function
function createSliderWithLabel(name, label, min, max, defaultValue, step, yPos, callback = null) {
// Load saved value or use default
let savedValue = getSliderValue(name + 'slider', defaultValue);
console.log('Using saved value for', name, savedValue);
// Create slider
sliders[name] = createSlider(min, max, savedValue, step);
sliders[name].position(10, yPos);
sliders[name].addClass('ui-slider');
sliders[name].input(() => {
saveSliderValue(name + 'slider', sliders[name].value());
updateLabels(); // Update labels on input
if (callback) callback();
});
// Create label
labels[name] = createDiv(label + ': ' + savedValue);
labels[name].attribute('x-label', label);
labels[name].position(150, yPos + 4);
labels[name].addClass('ui-label');
}
// Update all labels in real-time
function updateLabels() {
for (let name in sliders) {
let labelText = labels[name].attribute('x-label');
labels[name].html(labelText + ': ' + sliders[name].value());
}
}
// Save slider value to localStorage
function saveSliderValue(name, value) {
console.log('Saving', name, value);
storeItem(name, value);
}
// Get slider value from localStorage
function getSliderValue(name, defaultValue) {
let value = getItem(name);
console.log('Loading', name, value);
return value === null ? defaultValue : parseFloat(value);
}
// Quantize a value into discrete bins
function quantizeValue(value, minVal, maxVal, numBins) {
// Calculate bin size
let binSize = (maxVal - minVal) / numBins;
// Find which bin the value falls into
let binIndex = floor((value - minVal) / binSize);
// Clamp to valid range
binIndex = constrain(binIndex, 0, numBins - 1);
// Return the center value of that bin
return minVal + (binIndex + 0.5) * binSize;
}
// Check if mouse is over infobox
function isMouseOverInfobox() {
if (!infoBox || infoBox.style('display') === 'none') {
return false;
}
let infoBoxX = windowWidth - 290;
let infoBoxY = 45;
let infoBoxWidth = 250;
let infoBoxHeight = 410; // Approximate height
return mouseX >= infoBoxX && mouseX <= infoBoxX + infoBoxWidth &&
mouseY >= infoBoxY && mouseY <= infoBoxY + infoBoxHeight;
}
// Mouse pressed - start dragging if not over UI
function mousePressed() {
// Don't pan if UI is visible and mouse is over UI area or infobox
if ((uiVisible && mouseX < 250 && mouseY < 700) || isMouseOverInfobox()) {
return; // Let UI handle the interaction
}
isDragging = true;
lastMouseX = mouseX;
lastMouseY = mouseY;
}
// Toggle play/pause state
function togglePlayPause() {
if (song && song.isLoaded()) {
if (song.isPlaying()) {
song.pause();
playButton.html('▶');
if (analyzeSong && analyzeSong.isLoaded()) {
analyzeSong.pause();
}
} else {
song.loop();
playButton.html('❚❚');
}
}
}
// Keyboard shortcuts
function keyPressed() {
// Ignore if focus is on an input element (textarea, input, etc.)
if (document.activeElement.tagName === 'TEXTAREA' ||
document.activeElement.tagName === 'INPUT') {
return;
}
// Spacebar for play/pause
if (key === ' ') {
togglePlayPause();
return false; // Prevent default scrolling
}
}
// Mouse dragged - pan the view
function mouseDragged() {
if (isDragging) {
let dx = mouseX - lastMouseX;
let dy = mouseY - lastMouseY;
panX += dx;
panY += dy;
lastMouseX = mouseX;
lastMouseY = mouseY;
}
}
// Mouse released - stop dragging
function mouseReleased() {
isDragging = false;
// Save pan position
storeItem('panX', panX);
storeItem('panY', panY);
}
// Mouse wheel - zoom in/out
function mouseWheel(event) {
// Don't zoom if UI is visible and mouse is over UI area or infobox
if ((uiVisible && (mouseX < 250 && mouseY < 350)) || isMouseOverInfobox()) {
return; // Let UI handle the interaction
}
// Zoom factor
let zoomFactor = event.delta > 0 ? 0.95 : 1.05;
let newZoom = zoomLevel * zoomFactor;
// Clamp zoom level
newZoom = constrain(newZoom, 0.1, 10);
// Convert screen mouse coords to WebGL coords (origin at center)
let mouseXGL = mouseX - width / 2;
let mouseYGL = mouseY - height / 2;
// Zoom towards mouse position
let mouseXWorld = (mouseXGL - panX) / zoomLevel;
let mouseYWorld = (mouseYGL - panY) / zoomLevel;
panX = mouseXGL - mouseXWorld * newZoom;
panY = mouseYGL - mouseYWorld * newZoom;
zoomLevel = newZoom;
// Save zoom and pan values
storeItem('zoomLevel', zoomLevel);
storeItem('panX', panX);
storeItem('panY', panY);
return false; // Prevent default scrolling
}
// Handle window resize
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
genType(); // Regenerate text points for new canvas size
// Reposition help button and info box
if (helpButton) helpButton.position(windowWidth - 30, 10);
if (infoBox) infoBox.position(windowWidth - 290, 45);
}
// Start recording a GIF for one complete sine wavelength
function startRecording() {
isRecording = true;
recordStartFrame = frameCount;
recordButton.html('Recording...');
// Calculate frames for one complete sine wave cycle
// Period T = 2π / (sinspeed * frameRate)
// Frames needed = T * frameRate = 2π / sinspeed
let sinspeed = sliders.sinspeed.value();
if (sinspeed === 0) {
sinspeed = 0.001; // Avoid division by zero
}
let framesNeeded = ceil(TWO_PI / sinspeed);
console.log('Recording', framesNeeded, 'frames for one complete wavelength');
console.log('Duration:', (framesNeeded / 30).toFixed(2), 'seconds');
// Use p5.js saveGif function
// Record at reduced resolution to keep file size manageable
saveGif('audiotype', framesNeeded / 30, {
delay: 0,
units: 'seconds',
notificationDuration: 2
});
// Reset recording state after duration
setTimeout(() => {
isRecording = false;
// Reset button text after 1 second
setTimeout(() => {
recordButton.html('Record GIF');
}, 1000);
}, (framesNeeded / 30) * 1000 + 1000); // Add 1000ms buffer
}
// Helper to load audio from a source (URL or data)
function loadAudioFromSource(source) {
// Stop and remove previous songs if exist
if (song) {
song.stop();
}
if (analyzeSong) {
analyzeSong.stop();
}
// Reset play button
if (playButton) {
playButton.html('▶');
}
// Load the audio file for playback
song = loadSound(source, () => {
console.log('Playback audio loaded successfully');
song.amp(0.3); // Set volume for hearing
});
// Load the same audio file for FFT analysis
analyzeSong = loadSound(source, () => {
console.log('Analysis audio loaded successfully');
analyzeSong.disconnect(); // Disconnect from output
fft.setInput(analyzeSong); // Connect FFT to analysis song
});
}
// IndexedDB helpers for saving audio and fonts
const DB_NAME = 'AudioTypeDB';
const DB_VERSION = 2;
const AUDIO_STORE_NAME = 'audioFiles';
const FONT_STORE_NAME = 'fontFiles';
function openDB() {
return new Promise((resolve, reject) => {
let request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = (event) => reject('IndexedDB error: ' + event.target.error);
request.onupgradeneeded = (event) => {
let db = event.target.result;
if (!db.objectStoreNames.contains(AUDIO_STORE_NAME)) {
db.createObjectStore(AUDIO_STORE_NAME);
}
if (!db.objectStoreNames.contains(FONT_STORE_NAME)) {
db.createObjectStore(FONT_STORE_NAME);
}
};
request.onsuccess = (event) => resolve(event.target.result);
});
}
async function saveAudioToDB(fileData) {
try {
let db = await openDB();
let tx = db.transaction(AUDIO_STORE_NAME, 'readwrite');
let store = tx.objectStore(AUDIO_STORE_NAME);
store.put(fileData, 'savedAudio');
console.log('Audio saved to IndexedDB');
} catch (err) {
console.error('Error saving audio to DB:', err);
}
}
async function getAudioFromDB() {
try {
let db = await openDB();
return new Promise((resolve, reject) => {
let tx = db.transaction(AUDIO_STORE_NAME, 'readonly');
let store = tx.objectStore(AUDIO_STORE_NAME);
let request = store.get('savedAudio');
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
} catch (err) {
console.error('Error getting audio from DB:', err);
return null;
}
}
async function saveFontToDB(fileData, fontName) {
try {
let db = await openDB();
let tx = db.transaction(FONT_STORE_NAME, 'readwrite');
let store = tx.objectStore(FONT_STORE_NAME);
// Save both the file data and the name
store.put({ file: fileData, name: fontName }, 'savedFont');
console.log('Font saved to IndexedDB');
} catch (err) {
console.error('Error saving font to DB:', err);
}
}
async function getFontFromDB() {
try {
let db = await openDB();
return new Promise((resolve, reject) => {
let tx = db.transaction(FONT_STORE_NAME, 'readonly');
let store = tx.objectStore(FONT_STORE_NAME);
let request = store.get('savedFont');
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
} catch (err) {
console.error('Error getting font from DB:', err);
return null;
}
}
async function loadSavedAudio() {
let savedFile = await getAudioFromDB();
if (savedFile) {
console.log('Found saved audio in DB');
if (audioNameLabel && savedFile.name) audioNameLabel.html(savedFile.name);