All files / src/lib/fonts fontData.ts

95.12% Statements 78/82
83.33% Branches 15/18
100% Functions 9/9
94.52% Lines 69/73

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 15922x 22x 22x             22x                                     22x 22x 22x 22x 22x 22x     22x 22x   22x     19x 19x 19x 19x 19x 19x 19x   19x 19x 19x 19x 14x         14x         19x 247808x             19x 242x 3872x             3872x   3872x 285x     3872x               19x 19x 19x 3872x 3872x 3536x   3872x   19x 19x     19x   3872x 3536x 19x   19x                     22x 247808x 7008x   240800x 49306x   191494x     191494x     191494x     22x 19x 3536x 3536x 19x 19x 19x 3536x 3536x   19x     22x   3872x    
import Path from "path";
import { readJson } from "fs-extra";
import {
  ImageIndexFunction,
  IndexedImage,
  indexedImageTo2bppTileData,
  sliceIndexedImage,
  trimIndexedImageHorizontal,
} from "shared/lib/tiles/indexedImage";
import { readFileToIndexedImage } from "lib/tiles/readFileToTiles";
 
export interface CompiledFontData {
  name: string;
  table: number[];
  widths: number[];
  data: Uint8Array;
  isVariableWidth: boolean;
  is1Bit: boolean;
  mapping: Record<string, number>;
}
 
interface CharacterData {
  width: number;
  data: IndexedImage;
}
 
type CharLookup = Record<string, CharacterData>;
 
enum Color {
  White = 0,
  Light = 1,
  Mid = 2,
  Dark = 3,
  Transparent = 255,
}
 
const TILE_SIZE = 8;
const FIRST_CHAR = 32;
 
export const readFileToFontData = async (
  filename: string
): Promise<CompiledFontData> => {
  const name = Path.basename(filename);
  const image = await readFileToIndexedImage(filename, fontDataIndexFn);
  const tileWidth = Math.floor(image.width / TILE_SIZE);
  const tileHeight = Math.floor(image.height / TILE_SIZE);
  const chars: CharacterData[] = [];
  let is1Bit = true;
  let isVariableWidth = false;
 
  const metadataFilename = filename.replace(/\.png$/i, ".json");
  let mapping: Record<string, number> = {};
  try {
    const metadataFile = await readJson(metadataFilename);
    if (
      typeof metadataFile === "object" &&
      metadataFile.mapping &&
      typeof metadataFile.mapping === "object"
    ) {
      mapping = metadataFile.mapping;
    }
  } catch (e) {}
 
  // Determine if font is only using white & black pixels
  for (let i = 0; i < image.data.length; i++) {
    Iif (image.data[i] === Color.Light || image.data[i] === Color.Mid) {
      is1Bit = false;
      break;
    }
  }
 
  // Build tile list
  for (let ty = 0; ty < tileHeight; ty++) {
    for (let tx = 0; tx < tileWidth; tx++) {
      const tile = sliceIndexedImage(
        image,
        tx * TILE_SIZE,
        ty * TILE_SIZE,
        TILE_SIZE,
        TILE_SIZE
      );
      const trimmedTile = trimIndexedImageHorizontal(tile, Color.Transparent);
 
      if (trimmedTile.data.width < TILE_SIZE) {
        isVariableWidth = true;
      }
 
      chars.push({
        width: trimmedTile.data.width,
        data: sliceIndexedImage(trimmedTile.data, 0, 0, TILE_SIZE, TILE_SIZE),
      });
    }
  }
 
  // Build unique tiles list
  const uniqueTilesLookup: CharLookup = {};
  const charKeys: string[] = [];
  for (const char of chars) {
    const key = hashChar(char.data, char.width);
    if (!uniqueTilesLookup[key]) {
      uniqueTilesLookup[key] = char;
    }
    charKeys.push(key);
  }
  const uniqueTileKeys = Object.keys(uniqueTilesLookup);
  const uniqueTiles = Object.values(uniqueTilesLookup);
 
  // Construct output data
  const table = (Array.from(Array(FIRST_CHAR)) as number[])
    .fill(0)
    .concat(charKeys.map((key) => uniqueTileKeys.indexOf(key)));
  const widths = uniqueTiles.map((tile) => tile.width);
  const data = charLookupToTileData(uniqueTilesLookup);
 
  return {
    name,
    table,
    widths,
    data,
    isVariableWidth,
    is1Bit,
    mapping,
  };
};
 
export const fontDataIndexFn: ImageIndexFunction = (r, g, b, _a) => {
  if (g > 249 || (r > 249 && b > 249)) {
    return Color.Transparent;
  }
  if (g < 65) {
    return Color.Dark;
  }
  Iif (g < 130) {
    return Color.Mid;
  }
  Iif (g < 205) {
    return Color.Light;
  }
  return Color.White;
};
 
export const charLookupToTileData = (lookup: CharLookup): Uint8Array => {
  const chars = Object.values(lookup);
  const charsData = chars.map((char) => indexedImageTo2bppTileData(char.data));
  const size = charsData.reduce((memo, char) => memo + char.length, 0);
  const output = new Uint8Array(size);
  let index = 0;
  for (const charData of charsData) {
    output.set(charData, index);
    index += charData.length;
  }
  return output;
};
 
const hashChar = (char: IndexedImage, width: number): string => {
  // Will do for now...
  return `${width}_${JSON.stringify(char.data)}`;
};