All files / src/shared/lib/color gbcColors.ts

73.91% Statements 17/23
50% Branches 1/2
66.67% Functions 2/3
75% Lines 15/20

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 443x 3x 3x   3x         3x                     3x 1122x 1122x 1101x   21x 63x   21x         21x             21x 21x    
import Solver from "3x3-equation-solver";
import { hexDec } from "shared/lib/helpers/8bit";
import clamp from "shared/lib/helpers/clamp";
 
const rgbToGBCCache: Record<string, string> = {};
 
/**
 * Convert hex to closest GBC compatible hex
 */
export const GBCHexToClosestHex = (hex: string) => {
  Iif (hex.toLowerCase() === "ff0000") return hex; // otherwise comes back as 31,3,0
  const r = Math.floor(hexDec(hex.substring(0, 2)));
  const g = Math.floor(hexDec(hex.substring(2, 4)));
  const b = Math.floor(hexDec(hex.substring(4)));
  return rgbToClosestGBCHex(r, g, b);
};
 
/**
 * Convert rgb values to closest GBC compatible hex
 */
export const rgbToClosestGBCHex = (r: number, g: number, b: number): string => {
  const key = `${r}_${g}_${b}`;
  if (rgbToGBCCache[key]) {
    return rgbToGBCCache[key];
  }
  const clamp31 = (value: number) => {
    return clamp(value, 0, 31);
  };
  const [r2, g2, b2] = Solver([
    [13, 2, 1, r << 1],
    [0, 3, 1, g >> 1],
    [3, 2, 11, b << 1],
  ]);
  const hex = (
    (Math.round(255 * (clamp31(r2) / 31)) << 16) +
    (Math.round(255 * (clamp31(g2) / 31)) << 8) +
    Math.round(255 * (clamp31(b2) / 31))
  )
    .toString(16)
    .padStart(6, "0");
  rgbToGBCCache[key] = hex;
  return hex;
};