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

98.39% Statements 306/311
92.54% Branches 236/255
100% Functions 34/34
98.17% Lines 269/274

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 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762            93x           93x   93x             25x               25x                     25x             93x           6x             6x     6x                                                                 93x       93x 24x   93x         20x     20x 20x 20x 20x     93x         4x     4x 4x 4x 4x 4x 4x                 93x                       93x               220x 72x 72x 72x           148x 148x 148x 148x 148x 148x 148x                   93x           42x 42x   42x   42x 1253x 1253x 1253x       1253x 1067x     186x   186x       186x                 42x             1062x 1062x   1062x           306x     756x           42x   42x 1253x   1253x 1067x     186x 186x   186x 186x 186x 186x   186x           318x       42x     93x             8x 8x 8x 228x 114x   114x 114x 114x     114x       114x                 114x 114x   8x             146x 146x 146x           4x   142x         8x   8x 86x 86x 52x 52x   34x 34x 34x 34x 34x 34x 34x               10x         8x     93x     164x 164x 164x 164x   164x 229x 229x 229x   229x                 229x   229x 228x     229x 2170938x     229x     164x             93x       2725x     93x       9854x 1798x     8056x 8056x   8056x 361x     7695x                 93x               6x 6x 6x       6x 6x 6x 9x         6x     93x         37x 37x 37x         118x   93x       11x 11x 11x 9x             93x                       17x 17x   17x 13x         13x 6x 6x     18x         20x           17x     93x     12x 12x 13x 12x       12x 12x 12x 12x       8x 6x         12x 12x   12x   10x 9x       12x 12x   12x 25x       25x 25x   25x 8x     8x     17x   17x 1x 1x     16x 16x         12x 13x   12x     12x 12x 12x   12x 12x   12x 24x 24x     24x       24x 13x 13x     11x 11x 11x   11x 6x     11x     12x 10x       12x   12x 24x 24x 12x       12x   12x 11x 21x   21x       6x 6x         12x 2x     10x 3x               7x 12x   12x 14x   14x 3x 3x     11x 11x   11x 1x 1x     10x   10x       12x     7x         4x           8x             93x         56x   56x 3x     53x 34x   34x 16x       37x     93x                 16x 16x 16x 4x 2x   2x     16x    
import {
  AutotileDefinition,
  AutotileType,
  SceneTilemapLayer,
  SceneTilemapData,
} from "shared/lib/resources/types";
import {
  clearGridSelection,
  moveGridSelection,
  type GridOffset,
  type GridSelection,
} from "./grid";
import { MAX_SCENE_TILE_COUNT } from "consts";
 
export const moveTilemapLayerSelection = (
  layer: SceneTilemapLayer,
  sceneWidth: number,
  sceneHeight: number,
  selection: GridSelection,
  offset: GridOffset,
): SceneTilemapLayer => {
  const tiles = moveGridSelection(
    layer.tiles,
    sceneWidth,
    sceneHeight,
    selection,
    offset,
    0,
  );
  const autotiles = layer.autotiles
    ? moveGridSelection(
        layer.autotiles,
        sceneWidth,
        sceneHeight,
        selection,
        offset,
        0,
      )
    : undefined;
 
  return {
    ...layer,
    tiles,
    ...(autotiles ? { autotiles } : {}),
  };
};
 
export const clearTilemapLayerSelection = (
  layer: SceneTilemapLayer,
  sceneWidth: number,
  sceneHeight: number,
  selection: GridSelection,
): SceneTilemapLayer => {
  const tiles = clearGridSelection(
    layer.tiles,
    sceneWidth,
    sceneHeight,
    selection,
    0,
  );
  const autotiles = layer.autotiles
    ? clearGridSelection(layer.autotiles, sceneWidth, sceneHeight, selection, 0)
    : undefined;
  return {
    ...layer,
    tiles,
    ...(autotiles ? { autotiles } : {}),
  };
};
 
export interface SceneTilesetIndexEntry {
  tilesetId: string;
  tilesetIndex: number;
  width: number;
  height: number;
  offset: number;
  count: number;
}
 
export interface DecodedSceneTileRef {
  absoluteIndex: number;
  tilesetIndex: number;
  tileIndex: number;
  tilesetId: string;
  tilesetOffset: number;
}
 
export interface SceneTilesetLookup {
  entries: SceneTilesetIndexEntry[];
  entryByTilesetId: Map<string, SceneTilesetIndexEntry>;
  entryByAbsoluteIndex: Array<SceneTilesetIndexEntry | undefined>;
}
 
// The 16 possible 2x2 autotile shapes. Bits run clockwise around the corners:
// NW, NE, SE, SW. Variants are stored in a 4x4 block in this stable order,
// starting at the tile selected in the palette.
export const AUTOTILE_VARIANT_MASKS: readonly number[] = [
  8, 6, 13, 12, 5, 14, 15, 11, 2, 3, 7, 9, 0, 4, 10, 1,
];
 
export const autotileGroupSize = (type: AutotileType): number =>
  type === "9slice" ? 3 : 4;
 
export const isAutotileDefinitionWithinBounds = (
  definition: AutotileDefinition,
  width: number,
  height: number,
): boolean => {
  Iif (width <= 0 || height <= 0) {
    return false;
  }
  const x = definition.startTile % width;
  const y = Math.floor(definition.startTile / width);
  const groupSize = autotileGroupSize(definition.type);
  return x + groupSize <= width && y + groupSize <= height;
};
 
export const isTileWithinAutotileDefinition = (
  tileIndex: number,
  tilesetWidth: number,
  definition: AutotileDefinition,
): boolean => {
  Iif (tilesetWidth <= 0) {
    return false;
  }
  const clickedX = tileIndex % tilesetWidth;
  const clickedY = Math.floor(tileIndex / tilesetWidth);
  const groupX = definition.startTile % tilesetWidth;
  const groupY = Math.floor(definition.startTile / tilesetWidth);
  const groupSize = autotileGroupSize(definition.type);
  return (
    clickedX >= groupX &&
    clickedX < groupX + groupSize &&
    clickedY >= groupY &&
    clickedY < groupY + groupSize
  );
};
 
// Inverse lookup: connectivity mask to tile offset within the variant block.
const AUTOTILE_MASK_TO_VARIANT: readonly number[] = [
  12, 15, 8, 9, 13, 4, 1, 10, 0, 11, 14, 7, 3, 2, 5, 6,
];
 
type ResolvedAutotileSource = {
  definitionId: number;
  type: AutotileType;
  tilesetOffset: number;
  tileIndex: number;
  tilesetWidth: number;
};
 
const resolveAutotileVariant = (
  source: ResolvedAutotileSource,
  north: boolean,
  east: boolean,
  south: boolean,
  west: boolean,
  connected: (offsetX: number, offsetY: number) => boolean,
): number => {
  if (source.type === "9slice") {
    const variantX = !west ? 0 : !east ? 2 : 1;
    const variantY = !north ? 0 : !south ? 2 : 1;
    return encodeSceneTileRef(
      source.tilesetOffset,
      source.tileIndex + variantX + variantY * source.tilesetWidth,
    );
  }
 
  let mask = 0;
  if (north && west && connected(-1, -1)) mask |= 1;
  if (north && east && connected(1, -1)) mask |= 2;
  if (south && east && connected(1, 1)) mask |= 4;
  if (south && west && connected(-1, 1)) mask |= 8;
  const variant = AUTOTILE_MASK_TO_VARIANT[mask] ?? -1;
  return variant >= 0
    ? encodeSceneTileRef(
        source.tilesetOffset,
        source.tileIndex +
          (variant % 4) +
          Math.floor(variant / 4) * source.tilesetWidth,
      )
    : 0;
};
 
export const resolveSceneAutotiles = (
  autotiles: readonly number[],
  width: number,
  height: number,
  tilemap: Pick<SceneTilemapData, "tilesets" | "autotiles">,
): number[] => {
  const size = width * height;
  const tilesetLookup = buildSceneTilesetLookup(tilemap);
 
  const autotileSources = new Array<ResolvedAutotileSource | undefined>(size);
 
  for (let index = 0; index < size; index++) {
    const definitionId = autotiles[index] ?? 0;
    const definition = tilemap.autotiles?.[definitionId - 1];
    const ref = definition
      ? decodeSceneTileRef(definition.startTile, tilesetLookup)
      : undefined;
 
    if (!ref || !definition) {
      continue;
    }
 
    const tilesetWidth = tilesetLookup.entries[ref.tilesetIndex]?.width;
 
    Iif (!tilesetWidth) {
      continue;
    }
 
    autotileSources[index] = {
      definitionId,
      type: definition.type,
      tilesetOffset: ref.tilesetOffset,
      tileIndex: ref.tileIndex,
      tilesetWidth,
    };
  }
 
  const connected = (
    source: ResolvedAutotileSource,
    x: number,
    y: number,
    offsetX: number,
    offsetY: number,
  ) => {
    const neighbourX = x + offsetX;
    const neighbourY = y + offsetY;
 
    if (
      neighbourX < 0 ||
      neighbourY < 0 ||
      neighbourX >= width ||
      neighbourY >= height
    ) {
      return true;
    }
 
    return (
      autotileSources[neighbourY * width + neighbourX]?.definitionId ===
      source.definitionId
    );
  };
 
  const resolved = new Array<number>(size).fill(0);
 
  for (let index = 0; index < size; index++) {
    const source = autotileSources[index];
 
    if (!source) {
      continue;
    }
 
    const x = index % width;
    const y = Math.floor(index / width);
 
    const north = connected(source, x, y, 0, -1);
    const east = connected(source, x, y, 1, 0);
    const south = connected(source, x, y, 0, 1);
    const west = connected(source, x, y, -1, 0);
 
    resolved[index] = resolveAutotileVariant(
      source,
      north,
      east,
      south,
      west,
      (offsetX, offsetY) => connected(source, x, y, offsetX, offsetY),
    );
  }
 
  return resolved;
};
 
export const resolveSceneAutotilesForCells = (
  autotiles: readonly number[],
  width: number,
  height: number,
  tilemap: Pick<SceneTilemapData, "tilesets" | "autotiles">,
  cellIndexes: Iterable<number>,
): Map<number, number> => {
  const tilesetLookup = buildSceneTilesetLookup(tilemap);
  const sourceCache = new Map<number, ResolvedAutotileSource | undefined>();
  const sourceAt = (index: number) => {
    if (sourceCache.has(index)) {
      return sourceCache.get(index);
    }
    const definitionId = autotiles[index] ?? 0;
    const definition = tilemap.autotiles?.[definitionId - 1];
    const ref = definition
      ? decodeSceneTileRef(definition.startTile, tilesetLookup)
      : undefined;
    const tilesetWidth = ref
      ? tilesetLookup.entries[ref.tilesetIndex]?.width
      : undefined;
    const source =
      ref && definition && tilesetWidth
        ? {
            definitionId,
            type: definition.type,
            tilesetOffset: ref.tilesetOffset,
            tileIndex: ref.tileIndex,
            tilesetWidth,
          }
        : undefined;
    sourceCache.set(index, source);
    return source;
  };
  const connected = (
    source: ResolvedAutotileSource,
    x: number,
    y: number,
    offsetX: number,
    offsetY: number,
  ) => {
    const neighbourX = x + offsetX;
    const neighbourY = y + offsetY;
    if (
      neighbourX < 0 ||
      neighbourY < 0 ||
      neighbourX >= width ||
      neighbourY >= height
    ) {
      return true;
    }
    return (
      sourceAt(neighbourY * width + neighbourX)?.definitionId ===
      source.definitionId
    );
  };
  const resolved = new Map<number, number>();
 
  for (const index of cellIndexes) {
    const source = sourceAt(index);
    if (!source) {
      resolved.set(index, 0);
      continue;
    }
    const x = index % width;
    const y = Math.floor(index / width);
    const north = connected(source, x, y, 0, -1);
    const east = connected(source, x, y, 1, 0);
    const south = connected(source, x, y, 0, 1);
    const west = connected(source, x, y, -1, 0);
    resolved.set(
      index,
      resolveAutotileVariant(
        source,
        north,
        east,
        south,
        west,
        (offsetX, offsetY) => connected(source, x, y, offsetX, offsetY),
      ),
    );
  }
 
  return resolved;
};
 
export const buildSceneTilesetLookup = (
  tilemap: Pick<SceneTilemapData, "tilesets">,
): SceneTilesetLookup => {
  let offset = 0;
  const entries: SceneTilesetIndexEntry[] = [];
  const entryByTilesetId = new Map<string, SceneTilesetIndexEntry>();
  const entryByAbsoluteIndex: Array<SceneTilesetIndexEntry | undefined> = [];
 
  for (const [tilesetIndex, tileset] of tilemap.tilesets.entries()) {
    const width = Math.max(0, Math.floor(tileset.width));
    const height = Math.max(0, Math.floor(tileset.height));
    const count = width * height;
 
    const entry = {
      tilesetId: tileset.id,
      tilesetIndex,
      width,
      height,
      offset,
      count,
    };
 
    entries.push(entry);
 
    if (!entryByTilesetId.has(entry.tilesetId)) {
      entryByTilesetId.set(entry.tilesetId, entry);
    }
 
    for (let i = 0; i < count; i++) {
      entryByAbsoluteIndex[offset + i] = entry;
    }
 
    offset += count;
  }
 
  return {
    entries,
    entryByTilesetId,
    entryByAbsoluteIndex,
  };
};
 
export const encodeSceneTileRef = (
  tilesetOffset: number,
  tileIndex = 0,
): number => {
  return tilesetOffset + tileIndex + 1;
};
 
export const decodeSceneTileRef = (
  value: number,
  lookup: SceneTilesetLookup,
): DecodedSceneTileRef | undefined => {
  if (!value) {
    return undefined;
  }
 
  const absoluteIndex = value - 1;
  const entry = lookup.entryByAbsoluteIndex[absoluteIndex];
 
  if (!entry) {
    return undefined;
  }
 
  return {
    absoluteIndex,
    tilesetIndex: entry.tilesetIndex,
    tileIndex: absoluteIndex - entry.offset,
    tilesetId: entry.tilesetId,
    tilesetOffset: entry.offset,
  };
};
 
export const sceneStampLinePositions = (
  startX: number,
  startY: number,
  endX: number,
  endY: number,
  stampWidth: number,
  stampHeight: number,
): Array<{ x: number; y: number }> => {
  const dx = endX - startX;
  const dy = endY - startY;
  const distance = Math.max(
    Math.abs(dx) / Math.max(1, stampWidth),
    Math.abs(dy) / Math.max(1, stampHeight),
  );
  const steps = Math.floor(distance);
  const positions: Array<{ x: number; y: number }> = [];
  for (let step = 1; step <= steps; step++) {
    positions.push({
      x: startX + Math.round((dx * step) / distance),
      y: startY + Math.round((dy * step) / distance),
    });
  }
  return positions;
};
 
export const getTilemapLayersTileColors = (
  tilemap: SceneTilemapData,
  width: number,
  height: number,
): number[] => {
  const size = width * height;
  const tileColors = tilemap.tileColors ?? [];
  return tileColors
    .slice(0, size)
    .concat(new Array(Math.max(0, size - tileColors.length)).fill(0));
};
 
export { flattenTilemapLayers } from "shared/lib/tiles/sceneTilemapReferences";
 
export const isSceneAutotileDefinitionValid = (
  definition: AutotileDefinition,
  tilesetLookup: SceneTilesetLookup,
): boolean => {
  const ref = decodeSceneTileRef(definition.startTile, tilesetLookup);
  const entry = ref ? tilesetLookup.entries[ref.tilesetIndex] : undefined;
  if (!ref || !entry || entry.width <= 0) return false;
  return isAutotileDefinitionWithinBounds(
    { ...definition, startTile: ref.tileIndex },
    entry.width,
    entry.height,
  );
};
 
export const remapSceneAutotileDefinitions = (
  definitions: readonly AutotileDefinition[] | undefined,
  layers: readonly SceneTilemapLayer[],
  remapStartTile: (
    value: number,
    definition: AutotileDefinition,
    definitionId: number,
  ) => number,
): {
  autotiles: AutotileDefinition[];
  layers: SceneTilemapLayer[];
} => {
  const idMap = new Map<number, number>();
  const autotiles: AutotileDefinition[] = [];
 
  for (const [index, definition] of (definitions ?? []).entries()) {
    const startTile = remapStartTile(
      definition.startTile,
      definition,
      index + 1,
    );
    if (!startTile) continue;
    idMap.set(index + 1, autotiles.length + 1);
    autotiles.push({ ...definition, startTile });
  }
 
  const nextLayers = layers.map((layer) => ({
    ...layer,
    ...(layer.autotiles
      ? {
          autotiles: layer.autotiles.map((id) =>
            id ? (idMap.get(id) ?? 0) : 0,
          ),
        }
      : {}),
  }));
 
  return { autotiles, layers: nextLayers };
};
 
export const pruneTilemapLayersTilesets = (
  tilemap: SceneTilemapData,
): SceneTilemapData => {
  const usedAutotileIds = new Set<number>();
  for (const layer of tilemap.layers) {
    for (const definitionId of layer.autotiles ?? []) {
      if (definitionId > 0) usedAutotileIds.add(definitionId);
    }
  }
 
  const usedTilesetIds = new Set<string>();
  const tilesetLookup = buildSceneTilesetLookup(tilemap);
  const { entries, entryByAbsoluteIndex } = tilesetLookup;
  const remappedAutotiles = remapSceneAutotileDefinitions(
    tilemap.autotiles,
    tilemap.layers,
    (startTile, definition, definitionId) => {
      if (!usedAutotileIds.has(definitionId)) return 0;
      return isSceneAutotileDefinitionValid(definition, tilesetLookup)
        ? startTile
        : 0;
    },
  );
  const autotileDefinitions = remappedAutotiles.autotiles;
  const layersWithPrunedAutotiles = remappedAutotiles.layers;
  const autotilesChanged =
    autotileDefinitions.length !== (tilemap.autotiles?.length ?? 0) ||
    layersWithPrunedAutotiles.some((layer, index) =>
      layer.autotiles?.some(
        (id, cellIndex) => id !== tilemap.layers[index]?.autotiles?.[cellIndex],
      ),
    );
 
  const usedTilesetIndexes = new Array<boolean>(entries.length).fill(false);
  let invalidRefSeen = false;
 
  const scanRefs = (values: readonly number[] | undefined) => {
    Iif (!values) {
      return;
    }
 
    for (let i = 0; i < values.length; i++) {
      const value = values[i];
 
      if (!value) {
        Iif (value !== 0) {
          invalidRefSeen = true;
        }
        continue;
      }
 
      const entry = entryByAbsoluteIndex[value - 1];
 
      if (!entry) {
        invalidRefSeen = true;
        continue;
      }
 
      usedTilesetIds.add(entry.tilesetId);
      usedTilesetIndexes[entry.tilesetIndex] = true;
    }
  };
 
  // Find tilesets that are still being referenced.
  for (const layer of layersWithPrunedAutotiles) {
    scanRefs(layer.tiles);
  }
  scanRefs(autotileDefinitions.map((definition) => definition.startTile));
 
  // Keep only tilesets that are still referenced
  const seenTilesetIds = new Set<string>();
  const tilesets: SceneTilemapData["tilesets"] = [];
  const newOffsetByTilesetId = new Map<string, number>();
 
  let nextOffset = 0;
  let tilesetsChanged = false;
 
  for (let index = 0; index < tilemap.tilesets.length; index++) {
    const tileset = tilemap.tilesets[index];
    const entry = entries[index];
 
    const keep =
      !!entry &&
      usedTilesetIds.has(tileset.id) &&
      !seenTilesetIds.has(tileset.id);
 
    if (!keep) {
      tilesetsChanged = true;
      continue;
    }
 
    seenTilesetIds.add(tileset.id);
    newOffsetByTilesetId.set(tileset.id, nextOffset);
    tilesets.push(tileset);
 
    if (tilesets.length - 1 !== index) {
      tilesetsChanged = true;
    }
 
    nextOffset += entry.count;
  }
 
  if (tilesets.length !== tilemap.tilesets.length) {
    tilesetsChanged = true;
  }
 
  // Map every original tileset index to the new offset for its tileset id
  const newOffsetByTilesetIndex = new Array<number>(entries.length).fill(-1);
 
  for (const entry of entries) {
    const newOffset = newOffsetByTilesetId.get(entry.tilesetId);
    if (newOffset !== undefined) {
      newOffsetByTilesetIndex[entry.tilesetIndex] = newOffset;
    }
  }
 
  let remapRequired = invalidRefSeen;
 
  if (!remapRequired) {
    for (let index = 0; index < entries.length; index++) {
      const entry = entries[index];
 
      if (
        usedTilesetIndexes[index] &&
        newOffsetByTilesetIndex[index] !== entry.offset
      ) {
        remapRequired = true;
        break;
      }
    }
  }
 
  if (!tilesetsChanged && !remapRequired && !autotilesChanged) {
    return tilemap;
  }
 
  if (!remapRequired) {
    return {
      ...tilemap,
      tilesets,
      ...(tilemap.autotiles ? { autotiles: autotileDefinitions } : {}),
      layers: layersWithPrunedAutotiles,
    };
  }
 
  const remapRefs = (values: readonly number[]): number[] => {
    const result = new Array<number>(values.length);
 
    for (let i = 0; i < values.length; i++) {
      const value = values[i];
 
      if (!value) {
        result[i] = 0;
        continue;
      }
 
      const absoluteIndex = value - 1;
      const entry = entryByAbsoluteIndex[absoluteIndex];
 
      if (!entry) {
        result[i] = 0;
        continue;
      }
 
      const newOffset = newOffsetByTilesetIndex[entry.tilesetIndex];
 
      result[i] =
        newOffset >= 0 ? newOffset + (absoluteIndex - entry.offset) + 1 : 0;
    }
 
    return result;
  };
 
  return {
    ...tilemap,
    tilesets,
    ...(tilemap.autotiles
      ? {
          autotiles: autotileDefinitions.map((definition) => ({
            ...definition,
            startTile: remapRefs([definition.startTile])[0] ?? 0,
          })),
        }
      : {}),
    layers: layersWithPrunedAutotiles.map((layer) => ({
      ...layer,
      tiles: remapRefs(layer.tiles),
    })),
  };
};
 
export const isTilemapLayerCellTopmost = (
  tilemap: SceneTilemapData,
  layerIndex: number,
  cellIndex: number,
): boolean => {
  const layer = tilemap.layers[layerIndex];
 
  if (!layer?.visible || !layer.tiles[cellIndex]) {
    return false;
  }
 
  for (let index = layerIndex + 1; index < tilemap.layers.length; index++) {
    const aboveLayer = tilemap.layers[index];
 
    if (aboveLayer?.visible && aboveLayer.tiles[cellIndex]) {
      return false;
    }
  }
 
  return true;
};
 
export const normalizeTilemapLayersSize = ({
  width: requestedWidth,
  height: requestedHeight,
  resizeAxis,
}: {
  width: number;
  height: number;
  resizeAxis: "width" | "height";
}) => {
  let width = Math.min(255, Math.max(20, Math.floor(requestedWidth)));
  let height = Math.min(255, Math.max(18, Math.floor(requestedHeight)));
  if (width * height > MAX_SCENE_TILE_COUNT) {
    if (resizeAxis === "width") {
      width = Math.max(20, Math.floor(MAX_SCENE_TILE_COUNT / height));
    } else {
      height = Math.max(18, Math.floor(MAX_SCENE_TILE_COUNT / width));
    }
  }
  return { width, height };
};