All files / src/lib/compiler compileSprites.ts

30.77% Statements 36/117
8.57% Branches 3/35
7.41% Functions 2/27
29.09% Lines 32/110

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 3362x 2x 2x                 2x 2x   2x 2x 2x 2x 2x 2x                                                                     2x                               2x                                     2x             2x                                   2x                                                                                                                                                                                                                                                                                                 2x                 1x           1x           1x         1x             1x     1x 1x   1x         1x 1x 1x     1x     1x     2x                                       2x  
import promiseLimit from "lib/helpers/promiseLimit";
import { indexedImageTo2bppSpriteData } from "shared/lib/sprites/spriteData";
import {
  animationMapBySpriteType,
  toEngineOrder,
} from "shared/lib/sprites/helpers";
import type {
  ObjPalette,
  SpriteSheetData,
} from "shared/lib/entities/entitiesTypes";
import { IndexedImage } from "shared/lib/tiles/indexedImage";
import { assetFilename } from "shared/lib/helpers/assets";
import { optimiseTiles } from "lib/sprites/readSpriteData";
 
const S_PALETTE = 0x10;
const S_FLIPX = 0x20;
const S_FLIPY = 0x40;
const S_PRIORITY = 0x80;
const S_GBC_PALETTE_MASK = 0x7;
const S_VRAM2 = 0x8;
 
export type SpriteTileAllocationStrategy = (
  tileIndex: number,
  numTiles: number,
  sprite: SpriteSheetData
) => { tileIndex: number; inVRAM2: boolean };
 
interface AnimationOffset {
  start: number;
  end: number;
}
 
export type PrecompiledSpriteSheetData = SpriteSheetData & {
  vramData: [number[], number[]];
  tiles: IndexedImage[];
  metasprites: SpriteTileData[][];
  animationOffsets: AnimationOffset[];
  metaspritesOrder: number[];
};
 
interface SpriteTileData {
  tile: number;
  x: number;
  y: number;
  props: number;
}
 
/**
 * Allocates a sprite tile for to default DMG location.
 *
 * @param {number} tileIndex - The index of the sprite tile to allocate.
 * @param {number} numTiles - The total number of tiles available for allocation.
 * @returns {{ tileIndex: number, inVRAM2: boolean }} Updated tile index and flag which is set if tile has been reallocated to VRAM bank2.
 */
export const spriteTileAllocationDefault: SpriteTileAllocationStrategy = (
  tileIndex
) => {
  return {
    tileIndex,
    inVRAM2: false,
  };
};
 
/**
 * Allocates a sprite tile for color-only sprites and adjusts the tile index based on VRAM bank allocation.
 *
 * @param {number} tileIndex - The index of the sprite tile to allocate.
 * @param {number} numTiles - The total number of tiles available for allocation.
 * @returns {{ tileIndex: number, inVRAM2: boolean }} Updated tile index and flag which is set if tile has been reallocated to VRAM bank2.
 */
export const spriteTileAllocationColorOnly: SpriteTileAllocationStrategy = (
  tileIndex,
  numTiles
) => {
  const bank1NumTiles = Math.ceil(numTiles / 4) * 2;
  const inVRAM2 = tileIndex >= bank1NumTiles;
  return {
    tileIndex: inVRAM2 ? tileIndex - bank1NumTiles : tileIndex,
    inVRAM2: tileIndex >= bank1NumTiles,
  };
};
 
/**
 * Dummy sprite tile allocation strategy for testing purposes only allocates all sprite tiles to VRAM bank 2.
 *
 * @param {number} tileIndex - The index of the sprite tile to allocate.
 * @param {number} numTiles - The total number of tiles available for allocation.
 * @returns {{ tileIndex: number, inVRAM2: boolean }} Updated tile index and flag which is set if tile has been reallocated to VRAM bank2.
 */
export const spriteTileAllocationVRAM2Only = (tileIndex: number) => {
  return {
    tileIndex,
    inVRAM2: true,
  };
};
 
const makeProps = (
  objPalette: ObjPalette,
  paletteIndex: number,
  flipX: boolean,
  flipY: boolean,
  priority: boolean,
  inVRAM2: boolean
): number => {
  return (
    (objPalette === "OBP1" ? S_PALETTE : 0) +
    (flipX ? S_FLIPX : 0) +
    (flipY ? S_FLIPY : 0) +
    (priority ? S_PRIORITY : 0) +
    (paletteIndex & S_GBC_PALETTE_MASK) +
    (inVRAM2 ? S_VRAM2 : 0)
  );
};
 
export const compileSprite = async (
  spriteSheet: SpriteSheetData,
  cgbOnly: boolean,
  projectRoot: string
): Promise<PrecompiledSpriteSheetData> => {
  const filename = assetFilename(projectRoot, "sprites", spriteSheet);
 
  const tileAllocationStrategy = cgbOnly
    ? spriteTileAllocationColorOnly
    : spriteTileAllocationDefault;
 
  const metasprites = spriteSheet.states
    .map((state) => state.animations)
    .flat()
    .map((animation) => {
      return animation.frames.map((frame) => frame.tiles);
    })
    .flat();
 
  const { tiles, lookup } = await optimiseTiles(
    filename,
    spriteSheet.canvasWidth,
    spriteSheet.canvasHeight,
    metasprites
  );
 
  const animationDefs: SpriteTileData[][][] = spriteSheet.states
    .map((state) =>
      toEngineOrder(
        animationMapBySpriteType(
          state.animations,
          state.animationType,
          state.flipLeft,
          (animation, flip) => {
            Iif (!animation) {
              return [];
            }
            return animation.frames.map((frame) => {
              let currentX = 0;
              let currentY = 0;
              return [...frame.tiles]
                .reverse()
                .map((tile) => {
                  const optimisedTile = lookup[tile.id];
                  Iif (!optimisedTile) {
                    return null;
                  }
                  const { tileIndex, inVRAM2 } = tileAllocationStrategy(
                    optimisedTile.tile,
                    tiles.length,
                    spriteSheet
                  );
                  Iif (flip) {
                    const data: SpriteTileData = {
                      tile: tileIndex,
                      x: 8 - tile.x - currentX,
                      y: -tile.y - currentY,
                      props: makeProps(
                        tile.objPalette,
                        tile.paletteIndex,
                        !optimisedTile.flipX,
                        optimisedTile.flipY,
                        tile.priority,
                        inVRAM2
                      ),
                    };
                    currentX = 8 - tile.x;
                    currentY = -tile.y;
                    return data;
                  }
                  const data: SpriteTileData = {
                    tile: tileIndex,
                    x: tile.x - currentX,
                    y: -tile.y - currentY,
                    props: makeProps(
                      tile.objPalette,
                      tile.paletteIndex,
                      optimisedTile.flipX,
                      optimisedTile.flipY,
                      tile.priority,
                      inVRAM2
                    ),
                  };
                  currentX = tile.x;
                  currentY = -tile.y;
                  return data;
                })
                .filter((tile) => tile) as SpriteTileData[];
            });
          }
        )
      )
    )
    .flat();
 
  // const uniqFrames: SpriteTileData[][] = [];
  const uniqFramesLookup: Record<string, number> = {};
  const uniqFrames: SpriteTileData[][] = [];
  const uniqMap = animationDefs.map((animationDef) => {
    return animationDef.map((frame) => {
      const key = JSON.stringify(frame); // Any hash function can work here
      Iif (uniqFramesLookup[key] === undefined) {
        uniqFramesLookup[key] = uniqFrames.length;
        uniqFrames.push(frame);
      }
      return uniqFramesLookup[key];
    });
  });
 
  const orderedFrames: number[] = [];
  const animationOffsets = uniqMap.map((uniqIndexes) => {
    let start = 0;
    const matchIndex = firstIndexOfMatch(orderedFrames, uniqIndexes);
    if (matchIndex > -1) {
      start = matchIndex;
    } else {
      start = orderedFrames.length;
      orderedFrames.push(...uniqIndexes);
    }
    return {
      start,
      end: start + Math.max(0, uniqIndexes.length - 1),
    };
  });
 
  const vramData: [number[], number[]] = [[], []];
 
  // Split tiles into VRAM banks based on allocation strategy
  tiles.map(indexedImageTo2bppSpriteData).forEach((tile, i) => {
    const { inVRAM2 } = tileAllocationStrategy(i, tiles.length, spriteSheet);
    vramData[inVRAM2 ? 1 : 0].push(...tile);
  });
 
  const precompiled: PrecompiledSpriteSheetData = {
    ...spriteSheet,
    vramData,
    tiles,
    metasprites: uniqFrames,
    animationOffsets,
    metaspritesOrder: orderedFrames,
  };
 
  return precompiled;
};
 
const compileSprites = async (
  spriteSheets: SpriteSheetData[],
  cgbOnly: boolean,
  projectRoot: string
): Promise<{
  spritesData: PrecompiledSpriteSheetData[];
  statesOrder: string[];
  stateReferences: string[];
}> => {
  const spritesData = await promiseLimit(
    10,
    spriteSheets.map(
      (spriteSheet) => () => compileSprite(spriteSheet, cgbOnly, projectRoot)
    )
  );
  const stateNames = spritesData
    .map((sprite) => sprite.states)
    .flat()
    .map((state) => state.name)
    .filter((name) => name.length > 0);
 
  const stateCounts = stateNames.reduce((memo, name) => {
    name in memo ? (memo[name] += 1) : (memo[name] = 1);
    return memo;
  }, {} as Record<string, number>);
 
  const statesOrder = Object.keys(stateCounts).sort((a, b) => {
    Iif (stateCounts[a] === stateCounts[b]) {
      return 0;
    }
    return stateCounts[a] < stateCounts[b] ? 1 : -1;
  });
 
  statesOrder.unshift("");
 
  // Build reference names for states
  const stateReferences: string[] = [];
  statesOrder.forEach((name) => {
    const refName =
      (name || "Default")
        .replace(/ /g, "_")
        .replace(/[^a-zA-Z0-9_]/g, "")
        .toUpperCase() || "S";
 
    let insertName = `STATE_${refName}`;
    let insNum = 1;
    while (stateReferences.includes(insertName)) {
      insertName = `STATE_${refName}_${insNum++}`;
    }
    stateReferences.push(insertName);
  });
 
  return { spritesData, statesOrder, stateReferences };
};
 
const firstIndexOfMatch = <T>(arr: T[], pattern: T[]): number => {
  for (
    let i = 0;
    i < arr.length && i < arr.length - (pattern.length - 1);
    i++
  ) {
    let found = true;
    for (let j = 0; j < pattern.length; j++) {
      Iif (arr[i + j] !== pattern[j]) {
        found = false;
        break;
      }
    }
    Iif (found) {
      return i;
    }
  }
  return -1;
};
 
export default compileSprites;