-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2923 lines (2446 loc) · 105 KB
/
app.js
File metadata and controls
2923 lines (2446 loc) · 105 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
const scaleFactor = 10; // Scale factor for enlarging each pixel
// Global variable to store palette indices
let storedPaletteIndices = new Array(32 * 32).fill(1);
let monoPixelStates = new Array(32 * 32).fill(false); // Initialize all pixels to "off" (white)
// Global variable to store the current palette
let currentPalette = [];
// Global variables for color selection
let primaryColor = '#000000FF'; // Default primary color
let secondaryColor = '#FFFFFFFF'; // Default secondary color
let primaryColorIndex = 0; // Default index for primary color
let secondaryColorIndex = 1; // Default index for secondary color
// Add these global variables near the top with other globals
let monoDrawPrimary = true; // true = draw black/on, false = draw transparent/off
let monoDrawSecondary = false;
// Add these global variables near the top with other globals
let monoPaletteStates = new Array(16).fill(false); // Track toggle state for each palette index
// Add the 3D mode byte sequence constant
const THREED_MODE_SEQUENCE = new Uint8Array([
0xda, 0x69, 0xd0, 0xda, 0xc7, 0x4e, 0xf8, 0x36,
0x18, 0x92, 0x79, 0x68, 0x2d, 0xb5, 0x30, 0x86
]);
// Define a default palette with 16 colors
const defaultPalette = [
{ r: 0, g: 0, b: 0, a: 255 }, // Black
{ r: 255, g: 255, b: 255, a: 255 }, // White
{ r: 255, g: 0, b: 0, a: 255 }, // Red
{ r: 0, g: 255, b: 0, a: 255 }, // Green
{ r: 0, g: 0, b: 255, a: 255 }, // Blue
{ r: 255, g: 255, b: 0, a: 255 }, // Yellow
{ r: 0, g: 255, b: 255, a: 255 }, // Cyan
{ r: 255, g: 0, b: 255, a: 255 }, // Magenta
{ r: 187, g: 187, b: 187, a: 255 }, // Silver (11*17)
{ r: 136, g: 136, b: 136, a: 255 }, // Gray (8*17)
{ r: 136, g: 0, b: 0, a: 255 }, // Maroon (8*17)
{ r: 136, g: 136, b: 0, a: 255 }, // Olive (8*17)
{ r: 0, g: 136, b: 0, a: 255 }, // Dark Green (8*17)
{ r: 136, g: 0, b: 136, a: 255 }, // Purple (8*17)
{ r: 0, g: 136, b: 136, a: 255 }, // Teal (8*17)
{ r: 0, g: 0, b: 136, a: 255 } // Navy (8*17)
];
document.getElementById('color-file').addEventListener('change', function(event) {
handleFile(event, 'color');
});
document.getElementById('mono-file').addEventListener('change', function(event) {
handleFile(event, 'mono');
});
document.getElementById('unified-file').addEventListener('change', function(event) {
const file = event.target.files[0];
handleFileInput(file);
});
function handleFileInput(file) {
if (!file) return;
const extension = file.name.toLowerCase().split('.').pop();
const description = file.name.split('.')[0].slice(0, 16).toUpperCase();
if (extension === 'vms') {
// Handle VMS file
const reader = new FileReader();
reader.onload = function(e) {
const vmsData = new Uint8Array(e.target.result);
parseVMSFile(vmsData);
};
reader.readAsArrayBuffer(file);
} else if (extension === 'dci') {
// Handle DCI file
const reader = new FileReader();
reader.onload = function(e) {
const dciData = new Uint8Array(e.target.result);
parseDCIFile(dciData);
};
reader.readAsArrayBuffer(file);
} else if (extension === 'dcm') {
// Handle DCM file
const reader = new FileReader();
reader.onload = function(e) {
const dcmData = new Uint8Array(e.target.result);
parseDCMFile(dcmData);
};
reader.readAsArrayBuffer(file);
} else if (extension === 'psv') {
// Handle PSV file
const reader = new FileReader();
reader.onload = function(e) {
const psvData = new Uint8Array(e.target.result);
parsePSVFile(psvData);
};
reader.readAsArrayBuffer(file);
} else if (['ico', 'bmp', 'png', 'jpg', 'jpeg', 'gif', 'webp'].includes(extension)) {
// Handle image file - process both color and mono
const reader = new FileReader();
reader.onload = function(e) {
const img = new Image();
img.onload = function() {
processColorImage(img);
processMonoImage(img);
document.getElementById('description').value = description;
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
} else {
alert('Unsupported file type. Please use VMS or image files (PNG, JPG, GIF, WEBP).');
}
// Clear the file input after parsing
const fileInput = document.getElementById('unified-file');
if (fileInput) fileInput.value = ''; // Clear the file input
}
document.getElementById('save-button').addEventListener('click', saveVMSVMI);
function handleFile(event, type) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
const img = new Image();
img.onload = function() {
if (type === 'color') {
processColorImage(img);
} else {
processMonoImage(img);
}
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
let redInput = document.getElementById('red');
let greenInput = document.getElementById('green');
let blueInput = document.getElementById('blue');
let alphaInput = document.getElementById('alpha');
const colorPreview = document.getElementById('color-preview');
const customColorPicker = document.getElementById('custom-color-picker');
let currentPaletteIndex = null;
let lastRightClickTime = 0;
const doubleClickThreshold = 200; // Reduced time in milliseconds
const hueSlider = document.getElementById('hue-slider');
const colorPickerCanvas = document.getElementById('color-picker-canvas');
const hueCtx = hueSlider.getContext('2d', { willReadFrequently: true });
const colorCtx = colorPickerCanvas.getContext('2d', { willReadFrequently: true });
let currentHue = 0;
let isColorPickerDragging = false;
let isHueSliderDragging = false;
let colorIndicatorX = colorPickerCanvas.width - 1; // Default to the furthest right position
let colorIndicatorY = 0; // Default to the top position
// Add a variable to track the hue indicator position
let hueIndicatorX = 0;
// Add these variables near the other slider-related variables
const opacitySlider = document.getElementById('opacity-slider');
const opacityCtx = opacitySlider.getContext('2d', { willReadFrequently: true });
let opacityIndicatorX = opacitySlider.width; // Default to full opacity
function rgbaToHex(r, g, b, a) {
const hexR = (r & 0xFF).toString(16).padStart(2, '0');
const hexG = (g & 0xFF).toString(16).padStart(2, '0');
const hexB = (b & 0xFF).toString(16).padStart(2, '0');
const hexA = (a & 0xFF).toString(16).padStart(2, '0');
return `#${hexR}${hexG}${hexB}${hexA}`.toUpperCase();
}
// Convert HSB to RGB
function hsbToRgb(h, s, v) {
let r, g, b;
const i = Math.floor(h * 6);
const f = h * 6 - i;
const p = v * (1 - s);
const q = v * (1 - f * s);
const t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
return [r * 255, g * 255, b * 255];
}
// Update the drawHueSlider function
function drawHueSlider() {
const width = hueSlider.width;
const gradient = hueCtx.createLinearGradient(0, 0, width, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(0.17, 'yellow');
gradient.addColorStop(0.34, 'lime');
gradient.addColorStop(0.51, 'cyan');
gradient.addColorStop(0.68, 'blue');
gradient.addColorStop(0.85, 'magenta');
gradient.addColorStop(1, 'red');
hueCtx.fillStyle = gradient;
hueCtx.fillRect(0, 0, width, hueSlider.height);
// Calculate the color for the current hue
const [r, g, b] = hsbToRgb(hueIndicatorX / width, 1, 1);
// Add shadow before drawing the indicator
hueCtx.shadowColor = 'rgba(0, 0, 0, 0.25)';
hueCtx.shadowBlur = 1;
hueCtx.shadowOffsetX = 1;
// Draw the hue indicator with the selected color
hueCtx.beginPath();
hueCtx.arc(hueIndicatorX, hueSlider.height / 2, hueSlider.height / 2, 0, Math.PI * 2);
hueCtx.fillStyle = `rgb(${r}, ${g}, ${b})`;
hueCtx.fill();
hueCtx.strokeStyle = 'white';
hueCtx.lineWidth = 3;
hueCtx.stroke();
// Reset shadow settings
hueCtx.shadowColor = 'transparent';
hueCtx.shadowBlur = 0;
hueCtx.shadowOffsetX = 0;
}
// Draw the color canvas based on the selected hue
function drawColorCanvas(hue) {
const width = colorPickerCanvas.width;
const height = colorPickerCanvas.height;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const saturation = x / width;
const brightness = 1 - y / height;
const [r, g, b] = hsbToRgb(hue, saturation, brightness);
// Quantize to 4-bit color depth
const quantizedR = Math.round(r / 255 * 15) * 17;
const quantizedG = Math.round(g / 255 * 15) * 17;
const quantizedB = Math.round(b / 255 * 15) * 17;
colorCtx.fillStyle = `rgb(${quantizedR}, ${quantizedG}, ${quantizedB})`;
colorCtx.fillRect(x, y, 1, 1);
}
}
}
// Draw the selection circle
function drawCircle(x, y) {
colorCtx.beginPath();
colorCtx.arc(x, y, 6, 0, Math.PI * 2);
colorCtx.strokeStyle = 'white';
colorCtx.lineWidth = 3;
colorCtx.stroke();
}
function getStoredPaletteIndices() {
// Ensure this function returns the correct indices for the current canvas state
return storedPaletteIndices; // Make sure this is correctly populated elsewhere in your code
}
function updateCanvasWithPalette(palette) {
// console.log('Updating canvas with new palette');
const canvas = document.getElementById('color-canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
const originalWidth = 32;
const originalHeight = 32;
const imageData = ctx.createImageData(originalWidth, originalHeight);
const data = imageData.data;
// Assuming you have a stored array of palette indices for each pixel
const paletteIndices = getStoredPaletteIndices(); // Implement this function to retrieve stored indices
for (let i = 0; i < paletteIndices.length; i++) {
const index = paletteIndices[i]; // Get the palette index for this pixel
// Check if the index is valid
if (index >= 0 && index < palette.length) {
const color = palette[index]; // Get the new color from the updated palette
if (color) {
const pixelIndex = i * 4;
data[pixelIndex] = color.r;
data[pixelIndex + 1] = color.g;
data[pixelIndex + 2] = color.b;
data[pixelIndex + 3] = color.a; // Ensure alpha is also updated
}
}
}
// Draw the updated 32x32 image data onto the canvas
ctx.putImageData(imageData, 0, 0);
// Scale the 32x32 image data to the full canvas size
const scaledImageData = ctx.createImageData(canvas.width, canvas.height);
for (let y = 0; y < originalHeight; y++) {
for (let x = 0; x < originalWidth; x++) {
const originalIndex = (y * originalWidth + x) * 4;
for (let dy = 0; dy < scaleFactor; dy++) {
for (let dx = 0; dx < scaleFactor; dx++) {
const scaledIndex = ((y * scaleFactor + dy) * canvas.width + (x * scaleFactor + dx)) * 4;
scaledImageData.data[scaledIndex] = data[originalIndex];
scaledImageData.data[scaledIndex + 1] = data[originalIndex + 1];
scaledImageData.data[scaledIndex + 2] = data[originalIndex + 2];
scaledImageData.data[scaledIndex + 3] = data[originalIndex + 3];
}
}
}
}
ctx.putImageData(scaledImageData, 0, 0);
// console.log('Canvas updated with new palette');
}
function resetColorPickerIndicators(r, g, b, a) {
const [hue, saturation, brightness] = rgbToHsb(r, g, b);
// Update the hue indicator position
hueIndicatorX = hue * hueSlider.width;
currentHue = hue;
drawHueSlider();
// Update the opacity indicator position
opacityIndicatorX = (a / 255) * opacitySlider.width;
drawOpacitySlider();
// Update the color indicator positions
colorIndicatorX = Math.max(0, Math.min(saturation * colorPickerCanvas.width, colorPickerCanvas.width - 1));
colorIndicatorY = Math.max(0, Math.min((1 - brightness) * colorPickerCanvas.height, colorPickerCanvas.height - 1));
drawColorCanvas(currentHue);
drawCircle(colorIndicatorX, colorIndicatorY);
}
function updateColorPreview(event) {
const r = parseInt(redInput.value) * 17; // Scale 4-bit to 8-bit
const g = parseInt(greenInput.value) * 17;
const b = parseInt(blueInput.value) * 17;
const a = parseInt(alphaInput.value) * 17; // Scale 4-bit to 8-bit
colorPreview.style.backgroundColor = `rgba(${r}, ${g}, ${b}, ${a / 255})`;
// Apply the color change immediately
if (currentPaletteIndex !== null) {
currentPalette[currentPaletteIndex] = { r, g, b, a };
updateCanvasWithPalette(currentPalette);
displayColorPalette(currentPalette);
// Update primary or secondary color if necessary
if (currentPaletteIndex === primaryColorIndex) {
primaryColor = rgbaToHex(r, g, b, a);
updateColorIndicators();
}
if (currentPaletteIndex === secondaryColorIndex) {
secondaryColor = rgbaToHex(r, g, b, a);
updateColorIndicators();
}
// Reset the color-picker-canvas and hue slider indicators
// only if the color is changed by color form inputs.
if (event) resetColorPickerIndicators(r, g, b, a);
}
}
function showColorPicker(index, event) {
console.log(`Opening color picker for index: ${index}`);
currentPaletteIndex = index;
const color = currentPalette[index];
// Convert the current color to HSB
const [hue, saturation, brightness] = rgbToHsb(color.r, color.g, color.b);
// Update the hue indicator position
hueIndicatorX = hue * hueSlider.width;
currentHue = hue;
drawHueSlider();
// Update the color indicator positions
colorIndicatorX = Math.max(0, Math.min(saturation * colorPickerCanvas.width, colorPickerCanvas.width - 1));
colorIndicatorY = Math.max(0, Math.min((1 - brightness) * colorPickerCanvas.height, colorPickerCanvas.height - 1));
drawColorCanvas(currentHue);
drawCircle(colorIndicatorX, colorIndicatorY);
// Update the color preview and inputs
redInput.value = color.r / 17;
greenInput.value = color.g / 17;
blueInput.value = color.b / 17;
alphaInput.value = color.a / 17;
updateColorPreview();
// Position the color picker
const rect = document.getElementById('color-palette-item-index-' + index).getBoundingClientRect();
const topPosition = rect.bottom;
const leftPosition = rect.left;
if (customColorPicker) {
customColorPicker.style.position = 'fixed';
customColorPicker.style.top = `${topPosition}px`;
customColorPicker.style.left = `${leftPosition}px`;
customColorPicker.style.display = 'block';
} else {
console.error('customColorPicker element not found');
}
// Set the opacity slider position based on the alpha value
opacityIndicatorX = (color.a / 255) * opacitySlider.width;
drawOpacitySlider();
}
function hexToRgba(hex) {
const match = hex.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
return match ? { r: parseInt(match[1], 16), g: parseInt(match[2], 16), b: parseInt(match[3], 16), a: parseInt(match[4], 16) } : null;
}
function hexToRgbaString(hex) {
const match = hex.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
return match ? `rgba(${parseInt(match[1], 16)}, ${parseInt(match[2], 16)}, ${parseInt(match[3], 16)}, ${parseInt(match[4], 16) / 255})` : null;
}
function updateColorIndicators() {
const primaryIndicator = document.getElementById('primary-color-indicator');
const secondaryIndicator = document.getElementById('secondary-color-indicator');
primaryIndicator.style.backgroundColor = hexToRgbaString(primaryColor);
secondaryIndicator.style.backgroundColor = hexToRgbaString(secondaryColor);
}
// Add events to each color in the palette
function attachPaletteEvents() {
document.querySelectorAll('#color-palette div').forEach((colorDiv, index) => {
colorDiv.addEventListener('dblclick', (e) => {
e.preventDefault(); // Prevent the native color picker
showColorPicker(index, e); // Pass the event object
});
// Single click to set primary color
colorDiv.addEventListener('click', (e) => {
if (e.button === 0) { // Left click
primaryColor = rgbaToHex(currentPalette[index].r, currentPalette[index].g, currentPalette[index].b, currentPalette[index].a);
primaryColorIndex = index;
updateColorIndicators();
}
});
// Handle right-click for secondary color and double right-click for picker
colorDiv.addEventListener('contextmenu', (e) => {
e.preventDefault();
const currentTime = new Date().getTime();
if (currentTime - lastRightClickTime < doubleClickThreshold) {
showColorPicker(index, e); // Open picker on double right-click
} else {
secondaryColor = rgbaToHex(currentPalette[index].r, currentPalette[index].g, currentPalette[index].b, currentPalette[index].a);
secondaryColorIndex = index;
updateColorIndicators();
}
lastRightClickTime = currentTime;
});
});
}
function displayColorPalette(palette) {
const paletteContainer = document.getElementById('color-palette');
paletteContainer.innerHTML = ''; // Clear previous palette
const squareSize = 24; // Size of each color square
const columns = 8; // Number of columns in the grid
const gap = '0 0'; // Gap between squares
const borderSize = 1;
// Calculate the total width of the palette container
const totalWidth = columns * (squareSize + gap) - gap; // Subtract the last gap
// Set the palette container to display as a grid
paletteContainer.style.display = 'grid';
paletteContainer.style.gridTemplateColumns = `repeat(${columns}, ${squareSize+(borderSize*2)}px)`;
paletteContainer.style.gap = `${gap}px`;
paletteContainer.style.width = `${totalWidth}px`;
paletteContainer.style.border = `${borderSize}px solid #000`;
paletteContainer.style.borderRadius = '2px';
palette.forEach((color, index) => {
const colorDiv = document.createElement('div');
colorDiv.style.width = `${squareSize}px`;
colorDiv.style.height = `${squareSize}px`;
colorDiv.style.backgroundColor = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
colorDiv.style.cursor = 'pointer';
colorDiv.style.border = '1px solid #000'; // Optional: Add a border for better visibility
colorDiv.style.position = 'relative'; // Position relative to allow absolute positioning of the input
colorDiv.id = 'color-palette-item-index-' + index;
// Create a color input element
const colorInput = document.createElement('input');
colorInput.type = 'color';
colorInput.value = rgbaToHex(color.r, color.g, color.b, color.a).slice(0, 7); // Use only RGB for the color input
colorInput.style.position = 'absolute';
colorInput.style.top = '0';
colorInput.style.left = '0';
colorInput.style.width = '100%';
colorInput.style.height = '100%';
colorInput.style.opacity = '0'; // Hide the input visually but keep it accessible
colorInput.style.pointerEvents = 'none'; // Disable pointer events to prevent single click
// Store the alpha value as a data attribute
colorInput.setAttribute('data-alpha', (color.a & 0xFF).toString(16).padStart(2, '0'));
// Single click to set primary color
colorDiv.addEventListener('click', (e) => {
if (e.button === 0) { // Left click
const alphaHex = colorInput.getAttribute('data-alpha');
primaryColor = colorInput.value + alphaHex; // Append the alpha value
primaryColorIndex = index;
updateColorIndicators();
}
});
// Right click to set secondary color
colorDiv.addEventListener('contextmenu', (e) => {
e.preventDefault();
const alphaHex = colorInput.getAttribute('data-alpha');
secondaryColor = colorInput.value + alphaHex; // Append the alpha value
secondaryColorIndex = index;
updateColorIndicators();
});
// Add change event to update color
colorInput.addEventListener('input', () => {
const newColor = colorInput.value + 'FF'; // Append full opacity
const rgba = hexToRgba(newColor);
if (rgba) {
console.log(`Updating color index ${index} to`, rgba);
color.r = rgba.r;
color.g = rgba.g;
color.b = rgba.b;
color.a = rgba.a;
colorDiv.style.backgroundColor = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
// Update the canvas with the new palette
updateCanvasWithPalette(currentPalette);
// Update the color indicators if this color is selected
if (index === primaryColorIndex) {
primaryColor = newColor;
updateColorIndicators();
}
if (index === secondaryColorIndex) {
secondaryColor = newColor;
updateColorIndicators();
}
}
});
colorDiv.appendChild(colorInput);
paletteContainer.appendChild(colorDiv);
});
// Update color indicators based on the new palette
if (primaryColorIndex >= palette.length) {
primaryColorIndex = 0; // Reset to first color if out of bounds
}
if (secondaryColorIndex >= palette.length) {
secondaryColorIndex = 1; // Reset to second color if out of bounds
}
primaryColor = rgbaToHex(palette[primaryColorIndex].r, palette[primaryColorIndex].g, palette[primaryColorIndex].b, palette[primaryColorIndex].a);
secondaryColor = rgbaToHex(palette[secondaryColorIndex].r, palette[secondaryColorIndex].g, palette[secondaryColorIndex].b, palette[secondaryColorIndex].a);
updateColorIndicators();
// Store the current palette
currentPalette = [...palette];
attachPaletteEvents();
}
function processColorImage(img) {
// Create an invisible 32x32 canvas
const hiddenCanvas = document.createElement('canvas');
hiddenCanvas.width = 32;
hiddenCanvas.height = 32;
const hiddenCtx = hiddenCanvas.getContext('2d');
// Draw the image onto the 32x32 canvas
hiddenCtx.drawImage(img, 0, 0, 32, 32);
// Extract image data from the 32x32 canvas
const imageData = hiddenCtx.getImageData(0, 0, 32, 32);
const colors = extractColors(imageData);
// Check if transparent color exists in the image
const transparentColor = { r: 255, g: 255, b: 255, a: 0 };
const hasTransparent = colors.some(color => color.a === 0);
// Reduce the color palette to 16 colors
let reducedPalette = reducePalette(colors, hasTransparent ? 15 : 16);
// Quantize colors to 4 bits per channel
const quantizedColors = reducedPalette.map(color => ({
r: Math.round((color.r / 255) * 15) * 17,
g: Math.round((color.g / 255) * 15) * 17,
b: Math.round((color.b / 255) * 15) * 17,
a: Math.round((color.a / 255) * 15) * 17,
}));
// If transparent color was present, add it to the end of the palette
if (hasTransparent) {
quantizedColors.push(transparentColor);
}
// Ensure the palette has at least 16 colors
while (quantizedColors.length < 16) {
quantizedColors.push(transparentColor);
}
// Update the palette indices for each pixel
storedPaletteIndices = updatePaletteIndices(imageData, quantizedColors);
// Store the current palette
currentPalette = [...quantizedColors];
// Apply the reduced palette and palette indices to the visible canvas
applyPaletteToCanvas(storedPaletteIndices, quantizedColors);
displayColorPalette(quantizedColors);
// Add this at the end
updateMonoPaletteStates();
}
function applyPaletteToCanvas(paletteIndices, palette) {
const canvas = document.getElementById('color-canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
const imageData = ctx.createImageData(32, 32);
for (let i = 0; i < paletteIndices.length; i++) {
const color = palette[paletteIndices[i]];
if (!color) continue;
const index = i * 4;
imageData.data[index] = color.r;
imageData.data[index + 1] = color.g;
imageData.data[index + 2] = color.b;
imageData.data[index + 3] = color.a; // Use the alpha value from the palette
}
// Draw the 32x32 image data onto the canvas
ctx.putImageData(imageData, 0, 0);
colorCtx.clearRect(0, 0, canvas.width, canvas.height);
// Scale the 32x32 image data to the full canvas size
const scaledImageData = ctx.createImageData(canvas.width, canvas.height);
for (let y = 0; y < 32; y++) {
for (let x = 0; x < 32; x++) {
const originalIndex = (y * 32 + x) * 4;
for (let dy = 0; dy < scaleFactor; dy++) {
for (let dx = 0; dx < scaleFactor; dx++) {
const scaledIndex = ((y * scaleFactor + dy) * canvas.width + (x * scaleFactor + dx)) * 4;
scaledImageData.data[scaledIndex] = imageData.data[originalIndex];
scaledImageData.data[scaledIndex + 1] = imageData.data[originalIndex + 1];
scaledImageData.data[scaledIndex + 2] = imageData.data[originalIndex + 2];
scaledImageData.data[scaledIndex + 3] = imageData.data[originalIndex + 3];
}
}
}
}
ctx.putImageData(scaledImageData, 0, 0);
}
function extractColors(imageData) {
const colors = new Map();
for (let i = 0; i < imageData.data.length; i += 4) {
const r = imageData.data[i];
const g = imageData.data[i + 1];
const b = imageData.data[i + 2];
const a = imageData.data[i + 3];
const color = (r << 16) | (g << 8) | b;
if (!colors.has(color)) {
colors.set(color, { r, g, b, a });
}
}
return Array.from(colors.values());
}
function reducePalette(colors, maxColors) {
const colorsToReduce = colors.filter(color => color.a !== 0);
while (colorsToReduce.length > maxColors) {
let minDistance = Infinity;
let pairToMerge = [0, 1];
// Find the closest pair of colors
for (let i = 0; i < colorsToReduce.length; i++) {
for (let j = i + 1; j < colorsToReduce.length; j++) {
const distance = colorDistance(colorsToReduce[i], colorsToReduce[j]);
if (distance < minDistance) {
minDistance = distance;
pairToMerge = [i, j];
}
}
}
// Merge the closest pair
const [index1, index2] = pairToMerge;
const mergedColor = averageColor(colorsToReduce[index1], colorsToReduce[index2]);
colorsToReduce.splice(index2, 1);
colorsToReduce[index1] = mergedColor;
}
return colorsToReduce;
}
function colorDistance(color1, color2) {
return Math.sqrt(
Math.pow(color1.r - color2.r, 2) +
Math.pow(color1.g - color2.g, 2) +
Math.pow(color1.b - color2.b, 2)
);
}
function averageColor(color1, color2) {
return {
r: Math.round((color1.r + color2.r) / 2),
g: Math.round((color1.g + color2.g) / 2),
b: Math.round((color1.b + color2.b) / 2),
a: Math.round((color1.a + color2.a) / 2)
};
}
function updatePaletteIndices(imageData, palette) {
const indices = [];
const transparentIndex = palette.findIndex(color => color.a === 0);
for (let i = 0; i < imageData.data.length; i += 4) {
const r = imageData.data[i];
const g = imageData.data[i + 1];
const b = imageData.data[i + 2];
const a = imageData.data[i + 3];
if (a === 0) {
// Assign the transparent index if the pixel is fully transparent
indices.push(transparentIndex);
} else {
// Find the closest palette index for non-transparent pixels
const index = findClosestPaletteIndex(r, g, b, palette);
indices.push(index);
}
}
return indices;
}
function findClosestPaletteIndex(r, g, b, palette) {
let closestIndex = 0;
let minDistance = Infinity;
palette.forEach((color, index) => {
// Only compare non-transparent colors
if (color.a !== 0) {
const distance = colorDistance({ r, g, b }, color);
if (distance < minDistance) {
minDistance = distance;
closestIndex = index;
}
}
});
return closestIndex;
}
function processMonoImage(img) {
// Create an invisible 32x32 canvas
const hiddenCanvas = document.createElement('canvas');
hiddenCanvas.width = 32;
hiddenCanvas.height = 32;
const hiddenCtx = hiddenCanvas.getContext('2d');
// Draw the image onto the 32x32 canvas
hiddenCtx.drawImage(img, 0, 0, 32, 32);
// Extract image data from the 32x32 canvas
const imageData = hiddenCtx.getImageData(0, 0, 32, 32);
const data = imageData.data;
// Define a threshold for converting to black or transparent
const threshold = 64; // Adjust this value as needed
// Get the visible canvas and its context
const canvas = document.getElementById('mono-canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
// Clear the canvas first
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Process each pixel
monoPixelStates = []; // Reset monoPixelStates
for (let y = 0; y < 32; y++) {
for (let x = 0; x < 32; x++) {
const i = (y * 32 + x) * 4;
const brightness = 0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2];
const isOn = brightness <= threshold;
monoPixelStates.push(isOn);
if (isOn) {
// Draw LCD-style pixel with gaps
ctx.fillStyle = '#1d4781';
ctx.fillRect(
x * scaleFactor + 1,
y * scaleFactor + 1,
scaleFactor - 1,
scaleFactor - 1
);
}
}
}
// Add this at the end
updateMonoPaletteStates();
}
function createBMPData(pixelIndices, palette) {
// Calculate file size including the color masks
const headerSize = 14; // Bitmap file header
const dibSize = 56; // Extended DIB header for BITFIELDS (includes masks)
const rowSize = 32 * 4; // 32 pixels * 4 bytes per pixel
const pixelDataSize = rowSize * 32; // 32 rows
const fileSize = headerSize + dibSize + pixelDataSize;
const pixelDataOffset = headerSize + dibSize;
// BMP file header (14 bytes)
const fileHeader = new Uint8Array([
0x42, 0x4D, // Signature 'BM'
fileSize & 0xFF, // File size (little-endian)
(fileSize >> 8) & 0xFF,
(fileSize >> 16) & 0xFF,
(fileSize >> 24) & 0xFF,
0x00, 0x00, // Reserved
0x00, 0x00, // Reserved
pixelDataOffset & 0xFF, // Offset to pixel data (little-endian)
(pixelDataOffset >> 8) & 0xFF,
(pixelDataOffset >> 16) & 0xFF,
(pixelDataOffset >> 24) & 0xFF
]);
// DIB header with BITFIELDS (56 bytes)
const dibHeader = new Uint8Array([
0x38, 0x00, 0x00, 0x00, // DIB header size (56)
0x20, 0x00, 0x00, 0x00, // Width (32)
0x20, 0x00, 0x00, 0x00, // Height (32)
0x01, 0x00, // Color planes
0x20, 0x00, // Bits per pixel (32)
0x03, 0x00, 0x00, 0x00, // BI_BITFIELDS compression
pixelDataSize & 0xFF, // Image size
(pixelDataSize >> 8) & 0xFF,
(pixelDataSize >> 16) & 0xFF,
(pixelDataSize >> 24) & 0xFF,
0x00, 0x00, 0x00, 0x00, // X pixels per meter
0x00, 0x00, 0x00, 0x00, // Y pixels per meter
0x00, 0x00, 0x00, 0x00, // Total colors
0x00, 0x00, 0x00, 0x00, // Important colors
0x00, 0x00, 0xFF, 0x00, // Blue channel mask (0x00FF0000)
0x00, 0xFF, 0x00, 0x00, // Green channel mask (0x0000FF00)
0xFF, 0x00, 0x00, 0x00, // Red channel mask (0x000000FF)
0x00, 0x00, 0x00, 0xFF // Alpha channel mask (0xFF000000)
]);
// Create pixel data array
const pixelData = new Uint8Array(pixelDataSize);
for (let y = 0; y < 32; y++) {
for (let x = 0; x < 32; x++) {
const index = y * 32 + x;
const paletteIndex = pixelIndices[index];
const color = palette[paletteIndex];
const newX = x;
const newY = 31 - y; // Flip vertically for BMP
const dstOffset = (newY * rowSize) + (newX * 4);
pixelData[dstOffset] = color.b; // B
pixelData[dstOffset + 1] = color.g; // G
pixelData[dstOffset + 2] = color.r; // R
pixelData[dstOffset + 3] = color.a; // A
}
}
// Combine all parts into final BMP file
const bmpData = new Uint8Array(fileSize);
let offset = 0;
bmpData.set(fileHeader, offset);
offset += fileHeader.length;
bmpData.set(dibHeader, offset);
offset += dibHeader.length;
bmpData.set(pixelData, offset);
return bmpData;
}
function createMonoBMPData(monoPixelStates) {
// Define a monochrome palette: black for "on" and white for "off"
const monoPalette = [
{ r: 0, g: 0, b: 0, a: 255 }, // Black
{ r: 255, g: 255, b: 255, a: 255 } // White
];
// Convert monoPixelStates to pixelIndices
const pixelIndices = monoPixelStates.map(isOn => isOn ? 0 : 1);
// Use the existing createBMPData function to generate the BMP data
return createBMPData(pixelIndices, monoPalette);
}
/**
* Create a GIF Blob from a 32x32 image given a palette and pixel data.
* - width, height: dimensions (should be 32)
* - palette: an array of 16 {r, g, b, a} objects (the 16th is assumed transparent)
* - pixelIndices: an array of width*height numbers (each 0–15)
*/
function createColorGIFData(pixelIndices, palette) {
const width = 32;
const height = 32;
let bytes = [];
// --- GIF Header ("GIF89a") ---
bytes.push(0x47, 0x49, 0x46, 0x38, 0x39, 0x61);
// --- Logical Screen Descriptor ---
// Width & Height in little-endian order.
bytes.push(width & 0xFF, (width >> 8) & 0xFF);
bytes.push(height & 0xFF, (height >> 8) & 0xFF);
// Packed Field:
// Global Color Table Flag = 1 (bit 7)
// Color Resolution = 7 (bits 4–6: meaning 8 bits per primary color)
// Sort Flag = 0 (bit 3)
// Size of Global Color Table = 3 (bits 0–2: 2^(3+1)=16 colors)
let packed = (1 << 7) | (7 << 4) | (3);
bytes.push(packed);
// Background Color Index (0) and Pixel Aspect Ratio (0)
bytes.push(0, 0);
// --- Global Color Table (16 entries, 3 bytes each) ---
for (let i = 0; i < 16; i++) {
if (i < palette.length) {
bytes.push(palette[i].r, palette[i].g, palette[i].b);
} else {
// Pad if needed.
bytes.push(0, 0, 0);
}
}
// Determine if transparency is needed
const transparentIndex = palette.findIndex(color => color.a === 0);
const hasTransparency = transparentIndex !== -1;
// --- Graphic Control Extension (for transparency) ---
// This block indicates that palette index 15 is transparent.
bytes.push(0x21, 0xF9, 0x04);
bytes.push(hasTransparency ? 0x01 : 0x00); // Set transparency flag if needed
bytes.push(0, 0, hasTransparency ? transparentIndex : 0, 0);
// --- Image Descriptor ---
bytes.push(0x2C); // Image Separator.
// Image Left and Top (0,0)
bytes.push(0, 0, 0, 0);
// Image Width & Height (little-endian)
bytes.push(width & 0xFF, (width >> 8) & 0xFF);
bytes.push(height & 0xFF, (height >> 8) & 0xFF);
// Packed Field: no local color table, not interlaced.
bytes.push(0);
// --- Image Data ---
// LZW Minimum Code Size – for 16 colors use 4.
const lzwMinCodeSize = 4;
bytes.push(lzwMinCodeSize);
// Use our "brute force" LZW encoder that outputs a clear code before each pixel.
const lzwData = lzwEncodeNoCompression(pixelIndices, lzwMinCodeSize);
// Package the LZW data into sub-blocks (each block is at most 255 bytes).
let offset = 0;
while (offset < lzwData.length) {
const blockSize = Math.min(255, lzwData.length - offset);
bytes.push(blockSize);
for (let i = 0; i < blockSize; i++) {
bytes.push(lzwData[offset + i]);
}
offset += blockSize;
}