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

78.57% Statements 33/42
80% Branches 4/5
66.67% Functions 4/6
78.38% Lines 29/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        30x 1175552x 179368x   996184x 122233x   873951x 161451x   712500x     30x 29x   29x 18358x 18358x 2116x       29x     30x                     30x       29x 29x 29x 29x 18296x 18296x 18296x     18296x 18296x   29x     30x   36654x    
import { ImageIndexFunction } from "./indexedImage";
 
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;
};
 
const hashTileData = (tile: Uint8Array): string => {
  // Will do for now...
  return JSON.stringify(tile);
};