forked from rilden/tiledpalettequant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
487 lines (477 loc) · 18.8 KB
/
script.js
File metadata and controls
487 lines (477 loc) · 18.8 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
import { Action, ColorZeroBehaviour, Dither, DitherPattern, PaletteMode } from "./enums.js";
const body = document.getElementById("body");
const imageSelector = document.getElementById("image_selector");
const tileWidthInput = document.getElementById("tile_width");
const tileHeightInput = document.getElementById("tile_height");
const numPalettesInput = document.getElementById("palette_num");
const colorsPerPaletteInput = document.getElementById("colors_per_palette");
const bitsPerChannelInput = document.getElementById("bits_per_channel");
const fractionOfPixelsInput = document.getElementById("fraction_of_pixels");
const integerInputs = [
[tileWidthInput, 8],
[tileHeightInput, 8],
[numPalettesInput, 4],
[colorsPerPaletteInput, 16],
[bitsPerChannelInput, 5],
];
function validateIntegerInput(numberInput) {
const [inputElement, defaultValue] = numberInput;
let num = parseInt(inputElement.value, radix);
if (isNaN(num))
num = defaultValue;
const min = parseInt(inputElement.min, radix);
const max = parseInt(inputElement.max, radix);
if (num < min)
num = min;
if (num > max)
num = max;
inputElement.value = num.toString();
}
function validateFloatInput(numberInput) {
const [inputElement, defaultValue] = numberInput;
let num = parseFloat(inputElement.value);
if (isNaN(num))
num = defaultValue;
const min = parseFloat(inputElement.min);
const max = parseFloat(inputElement.max);
if (num < min)
num = min;
if (num > max)
num = max;
inputElement.value = num.toFixed(2);
}
const uniqueInput = document.getElementById("unique");
const sharedInput = document.getElementById("shared");
const transparentFromTransparentInput = document.getElementById("transparent_from_transparent");
const transparentFromColorInput = document.getElementById("transparent_from_color");
const indexZeroButtons = [
uniqueInput,
sharedInput,
transparentFromTransparentInput,
transparentFromColorInput,
];
const indexZeroValues = [
ColorZeroBehaviour.Unique,
ColorZeroBehaviour.Shared,
ColorZeroBehaviour.TransparentFromTransparent,
ColorZeroBehaviour.TransparentFromColor,
];
const colorZeroAbbreviations = ["u", "s", "t", "tc"];
const sharedColorInput = document.getElementById("shared_color");
const transparentColorInput = document.getElementById("transparent_color");
const defaultColorInput = document.createElement("input");
defaultColorInput.value = "#000000";
const colorValues = [
defaultColorInput,
sharedColorInput,
transparentColorInput,
transparentColorInput,
];
const ditherOffInput = document.getElementById("dither_off");
const ditherFastInput = document.getElementById("dither_fast");
const ditherSlowInput = document.getElementById("dither_slow");
const ditherButtons = [ditherOffInput, ditherFastInput, ditherSlowInput];
const ditherValues = [Dither.Off, Dither.Fast, Dither.Slow];
const ditherWeightInput = document.getElementById("dither_weight");
const ditherDiagonal4Input = document.getElementById("dither_diagonal4");
const ditherHorizontal4Input = document.getElementById("dither_horizontal4");
const ditherVertical4Input = document.getElementById("dither_vertical4");
const ditherDiagonal2Input = document.getElementById("dither_diagonal2");
const ditherHorizontal2Input = document.getElementById("dither_horizontal2");
const ditherVertical2Input = document.getElementById("dither_vertical2");
const ditherPatternButtons = [
ditherDiagonal4Input,
ditherHorizontal4Input,
ditherVertical4Input,
ditherDiagonal2Input,
ditherHorizontal2Input,
ditherVertical2Input,
];
const ditherPatternValues = [
DitherPattern.Diagonal4,
DitherPattern.Horizontal4,
DitherPattern.Vertical4,
DitherPattern.Diagonal2,
DitherPattern.Horizontal2,
DitherPattern.Vertical2,
];
let sourceImageName = "carina";
const paletteGenerateInput = document.getElementById("palette_generate");
const paletteCustomInput = document.getElementById("palette_custom");
const paletteFileInput = document.getElementById("palette_file");
const paletteModeButtons = [paletteGenerateInput, paletteCustomInput];
const paletteModeValues = [PaletteMode.Generate, PaletteMode.Custom];
let customPalette = null;
let sourceImage = document.getElementById("source_img");
// Store original label text for palette mode UI updates
const originalLabels = {
bits_per_channel: document.querySelector('label[for="bits_per_channel"]')?.textContent || "",
fraction_of_pixels: document.querySelector('label[for="fraction_of_pixels"]')?.textContent || "",
};
function updatePaletteModeUI() {
const isCustomMode = paletteCustomInput.checked;
// Inputs to disable in custom palette mode
const disabledInCustomMode = [
[bitsPerChannelInput, "bits_per_channel"],
[fractionOfPixelsInput, "fraction_of_pixels"],
];
for (const [input, labelId] of disabledInCustomMode) {
input.disabled = isCustomMode;
const label = document.querySelector(`label[for="${labelId}"]`);
if (label) {
if (isCustomMode) {
label.textContent = originalLabels[labelId];
label.style.opacity = "0.6";
} else {
label.textContent = originalLabels[labelId];
label.style.opacity = "1";
}
}
}
}
paletteGenerateInput.addEventListener("change", updatePaletteModeUI);
paletteCustomInput.addEventListener("change", updatePaletteModeUI);
body.addEventListener("dragover", (event) => {
event.preventDefault();
if (event.dataTransfer == null)
return;
event.dataTransfer.dropEffect = "move";
});
body.addEventListener("drop", (event) => {
event.preventDefault();
const dt = event.dataTransfer;
if (dt == null)
return;
if (dt.files.length > 0) {
const file = dt.files[0];
if (file.type.substring(0, 6) === "image/") {
sourceImageName = file.name.substring(0, file.name.lastIndexOf("."));
sourceImage.src = URL.createObjectURL(file);
}
}
});
imageSelector.addEventListener("change", () => {
if (imageSelector.files == null)
return;
if (imageSelector.files.length > 0) {
const file = imageSelector.files[0];
sourceImageName = file.name.substring(0, file.name.lastIndexOf("."));
sourceImage.src = URL.createObjectURL(file);
}
});
let inProgress = false;
paletteFileInput.addEventListener("change", () => {
if (paletteFileInput.files == null)
return;
if (paletteFileInput.files.length > 0) {
const file = paletteFileInput.files[0];
const fileExt = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
if (fileExt === ".json") {
parsePaletteJson(file);
}
else if (fileExt === ".txt" || fileExt === ".pal") {
parsePaletteText(file);
}
else {
parsePaletteImage(file);
}
}
});
function parsePaletteImage(file) {
const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.onload = () => {
const palette = extractPaletteFromImage(img);
customPalette = palette;
console.log(`Loaded custom palette with ${palette.length} colors`);
};
img.onerror = () => {
alert("Failed to load palette image");
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
}
function parsePaletteJson(file) {
const reader = new FileReader();
reader.onload = (event) => {
try {
const data = JSON.parse(event.target.result);
const palette = [];
for (const color of data) {
if (typeof color === "string") {
palette.push(hexToColor(color));
}
else if (Array.isArray(color) && color.length >= 3) {
palette.push([color[0], color[1], color[2]]);
}
}
customPalette = palette;
console.log(`Loaded custom palette with ${palette.length} colors`);
}
catch (e) {
alert("Invalid palette JSON format: " + e.message);
}
};
reader.readAsText(file);
}
function parsePaletteText(file) {
const reader = new FileReader();
reader.onload = (event) => {
try {
const lines = event.target.result.split("\n");
const palette = [];
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length === 0 || trimmed.startsWith("#") || trimmed.startsWith(";"))
continue;
const parts = trimmed.split(/[\s,]+/);
if (parts.length >= 3) {
const r = parseInt(parts[0], 10);
const g = parseInt(parts[1], 10);
const b = parseInt(parts[2], 10);
if (!isNaN(r) && !isNaN(g) && !isNaN(b)) {
palette.push([
Math.max(0, Math.min(255, r)),
Math.max(0, Math.min(255, g)),
Math.max(0, Math.min(255, b)),
]);
}
}
}
if (palette.length === 0) {
alert("No valid colors found in palette file");
}
else {
customPalette = palette;
console.log(`Loaded custom palette with ${palette.length} colors`);
}
}
catch (e) {
alert("Failed to parse palette file: " + e.message);
}
};
reader.readAsText(file);
}
function extractPaletteFromImage(img) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, img.width, img.height);
const colorSet = 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];
if (a > 128) {
const key = `${r},${g},${b}`;
if (!colorSet.has(key)) {
colorSet.set(key, [r, g, b]);
}
}
}
return Array.from(colorSet.values());
}
let quantizedImageDownload = document.createElement("a");
let palettesImageDownload = document.createElement("a");
let quantizedImage = document.createElement("canvas");
let palettesImage = document.createElement("canvas");
let worker = null;
const quantizeButton = document.getElementById("quantizeButton");
const quantizedImages = document.getElementById("quantized_images");
const progress = document.getElementById("progress");
const radix = 10;
quantizeButton.addEventListener("click", () => {
sourceImage = document.getElementById("source_img");
if (!inProgress) {
inProgress = true;
quantizedImage = document.createElement("canvas");
quantizedImage.width = sourceImage.width;
quantizedImage.height = sourceImage.height;
quantizedImage.style.marginTop = "8px";
quantizedImage.style.marginLeft = "8px";
quantizedImageDownload = document.createElement("a");
quantizedImageDownload.appendChild(quantizedImage);
palettesImage = document.createElement("canvas");
palettesImage.width = 16;
palettesImage.height = sourceImage.height;
palettesImage.style.marginTop = "8px";
palettesImage.style.marginLeft = "8px";
palettesImageDownload = document.createElement("a");
palettesImageDownload.appendChild(palettesImage);
const div = document.createElement("div");
div.appendChild(quantizedImageDownload);
div.appendChild(palettesImageDownload);
quantizedImages.prepend(div);
}
integerInputs.forEach(validateIntegerInput);
validateFloatInput([fractionOfPixelsInput, 0.1]);
validateFloatInput([ditherWeightInput, 0.5]);
const colorZeroBehaviour = selectedValue(indexZeroButtons, indexZeroValues);
const colorInput = selectedValue(indexZeroButtons, colorValues);
const colorZeroValue = hexToColor(colorInput.value);
const ditherMethod = selectedValue(ditherButtons, ditherValues);
const ditherPattern = selectedValue(ditherPatternButtons, ditherPatternValues);
const colorZeroAbbreviation = selectedValue(indexZeroButtons, colorZeroAbbreviations);
const paletteMode = selectedValue(paletteModeButtons, paletteModeValues);
if (paletteMode === PaletteMode.Custom && customPalette === null) {
alert("Please select a custom palette file first");
inProgress = false;
return;
}
const settingsStr = `-${tileWidthInput.value}x${tileHeightInput.value}-${numPalettesInput.value}p${colorsPerPaletteInput.value}c-${colorZeroAbbreviation}`;
const totalPaletteColors = parseInt(numPalettesInput.value, radix) *
parseInt(colorsPerPaletteInput.value, radix);
if (totalPaletteColors > 256) {
quantizedImageDownload.download =
sourceImageName + settingsStr + ".png";
}
else {
quantizedImageDownload.download =
sourceImageName + settingsStr + ".bmp";
}
palettesImageDownload.download =
sourceImageName + settingsStr + "-palette.png";
if (worker)
worker.terminate();
worker = new Worker("./worker.js");
worker.onmessage = function (event) {
const data = event.data;
if (data.action === Action.UpdateProgress) {
progress.value = data.progress;
}
else if (data.action === Action.DoneQuantization) {
inProgress = false;
}
else if (data.action === Action.UpdateQuantizedImage) {
const imageData = data.imageData;
const quantizedImageData = new window.ImageData(imageData.width, imageData.height);
for (let i = 0; i < imageData.data.length; i++) {
quantizedImageData.data[i] = imageData.data[i];
}
quantizedImage.width = imageData.width;
quantizedImage.height = imageData.height;
const ctx = quantizedImage.getContext("2d");
ctx.putImageData(quantizedImageData, 0, 0);
if (imageData.totalPaletteColors > 256) {
quantizedImageDownload.href = quantizedImage.toDataURL();
}
else {
quantizedImageDownload.href = bmpToDataURL(imageData.width, imageData.height, imageData.paletteData, imageData.colorIndexes);
}
}
else if (data.action === Action.UpdatePalettes) {
const palettes = data.palettes;
const paletteDisplayHeight = 16;
const paletteDisplayWidth = Math.min(16, Math.ceil(512 / data.numColors));
palettesImage.width = data.numColors * paletteDisplayWidth;
palettesImage.height = data.numPalettes * paletteDisplayHeight;
const palCtx = palettesImage.getContext("2d");
for (let j = 0; j < palettes.length; j += 1) {
for (let i = 0; i < palettes[j].length; i += 1) {
palCtx.fillStyle = `rgb(
${Math.round(palettes[j][i][0])},
${Math.round(palettes[j][i][1])},
${Math.round(palettes[j][i][2])})`;
palCtx.fillRect(i * paletteDisplayWidth, j * paletteDisplayHeight, paletteDisplayWidth, paletteDisplayHeight);
}
}
palettesImageDownload.href = palettesImage.toDataURL();
}
};
worker.postMessage({
action: Action.StartQuantization,
imageData: imageDataFrom(sourceImage),
paletteMode: paletteMode,
customPalette: customPalette,
quantizationOptions: {
tileWidth: parseInt(tileWidthInput.value, radix),
tileHeight: parseInt(tileHeightInput.value, radix),
numPalettes: parseInt(numPalettesInput.value, radix),
colorsPerPalette: parseInt(colorsPerPaletteInput.value, radix),
bitsPerChannel: parseInt(bitsPerChannelInput.value, radix),
fractionOfPixels: parseFloat(fractionOfPixelsInput.value),
colorZeroBehaviour: colorZeroBehaviour,
colorZeroValue: colorZeroValue,
dither: ditherMethod,
ditherWeight: parseFloat(ditherWeightInput.value),
ditherPattern: ditherPattern,
},
});
});
function hexToColor(colorStr) {
return [
parseInt(colorStr.slice(1, 3), 16),
parseInt(colorStr.slice(3, 5), 16),
parseInt(colorStr.slice(5, 7), 16),
];
}
function selectedValue(radioInputs, values) {
for (let i = 0; i < radioInputs.length; i++) {
if (radioInputs[i].checked) {
return values[i];
}
}
throw "No radio inputs selected";
}
function imageDataFrom(img) {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0);
return context.getImageData(0, 0, img.width, img.height);
}
function bmpToDataURL(width, height, paletteData, colorIndexes) {
const bmpFileSize = 54 + paletteData.length + colorIndexes.length;
const bmpData = new Uint8ClampedArray(bmpFileSize);
bmpData[0] = 66;
bmpData[1] = 77;
write32Le(bmpData, 2, bmpFileSize);
write32Le(bmpData, 6, 0);
write32Le(bmpData, 0xa, 54 + paletteData.length);
write32Le(bmpData, 0xe, 40);
write32Le(bmpData, 0x12, width);
write32Le(bmpData, 0x16, height);
write16Le(bmpData, 0x1a, 1);
write16Le(bmpData, 0x1c, 8);
write32Le(bmpData, 0x1e, 0);
write32Le(bmpData, 0x22, colorIndexes.length);
write32Le(bmpData, 0x26, 2835);
write32Le(bmpData, 0x2a, 2835);
write32Le(bmpData, 0x2e, 256);
write32Le(bmpData, 0x32, 0);
for (let i = 0; i < paletteData.length; i++) {
bmpData[i + 54] = paletteData[i];
}
const imageDataAddress = 54 + paletteData.length;
for (let i = 0; i < colorIndexes.length; i++) {
bmpData[i + imageDataAddress] = colorIndexes[i];
}
return "data:image/bmp;base64," + uint8ToBase64(bmpData);
}
function uint8ToBase64(arr) {
return btoa(Array(arr.length)
.fill("")
.map((_, i) => String.fromCharCode(arr[i]))
.join(""));
}
function write32Le(bmpData, index, value) {
bmpData[index] = value % 256;
value = Math.floor(value / 256);
bmpData[index + 1] = value % 256;
value = Math.floor(value / 256);
bmpData[index + 2] = value % 256;
value = Math.floor(value / 256);
bmpData[index + 3] = value % 256;
}
function write16Le(bmpData, index, value) {
bmpData[index] = value % 256;
value = Math.floor(value / 256);
bmpData[index + 1] = value % 256;
}
//# sourceMappingURL=script.js.map