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

97.67% Statements 42/43
90% Branches 9/10
100% Functions 6/6
97.29% Lines 36/37

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        65x 1745430x 396476x   1348954x 169338x   1179616x 229332x   950284x     65x 56x   56x 20564x 20564x 2012x       56x     65x 1800x 5x 5x 5x 1800x 1800x   5x     65x       48x 48x 48x 48x 25175x 25175x 25175x     25175x 25175x   48x     65x   72069x    
import { ImageIndexFunction } from "./indexedImage";
 
export type TileLookup = Record<string, Uint8Array>;
 
export const tileDataIndexFn: ImageIndexFunction = (_r, g, _b, _a) => {
  if (g < 65) {
    return 3;
  }
  if (g < 130) {
    return 2;
  }
  if (g < 205) {
    return 1;
  }
  return 0;
};
 
export const toTileLookup = (tiles: Uint8Array[]): TileLookup => {
  const output: TileLookup = {};
 
  for (const tile of tiles) {
    const key = hashTileData(tile);
    if (!output[key]) {
      output[key] = tile;
    }
  }
 
  return output;
};
 
export const tileArrayToTileData = (tiles: Uint8Array[]): Uint8Array => {
  const size = tiles.reduce((memo, tile) => memo + tile.length, 0);
  const output = new Uint8Array(size);
  let index = 0;
  for (const tileData of tiles) {
    output.set(tileData, index);
    index += tileData.length;
  }
  return output;
};
 
export const tilesAndLookupToTilemap = (
  tiles: Uint8Array[],
  lookup: TileLookup,
): number[] => {
  const output = new Array(tiles.length).fill(0);
  const keys = Object.keys(lookup);
  let i = 0;
  for (const tileData of tiles) {
    const key = hashTileData(tileData);
    const value = keys.indexOf(key);
    Iif (value === -1) {
      throw new Error("Missing Tile" + key);
    }
    output[i] = value;
    i++;
  }
  return output;
};
 
export const hashTileData = (tile: Uint8Array): string => {
  // Will do for now...
  return JSON.stringify(tile);
};