@flare-engine/tilemap 0.4.11 → 0.4.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.d.mts +9 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +45 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +45 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @flare-engine/tilemap
|
|
2
2
|
|
|
3
|
-
Tiled `.tmj` and LDtk parsing + culled rendering + collider extraction. `parseTiled` / `parseLDtk` return a normalized `TilemapData`; `TilemapRenderer` owns its own `SpriteBatch` and only queues tiles inside the camera bounds; `drawInto(camera, batch, opts?)` queues into a caller-owned batch for single-flush z-ordering with sprites, honouring each layer's `opacity` and taking an optional shared `effect` / `alphaScale`; `extractColliders` produces collision shapes for `@flare-engine/physics
|
|
3
|
+
Tiled `.tmj` and LDtk parsing + culled rendering + collider extraction. `parseTiled` / `parseLDtk` return a normalized `TilemapData`; `TilemapRenderer` owns its own `SpriteBatch` and only queues tiles inside the camera bounds; `drawInto(camera, batch, opts?)` queues into a caller-owned batch for single-flush z-ordering with sprites, honouring each layer's `opacity` and taking an optional shared `effect` / `alphaScale`; `extractColliders` produces collision shapes for `@flare-engine/physics`; `getTileAt` / `setTileAt` read and write one cell of a tile layer, bounds-checked.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
package/dist/index.d.mts
CHANGED
|
@@ -142,6 +142,13 @@ interface TilemapData {
|
|
|
142
142
|
export declare function createTilemapData(width: number, height: number, tileWidth: number, tileHeight: number): TilemapData;
|
|
143
143
|
/** Get a tile GID at a grid position from a tile layer. Returns 0 if out of bounds. */
|
|
144
144
|
export declare function getTileAt(layer: TileLayer, col: number, row: number): number;
|
|
145
|
+
/**
|
|
146
|
+
* Write a tile GID at a grid position in a tile layer; `getTileAt` and the
|
|
147
|
+
* renderer read it back. Returns `true` when the cell was written, `false` (and
|
|
148
|
+
* writes nothing) when the position is out of bounds or not an integer.
|
|
149
|
+
* The GID is stored raw, Tiled flip bits included. Zero-alloc.
|
|
150
|
+
*/
|
|
151
|
+
export declare function setTileAt(layer: TileLayer, col: number, row: number, gid: number): boolean;
|
|
145
152
|
/** Get the tileset that owns a given GID. Handles Tiled flip bits in the high bits. */
|
|
146
153
|
export declare function getTilesetForGid(tilesets: TilesetRef[], gid: number): TilesetRef | undefined;
|
|
147
154
|
/** Compute the source rect in a tileset image for a given GID into `out`. Strips Tiled flip bits. Zero-alloc. */
|
|
@@ -236,6 +243,8 @@ export declare class TilemapRenderer {
|
|
|
236
243
|
readonly batch: SpriteBatch;
|
|
237
244
|
/** Map from tileset name → SkImage. Set via setTilesetImage(). */
|
|
238
245
|
private _images;
|
|
246
|
+
/** Images in `map.tilesets` order, refreshed from `_images` at the start of each draw. */
|
|
247
|
+
private _tilesetImages;
|
|
239
248
|
/** Reusable bounds rect — avoids per-frame allocation from camera.getBounds(). */
|
|
240
249
|
private _boundsBuf;
|
|
241
250
|
/** Reusable source rect — avoids a per-tile allocation from getTileSourceRect. */
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/tilemap-data.ts","../src/ldtk-parser.ts","../src/parse-error.ts","../src/tiled-parser.ts","../src/tilemap-collider.ts","../src/tilemap-renderer.ts"],"mappings":";;;;;qBAGa;;UAOI;EACf;EACA;EACA;;;wBAIc,cAAc;;;;;;wBASd,eAAe,cAAc;;UAS5B;WACN;;EAET;;EAEA;;EAEA;;;;;;;;;;WAUS,OAAO;;EAEhB;;EAEA;;EAEA;EACA;;EAEA,YAAY;;;UAIG;;EAEf;;EAEA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;;EAEA,YAAY;;;UAIG;WACN;;EAET;;EAEA,SAAS;;EAET;;EAEA;;EAEA,YAAY;;;KAIF,WAAW,YAAY;;;;;UAMlB;;EAEf,QAAQ;;EAER,MAAM;;EAEN;;;UAIe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,gBAAgB,YAAY;;EAE5B,YAAY;;EAEZ,aAAa,YAAY;;;UAIV;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,QAAQ;;EAER,UAAU;;EAEV,YAAY;;;wBAIE,kBACd,eACA,gBACA,mBACA,qBACC;;wBAaa,UAAU,OAAO,WAAW,aAAa;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/tilemap-data.ts","../src/ldtk-parser.ts","../src/parse-error.ts","../src/tiled-parser.ts","../src/tilemap-collider.ts","../src/tilemap-renderer.ts"],"mappings":";;;;;qBAGa;;UAOI;EACf;EACA;EACA;;;wBAIc,cAAc;;;;;;wBASd,eAAe,cAAc;;UAS5B;WACN;;EAET;;EAEA;;EAEA;;;;;;;;;;WAUS,OAAO;;EAEhB;;EAEA;;EAEA;EACA;;EAEA,YAAY;;;UAIG;;EAEf;;EAEA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;;EAEA,YAAY;;;UAIG;WACN;;EAET;;EAEA,SAAS;;EAET;;EAEA;;EAEA,YAAY;;;KAIF,WAAW,YAAY;;;;;UAMlB;;EAEf,QAAQ;;EAER,MAAM;;EAEN;;;UAIe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,gBAAgB,YAAY;;EAE5B,YAAY;;EAEZ,aAAa,YAAY;;;UAIV;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,QAAQ;;EAER,UAAU;;EAEV,YAAY;;;wBAIE,kBACd,eACA,gBACA,mBACA,qBACC;;wBAaa,UAAU,OAAO,WAAW,aAAa;;;;;;;wBAczC,UAAU,OAAO,WAAW,aAAa,aAAa;;wBAUtD,iBAAiB,UAAU,cAAc,cAAc;;wBAevD,sBAAsB,SAAS,YAAY,aAAa,KAAK,OAAO;;wBAYpE,kBAAkB,SAAS,YAAY,cAAc;UCrJpD;;EAEf,gBAAgB;;UAGD;;EAEf;;EAEA;EACA;;EAEA;EACA;;EAEA,QAAQ;;;;;;wBAOM,kBAAkB,KAAK,cAAc;;;;;;wBAuBrC,UAAU,eAAe,UAAS,mBAAwB;;qBC9H7D,0BAA0B;EACzB,YAAA;;;;;;;;wBCqJE,WAAW,gBAAgB;;UCjJ1B;;EAEf;EACA;;EAEA,OAAO;;EAEP;;EAEA;;EAEA;;;;;;;;;;wBAWc,iBAAiB,KAAK,aAAa,qBAAqB;;;;;;;;;;;;UCCvD;EACf,SAAS;EACT;EACA;;;;;;qBAoBW;;WAEF,KAAK;;WAGL,OAAO;;UAGR;;UAGA;;UAGA;;UAGA;EAEI,YAAA,KAAK;;EAMjB,gBAAgB,qBAAqB,OAAO;;;;;;;;;;EAa5C,SAAS,QAAQ,UAAU,OAAO,aAAa,OAAO;;;;;;;EAyCtD,KAAK,QAAQ,UAAU,QAAQ,OAAO,sBAAsB,OAAO;UAQ3D"}
|
package/dist/index.d.ts
CHANGED
|
@@ -142,6 +142,13 @@ interface TilemapData {
|
|
|
142
142
|
export declare function createTilemapData(width: number, height: number, tileWidth: number, tileHeight: number): TilemapData;
|
|
143
143
|
/** Get a tile GID at a grid position from a tile layer. Returns 0 if out of bounds. */
|
|
144
144
|
export declare function getTileAt(layer: TileLayer, col: number, row: number): number;
|
|
145
|
+
/**
|
|
146
|
+
* Write a tile GID at a grid position in a tile layer; `getTileAt` and the
|
|
147
|
+
* renderer read it back. Returns `true` when the cell was written, `false` (and
|
|
148
|
+
* writes nothing) when the position is out of bounds or not an integer.
|
|
149
|
+
* The GID is stored raw, Tiled flip bits included. Zero-alloc.
|
|
150
|
+
*/
|
|
151
|
+
export declare function setTileAt(layer: TileLayer, col: number, row: number, gid: number): boolean;
|
|
145
152
|
/** Get the tileset that owns a given GID. Handles Tiled flip bits in the high bits. */
|
|
146
153
|
export declare function getTilesetForGid(tilesets: TilesetRef[], gid: number): TilesetRef | undefined;
|
|
147
154
|
/** Compute the source rect in a tileset image for a given GID into `out`. Strips Tiled flip bits. Zero-alloc. */
|
|
@@ -236,6 +243,8 @@ export declare class TilemapRenderer {
|
|
|
236
243
|
readonly batch: SpriteBatch;
|
|
237
244
|
/** Map from tileset name → SkImage. Set via setTilesetImage(). */
|
|
238
245
|
private _images;
|
|
246
|
+
/** Images in `map.tilesets` order, refreshed from `_images` at the start of each draw. */
|
|
247
|
+
private _tilesetImages;
|
|
239
248
|
/** Reusable bounds rect — avoids per-frame allocation from camera.getBounds(). */
|
|
240
249
|
private _boundsBuf;
|
|
241
250
|
/** Reusable source rect — avoids a per-tile allocation from getTileSourceRect. */
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/tilemap-data.ts","../src/ldtk-parser.ts","../src/parse-error.ts","../src/tiled-parser.ts","../src/tilemap-collider.ts","../src/tilemap-renderer.ts"],"mappings":";;;;;qBAGa;;UAOI;EACf;EACA;EACA;;;wBAIc,cAAc;;;;;;wBASd,eAAe,cAAc;;UAS5B;WACN;;EAET;;EAEA;;EAEA;;;;;;;;;;WAUS,OAAO;;EAEhB;;EAEA;;EAEA;EACA;;EAEA,YAAY;;;UAIG;;EAEf;;EAEA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;;EAEA,YAAY;;;UAIG;WACN;;EAET;;EAEA,SAAS;;EAET;;EAEA;;EAEA,YAAY;;;KAIF,WAAW,YAAY;;;;;UAMlB;;EAEf,QAAQ;;EAER,MAAM;;EAEN;;;UAIe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,gBAAgB,YAAY;;EAE5B,YAAY;;EAEZ,aAAa,YAAY;;;UAIV;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,QAAQ;;EAER,UAAU;;EAEV,YAAY;;;wBAIE,kBACd,eACA,gBACA,mBACA,qBACC;;wBAaa,UAAU,OAAO,WAAW,aAAa;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/tilemap-data.ts","../src/ldtk-parser.ts","../src/parse-error.ts","../src/tiled-parser.ts","../src/tilemap-collider.ts","../src/tilemap-renderer.ts"],"mappings":";;;;;qBAGa;;UAOI;EACf;EACA;EACA;;;wBAIc,cAAc;;;;;;wBASd,eAAe,cAAc;;UAS5B;WACN;;EAET;;EAEA;;EAEA;;;;;;;;;;WAUS,OAAO;;EAEhB;;EAEA;;EAEA;EACA;;EAEA,YAAY;;;UAIG;;EAEf;;EAEA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;;EAEA,YAAY;;;UAIG;WACN;;EAET;;EAEA,SAAS;;EAET;;EAEA;;EAEA,YAAY;;;KAIF,WAAW,YAAY;;;;;UAMlB;;EAEf,QAAQ;;EAER,MAAM;;EAEN;;;UAIe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,gBAAgB,YAAY;;EAE5B,YAAY;;EAEZ,aAAa,YAAY;;;UAIV;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA,QAAQ;;EAER,UAAU;;EAEV,YAAY;;;wBAIE,kBACd,eACA,gBACA,mBACA,qBACC;;wBAaa,UAAU,OAAO,WAAW,aAAa;;;;;;;wBAczC,UAAU,OAAO,WAAW,aAAa,aAAa;;wBAUtD,iBAAiB,UAAU,cAAc,cAAc;;wBAevD,sBAAsB,SAAS,YAAY,aAAa,KAAK,OAAO;;wBAYpE,kBAAkB,SAAS,YAAY,cAAc;UCrJpD;;EAEf,gBAAgB;;UAGD;;EAEf;;EAEA;EACA;;EAEA;EACA;;EAEA,QAAQ;;;;;;wBAOM,kBAAkB,KAAK,cAAc;;;;;;wBAuBrC,UAAU,eAAe,UAAS,mBAAwB;;qBC9H7D,0BAA0B;EACzB,YAAA;;;;;;;;wBCqJE,WAAW,gBAAgB;;UCjJ1B;;EAEf;EACA;;EAEA,OAAO;;EAEP;;EAEA;;EAEA;;;;;;;;;;wBAWc,iBAAiB,KAAK,aAAa,qBAAqB;;;;;;;;;;;;UCCvD;EACf,SAAS;EACT;EACA;;;;;;qBAoBW;;WAEF,KAAK;;WAGL,OAAO;;UAGR;;UAGA;;UAGA;;UAGA;EAEI,YAAA,KAAK;;EAMjB,gBAAgB,qBAAqB,OAAO;;;;;;;;;;EAa5C,SAAS,QAAQ,UAAU,OAAO,aAAa,OAAO;;;;;;;EAyCtD,KAAK,QAAQ,UAAU,QAAQ,OAAO,sBAAsB,OAAO;UAQ3D"}
|
package/dist/index.js
CHANGED
|
@@ -48,6 +48,18 @@ function getTileAt(layer, col, row) {
|
|
|
48
48
|
if (col < 0 || col >= layer.width || row < 0 || row >= layer.height) return 0;
|
|
49
49
|
return layer.tiles[row * layer.width + col] ?? 0;
|
|
50
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* Write a tile GID at a grid position in a tile layer; `getTileAt` and the
|
|
53
|
+
* renderer read it back. Returns `true` when the cell was written, `false` (and
|
|
54
|
+
* writes nothing) when the position is out of bounds or not an integer.
|
|
55
|
+
* The GID is stored raw, Tiled flip bits included. Zero-alloc.
|
|
56
|
+
*/
|
|
57
|
+
function setTileAt(layer, col, row, gid) {
|
|
58
|
+
if (col < 0 || col >= layer.width || row < 0 || row >= layer.height) return false;
|
|
59
|
+
if (!Number.isInteger(col) || !Number.isInteger(row)) return false;
|
|
60
|
+
layer.tiles[row * layer.width + col] = gid;
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
51
63
|
/** Get the tileset that owns a given GID. Handles Tiled flip bits in the high bits. */
|
|
52
64
|
function getTilesetForGid(tilesets, gid) {
|
|
53
65
|
const id = gid & GID_FLIP_MASK;
|
|
@@ -439,6 +451,8 @@ var TilemapRenderer = class {
|
|
|
439
451
|
batch;
|
|
440
452
|
/** Map from tileset name → SkImage. Set via setTilesetImage(). */
|
|
441
453
|
_images = /* @__PURE__ */ new Map();
|
|
454
|
+
/** Images in `map.tilesets` order, refreshed from `_images` at the start of each draw. */
|
|
455
|
+
_tilesetImages = [];
|
|
442
456
|
/** Reusable bounds rect — avoids per-frame allocation from camera.getBounds(). */
|
|
443
457
|
_boundsBuf = {
|
|
444
458
|
x: 0,
|
|
@@ -477,6 +491,13 @@ var TilemapRenderer = class {
|
|
|
477
491
|
const effect = opts?.effect;
|
|
478
492
|
const alphaScale = opts?.alphaScale ?? 1;
|
|
479
493
|
const time = opts?.time ?? NaN;
|
|
494
|
+
const tilesets = this.map.tilesets;
|
|
495
|
+
const images = this._tilesetImages;
|
|
496
|
+
images.length = tilesets.length;
|
|
497
|
+
for (let i = 0; i < tilesets.length; i++) {
|
|
498
|
+
const tileset = tilesets[i];
|
|
499
|
+
if (tileset !== void 0) images[i] = this._images.get(tileset.name);
|
|
500
|
+
}
|
|
480
501
|
for (const layer of this.map.layers) {
|
|
481
502
|
if (layer.type !== "tile" || !layer.visible) continue;
|
|
482
503
|
this._drawTileLayer(layer, bounds.x, bounds.y, bounds.width, bounds.height, tw, th, batch, effect, layer.opacity * alphaScale, time);
|
|
@@ -496,6 +517,12 @@ var TilemapRenderer = class {
|
|
|
496
517
|
const offsetX = layer.offsetX;
|
|
497
518
|
const offsetY = layer.offsetY;
|
|
498
519
|
const animate = Number.isFinite(time);
|
|
520
|
+
const tilesets = this.map.tilesets;
|
|
521
|
+
const images = this._tilesetImages;
|
|
522
|
+
let tileset;
|
|
523
|
+
let image;
|
|
524
|
+
let runLo = 1;
|
|
525
|
+
let runHi = 0;
|
|
499
526
|
const startCol = Math.max(0, Math.floor((viewX - offsetX) / tw));
|
|
500
527
|
const startRow = Math.max(0, Math.floor((viewY - offsetY) / th));
|
|
501
528
|
const endCol = Math.min(layer.width - 1, Math.floor((viewX - offsetX + viewW) / tw));
|
|
@@ -503,13 +530,27 @@ var TilemapRenderer = class {
|
|
|
503
530
|
for (let row = startRow; row <= endRow; row++) for (let col = startCol; col <= endCol; col++) {
|
|
504
531
|
const gid = getTileAt(layer, col, row);
|
|
505
532
|
if (gid === 0) continue;
|
|
506
|
-
const
|
|
533
|
+
const id = gid & GID_FLIP_MASK;
|
|
534
|
+
if (id < runLo || id >= runHi) {
|
|
535
|
+
tileset = getTilesetForGid(tilesets, id);
|
|
536
|
+
image = void 0;
|
|
537
|
+
runLo = 1;
|
|
538
|
+
runHi = 0;
|
|
539
|
+
if (tileset !== void 0) {
|
|
540
|
+
let index = 0;
|
|
541
|
+
runLo = tileset.firstGid;
|
|
542
|
+
for (let ts = tilesets[0]; ts !== void 0 && ts !== tileset; ts = tilesets[++index]) if (ts.firstGid > runLo) runLo = ts.firstGid;
|
|
543
|
+
image = images[index];
|
|
544
|
+
runHi = tileset.firstGid + tileset.tileCount;
|
|
545
|
+
const next = tilesets[index + 1];
|
|
546
|
+
if (next !== void 0 && next.firstGid < runHi) runHi = next.firstGid;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
507
549
|
if (!tileset) continue;
|
|
508
|
-
const image = this._images.get(tileset.name);
|
|
509
550
|
if (!image) continue;
|
|
510
551
|
let srcGid = gid;
|
|
511
552
|
if (animate && tileset.animations !== void 0) {
|
|
512
|
-
const anim = tileset.animations.get(
|
|
553
|
+
const anim = tileset.animations.get(id - tileset.firstGid);
|
|
513
554
|
if (anim !== void 0) srcGid = tileset.firstGid + animatedLocalId(anim, time);
|
|
514
555
|
}
|
|
515
556
|
const src = getTileSourceRectInto(tileset, srcGid, this._srcBuf);
|
|
@@ -541,6 +582,7 @@ exports.getTilesetForGid = getTilesetForGid;
|
|
|
541
582
|
exports.parseLDtk = parseLDtk;
|
|
542
583
|
exports.parseLDtkEntities = parseLDtkEntities;
|
|
543
584
|
exports.parseTiled = parseTiled;
|
|
585
|
+
exports.setTileAt = setTileAt;
|
|
544
586
|
exports.stripGidFlags = stripGidFlags;
|
|
545
587
|
|
|
546
588
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["FLIP_H","FLIP_V","FLIP_D","AABB","SpriteBatch"],"sources":["../src/parse-error.ts","../src/tilemap-data.ts","../src/ldtk-parser.ts","../src/tiled-parser.ts","../src/tilemap-collider.ts","../src/tilemap-renderer.ts"],"sourcesContent":["/** Thrown by parseTiled/parseLDtk when a map uses an unsupported format or feature. */\nexport class TilemapParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'TilemapParseError';\n }\n}\n","import type { Rect } from '@flare-engine/math';\n\n/** Low 29 bits of a Tiled GID — Tiled stores flip state in the high 3 bits. */\nexport const GID_FLIP_MASK = 0x1fffffff;\n\nconst FLIP_H = 0x80000000;\nconst FLIP_V = 0x40000000;\nconst FLIP_D = 0x20000000;\n\n/** Flip state encoded in the high bits of a Tiled GID. */\nexport interface TileFlipFlags {\n horizontal: boolean;\n vertical: boolean;\n diagonal: boolean;\n}\n\n/** Strip the Tiled flip bits from a raw GID, returning the real global tile id. */\nexport function stripGidFlags(gid: number): number {\n return gid & GID_FLIP_MASK;\n}\n\n/**\n * Decode the Tiled flip bits encoded in the high bits of a raw GID.\n * Note: `gid & 0x80000000` yields a negative Int32 when the bit is set;\n * compare with `!== 0`, not `> 0`.\n */\nexport function decodeGidFlags(gid: number): TileFlipFlags {\n return {\n horizontal: (gid & FLIP_H) !== 0,\n vertical: (gid & FLIP_V) !== 0,\n diagonal: (gid & FLIP_D) !== 0,\n };\n}\n\n/** A layer of tiles in a grid. */\nexport interface TileLayer {\n readonly type: 'tile';\n /** Layer name. */\n name: string;\n /** Grid width in tiles. */\n width: number;\n /** Grid height in tiles. */\n height: number;\n /**\n * Flat array of tile GIDs (row-major, length = width * height). `Uint32Array`,\n * not `Float32Array` — a 24-bit mantissa cannot hold Tiled's flip-bit GIDs\n * (`0x80000000` and up). This is a type decision for bulk numeric data per the\n * repo convention, not a measured perf change.\n *\n * `readonly` like `SolidGrid.solid`: the array cannot be swapped out from under a\n * parsed map, but its cells stay writable (`layer.tiles[i] = gid`).\n */\n readonly tiles: Uint32Array;\n /** Visibility flag. */\n visible: boolean;\n /** Opacity (0–1). */\n opacity: number;\n /** Layer offset in pixels. */\n offsetX: number;\n offsetY: number;\n /** Custom properties. */\n properties: Record<string, unknown>;\n}\n\n/** An object in an object layer. */\nexport interface MapObject {\n /** Object ID. */\n id: number;\n /** Object name. */\n name: string;\n /** Object type/class. */\n type: string;\n /** Position in pixels. */\n x: number;\n y: number;\n /** Size in pixels. */\n width: number;\n height: number;\n /** Rotation in degrees. */\n rotation: number;\n /** Custom properties. */\n properties: Record<string, unknown>;\n}\n\n/** A layer of objects. */\nexport interface ObjectLayer {\n readonly type: 'object';\n /** Layer name. */\n name: string;\n /** Objects in the layer. */\n objects: MapObject[];\n /** Visibility flag. */\n visible: boolean;\n /** Opacity (0–1). */\n opacity: number;\n /** Custom properties. */\n properties: Record<string, unknown>;\n}\n\n/** Union of layer types. */\nexport type MapLayer = TileLayer | ObjectLayer;\n\n/**\n * A Tiled per-tile animation, parsed into flat per-frame arrays so a renderer\n * can resolve the current frame without allocating.\n */\nexport interface TileAnimation {\n /** Local tile id of each frame, in order. */\n frames: Uint32Array;\n /** Cumulative end time of each frame, in seconds (frame i covers [ends[i-1], ends[i])). */\n ends: Float64Array;\n /** Total cycle length, seconds. */\n duration: number;\n}\n\n/** Information about a tileset used in the map. */\nexport interface TilesetRef {\n /** First GID in this tileset. */\n firstGid: number;\n /** Tileset name. */\n name: string;\n /** Tile width in pixels. */\n tileWidth: number;\n /** Tile height in pixels. */\n tileHeight: number;\n /** Number of columns in the tileset image. */\n columns: number;\n /** Total tile count. */\n tileCount: number;\n /** Image source path (may need resolving). */\n image: string;\n /** Image width in pixels. */\n imageWidth: number;\n /** Image height in pixels. */\n imageHeight: number;\n /** Per-tile properties (indexed by local tile ID). */\n tileProperties: Map<number, Record<string, unknown>>;\n /** Tile IDs marked as solid/collision. */\n solidTiles: Set<number>;\n /** Tiled per-tile animations keyed by local tile id; absent when no tile is animated. */\n animations?: Map<number, TileAnimation>;\n}\n\n/** Complete parsed tilemap data — format-independent. */\nexport interface TilemapData {\n /** Map width in tiles. */\n width: number;\n /** Map height in tiles. */\n height: number;\n /** Tile width in pixels. */\n tileWidth: number;\n /** Tile height in pixels. */\n tileHeight: number;\n /** All layers in order. */\n layers: MapLayer[];\n /** Tilesets referenced by this map. */\n tilesets: TilesetRef[];\n /** Custom map properties. */\n properties: Record<string, unknown>;\n}\n\n/** Create an empty TilemapData. */\nexport function createTilemapData(\n width: number,\n height: number,\n tileWidth: number,\n tileHeight: number,\n): TilemapData {\n return {\n width,\n height,\n tileWidth,\n tileHeight,\n layers: [],\n tilesets: [],\n properties: {},\n };\n}\n\n/** Get a tile GID at a grid position from a tile layer. Returns 0 if out of bounds. */\nexport function getTileAt(layer: TileLayer, col: number, row: number): number {\n if (col < 0 || col >= layer.width || row < 0 || row >= layer.height) return 0;\n // The `?? 0` is unreachable at runtime (the bounds check above guarantees an\n // in-range index into a hole-free Uint32Array) — it satisfies noUncheckedIndexedAccess,\n // which types every typed-array index read as `number | undefined`.\n return layer.tiles[row * layer.width + col] ?? 0;\n}\n\n/** Get the tileset that owns a given GID. Handles Tiled flip bits in the high bits. */\nexport function getTilesetForGid(tilesets: TilesetRef[], gid: number): TilesetRef | undefined {\n const id = gid & GID_FLIP_MASK;\n // Tilesets are ordered by firstGid; find the last one where firstGid <= id\n let result: TilesetRef | undefined;\n for (const ts of tilesets) {\n if (ts.firstGid <= id) {\n result = ts;\n } else {\n break;\n }\n }\n return result;\n}\n\n/** Compute the source rect in a tileset image for a given GID into `out`. Strips Tiled flip bits. Zero-alloc. */\nexport function getTileSourceRectInto(tileset: TilesetRef, gid: number, out: Rect): Rect {\n const localId = (gid & GID_FLIP_MASK) - tileset.firstGid;\n const col = localId % tileset.columns;\n const row = Math.floor(localId / tileset.columns);\n out.x = col * tileset.tileWidth;\n out.y = row * tileset.tileHeight;\n out.width = tileset.tileWidth;\n out.height = tileset.tileHeight;\n return out;\n}\n\n/** Compute the source rect in a tileset image for a given GID. Strips Tiled flip bits. */\nexport function getTileSourceRect(tileset: TilesetRef, gid: number): Rect {\n return getTileSourceRectInto(tileset, gid, { x: 0, y: 0, width: 0, height: 0 });\n}\n","import { TilemapParseError } from './parse-error.js';\nimport type { MapObject, ObjectLayer, TileLayer, TilemapData, TilesetRef } from './tilemap-data.js';\nimport { createTilemapData } from './tilemap-data.js';\n\n// ----- LDtk JSON types -----\n\ninterface LDtkFieldInstance {\n __identifier: string;\n __value: unknown;\n __type: string;\n}\n\ninterface LDtkEntityInstance {\n __identifier: string;\n __grid: [number, number];\n __pivot: [number, number];\n __tile?: { x: number; y: number; w: number; h: number };\n iid: string;\n width: number;\n height: number;\n px: [number, number];\n fieldInstances: LDtkFieldInstance[];\n}\n\ninterface LDtkTileInstance {\n px: [number, number];\n src: [number, number];\n f: number; // flip flags\n t: number; // tile ID\n}\n\ninterface LDtkLayerInstance {\n __identifier: string;\n __type: string;\n __cWid: number;\n __cHei: number;\n __gridSize: number;\n __tilesetDefUid?: number;\n __tilesetRelPath?: string;\n visible: boolean;\n __opacity: number;\n intGridCsv?: number[];\n // Real LDtk output always emits both arrays on every layer instance — only\n // one is ever populated per __type (an AutoLayer's gridTiles is always []).\n // Required (not optional) so a fixture omitting the unused one, as every\n // fixture here did before F057, cannot pass this module's own types.\n gridTiles: LDtkTileInstance[];\n autoLayerTiles: LDtkTileInstance[];\n entityInstances?: LDtkEntityInstance[];\n}\n\ninterface LDtkTilesetDef {\n uid: number;\n identifier: string;\n relPath: string;\n pxWid: number;\n pxHei: number;\n tileGridSize: number;\n __cWid: number;\n __cHei: number;\n}\n\ninterface LDtkLevel {\n identifier: string;\n uid: number;\n pxWid: number;\n pxHei: number;\n worldX: number;\n worldY: number;\n layerInstances?: LDtkLayerInstance[];\n fieldInstances?: LDtkFieldInstance[];\n}\n\ninterface LDtkJSON {\n defaultGridSize: number;\n externalLevels?: boolean;\n defs: {\n tilesets: LDtkTilesetDef[];\n };\n levels: LDtkLevel[];\n}\n\nexport interface ParseLDtkOptions {\n /** Predicate deciding whether an IntGrid value marks a solid cell. Default: value > 0. */\n intGridSolid?: (value: number) => boolean;\n}\n\nexport interface LDtkEntity {\n /** LDtk entity identifier (its type, e.g. \"Player\") — the key you switch on to decide what to spawn. */\n id: string;\n /** Entity position in pixels (LDtk px, pivot-adjusted per the parser convention). */\n x: number;\n y: number;\n /** Entity box size in pixels. */\n width: number;\n height: number;\n /** Custom field instances, keyed by field identifier. */\n fields: Record<string, unknown>;\n}\n\n/**\n * Extract every LDtk entity from a parsed map as a flat, spawn-ready list —\n * the LDtk-entity → ECS spawn convention. Walks all object layers; tile layers are skipped.\n */\nexport function parseLDtkEntities(map: TilemapData): LDtkEntity[] {\n const entities: LDtkEntity[] = [];\n for (const layer of map.layers) {\n if (layer.type !== 'object') continue;\n for (const obj of layer.objects) {\n entities.push({\n id: obj.type,\n x: obj.x,\n y: obj.y,\n width: obj.width,\n height: obj.height,\n fields: obj.properties,\n });\n }\n }\n return entities;\n}\n\n/**\n * Parse an LDtk JSON project into an array of TilemapData (one per level).\n * Returns all levels with their tile and entity layers.\n * Throws TilemapParseError for unsupported formats (externalLevels, invalid input).\n */\nexport function parseLDtk(json: unknown, options: ParseLDtkOptions = {}): TilemapData[] {\n if (\n !json ||\n typeof json !== 'object' ||\n !Array.isArray((json as Record<string, unknown>).levels) ||\n !(json as Record<string, unknown>).defs ||\n !Array.isArray(((json as Record<string, unknown>).defs as Record<string, unknown>).tilesets)\n ) {\n throw new TilemapParseError(\n 'parseLDtk: input is not an LDtk project JSON (missing defs.tilesets or levels).',\n );\n }\n\n const data = json as LDtkJSON;\n\n if (data.externalLevels === true) {\n throw new TilemapParseError(\n 'parseLDtk: projects with \"Save levels to separate files\" (externalLevels) are not supported. Disable it in LDtk ▸ Project settings and re-save.',\n );\n }\n\n const isSolid = options.intGridSolid ?? ((v) => v > 0);\n\n const tilesetDefs = new Map<number, LDtkTilesetDef>();\n for (const ts of data.defs.tilesets) {\n tilesetDefs.set(ts.uid, ts);\n }\n\n const results: TilemapData[] = [];\n\n for (const level of data.levels) {\n const gridSize = data.defaultGridSize;\n const mapWidth = Math.ceil(level.pxWid / gridSize);\n const mapHeight = Math.ceil(level.pxHei / gridSize);\n const map = createTilemapData(mapWidth, mapHeight, gridSize, gridSize);\n\n if (level.fieldInstances) {\n for (const field of level.fieldInstances) {\n map.properties[field.__identifier] = field.__value;\n }\n }\n\n // Pass 1: collect tile-layer tileset uids, sort ascending, assign deterministic firstGids.\n // Tilesets must be sorted by firstGid (ascending) for getTilesetForGid's early-break.\n const firstGidByUid = new Map<number, number>();\n let nextFirstGid = 1;\n\n if (level.layerInstances) {\n const usedTileUids = new Set<number>();\n for (const layerInst of level.layerInstances) {\n if (\n (layerInst.__type === 'Tiles' || layerInst.__type === 'AutoLayer') &&\n layerInst.__tilesetDefUid !== undefined\n ) {\n usedTileUids.add(layerInst.__tilesetDefUid);\n }\n }\n\n const sortedUids = Array.from(usedTileUids).sort((a, b) => a - b);\n for (const uid of sortedUids) {\n const def = tilesetDefs.get(uid);\n if (!def) continue;\n const columns = def.__cWid;\n const tileCount = def.__cWid * def.__cHei;\n firstGidByUid.set(uid, nextFirstGid);\n const ref: TilesetRef = {\n firstGid: nextFirstGid,\n name: def.identifier,\n tileWidth: def.tileGridSize,\n tileHeight: def.tileGridSize,\n columns,\n tileCount,\n image: def.relPath,\n imageWidth: def.pxWid,\n imageHeight: def.pxHei,\n tileProperties: new Map(),\n solidTiles: new Set(),\n };\n map.tilesets.push(ref);\n nextFirstGid += tileCount;\n }\n }\n\n // Pass 2: parse layers in reverse order (LDtk stores top-first; emit bottom-first).\n if (level.layerInstances) {\n for (let i = level.layerInstances.length - 1; i >= 0; i--) {\n const layerInst = level.layerInstances[i]!;\n\n if (layerInst.__type === 'IntGrid') {\n // IntGrid layers are treated as collision grids; IntGrid layers that also\n // carry auto-render tiles keep collision only (visual auto-tiles are M4 scope).\n const csv = layerInst.intGridCsv;\n const cellCount = layerInst.__cWid * layerInst.__cHei;\n const tiles = new Uint32Array(cellCount);\n const intFirstGid = nextFirstGid;\n let maxLocal = 0;\n let hasNonZero = false;\n const solidSet = new Set<number>();\n\n if (csv) {\n for (let j = 0; j < csv.length; j++) {\n const v = csv[j] ?? 0;\n if (v > 0) {\n hasNonZero = true;\n const localId = v - 1;\n if (localId > maxLocal) maxLocal = localId;\n tiles[j] = intFirstGid + localId;\n if (isSolid(v)) solidSet.add(localId);\n }\n }\n }\n\n if (hasNonZero) {\n const tileCount = maxLocal + 1;\n map.tilesets.push({\n firstGid: intFirstGid,\n name: layerInst.__identifier,\n tileWidth: layerInst.__gridSize,\n tileHeight: layerInst.__gridSize,\n columns: tileCount,\n tileCount,\n image: '',\n imageWidth: 0,\n imageHeight: 0,\n tileProperties: new Map(),\n solidTiles: solidSet,\n });\n nextFirstGid += tileCount;\n }\n\n map.layers.push({\n type: 'tile',\n name: layerInst.__identifier,\n width: layerInst.__cWid,\n height: layerInst.__cHei,\n tiles,\n visible: layerInst.visible,\n opacity: layerInst.__opacity,\n offsetX: 0,\n offsetY: 0,\n properties: {},\n });\n } else if (layerInst.__type === 'Tiles' || layerInst.__type === 'AutoLayer') {\n const firstGid = firstGidByUid.get(layerInst.__tilesetDefUid ?? -1) ?? 1;\n map.layers.push(parseTilesLayer(layerInst, mapWidth, mapHeight, gridSize, firstGid));\n } else if (layerInst.__type === 'Entities') {\n map.layers.push(parseEntitiesLayer(layerInst));\n }\n }\n }\n\n results.push(map);\n }\n\n return results;\n}\n\nfunction parseTilesLayer(\n layer: LDtkLayerInstance,\n mapWidth: number,\n mapHeight: number,\n gridSize: number,\n firstGid: number,\n): TileLayer {\n const tiles = new Uint32Array(mapWidth * mapHeight);\n // An AutoLayer's tiles live in autoLayerTiles; its gridTiles is always [].\n // `gridTiles ?? autoLayerTiles` picked the empty gridTiles for every\n // AutoLayer, since `??` only falls through on null/undefined, never on `[]`\n // — select by __type instead, which is the field LDtk itself keys on.\n const tileInstances = layer.__type === 'AutoLayer' ? layer.autoLayerTiles : layer.gridTiles;\n\n for (const ti of tileInstances) {\n const col = Math.floor(ti.px[0] / gridSize);\n const row = Math.floor(ti.px[1] / gridSize);\n if (col >= 0 && col < mapWidth && row >= 0 && row < mapHeight) {\n tiles[row * mapWidth + col] = firstGid + ti.t;\n }\n }\n\n return {\n type: 'tile',\n name: layer.__identifier,\n width: mapWidth,\n height: mapHeight,\n tiles,\n visible: layer.visible,\n opacity: layer.__opacity,\n offsetX: 0,\n offsetY: 0,\n properties: {},\n };\n}\n\nfunction parseEntitiesLayer(layer: LDtkLayerInstance): ObjectLayer {\n const objects: MapObject[] = (layer.entityInstances ?? []).map((ent, idx) => {\n const props: Record<string, unknown> = {};\n for (const field of ent.fieldInstances) {\n props[field.__identifier] = field.__value;\n }\n return {\n id: idx + 1,\n name: ent.__identifier,\n type: ent.__identifier,\n x: ent.px[0],\n y: ent.px[1],\n width: ent.width,\n height: ent.height,\n rotation: 0,\n properties: props,\n };\n });\n\n return {\n type: 'object',\n name: layer.__identifier,\n objects,\n visible: layer.visible,\n opacity: layer.__opacity,\n properties: {},\n };\n}\n","import { TilemapParseError } from './parse-error.js';\nimport type {\n MapLayer,\n MapObject,\n ObjectLayer,\n TileAnimation,\n TileLayer,\n TilemapData,\n TilesetRef,\n} from './tilemap-data.js';\nimport { createTilemapData } from './tilemap-data.js';\n\n// ----- Tiled JSON types (.tmj format) -----\n\ninterface TiledProperty {\n name: string;\n type: string;\n value: unknown;\n}\n\ninterface TiledTileLayer {\n type: 'tilelayer';\n name: string;\n width: number;\n height: number;\n data: number[] | string;\n encoding?: string;\n compression?: string;\n chunks?: unknown[];\n visible: boolean;\n opacity: number;\n offsetx?: number;\n offsety?: number;\n properties?: TiledProperty[];\n}\n\ninterface TiledObject {\n id: number;\n name: string;\n type?: string;\n class?: string;\n x: number;\n y: number;\n width: number;\n height: number;\n rotation: number;\n properties?: TiledProperty[];\n}\n\ninterface TiledObjectLayer {\n type: 'objectgroup';\n name: string;\n objects: TiledObject[];\n visible: boolean;\n opacity: number;\n properties?: TiledProperty[];\n}\n\ntype TiledLayer = TiledTileLayer | TiledObjectLayer;\n\ninterface TiledAnimationFrame {\n tileid: number;\n /** Milliseconds. */\n duration: number;\n}\n\ninterface TiledTile {\n id: number;\n properties?: TiledProperty[];\n type?: string;\n class?: string;\n animation?: TiledAnimationFrame[];\n}\n\ninterface TiledTileset {\n firstgid: number;\n name: string;\n tilewidth: number;\n tileheight: number;\n columns: number;\n tilecount: number;\n image: string;\n imagewidth: number;\n imageheight: number;\n tiles?: TiledTile[];\n properties?: TiledProperty[];\n source?: string;\n}\n\ninterface TiledMapJSON {\n width: number;\n height: number;\n tilewidth: number;\n tileheight: number;\n orientation: string;\n infinite?: boolean;\n layers: TiledLayer[];\n tilesets: TiledTileset[];\n properties?: TiledProperty[];\n}\n\n/** Convert Tiled properties array to a Record. */\nfunction parseProperties(props?: TiledProperty[]): Record<string, unknown> {\n if (!props || props.length === 0) return {};\n const result: Record<string, unknown> = {};\n for (const p of props) {\n result[p.name] = p.value;\n }\n return result;\n}\n\n/**\n * Build a tile's Tiled animation (frame durations in ms) into cumulative seconds.\n * Returns `undefined` for an empty animation or one whose durations sum to 0 —\n * such a tile draws as authored.\n */\nfunction parseTileAnimation(ts: TiledTileset, tile: TiledTile): TileAnimation | undefined {\n const source = tile.animation;\n if (source === undefined || source.length === 0) return undefined;\n const frames = new Uint32Array(source.length);\n const ends = new Float64Array(source.length);\n // Summed in ms and divided once per frame so integer-ms inputs give exact seconds.\n let totalMs = 0;\n for (let i = 0; i < source.length; i++) {\n const frame = source[i]!;\n const tileid = frame.tileid;\n const duration = frame.duration;\n if (!Number.isInteger(tileid) || tileid < 0 || tileid >= ts.tilecount) {\n throw new TilemapParseError(\n `parseTiled: tileset \"${ts.name}\" tile ${tile.id} animation frame ${i} has tileid ${tileid} — expected an integer in [0, ${ts.tilecount}).`,\n );\n }\n if (!Number.isFinite(duration) || duration < 0) {\n throw new TilemapParseError(\n `parseTiled: tileset \"${ts.name}\" tile ${tile.id} animation frame ${i} has duration ${duration} — expected a finite number of milliseconds >= 0.`,\n );\n }\n totalMs += duration;\n frames[i] = tileid;\n ends[i] = totalMs / 1000;\n }\n if (totalMs === 0) return undefined;\n return { frames, ends, duration: totalMs / 1000 };\n}\n\n/**\n * Parse a Tiled .tmj (JSON) map into TilemapData.\n * Supports orthogonal maps with CSV tile layers and object layers.\n * Throws TilemapParseError for unsupported formats (infinite, non-orthogonal,\n * external tilesets, base64/compressed/chunked layer data).\n */\nexport function parseTiled(json: unknown): TilemapData {\n if (\n !json ||\n typeof json !== 'object' ||\n typeof (json as Record<string, unknown>).width !== 'number' ||\n typeof (json as Record<string, unknown>).height !== 'number' ||\n !Array.isArray((json as Record<string, unknown>).layers) ||\n !Array.isArray((json as Record<string, unknown>).tilesets)\n ) {\n throw new TilemapParseError(\n 'parseTiled: input is not a Tiled map JSON (missing width/height/layers/tilesets).',\n );\n }\n\n const data = json as TiledMapJSON;\n\n if (data.infinite === true) {\n throw new TilemapParseError(\n 'parseTiled: infinite maps are not supported. In Tiled: Map ▸ Map Properties ▸ set \"Infinite\" to false, then re-export.',\n );\n }\n if (data.orientation && data.orientation !== 'orthogonal') {\n throw new TilemapParseError(\n `parseTiled: orientation \"${data.orientation}\" is not supported — only orthogonal maps are supported.`,\n );\n }\n\n const map = createTilemapData(data.width, data.height, data.tilewidth, data.tileheight);\n map.properties = parseProperties(data.properties);\n\n // Parse tilesets\n for (const ts of data.tilesets) {\n if (ts.source !== undefined) {\n throw new TilemapParseError(\n `parseTiled: external tileset \"${ts.source}\" is not supported. Embed tilesets on export (Tiled ▸ Map ▸ \"Embed tilesets\") or run it through \\`flare tiled-to-flare\\` (which embeds tilesets by default).`,\n );\n }\n\n const tileProperties = new Map<number, Record<string, unknown>>();\n const solidTiles = new Set<number>();\n let animations: Map<number, TileAnimation> | undefined;\n\n if (ts.tiles) {\n for (const tile of ts.tiles) {\n const props = parseProperties(tile.properties);\n if (Object.keys(props).length > 0) {\n tileProperties.set(tile.id, props);\n }\n // Mark as solid if it has a \"collision\" or \"solid\" property, or type/class is \"solid\"\n const tileType = tile.type ?? tile.class ?? '';\n if (tileType === 'solid' || props.solid === true || props.collision === true) {\n solidTiles.add(tile.id);\n }\n const animation = parseTileAnimation(ts, tile);\n if (animation !== undefined) {\n animations ??= new Map();\n animations.set(tile.id, animation);\n }\n }\n }\n\n const ref: TilesetRef = {\n firstGid: ts.firstgid,\n name: ts.name,\n tileWidth: ts.tilewidth,\n tileHeight: ts.tileheight,\n columns: ts.columns,\n tileCount: ts.tilecount,\n image: ts.image,\n imageWidth: ts.imagewidth,\n imageHeight: ts.imageheight,\n tileProperties,\n solidTiles,\n };\n if (animations !== undefined) ref.animations = animations;\n map.tilesets.push(ref);\n }\n\n // Sort tilesets by firstGid\n map.tilesets.sort((a, b) => a.firstGid - b.firstGid);\n\n // Parse layers\n for (const layer of data.layers) {\n map.layers.push(parseLayer(layer));\n }\n\n return map;\n}\n\nfunction parseLayer(layer: TiledLayer): MapLayer {\n if (layer.type === 'tilelayer') return parseTileLayer(layer);\n if (layer.type === 'objectgroup') return parseObjectLayer(layer);\n const l = layer as { type: string; name?: string };\n throw new TilemapParseError(\n `parseTiled: layer \"${l.name ?? ''}\" has unsupported type \"${l.type}\". Only tilelayer and objectgroup are supported — flatten group layers and remove image layers before export.`,\n );\n}\n\nfunction parseTileLayer(layer: TiledTileLayer): TileLayer {\n if (\n (layer.encoding !== undefined && layer.encoding !== 'csv') ||\n layer.compression !== undefined ||\n layer.chunks !== undefined\n ) {\n throw new TilemapParseError(\n 'parseTiled: base64/compressed/chunked (infinite) layer data is not supported. In Tiled export options set Tile Layer Format to \"CSV\".',\n );\n }\n if (typeof layer.data === 'string') {\n throw new TilemapParseError(\n 'parseTiled: base64/compressed/chunked (infinite) layer data is not supported. In Tiled export options set Tile Layer Format to \"CSV\".',\n );\n }\n // layer.data is number[] here — Uint32Array.from preserves flip-bit GIDs\n // (values up to 0xffffffff), unlike a Float32Array's 24-bit mantissa.\n return {\n type: 'tile',\n name: layer.name,\n width: layer.width,\n height: layer.height,\n tiles: Uint32Array.from(layer.data),\n visible: layer.visible,\n opacity: layer.opacity,\n offsetX: layer.offsetx ?? 0,\n offsetY: layer.offsety ?? 0,\n properties: parseProperties(layer.properties),\n };\n}\n\nfunction parseObjectLayer(layer: TiledObjectLayer): ObjectLayer {\n const objects: MapObject[] = layer.objects.map((obj) => ({\n id: obj.id,\n name: obj.name,\n type: obj.type ?? obj.class ?? '',\n x: obj.x,\n y: obj.y,\n width: obj.width,\n height: obj.height,\n rotation: obj.rotation,\n properties: parseProperties(obj.properties),\n }));\n\n return {\n type: 'object',\n name: layer.name,\n objects,\n visible: layer.visible,\n opacity: layer.opacity,\n properties: parseProperties(layer.properties),\n };\n}\n","import type { AABBShape } from '@flare-engine/physics';\nimport { AABB } from '@flare-engine/physics';\nimport type { TileLayer, TilemapData, TilesetRef } from './tilemap-data.js';\nimport { GID_FLIP_MASK, getTilesetForGid } from './tilemap-data.js';\n\n/** A collision body extracted from a solid tile. */\nexport interface TileCollider {\n /** World position of the tile center. */\n x: number;\n y: number;\n /** AABB collision shape. */\n shape: AABBShape;\n /** Grid column. */\n col: number;\n /** Grid row. */\n row: number;\n /** The tile GID (flip bits stripped — AABB is symmetric, downstream lookups want the real id). */\n gid: number;\n}\n\n/**\n * Extract collision shapes from solid tiles in a tilemap.\n * A tile is considered solid if its tileset marks the local tile ID as solid.\n *\n * @param map The parsed tilemap data.\n * @param layerName Optional: only extract from this layer. If omitted, extracts from all tile layers.\n * @returns Array of TileCollider bodies.\n */\nexport function extractColliders(map: TilemapData, layerName?: string): TileCollider[] {\n const colliders: TileCollider[] = [];\n const tw = map.tileWidth;\n const th = map.tileHeight;\n\n for (const layer of map.layers) {\n if (layer.type !== 'tile') continue;\n if (layerName !== undefined && layer.name !== layerName) continue;\n\n extractFromLayer(layer, map.tilesets, tw, th, colliders);\n }\n\n return colliders;\n}\n\nfunction extractFromLayer(\n layer: TileLayer,\n tilesets: TilesetRef[],\n tw: number,\n th: number,\n out: TileCollider[],\n): void {\n for (let row = 0; row < layer.height; row++) {\n for (let col = 0; col < layer.width; col++) {\n const gid = layer.tiles[row * layer.width + col] ?? 0;\n if (gid === 0) continue;\n\n const tileset = getTilesetForGid(tilesets, gid);\n if (!tileset) continue;\n\n const localId = (gid & GID_FLIP_MASK) - tileset.firstGid;\n if (!tileset.solidTiles.has(localId)) continue;\n\n out.push({\n x: col * tw + tw * 0.5 + layer.offsetX,\n y: row * th + th * 0.5 + layer.offsetY,\n shape: AABB(tw, th),\n col,\n row,\n gid: gid & GID_FLIP_MASK,\n });\n }\n }\n}\n","import type { SkImageLike } from '@flare-engine/assets';\nimport type { Rect } from '@flare-engine/math';\nimport type { AnySpriteEffect, Camera2D } from '@flare-engine/render';\nimport { SpriteBatch } from '@flare-engine/render';\nimport type { TileAnimation, TileLayer, TilemapData } from './tilemap-data.js';\nimport {\n GID_FLIP_MASK,\n getTileAt,\n getTileSourceRectInto,\n getTilesetForGid,\n} from './tilemap-data.js';\n\n// Tiled GID flag bits (kept module-private; tilemap-data.ts owns the public mask).\nconst FLIP_H = 0x80000000;\nconst FLIP_V = 0x40000000;\nconst FLIP_D = 0x20000000;\nconst QUARTER_TURN = Math.PI / 2;\n\n/**\n * Per-draw options for `TilemapRenderer.drawInto` / `draw`.\n *\n * `effect` is set on every queued tile command. Batch runs key on the effect\n * by reference, so one shared instance (e.g. an ambient `tint()`) keeps every\n * tile — and any sprite drawn with the same instance — in a single run.\n * `alphaScale` multiplies each layer's own `opacity` (default 1).\n * `time` (seconds, e.g. the clock's elapsed) advances Tiled tile animations\n * parsed onto `TilesetRef.animations`; it wraps in both directions. Without\n * it (or when non-finite) every tile draws as authored.\n */\nexport interface TilemapDrawOptions {\n effect?: AnySpriteEffect;\n alphaScale?: number;\n time?: number;\n}\n\n/** Local tile id of the frame an animation shows at `time` (seconds, finite). */\nfunction animatedLocalId(anim: TileAnimation, time: number): number {\n let t = time % anim.duration;\n if (t < 0) t += anim.duration;\n const ends = anim.ends;\n const last = ends.length - 1;\n let i = 0;\n // A frame boundary belongs to the next frame; ends[last] === duration > t stops the scan.\n while (i < last && t >= (ends[i] ?? 0)) i++;\n // The `?? 0` is unreachable (i <= last < frames.length) — it satisfies noUncheckedIndexedAccess.\n return anim.frames[i] ?? 0;\n}\n\n/**\n * TilemapRenderer — draws a tilemap with viewport culling.\n * Only tiles visible to the camera are submitted to the SpriteBatch.\n */\nexport class TilemapRenderer {\n /** The tilemap data to render. */\n readonly map: TilemapData;\n\n /** SpriteBatch used for batched tile rendering. */\n readonly batch: SpriteBatch;\n\n /** Map from tileset name → SkImage. Set via setTilesetImage(). */\n private _images = new Map<string, SkImageLike>();\n\n /** Reusable bounds rect — avoids per-frame allocation from camera.getBounds(). */\n private _boundsBuf: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n /** Reusable source rect — avoids a per-tile allocation from getTileSourceRect. */\n private _srcBuf: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n constructor(map: TilemapData) {\n this.map = map;\n this.batch = new SpriteBatch();\n }\n\n /** Associate a loaded image with a tileset by name. */\n setTilesetImage(tilesetName: string, image: SkImageLike): void {\n this._images.set(tilesetName, image);\n }\n\n /**\n * Queue visible tile layers into a caller-owned `batch` using the camera for\n * culling. Does NOT flush — the caller owns the single flush so tiles z-order\n * under sprites. Zero-alloc: reuses the internal bounds buffer.\n *\n * Each tile's `alpha` is `layer.opacity * opts.alphaScale`; `opts.effect`\n * is applied to every tile; `opts.time` picks each animated tile's frame\n * (see `TilemapDrawOptions`).\n */\n drawInto(camera: Camera2D, batch: SpriteBatch, opts?: TilemapDrawOptions): void {\n const bounds = camera.getBoundsInto(this._boundsBuf);\n const tw = this.map.tileWidth;\n const th = this.map.tileHeight;\n const effect = opts?.effect;\n const alphaScale = opts?.alphaScale ?? 1;\n // NaN stands for \"no time\": the layer pass animates only when `time` is finite.\n const time = opts?.time ?? Number.NaN;\n\n for (const layer of this.map.layers) {\n if (layer.type !== 'tile' || !layer.visible) continue;\n this._drawTileLayer(\n layer,\n bounds.x,\n bounds.y,\n bounds.width,\n bounds.height,\n tw,\n th,\n batch,\n effect,\n layer.opacity * alphaScale,\n time,\n );\n }\n }\n\n /**\n * Draw visible tile layers using the camera for culling.\n * Call `flush` on a callback to issue the actual draw calls.\n * Delegates to `drawInto` so culling and queuing logic live in one place;\n * `opts` is threaded through unchanged.\n */\n draw(camera: Camera2D, flush: (batch: SpriteBatch) => void, opts?: TilemapDrawOptions): void {\n this.drawInto(camera, this.batch, opts);\n flush(this.batch);\n }\n\n // Tiled flip bits: H/V become the batch's flipX/flipY; the diagonal bit is a\n // quarter turn about the tile centre composed with the flip Tiled defines\n // (D+H = 90° CW, D+V = 90° CCW, D = flipY + CW, D+H+V = flipX + CW).\n private _drawTileLayer(\n layer: TileLayer,\n viewX: number,\n viewY: number,\n viewW: number,\n viewH: number,\n tw: number,\n th: number,\n batch: SpriteBatch,\n effect: AnySpriteEffect | undefined,\n alpha: number,\n time: number,\n ): void {\n const offsetX = layer.offsetX;\n const offsetY = layer.offsetY;\n const animate = Number.isFinite(time);\n\n // Calculate visible tile range (clamped to layer bounds)\n const startCol = Math.max(0, Math.floor((viewX - offsetX) / tw));\n const startRow = Math.max(0, Math.floor((viewY - offsetY) / th));\n const endCol = Math.min(layer.width - 1, Math.floor((viewX - offsetX + viewW) / tw));\n const endRow = Math.min(layer.height - 1, Math.floor((viewY - offsetY + viewH) / th));\n\n for (let row = startRow; row <= endRow; row++) {\n for (let col = startCol; col <= endCol; col++) {\n const gid = getTileAt(layer, col, row);\n if (gid === 0) continue;\n\n const tileset = getTilesetForGid(this.map.tilesets, gid);\n if (!tileset) continue;\n\n const image = this._images.get(tileset.name);\n if (!image) continue;\n\n // An animated tile sources its current frame; flip bits still come from `gid`.\n let srcGid = gid;\n if (animate && tileset.animations !== undefined) {\n const anim = tileset.animations.get((gid & GID_FLIP_MASK) - tileset.firstGid);\n if (anim !== undefined) srcGid = tileset.firstGid + animatedLocalId(anim, time);\n }\n\n // Strips flip bits; writes into the reusable buffer, no per-tile allocation.\n const src = getTileSourceRectInto(tileset, srcGid, this._srcBuf);\n\n // Bit tests only — `gid & FLIP_H` is a negative Int32 when set, so compare to 0.\n const h = (gid & FLIP_H) !== 0;\n const v = (gid & FLIP_V) !== 0;\n const d = (gid & FLIP_D) !== 0;\n let flipX = h;\n let flipY = v;\n let rotation = 0;\n if (d) {\n rotation = !h && v ? -QUARTER_TURN : QUARTER_TURN;\n flipX = h && v;\n flipY = !h && !v;\n }\n\n // Centre anchor keeps a turned tile in its cell; the stored dstX/dstY\n // stay the cell's top-left. Positional slots — no per-tile object.\n batch.drawRaw(\n image,\n src.x,\n src.y,\n src.width,\n src.height,\n col * tw + offsetX + tw * 0.5,\n row * th + offsetY + th * 0.5,\n tw,\n th,\n effect,\n 0.5,\n 0.5,\n alpha,\n rotation,\n false,\n 'normal',\n flipX,\n flipY,\n );\n }\n }\n }\n}\n"],"mappings":";;;;;AACA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;ACHA,MAAa,gBAAgB;AAE7B,MAAMA,WAAS;AACf,MAAMC,WAAS;AACf,MAAMC,WAAS;;AAUf,SAAgB,cAAc,KAAqB;CACjD,OAAO,MAAM;AACf;;;;;;AAOA,SAAgB,eAAe,KAA4B;CACzD,OAAO;EACL,aAAa,MAAMF,cAAY;EAC/B,WAAW,MAAMC,cAAY;EAC7B,WAAW,MAAMC,cAAY;CAC/B;AACF;;AAkIA,SAAgB,kBACd,OACA,QACA,WACA,YACa;CACb,OAAO;EACL;EACA;EACA;EACA;EACA,QAAQ,CAAC;EACT,UAAU,CAAC;EACX,YAAY,CAAC;CACf;AACF;;A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,UACA,OACA,UACA,OACA,KACF;EACF;CAEJ;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["FLIP_H","FLIP_V","FLIP_D","AABB","SpriteBatch"],"sources":["../src/parse-error.ts","../src/tilemap-data.ts","../src/ldtk-parser.ts","../src/tiled-parser.ts","../src/tilemap-collider.ts","../src/tilemap-renderer.ts"],"sourcesContent":["/** Thrown by parseTiled/parseLDtk when a map uses an unsupported format or feature. */\nexport class TilemapParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'TilemapParseError';\n }\n}\n","import type { Rect } from '@flare-engine/math';\n\n/** Low 29 bits of a Tiled GID — Tiled stores flip state in the high 3 bits. */\nexport const GID_FLIP_MASK = 0x1fffffff;\n\nconst FLIP_H = 0x80000000;\nconst FLIP_V = 0x40000000;\nconst FLIP_D = 0x20000000;\n\n/** Flip state encoded in the high bits of a Tiled GID. */\nexport interface TileFlipFlags {\n horizontal: boolean;\n vertical: boolean;\n diagonal: boolean;\n}\n\n/** Strip the Tiled flip bits from a raw GID, returning the real global tile id. */\nexport function stripGidFlags(gid: number): number {\n return gid & GID_FLIP_MASK;\n}\n\n/**\n * Decode the Tiled flip bits encoded in the high bits of a raw GID.\n * Note: `gid & 0x80000000` yields a negative Int32 when the bit is set;\n * compare with `!== 0`, not `> 0`.\n */\nexport function decodeGidFlags(gid: number): TileFlipFlags {\n return {\n horizontal: (gid & FLIP_H) !== 0,\n vertical: (gid & FLIP_V) !== 0,\n diagonal: (gid & FLIP_D) !== 0,\n };\n}\n\n/** A layer of tiles in a grid. */\nexport interface TileLayer {\n readonly type: 'tile';\n /** Layer name. */\n name: string;\n /** Grid width in tiles. */\n width: number;\n /** Grid height in tiles. */\n height: number;\n /**\n * Flat array of tile GIDs (row-major, length = width * height). `Uint32Array`,\n * not `Float32Array` — a 24-bit mantissa cannot hold Tiled's flip-bit GIDs\n * (`0x80000000` and up). This is a type decision for bulk numeric data per the\n * repo convention, not a measured perf change.\n *\n * `readonly` like `SolidGrid.solid`: the array cannot be swapped out from under a\n * parsed map, but its cells stay writable (`layer.tiles[i] = gid`).\n */\n readonly tiles: Uint32Array;\n /** Visibility flag. */\n visible: boolean;\n /** Opacity (0–1). */\n opacity: number;\n /** Layer offset in pixels. */\n offsetX: number;\n offsetY: number;\n /** Custom properties. */\n properties: Record<string, unknown>;\n}\n\n/** An object in an object layer. */\nexport interface MapObject {\n /** Object ID. */\n id: number;\n /** Object name. */\n name: string;\n /** Object type/class. */\n type: string;\n /** Position in pixels. */\n x: number;\n y: number;\n /** Size in pixels. */\n width: number;\n height: number;\n /** Rotation in degrees. */\n rotation: number;\n /** Custom properties. */\n properties: Record<string, unknown>;\n}\n\n/** A layer of objects. */\nexport interface ObjectLayer {\n readonly type: 'object';\n /** Layer name. */\n name: string;\n /** Objects in the layer. */\n objects: MapObject[];\n /** Visibility flag. */\n visible: boolean;\n /** Opacity (0–1). */\n opacity: number;\n /** Custom properties. */\n properties: Record<string, unknown>;\n}\n\n/** Union of layer types. */\nexport type MapLayer = TileLayer | ObjectLayer;\n\n/**\n * A Tiled per-tile animation, parsed into flat per-frame arrays so a renderer\n * can resolve the current frame without allocating.\n */\nexport interface TileAnimation {\n /** Local tile id of each frame, in order. */\n frames: Uint32Array;\n /** Cumulative end time of each frame, in seconds (frame i covers [ends[i-1], ends[i])). */\n ends: Float64Array;\n /** Total cycle length, seconds. */\n duration: number;\n}\n\n/** Information about a tileset used in the map. */\nexport interface TilesetRef {\n /** First GID in this tileset. */\n firstGid: number;\n /** Tileset name. */\n name: string;\n /** Tile width in pixels. */\n tileWidth: number;\n /** Tile height in pixels. */\n tileHeight: number;\n /** Number of columns in the tileset image. */\n columns: number;\n /** Total tile count. */\n tileCount: number;\n /** Image source path (may need resolving). */\n image: string;\n /** Image width in pixels. */\n imageWidth: number;\n /** Image height in pixels. */\n imageHeight: number;\n /** Per-tile properties (indexed by local tile ID). */\n tileProperties: Map<number, Record<string, unknown>>;\n /** Tile IDs marked as solid/collision. */\n solidTiles: Set<number>;\n /** Tiled per-tile animations keyed by local tile id; absent when no tile is animated. */\n animations?: Map<number, TileAnimation>;\n}\n\n/** Complete parsed tilemap data — format-independent. */\nexport interface TilemapData {\n /** Map width in tiles. */\n width: number;\n /** Map height in tiles. */\n height: number;\n /** Tile width in pixels. */\n tileWidth: number;\n /** Tile height in pixels. */\n tileHeight: number;\n /** All layers in order. */\n layers: MapLayer[];\n /** Tilesets referenced by this map. */\n tilesets: TilesetRef[];\n /** Custom map properties. */\n properties: Record<string, unknown>;\n}\n\n/** Create an empty TilemapData. */\nexport function createTilemapData(\n width: number,\n height: number,\n tileWidth: number,\n tileHeight: number,\n): TilemapData {\n return {\n width,\n height,\n tileWidth,\n tileHeight,\n layers: [],\n tilesets: [],\n properties: {},\n };\n}\n\n/** Get a tile GID at a grid position from a tile layer. Returns 0 if out of bounds. */\nexport function getTileAt(layer: TileLayer, col: number, row: number): number {\n if (col < 0 || col >= layer.width || row < 0 || row >= layer.height) return 0;\n // The `?? 0` is unreachable at runtime (the bounds check above guarantees an\n // in-range index into a hole-free Uint32Array) — it satisfies noUncheckedIndexedAccess,\n // which types every typed-array index read as `number | undefined`.\n return layer.tiles[row * layer.width + col] ?? 0;\n}\n\n/**\n * Write a tile GID at a grid position in a tile layer; `getTileAt` and the\n * renderer read it back. Returns `true` when the cell was written, `false` (and\n * writes nothing) when the position is out of bounds or not an integer.\n * The GID is stored raw, Tiled flip bits included. Zero-alloc.\n */\nexport function setTileAt(layer: TileLayer, col: number, row: number, gid: number): boolean {\n if (col < 0 || col >= layer.width || row < 0 || row >= layer.height) return false;\n // A fractional col/row can still land on a whole index (row 0.5 on an even\n // width), which would write a different cell than the one named.\n if (!Number.isInteger(col) || !Number.isInteger(row)) return false;\n layer.tiles[row * layer.width + col] = gid;\n return true;\n}\n\n/** Get the tileset that owns a given GID. Handles Tiled flip bits in the high bits. */\nexport function getTilesetForGid(tilesets: TilesetRef[], gid: number): TilesetRef | undefined {\n const id = gid & GID_FLIP_MASK;\n // Tilesets are ordered by firstGid; find the last one where firstGid <= id\n let result: TilesetRef | undefined;\n for (const ts of tilesets) {\n if (ts.firstGid <= id) {\n result = ts;\n } else {\n break;\n }\n }\n return result;\n}\n\n/** Compute the source rect in a tileset image for a given GID into `out`. Strips Tiled flip bits. Zero-alloc. */\nexport function getTileSourceRectInto(tileset: TilesetRef, gid: number, out: Rect): Rect {\n const localId = (gid & GID_FLIP_MASK) - tileset.firstGid;\n const col = localId % tileset.columns;\n const row = Math.floor(localId / tileset.columns);\n out.x = col * tileset.tileWidth;\n out.y = row * tileset.tileHeight;\n out.width = tileset.tileWidth;\n out.height = tileset.tileHeight;\n return out;\n}\n\n/** Compute the source rect in a tileset image for a given GID. Strips Tiled flip bits. */\nexport function getTileSourceRect(tileset: TilesetRef, gid: number): Rect {\n return getTileSourceRectInto(tileset, gid, { x: 0, y: 0, width: 0, height: 0 });\n}\n","import { TilemapParseError } from './parse-error.js';\nimport type { MapObject, ObjectLayer, TileLayer, TilemapData, TilesetRef } from './tilemap-data.js';\nimport { createTilemapData } from './tilemap-data.js';\n\n// ----- LDtk JSON types -----\n\ninterface LDtkFieldInstance {\n __identifier: string;\n __value: unknown;\n __type: string;\n}\n\ninterface LDtkEntityInstance {\n __identifier: string;\n __grid: [number, number];\n __pivot: [number, number];\n __tile?: { x: number; y: number; w: number; h: number };\n iid: string;\n width: number;\n height: number;\n px: [number, number];\n fieldInstances: LDtkFieldInstance[];\n}\n\ninterface LDtkTileInstance {\n px: [number, number];\n src: [number, number];\n f: number; // flip flags\n t: number; // tile ID\n}\n\ninterface LDtkLayerInstance {\n __identifier: string;\n __type: string;\n __cWid: number;\n __cHei: number;\n __gridSize: number;\n __tilesetDefUid?: number;\n __tilesetRelPath?: string;\n visible: boolean;\n __opacity: number;\n intGridCsv?: number[];\n // Real LDtk output always emits both arrays on every layer instance — only\n // one is ever populated per __type (an AutoLayer's gridTiles is always []).\n // Required (not optional) so a fixture omitting the unused one, as every\n // fixture here did before F057, cannot pass this module's own types.\n gridTiles: LDtkTileInstance[];\n autoLayerTiles: LDtkTileInstance[];\n entityInstances?: LDtkEntityInstance[];\n}\n\ninterface LDtkTilesetDef {\n uid: number;\n identifier: string;\n relPath: string;\n pxWid: number;\n pxHei: number;\n tileGridSize: number;\n __cWid: number;\n __cHei: number;\n}\n\ninterface LDtkLevel {\n identifier: string;\n uid: number;\n pxWid: number;\n pxHei: number;\n worldX: number;\n worldY: number;\n layerInstances?: LDtkLayerInstance[];\n fieldInstances?: LDtkFieldInstance[];\n}\n\ninterface LDtkJSON {\n defaultGridSize: number;\n externalLevels?: boolean;\n defs: {\n tilesets: LDtkTilesetDef[];\n };\n levels: LDtkLevel[];\n}\n\nexport interface ParseLDtkOptions {\n /** Predicate deciding whether an IntGrid value marks a solid cell. Default: value > 0. */\n intGridSolid?: (value: number) => boolean;\n}\n\nexport interface LDtkEntity {\n /** LDtk entity identifier (its type, e.g. \"Player\") — the key you switch on to decide what to spawn. */\n id: string;\n /** Entity position in pixels (LDtk px, pivot-adjusted per the parser convention). */\n x: number;\n y: number;\n /** Entity box size in pixels. */\n width: number;\n height: number;\n /** Custom field instances, keyed by field identifier. */\n fields: Record<string, unknown>;\n}\n\n/**\n * Extract every LDtk entity from a parsed map as a flat, spawn-ready list —\n * the LDtk-entity → ECS spawn convention. Walks all object layers; tile layers are skipped.\n */\nexport function parseLDtkEntities(map: TilemapData): LDtkEntity[] {\n const entities: LDtkEntity[] = [];\n for (const layer of map.layers) {\n if (layer.type !== 'object') continue;\n for (const obj of layer.objects) {\n entities.push({\n id: obj.type,\n x: obj.x,\n y: obj.y,\n width: obj.width,\n height: obj.height,\n fields: obj.properties,\n });\n }\n }\n return entities;\n}\n\n/**\n * Parse an LDtk JSON project into an array of TilemapData (one per level).\n * Returns all levels with their tile and entity layers.\n * Throws TilemapParseError for unsupported formats (externalLevels, invalid input).\n */\nexport function parseLDtk(json: unknown, options: ParseLDtkOptions = {}): TilemapData[] {\n if (\n !json ||\n typeof json !== 'object' ||\n !Array.isArray((json as Record<string, unknown>).levels) ||\n !(json as Record<string, unknown>).defs ||\n !Array.isArray(((json as Record<string, unknown>).defs as Record<string, unknown>).tilesets)\n ) {\n throw new TilemapParseError(\n 'parseLDtk: input is not an LDtk project JSON (missing defs.tilesets or levels).',\n );\n }\n\n const data = json as LDtkJSON;\n\n if (data.externalLevels === true) {\n throw new TilemapParseError(\n 'parseLDtk: projects with \"Save levels to separate files\" (externalLevels) are not supported. Disable it in LDtk ▸ Project settings and re-save.',\n );\n }\n\n const isSolid = options.intGridSolid ?? ((v) => v > 0);\n\n const tilesetDefs = new Map<number, LDtkTilesetDef>();\n for (const ts of data.defs.tilesets) {\n tilesetDefs.set(ts.uid, ts);\n }\n\n const results: TilemapData[] = [];\n\n for (const level of data.levels) {\n const gridSize = data.defaultGridSize;\n const mapWidth = Math.ceil(level.pxWid / gridSize);\n const mapHeight = Math.ceil(level.pxHei / gridSize);\n const map = createTilemapData(mapWidth, mapHeight, gridSize, gridSize);\n\n if (level.fieldInstances) {\n for (const field of level.fieldInstances) {\n map.properties[field.__identifier] = field.__value;\n }\n }\n\n // Pass 1: collect tile-layer tileset uids, sort ascending, assign deterministic firstGids.\n // Tilesets must be sorted by firstGid (ascending) for getTilesetForGid's early-break.\n const firstGidByUid = new Map<number, number>();\n let nextFirstGid = 1;\n\n if (level.layerInstances) {\n const usedTileUids = new Set<number>();\n for (const layerInst of level.layerInstances) {\n if (\n (layerInst.__type === 'Tiles' || layerInst.__type === 'AutoLayer') &&\n layerInst.__tilesetDefUid !== undefined\n ) {\n usedTileUids.add(layerInst.__tilesetDefUid);\n }\n }\n\n const sortedUids = Array.from(usedTileUids).sort((a, b) => a - b);\n for (const uid of sortedUids) {\n const def = tilesetDefs.get(uid);\n if (!def) continue;\n const columns = def.__cWid;\n const tileCount = def.__cWid * def.__cHei;\n firstGidByUid.set(uid, nextFirstGid);\n const ref: TilesetRef = {\n firstGid: nextFirstGid,\n name: def.identifier,\n tileWidth: def.tileGridSize,\n tileHeight: def.tileGridSize,\n columns,\n tileCount,\n image: def.relPath,\n imageWidth: def.pxWid,\n imageHeight: def.pxHei,\n tileProperties: new Map(),\n solidTiles: new Set(),\n };\n map.tilesets.push(ref);\n nextFirstGid += tileCount;\n }\n }\n\n // Pass 2: parse layers in reverse order (LDtk stores top-first; emit bottom-first).\n if (level.layerInstances) {\n for (let i = level.layerInstances.length - 1; i >= 0; i--) {\n const layerInst = level.layerInstances[i]!;\n\n if (layerInst.__type === 'IntGrid') {\n // IntGrid layers are treated as collision grids; IntGrid layers that also\n // carry auto-render tiles keep collision only (visual auto-tiles are M4 scope).\n const csv = layerInst.intGridCsv;\n const cellCount = layerInst.__cWid * layerInst.__cHei;\n const tiles = new Uint32Array(cellCount);\n const intFirstGid = nextFirstGid;\n let maxLocal = 0;\n let hasNonZero = false;\n const solidSet = new Set<number>();\n\n if (csv) {\n for (let j = 0; j < csv.length; j++) {\n const v = csv[j] ?? 0;\n if (v > 0) {\n hasNonZero = true;\n const localId = v - 1;\n if (localId > maxLocal) maxLocal = localId;\n tiles[j] = intFirstGid + localId;\n if (isSolid(v)) solidSet.add(localId);\n }\n }\n }\n\n if (hasNonZero) {\n const tileCount = maxLocal + 1;\n map.tilesets.push({\n firstGid: intFirstGid,\n name: layerInst.__identifier,\n tileWidth: layerInst.__gridSize,\n tileHeight: layerInst.__gridSize,\n columns: tileCount,\n tileCount,\n image: '',\n imageWidth: 0,\n imageHeight: 0,\n tileProperties: new Map(),\n solidTiles: solidSet,\n });\n nextFirstGid += tileCount;\n }\n\n map.layers.push({\n type: 'tile',\n name: layerInst.__identifier,\n width: layerInst.__cWid,\n height: layerInst.__cHei,\n tiles,\n visible: layerInst.visible,\n opacity: layerInst.__opacity,\n offsetX: 0,\n offsetY: 0,\n properties: {},\n });\n } else if (layerInst.__type === 'Tiles' || layerInst.__type === 'AutoLayer') {\n const firstGid = firstGidByUid.get(layerInst.__tilesetDefUid ?? -1) ?? 1;\n map.layers.push(parseTilesLayer(layerInst, mapWidth, mapHeight, gridSize, firstGid));\n } else if (layerInst.__type === 'Entities') {\n map.layers.push(parseEntitiesLayer(layerInst));\n }\n }\n }\n\n results.push(map);\n }\n\n return results;\n}\n\nfunction parseTilesLayer(\n layer: LDtkLayerInstance,\n mapWidth: number,\n mapHeight: number,\n gridSize: number,\n firstGid: number,\n): TileLayer {\n const tiles = new Uint32Array(mapWidth * mapHeight);\n // An AutoLayer's tiles live in autoLayerTiles; its gridTiles is always [].\n // `gridTiles ?? autoLayerTiles` picked the empty gridTiles for every\n // AutoLayer, since `??` only falls through on null/undefined, never on `[]`\n // — select by __type instead, which is the field LDtk itself keys on.\n const tileInstances = layer.__type === 'AutoLayer' ? layer.autoLayerTiles : layer.gridTiles;\n\n for (const ti of tileInstances) {\n const col = Math.floor(ti.px[0] / gridSize);\n const row = Math.floor(ti.px[1] / gridSize);\n if (col >= 0 && col < mapWidth && row >= 0 && row < mapHeight) {\n tiles[row * mapWidth + col] = firstGid + ti.t;\n }\n }\n\n return {\n type: 'tile',\n name: layer.__identifier,\n width: mapWidth,\n height: mapHeight,\n tiles,\n visible: layer.visible,\n opacity: layer.__opacity,\n offsetX: 0,\n offsetY: 0,\n properties: {},\n };\n}\n\nfunction parseEntitiesLayer(layer: LDtkLayerInstance): ObjectLayer {\n const objects: MapObject[] = (layer.entityInstances ?? []).map((ent, idx) => {\n const props: Record<string, unknown> = {};\n for (const field of ent.fieldInstances) {\n props[field.__identifier] = field.__value;\n }\n return {\n id: idx + 1,\n name: ent.__identifier,\n type: ent.__identifier,\n x: ent.px[0],\n y: ent.px[1],\n width: ent.width,\n height: ent.height,\n rotation: 0,\n properties: props,\n };\n });\n\n return {\n type: 'object',\n name: layer.__identifier,\n objects,\n visible: layer.visible,\n opacity: layer.__opacity,\n properties: {},\n };\n}\n","import { TilemapParseError } from './parse-error.js';\nimport type {\n MapLayer,\n MapObject,\n ObjectLayer,\n TileAnimation,\n TileLayer,\n TilemapData,\n TilesetRef,\n} from './tilemap-data.js';\nimport { createTilemapData } from './tilemap-data.js';\n\n// ----- Tiled JSON types (.tmj format) -----\n\ninterface TiledProperty {\n name: string;\n type: string;\n value: unknown;\n}\n\ninterface TiledTileLayer {\n type: 'tilelayer';\n name: string;\n width: number;\n height: number;\n data: number[] | string;\n encoding?: string;\n compression?: string;\n chunks?: unknown[];\n visible: boolean;\n opacity: number;\n offsetx?: number;\n offsety?: number;\n properties?: TiledProperty[];\n}\n\ninterface TiledObject {\n id: number;\n name: string;\n type?: string;\n class?: string;\n x: number;\n y: number;\n width: number;\n height: number;\n rotation: number;\n properties?: TiledProperty[];\n}\n\ninterface TiledObjectLayer {\n type: 'objectgroup';\n name: string;\n objects: TiledObject[];\n visible: boolean;\n opacity: number;\n properties?: TiledProperty[];\n}\n\ntype TiledLayer = TiledTileLayer | TiledObjectLayer;\n\ninterface TiledAnimationFrame {\n tileid: number;\n /** Milliseconds. */\n duration: number;\n}\n\ninterface TiledTile {\n id: number;\n properties?: TiledProperty[];\n type?: string;\n class?: string;\n animation?: TiledAnimationFrame[];\n}\n\ninterface TiledTileset {\n firstgid: number;\n name: string;\n tilewidth: number;\n tileheight: number;\n columns: number;\n tilecount: number;\n image: string;\n imagewidth: number;\n imageheight: number;\n tiles?: TiledTile[];\n properties?: TiledProperty[];\n source?: string;\n}\n\ninterface TiledMapJSON {\n width: number;\n height: number;\n tilewidth: number;\n tileheight: number;\n orientation: string;\n infinite?: boolean;\n layers: TiledLayer[];\n tilesets: TiledTileset[];\n properties?: TiledProperty[];\n}\n\n/** Convert Tiled properties array to a Record. */\nfunction parseProperties(props?: TiledProperty[]): Record<string, unknown> {\n if (!props || props.length === 0) return {};\n const result: Record<string, unknown> = {};\n for (const p of props) {\n result[p.name] = p.value;\n }\n return result;\n}\n\n/**\n * Build a tile's Tiled animation (frame durations in ms) into cumulative seconds.\n * Returns `undefined` for an empty animation or one whose durations sum to 0 —\n * such a tile draws as authored.\n */\nfunction parseTileAnimation(ts: TiledTileset, tile: TiledTile): TileAnimation | undefined {\n const source = tile.animation;\n if (source === undefined || source.length === 0) return undefined;\n const frames = new Uint32Array(source.length);\n const ends = new Float64Array(source.length);\n // Summed in ms and divided once per frame so integer-ms inputs give exact seconds.\n let totalMs = 0;\n for (let i = 0; i < source.length; i++) {\n const frame = source[i]!;\n const tileid = frame.tileid;\n const duration = frame.duration;\n if (!Number.isInteger(tileid) || tileid < 0 || tileid >= ts.tilecount) {\n throw new TilemapParseError(\n `parseTiled: tileset \"${ts.name}\" tile ${tile.id} animation frame ${i} has tileid ${tileid} — expected an integer in [0, ${ts.tilecount}).`,\n );\n }\n if (!Number.isFinite(duration) || duration < 0) {\n throw new TilemapParseError(\n `parseTiled: tileset \"${ts.name}\" tile ${tile.id} animation frame ${i} has duration ${duration} — expected a finite number of milliseconds >= 0.`,\n );\n }\n totalMs += duration;\n frames[i] = tileid;\n ends[i] = totalMs / 1000;\n }\n if (totalMs === 0) return undefined;\n return { frames, ends, duration: totalMs / 1000 };\n}\n\n/**\n * Parse a Tiled .tmj (JSON) map into TilemapData.\n * Supports orthogonal maps with CSV tile layers and object layers.\n * Throws TilemapParseError for unsupported formats (infinite, non-orthogonal,\n * external tilesets, base64/compressed/chunked layer data).\n */\nexport function parseTiled(json: unknown): TilemapData {\n if (\n !json ||\n typeof json !== 'object' ||\n typeof (json as Record<string, unknown>).width !== 'number' ||\n typeof (json as Record<string, unknown>).height !== 'number' ||\n !Array.isArray((json as Record<string, unknown>).layers) ||\n !Array.isArray((json as Record<string, unknown>).tilesets)\n ) {\n throw new TilemapParseError(\n 'parseTiled: input is not a Tiled map JSON (missing width/height/layers/tilesets).',\n );\n }\n\n const data = json as TiledMapJSON;\n\n if (data.infinite === true) {\n throw new TilemapParseError(\n 'parseTiled: infinite maps are not supported. In Tiled: Map ▸ Map Properties ▸ set \"Infinite\" to false, then re-export.',\n );\n }\n if (data.orientation && data.orientation !== 'orthogonal') {\n throw new TilemapParseError(\n `parseTiled: orientation \"${data.orientation}\" is not supported — only orthogonal maps are supported.`,\n );\n }\n\n const map = createTilemapData(data.width, data.height, data.tilewidth, data.tileheight);\n map.properties = parseProperties(data.properties);\n\n // Parse tilesets\n for (const ts of data.tilesets) {\n if (ts.source !== undefined) {\n throw new TilemapParseError(\n `parseTiled: external tileset \"${ts.source}\" is not supported. Embed tilesets on export (Tiled ▸ Map ▸ \"Embed tilesets\") or run it through \\`flare tiled-to-flare\\` (which embeds tilesets by default).`,\n );\n }\n\n const tileProperties = new Map<number, Record<string, unknown>>();\n const solidTiles = new Set<number>();\n let animations: Map<number, TileAnimation> | undefined;\n\n if (ts.tiles) {\n for (const tile of ts.tiles) {\n const props = parseProperties(tile.properties);\n if (Object.keys(props).length > 0) {\n tileProperties.set(tile.id, props);\n }\n // Mark as solid if it has a \"collision\" or \"solid\" property, or type/class is \"solid\"\n const tileType = tile.type ?? tile.class ?? '';\n if (tileType === 'solid' || props.solid === true || props.collision === true) {\n solidTiles.add(tile.id);\n }\n const animation = parseTileAnimation(ts, tile);\n if (animation !== undefined) {\n animations ??= new Map();\n animations.set(tile.id, animation);\n }\n }\n }\n\n const ref: TilesetRef = {\n firstGid: ts.firstgid,\n name: ts.name,\n tileWidth: ts.tilewidth,\n tileHeight: ts.tileheight,\n columns: ts.columns,\n tileCount: ts.tilecount,\n image: ts.image,\n imageWidth: ts.imagewidth,\n imageHeight: ts.imageheight,\n tileProperties,\n solidTiles,\n };\n if (animations !== undefined) ref.animations = animations;\n map.tilesets.push(ref);\n }\n\n // Sort tilesets by firstGid\n map.tilesets.sort((a, b) => a.firstGid - b.firstGid);\n\n // Parse layers\n for (const layer of data.layers) {\n map.layers.push(parseLayer(layer));\n }\n\n return map;\n}\n\nfunction parseLayer(layer: TiledLayer): MapLayer {\n if (layer.type === 'tilelayer') return parseTileLayer(layer);\n if (layer.type === 'objectgroup') return parseObjectLayer(layer);\n const l = layer as { type: string; name?: string };\n throw new TilemapParseError(\n `parseTiled: layer \"${l.name ?? ''}\" has unsupported type \"${l.type}\". Only tilelayer and objectgroup are supported — flatten group layers and remove image layers before export.`,\n );\n}\n\nfunction parseTileLayer(layer: TiledTileLayer): TileLayer {\n if (\n (layer.encoding !== undefined && layer.encoding !== 'csv') ||\n layer.compression !== undefined ||\n layer.chunks !== undefined\n ) {\n throw new TilemapParseError(\n 'parseTiled: base64/compressed/chunked (infinite) layer data is not supported. In Tiled export options set Tile Layer Format to \"CSV\".',\n );\n }\n if (typeof layer.data === 'string') {\n throw new TilemapParseError(\n 'parseTiled: base64/compressed/chunked (infinite) layer data is not supported. In Tiled export options set Tile Layer Format to \"CSV\".',\n );\n }\n // layer.data is number[] here — Uint32Array.from preserves flip-bit GIDs\n // (values up to 0xffffffff), unlike a Float32Array's 24-bit mantissa.\n return {\n type: 'tile',\n name: layer.name,\n width: layer.width,\n height: layer.height,\n tiles: Uint32Array.from(layer.data),\n visible: layer.visible,\n opacity: layer.opacity,\n offsetX: layer.offsetx ?? 0,\n offsetY: layer.offsety ?? 0,\n properties: parseProperties(layer.properties),\n };\n}\n\nfunction parseObjectLayer(layer: TiledObjectLayer): ObjectLayer {\n const objects: MapObject[] = layer.objects.map((obj) => ({\n id: obj.id,\n name: obj.name,\n type: obj.type ?? obj.class ?? '',\n x: obj.x,\n y: obj.y,\n width: obj.width,\n height: obj.height,\n rotation: obj.rotation,\n properties: parseProperties(obj.properties),\n }));\n\n return {\n type: 'object',\n name: layer.name,\n objects,\n visible: layer.visible,\n opacity: layer.opacity,\n properties: parseProperties(layer.properties),\n };\n}\n","import type { AABBShape } from '@flare-engine/physics';\nimport { AABB } from '@flare-engine/physics';\nimport type { TileLayer, TilemapData, TilesetRef } from './tilemap-data.js';\nimport { GID_FLIP_MASK, getTilesetForGid } from './tilemap-data.js';\n\n/** A collision body extracted from a solid tile. */\nexport interface TileCollider {\n /** World position of the tile center. */\n x: number;\n y: number;\n /** AABB collision shape. */\n shape: AABBShape;\n /** Grid column. */\n col: number;\n /** Grid row. */\n row: number;\n /** The tile GID (flip bits stripped — AABB is symmetric, downstream lookups want the real id). */\n gid: number;\n}\n\n/**\n * Extract collision shapes from solid tiles in a tilemap.\n * A tile is considered solid if its tileset marks the local tile ID as solid.\n *\n * @param map The parsed tilemap data.\n * @param layerName Optional: only extract from this layer. If omitted, extracts from all tile layers.\n * @returns Array of TileCollider bodies.\n */\nexport function extractColliders(map: TilemapData, layerName?: string): TileCollider[] {\n const colliders: TileCollider[] = [];\n const tw = map.tileWidth;\n const th = map.tileHeight;\n\n for (const layer of map.layers) {\n if (layer.type !== 'tile') continue;\n if (layerName !== undefined && layer.name !== layerName) continue;\n\n extractFromLayer(layer, map.tilesets, tw, th, colliders);\n }\n\n return colliders;\n}\n\nfunction extractFromLayer(\n layer: TileLayer,\n tilesets: TilesetRef[],\n tw: number,\n th: number,\n out: TileCollider[],\n): void {\n for (let row = 0; row < layer.height; row++) {\n for (let col = 0; col < layer.width; col++) {\n const gid = layer.tiles[row * layer.width + col] ?? 0;\n if (gid === 0) continue;\n\n const tileset = getTilesetForGid(tilesets, gid);\n if (!tileset) continue;\n\n const localId = (gid & GID_FLIP_MASK) - tileset.firstGid;\n if (!tileset.solidTiles.has(localId)) continue;\n\n out.push({\n x: col * tw + tw * 0.5 + layer.offsetX,\n y: row * th + th * 0.5 + layer.offsetY,\n shape: AABB(tw, th),\n col,\n row,\n gid: gid & GID_FLIP_MASK,\n });\n }\n }\n}\n","import type { SkImageLike } from '@flare-engine/assets';\nimport type { Rect } from '@flare-engine/math';\nimport type { AnySpriteEffect, Camera2D } from '@flare-engine/render';\nimport { SpriteBatch } from '@flare-engine/render';\nimport type { TileAnimation, TileLayer, TilemapData, TilesetRef } from './tilemap-data.js';\nimport {\n GID_FLIP_MASK,\n getTileAt,\n getTileSourceRectInto,\n getTilesetForGid,\n} from './tilemap-data.js';\n\n// Tiled GID flag bits (kept module-private; tilemap-data.ts owns the public mask).\nconst FLIP_H = 0x80000000;\nconst FLIP_V = 0x40000000;\nconst FLIP_D = 0x20000000;\nconst QUARTER_TURN = Math.PI / 2;\n\n/**\n * Per-draw options for `TilemapRenderer.drawInto` / `draw`.\n *\n * `effect` is set on every queued tile command. Batch runs key on the effect\n * by reference, so one shared instance (e.g. an ambient `tint()`) keeps every\n * tile — and any sprite drawn with the same instance — in a single run.\n * `alphaScale` multiplies each layer's own `opacity` (default 1).\n * `time` (seconds, e.g. the clock's elapsed) advances Tiled tile animations\n * parsed onto `TilesetRef.animations`; it wraps in both directions. Without\n * it (or when non-finite) every tile draws as authored.\n */\nexport interface TilemapDrawOptions {\n effect?: AnySpriteEffect;\n alphaScale?: number;\n time?: number;\n}\n\n/** Local tile id of the frame an animation shows at `time` (seconds, finite). */\nfunction animatedLocalId(anim: TileAnimation, time: number): number {\n let t = time % anim.duration;\n if (t < 0) t += anim.duration;\n const ends = anim.ends;\n const last = ends.length - 1;\n let i = 0;\n // A frame boundary belongs to the next frame; ends[last] === duration > t stops the scan.\n while (i < last && t >= (ends[i] ?? 0)) i++;\n // The `?? 0` is unreachable (i <= last < frames.length) — it satisfies noUncheckedIndexedAccess.\n return anim.frames[i] ?? 0;\n}\n\n/**\n * TilemapRenderer — draws a tilemap with viewport culling.\n * Only tiles visible to the camera are submitted to the SpriteBatch.\n */\nexport class TilemapRenderer {\n /** The tilemap data to render. */\n readonly map: TilemapData;\n\n /** SpriteBatch used for batched tile rendering. */\n readonly batch: SpriteBatch;\n\n /** Map from tileset name → SkImage. Set via setTilesetImage(). */\n private _images = new Map<string, SkImageLike>();\n\n /** Images in `map.tilesets` order, refreshed from `_images` at the start of each draw. */\n private _tilesetImages: (SkImageLike | undefined)[] = [];\n\n /** Reusable bounds rect — avoids per-frame allocation from camera.getBounds(). */\n private _boundsBuf: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n /** Reusable source rect — avoids a per-tile allocation from getTileSourceRect. */\n private _srcBuf: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n constructor(map: TilemapData) {\n this.map = map;\n this.batch = new SpriteBatch();\n }\n\n /** Associate a loaded image with a tileset by name. */\n setTilesetImage(tilesetName: string, image: SkImageLike): void {\n this._images.set(tilesetName, image);\n }\n\n /**\n * Queue visible tile layers into a caller-owned `batch` using the camera for\n * culling. Does NOT flush — the caller owns the single flush so tiles z-order\n * under sprites. Zero-alloc: reuses the internal bounds buffer.\n *\n * Each tile's `alpha` is `layer.opacity * opts.alphaScale`; `opts.effect`\n * is applied to every tile; `opts.time` picks each animated tile's frame\n * (see `TilemapDrawOptions`).\n */\n drawInto(camera: Camera2D, batch: SpriteBatch, opts?: TilemapDrawOptions): void {\n const bounds = camera.getBoundsInto(this._boundsBuf);\n const tw = this.map.tileWidth;\n const th = this.map.tileHeight;\n const effect = opts?.effect;\n const alphaScale = opts?.alphaScale ?? 1;\n // NaN stands for \"no time\": the layer pass animates only when `time` is finite.\n const time = opts?.time ?? Number.NaN;\n\n const tilesets = this.map.tilesets;\n const images = this._tilesetImages;\n images.length = tilesets.length;\n for (let i = 0; i < tilesets.length; i++) {\n const tileset = tilesets[i];\n if (tileset !== undefined) images[i] = this._images.get(tileset.name);\n }\n\n for (const layer of this.map.layers) {\n if (layer.type !== 'tile' || !layer.visible) continue;\n this._drawTileLayer(\n layer,\n bounds.x,\n bounds.y,\n bounds.width,\n bounds.height,\n tw,\n th,\n batch,\n effect,\n layer.opacity * alphaScale,\n time,\n );\n }\n }\n\n /**\n * Draw visible tile layers using the camera for culling.\n * Call `flush` on a callback to issue the actual draw calls.\n * Delegates to `drawInto` so culling and queuing logic live in one place;\n * `opts` is threaded through unchanged.\n */\n draw(camera: Camera2D, flush: (batch: SpriteBatch) => void, opts?: TilemapDrawOptions): void {\n this.drawInto(camera, this.batch, opts);\n flush(this.batch);\n }\n\n // Tiled flip bits: H/V become the batch's flipX/flipY; the diagonal bit is a\n // quarter turn about the tile centre composed with the flip Tiled defines\n // (D+H = 90° CW, D+V = 90° CCW, D = flipY + CW, D+H+V = flipX + CW).\n private _drawTileLayer(\n layer: TileLayer,\n viewX: number,\n viewY: number,\n viewW: number,\n viewH: number,\n tw: number,\n th: number,\n batch: SpriteBatch,\n effect: AnySpriteEffect | undefined,\n alpha: number,\n time: number,\n ): void {\n const offsetX = layer.offsetX;\n const offsetY = layer.offsetY;\n const animate = Number.isFinite(time);\n const tilesets = this.map.tilesets;\n const images = this._tilesetImages;\n\n // The current run: `tileset` and `image` own every stripped gid in [runLo, runHi).\n let tileset: TilesetRef | undefined;\n let image: SkImageLike | undefined;\n let runLo = 1;\n let runHi = 0;\n\n // Calculate visible tile range (clamped to layer bounds)\n const startCol = Math.max(0, Math.floor((viewX - offsetX) / tw));\n const startRow = Math.max(0, Math.floor((viewY - offsetY) / th));\n const endCol = Math.min(layer.width - 1, Math.floor((viewX - offsetX + viewW) / tw));\n const endRow = Math.min(layer.height - 1, Math.floor((viewY - offsetY + viewH) / th));\n\n for (let row = startRow; row <= endRow; row++) {\n for (let col = startCol; col <= endCol; col++) {\n const gid = getTileAt(layer, col, row);\n if (gid === 0) continue;\n\n const id = gid & GID_FLIP_MASK;\n if (id < runLo || id >= runHi) {\n tileset = getTilesetForGid(tilesets, id);\n image = undefined;\n runLo = 1;\n runHi = 0;\n if (tileset !== undefined) {\n // The run covers only gids the front-to-back walk maps to this tileset again:\n // at or above every firstGid up to it, below the next one and its own end.\n let index = 0;\n runLo = tileset.firstGid;\n for (let ts = tilesets[0]; ts !== undefined && ts !== tileset; ts = tilesets[++index]) {\n if (ts.firstGid > runLo) runLo = ts.firstGid;\n }\n image = images[index];\n runHi = tileset.firstGid + tileset.tileCount;\n const next = tilesets[index + 1];\n if (next !== undefined && next.firstGid < runHi) runHi = next.firstGid;\n }\n }\n if (!tileset) continue;\n if (!image) continue;\n\n // An animated tile sources its current frame; flip bits still come from `gid`.\n let srcGid = gid;\n if (animate && tileset.animations !== undefined) {\n const anim = tileset.animations.get(id - tileset.firstGid);\n if (anim !== undefined) srcGid = tileset.firstGid + animatedLocalId(anim, time);\n }\n\n // Strips flip bits; writes into the reusable buffer, no per-tile allocation.\n const src = getTileSourceRectInto(tileset, srcGid, this._srcBuf);\n\n // Bit tests only — `gid & FLIP_H` is a negative Int32 when set, so compare to 0.\n const h = (gid & FLIP_H) !== 0;\n const v = (gid & FLIP_V) !== 0;\n const d = (gid & FLIP_D) !== 0;\n let flipX = h;\n let flipY = v;\n let rotation = 0;\n if (d) {\n rotation = !h && v ? -QUARTER_TURN : QUARTER_TURN;\n flipX = h && v;\n flipY = !h && !v;\n }\n\n // Centre anchor keeps a turned tile in its cell; the stored dstX/dstY\n // stay the cell's top-left. Positional slots — no per-tile object.\n batch.drawRaw(\n image,\n src.x,\n src.y,\n src.width,\n src.height,\n col * tw + offsetX + tw * 0.5,\n row * th + offsetY + th * 0.5,\n tw,\n th,\n effect,\n 0.5,\n 0.5,\n alpha,\n rotation,\n false,\n 'normal',\n flipX,\n flipY,\n );\n }\n }\n }\n}\n"],"mappings":";;;;;AACA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;ACHA,MAAa,gBAAgB;AAE7B,MAAMA,WAAS;AACf,MAAMC,WAAS;AACf,MAAMC,WAAS;;AAUf,SAAgB,cAAc,KAAqB;CACjD,OAAO,MAAM;AACf;;;;;;AAOA,SAAgB,eAAe,KAA4B;CACzD,OAAO;EACL,aAAa,MAAMF,cAAY;EAC/B,WAAW,MAAMC,cAAY;EAC7B,WAAW,MAAMC,cAAY;CAC/B;AACF;;AAkIA,SAAgB,kBACd,OACA,QACA,WACA,YACa;CACb,OAAO;EACL;EACA;EACA;EACA;EACA,QAAQ,CAAC;EACT,UAAU,CAAC;EACX,YAAY,CAAC;CACf;AACF;;AAGA,SAAgB,UAAU,OAAkB,KAAa,KAAqB;CAC5E,IAAI,MAAM,KAAK,OAAO,MAAM,SAAS,MAAM,KAAK,OAAO,MAAM,QAAQ,OAAO;CAI5E,OAAO,MAAM,MAAM,MAAM,MAAM,QAAQ,QAAQ;AACjD;;;;;;;AAQA,SAAgB,UAAU,OAA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;KACnC,MAAM,OAAO,SAAS,QAAQ;KAC9B,IAAI,SAAS,KAAA,KAAa,KAAK,WAAW,OAAO,QAAQ,KAAK;IAChE;GACF;GACA,IAAI,CAAC,SAAS;GACd,IAAI,CAAC,OAAO;GAGZ,IAAI,SAAS;GACb,IAAI,WAAW,QAAQ,eAAe,KAAA,GAAW;IAC/C,MAAM,OAAO,QAAQ,WAAW,IAAI,KAAK,QAAQ,QAAQ;IACzD,IAAI,SAAS,KAAA,GAAW,SAAS,QAAQ,WAAW,gBAAgB,MAAM,IAAI;GAChF;GAGA,MAAM,MAAM,sBAAsB,SAAS,QAAQ,KAAK,OAAO;GAG/D,MAAM,KAAK,MAAM,YAAY;GAC7B,MAAM,KAAK,MAAM,YAAY;GAC7B,MAAM,KAAK,MAAM,YAAY;GAC7B,IAAI,QAAQ;GACZ,IAAI,QAAQ;GACZ,IAAI,WAAW;GACf,IAAI,GAAG;IACL,WAAW,CAAC,KAAK,IAAI,CAAC,eAAe;IACrC,QAAQ,KAAK;IACb,QAAQ,CAAC,KAAK,CAAC;GACjB;GAIA,MAAM,QACJ,OACA,IAAI,GACJ,IAAI,GACJ,IAAI,OACJ,IAAI,QACJ,MAAM,KAAK,UAAU,KAAK,IAC1B,MAAM,KAAK,UAAU,KAAK,IAC1B,IACA,IACA,QACA,IACA,IACA,OACA,UACA,OACA,UACA,OACA,KACF;EACF;CAEJ;AACF"}
|
package/dist/index.mjs
CHANGED
|
@@ -47,6 +47,18 @@ function getTileAt(layer, col, row) {
|
|
|
47
47
|
if (col < 0 || col >= layer.width || row < 0 || row >= layer.height) return 0;
|
|
48
48
|
return layer.tiles[row * layer.width + col] ?? 0;
|
|
49
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Write a tile GID at a grid position in a tile layer; `getTileAt` and the
|
|
52
|
+
* renderer read it back. Returns `true` when the cell was written, `false` (and
|
|
53
|
+
* writes nothing) when the position is out of bounds or not an integer.
|
|
54
|
+
* The GID is stored raw, Tiled flip bits included. Zero-alloc.
|
|
55
|
+
*/
|
|
56
|
+
function setTileAt(layer, col, row, gid) {
|
|
57
|
+
if (col < 0 || col >= layer.width || row < 0 || row >= layer.height) return false;
|
|
58
|
+
if (!Number.isInteger(col) || !Number.isInteger(row)) return false;
|
|
59
|
+
layer.tiles[row * layer.width + col] = gid;
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
50
62
|
/** Get the tileset that owns a given GID. Handles Tiled flip bits in the high bits. */
|
|
51
63
|
function getTilesetForGid(tilesets, gid) {
|
|
52
64
|
const id = gid & GID_FLIP_MASK;
|
|
@@ -438,6 +450,8 @@ var TilemapRenderer = class {
|
|
|
438
450
|
batch;
|
|
439
451
|
/** Map from tileset name → SkImage. Set via setTilesetImage(). */
|
|
440
452
|
_images = /* @__PURE__ */ new Map();
|
|
453
|
+
/** Images in `map.tilesets` order, refreshed from `_images` at the start of each draw. */
|
|
454
|
+
_tilesetImages = [];
|
|
441
455
|
/** Reusable bounds rect — avoids per-frame allocation from camera.getBounds(). */
|
|
442
456
|
_boundsBuf = {
|
|
443
457
|
x: 0,
|
|
@@ -476,6 +490,13 @@ var TilemapRenderer = class {
|
|
|
476
490
|
const effect = opts?.effect;
|
|
477
491
|
const alphaScale = opts?.alphaScale ?? 1;
|
|
478
492
|
const time = opts?.time ?? NaN;
|
|
493
|
+
const tilesets = this.map.tilesets;
|
|
494
|
+
const images = this._tilesetImages;
|
|
495
|
+
images.length = tilesets.length;
|
|
496
|
+
for (let i = 0; i < tilesets.length; i++) {
|
|
497
|
+
const tileset = tilesets[i];
|
|
498
|
+
if (tileset !== void 0) images[i] = this._images.get(tileset.name);
|
|
499
|
+
}
|
|
479
500
|
for (const layer of this.map.layers) {
|
|
480
501
|
if (layer.type !== "tile" || !layer.visible) continue;
|
|
481
502
|
this._drawTileLayer(layer, bounds.x, bounds.y, bounds.width, bounds.height, tw, th, batch, effect, layer.opacity * alphaScale, time);
|
|
@@ -495,6 +516,12 @@ var TilemapRenderer = class {
|
|
|
495
516
|
const offsetX = layer.offsetX;
|
|
496
517
|
const offsetY = layer.offsetY;
|
|
497
518
|
const animate = Number.isFinite(time);
|
|
519
|
+
const tilesets = this.map.tilesets;
|
|
520
|
+
const images = this._tilesetImages;
|
|
521
|
+
let tileset;
|
|
522
|
+
let image;
|
|
523
|
+
let runLo = 1;
|
|
524
|
+
let runHi = 0;
|
|
498
525
|
const startCol = Math.max(0, Math.floor((viewX - offsetX) / tw));
|
|
499
526
|
const startRow = Math.max(0, Math.floor((viewY - offsetY) / th));
|
|
500
527
|
const endCol = Math.min(layer.width - 1, Math.floor((viewX - offsetX + viewW) / tw));
|
|
@@ -502,13 +529,27 @@ var TilemapRenderer = class {
|
|
|
502
529
|
for (let row = startRow; row <= endRow; row++) for (let col = startCol; col <= endCol; col++) {
|
|
503
530
|
const gid = getTileAt(layer, col, row);
|
|
504
531
|
if (gid === 0) continue;
|
|
505
|
-
const
|
|
532
|
+
const id = gid & GID_FLIP_MASK;
|
|
533
|
+
if (id < runLo || id >= runHi) {
|
|
534
|
+
tileset = getTilesetForGid(tilesets, id);
|
|
535
|
+
image = void 0;
|
|
536
|
+
runLo = 1;
|
|
537
|
+
runHi = 0;
|
|
538
|
+
if (tileset !== void 0) {
|
|
539
|
+
let index = 0;
|
|
540
|
+
runLo = tileset.firstGid;
|
|
541
|
+
for (let ts = tilesets[0]; ts !== void 0 && ts !== tileset; ts = tilesets[++index]) if (ts.firstGid > runLo) runLo = ts.firstGid;
|
|
542
|
+
image = images[index];
|
|
543
|
+
runHi = tileset.firstGid + tileset.tileCount;
|
|
544
|
+
const next = tilesets[index + 1];
|
|
545
|
+
if (next !== void 0 && next.firstGid < runHi) runHi = next.firstGid;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
506
548
|
if (!tileset) continue;
|
|
507
|
-
const image = this._images.get(tileset.name);
|
|
508
549
|
if (!image) continue;
|
|
509
550
|
let srcGid = gid;
|
|
510
551
|
if (animate && tileset.animations !== void 0) {
|
|
511
|
-
const anim = tileset.animations.get(
|
|
552
|
+
const anim = tileset.animations.get(id - tileset.firstGid);
|
|
512
553
|
if (anim !== void 0) srcGid = tileset.firstGid + animatedLocalId(anim, time);
|
|
513
554
|
}
|
|
514
555
|
const src = getTileSourceRectInto(tileset, srcGid, this._srcBuf);
|
|
@@ -527,6 +568,6 @@ var TilemapRenderer = class {
|
|
|
527
568
|
}
|
|
528
569
|
}
|
|
529
570
|
};
|
|
530
|
-
export { GID_FLIP_MASK, TilemapParseError, TilemapRenderer, createTilemapData, decodeGidFlags, extractColliders, getTileAt, getTileSourceRect, getTileSourceRectInto, getTilesetForGid, parseLDtk, parseLDtkEntities, parseTiled, stripGidFlags };
|
|
571
|
+
export { GID_FLIP_MASK, TilemapParseError, TilemapRenderer, createTilemapData, decodeGidFlags, extractColliders, getTileAt, getTileSourceRect, getTileSourceRectInto, getTilesetForGid, parseLDtk, parseLDtkEntities, parseTiled, setTileAt, stripGidFlags };
|
|
531
572
|
|
|
532
573
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["FLIP_H","FLIP_V","FLIP_D"],"sources":["../src/parse-error.ts","../src/tilemap-data.ts","../src/ldtk-parser.ts","../src/tiled-parser.ts","../src/tilemap-collider.ts","../src/tilemap-renderer.ts"],"sourcesContent":["/** Thrown by parseTiled/parseLDtk when a map uses an unsupported format or feature. */\nexport class TilemapParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'TilemapParseError';\n }\n}\n","import type { Rect } from '@flare-engine/math';\n\n/** Low 29 bits of a Tiled GID — Tiled stores flip state in the high 3 bits. */\nexport const GID_FLIP_MASK = 0x1fffffff;\n\nconst FLIP_H = 0x80000000;\nconst FLIP_V = 0x40000000;\nconst FLIP_D = 0x20000000;\n\n/** Flip state encoded in the high bits of a Tiled GID. */\nexport interface TileFlipFlags {\n horizontal: boolean;\n vertical: boolean;\n diagonal: boolean;\n}\n\n/** Strip the Tiled flip bits from a raw GID, returning the real global tile id. */\nexport function stripGidFlags(gid: number): number {\n return gid & GID_FLIP_MASK;\n}\n\n/**\n * Decode the Tiled flip bits encoded in the high bits of a raw GID.\n * Note: `gid & 0x80000000` yields a negative Int32 when the bit is set;\n * compare with `!== 0`, not `> 0`.\n */\nexport function decodeGidFlags(gid: number): TileFlipFlags {\n return {\n horizontal: (gid & FLIP_H) !== 0,\n vertical: (gid & FLIP_V) !== 0,\n diagonal: (gid & FLIP_D) !== 0,\n };\n}\n\n/** A layer of tiles in a grid. */\nexport interface TileLayer {\n readonly type: 'tile';\n /** Layer name. */\n name: string;\n /** Grid width in tiles. */\n width: number;\n /** Grid height in tiles. */\n height: number;\n /**\n * Flat array of tile GIDs (row-major, length = width * height). `Uint32Array`,\n * not `Float32Array` — a 24-bit mantissa cannot hold Tiled's flip-bit GIDs\n * (`0x80000000` and up). This is a type decision for bulk numeric data per the\n * repo convention, not a measured perf change.\n *\n * `readonly` like `SolidGrid.solid`: the array cannot be swapped out from under a\n * parsed map, but its cells stay writable (`layer.tiles[i] = gid`).\n */\n readonly tiles: Uint32Array;\n /** Visibility flag. */\n visible: boolean;\n /** Opacity (0–1). */\n opacity: number;\n /** Layer offset in pixels. */\n offsetX: number;\n offsetY: number;\n /** Custom properties. */\n properties: Record<string, unknown>;\n}\n\n/** An object in an object layer. */\nexport interface MapObject {\n /** Object ID. */\n id: number;\n /** Object name. */\n name: string;\n /** Object type/class. */\n type: string;\n /** Position in pixels. */\n x: number;\n y: number;\n /** Size in pixels. */\n width: number;\n height: number;\n /** Rotation in degrees. */\n rotation: number;\n /** Custom properties. */\n properties: Record<string, unknown>;\n}\n\n/** A layer of objects. */\nexport interface ObjectLayer {\n readonly type: 'object';\n /** Layer name. */\n name: string;\n /** Objects in the layer. */\n objects: MapObject[];\n /** Visibility flag. */\n visible: boolean;\n /** Opacity (0–1). */\n opacity: number;\n /** Custom properties. */\n properties: Record<string, unknown>;\n}\n\n/** Union of layer types. */\nexport type MapLayer = TileLayer | ObjectLayer;\n\n/**\n * A Tiled per-tile animation, parsed into flat per-frame arrays so a renderer\n * can resolve the current frame without allocating.\n */\nexport interface TileAnimation {\n /** Local tile id of each frame, in order. */\n frames: Uint32Array;\n /** Cumulative end time of each frame, in seconds (frame i covers [ends[i-1], ends[i])). */\n ends: Float64Array;\n /** Total cycle length, seconds. */\n duration: number;\n}\n\n/** Information about a tileset used in the map. */\nexport interface TilesetRef {\n /** First GID in this tileset. */\n firstGid: number;\n /** Tileset name. */\n name: string;\n /** Tile width in pixels. */\n tileWidth: number;\n /** Tile height in pixels. */\n tileHeight: number;\n /** Number of columns in the tileset image. */\n columns: number;\n /** Total tile count. */\n tileCount: number;\n /** Image source path (may need resolving). */\n image: string;\n /** Image width in pixels. */\n imageWidth: number;\n /** Image height in pixels. */\n imageHeight: number;\n /** Per-tile properties (indexed by local tile ID). */\n tileProperties: Map<number, Record<string, unknown>>;\n /** Tile IDs marked as solid/collision. */\n solidTiles: Set<number>;\n /** Tiled per-tile animations keyed by local tile id; absent when no tile is animated. */\n animations?: Map<number, TileAnimation>;\n}\n\n/** Complete parsed tilemap data — format-independent. */\nexport interface TilemapData {\n /** Map width in tiles. */\n width: number;\n /** Map height in tiles. */\n height: number;\n /** Tile width in pixels. */\n tileWidth: number;\n /** Tile height in pixels. */\n tileHeight: number;\n /** All layers in order. */\n layers: MapLayer[];\n /** Tilesets referenced by this map. */\n tilesets: TilesetRef[];\n /** Custom map properties. */\n properties: Record<string, unknown>;\n}\n\n/** Create an empty TilemapData. */\nexport function createTilemapData(\n width: number,\n height: number,\n tileWidth: number,\n tileHeight: number,\n): TilemapData {\n return {\n width,\n height,\n tileWidth,\n tileHeight,\n layers: [],\n tilesets: [],\n properties: {},\n };\n}\n\n/** Get a tile GID at a grid position from a tile layer. Returns 0 if out of bounds. */\nexport function getTileAt(layer: TileLayer, col: number, row: number): number {\n if (col < 0 || col >= layer.width || row < 0 || row >= layer.height) return 0;\n // The `?? 0` is unreachable at runtime (the bounds check above guarantees an\n // in-range index into a hole-free Uint32Array) — it satisfies noUncheckedIndexedAccess,\n // which types every typed-array index read as `number | undefined`.\n return layer.tiles[row * layer.width + col] ?? 0;\n}\n\n/** Get the tileset that owns a given GID. Handles Tiled flip bits in the high bits. */\nexport function getTilesetForGid(tilesets: TilesetRef[], gid: number): TilesetRef | undefined {\n const id = gid & GID_FLIP_MASK;\n // Tilesets are ordered by firstGid; find the last one where firstGid <= id\n let result: TilesetRef | undefined;\n for (const ts of tilesets) {\n if (ts.firstGid <= id) {\n result = ts;\n } else {\n break;\n }\n }\n return result;\n}\n\n/** Compute the source rect in a tileset image for a given GID into `out`. Strips Tiled flip bits. Zero-alloc. */\nexport function getTileSourceRectInto(tileset: TilesetRef, gid: number, out: Rect): Rect {\n const localId = (gid & GID_FLIP_MASK) - tileset.firstGid;\n const col = localId % tileset.columns;\n const row = Math.floor(localId / tileset.columns);\n out.x = col * tileset.tileWidth;\n out.y = row * tileset.tileHeight;\n out.width = tileset.tileWidth;\n out.height = tileset.tileHeight;\n return out;\n}\n\n/** Compute the source rect in a tileset image for a given GID. Strips Tiled flip bits. */\nexport function getTileSourceRect(tileset: TilesetRef, gid: number): Rect {\n return getTileSourceRectInto(tileset, gid, { x: 0, y: 0, width: 0, height: 0 });\n}\n","import { TilemapParseError } from './parse-error.js';\nimport type { MapObject, ObjectLayer, TileLayer, TilemapData, TilesetRef } from './tilemap-data.js';\nimport { createTilemapData } from './tilemap-data.js';\n\n// ----- LDtk JSON types -----\n\ninterface LDtkFieldInstance {\n __identifier: string;\n __value: unknown;\n __type: string;\n}\n\ninterface LDtkEntityInstance {\n __identifier: string;\n __grid: [number, number];\n __pivot: [number, number];\n __tile?: { x: number; y: number; w: number; h: number };\n iid: string;\n width: number;\n height: number;\n px: [number, number];\n fieldInstances: LDtkFieldInstance[];\n}\n\ninterface LDtkTileInstance {\n px: [number, number];\n src: [number, number];\n f: number; // flip flags\n t: number; // tile ID\n}\n\ninterface LDtkLayerInstance {\n __identifier: string;\n __type: string;\n __cWid: number;\n __cHei: number;\n __gridSize: number;\n __tilesetDefUid?: number;\n __tilesetRelPath?: string;\n visible: boolean;\n __opacity: number;\n intGridCsv?: number[];\n // Real LDtk output always emits both arrays on every layer instance — only\n // one is ever populated per __type (an AutoLayer's gridTiles is always []).\n // Required (not optional) so a fixture omitting the unused one, as every\n // fixture here did before F057, cannot pass this module's own types.\n gridTiles: LDtkTileInstance[];\n autoLayerTiles: LDtkTileInstance[];\n entityInstances?: LDtkEntityInstance[];\n}\n\ninterface LDtkTilesetDef {\n uid: number;\n identifier: string;\n relPath: string;\n pxWid: number;\n pxHei: number;\n tileGridSize: number;\n __cWid: number;\n __cHei: number;\n}\n\ninterface LDtkLevel {\n identifier: string;\n uid: number;\n pxWid: number;\n pxHei: number;\n worldX: number;\n worldY: number;\n layerInstances?: LDtkLayerInstance[];\n fieldInstances?: LDtkFieldInstance[];\n}\n\ninterface LDtkJSON {\n defaultGridSize: number;\n externalLevels?: boolean;\n defs: {\n tilesets: LDtkTilesetDef[];\n };\n levels: LDtkLevel[];\n}\n\nexport interface ParseLDtkOptions {\n /** Predicate deciding whether an IntGrid value marks a solid cell. Default: value > 0. */\n intGridSolid?: (value: number) => boolean;\n}\n\nexport interface LDtkEntity {\n /** LDtk entity identifier (its type, e.g. \"Player\") — the key you switch on to decide what to spawn. */\n id: string;\n /** Entity position in pixels (LDtk px, pivot-adjusted per the parser convention). */\n x: number;\n y: number;\n /** Entity box size in pixels. */\n width: number;\n height: number;\n /** Custom field instances, keyed by field identifier. */\n fields: Record<string, unknown>;\n}\n\n/**\n * Extract every LDtk entity from a parsed map as a flat, spawn-ready list —\n * the LDtk-entity → ECS spawn convention. Walks all object layers; tile layers are skipped.\n */\nexport function parseLDtkEntities(map: TilemapData): LDtkEntity[] {\n const entities: LDtkEntity[] = [];\n for (const layer of map.layers) {\n if (layer.type !== 'object') continue;\n for (const obj of layer.objects) {\n entities.push({\n id: obj.type,\n x: obj.x,\n y: obj.y,\n width: obj.width,\n height: obj.height,\n fields: obj.properties,\n });\n }\n }\n return entities;\n}\n\n/**\n * Parse an LDtk JSON project into an array of TilemapData (one per level).\n * Returns all levels with their tile and entity layers.\n * Throws TilemapParseError for unsupported formats (externalLevels, invalid input).\n */\nexport function parseLDtk(json: unknown, options: ParseLDtkOptions = {}): TilemapData[] {\n if (\n !json ||\n typeof json !== 'object' ||\n !Array.isArray((json as Record<string, unknown>).levels) ||\n !(json as Record<string, unknown>).defs ||\n !Array.isArray(((json as Record<string, unknown>).defs as Record<string, unknown>).tilesets)\n ) {\n throw new TilemapParseError(\n 'parseLDtk: input is not an LDtk project JSON (missing defs.tilesets or levels).',\n );\n }\n\n const data = json as LDtkJSON;\n\n if (data.externalLevels === true) {\n throw new TilemapParseError(\n 'parseLDtk: projects with \"Save levels to separate files\" (externalLevels) are not supported. Disable it in LDtk ▸ Project settings and re-save.',\n );\n }\n\n const isSolid = options.intGridSolid ?? ((v) => v > 0);\n\n const tilesetDefs = new Map<number, LDtkTilesetDef>();\n for (const ts of data.defs.tilesets) {\n tilesetDefs.set(ts.uid, ts);\n }\n\n const results: TilemapData[] = [];\n\n for (const level of data.levels) {\n const gridSize = data.defaultGridSize;\n const mapWidth = Math.ceil(level.pxWid / gridSize);\n const mapHeight = Math.ceil(level.pxHei / gridSize);\n const map = createTilemapData(mapWidth, mapHeight, gridSize, gridSize);\n\n if (level.fieldInstances) {\n for (const field of level.fieldInstances) {\n map.properties[field.__identifier] = field.__value;\n }\n }\n\n // Pass 1: collect tile-layer tileset uids, sort ascending, assign deterministic firstGids.\n // Tilesets must be sorted by firstGid (ascending) for getTilesetForGid's early-break.\n const firstGidByUid = new Map<number, number>();\n let nextFirstGid = 1;\n\n if (level.layerInstances) {\n const usedTileUids = new Set<number>();\n for (const layerInst of level.layerInstances) {\n if (\n (layerInst.__type === 'Tiles' || layerInst.__type === 'AutoLayer') &&\n layerInst.__tilesetDefUid !== undefined\n ) {\n usedTileUids.add(layerInst.__tilesetDefUid);\n }\n }\n\n const sortedUids = Array.from(usedTileUids).sort((a, b) => a - b);\n for (const uid of sortedUids) {\n const def = tilesetDefs.get(uid);\n if (!def) continue;\n const columns = def.__cWid;\n const tileCount = def.__cWid * def.__cHei;\n firstGidByUid.set(uid, nextFirstGid);\n const ref: TilesetRef = {\n firstGid: nextFirstGid,\n name: def.identifier,\n tileWidth: def.tileGridSize,\n tileHeight: def.tileGridSize,\n columns,\n tileCount,\n image: def.relPath,\n imageWidth: def.pxWid,\n imageHeight: def.pxHei,\n tileProperties: new Map(),\n solidTiles: new Set(),\n };\n map.tilesets.push(ref);\n nextFirstGid += tileCount;\n }\n }\n\n // Pass 2: parse layers in reverse order (LDtk stores top-first; emit bottom-first).\n if (level.layerInstances) {\n for (let i = level.layerInstances.length - 1; i >= 0; i--) {\n const layerInst = level.layerInstances[i]!;\n\n if (layerInst.__type === 'IntGrid') {\n // IntGrid layers are treated as collision grids; IntGrid layers that also\n // carry auto-render tiles keep collision only (visual auto-tiles are M4 scope).\n const csv = layerInst.intGridCsv;\n const cellCount = layerInst.__cWid * layerInst.__cHei;\n const tiles = new Uint32Array(cellCount);\n const intFirstGid = nextFirstGid;\n let maxLocal = 0;\n let hasNonZero = false;\n const solidSet = new Set<number>();\n\n if (csv) {\n for (let j = 0; j < csv.length; j++) {\n const v = csv[j] ?? 0;\n if (v > 0) {\n hasNonZero = true;\n const localId = v - 1;\n if (localId > maxLocal) maxLocal = localId;\n tiles[j] = intFirstGid + localId;\n if (isSolid(v)) solidSet.add(localId);\n }\n }\n }\n\n if (hasNonZero) {\n const tileCount = maxLocal + 1;\n map.tilesets.push({\n firstGid: intFirstGid,\n name: layerInst.__identifier,\n tileWidth: layerInst.__gridSize,\n tileHeight: layerInst.__gridSize,\n columns: tileCount,\n tileCount,\n image: '',\n imageWidth: 0,\n imageHeight: 0,\n tileProperties: new Map(),\n solidTiles: solidSet,\n });\n nextFirstGid += tileCount;\n }\n\n map.layers.push({\n type: 'tile',\n name: layerInst.__identifier,\n width: layerInst.__cWid,\n height: layerInst.__cHei,\n tiles,\n visible: layerInst.visible,\n opacity: layerInst.__opacity,\n offsetX: 0,\n offsetY: 0,\n properties: {},\n });\n } else if (layerInst.__type === 'Tiles' || layerInst.__type === 'AutoLayer') {\n const firstGid = firstGidByUid.get(layerInst.__tilesetDefUid ?? -1) ?? 1;\n map.layers.push(parseTilesLayer(layerInst, mapWidth, mapHeight, gridSize, firstGid));\n } else if (layerInst.__type === 'Entities') {\n map.layers.push(parseEntitiesLayer(layerInst));\n }\n }\n }\n\n results.push(map);\n }\n\n return results;\n}\n\nfunction parseTilesLayer(\n layer: LDtkLayerInstance,\n mapWidth: number,\n mapHeight: number,\n gridSize: number,\n firstGid: number,\n): TileLayer {\n const tiles = new Uint32Array(mapWidth * mapHeight);\n // An AutoLayer's tiles live in autoLayerTiles; its gridTiles is always [].\n // `gridTiles ?? autoLayerTiles` picked the empty gridTiles for every\n // AutoLayer, since `??` only falls through on null/undefined, never on `[]`\n // — select by __type instead, which is the field LDtk itself keys on.\n const tileInstances = layer.__type === 'AutoLayer' ? layer.autoLayerTiles : layer.gridTiles;\n\n for (const ti of tileInstances) {\n const col = Math.floor(ti.px[0] / gridSize);\n const row = Math.floor(ti.px[1] / gridSize);\n if (col >= 0 && col < mapWidth && row >= 0 && row < mapHeight) {\n tiles[row * mapWidth + col] = firstGid + ti.t;\n }\n }\n\n return {\n type: 'tile',\n name: layer.__identifier,\n width: mapWidth,\n height: mapHeight,\n tiles,\n visible: layer.visible,\n opacity: layer.__opacity,\n offsetX: 0,\n offsetY: 0,\n properties: {},\n };\n}\n\nfunction parseEntitiesLayer(layer: LDtkLayerInstance): ObjectLayer {\n const objects: MapObject[] = (layer.entityInstances ?? []).map((ent, idx) => {\n const props: Record<string, unknown> = {};\n for (const field of ent.fieldInstances) {\n props[field.__identifier] = field.__value;\n }\n return {\n id: idx + 1,\n name: ent.__identifier,\n type: ent.__identifier,\n x: ent.px[0],\n y: ent.px[1],\n width: ent.width,\n height: ent.height,\n rotation: 0,\n properties: props,\n };\n });\n\n return {\n type: 'object',\n name: layer.__identifier,\n objects,\n visible: layer.visible,\n opacity: layer.__opacity,\n properties: {},\n };\n}\n","import { TilemapParseError } from './parse-error.js';\nimport type {\n MapLayer,\n MapObject,\n ObjectLayer,\n TileAnimation,\n TileLayer,\n TilemapData,\n TilesetRef,\n} from './tilemap-data.js';\nimport { createTilemapData } from './tilemap-data.js';\n\n// ----- Tiled JSON types (.tmj format) -----\n\ninterface TiledProperty {\n name: string;\n type: string;\n value: unknown;\n}\n\ninterface TiledTileLayer {\n type: 'tilelayer';\n name: string;\n width: number;\n height: number;\n data: number[] | string;\n encoding?: string;\n compression?: string;\n chunks?: unknown[];\n visible: boolean;\n opacity: number;\n offsetx?: number;\n offsety?: number;\n properties?: TiledProperty[];\n}\n\ninterface TiledObject {\n id: number;\n name: string;\n type?: string;\n class?: string;\n x: number;\n y: number;\n width: number;\n height: number;\n rotation: number;\n properties?: TiledProperty[];\n}\n\ninterface TiledObjectLayer {\n type: 'objectgroup';\n name: string;\n objects: TiledObject[];\n visible: boolean;\n opacity: number;\n properties?: TiledProperty[];\n}\n\ntype TiledLayer = TiledTileLayer | TiledObjectLayer;\n\ninterface TiledAnimationFrame {\n tileid: number;\n /** Milliseconds. */\n duration: number;\n}\n\ninterface TiledTile {\n id: number;\n properties?: TiledProperty[];\n type?: string;\n class?: string;\n animation?: TiledAnimationFrame[];\n}\n\ninterface TiledTileset {\n firstgid: number;\n name: string;\n tilewidth: number;\n tileheight: number;\n columns: number;\n tilecount: number;\n image: string;\n imagewidth: number;\n imageheight: number;\n tiles?: TiledTile[];\n properties?: TiledProperty[];\n source?: string;\n}\n\ninterface TiledMapJSON {\n width: number;\n height: number;\n tilewidth: number;\n tileheight: number;\n orientation: string;\n infinite?: boolean;\n layers: TiledLayer[];\n tilesets: TiledTileset[];\n properties?: TiledProperty[];\n}\n\n/** Convert Tiled properties array to a Record. */\nfunction parseProperties(props?: TiledProperty[]): Record<string, unknown> {\n if (!props || props.length === 0) return {};\n const result: Record<string, unknown> = {};\n for (const p of props) {\n result[p.name] = p.value;\n }\n return result;\n}\n\n/**\n * Build a tile's Tiled animation (frame durations in ms) into cumulative seconds.\n * Returns `undefined` for an empty animation or one whose durations sum to 0 —\n * such a tile draws as authored.\n */\nfunction parseTileAnimation(ts: TiledTileset, tile: TiledTile): TileAnimation | undefined {\n const source = tile.animation;\n if (source === undefined || source.length === 0) return undefined;\n const frames = new Uint32Array(source.length);\n const ends = new Float64Array(source.length);\n // Summed in ms and divided once per frame so integer-ms inputs give exact seconds.\n let totalMs = 0;\n for (let i = 0; i < source.length; i++) {\n const frame = source[i]!;\n const tileid = frame.tileid;\n const duration = frame.duration;\n if (!Number.isInteger(tileid) || tileid < 0 || tileid >= ts.tilecount) {\n throw new TilemapParseError(\n `parseTiled: tileset \"${ts.name}\" tile ${tile.id} animation frame ${i} has tileid ${tileid} — expected an integer in [0, ${ts.tilecount}).`,\n );\n }\n if (!Number.isFinite(duration) || duration < 0) {\n throw new TilemapParseError(\n `parseTiled: tileset \"${ts.name}\" tile ${tile.id} animation frame ${i} has duration ${duration} — expected a finite number of milliseconds >= 0.`,\n );\n }\n totalMs += duration;\n frames[i] = tileid;\n ends[i] = totalMs / 1000;\n }\n if (totalMs === 0) return undefined;\n return { frames, ends, duration: totalMs / 1000 };\n}\n\n/**\n * Parse a Tiled .tmj (JSON) map into TilemapData.\n * Supports orthogonal maps with CSV tile layers and object layers.\n * Throws TilemapParseError for unsupported formats (infinite, non-orthogonal,\n * external tilesets, base64/compressed/chunked layer data).\n */\nexport function parseTiled(json: unknown): TilemapData {\n if (\n !json ||\n typeof json !== 'object' ||\n typeof (json as Record<string, unknown>).width !== 'number' ||\n typeof (json as Record<string, unknown>).height !== 'number' ||\n !Array.isArray((json as Record<string, unknown>).layers) ||\n !Array.isArray((json as Record<string, unknown>).tilesets)\n ) {\n throw new TilemapParseError(\n 'parseTiled: input is not a Tiled map JSON (missing width/height/layers/tilesets).',\n );\n }\n\n const data = json as TiledMapJSON;\n\n if (data.infinite === true) {\n throw new TilemapParseError(\n 'parseTiled: infinite maps are not supported. In Tiled: Map ▸ Map Properties ▸ set \"Infinite\" to false, then re-export.',\n );\n }\n if (data.orientation && data.orientation !== 'orthogonal') {\n throw new TilemapParseError(\n `parseTiled: orientation \"${data.orientation}\" is not supported — only orthogonal maps are supported.`,\n );\n }\n\n const map = createTilemapData(data.width, data.height, data.tilewidth, data.tileheight);\n map.properties = parseProperties(data.properties);\n\n // Parse tilesets\n for (const ts of data.tilesets) {\n if (ts.source !== undefined) {\n throw new TilemapParseError(\n `parseTiled: external tileset \"${ts.source}\" is not supported. Embed tilesets on export (Tiled ▸ Map ▸ \"Embed tilesets\") or run it through \\`flare tiled-to-flare\\` (which embeds tilesets by default).`,\n );\n }\n\n const tileProperties = new Map<number, Record<string, unknown>>();\n const solidTiles = new Set<number>();\n let animations: Map<number, TileAnimation> | undefined;\n\n if (ts.tiles) {\n for (const tile of ts.tiles) {\n const props = parseProperties(tile.properties);\n if (Object.keys(props).length > 0) {\n tileProperties.set(tile.id, props);\n }\n // Mark as solid if it has a \"collision\" or \"solid\" property, or type/class is \"solid\"\n const tileType = tile.type ?? tile.class ?? '';\n if (tileType === 'solid' || props.solid === true || props.collision === true) {\n solidTiles.add(tile.id);\n }\n const animation = parseTileAnimation(ts, tile);\n if (animation !== undefined) {\n animations ??= new Map();\n animations.set(tile.id, animation);\n }\n }\n }\n\n const ref: TilesetRef = {\n firstGid: ts.firstgid,\n name: ts.name,\n tileWidth: ts.tilewidth,\n tileHeight: ts.tileheight,\n columns: ts.columns,\n tileCount: ts.tilecount,\n image: ts.image,\n imageWidth: ts.imagewidth,\n imageHeight: ts.imageheight,\n tileProperties,\n solidTiles,\n };\n if (animations !== undefined) ref.animations = animations;\n map.tilesets.push(ref);\n }\n\n // Sort tilesets by firstGid\n map.tilesets.sort((a, b) => a.firstGid - b.firstGid);\n\n // Parse layers\n for (const layer of data.layers) {\n map.layers.push(parseLayer(layer));\n }\n\n return map;\n}\n\nfunction parseLayer(layer: TiledLayer): MapLayer {\n if (layer.type === 'tilelayer') return parseTileLayer(layer);\n if (layer.type === 'objectgroup') return parseObjectLayer(layer);\n const l = layer as { type: string; name?: string };\n throw new TilemapParseError(\n `parseTiled: layer \"${l.name ?? ''}\" has unsupported type \"${l.type}\". Only tilelayer and objectgroup are supported — flatten group layers and remove image layers before export.`,\n );\n}\n\nfunction parseTileLayer(layer: TiledTileLayer): TileLayer {\n if (\n (layer.encoding !== undefined && layer.encoding !== 'csv') ||\n layer.compression !== undefined ||\n layer.chunks !== undefined\n ) {\n throw new TilemapParseError(\n 'parseTiled: base64/compressed/chunked (infinite) layer data is not supported. In Tiled export options set Tile Layer Format to \"CSV\".',\n );\n }\n if (typeof layer.data === 'string') {\n throw new TilemapParseError(\n 'parseTiled: base64/compressed/chunked (infinite) layer data is not supported. In Tiled export options set Tile Layer Format to \"CSV\".',\n );\n }\n // layer.data is number[] here — Uint32Array.from preserves flip-bit GIDs\n // (values up to 0xffffffff), unlike a Float32Array's 24-bit mantissa.\n return {\n type: 'tile',\n name: layer.name,\n width: layer.width,\n height: layer.height,\n tiles: Uint32Array.from(layer.data),\n visible: layer.visible,\n opacity: layer.opacity,\n offsetX: layer.offsetx ?? 0,\n offsetY: layer.offsety ?? 0,\n properties: parseProperties(layer.properties),\n };\n}\n\nfunction parseObjectLayer(layer: TiledObjectLayer): ObjectLayer {\n const objects: MapObject[] = layer.objects.map((obj) => ({\n id: obj.id,\n name: obj.name,\n type: obj.type ?? obj.class ?? '',\n x: obj.x,\n y: obj.y,\n width: obj.width,\n height: obj.height,\n rotation: obj.rotation,\n properties: parseProperties(obj.properties),\n }));\n\n return {\n type: 'object',\n name: layer.name,\n objects,\n visible: layer.visible,\n opacity: layer.opacity,\n properties: parseProperties(layer.properties),\n };\n}\n","import type { AABBShape } from '@flare-engine/physics';\nimport { AABB } from '@flare-engine/physics';\nimport type { TileLayer, TilemapData, TilesetRef } from './tilemap-data.js';\nimport { GID_FLIP_MASK, getTilesetForGid } from './tilemap-data.js';\n\n/** A collision body extracted from a solid tile. */\nexport interface TileCollider {\n /** World position of the tile center. */\n x: number;\n y: number;\n /** AABB collision shape. */\n shape: AABBShape;\n /** Grid column. */\n col: number;\n /** Grid row. */\n row: number;\n /** The tile GID (flip bits stripped — AABB is symmetric, downstream lookups want the real id). */\n gid: number;\n}\n\n/**\n * Extract collision shapes from solid tiles in a tilemap.\n * A tile is considered solid if its tileset marks the local tile ID as solid.\n *\n * @param map The parsed tilemap data.\n * @param layerName Optional: only extract from this layer. If omitted, extracts from all tile layers.\n * @returns Array of TileCollider bodies.\n */\nexport function extractColliders(map: TilemapData, layerName?: string): TileCollider[] {\n const colliders: TileCollider[] = [];\n const tw = map.tileWidth;\n const th = map.tileHeight;\n\n for (const layer of map.layers) {\n if (layer.type !== 'tile') continue;\n if (layerName !== undefined && layer.name !== layerName) continue;\n\n extractFromLayer(layer, map.tilesets, tw, th, colliders);\n }\n\n return colliders;\n}\n\nfunction extractFromLayer(\n layer: TileLayer,\n tilesets: TilesetRef[],\n tw: number,\n th: number,\n out: TileCollider[],\n): void {\n for (let row = 0; row < layer.height; row++) {\n for (let col = 0; col < layer.width; col++) {\n const gid = layer.tiles[row * layer.width + col] ?? 0;\n if (gid === 0) continue;\n\n const tileset = getTilesetForGid(tilesets, gid);\n if (!tileset) continue;\n\n const localId = (gid & GID_FLIP_MASK) - tileset.firstGid;\n if (!tileset.solidTiles.has(localId)) continue;\n\n out.push({\n x: col * tw + tw * 0.5 + layer.offsetX,\n y: row * th + th * 0.5 + layer.offsetY,\n shape: AABB(tw, th),\n col,\n row,\n gid: gid & GID_FLIP_MASK,\n });\n }\n }\n}\n","import type { SkImageLike } from '@flare-engine/assets';\nimport type { Rect } from '@flare-engine/math';\nimport type { AnySpriteEffect, Camera2D } from '@flare-engine/render';\nimport { SpriteBatch } from '@flare-engine/render';\nimport type { TileAnimation, TileLayer, TilemapData } from './tilemap-data.js';\nimport {\n GID_FLIP_MASK,\n getTileAt,\n getTileSourceRectInto,\n getTilesetForGid,\n} from './tilemap-data.js';\n\n// Tiled GID flag bits (kept module-private; tilemap-data.ts owns the public mask).\nconst FLIP_H = 0x80000000;\nconst FLIP_V = 0x40000000;\nconst FLIP_D = 0x20000000;\nconst QUARTER_TURN = Math.PI / 2;\n\n/**\n * Per-draw options for `TilemapRenderer.drawInto` / `draw`.\n *\n * `effect` is set on every queued tile command. Batch runs key on the effect\n * by reference, so one shared instance (e.g. an ambient `tint()`) keeps every\n * tile — and any sprite drawn with the same instance — in a single run.\n * `alphaScale` multiplies each layer's own `opacity` (default 1).\n * `time` (seconds, e.g. the clock's elapsed) advances Tiled tile animations\n * parsed onto `TilesetRef.animations`; it wraps in both directions. Without\n * it (or when non-finite) every tile draws as authored.\n */\nexport interface TilemapDrawOptions {\n effect?: AnySpriteEffect;\n alphaScale?: number;\n time?: number;\n}\n\n/** Local tile id of the frame an animation shows at `time` (seconds, finite). */\nfunction animatedLocalId(anim: TileAnimation, time: number): number {\n let t = time % anim.duration;\n if (t < 0) t += anim.duration;\n const ends = anim.ends;\n const last = ends.length - 1;\n let i = 0;\n // A frame boundary belongs to the next frame; ends[last] === duration > t stops the scan.\n while (i < last && t >= (ends[i] ?? 0)) i++;\n // The `?? 0` is unreachable (i <= last < frames.length) — it satisfies noUncheckedIndexedAccess.\n return anim.frames[i] ?? 0;\n}\n\n/**\n * TilemapRenderer — draws a tilemap with viewport culling.\n * Only tiles visible to the camera are submitted to the SpriteBatch.\n */\nexport class TilemapRenderer {\n /** The tilemap data to render. */\n readonly map: TilemapData;\n\n /** SpriteBatch used for batched tile rendering. */\n readonly batch: SpriteBatch;\n\n /** Map from tileset name → SkImage. Set via setTilesetImage(). */\n private _images = new Map<string, SkImageLike>();\n\n /** Reusable bounds rect — avoids per-frame allocation from camera.getBounds(). */\n private _boundsBuf: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n /** Reusable source rect — avoids a per-tile allocation from getTileSourceRect. */\n private _srcBuf: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n constructor(map: TilemapData) {\n this.map = map;\n this.batch = new SpriteBatch();\n }\n\n /** Associate a loaded image with a tileset by name. */\n setTilesetImage(tilesetName: string, image: SkImageLike): void {\n this._images.set(tilesetName, image);\n }\n\n /**\n * Queue visible tile layers into a caller-owned `batch` using the camera for\n * culling. Does NOT flush — the caller owns the single flush so tiles z-order\n * under sprites. Zero-alloc: reuses the internal bounds buffer.\n *\n * Each tile's `alpha` is `layer.opacity * opts.alphaScale`; `opts.effect`\n * is applied to every tile; `opts.time` picks each animated tile's frame\n * (see `TilemapDrawOptions`).\n */\n drawInto(camera: Camera2D, batch: SpriteBatch, opts?: TilemapDrawOptions): void {\n const bounds = camera.getBoundsInto(this._boundsBuf);\n const tw = this.map.tileWidth;\n const th = this.map.tileHeight;\n const effect = opts?.effect;\n const alphaScale = opts?.alphaScale ?? 1;\n // NaN stands for \"no time\": the layer pass animates only when `time` is finite.\n const time = opts?.time ?? Number.NaN;\n\n for (const layer of this.map.layers) {\n if (layer.type !== 'tile' || !layer.visible) continue;\n this._drawTileLayer(\n layer,\n bounds.x,\n bounds.y,\n bounds.width,\n bounds.height,\n tw,\n th,\n batch,\n effect,\n layer.opacity * alphaScale,\n time,\n );\n }\n }\n\n /**\n * Draw visible tile layers using the camera for culling.\n * Call `flush` on a callback to issue the actual draw calls.\n * Delegates to `drawInto` so culling and queuing logic live in one place;\n * `opts` is threaded through unchanged.\n */\n draw(camera: Camera2D, flush: (batch: SpriteBatch) => void, opts?: TilemapDrawOptions): void {\n this.drawInto(camera, this.batch, opts);\n flush(this.batch);\n }\n\n // Tiled flip bits: H/V become the batch's flipX/flipY; the diagonal bit is a\n // quarter turn about the tile centre composed with the flip Tiled defines\n // (D+H = 90° CW, D+V = 90° CCW, D = flipY + CW, D+H+V = flipX + CW).\n private _drawTileLayer(\n layer: TileLayer,\n viewX: number,\n viewY: number,\n viewW: number,\n viewH: number,\n tw: number,\n th: number,\n batch: SpriteBatch,\n effect: AnySpriteEffect | undefined,\n alpha: number,\n time: number,\n ): void {\n const offsetX = layer.offsetX;\n const offsetY = layer.offsetY;\n const animate = Number.isFinite(time);\n\n // Calculate visible tile range (clamped to layer bounds)\n const startCol = Math.max(0, Math.floor((viewX - offsetX) / tw));\n const startRow = Math.max(0, Math.floor((viewY - offsetY) / th));\n const endCol = Math.min(layer.width - 1, Math.floor((viewX - offsetX + viewW) / tw));\n const endRow = Math.min(layer.height - 1, Math.floor((viewY - offsetY + viewH) / th));\n\n for (let row = startRow; row <= endRow; row++) {\n for (let col = startCol; col <= endCol; col++) {\n const gid = getTileAt(layer, col, row);\n if (gid === 0) continue;\n\n const tileset = getTilesetForGid(this.map.tilesets, gid);\n if (!tileset) continue;\n\n const image = this._images.get(tileset.name);\n if (!image) continue;\n\n // An animated tile sources its current frame; flip bits still come from `gid`.\n let srcGid = gid;\n if (animate && tileset.animations !== undefined) {\n const anim = tileset.animations.get((gid & GID_FLIP_MASK) - tileset.firstGid);\n if (anim !== undefined) srcGid = tileset.firstGid + animatedLocalId(anim, time);\n }\n\n // Strips flip bits; writes into the reusable buffer, no per-tile allocation.\n const src = getTileSourceRectInto(tileset, srcGid, this._srcBuf);\n\n // Bit tests only — `gid & FLIP_H` is a negative Int32 when set, so compare to 0.\n const h = (gid & FLIP_H) !== 0;\n const v = (gid & FLIP_V) !== 0;\n const d = (gid & FLIP_D) !== 0;\n let flipX = h;\n let flipY = v;\n let rotation = 0;\n if (d) {\n rotation = !h && v ? -QUARTER_TURN : QUARTER_TURN;\n flipX = h && v;\n flipY = !h && !v;\n }\n\n // Centre anchor keeps a turned tile in its cell; the stored dstX/dstY\n // stay the cell's top-left. Positional slots — no per-tile object.\n batch.drawRaw(\n image,\n src.x,\n src.y,\n src.width,\n src.height,\n col * tw + offsetX + tw * 0.5,\n row * th + offsetY + th * 0.5,\n tw,\n th,\n effect,\n 0.5,\n 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I,SAAS,KAAA,GAAW,SAAS,QAAQ,WAAW,gBAAgB,MAAM,IAAI;GAChF;GAGA,MAAM,MAAM,sBAAsB,SAAS,QAAQ,KAAK,OAAO;GAG/D,MAAM,KAAK,MAAM,YAAY;GAC7B,MAAM,KAAK,MAAM,YAAY;GAC7B,MAAM,KAAK,MAAM,YAAY;GAC7B,IAAI,QAAQ;GACZ,IAAI,QAAQ;GACZ,IAAI,WAAW;GACf,IAAI,GAAG;IACL,WAAW,CAAC,KAAK,IAAI,CAAC,eAAe;IACrC,QAAQ,KAAK;IACb,QAAQ,CAAC,KAAK,CAAC;GACjB;GAIA,MAAM,QACJ,OACA,IAAI,GACJ,IAAI,GACJ,IAAI,OACJ,IAAI,QACJ,MAAM,KAAK,UAAU,KAAK,IAC1B,MAAM,KAAK,UAAU,KAAK,IAC1B,IACA,IACA,QACA,IACA,IACA,OACA,UACA,OACA,UACA,OACA,KACF;EACF;CAEJ;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["FLIP_H","FLIP_V","FLIP_D"],"sources":["../src/parse-error.ts","../src/tilemap-data.ts","../src/ldtk-parser.ts","../src/tiled-parser.ts","../src/tilemap-collider.ts","../src/tilemap-renderer.ts"],"sourcesContent":["/** Thrown by parseTiled/parseLDtk when a map uses an unsupported format or feature. */\nexport class TilemapParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'TilemapParseError';\n }\n}\n","import type { Rect } from '@flare-engine/math';\n\n/** Low 29 bits of a Tiled GID — Tiled stores flip state in the high 3 bits. */\nexport const GID_FLIP_MASK = 0x1fffffff;\n\nconst FLIP_H = 0x80000000;\nconst FLIP_V = 0x40000000;\nconst FLIP_D = 0x20000000;\n\n/** Flip state encoded in the high bits of a Tiled GID. */\nexport interface TileFlipFlags {\n horizontal: boolean;\n vertical: boolean;\n diagonal: boolean;\n}\n\n/** Strip the Tiled flip bits from a raw GID, returning the real global tile id. */\nexport function stripGidFlags(gid: number): number {\n return gid & GID_FLIP_MASK;\n}\n\n/**\n * Decode the Tiled flip bits encoded in the high bits of a raw GID.\n * Note: `gid & 0x80000000` yields a negative Int32 when the bit is set;\n * compare with `!== 0`, not `> 0`.\n */\nexport function decodeGidFlags(gid: number): TileFlipFlags {\n return {\n horizontal: (gid & FLIP_H) !== 0,\n vertical: (gid & FLIP_V) !== 0,\n diagonal: (gid & FLIP_D) !== 0,\n };\n}\n\n/** A layer of tiles in a grid. */\nexport interface TileLayer {\n readonly type: 'tile';\n /** Layer name. */\n name: string;\n /** Grid width in tiles. */\n width: number;\n /** Grid height in tiles. */\n height: number;\n /**\n * Flat array of tile GIDs (row-major, length = width * height). `Uint32Array`,\n * not `Float32Array` — a 24-bit mantissa cannot hold Tiled's flip-bit GIDs\n * (`0x80000000` and up). This is a type decision for bulk numeric data per the\n * repo convention, not a measured perf change.\n *\n * `readonly` like `SolidGrid.solid`: the array cannot be swapped out from under a\n * parsed map, but its cells stay writable (`layer.tiles[i] = gid`).\n */\n readonly tiles: Uint32Array;\n /** Visibility flag. */\n visible: boolean;\n /** Opacity (0–1). */\n opacity: number;\n /** Layer offset in pixels. */\n offsetX: number;\n offsetY: number;\n /** Custom properties. */\n properties: Record<string, unknown>;\n}\n\n/** An object in an object layer. */\nexport interface MapObject {\n /** Object ID. */\n id: number;\n /** Object name. */\n name: string;\n /** Object type/class. */\n type: string;\n /** Position in pixels. */\n x: number;\n y: number;\n /** Size in pixels. */\n width: number;\n height: number;\n /** Rotation in degrees. */\n rotation: number;\n /** Custom properties. */\n properties: Record<string, unknown>;\n}\n\n/** A layer of objects. */\nexport interface ObjectLayer {\n readonly type: 'object';\n /** Layer name. */\n name: string;\n /** Objects in the layer. */\n objects: MapObject[];\n /** Visibility flag. */\n visible: boolean;\n /** Opacity (0–1). */\n opacity: number;\n /** Custom properties. */\n properties: Record<string, unknown>;\n}\n\n/** Union of layer types. */\nexport type MapLayer = TileLayer | ObjectLayer;\n\n/**\n * A Tiled per-tile animation, parsed into flat per-frame arrays so a renderer\n * can resolve the current frame without allocating.\n */\nexport interface TileAnimation {\n /** Local tile id of each frame, in order. */\n frames: Uint32Array;\n /** Cumulative end time of each frame, in seconds (frame i covers [ends[i-1], ends[i])). */\n ends: Float64Array;\n /** Total cycle length, seconds. */\n duration: number;\n}\n\n/** Information about a tileset used in the map. */\nexport interface TilesetRef {\n /** First GID in this tileset. */\n firstGid: number;\n /** Tileset name. */\n name: string;\n /** Tile width in pixels. */\n tileWidth: number;\n /** Tile height in pixels. */\n tileHeight: number;\n /** Number of columns in the tileset image. */\n columns: number;\n /** Total tile count. */\n tileCount: number;\n /** Image source path (may need resolving). */\n image: string;\n /** Image width in pixels. */\n imageWidth: number;\n /** Image height in pixels. */\n imageHeight: number;\n /** Per-tile properties (indexed by local tile ID). */\n tileProperties: Map<number, Record<string, unknown>>;\n /** Tile IDs marked as solid/collision. */\n solidTiles: Set<number>;\n /** Tiled per-tile animations keyed by local tile id; absent when no tile is animated. */\n animations?: Map<number, TileAnimation>;\n}\n\n/** Complete parsed tilemap data — format-independent. */\nexport interface TilemapData {\n /** Map width in tiles. */\n width: number;\n /** Map height in tiles. */\n height: number;\n /** Tile width in pixels. */\n tileWidth: number;\n /** Tile height in pixels. */\n tileHeight: number;\n /** All layers in order. */\n layers: MapLayer[];\n /** Tilesets referenced by this map. */\n tilesets: TilesetRef[];\n /** Custom map properties. */\n properties: Record<string, unknown>;\n}\n\n/** Create an empty TilemapData. */\nexport function createTilemapData(\n width: number,\n height: number,\n tileWidth: number,\n tileHeight: number,\n): TilemapData {\n return {\n width,\n height,\n tileWidth,\n tileHeight,\n layers: [],\n tilesets: [],\n properties: {},\n };\n}\n\n/** Get a tile GID at a grid position from a tile layer. Returns 0 if out of bounds. */\nexport function getTileAt(layer: TileLayer, col: number, row: number): number {\n if (col < 0 || col >= layer.width || row < 0 || row >= layer.height) return 0;\n // The `?? 0` is unreachable at runtime (the bounds check above guarantees an\n // in-range index into a hole-free Uint32Array) — it satisfies noUncheckedIndexedAccess,\n // which types every typed-array index read as `number | undefined`.\n return layer.tiles[row * layer.width + col] ?? 0;\n}\n\n/**\n * Write a tile GID at a grid position in a tile layer; `getTileAt` and the\n * renderer read it back. Returns `true` when the cell was written, `false` (and\n * writes nothing) when the position is out of bounds or not an integer.\n * The GID is stored raw, Tiled flip bits included. Zero-alloc.\n */\nexport function setTileAt(layer: TileLayer, col: number, row: number, gid: number): boolean {\n if (col < 0 || col >= layer.width || row < 0 || row >= layer.height) return false;\n // A fractional col/row can still land on a whole index (row 0.5 on an even\n // width), which would write a different cell than the one named.\n if (!Number.isInteger(col) || !Number.isInteger(row)) return false;\n layer.tiles[row * layer.width + col] = gid;\n return true;\n}\n\n/** Get the tileset that owns a given GID. Handles Tiled flip bits in the high bits. */\nexport function getTilesetForGid(tilesets: TilesetRef[], gid: number): TilesetRef | undefined {\n const id = gid & GID_FLIP_MASK;\n // Tilesets are ordered by firstGid; find the last one where firstGid <= id\n let result: TilesetRef | undefined;\n for (const ts of tilesets) {\n if (ts.firstGid <= id) {\n result = ts;\n } else {\n break;\n }\n }\n return result;\n}\n\n/** Compute the source rect in a tileset image for a given GID into `out`. Strips Tiled flip bits. Zero-alloc. */\nexport function getTileSourceRectInto(tileset: TilesetRef, gid: number, out: Rect): Rect {\n const localId = (gid & GID_FLIP_MASK) - tileset.firstGid;\n const col = localId % tileset.columns;\n const row = Math.floor(localId / tileset.columns);\n out.x = col * tileset.tileWidth;\n out.y = row * tileset.tileHeight;\n out.width = tileset.tileWidth;\n out.height = tileset.tileHeight;\n return out;\n}\n\n/** Compute the source rect in a tileset image for a given GID. Strips Tiled flip bits. */\nexport function getTileSourceRect(tileset: TilesetRef, gid: number): Rect {\n return getTileSourceRectInto(tileset, gid, { x: 0, y: 0, width: 0, height: 0 });\n}\n","import { TilemapParseError } from './parse-error.js';\nimport type { MapObject, ObjectLayer, TileLayer, TilemapData, TilesetRef } from './tilemap-data.js';\nimport { createTilemapData } from './tilemap-data.js';\n\n// ----- LDtk JSON types -----\n\ninterface LDtkFieldInstance {\n __identifier: string;\n __value: unknown;\n __type: string;\n}\n\ninterface LDtkEntityInstance {\n __identifier: string;\n __grid: [number, number];\n __pivot: [number, number];\n __tile?: { x: number; y: number; w: number; h: number };\n iid: string;\n width: number;\n height: number;\n px: [number, number];\n fieldInstances: LDtkFieldInstance[];\n}\n\ninterface LDtkTileInstance {\n px: [number, number];\n src: [number, number];\n f: number; // flip flags\n t: number; // tile ID\n}\n\ninterface LDtkLayerInstance {\n __identifier: string;\n __type: string;\n __cWid: number;\n __cHei: number;\n __gridSize: number;\n __tilesetDefUid?: number;\n __tilesetRelPath?: string;\n visible: boolean;\n __opacity: number;\n intGridCsv?: number[];\n // Real LDtk output always emits both arrays on every layer instance — only\n // one is ever populated per __type (an AutoLayer's gridTiles is always []).\n // Required (not optional) so a fixture omitting the unused one, as every\n // fixture here did before F057, cannot pass this module's own types.\n gridTiles: LDtkTileInstance[];\n autoLayerTiles: LDtkTileInstance[];\n entityInstances?: LDtkEntityInstance[];\n}\n\ninterface LDtkTilesetDef {\n uid: number;\n identifier: string;\n relPath: string;\n pxWid: number;\n pxHei: number;\n tileGridSize: number;\n __cWid: number;\n __cHei: number;\n}\n\ninterface LDtkLevel {\n identifier: string;\n uid: number;\n pxWid: number;\n pxHei: number;\n worldX: number;\n worldY: number;\n layerInstances?: LDtkLayerInstance[];\n fieldInstances?: LDtkFieldInstance[];\n}\n\ninterface LDtkJSON {\n defaultGridSize: number;\n externalLevels?: boolean;\n defs: {\n tilesets: LDtkTilesetDef[];\n };\n levels: LDtkLevel[];\n}\n\nexport interface ParseLDtkOptions {\n /** Predicate deciding whether an IntGrid value marks a solid cell. Default: value > 0. */\n intGridSolid?: (value: number) => boolean;\n}\n\nexport interface LDtkEntity {\n /** LDtk entity identifier (its type, e.g. \"Player\") — the key you switch on to decide what to spawn. */\n id: string;\n /** Entity position in pixels (LDtk px, pivot-adjusted per the parser convention). */\n x: number;\n y: number;\n /** Entity box size in pixels. */\n width: number;\n height: number;\n /** Custom field instances, keyed by field identifier. */\n fields: Record<string, unknown>;\n}\n\n/**\n * Extract every LDtk entity from a parsed map as a flat, spawn-ready list —\n * the LDtk-entity → ECS spawn convention. Walks all object layers; tile layers are skipped.\n */\nexport function parseLDtkEntities(map: TilemapData): LDtkEntity[] {\n const entities: LDtkEntity[] = [];\n for (const layer of map.layers) {\n if (layer.type !== 'object') continue;\n for (const obj of layer.objects) {\n entities.push({\n id: obj.type,\n x: obj.x,\n y: obj.y,\n width: obj.width,\n height: obj.height,\n fields: obj.properties,\n });\n }\n }\n return entities;\n}\n\n/**\n * Parse an LDtk JSON project into an array of TilemapData (one per level).\n * Returns all levels with their tile and entity layers.\n * Throws TilemapParseError for unsupported formats (externalLevels, invalid input).\n */\nexport function parseLDtk(json: unknown, options: ParseLDtkOptions = {}): TilemapData[] {\n if (\n !json ||\n typeof json !== 'object' ||\n !Array.isArray((json as Record<string, unknown>).levels) ||\n !(json as Record<string, unknown>).defs ||\n !Array.isArray(((json as Record<string, unknown>).defs as Record<string, unknown>).tilesets)\n ) {\n throw new TilemapParseError(\n 'parseLDtk: input is not an LDtk project JSON (missing defs.tilesets or levels).',\n );\n }\n\n const data = json as LDtkJSON;\n\n if (data.externalLevels === true) {\n throw new TilemapParseError(\n 'parseLDtk: projects with \"Save levels to separate files\" (externalLevels) are not supported. Disable it in LDtk ▸ Project settings and re-save.',\n );\n }\n\n const isSolid = options.intGridSolid ?? ((v) => v > 0);\n\n const tilesetDefs = new Map<number, LDtkTilesetDef>();\n for (const ts of data.defs.tilesets) {\n tilesetDefs.set(ts.uid, ts);\n }\n\n const results: TilemapData[] = [];\n\n for (const level of data.levels) {\n const gridSize = data.defaultGridSize;\n const mapWidth = Math.ceil(level.pxWid / gridSize);\n const mapHeight = Math.ceil(level.pxHei / gridSize);\n const map = createTilemapData(mapWidth, mapHeight, gridSize, gridSize);\n\n if (level.fieldInstances) {\n for (const field of level.fieldInstances) {\n map.properties[field.__identifier] = field.__value;\n }\n }\n\n // Pass 1: collect tile-layer tileset uids, sort ascending, assign deterministic firstGids.\n // Tilesets must be sorted by firstGid (ascending) for getTilesetForGid's early-break.\n const firstGidByUid = new Map<number, number>();\n let nextFirstGid = 1;\n\n if (level.layerInstances) {\n const usedTileUids = new Set<number>();\n for (const layerInst of level.layerInstances) {\n if (\n (layerInst.__type === 'Tiles' || layerInst.__type === 'AutoLayer') &&\n layerInst.__tilesetDefUid !== undefined\n ) {\n usedTileUids.add(layerInst.__tilesetDefUid);\n }\n }\n\n const sortedUids = Array.from(usedTileUids).sort((a, b) => a - b);\n for (const uid of sortedUids) {\n const def = tilesetDefs.get(uid);\n if (!def) continue;\n const columns = def.__cWid;\n const tileCount = def.__cWid * def.__cHei;\n firstGidByUid.set(uid, nextFirstGid);\n const ref: TilesetRef = {\n firstGid: nextFirstGid,\n name: def.identifier,\n tileWidth: def.tileGridSize,\n tileHeight: def.tileGridSize,\n columns,\n tileCount,\n image: def.relPath,\n imageWidth: def.pxWid,\n imageHeight: def.pxHei,\n tileProperties: new Map(),\n solidTiles: new Set(),\n };\n map.tilesets.push(ref);\n nextFirstGid += tileCount;\n }\n }\n\n // Pass 2: parse layers in reverse order (LDtk stores top-first; emit bottom-first).\n if (level.layerInstances) {\n for (let i = level.layerInstances.length - 1; i >= 0; i--) {\n const layerInst = level.layerInstances[i]!;\n\n if (layerInst.__type === 'IntGrid') {\n // IntGrid layers are treated as collision grids; IntGrid layers that also\n // carry auto-render tiles keep collision only (visual auto-tiles are M4 scope).\n const csv = layerInst.intGridCsv;\n const cellCount = layerInst.__cWid * layerInst.__cHei;\n const tiles = new Uint32Array(cellCount);\n const intFirstGid = nextFirstGid;\n let maxLocal = 0;\n let hasNonZero = false;\n const solidSet = new Set<number>();\n\n if (csv) {\n for (let j = 0; j < csv.length; j++) {\n const v = csv[j] ?? 0;\n if (v > 0) {\n hasNonZero = true;\n const localId = v - 1;\n if (localId > maxLocal) maxLocal = localId;\n tiles[j] = intFirstGid + localId;\n if (isSolid(v)) solidSet.add(localId);\n }\n }\n }\n\n if (hasNonZero) {\n const tileCount = maxLocal + 1;\n map.tilesets.push({\n firstGid: intFirstGid,\n name: layerInst.__identifier,\n tileWidth: layerInst.__gridSize,\n tileHeight: layerInst.__gridSize,\n columns: tileCount,\n tileCount,\n image: '',\n imageWidth: 0,\n imageHeight: 0,\n tileProperties: new Map(),\n solidTiles: solidSet,\n });\n nextFirstGid += tileCount;\n }\n\n map.layers.push({\n type: 'tile',\n name: layerInst.__identifier,\n width: layerInst.__cWid,\n height: layerInst.__cHei,\n tiles,\n visible: layerInst.visible,\n opacity: layerInst.__opacity,\n offsetX: 0,\n offsetY: 0,\n properties: {},\n });\n } else if (layerInst.__type === 'Tiles' || layerInst.__type === 'AutoLayer') {\n const firstGid = firstGidByUid.get(layerInst.__tilesetDefUid ?? -1) ?? 1;\n map.layers.push(parseTilesLayer(layerInst, mapWidth, mapHeight, gridSize, firstGid));\n } else if (layerInst.__type === 'Entities') {\n map.layers.push(parseEntitiesLayer(layerInst));\n }\n }\n }\n\n results.push(map);\n }\n\n return results;\n}\n\nfunction parseTilesLayer(\n layer: LDtkLayerInstance,\n mapWidth: number,\n mapHeight: number,\n gridSize: number,\n firstGid: number,\n): TileLayer {\n const tiles = new Uint32Array(mapWidth * mapHeight);\n // An AutoLayer's tiles live in autoLayerTiles; its gridTiles is always [].\n // `gridTiles ?? autoLayerTiles` picked the empty gridTiles for every\n // AutoLayer, since `??` only falls through on null/undefined, never on `[]`\n // — select by __type instead, which is the field LDtk itself keys on.\n const tileInstances = layer.__type === 'AutoLayer' ? layer.autoLayerTiles : layer.gridTiles;\n\n for (const ti of tileInstances) {\n const col = Math.floor(ti.px[0] / gridSize);\n const row = Math.floor(ti.px[1] / gridSize);\n if (col >= 0 && col < mapWidth && row >= 0 && row < mapHeight) {\n tiles[row * mapWidth + col] = firstGid + ti.t;\n }\n }\n\n return {\n type: 'tile',\n name: layer.__identifier,\n width: mapWidth,\n height: mapHeight,\n tiles,\n visible: layer.visible,\n opacity: layer.__opacity,\n offsetX: 0,\n offsetY: 0,\n properties: {},\n };\n}\n\nfunction parseEntitiesLayer(layer: LDtkLayerInstance): ObjectLayer {\n const objects: MapObject[] = (layer.entityInstances ?? []).map((ent, idx) => {\n const props: Record<string, unknown> = {};\n for (const field of ent.fieldInstances) {\n props[field.__identifier] = field.__value;\n }\n return {\n id: idx + 1,\n name: ent.__identifier,\n type: ent.__identifier,\n x: ent.px[0],\n y: ent.px[1],\n width: ent.width,\n height: ent.height,\n rotation: 0,\n properties: props,\n };\n });\n\n return {\n type: 'object',\n name: layer.__identifier,\n objects,\n visible: layer.visible,\n opacity: layer.__opacity,\n properties: {},\n };\n}\n","import { TilemapParseError } from './parse-error.js';\nimport type {\n MapLayer,\n MapObject,\n ObjectLayer,\n TileAnimation,\n TileLayer,\n TilemapData,\n TilesetRef,\n} from './tilemap-data.js';\nimport { createTilemapData } from './tilemap-data.js';\n\n// ----- Tiled JSON types (.tmj format) -----\n\ninterface TiledProperty {\n name: string;\n type: string;\n value: unknown;\n}\n\ninterface TiledTileLayer {\n type: 'tilelayer';\n name: string;\n width: number;\n height: number;\n data: number[] | string;\n encoding?: string;\n compression?: string;\n chunks?: unknown[];\n visible: boolean;\n opacity: number;\n offsetx?: number;\n offsety?: number;\n properties?: TiledProperty[];\n}\n\ninterface TiledObject {\n id: number;\n name: string;\n type?: string;\n class?: string;\n x: number;\n y: number;\n width: number;\n height: number;\n rotation: number;\n properties?: TiledProperty[];\n}\n\ninterface TiledObjectLayer {\n type: 'objectgroup';\n name: string;\n objects: TiledObject[];\n visible: boolean;\n opacity: number;\n properties?: TiledProperty[];\n}\n\ntype TiledLayer = TiledTileLayer | TiledObjectLayer;\n\ninterface TiledAnimationFrame {\n tileid: number;\n /** Milliseconds. */\n duration: number;\n}\n\ninterface TiledTile {\n id: number;\n properties?: TiledProperty[];\n type?: string;\n class?: string;\n animation?: TiledAnimationFrame[];\n}\n\ninterface TiledTileset {\n firstgid: number;\n name: string;\n tilewidth: number;\n tileheight: number;\n columns: number;\n tilecount: number;\n image: string;\n imagewidth: number;\n imageheight: number;\n tiles?: TiledTile[];\n properties?: TiledProperty[];\n source?: string;\n}\n\ninterface TiledMapJSON {\n width: number;\n height: number;\n tilewidth: number;\n tileheight: number;\n orientation: string;\n infinite?: boolean;\n layers: TiledLayer[];\n tilesets: TiledTileset[];\n properties?: TiledProperty[];\n}\n\n/** Convert Tiled properties array to a Record. */\nfunction parseProperties(props?: TiledProperty[]): Record<string, unknown> {\n if (!props || props.length === 0) return {};\n const result: Record<string, unknown> = {};\n for (const p of props) {\n result[p.name] = p.value;\n }\n return result;\n}\n\n/**\n * Build a tile's Tiled animation (frame durations in ms) into cumulative seconds.\n * Returns `undefined` for an empty animation or one whose durations sum to 0 —\n * such a tile draws as authored.\n */\nfunction parseTileAnimation(ts: TiledTileset, tile: TiledTile): TileAnimation | undefined {\n const source = tile.animation;\n if (source === undefined || source.length === 0) return undefined;\n const frames = new Uint32Array(source.length);\n const ends = new Float64Array(source.length);\n // Summed in ms and divided once per frame so integer-ms inputs give exact seconds.\n let totalMs = 0;\n for (let i = 0; i < source.length; i++) {\n const frame = source[i]!;\n const tileid = frame.tileid;\n const duration = frame.duration;\n if (!Number.isInteger(tileid) || tileid < 0 || tileid >= ts.tilecount) {\n throw new TilemapParseError(\n `parseTiled: tileset \"${ts.name}\" tile ${tile.id} animation frame ${i} has tileid ${tileid} — expected an integer in [0, ${ts.tilecount}).`,\n );\n }\n if (!Number.isFinite(duration) || duration < 0) {\n throw new TilemapParseError(\n `parseTiled: tileset \"${ts.name}\" tile ${tile.id} animation frame ${i} has duration ${duration} — expected a finite number of milliseconds >= 0.`,\n );\n }\n totalMs += duration;\n frames[i] = tileid;\n ends[i] = totalMs / 1000;\n }\n if (totalMs === 0) return undefined;\n return { frames, ends, duration: totalMs / 1000 };\n}\n\n/**\n * Parse a Tiled .tmj (JSON) map into TilemapData.\n * Supports orthogonal maps with CSV tile layers and object layers.\n * Throws TilemapParseError for unsupported formats (infinite, non-orthogonal,\n * external tilesets, base64/compressed/chunked layer data).\n */\nexport function parseTiled(json: unknown): TilemapData {\n if (\n !json ||\n typeof json !== 'object' ||\n typeof (json as Record<string, unknown>).width !== 'number' ||\n typeof (json as Record<string, unknown>).height !== 'number' ||\n !Array.isArray((json as Record<string, unknown>).layers) ||\n !Array.isArray((json as Record<string, unknown>).tilesets)\n ) {\n throw new TilemapParseError(\n 'parseTiled: input is not a Tiled map JSON (missing width/height/layers/tilesets).',\n );\n }\n\n const data = json as TiledMapJSON;\n\n if (data.infinite === true) {\n throw new TilemapParseError(\n 'parseTiled: infinite maps are not supported. In Tiled: Map ▸ Map Properties ▸ set \"Infinite\" to false, then re-export.',\n );\n }\n if (data.orientation && data.orientation !== 'orthogonal') {\n throw new TilemapParseError(\n `parseTiled: orientation \"${data.orientation}\" is not supported — only orthogonal maps are supported.`,\n );\n }\n\n const map = createTilemapData(data.width, data.height, data.tilewidth, data.tileheight);\n map.properties = parseProperties(data.properties);\n\n // Parse tilesets\n for (const ts of data.tilesets) {\n if (ts.source !== undefined) {\n throw new TilemapParseError(\n `parseTiled: external tileset \"${ts.source}\" is not supported. Embed tilesets on export (Tiled ▸ Map ▸ \"Embed tilesets\") or run it through \\`flare tiled-to-flare\\` (which embeds tilesets by default).`,\n );\n }\n\n const tileProperties = new Map<number, Record<string, unknown>>();\n const solidTiles = new Set<number>();\n let animations: Map<number, TileAnimation> | undefined;\n\n if (ts.tiles) {\n for (const tile of ts.tiles) {\n const props = parseProperties(tile.properties);\n if (Object.keys(props).length > 0) {\n tileProperties.set(tile.id, props);\n }\n // Mark as solid if it has a \"collision\" or \"solid\" property, or type/class is \"solid\"\n const tileType = tile.type ?? tile.class ?? '';\n if (tileType === 'solid' || props.solid === true || props.collision === true) {\n solidTiles.add(tile.id);\n }\n const animation = parseTileAnimation(ts, tile);\n if (animation !== undefined) {\n animations ??= new Map();\n animations.set(tile.id, animation);\n }\n }\n }\n\n const ref: TilesetRef = {\n firstGid: ts.firstgid,\n name: ts.name,\n tileWidth: ts.tilewidth,\n tileHeight: ts.tileheight,\n columns: ts.columns,\n tileCount: ts.tilecount,\n image: ts.image,\n imageWidth: ts.imagewidth,\n imageHeight: ts.imageheight,\n tileProperties,\n solidTiles,\n };\n if (animations !== undefined) ref.animations = animations;\n map.tilesets.push(ref);\n }\n\n // Sort tilesets by firstGid\n map.tilesets.sort((a, b) => a.firstGid - b.firstGid);\n\n // Parse layers\n for (const layer of data.layers) {\n map.layers.push(parseLayer(layer));\n }\n\n return map;\n}\n\nfunction parseLayer(layer: TiledLayer): MapLayer {\n if (layer.type === 'tilelayer') return parseTileLayer(layer);\n if (layer.type === 'objectgroup') return parseObjectLayer(layer);\n const l = layer as { type: string; name?: string };\n throw new TilemapParseError(\n `parseTiled: layer \"${l.name ?? ''}\" has unsupported type \"${l.type}\". Only tilelayer and objectgroup are supported — flatten group layers and remove image layers before export.`,\n );\n}\n\nfunction parseTileLayer(layer: TiledTileLayer): TileLayer {\n if (\n (layer.encoding !== undefined && layer.encoding !== 'csv') ||\n layer.compression !== undefined ||\n layer.chunks !== undefined\n ) {\n throw new TilemapParseError(\n 'parseTiled: base64/compressed/chunked (infinite) layer data is not supported. In Tiled export options set Tile Layer Format to \"CSV\".',\n );\n }\n if (typeof layer.data === 'string') {\n throw new TilemapParseError(\n 'parseTiled: base64/compressed/chunked (infinite) layer data is not supported. In Tiled export options set Tile Layer Format to \"CSV\".',\n );\n }\n // layer.data is number[] here — Uint32Array.from preserves flip-bit GIDs\n // (values up to 0xffffffff), unlike a Float32Array's 24-bit mantissa.\n return {\n type: 'tile',\n name: layer.name,\n width: layer.width,\n height: layer.height,\n tiles: Uint32Array.from(layer.data),\n visible: layer.visible,\n opacity: layer.opacity,\n offsetX: layer.offsetx ?? 0,\n offsetY: layer.offsety ?? 0,\n properties: parseProperties(layer.properties),\n };\n}\n\nfunction parseObjectLayer(layer: TiledObjectLayer): ObjectLayer {\n const objects: MapObject[] = layer.objects.map((obj) => ({\n id: obj.id,\n name: obj.name,\n type: obj.type ?? obj.class ?? '',\n x: obj.x,\n y: obj.y,\n width: obj.width,\n height: obj.height,\n rotation: obj.rotation,\n properties: parseProperties(obj.properties),\n }));\n\n return {\n type: 'object',\n name: layer.name,\n objects,\n visible: layer.visible,\n opacity: layer.opacity,\n properties: parseProperties(layer.properties),\n };\n}\n","import type { AABBShape } from '@flare-engine/physics';\nimport { AABB } from '@flare-engine/physics';\nimport type { TileLayer, TilemapData, TilesetRef } from './tilemap-data.js';\nimport { GID_FLIP_MASK, getTilesetForGid } from './tilemap-data.js';\n\n/** A collision body extracted from a solid tile. */\nexport interface TileCollider {\n /** World position of the tile center. */\n x: number;\n y: number;\n /** AABB collision shape. */\n shape: AABBShape;\n /** Grid column. */\n col: number;\n /** Grid row. */\n row: number;\n /** The tile GID (flip bits stripped — AABB is symmetric, downstream lookups want the real id). */\n gid: number;\n}\n\n/**\n * Extract collision shapes from solid tiles in a tilemap.\n * A tile is considered solid if its tileset marks the local tile ID as solid.\n *\n * @param map The parsed tilemap data.\n * @param layerName Optional: only extract from this layer. If omitted, extracts from all tile layers.\n * @returns Array of TileCollider bodies.\n */\nexport function extractColliders(map: TilemapData, layerName?: string): TileCollider[] {\n const colliders: TileCollider[] = [];\n const tw = map.tileWidth;\n const th = map.tileHeight;\n\n for (const layer of map.layers) {\n if (layer.type !== 'tile') continue;\n if (layerName !== undefined && layer.name !== layerName) continue;\n\n extractFromLayer(layer, map.tilesets, tw, th, colliders);\n }\n\n return colliders;\n}\n\nfunction extractFromLayer(\n layer: TileLayer,\n tilesets: TilesetRef[],\n tw: number,\n th: number,\n out: TileCollider[],\n): void {\n for (let row = 0; row < layer.height; row++) {\n for (let col = 0; col < layer.width; col++) {\n const gid = layer.tiles[row * layer.width + col] ?? 0;\n if (gid === 0) continue;\n\n const tileset = getTilesetForGid(tilesets, gid);\n if (!tileset) continue;\n\n const localId = (gid & GID_FLIP_MASK) - tileset.firstGid;\n if (!tileset.solidTiles.has(localId)) continue;\n\n out.push({\n x: col * tw + tw * 0.5 + layer.offsetX,\n y: row * th + th * 0.5 + layer.offsetY,\n shape: AABB(tw, th),\n col,\n row,\n gid: gid & GID_FLIP_MASK,\n });\n }\n }\n}\n","import type { SkImageLike } from '@flare-engine/assets';\nimport type { Rect } from '@flare-engine/math';\nimport type { AnySpriteEffect, Camera2D } from '@flare-engine/render';\nimport { SpriteBatch } from '@flare-engine/render';\nimport type { TileAnimation, TileLayer, TilemapData, TilesetRef } from './tilemap-data.js';\nimport {\n GID_FLIP_MASK,\n getTileAt,\n getTileSourceRectInto,\n getTilesetForGid,\n} from './tilemap-data.js';\n\n// Tiled GID flag bits (kept module-private; tilemap-data.ts owns the public mask).\nconst FLIP_H = 0x80000000;\nconst FLIP_V = 0x40000000;\nconst FLIP_D = 0x20000000;\nconst QUARTER_TURN = Math.PI / 2;\n\n/**\n * Per-draw options for `TilemapRenderer.drawInto` / `draw`.\n *\n * `effect` is set on every queued tile command. Batch runs key on the effect\n * by reference, so one shared instance (e.g. an ambient `tint()`) keeps every\n * tile — and any sprite drawn with the same instance — in a single run.\n * `alphaScale` multiplies each layer's own `opacity` (default 1).\n * `time` (seconds, e.g. the clock's elapsed) advances Tiled tile animations\n * parsed onto `TilesetRef.animations`; it wraps in both directions. Without\n * it (or when non-finite) every tile draws as authored.\n */\nexport interface TilemapDrawOptions {\n effect?: AnySpriteEffect;\n alphaScale?: number;\n time?: number;\n}\n\n/** Local tile id of the frame an animation shows at `time` (seconds, finite). */\nfunction animatedLocalId(anim: TileAnimation, time: number): number {\n let t = time % anim.duration;\n if (t < 0) t += anim.duration;\n const ends = anim.ends;\n const last = ends.length - 1;\n let i = 0;\n // A frame boundary belongs to the next frame; ends[last] === duration > t stops the scan.\n while (i < last && t >= (ends[i] ?? 0)) i++;\n // The `?? 0` is unreachable (i <= last < frames.length) — it satisfies noUncheckedIndexedAccess.\n return anim.frames[i] ?? 0;\n}\n\n/**\n * TilemapRenderer — draws a tilemap with viewport culling.\n * Only tiles visible to the camera are submitted to the SpriteBatch.\n */\nexport class TilemapRenderer {\n /** The tilemap data to render. */\n readonly map: TilemapData;\n\n /** SpriteBatch used for batched tile rendering. */\n readonly batch: SpriteBatch;\n\n /** Map from tileset name → SkImage. Set via setTilesetImage(). */\n private _images = new Map<string, SkImageLike>();\n\n /** Images in `map.tilesets` order, refreshed from `_images` at the start of each draw. */\n private _tilesetImages: (SkImageLike | undefined)[] = [];\n\n /** Reusable bounds rect — avoids per-frame allocation from camera.getBounds(). */\n private _boundsBuf: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n /** Reusable source rect — avoids a per-tile allocation from getTileSourceRect. */\n private _srcBuf: Rect = { x: 0, y: 0, width: 0, height: 0 };\n\n constructor(map: TilemapData) {\n this.map = map;\n this.batch = new SpriteBatch();\n }\n\n /** Associate a loaded image with a tileset by name. */\n setTilesetImage(tilesetName: string, image: SkImageLike): void {\n this._images.set(tilesetName, image);\n }\n\n /**\n * Queue visible tile layers into a caller-owned `batch` using the camera for\n * culling. Does NOT flush — the caller owns the single flush so tiles z-order\n * under sprites. Zero-alloc: reuses the internal bounds buffer.\n *\n * Each tile's `alpha` is `layer.opacity * opts.alphaScale`; `opts.effect`\n * is applied to every tile; `opts.time` picks each animated tile's frame\n * (see `TilemapDrawOptions`).\n */\n drawInto(camera: Camera2D, batch: SpriteBatch, opts?: TilemapDrawOptions): void {\n const bounds = camera.getBoundsInto(this._boundsBuf);\n const tw = this.map.tileWidth;\n const th = this.map.tileHeight;\n const effect = opts?.effect;\n const alphaScale = opts?.alphaScale ?? 1;\n // NaN stands for \"no time\": the layer pass animates only when `time` is finite.\n const time = opts?.time ?? Number.NaN;\n\n const tilesets = this.map.tilesets;\n const images = this._tilesetImages;\n images.length = tilesets.length;\n for (let i = 0; i < tilesets.length; i++) {\n const tileset = tilesets[i];\n if (tileset !== undefined) images[i] = this._images.get(tileset.name);\n }\n\n for (const layer of this.map.layers) {\n if (layer.type !== 'tile' || !layer.visible) continue;\n this._drawTileLayer(\n layer,\n bounds.x,\n bounds.y,\n bounds.width,\n bounds.height,\n tw,\n th,\n batch,\n effect,\n layer.opacity * alphaScale,\n time,\n );\n }\n }\n\n /**\n * Draw visible tile layers using the camera for culling.\n * Call `flush` on a callback to issue the actual draw calls.\n * Delegates to `drawInto` so culling and queuing logic live in one place;\n * `opts` is threaded through unchanged.\n */\n draw(camera: Camera2D, flush: (batch: SpriteBatch) => void, opts?: TilemapDrawOptions): void {\n this.drawInto(camera, this.batch, opts);\n flush(this.batch);\n }\n\n // Tiled flip bits: H/V become the batch's flipX/flipY; the diagonal bit is a\n // quarter turn about the tile centre composed with the flip Tiled defines\n // (D+H = 90° CW, D+V = 90° CCW, D = flipY + CW, D+H+V = flipX + CW).\n private _drawTileLayer(\n layer: TileLayer,\n viewX: number,\n viewY: number,\n viewW: number,\n viewH: number,\n tw: number,\n th: number,\n batch: SpriteBatch,\n effect: AnySpriteEffect | undefined,\n alpha: number,\n time: number,\n ): void {\n const offsetX = layer.offsetX;\n const offsetY = layer.offsetY;\n const animate = Number.isFinite(time);\n const tilesets = this.map.tilesets;\n const images = this._tilesetImages;\n\n // The current run: `tileset` and `image` own every stripped gid in [runLo, runHi).\n let tileset: TilesetRef | undefined;\n let image: SkImageLike | undefined;\n let runLo = 1;\n let runHi = 0;\n\n // Calculate visible tile range (clamped to layer bounds)\n const startCol = Math.max(0, Math.floor((viewX - offsetX) / tw));\n const startRow = Math.max(0, Math.floor((viewY - offsetY) / th));\n const endCol = Math.min(layer.width - 1, Math.floor((viewX - offsetX + viewW) / tw));\n const endRow = Math.min(layer.height - 1, Math.floor((viewY - offsetY + viewH) / th));\n\n for (let row = startRow; row <= endRow; row++) {\n for (let col = startCol; col <= endCol; col++) {\n const gid = getTileAt(layer, col, row);\n if (gid === 0) continue;\n\n const id = gid & GID_FLIP_MASK;\n if (id < runLo || id >= runHi) {\n tileset = getTilesetForGid(tilesets, id);\n image = undefined;\n runLo = 1;\n runHi = 0;\n if (tileset !== undefined) {\n // The run covers only gids the front-to-back walk maps to this tileset again:\n // at or above every firstGid up to it, below the next one and its own end.\n let index = 0;\n runLo = tileset.firstGid;\n for (let ts = tilesets[0]; ts !== undefined && ts !== tileset; ts = tilesets[++index]) {\n if (ts.firstGid > runLo) runLo = ts.firstGid;\n }\n image = images[index];\n runHi = tileset.firstGid + tileset.tileCount;\n const next = tilesets[index + 1];\n if (next !== undefined && next.firstGid < runHi) runHi = next.firstGid;\n }\n }\n if (!tileset) continue;\n if (!image) continue;\n\n // An animated tile sources its current frame; flip bits still come from `gid`.\n let srcGid = gid;\n if (animate && tileset.animations !== undefined) {\n const anim = tileset.animations.get(id - tileset.firstGid);\n if (anim !== undefined) srcGid = tileset.firstGid + animatedLocalId(anim, time);\n }\n\n // Strips flip bits; writes into the reusable buffer, no per-tile allocation.\n const src = getTileSourceRectInto(tileset, srcGid, this._srcBuf);\n\n // Bit tests only — `gid & FLIP_H` is a negative Int32 when set, so compare to 0.\n const h = (gid & FLIP_H) !== 0;\n const v = (gid & FLIP_V) !== 0;\n const d = (gid & FLIP_D) !== 0;\n let flipX = h;\n let flipY = v;\n let rotation = 0;\n if (d) {\n rotation = !h && v ? -QUARTER_TURN : QUARTER_TURN;\n flipX = h && v;\n flipY = !h && !v;\n }\n\n // Centre anchor keeps a turned tile in its cell; the stored dstX/dstY\n // stay the cell's top-left. Positional slots — no per-tile object.\n batch.drawRaw(\n image,\n src.x,\n src.y,\n src.width,\n src.height,\n col * tw + offsetX + tw * 0.5,\n row * th + offsetY + th * 0.5,\n tw,\n th,\n effect,\n 0.5,\n 0.5,\n alpha,\n rotation,\n false,\n 'normal',\n flipX,\n flipY,\n );\n }\n }\n }\n}\n"],"mappings":";;;;AACA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;;ACHA,MAAa,gBAAgB;AAE7B,MAAMA,WAAS;AACf,MAAMC,WAAS;AACf,MAAMC,W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,MAAM,KAAK,UAAU,KAAK,IAC1B,MAAM,KAAK,UAAU,KAAK,IAC1B,IACA,IACA,QACA,IACA,IACA,OACA,UACA,OACA,UACA,OACA,KACF;EACF;CAEJ;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flare-engine/tilemap",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.13",
|
|
4
4
|
"description": "Tiled/LDtk parser, culled tilemap renderer",
|
|
5
5
|
"keywords": ["flare-engine", "tilemap", "tiled", "ldtk", "react-native", "typescript"],
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -37,10 +37,10 @@
|
|
|
37
37
|
"typecheck": "tsc --noEmit"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@flare-engine/assets": "^0.4.
|
|
41
|
-
"@flare-engine/math": "^0.4.
|
|
42
|
-
"@flare-engine/physics": "^0.4.
|
|
43
|
-
"@flare-engine/render": "^0.4.
|
|
40
|
+
"@flare-engine/assets": "^0.4.13",
|
|
41
|
+
"@flare-engine/math": "^0.4.13",
|
|
42
|
+
"@flare-engine/physics": "^0.4.13",
|
|
43
|
+
"@flare-engine/render": "^0.4.13"
|
|
44
44
|
},
|
|
45
45
|
"engines": {
|
|
46
46
|
"node": ">=20"
|