-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
3520 lines (3009 loc) · 150 KB
/
script.js
File metadata and controls
3520 lines (3009 loc) · 150 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
/* ============================================================================
GLYPHTRIX - JAVASCRIPT
============================================================================
Table of Contents:
1. UTILITY FUNCTIONS
2. CHARACTER SET CONFIGURATION
3. DOM ELEMENT REFERENCES
3.1 Canvas & Media Elements
3.2 Image Settings Controls
3.3 Glyph/Font Settings Controls
3.4 Output Settings Controls
3.5 Button & Action Elements
3.6 Layout & Panel Elements
4. STATE MANAGEMENT VARIABLES
5. CONFIGURATION - FONTS & CONSTANTS
6. HISTORY & UNDO/REDO SYSTEM
7. FILE UPLOAD & LOADING
8. IMAGE PROCESSING FUNCTIONS
9. ASCII RENDERING ENGINE
10. VIDEO PROCESSING
11. EXPORT FUNCTIONS
12. UI EVENT HANDLERS
13. MOBILE SUPPORT
14. INITIALIZATION & EVENT LISTENERS
============================================================================ */
/* ============================================================================
1. UTILITY FUNCTIONS
============================================================================ */
// Global spinner SVG generator
function getSpinner(size = 24) {
return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24"><g><rect width="2" height="5" x="11" y="1" fill="currentColor" opacity=".14"/><rect width="2" height="5" x="11" y="1" fill="currentColor" opacity=".29" transform="rotate(30 12 12)"/><rect width="2" height="5" x="11" y="1" fill="currentColor" opacity=".43" transform="rotate(60 12 12)"/><rect width="2" height="5" x="11" y="1" fill="currentColor" opacity=".57" transform="rotate(90 12 12)"/><rect width="2" height="5" x="11" y="1" fill="currentColor" opacity=".71" transform="rotate(120 12 12)"/><rect width="2" height="5" x="11" y="1" fill="currentColor" opacity=".86" transform="rotate(150 12 12)"/><rect width="2" height="5" x="11" y="1" fill="currentColor" transform="rotate(180 12 12)"/><animateTransform attributeName="transform" calcMode="discrete" dur="0.75s" repeatCount="indefinite" type="rotate" values="0 12 12;30 12 12;60 12 12;90 12 12;120 12 12;150 12 12;180 12 12;210 12 12;240 12 12;270 12 12;300 12 12;330 12 12;360 12 12"/></g></svg>`;
}
/* ============================================================================
2. CHARACTER SET CONFIGURATION
============================================================================ */
let randomNumberMap = {};
const numbersChars = "0123456789";
const latinBasicChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const latinChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ";
const cyrillicChars = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя";
const devanagariChars = "अआइईउऊऋॠऌएऐओऔअंअःकखगघङचछजझञटठडढणतथदधनपफबभमयरलवशषसहक़ख़ग़ज़ड़ढ़फ़य़ऴक्षत्रज्ञािीुूेैोौं";
const thaiChars = "กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะาำิีึืุูเแโใไๅๆ็่้๊๋์";
const japaneseChars = "一あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわをんアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン日一国会人年大十二本中長出三同時政事自行社見月分議後前民生連五発間対上部東者党地合市業内相方法四定今回新場金員九入選立開手米力学問高代明実円関決子動京全目表戦経通外最言氏現理調体化田当八六約主題下首意法";
const koreanChars = "의가은은이하고는에의한을은도를다지지와과는있사기대에고는도한수시나자일내하는로와는생것있적정면위자이에서들중로서나시로를만아지자에서어는국년시기다리리마게명야";
const chineseChars = "一的是不了人在有我他这中大为上个国到说们时要就出会可也你对生能而子那得于着下自之年过发后作里用道行所然家种事成方多经么去法学如都同现当没动面起看定天分还进好小部其些主样理心她本前开但因只从想实日军者无力它与长把机十民第公此已工使情明性知全三又关点正业外将两高间由问很最重并物手应战向头文体政美相见被利什二等产或新己制身果加西斯月话合回特代内信表化老给世位次度门任常先海通教儿原东声提立及比员解水名真论处走义各入几口认条平系气题活尔更别打女变四神总何电数安少报才结反受目太量再感建务做接必场件计管期市直德资命山金指克许统区保至队形社便空决治展马科司五基眼书非则听白却界达光放强即像难且权思王象完设式色路记南品住告类求据程北边风规解";
const arabicChars = "ابتثجحخدذرزسشصضطظعغفقكلمنهوي";
let customCharSeqIndex = 0;
/* ============================================================================
3. DOM ELEMENT REFERENCES
============================================================================ */
/* 3.1 Canvas & Media Elements */
const imageUpload = document.getElementById('imageUpload');
const condensedImageUpload = document.getElementById('condensedImageUpload');
const inputCanvas = document.getElementById('inputCanvas');
const inputVideo = document.getElementById('inputVideo');
const outputCanvas = document.getElementById('outputCanvas');
const inputCtx = inputCanvas.getContext('2d');
const outputCtx = outputCanvas.getContext('2d');
const loadingSpinner = document.getElementById('loadingSpinner');
const mobileLoadingSpinner = document.getElementById('mobileLoadingSpinner');
const sequenceLoadingOverlay = document.getElementById('sequenceLoadingOverlay');
const sequenceLoadingOverlayText = document.getElementById('sequenceLoadingOverlayText');
const cancelSequenceButton = document.getElementById('cancelSequenceButton');
const condensedUploadZone = document.getElementById('condensedUploadZone');
const condensedFilename = document.getElementById('condensedFilename');
const uploadPanelTitle = document.getElementById('uploadPanelTitle');
/* 3.2 Image Settings Controls */
const levelsSlider = document.getElementById('levelsSlider');
const levelsValueDisplay = document.getElementById('levelsValueDisplay');
const brightnessSlider = document.getElementById('brightnessSlider');
const brightnessValueDisplay = document.getElementById('brightnessValueDisplay');
const shadowInputSlider = document.getElementById('shadowInputSlider');
const shadowInputValueDisplay = document.getElementById('shadowInputValueDisplay');
const midtoneGammaSlider = document.getElementById('midtoneGammaSlider');
const midtoneGammaValueDisplay = document.getElementById('midtoneGammaValueDisplay');
const highlightInputSlider = document.getElementById('highlightInputSlider');
const highlightInputValueDisplay = document.getElementById('highlightInputValueDisplay');
const previewChangesToggle = document.getElementById('previewChangesToggle');
const invertColorsToggle = document.getElementById('invertColorsToggle');
const contrastSlider = document.getElementById('contrastSlider');
const contrastSliderContainer = document.getElementById('contrastSliderContainer');
const contrastValueDisplay = document.getElementById('contrastValueDisplay');
const chromaRemovalToggle = document.getElementById('backgroundRemovalToggle');
const chromaRemovalContainer = document.getElementById('backgroundRemovalContainer');
const invertColorsContainer = document.getElementById('invertColorsContainer');
const previewChangesContainer = document.getElementById('previewChangesContainer');
/* 3.3 Glyph/Font Settings Controls */
const densityInput = document.getElementById('densityInput');
const densityDecrement = document.getElementById('densityDecrement');
const densityIncrement = document.getElementById('densityIncrement');
const gridSizeDisplay = document.getElementById('gridSizeDisplay');
const fontSelect = document.getElementById('fontSelect');
const prevFontButton = document.getElementById('prevFontButton');
const nextFontButton = document.getElementById('nextFontButton');
const characterSetSelect = document.getElementById('characterSetSelect');
const prevCharSetButton = document.getElementById('prevCharSetButton');
const nextCharSetButton = document.getElementById('nextCharSetButton');
const customCharsContainer = document.getElementById('customCharsContainer');
const customCharsInput = document.getElementById('customCharsInput');
const customCharsHelpButton = document.getElementById('customCharsHelpButton');
/* 3.4 Output Settings Controls */
const scaleFactorInput = document.getElementById('scaleFactorInput');
const scaleFactorDecrement = document.getElementById('scaleFactorDecrement');
const scaleFactorIncrement = document.getElementById('scaleFactorIncrement');
const outputResolutionDisplay = document.getElementById('outputResolutionDisplay');
const colorSchemeSelect = document.getElementById('colorSchemeSelect');
const prevColorSchemeButton = document.getElementById('prevColorSchemeButton');
const nextColorSchemeButton = document.getElementById('nextColorSchemeButton');
const customColorsContainer = document.getElementById('customColorsContainer');
const customTextColor = document.getElementById('customTextColor');
const customBackgroundColor = document.getElementById('customBackgroundColor');
const transparentBgToggle = document.getElementById('transparentBgToggle');
const transparentBgGrid = document.getElementById('transparentBgGrid');
const charSpacingSlider = document.getElementById('charSpacingSlider');
const charSpacingValueDisplay = document.getElementById('charSpacingValueDisplay');
const randomSpacingToggle = document.getElementById('randomSpacingToggle');
const outputBloomSlider = document.getElementById('outputBloomSlider');
const outputBloomValueDisplay = document.getElementById('outputBloomValueDisplay');
let isBgColorTransparent = false;
let currentCharSpacing = 0;
let isRandomSpacingActive = true;
let columnOffsets = [];
/* 3.5 Button & Action Elements */
const openNewTabButton = document.getElementById('openNewTabButton');
const downloadPngButton = document.getElementById('downloadPngButton');
const downloadTextButton = document.getElementById('downloadTextButton');
const downloadPngSequenceButton = document.getElementById('downloadPngSequenceButton');
const recordWebcamButton = document.getElementById('recordWebcamButton');
const fullscreenButton = document.getElementById('fullscreenButton');
const recordingOverlay = document.getElementById('recordingOverlay');
const recordingTimer = document.getElementById('recordingTimer');
const recordingText = document.getElementById('recordingText');
/* 3.6 Layout & Panel Elements */
const mainContainer = document.getElementById('mainContainer');
const desktopSettingsPanelContainer = document.getElementById('desktopSettingsPanel');
const mobileSettingsPanel = document.getElementById('mobileSettingsPanel');
const mobileUploadPanelPlaceholder = document.getElementById('mobileUploadPanelPlaceholder');
const mobileDownloadPanelPlaceholder = document.getElementById('mobileDownloadPanelPlaceholder');
const uploadPanelContent = document.getElementById('uploadPanelContent');
const settingsTitleSection = document.getElementById('settingsTitleSection');
const imageSettingsContent = document.getElementById('imageSettingsContent');
const fontSettingsContent = document.getElementById('fontSettingsContent');
const outputSettingsContent = document.getElementById('outputSettingsContent');
const downloadPanelContent = document.getElementById('downloadPanelContent');
/* ============================================================================
4. STATE MANAGEMENT VARIABLES
============================================================================ */
/* Media & Processing State */
let currentBlobMatrix = null;
let currentMediaElement = null;
let originalPixelData = null;
let currentImageOriginalWidth = 0;
let currentImageOriginalHeight = 0;
let isPreviewChangesActive = false;
let isInvertColorsActive = false;
let isChromaRemovalActive = false;
let currentBackgroundTolerance = 10;
let currentOutputBloom = 0;
let isVideoInput = false;
let videoProcessLoopId = null;
let isWebcamActive = false;
let webcamStream = null;
let isRecordingWebcam = false;
let mediaRecorder = null;
let recordedChunks = [];
let isSequenceRendering = false;
let cancelSequenceRenderFlag = false;
let cachedZipBlob = null;
let sequenceSettingsSnapshot = null;
let actionHistory = [];
let currentHistoryIndex = -1;
const MAX_HISTORY_SIZE = 100;
let isFileJustLoaded = false;
let sliderChangeTimeout = null;
const SLIDER_DEBOUNCE_DELAY = 500;
/* Text Direction State */
let isVerticalTextMode = false;
/* ============================================================================
5. CONFIGURATION - FONTS & CONSTANTS
============================================================================ */
const availableFonts = [
{ name: 'Courier New', cssName: '"Courier New", Courier, monospace' },
{ name: 'Cutive Mono', cssName: '"Cutive Mono", monospace' },
{ name: 'Source Code Pro', cssName: '"Source Code Pro", monospace' },
{ name: 'Victor Mono', cssName: '"Victor Mono", monospace' },
{ name: 'Workbench', cssName: '"Workbench", monospace' },
{ name: 'Doto', cssName: '"Doto", monospace' },
{ name: 'VT323', cssName: '"VT323", monospace' },
{ name: 'Bytesized', cssName: '"Bytesized", monospace' }
];
let currentFontFamily;
let currentNumLevels, currentBrightness, currentContrast, currentShadowInput,
currentMidtoneGamma, currentHighlightInput, currentDensity,
currentScaleFactor, currentColorScheme, currentCharacterSet;
const FIXED_FONT_SIZE = 8;
/* ============================================================================
6. HISTORY & UNDO/REDO SYSTEM
============================================================================ */
function getCurrentSettingsSnapshot(fps) {
return JSON.stringify({
levels: levelsSlider.value,
brightness: brightnessSlider.value,
contrast: contrastSlider.value,
shadow: shadowInputSlider.value,
midtone: midtoneGammaSlider.value,
highlight: highlightInputSlider.value,
density: densityInput.value,
scale: scaleFactorInput.value,
colorScheme: colorSchemeSelect.value,
font: fontSelect.value,
charSet: characterSetSelect.value,
customChars: customCharsInput.value,
invert: invertColorsToggle.checked,
chromaRemoval: chromaRemovalToggle.checked,
outputBloom: outputBloomSlider.value,
sequenceFps: fps,
customText: customTextColor.value,
customBackground: customBackgroundColor.value,
transparentBg: isBgColorTransparent,
charSpacing: charSpacingSlider.value,
});
}
function saveActionToHistory() {
if (isFileJustLoaded) return;
const currentSettings = getCurrentSettingsSnapshot();
actionHistory = actionHistory.slice(0, currentHistoryIndex + 1);
actionHistory.push(currentSettings);
if (actionHistory.length > MAX_HISTORY_SIZE) {
actionHistory.shift();
} else {
currentHistoryIndex++;
}
updateUndoRedoButtons();
}
function updateUndoRedoButtons() {
const undoButton = document.getElementById('undoButton');
const redoButton = document.getElementById('redoButton');
if (undoButton) undoButton.disabled = currentHistoryIndex <= 0 || isFileJustLoaded;
if (redoButton) redoButton.disabled = currentHistoryIndex >= actionHistory.length - 1;
}
function initializeHistoryForNewFile() {
isFileJustLoaded = true;
actionHistory = [];
currentHistoryIndex = -1;
const currentSettings = getCurrentSettingsSnapshot();
actionHistory.push(currentSettings);
currentHistoryIndex = 0;
updateUndoRedoButtons();
if (sliderChangeTimeout) {
clearTimeout(sliderChangeTimeout);
sliderChangeTimeout = null;
}
}
function enableHistoryAfterUserChange() {
if (isFileJustLoaded) {
isFileJustLoaded = false;
updateUndoRedoButtons();
}
}
function debouncedSaveSliderToHistory() {
if (sliderChangeTimeout) {
clearTimeout(sliderChangeTimeout);
}
sliderChangeTimeout = setTimeout(() => {
enableHistoryAfterUserChange();
saveActionToHistory();
}, SLIDER_DEBOUNCE_DELAY);
}
function undoAction() {
if (currentHistoryIndex > 0) {
currentHistoryIndex--;
restoreSettingsFromSnapshot(actionHistory[currentHistoryIndex]);
updateUndoRedoButtons();
}
}
function redoAction() {
if (currentHistoryIndex < actionHistory.length - 1) {
currentHistoryIndex++;
restoreSettingsFromSnapshot(actionHistory[currentHistoryIndex]);
updateUndoRedoButtons();
}
}
function restoreSettingsFromSnapshot(snapshot) {
try {
const settings = JSON.parse(snapshot);
levelsSlider.value = settings.levels;
levelsValueDisplay.textContent = settings.levels;
brightnessSlider.value = settings.brightness;
brightnessValueDisplay.textContent = settings.brightness;
contrastSlider.value = settings.contrast;
contrastValueDisplay.textContent = settings.contrast;
shadowInputSlider.value = settings.shadow;
shadowInputValueDisplay.textContent = settings.shadow;
midtoneGammaSlider.value = settings.midtone;
midtoneGammaValueDisplay.textContent = parseFloat(settings.midtone).toFixed(1);
highlightInputSlider.value = settings.highlight;
highlightInputValueDisplay.textContent = settings.highlight;
densityInput.value = settings.density;
scaleFactorInput.value = settings.scale;
colorSchemeSelect.value = settings.colorScheme;
syncCustomColorsWithPreset(settings.colorScheme);
// Font restore
if ([...fontSelect.options].some(opt => opt.value === settings.font)) {
fontSelect.value = settings.font;
} else {
fontSelect.selectedIndex = parseInt(settings.font) || 0;
}
characterSetSelect.value = settings.charSet;
customCharsInput.value = settings.customChars;
invertColorsToggle.checked = settings.invert;
chromaRemovalToggle.checked = settings.chromaRemoval;
outputBloomSlider.value = settings.outputBloom !== undefined ? settings.outputBloom : 0;
outputBloomValueDisplay.textContent = toBloomDisplayValue(outputBloomSlider.value);
if (settings.previewChanges !== undefined) {
previewChangesToggle.checked = settings.previewChanges;
}
const isMobile = window.innerWidth <= 768;
isPreviewChangesActive = !isMobile && previewChangesToggle.checked;
if (settings.customText) customTextColor.value = settings.customText;
if (settings.customBackground) customBackgroundColor.value = settings.customBackground;
isBgColorTransparent = settings.transparentBg || false;
updateTransparentBgUI();
charSpacingSlider.value = settings.charSpacing || 0;
charSpacingValueDisplay.textContent = settings.charSpacing || 0;
isChromaRemovalActive = settings.chromaRemoval;
isInvertColorsActive = settings.invert;
currentOutputBloom = parseInt(outputBloomSlider.value);
customCharsContainer.style.display = 'flex';
if (characterSetSelect.value === 'custom') {
customCharsInput.disabled = false;
customCharsHelpButton.disabled = false;
} else {
customCharsInput.disabled = true;
customCharsHelpButton.disabled = true;
}
processImageWithCurrentSettings();
if (!isVideoInput) updateInputCanvasPreview();
} catch (error) {
console.error('Error restoring settings:', error);
}
}
function clearCachedSequence() {
cachedZipBlob = null;
sequenceSettingsSnapshot = null;
customCharSeqIndex = 0;
updatePngSequenceButtonState();
}
function updatePngSequenceButtonState() {
if (!isVideoInput || isWebcamActive) {
downloadPngSequenceButton.style.display = 'none';
return;
}
downloadPngSequenceButton.style.display = 'inline-flex';
downloadPngSequenceButton.innerHTML = '<i class="ri-download-2-line"></i> Download Sequence';
downloadPngSequenceButton.disabled = isSequenceRendering;
}
function toggleSequenceRenderingUI(isRendering, message = "") {
isSequenceRendering = isRendering;
cancelSequenceRenderFlag = false;
if (isRendering) {
outputCanvas.style.display = 'none';
sequenceLoadingOverlay.style.display = 'flex';
sequenceLoadingOverlayText.textContent = message || "Rendering Sequence...";
cancelSequenceButton.style.display = 'block';
} else {
outputCanvas.style.display = 'block';
sequenceLoadingOverlay.style.display = 'none';
cancelSequenceButton.style.display = 'none';
}
const controlsToDisable = [
imageUpload, condensedImageUpload,
levelsSlider, brightnessSlider,
shadowInputSlider, midtoneGammaSlider, highlightInputSlider,
invertColorsToggle, previewChangesToggle,
outputBloomSlider,
densityInput, densityDecrement, densityIncrement, fontSelect, prevFontButton, nextFontButton,
characterSetSelect, prevCharSetButton, nextCharSetButton, customCharsInput,
scaleFactorInput, scaleFactorDecrement, scaleFactorIncrement, colorSchemeSelect, prevColorSchemeButton, nextColorSchemeButton,
openNewTabButton, downloadPngButton, downloadTextButton
];
controlsToDisable.forEach(control => {
if (control) control.disabled = isRendering;
});
updatePngSequenceButtonState();
}
cancelSequenceButton.addEventListener('click', () => {
cancelSequenceRenderFlag = true;
sequenceLoadingOverlayText.textContent = "Cancelling rendering...";
});
async function generateGlyphtrixFrameBlob(videoTime, tempCanvas, tempCtx, offscreenRenderCanvas, offscreenRenderCtx) {
return new Promise(async (resolve, reject) => {
if (cancelSequenceRenderFlag) {
return reject(new Error("Sequence rendering cancelled by user."));
}
inputVideo.currentTime = videoTime;
const onSeeked = async () => {
inputVideo.removeEventListener('seeked', onSeeked);
inputVideo.removeEventListener('error', onError);
if (cancelSequenceRenderFlag) {
return reject(new Error("Sequence rendering cancelled during seek."));
}
try {
tempCtx.drawImage(inputVideo, 0, 0, currentImageOriginalWidth, currentImageOriginalHeight);
let framePixelData = tempCtx.getImageData(0, 0, currentImageOriginalWidth, currentImageOriginalHeight).data;
if (chromaRemovalToggle.checked) {
framePixelData = removeChroma(framePixelData, currentImageOriginalWidth, currentImageOriginalHeight, 10);
}
if (invertColorsToggle.checked) {
framePixelData = invertPixelData(framePixelData);
}
let processedData = applyContrast(new Uint8ClampedArray(framePixelData), currentImageOriginalWidth, currentImageOriginalHeight, parseInt(contrastSlider.value));
processedData = applyLevelsAndBrightness(processedData, currentImageOriginalWidth, currentImageOriginalHeight, parseInt(brightnessSlider.value), parseInt(shadowInputSlider.value), parseFloat(midtoneGammaSlider.value), parseInt(highlightInputSlider.value));
const frameGrayscaleLevels = generateGrayscaleLevels(parseInt(levelsSlider.value));
const frameBlobMatrix = generateBlobMatrix(processedData, currentImageOriginalWidth, currentImageOriginalHeight, frameGrayscaleLevels, parseInt(densityInput.value), colorSchemeSelect.value, characterSetSelect.value);
const baseCharSize = FIXED_FONT_SIZE;
const effectiveCharSize = baseCharSize * parseFloat(scaleFactorInput.value);
const charWidth = effectiveCharSize;
const charHeight = effectiveCharSize;
if (frameBlobMatrix.length === 0 || frameBlobMatrix[0].length === 0) {
return reject(new Error("Empty frame matrix generated"));
}
const numOutputRows = frameBlobMatrix.length;
const numOutputCols = frameBlobMatrix[0].length;
const charSpacing = currentCharSpacing || 0;
const colsToAdjust = Math.floor(charSpacing);
const originalCols = numOutputCols + colsToAdjust;
offscreenRenderCanvas.width = Math.max(1, originalCols * charWidth);
offscreenRenderCanvas.height = Math.max(1, numOutputRows * charHeight);
offscreenRenderCtx.fillStyle = getCanvasBackgroundColor(colorSchemeSelect.value);
offscreenRenderCtx.fillRect(0, 0, offscreenRenderCanvas.width, offscreenRenderCanvas.height);
offscreenRenderCtx.font = `${effectiveCharSize}px ${availableFonts[fontSelect.selectedIndex].cssName}`;
offscreenRenderCtx.textAlign = 'left';
offscreenRenderCtx.textBaseline = 'top';
const cellWidth = numOutputCols > 1 ? offscreenRenderCanvas.width / numOutputCols : charWidth;
let currentY = 0;
for (let y = 0; y < numOutputRows; y++) {
let currentX = 0;
for (let x = 0; x < numOutputCols; x++) {
if (frameBlobMatrix[y] && frameBlobMatrix[y][x]) {
const cellColor = frameBlobMatrix[y][x].color;
if (cellColor !== 'rgba(0, 0, 0, 0)') {
offscreenRenderCtx.fillStyle = cellColor;
offscreenRenderCtx.fillText(frameBlobMatrix[y][x].char, currentX, currentY);
}
}
currentX += cellWidth;
}
currentY += charHeight;
}
offscreenRenderCanvas.toBlob(blob => {
if (blob) resolve(blob);
else reject(new Error("Failed to create blob from offscreen canvas"));
}, 'image/png');
} catch (error) {
reject(error);
}
};
const onError = (e) => {
inputVideo.removeEventListener('seeked', onSeeked);
inputVideo.removeEventListener('error', onError);
reject(new Error("Video seeking error during sequence rendering."));
};
inputVideo.addEventListener('seeked', onSeeked, { once: true });
inputVideo.addEventListener('error', onError, { once: true });
});
}
async function downloadPngSequenceWithFps(fps) {
if (!isVideoInput || inputVideo.readyState < inputVideo.HAVE_METADATA || isSequenceRendering) return;
closeFpsModal();
const currentSettings = getCurrentSettingsSnapshot(fps);
if (cachedZipBlob && sequenceSettingsSnapshot === currentSettings) {
const randomHash = generateRandomHash(8);
const link = document.createElement('a');
link.href = URL.createObjectURL(cachedZipBlob);
link.download = `Glyphtrix_sequence_${randomHash}.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
return;
}
clearCachedSequence();
const wasPaused = inputVideo.paused;
if (!wasPaused) inputVideo.pause();
toggleSequenceRenderingUI(true, "Initializing sequence rendering...");
const pngBlobs = [];
const videoDuration = inputVideo.duration;
const selectedFps = fps;
const frameInterval = 1 / selectedFps;
const numFrames = Math.floor(videoDuration / frameInterval);
const tempCaptureCanvas = document.createElement('canvas');
tempCaptureCanvas.width = currentImageOriginalWidth;
tempCaptureCanvas.height = currentImageOriginalHeight;
const tempCaptureCtx = tempCaptureCanvas.getContext('2d');
const offscreenRenderCanvas = document.createElement('canvas');
const offscreenRenderCtx = offscreenRenderCanvas.getContext('2d');
let renderingCancelled = false;
try {
for (let i = 0; i < numFrames; i++) {
if (cancelSequenceRenderFlag) {
renderingCancelled = true;
sequenceLoadingOverlayText.textContent = "Rendering cancelled.";
await new Promise(r => setTimeout(r, 1500));
break;
}
const currentTime = i * frameInterval;
const progressMessage = `Rendering frame ${i + 1} of ${numFrames} and creating a .zip archive...`;
sequenceLoadingOverlayText.textContent = progressMessage;
const blob = await generateGlyphtrixFrameBlob(currentTime, tempCaptureCanvas, tempCaptureCtx, offscreenRenderCanvas, offscreenRenderCtx);
pngBlobs.push(blob);
}
if (!renderingCancelled && pngBlobs.length > 0) {
sequenceLoadingOverlayText.textContent = "Zipping frames and creating .zip archive...";
const zip = new JSZip();
pngBlobs.forEach((blob, index) => {
const frameNumber = (index + 1).toString().padStart(4, '0');
zip.file(`frame_${frameNumber}.png`, blob);
});
cachedZipBlob = await zip.generateAsync({ type: "blob" });
sequenceSettingsSnapshot = currentSettings;
const randomHash = generateRandomHash(8);
const link = document.createElement('a');
link.href = URL.createObjectURL(cachedZipBlob);
link.download = `Glyphtrix_sequence_${randomHash}.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
} else if (!renderingCancelled && numFrames > 0) {
alert("No frames were rendered for the sequence. This might be due to a very short video or an issue.");
}
} catch (error) {
if (!error.message.toLowerCase().includes("cancel")) {
console.error("Error during PNG sequence rendering: ", error);
alert(`Error during PNG sequence rendering: ${error.message}`);
}
} finally {
toggleSequenceRenderingUI(false);
if (!wasPaused && inputVideo.readyState >= inputVideo.HAVE_ENOUGH_DATA && !renderingCancelled) {
}
updatePngSequenceButtonState();
}
}
function processCurrentFrame() {
if (!inputVideo || inputVideo.paused || inputVideo.ended || inputVideo.readyState < inputVideo.HAVE_CURRENT_DATA) {
stopVideoProcessingLoop();
return;
}
processImageWithCurrentSettings().then(() => {
if (isPreviewChangesActive) {
updateInputCanvasPreview();
}
if (window.innerWidth <= 768 && mobilePreviewActive) {
debouncedUpdateMobilePreview();
}
if (!inputVideo.paused && !inputVideo.ended) {
videoProcessLoopId = requestAnimationFrame(processCurrentFrame);
} else {
stopVideoProcessingLoop();
}
}).catch(error => {
console.error("Error processing video frame:", error);
stopVideoProcessingLoop();
});
}
function setDownloadButtonsState(disabled) {
openNewTabButton.disabled = disabled;
downloadPngButton.disabled = disabled;
downloadTextButton.disabled = disabled;
fullscreenButton.disabled = disabled;
}
function getFailsafeDensity(width) {
if (width > 2500) {
return 40;
} else if (width >= 1000) {
return 20;
} else {
return 10;
}
}
function setDefaultValues(contentWidth = null) {
levelsSlider.value = 4; levelsValueDisplay.textContent = '4';
brightnessSlider.value = 0; brightnessValueDisplay.textContent = '0';
contrastSlider.value = 0; contrastValueDisplay.textContent = '0';
shadowInputSlider.value = 0; shadowInputValueDisplay.textContent = '0';
midtoneGammaSlider.value = 1.0; midtoneGammaValueDisplay.textContent = '1.0';
highlightInputSlider.value = 255; highlightInputValueDisplay.textContent = '255';
chromaRemovalToggle.checked = false;
invertColorsToggle.checked = false;
outputBloomSlider.value = 0; outputBloomValueDisplay.textContent = '0';
isBgColorTransparent = false;
updateTransparentBgUI();
charSpacingSlider.value = 0;
charSpacingValueDisplay.textContent = '0';
previewChangesToggle.checked = true;
showExampleButtons();
const failsafeDensity = contentWidth ? getFailsafeDensity(contentWidth) : 10;
densityInput.value = failsafeDensity;
scaleFactorInput.value = 1.0;
colorSchemeSelect.value = 'color1';
syncCustomColorsWithPreset('color1');
fontSelect.selectedIndex = 0;
characterSetSelect.value = 'binary';
customCharsInput.value = '0,1';
customCharsContainer.style.display = 'flex';
customCharsInput.disabled = false;
customCharsHelpButton.disabled = false;
customTextColor.value = '#00FF00';
customBackgroundColor.value = '#000000';
if (!window.savedCustomColors) {
window.savedCustomColors = {
text: '#00FF00',
background: '#000000'
};
}
gridSizeDisplay.textContent = '-';
isChromaRemovalActive = chromaRemovalToggle.checked;
currentBackgroundTolerance = 10;
isInvertColorsActive = invertColorsToggle.checked;
currentOutputBloom = parseInt(outputBloomSlider.value);
isPreviewChangesActive = previewChangesToggle.checked;
currentNumLevels = parseInt(levelsSlider.value);
currentBrightness = parseInt(brightnessSlider.value);
currentContrast = parseInt(contrastSlider.value);
currentShadowInput = parseInt(shadowInputSlider.value);
currentMidtoneGamma = parseFloat(midtoneGammaSlider.value);
currentHighlightInput = parseInt(highlightInputSlider.value);
currentDensity = parseInt(densityInput.value);
currentScaleFactor = parseFloat(scaleFactorInput.value);
currentColorScheme = colorSchemeSelect.value;
currentFontFamily = availableFonts[fontSelect.selectedIndex].cssName;
currentCharacterSet = characterSetSelect.value;
setDownloadButtonsState(true);
clearCachedSequence();
}
function generateGrayscaleLevels(numLevels) {
if (numLevels < 2) return [0, 1];
const levels = [];
for (let i = 0; i < numLevels; i++) { levels.push(i / (numLevels - 1)); }
return levels;
}
function getRandomCharacterForLevel(grayscaleValue, charSet) {
let charsToUse;
switch (charSet) {
case 'numbers': charsToUse = numbersChars; break;
case 'latin_basic': charsToUse = latinBasicChars; break;
case 'latin': charsToUse = latinChars; break;
case 'cyrillic': charsToUse = cyrillicChars; break;
case 'devanagari': charsToUse = devanagariChars; break;
case 'thai': charsToUse = thaiChars; break;
case 'japanese': charsToUse = japaneseChars; break;
case 'korean': charsToUse = koreanChars; break;
case 'chinese': charsToUse = chineseChars; break;
case 'arabic': charsToUse = arabicChars; break;
default: return '?';
}
return charsToUse[Math.floor(Math.random() * charsToUse.length)];
}
function invertPixelData(sourceData) {
const invertedData = new Uint8ClampedArray(sourceData.length);
for (let i = 0; i < sourceData.length; i += 4) {
invertedData[i] = 255 - sourceData[i];
invertedData[i + 1] = 255 - sourceData[i + 1];
invertedData[i + 2] = 255 - sourceData[i + 2];
invertedData[i + 3] = sourceData[i + 3];
}
return invertedData;
}
function applyContrast(sourceData, width, height, contrastAmount) {
if (contrastAmount === 0) return new Uint8ClampedArray(sourceData);
const outputData = new Uint8ClampedArray(sourceData);
const factor = (259 * (contrastAmount + 255)) / (255 * (259 - contrastAmount));
for (let i = 0; i < outputData.length; i += 4) {
for (let c = 0; c < 3; c++) {
let val = factor * (outputData[i + c] - 128) + 128;
outputData[i + c] = Math.max(0, Math.min(255, val));
}
}
return outputData;
}
function removeChroma(sourceData, width, height, tolerance) {
if (!sourceData) return new Uint8ClampedArray(sourceData);
const outputData = new Uint8ClampedArray(sourceData);
// Sample corner pixels to detect chroma key color
const corners = [
0,
(width - 1) * 4,
(height - 1) * width * 4,
((height - 1) * width + (width - 1)) * 4
];
let chromaR = 0, chromaG = 0, chromaB = 0;
let validCorners = 0;
for (let corner of corners) {
if (corner < sourceData.length - 3) {
chromaR += sourceData[corner];
chromaG += sourceData[corner + 1];
chromaB += sourceData[corner + 2];
validCorners++;
}
}
if (validCorners === 0) return outputData;
chromaR = Math.round(chromaR / validCorners);
chromaG = Math.round(chromaG / validCorners);
chromaB = Math.round(chromaB / validCorners);
const toleranceValue = tolerance * 2.55;
for (let i = 0; i < outputData.length; i += 4) {
const r = outputData[i];
const g = outputData[i + 1];
const b = outputData[i + 2];
const diff = Math.sqrt(
Math.pow(r - chromaR, 2) +
Math.pow(g - chromaG, 2) +
Math.pow(b - chromaB, 2)
);
if (diff <= toleranceValue) {
const replacement = (typeof isInvertColorsActive !== 'undefined' && isInvertColorsActive) ? 255 : 0;
outputData[i] = replacement;
outputData[i + 1] = replacement;
outputData[i + 2] = replacement;
}
}
return outputData;
}
function applyLevelsAndBrightness(sourcePixelData, width, height, brightness, shadowIn, gamma, highlightIn) {
const data = new Uint8ClampedArray(sourcePixelData);
const bVal = (brightness / 100.0) * 127.5;
const invGamma = 1.0 / gamma;
const inputRange = Math.max(1, highlightIn - shadowIn);
for (let i = 0; i < data.length; i += 4) {
for (let c = 0; c < 3; c++) {
let val = data[i + c] + bVal;
if (val <= shadowIn) { val = 0; }
else if (val >= highlightIn) { val = 255; }
else { val = ((val - shadowIn) / inputRange) * 255; }
val = 255 * Math.pow(val / 255, invGamma);
data[i + c] = Math.max(0, Math.min(255, val));
}
}
return data;
}
function getCharacterDisplayColor(level, scheme, rowIndex = 0, totalRows = 1) {
const value = Math.round(level * 255);
switch (scheme) {
case 'color1': return `rgb(0, ${value}, 0)`;
case 'color2': return `rgb(${value}, ${value}, ${value})`;
case 'color3': {
const textColor = {r: 20, g: 238, b: 94};
const bgColor = hexToRgb(customBackgroundColor.value);
if (value === 0) return `rgb(${bgColor.r}, ${bgColor.g}, ${bgColor.b})`;
return `rgb(${bgColor.r + Math.round((textColor.r - bgColor.r) * value / 255)}, ${bgColor.g + Math.round((textColor.g - bgColor.g) * value / 255)}, ${bgColor.b + Math.round((textColor.b - bgColor.b) * value / 255)})`;
}
case 'custom': {
const textColor = hexToRgb(customTextColor.value);
const bgColor = isBgColorTransparent ? {r: 0, g: 0, b: 0} : hexToRgb(customBackgroundColor.value);
const brightness = level;
if (brightness === 0) {
if (isBgColorTransparent) {
return 'rgba(0, 0, 0, 0)';
}
return `rgb(${bgColor.r}, ${bgColor.g}, ${bgColor.b})`;
}
return `rgb(${Math.round(textColor.r * brightness)}, ${Math.round(textColor.g * brightness)}, ${Math.round(textColor.b * brightness)})`;
}
default: return `rgb(0, ${value}, 0)`;
}
}
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : {r: 0, g: 255, b: 0};
}
function toBloomDisplayValue(rawValue) {
return Math.round(rawValue / 2);
}
function updateTransparentBgUI() {
const transparent = isBgColorTransparent;
transparentBgToggle.className = transparent ? 'btn-base ri-eye-off-line' : 'btn-base ri-eye-line';
transparentBgToggle.title = transparent ? 'Transparent background (click to use color)' : 'Enable transparent background';
customBackgroundColor.disabled = transparent;
if (transparentBgGrid) {
transparentBgGrid.style.display = transparent ? 'grid' : 'none';
customBackgroundColor.style.display = transparent ? 'none' : '';
} else {
customBackgroundColor.style.opacity = transparent ? '0.3' : '1';
}
}
function syncCustomColorsWithPreset(scheme) {
const customTextColor = document.getElementById('customTextColor');
const customBackgroundColor = document.getElementById('customBackgroundColor');
if (!customTextColor || !customBackgroundColor) return;
switch (scheme) {
case 'color1':
customTextColor.value = '#00FF00';
customBackgroundColor.value = '#000000';
break;
case 'color2':
customTextColor.value = '#FFFFFF';
customBackgroundColor.value = '#000000';
break;
case 'color3':
customTextColor.value = '#14ee5e';
customBackgroundColor.value = '#c80a60';
break;
case 'custom':
if (window.savedCustomColors) {
customTextColor.value = window.savedCustomColors.text || '#00FF00';
customBackgroundColor.value = window.savedCustomColors.background || '#000000';
}
break;
case 'source':
break;
default:
customTextColor.value = '#00FF00';
customBackgroundColor.value = '#000000';
}
if (customColorsContainer) {
const isSource = scheme === 'source';
customColorsContainer.style.pointerEvents = isSource ? 'none' : '';
customColorsContainer.style.opacity = isSource ? '0.5' : '';
customColorsContainer.querySelectorAll('input, button').forEach(el => { el.disabled = isSource; });
}
const isSource = scheme === 'source';
if (levelsSlider) {
levelsSlider.disabled = isSource;
const grayscaleValuesContainer = levelsSlider.closest('.slider-container');
if (grayscaleValuesContainer) {
grayscaleValuesContainer.style.pointerEvents = isSource ? 'none' : '';
grayscaleValuesContainer.style.opacity = isSource ? '0.5' : '';
}
}
}
function getCanvasBackgroundColor(scheme) {
switch (scheme) {
case 'source': case 'color1': case 'color2': return getComputedStyle(document.documentElement).getPropertyValue('--primary-bg');
case 'color3': case 'custom':
return isBgColorTransparent ? 'transparent' : customBackgroundColor.value;
default: return getComputedStyle(document.documentElement).getPropertyValue('--primary-bg');
}
}
function drawPosterizedPreview(pixelDataToProcess, width, height, levelsArray) {
inputCanvas.width = width;
inputCanvas.height = height;
const previewCtx = inputCanvas.getContext('2d');
previewCtx.clearRect(0, 0, width, height);
const outputImageData = previewCtx.createImageData(width, height);
const outputData = outputImageData.data;