Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 92x 8896x 8896x 8896x 8896x 450x 450x 8896x 8896x 8850x 46x 46x 46x 2x 2x 92x 8896x 8896x 8896x 2x 4x 4x 8896x 8896x 8896x 8896x 8896x 8896x 71168x 569344x 569344x 569344x 569344x 8896x 4x 450x 450x 450x 450x 450x 450x 450x 3397x 26950x 26950x 26950x 1084x 1084x 1084x 1084x 1084x 53x 397x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 2x 4x 470x 1162x 1162x 4x 8896x 8896x 8896x 8896x 8896x 8896x 71168x 569344x 569344x 569344x 569344x 219552x 38x 219552x 219552x 219552x 569344x 4x 236x 236x 236x 236x 236x 236x 236x 4x 38x 38x 38x 152x 152x 90x 90x 38x 4x 4x 64x 4x 4x 48x 48x 119x 710x 710x 710x 44x 44x 44x 44x 44x 44x 119x 4x 4x 64x 4x 20x 64x 4x 4x 947x 4x 3x 9x 9x 8x 1x 4x 2x 2x 8x 2x 4x 5x 20x 3x 2x 2x 2x 5x 5x 3x 2x 2x 2x 2x 5x 3x 3x 2x 4x 2x 3x 4x 39x 132x 132x 132x 132x 132x 100x 39x 39x 39x 39x 39x 72x 72x 132x 72x 72x 72x 60x 60x 60x 72x 72x 72x 72x 72x 60x 39x 31x 31x 31x 39x 60x 34x 45x 39x 47x 83x 4x 39x 60x 60x 60x 60x 58x 58x 39x 156x 39x 4x 5x 23x 4x 21x 21x 84x 84x 84x 21x 4x 6x 1x 5x 2x 2x 4x 2x 2x 3x 3x 3x 3x 3x 3x 21x 21x 6x 6x 3x 3x 3x 3x 3x 24x 21x 18x 3x | import chroma from "chroma-js";
import { TILE_SIZE } from "consts";
import { IndexedImage } from "shared/lib/tiles/indexedImage";
import { rgbToColorCorrectedHex } from "shared/lib/color/colorCorrection";
import { ColorCorrectionSetting } from "shared/lib/resources/types";
import { rgb2hex } from "shared/lib/helpers/color";
import { tileDataIndexFn } from "./tileData";
export type VariableLengthHexPalette = string[];
export type SparseHexPalette = [
string | undefined,
string | undefined,
string | undefined,
string | undefined,
];
export type HexPalette = [string, string, string, string];
export type AutoPaletteResult = {
map: number[];
palettes: HexPalette[];
indexedImage: IndexedImage;
};
interface IndexedColor {
hex: string;
index: number;
lightness: number;
}
const emptyPalette: HexPalette = ["000000", "000000", "000000", "000000"];
const BRIGHTNESS_ANCHOR: [number, number, number, number] = [100, 66, 33, 0];
/**
* Given raw RGBA pixel data construct:
* + an array of GBC compatible color palettes
* + DMG tile data
* + an attr map from tile index to color palette
*/
export const autoPalette = (
width: number,
height: number,
pixels: Buffer | Uint8ClampedArray,
colorCorrection: ColorCorrectionSetting,
uiPalette?: HexPalette,
): AutoPaletteResult => {
const xTiles = Math.floor(width / TILE_SIZE);
const yTiles = Math.floor(height / TILE_SIZE);
const paletteCache: Record<string, number> = {};
const allPalettes: VariableLengthHexPalette[] = [];
const tilePaletteMap: number[] = [];
const recolorCache: Record<string, string> = {};
const indexedImage = {
width,
height,
data: new Uint8Array(width * height),
};
// Loop each tile to extract palette used and build
// mapping table from tile to palette
// Keep cache of tile rgb data to hex palette so don't
// evaluate identical tile data multiple times
const tilePaletteCache: Record<string, VariableLengthHexPalette> = {};
for (let tyi = 0; tyi < yTiles; tyi++) {
for (let txi = 0; txi < xTiles; txi++) {
const ti = tyi * xTiles + txi;
const tileKey = tileToCacheKey(pixels, width, txi, tyi);
let palette = tilePaletteCache[tileKey];
if (!palette) {
palette = extractTilePalette(pixels, width, txi, tyi, colorCorrection);
tilePaletteCache[tileKey] = palette;
}
const key = palette.join("");
if (paletteCache[key]) {
tilePaletteMap[ti] = paletteCache[key];
} else {
tilePaletteMap[ti] = allPalettes.length;
paletteCache[key] = tilePaletteMap[ti];
allPalettes.push(palette);
}
}
}
// As some tiles may overlap it's possible to compress them further
// mapping table maps original palette index to indexed in compressed list
const { palettes, mappingTable } = setUIPalette(
compressPalettes(allPalettes),
uiPalette,
);
// Given the extracted colors we can now build the tile data
// and the mapping of tiles to color palette
for (let tyi = 0; tyi < yTiles; tyi++) {
for (let txi = 0; txi < xTiles; txi++) {
const ti = tyi * xTiles + txi;
tilePaletteMap[ti] = mappingTable[tilePaletteMap[ti]];
buildIndexedTile(
pixels,
width,
txi,
tyi,
tilePaletteMap[ti],
palettes[tilePaletteMap[ti]],
recolorCache,
indexedImage,
);
}
}
return {
map: tilePaletteMap,
palettes,
indexedImage,
};
};
/**
* Given raw RGBA pixel data and DMG indexed image construct:
* + an array of GBC compatible color palettes
* + an attr map from tile index to color palette
*/
export const autoPaletteUsingTiles = (
width: number,
height: number,
pixels: Buffer | Uint8ClampedArray,
tileData: IndexedImage,
colorCorrection: ColorCorrectionSetting,
uiPalette?: HexPalette,
): AutoPaletteResult => {
const xTiles = Math.floor(width / TILE_SIZE);
const yTiles = Math.floor(height / TILE_SIZE);
const paletteCache: Record<string, number> = {};
const allPalettes: SparseHexPalette[] = [];
const tilePaletteMap: number[] = [];
// Loop each tile to extract palette used and build
// mapping table from tile to palette
// using the DMG tile data as a hint for color mapping
for (let tyi = 0; tyi < yTiles; tyi++) {
for (let txi = 0; txi < xTiles; txi++) {
const ti = tyi * xTiles + txi;
const palette = extractTilePaletteWithHint(
pixels,
width,
txi,
tyi,
tileData,
colorCorrection,
);
const key = JSON.stringify(palette);
if (paletteCache[key]) {
tilePaletteMap[ti] = paletteCache[key];
} else {
tilePaletteMap[ti] = allPalettes.length;
paletteCache[key] = tilePaletteMap[ti];
allPalettes.push(palette);
}
}
}
// As some tiles may overlap it's possible to compress them further
// mapping table maps original palette index to indexed in compressed list
// const { palettes, mappingTable } = compressSparsePalettes(allPalettes);
const { palettes, mappingTable } = setUIPalette(
compressSparsePalettes(allPalettes),
uiPalette,
);
// Build mapping of tiles to color palette
for (let tyi = 0; tyi < yTiles; tyi++) {
for (let txi = 0; txi < xTiles; txi++) {
const ti = tyi * xTiles + txi;
tilePaletteMap[ti] = mappingTable[tilePaletteMap[ti]];
}
}
return {
map: tilePaletteMap,
palettes,
indexedImage: tileData,
};
};
/**
* Build a cache key for a given tile's pixel data
*/
const tileToCacheKey = (
pixels: Buffer | Uint8ClampedArray,
width: number,
tileX: number,
tileY: number,
): string => {
const startX = tileX * TILE_SIZE;
const endX = (tileX + 1) * TILE_SIZE;
const startY = tileY * TILE_SIZE;
const endY = (tileY + 1) * TILE_SIZE;
const values: number[] = [];
for (let yi = startY; yi < endY; yi++) {
for (let xi = startX; xi < endX; xi++) {
const i = (yi * width + xi) * 4;
values.push(pixels[i]);
values.push(pixels[i + 1]);
values.push(pixels[i + 2]);
}
}
return values.join();
};
/**
* For a given tile color data extract the first four colors found sorted by perceptual lightness
*/
const extractTilePalette = (
pixels: Buffer | Uint8ClampedArray,
width: number,
tileX: number,
tileY: number,
colorCorrection: ColorCorrectionSetting,
): VariableLengthHexPalette => {
const startX = tileX * TILE_SIZE;
const endX = (tileX + 1) * TILE_SIZE;
const startY = tileY * TILE_SIZE;
const endY = (tileY + 1) * TILE_SIZE;
const seenColorLookup: Record<string, boolean> = {};
const colors: VariableLengthHexPalette = [];
for (let yi = startY; yi < endY; yi++) {
for (let xi = startX; xi < endX; xi++) {
const i = (yi * width + xi) * 4;
const key = `${pixels[i]},${pixels[i + 1]},${pixels[i + 2]}`;
if (!seenColorLookup[key]) {
seenColorLookup[key] = true;
const colorCorrectionFn =
colorCorrection === "default" ? rgbToColorCorrectedHex : rgb2hex;
const hex = colorCorrectionFn(pixels[i], pixels[i + 1], pixels[i + 2]);
colors.push(hex);
if (colors.length === 4) {
return sortHexPalette(colors);
}
}
}
}
return sortHexPalette(colors);
};
/**
* For a given tile color data and DMG tile hint extract a sparse palette mapping from DMG index to color
*/
export const extractTilePaletteWithHint = (
pixels: Buffer | Uint8ClampedArray,
width: number,
tileX: number,
tileY: number,
indexedImage: IndexedImage,
colorCorrection: ColorCorrectionSetting,
): SparseHexPalette => {
const startX = tileX * TILE_SIZE;
const endX = (tileX + 1) * TILE_SIZE;
const startY = tileY * TILE_SIZE;
const endY = (tileY + 1) * TILE_SIZE;
const seenColorLookup: Record<string, boolean> = {};
const colors: SparseHexPalette = [undefined, undefined, undefined, undefined];
let seenCount = 0;
for (let yi = startY; yi < endY; yi++) {
for (let xi = startX; xi < endX; xi++) {
const ii = yi * width + xi;
const i = ii * 4;
const index = indexedImage.data[ii];
Iif (colors[index]) {
continue;
}
const key = `${pixels[i]},${pixels[i + 1]},${pixels[i + 2]}`;
if (!seenColorLookup[key]) {
seenColorLookup[key] = true;
const colorCorrectionFn =
colorCorrection === "default" ? rgbToColorCorrectedHex : rgb2hex;
const hex = colorCorrectionFn(pixels[i], pixels[i + 1], pixels[i + 2]);
colors[index] = hex;
seenCount++;
if (seenCount === 4) {
return colors;
}
}
}
}
return colors;
};
/**
* Sort palette by perceptual lightness
*/
const sortHexPalette = (
input: VariableLengthHexPalette,
): VariableLengthHexPalette => {
return input
.map((hex) => ({ hex, lightness: chroma(hex).lab()[0] }))
.sort(sortLightnessProp)
.map(({ hex }) => hex);
};
/**
* Given a palette for a selected tile build DMG indexed tile data
* by finding closest palette color for each pixel in tile
*/
const buildIndexedTile = (
pixels: Buffer | Uint8ClampedArray,
width: number,
tileX: number,
tileY: number,
paletteIndex: number,
palette: VariableLengthHexPalette,
recolorCache: Record<string, string>,
indexedImage: IndexedImage,
): void => {
const startX = tileX * TILE_SIZE;
const endX = (tileX + 1) * TILE_SIZE;
const startY = tileY * TILE_SIZE;
const endY = (tileY + 1) * TILE_SIZE;
const indexCache: Record<string, number> = {};
for (let yi = startY; yi < endY; yi++) {
for (let xi = startX; xi < endX; xi++) {
const ii = yi * width + xi;
const i = ii * 4;
// Cache key for this RGB + Palette index combination
const key = `${paletteIndex}:${pixels[i]},${pixels[i + 1]},${
pixels[i + 2]
}`;
// Check local cache for RGB to index value
if (!indexCache[key]) {
// Otherwise check image wide cache for palette + RGB to closest hex
if (!recolorCache[key]) {
recolorCache[key] = findClosestHexColor(
rgbToColorCorrectedHex(pixels[i], pixels[i + 1], pixels[i + 2]),
palette,
);
}
const color = recolorCache[key];
const index = palette.indexOf(color);
indexCache[key] = index;
}
indexedImage.data[ii] = indexCache[key];
}
}
};
/**
* Calculate quick rough distance between two hex colors
*/
const manhattanHexDistance = (color1: string, color2: string): number => {
const r1 = parseInt(color1.substring(0, 2), 16);
const g1 = parseInt(color1.substring(2, 4), 16);
const b1 = parseInt(color1.substring(4, 6), 16);
const r2 = parseInt(color2.substring(0, 2), 16);
const g2 = parseInt(color2.substring(2, 4), 16);
const b2 = parseInt(color2.substring(4, 6), 16);
return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2);
};
/**
* Given a calculated palette find the closest match to a given hex color
*/
const findClosestHexColor = (
color: string,
palette: VariableLengthHexPalette,
): string => {
let closestColor = palette[0];
let minDistance = Infinity;
for (const paletteColor of palette) {
const distance = manhattanHexDistance(color, paletteColor);
if (distance < minDistance) {
minDistance = distance;
closestColor = paletteColor;
}
}
return closestColor;
};
/**
* Compress array of hex palettes by merging overlapping palettes
* builds a mapping table from old palette to new index
*/
export const compressPalettes = (allPalettes: VariableLengthHexPalette[]) => {
let outPalettes = [...allPalettes];
// let labPalettes = allPalettes.map((palette) => palette.map((hex) => ({hex, chroma:chroma(hex)})));
const originIndices: number[][] = allPalettes.map((_, index) => [index]); // Tracks original indices for each new palette
// Sort with largest palettes first before merging
// Need to tests to see if this is needed
// If it is needs a mapping table update
// labPalettes = labPalettes.sort((a, b) => b.length - a.length);
// Merge overlapping palettes
let merged = true;
while (merged) {
merged = false;
for (let i = 0; i < outPalettes.length; i++) {
for (let j = i + 1; j < outPalettes.length; j++) {
const combined = [...outPalettes[i], ...outPalettes[j]];
const uniqueColors = new Set(combined);
if (uniqueColors.size <= 4) {
outPalettes[i] = Array.from(uniqueColors);
originIndices[i] = [...originIndices[i], ...originIndices[j]]; // Merge origin indices
outPalettes.splice(j, 1);
originIndices.splice(j, 1); // Remove the merged palette's origin indices
merged = true;
break;
}
}
if (merged) break;
}
}
// Sort palettes by lightness
outPalettes = outPalettes.map(sortHexPalette);
// Generate mapping table
const mappingTable = new Array(allPalettes.length)
.fill(0)
.map((a, i) => i % 8);
originIndices.forEach((origins, newIndex) => {
origins.forEach((origin) => {
mappingTable[origin] = newIndex % 8;
});
});
return { palettes: fillVariablePalettes(outPalettes), mappingTable };
};
/**
* Sort function comparing two Chroma Colors in LAB space by perceptual lightness
*/
const sortLightnessProp = <T extends { lightness: number }>(a: T, b: T) =>
b.lightness - a.lightness;
/**
* Determine if two sparse palettes contain enough overlap to be mergable
*/
const canMergeSparsePalette = (
palette1: SparseHexPalette,
palette2: SparseHexPalette,
): boolean => {
// Check every color in both palettes is able to merge
return palette1.every((color1, index) => {
const color2 = palette2[index];
// Can merge empty spaces
if (color1 === undefined || color2 === undefined) {
return true;
}
// Or can merge if colors at index are identical
return color1 === color2;
});
};
/**
* Combine two sparse RGB palettes to include all colors from both palettes
* must confirm palettes are able to be merged with canMergeSparsePalette() first
*/
const mergeSparsePalette = (
palette1: SparseHexPalette,
palette2: SparseHexPalette,
): SparseHexPalette => {
const merged: SparseHexPalette = [undefined, undefined, undefined, undefined];
for (let i = 0; i < 4; i++) {
merged[i] = palette1[i] !== undefined ? palette1[i] : palette2[i];
}
return merged;
};
/**
* Compress array of sparse palettes by merging overlapping palettes
* builds a mapping table from old palette to new index
*/
export const compressSparsePalettes = (allPalettes: SparseHexPalette[]) => {
const indexedPalettes = allPalettes.map((palette, index) => ({
palette,
index,
numDefined: palette.reduce((memo, color) => memo + (color ? 1 : 0), 0),
}));
// Sort indexed palettes by the number of defined colors, descending
// to reduce fragmentation of palettes
indexedPalettes.sort((a, b) => b.numDefined - a.numDefined);
const palettes: SparseHexPalette[] = [];
const mappingTable: number[] = Array(allPalettes.length).fill(-1);
// Merge overlapping palettes and build mapping table
indexedPalettes.forEach(({ palette, index }) => {
let merged = false;
for (let i = 0; i < palettes.length; i++) {
if (canMergeSparsePalette(palettes[i], palette)) {
palettes[i] = mergeSparsePalette(palettes[i], palette);
mappingTable[index] = i;
merged = true;
break;
}
}
if (!merged) {
palettes.push(palette);
mappingTable[index] = palettes.length - 1;
}
});
return { palettes: fillSparsePalettes(palettes), mappingTable };
};
/**
* Given an array of spares hex palettes
* fill them so each contains four values
*/
const fillSparsePalettes = (palettes: SparseHexPalette[]): HexPalette[] => {
return palettes.map((palette) => {
return [
palette[0] ?? "000000",
palette[1] ?? "000000",
palette[2] ?? "000000",
palette[3] ?? "000000",
];
});
};
/**
* Fill and sort a variable length palette into a strict 4-entry HexPalette
* using brightness anchors and closest color matching
*/
export const fillVariablePalette = (
palette: VariableLengthHexPalette,
): HexPalette => {
// Convert palette into structured entries
const colors: IndexedColor[] = palette.map((hex) => {
const color = chroma(hex);
const [r, g, b] = color.rgb();
const lightness = color.lab()[0];
const colorIndex = tileDataIndexFn(r, g, b, 255);
return {
hex,
index: colorIndex,
lightness: lightness,
};
});
colors.sort((a, b) => a.index - b.index);
const result: (string | undefined)[] = [
undefined,
undefined,
undefined,
undefined,
];
const claimed: boolean[] = [false, false, false, false];
const overflow: IndexedColor[] = [];
// First pass: claim preferred slots based on index
{
let i = 0;
while (i < colors.length) {
const slotIndex = colors[i].index;
// Collect all colors that prefer this same slot
const start = i;
while (i < colors.length && colors[i].index === slotIndex) i++;
const group = colors.slice(start, i);
// Sort group by distance to brightness anchor for this slot
const anchor = BRIGHTNESS_ANCHOR[slotIndex];
group.sort((a, b) => {
const da = Math.abs(a.lightness - anchor);
const db = Math.abs(b.lightness - anchor);
return da - db;
});
// Winner claims preferred slot
const winner = group[0];
if (!claimed[slotIndex] && result[slotIndex] === undefined) {
result[slotIndex] = winner.hex;
claimed[slotIndex] = true;
} else E{
overflow.push(winner);
}
// Others overflow
for (let j = 1; j < group.length; j++) {
overflow.push(group[j]);
}
}
}
// Sort overflow for placement:
overflow.sort((a, b) => {
const da = Math.abs(a.lightness - BRIGHTNESS_ANCHOR[a.index]);
const db = Math.abs(b.lightness - BRIGHTNESS_ANCHOR[b.index]);
return da - db;
});
const findForward = (start: number): number | null => {
for (let i = start + 1; i < 4; i++) {
if (result[i] === undefined) return i;
}
return null;
};
const findBackward = (start: number): number | null => {
for (let i = start - 1; i >= 0; i--) {
if (result[i] === undefined) return i;
}
return null;
};
// Second pass: place overflow items
for (const col of overflow) {
let slot = findForward(col.index);
if (slot === null) slot = findBackward(col.index);
if (slot === null) slot = findBackward(4);
if (slot !== null) {
result[slot] = col.hex;
claimed[slot] = true;
}
}
// Fill empty slots
for (let i = 0; i < 4; i++) {
if (result[i] === undefined) result[i] = "000000";
}
return result as HexPalette;
};
export const fillVariablePalettes = (
palettes: VariableLengthHexPalette[],
): HexPalette[] => {
return palettes.map((palette) => {
return fillVariablePalette(palette);
});
};
const calculatePaletteDistance = (
palette1: HexPalette,
palette2: HexPalette,
): number => {
let totalDistance = 0;
for (let i = 0; i < 4; i++) {
const color1 = palette1[i] || "000000";
const color2 = palette2[i] || "000000";
totalDistance += manhattanHexDistance(color1, color2);
}
return totalDistance;
};
export const setUIPalette = (
{
palettes,
mappingTable,
}: { palettes: HexPalette[]; mappingTable: number[] },
uiPalette?: HexPalette,
): { palettes: HexPalette[]; mappingTable: number[] } => {
if (!uiPalette) {
return { palettes, mappingTable };
}
if (palettes.length < 8) {
const base = palettes.slice(0, 7);
while (base.length < 7) {
base.push(emptyPalette);
}
base.push(uiPalette);
return { palettes: base, mappingTable };
}
// Ensure we have at least 8 slots to work with
const base = palettes.slice(0);
while (base.length < 8) {
base.push(emptyPalette);
}
// Determine which palette in [0..6] most closely matches the UI palette
const candidateMax = Math.min(6, palettes.length - 1);
let replaceIndex = 0;
let minDistance = Number.POSITIVE_INFINITY;
for (let i = 0; i <= candidateMax; i++) {
const d = calculatePaletteDistance(base[i], uiPalette);
if (d < minDistance) {
minDistance = d;
replaceIndex = i;
}
}
// Build the new palettes:
// - Move whatever was at [7] into the slot we are replacing
// - Place the UI palette at [7]
const outPalettes = base.slice(0);
const previousAt7 = base[7];
outPalettes[replaceIndex] = previousAt7;
outPalettes[7] = uiPalette;
const outMapping = mappingTable.map((i) => {
if (i === replaceIndex) return 7;
if (i === 7) return replaceIndex;
return i;
});
return { palettes: outPalettes, mappingTable: outMapping };
};
|