All files / src/shared/lib/tiles autoColor.ts

65.13% Statements 155/238
58.54% Branches 24/41
60.71% Functions 17/28
65.88% Lines 139/211

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 4983x 3x   3x                                                 3x         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                       3x                                                                                                                   3x           8896x 8896x 8896x 8896x 8896x 8896x 71168x 569344x 569344x 569344x 569344x     8896x           3x           450x 450x 450x 450x 450x 450x 450x 3397x 26950x 26950x 26950x 1084x 1084x 1084x 1084x 53x         397x           3x                                                                               3x     460x 1122x   1122x             3x                   8896x 8896x 8896x 8896x 8896x 8896x 71168x 569344x 569344x   569344x       569344x   220960x 38x         220960x 220960x 220960x   569344x               3x 148x 148x 148x 148x 148x 148x 148x           3x       38x 38x 38x 148x 148x 91x 91x     38x             3x   2x         2x   46x               2x 2x 38x 38x 101x 666x 666x 666x 36x 36x 36x 36x 36x 36x     101x         2x     2x   46x 2x 10x 46x       2x           3x 917x         3x                                       3x                             3x                                                                           3x     2x 10x                
import chroma from "chroma-js";
import { TILE_SIZE } from "consts";
import { IndexedImage } from "shared/lib/tiles/indexedImage";
import { rgbToClosestGBCHex } from "shared/lib/color/gbcColors";
 
type VariableLengthHexPalette = string[];
 
type SparseHexPalette = [
  string | undefined,
  string | undefined,
  string | undefined,
  string | undefined
];
 
type HexPalette = [string, string, string, string];
 
export type AutoPaletteResult = {
  map: number[];
  palettes: HexPalette[];
  indexedImage: IndexedImage;
};
 
/**
 * 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
): 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);
        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 } = compressPalettes(allPalettes);
 
  // 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: fillHexPalette(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
): 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
      );
      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);
 
  // 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: fillHexPalette(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
): 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 hex = rgbToClosestGBCHex(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
 */
const extractTilePaletteWithHint = (
  pixels: Buffer | Uint8ClampedArray,
  width: number,
  tileX: number,
  tileY: number,
  indexedImage: IndexedImage
): 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]}`;
      Iif (!seenColorLookup[key]) {
        seenColorLookup[key] = true;
        const hex = rgbToClosestGBCHex(pixels[i], pixels[i + 1], pixels[i + 2]);
        colors[index] = hex;
        seenCount++;
        Iif (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(
            rgbToClosestGBCHex(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
 */
const compressPalettes = (allPalettes: VariableLengthHexPalette[]) => {
  // Early exit if 8 or fewer palettes are provided
  Iif (allPalettes.length <= 8) {
    const mappingTable = allPalettes.map((_, index) => index);
    return { palettes: allPalettes, mappingTable };
  }
 
  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: 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
    Iif (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
 */
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++) {
      Iif (canMergeSparsePalette(palettes[i], palette)) {
        palettes[i] = mergeSparsePalette(palettes[i], palette);
        mappingTable[index] = i;
        merged = true;
        break;
      }
    }
    Iif (!merged) {
      palettes.push(palette);
      mappingTable[index] = palettes.length - 1;
    }
  });
 
  return { palettes, mappingTable };
};
 
/**
 * Given an array of hex palettes
 * fill them so each contains four values
 */
const fillHexPalette = (
  palettes: Array<VariableLengthHexPalette | SparseHexPalette>
): HexPalette[] => {
  return palettes.map((palette) => {
    return [
      palette[0] ?? "000000",
      palette[1] ?? "000000",
      palette[2] ?? "000000",
      palette[3] ?? "000000",
    ];
  });
};