@flare-engine/tilemap 0.2.0 → 0.3.0

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/dist/index.js CHANGED
@@ -1,414 +1,467 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _flare_engine_physics = require("@flare-engine/physics");
3
+ let _flare_engine_render = require("@flare-engine/render");
4
+ //#region src/parse-error.ts
5
+ /** Thrown by parseTiled/parseLDtk when a map uses an unsupported format or feature. */
6
+ var TilemapParseError = class extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "TilemapParseError";
10
+ }
9
11
  };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- TilemapRenderer: () => TilemapRenderer,
24
- createTilemapData: () => createTilemapData,
25
- extractColliders: () => extractColliders,
26
- getTileAt: () => getTileAt,
27
- getTileSourceRect: () => getTileSourceRect,
28
- getTilesetForGid: () => getTilesetForGid,
29
- parseLDtk: () => parseLDtk,
30
- parseTiled: () => parseTiled
31
- });
32
- module.exports = __toCommonJS(index_exports);
33
-
34
- // src/tilemap-data.ts
12
+ //#endregion
13
+ //#region src/tilemap-data.ts
14
+ /** Low 29 bits of a Tiled GID — Tiled stores flip state in the high 3 bits. */
15
+ const GID_FLIP_MASK = 536870911;
16
+ const FLIP_H = 2147483648;
17
+ const FLIP_V = 1073741824;
18
+ const FLIP_D = 536870912;
19
+ /** Strip the Tiled flip bits from a raw GID, returning the real global tile id. */
20
+ function stripGidFlags(gid) {
21
+ return gid & GID_FLIP_MASK;
22
+ }
23
+ /**
24
+ * Decode the Tiled flip bits encoded in the high bits of a raw GID.
25
+ * Note: `gid & 0x80000000` yields a negative Int32 when the bit is set;
26
+ * compare with `!== 0`, not `> 0`.
27
+ */
28
+ function decodeGidFlags(gid) {
29
+ return {
30
+ horizontal: (gid & FLIP_H) !== 0,
31
+ vertical: (gid & FLIP_V) !== 0,
32
+ diagonal: (gid & FLIP_D) !== 0
33
+ };
34
+ }
35
+ /** Create an empty TilemapData. */
35
36
  function createTilemapData(width, height, tileWidth, tileHeight) {
36
- return {
37
- width,
38
- height,
39
- tileWidth,
40
- tileHeight,
41
- layers: [],
42
- tilesets: [],
43
- properties: {}
44
- };
37
+ return {
38
+ width,
39
+ height,
40
+ tileWidth,
41
+ tileHeight,
42
+ layers: [],
43
+ tilesets: [],
44
+ properties: {}
45
+ };
45
46
  }
47
+ /** Get a tile GID at a grid position from a tile layer. Returns 0 if out of bounds. */
46
48
  function getTileAt(layer, col, row) {
47
- if (col < 0 || col >= layer.width || row < 0 || row >= layer.height) return 0;
48
- return layer.tiles[row * layer.width + col] ?? 0;
49
+ if (col < 0 || col >= layer.width || row < 0 || row >= layer.height) return 0;
50
+ return layer.tiles[row * layer.width + col] ?? 0;
49
51
  }
52
+ /** Get the tileset that owns a given GID. Handles Tiled flip bits in the high bits. */
50
53
  function getTilesetForGid(tilesets, gid) {
51
- let result;
52
- for (const ts of tilesets) {
53
- if (ts.firstGid <= gid) {
54
- result = ts;
55
- } else {
56
- break;
57
- }
58
- }
59
- return result;
54
+ const id = gid & GID_FLIP_MASK;
55
+ let result;
56
+ for (const ts of tilesets) if (ts.firstGid <= id) result = ts;
57
+ else break;
58
+ return result;
60
59
  }
60
+ /** Compute the source rect in a tileset image for a given GID. Strips Tiled flip bits. */
61
61
  function getTileSourceRect(tileset, gid) {
62
- const localId = gid - tileset.firstGid;
63
- const col = localId % tileset.columns;
64
- const row = Math.floor(localId / tileset.columns);
65
- return {
66
- x: col * tileset.tileWidth,
67
- y: row * tileset.tileHeight,
68
- width: tileset.tileWidth,
69
- height: tileset.tileHeight
70
- };
62
+ const localId = (gid & GID_FLIP_MASK) - tileset.firstGid;
63
+ const col = localId % tileset.columns;
64
+ const row = Math.floor(localId / tileset.columns);
65
+ return {
66
+ x: col * tileset.tileWidth,
67
+ y: row * tileset.tileHeight,
68
+ width: tileset.tileWidth,
69
+ height: tileset.tileHeight
70
+ };
71
71
  }
72
-
73
- // src/tiled-parser.ts
72
+ //#endregion
73
+ //#region src/ldtk-parser.ts
74
+ /**
75
+ * Extract every LDtk entity from a parsed map as a flat, spawn-ready list —
76
+ * the LDtk-entity → ECS spawn convention. Walks all object layers; tile layers are skipped.
77
+ */
78
+ function parseLDtkEntities(map) {
79
+ const entities = [];
80
+ for (const layer of map.layers) {
81
+ if (layer.type !== "object") continue;
82
+ for (const obj of layer.objects) entities.push({
83
+ id: obj.type,
84
+ x: obj.x,
85
+ y: obj.y,
86
+ width: obj.width,
87
+ height: obj.height,
88
+ fields: obj.properties
89
+ });
90
+ }
91
+ return entities;
92
+ }
93
+ /**
94
+ * Parse an LDtk JSON project into an array of TilemapData (one per level).
95
+ * Returns all levels with their tile and entity layers.
96
+ * Throws TilemapParseError for unsupported formats (externalLevels, invalid input).
97
+ */
98
+ function parseLDtk(json, options = {}) {
99
+ if (!json || typeof json !== "object" || !Array.isArray(json.levels) || !json.defs || !Array.isArray(json.defs.tilesets)) throw new TilemapParseError("parseLDtk: input is not an LDtk project JSON (missing defs.tilesets or levels).");
100
+ const data = json;
101
+ if (data.externalLevels === true) throw new TilemapParseError("parseLDtk: projects with \"Save levels to separate files\" (externalLevels) are not supported. Disable it in LDtk ▸ Project settings and re-save.");
102
+ const isSolid = options.intGridSolid ?? ((v) => v > 0);
103
+ const tilesetDefs = /* @__PURE__ */ new Map();
104
+ for (const ts of data.defs.tilesets) tilesetDefs.set(ts.uid, ts);
105
+ const results = [];
106
+ for (const level of data.levels) {
107
+ const gridSize = data.defaultGridSize;
108
+ const mapWidth = Math.ceil(level.pxWid / gridSize);
109
+ const mapHeight = Math.ceil(level.pxHei / gridSize);
110
+ const map = createTilemapData(mapWidth, mapHeight, gridSize, gridSize);
111
+ if (level.fieldInstances) for (const field of level.fieldInstances) map.properties[field.__identifier] = field.__value;
112
+ const firstGidByUid = /* @__PURE__ */ new Map();
113
+ let nextFirstGid = 1;
114
+ if (level.layerInstances) {
115
+ const usedTileUids = /* @__PURE__ */ new Set();
116
+ for (const layerInst of level.layerInstances) if ((layerInst.__type === "Tiles" || layerInst.__type === "AutoLayer") && layerInst.__tilesetDefUid !== void 0) usedTileUids.add(layerInst.__tilesetDefUid);
117
+ const sortedUids = Array.from(usedTileUids).sort((a, b) => a - b);
118
+ for (const uid of sortedUids) {
119
+ const def = tilesetDefs.get(uid);
120
+ if (!def) continue;
121
+ const columns = def.__cWid;
122
+ const tileCount = def.__cWid * def.__cHei;
123
+ firstGidByUid.set(uid, nextFirstGid);
124
+ const ref = {
125
+ firstGid: nextFirstGid,
126
+ name: def.identifier,
127
+ tileWidth: def.tileGridSize,
128
+ tileHeight: def.tileGridSize,
129
+ columns,
130
+ tileCount,
131
+ image: def.relPath,
132
+ imageWidth: def.pxWid,
133
+ imageHeight: def.pxHei,
134
+ tileProperties: /* @__PURE__ */ new Map(),
135
+ solidTiles: /* @__PURE__ */ new Set()
136
+ };
137
+ map.tilesets.push(ref);
138
+ nextFirstGid += tileCount;
139
+ }
140
+ }
141
+ if (level.layerInstances) for (let i = level.layerInstances.length - 1; i >= 0; i--) {
142
+ const layerInst = level.layerInstances[i];
143
+ if (layerInst.__type === "IntGrid") {
144
+ const csv = layerInst.intGridCsv;
145
+ const cellCount = layerInst.__cWid * layerInst.__cHei;
146
+ const tiles = new Array(cellCount).fill(0);
147
+ const intFirstGid = nextFirstGid;
148
+ let maxLocal = 0;
149
+ let hasNonZero = false;
150
+ const solidSet = /* @__PURE__ */ new Set();
151
+ if (csv) for (let j = 0; j < csv.length; j++) {
152
+ const v = csv[j] ?? 0;
153
+ if (v > 0) {
154
+ hasNonZero = true;
155
+ const localId = v - 1;
156
+ if (localId > maxLocal) maxLocal = localId;
157
+ tiles[j] = intFirstGid + localId;
158
+ if (isSolid(v)) solidSet.add(localId);
159
+ }
160
+ }
161
+ if (hasNonZero) {
162
+ const tileCount = maxLocal + 1;
163
+ map.tilesets.push({
164
+ firstGid: intFirstGid,
165
+ name: layerInst.__identifier,
166
+ tileWidth: layerInst.__gridSize,
167
+ tileHeight: layerInst.__gridSize,
168
+ columns: tileCount,
169
+ tileCount,
170
+ image: "",
171
+ imageWidth: 0,
172
+ imageHeight: 0,
173
+ tileProperties: /* @__PURE__ */ new Map(),
174
+ solidTiles: solidSet
175
+ });
176
+ nextFirstGid += tileCount;
177
+ }
178
+ map.layers.push({
179
+ type: "tile",
180
+ name: layerInst.__identifier,
181
+ width: layerInst.__cWid,
182
+ height: layerInst.__cHei,
183
+ tiles,
184
+ visible: layerInst.visible,
185
+ opacity: layerInst.__opacity,
186
+ offsetX: 0,
187
+ offsetY: 0,
188
+ properties: {}
189
+ });
190
+ } else if (layerInst.__type === "Tiles" || layerInst.__type === "AutoLayer") {
191
+ const firstGid = firstGidByUid.get(layerInst.__tilesetDefUid ?? -1) ?? 1;
192
+ map.layers.push(parseTilesLayer(layerInst, mapWidth, mapHeight, gridSize, firstGid));
193
+ } else if (layerInst.__type === "Entities") map.layers.push(parseEntitiesLayer(layerInst));
194
+ }
195
+ results.push(map);
196
+ }
197
+ return results;
198
+ }
199
+ function parseTilesLayer(layer, mapWidth, mapHeight, gridSize, firstGid) {
200
+ const tiles = new Array(mapWidth * mapHeight).fill(0);
201
+ const tileInstances = layer.gridTiles ?? layer.autoLayerTiles ?? [];
202
+ for (const ti of tileInstances) {
203
+ const col = Math.floor(ti.px[0] / gridSize);
204
+ const row = Math.floor(ti.px[1] / gridSize);
205
+ if (col >= 0 && col < mapWidth && row >= 0 && row < mapHeight) tiles[row * mapWidth + col] = firstGid + ti.t;
206
+ }
207
+ return {
208
+ type: "tile",
209
+ name: layer.__identifier,
210
+ width: mapWidth,
211
+ height: mapHeight,
212
+ tiles,
213
+ visible: layer.visible,
214
+ opacity: layer.__opacity,
215
+ offsetX: 0,
216
+ offsetY: 0,
217
+ properties: {}
218
+ };
219
+ }
220
+ function parseEntitiesLayer(layer) {
221
+ const objects = (layer.entityInstances ?? []).map((ent, idx) => {
222
+ const props = {};
223
+ for (const field of ent.fieldInstances) props[field.__identifier] = field.__value;
224
+ return {
225
+ id: idx + 1,
226
+ name: ent.__identifier,
227
+ type: ent.__identifier,
228
+ x: ent.px[0],
229
+ y: ent.px[1],
230
+ width: ent.width,
231
+ height: ent.height,
232
+ rotation: 0,
233
+ properties: props
234
+ };
235
+ });
236
+ return {
237
+ type: "object",
238
+ name: layer.__identifier,
239
+ objects,
240
+ visible: layer.visible,
241
+ opacity: layer.__opacity,
242
+ properties: {}
243
+ };
244
+ }
245
+ //#endregion
246
+ //#region src/tiled-parser.ts
247
+ /** Convert Tiled properties array to a Record. */
74
248
  function parseProperties(props) {
75
- if (!props || props.length === 0) return {};
76
- const result = {};
77
- for (const p of props) {
78
- result[p.name] = p.value;
79
- }
80
- return result;
249
+ if (!props || props.length === 0) return {};
250
+ const result = {};
251
+ for (const p of props) result[p.name] = p.value;
252
+ return result;
81
253
  }
254
+ /**
255
+ * Parse a Tiled .tmj (JSON) map into TilemapData.
256
+ * Supports orthogonal maps with CSV tile layers and object layers.
257
+ * Throws TilemapParseError for unsupported formats (infinite, non-orthogonal,
258
+ * external tilesets, base64/compressed/chunked layer data).
259
+ */
82
260
  function parseTiled(json) {
83
- const data = json;
84
- const map = createTilemapData(data.width, data.height, data.tilewidth, data.tileheight);
85
- map.properties = parseProperties(data.properties);
86
- for (const ts of data.tilesets) {
87
- const tileProperties = /* @__PURE__ */ new Map();
88
- const solidTiles = /* @__PURE__ */ new Set();
89
- if (ts.tiles) {
90
- for (const tile of ts.tiles) {
91
- const props = parseProperties(tile.properties);
92
- if (Object.keys(props).length > 0) {
93
- tileProperties.set(tile.id, props);
94
- }
95
- const tileType = tile.type ?? tile.class ?? "";
96
- if (tileType === "solid" || props.solid === true || props.collision === true) {
97
- solidTiles.add(tile.id);
98
- }
99
- }
100
- }
101
- const ref = {
102
- firstGid: ts.firstgid,
103
- name: ts.name,
104
- tileWidth: ts.tilewidth,
105
- tileHeight: ts.tileheight,
106
- columns: ts.columns,
107
- tileCount: ts.tilecount,
108
- image: ts.image,
109
- imageWidth: ts.imagewidth,
110
- imageHeight: ts.imageheight,
111
- tileProperties,
112
- solidTiles
113
- };
114
- map.tilesets.push(ref);
115
- }
116
- map.tilesets.sort((a, b) => a.firstGid - b.firstGid);
117
- for (const layer of data.layers) {
118
- map.layers.push(parseLayer(layer));
119
- }
120
- return map;
261
+ const data = json;
262
+ if (data.infinite === true) throw new TilemapParseError("parseTiled: infinite maps are not supported. In Tiled: Map ▸ Map Properties ▸ set \"Infinite\" to false, then re-export.");
263
+ if (data.orientation && data.orientation !== "orthogonal") throw new TilemapParseError(`parseTiled: orientation "${data.orientation}" is not supported — only orthogonal maps are supported.`);
264
+ const map = createTilemapData(data.width, data.height, data.tilewidth, data.tileheight);
265
+ map.properties = parseProperties(data.properties);
266
+ for (const ts of data.tilesets) {
267
+ if (ts.source !== void 0) throw new TilemapParseError(`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).`);
268
+ const tileProperties = /* @__PURE__ */ new Map();
269
+ const solidTiles = /* @__PURE__ */ new Set();
270
+ if (ts.tiles) for (const tile of ts.tiles) {
271
+ const props = parseProperties(tile.properties);
272
+ if (Object.keys(props).length > 0) tileProperties.set(tile.id, props);
273
+ if ((tile.type ?? tile.class ?? "") === "solid" || props.solid === true || props.collision === true) solidTiles.add(tile.id);
274
+ }
275
+ const ref = {
276
+ firstGid: ts.firstgid,
277
+ name: ts.name,
278
+ tileWidth: ts.tilewidth,
279
+ tileHeight: ts.tileheight,
280
+ columns: ts.columns,
281
+ tileCount: ts.tilecount,
282
+ image: ts.image,
283
+ imageWidth: ts.imagewidth,
284
+ imageHeight: ts.imageheight,
285
+ tileProperties,
286
+ solidTiles
287
+ };
288
+ map.tilesets.push(ref);
289
+ }
290
+ map.tilesets.sort((a, b) => a.firstGid - b.firstGid);
291
+ for (const layer of data.layers) map.layers.push(parseLayer(layer));
292
+ return map;
121
293
  }
122
294
  function parseLayer(layer) {
123
- if (layer.type === "tilelayer") {
124
- return parseTileLayer(layer);
125
- }
126
- return parseObjectLayer(layer);
295
+ if (layer.type === "tilelayer") return parseTileLayer(layer);
296
+ if (layer.type === "objectgroup") return parseObjectLayer(layer);
297
+ const l = layer;
298
+ throw new TilemapParseError(`parseTiled: layer "${l.name ?? ""}" has unsupported type "${l.type}". Only tilelayer and objectgroup are supported — flatten group layers and remove image layers before export.`);
127
299
  }
128
300
  function parseTileLayer(layer) {
129
- return {
130
- type: "tile",
131
- name: layer.name,
132
- width: layer.width,
133
- height: layer.height,
134
- tiles: layer.data.slice(),
135
- visible: layer.visible,
136
- opacity: layer.opacity,
137
- offsetX: layer.offsetx ?? 0,
138
- offsetY: layer.offsety ?? 0,
139
- properties: parseProperties(layer.properties)
140
- };
301
+ if (layer.encoding !== void 0 && layer.encoding !== "csv" || layer.compression !== void 0 || layer.chunks !== void 0) throw new TilemapParseError("parseTiled: base64/compressed/chunked (infinite) layer data is not supported. In Tiled export options set Tile Layer Format to \"CSV\".");
302
+ if (typeof layer.data === "string") throw new TilemapParseError("parseTiled: base64/compressed/chunked (infinite) layer data is not supported. In Tiled export options set Tile Layer Format to \"CSV\".");
303
+ return {
304
+ type: "tile",
305
+ name: layer.name,
306
+ width: layer.width,
307
+ height: layer.height,
308
+ tiles: layer.data.slice(),
309
+ visible: layer.visible,
310
+ opacity: layer.opacity,
311
+ offsetX: layer.offsetx ?? 0,
312
+ offsetY: layer.offsety ?? 0,
313
+ properties: parseProperties(layer.properties)
314
+ };
141
315
  }
142
316
  function parseObjectLayer(layer) {
143
- const objects = layer.objects.map((obj) => ({
144
- id: obj.id,
145
- name: obj.name,
146
- type: obj.type ?? obj.class ?? "",
147
- x: obj.x,
148
- y: obj.y,
149
- width: obj.width,
150
- height: obj.height,
151
- rotation: obj.rotation,
152
- properties: parseProperties(obj.properties)
153
- }));
154
- return {
155
- type: "object",
156
- name: layer.name,
157
- objects,
158
- visible: layer.visible,
159
- opacity: layer.opacity,
160
- properties: parseProperties(layer.properties)
161
- };
317
+ const objects = layer.objects.map((obj) => ({
318
+ id: obj.id,
319
+ name: obj.name,
320
+ type: obj.type ?? obj.class ?? "",
321
+ x: obj.x,
322
+ y: obj.y,
323
+ width: obj.width,
324
+ height: obj.height,
325
+ rotation: obj.rotation,
326
+ properties: parseProperties(obj.properties)
327
+ }));
328
+ return {
329
+ type: "object",
330
+ name: layer.name,
331
+ objects,
332
+ visible: layer.visible,
333
+ opacity: layer.opacity,
334
+ properties: parseProperties(layer.properties)
335
+ };
162
336
  }
163
-
164
- // src/ldtk-parser.ts
165
- function parseLDtk(json) {
166
- const data = json;
167
- const results = [];
168
- const tilesetDefs = /* @__PURE__ */ new Map();
169
- for (const ts of data.defs.tilesets) {
170
- tilesetDefs.set(ts.uid, ts);
171
- }
172
- for (const level of data.levels) {
173
- const gridSize = data.defaultGridSize;
174
- const mapWidth = Math.ceil(level.pxWid / gridSize);
175
- const mapHeight = Math.ceil(level.pxHei / gridSize);
176
- const map = createTilemapData(mapWidth, mapHeight, gridSize, gridSize);
177
- if (level.fieldInstances) {
178
- for (const field of level.fieldInstances) {
179
- map.properties[field.__identifier] = field.__value;
180
- }
181
- }
182
- const usedTilesets = /* @__PURE__ */ new Set();
183
- if (level.layerInstances) {
184
- for (let i = level.layerInstances.length - 1; i >= 0; i--) {
185
- const layerInst = level.layerInstances[i];
186
- const layer = parseLayerInstance(layerInst, mapWidth, mapHeight, gridSize);
187
- if (layer) {
188
- map.layers.push(layer);
189
- }
190
- if (layerInst.__tilesetDefUid !== void 0) {
191
- usedTilesets.add(layerInst.__tilesetDefUid);
192
- }
193
- }
194
- }
195
- let firstGid = 1;
196
- for (const uid of usedTilesets) {
197
- const def = tilesetDefs.get(uid);
198
- if (!def) continue;
199
- const columns = def.__cWid;
200
- const tileCount = def.__cWid * def.__cHei;
201
- const ref = {
202
- firstGid,
203
- name: def.identifier,
204
- tileWidth: def.tileGridSize,
205
- tileHeight: def.tileGridSize,
206
- columns,
207
- tileCount,
208
- image: def.relPath,
209
- imageWidth: def.pxWid,
210
- imageHeight: def.pxHei,
211
- tileProperties: /* @__PURE__ */ new Map(),
212
- solidTiles: /* @__PURE__ */ new Set()
213
- };
214
- map.tilesets.push(ref);
215
- firstGid += tileCount;
216
- }
217
- results.push(map);
218
- }
219
- return results;
220
- }
221
- function parseLayerInstance(layer, mapWidth, mapHeight, gridSize) {
222
- switch (layer.__type) {
223
- case "IntGrid":
224
- return parseIntGridLayer(layer, mapWidth, mapHeight);
225
- case "Tiles":
226
- case "AutoLayer":
227
- return parseTilesLayer(layer, mapWidth, mapHeight, gridSize);
228
- case "Entities":
229
- return parseEntitiesLayer(layer);
230
- default:
231
- return null;
232
- }
233
- }
234
- function parseIntGridLayer(layer, mapWidth, mapHeight) {
235
- const tiles = layer.intGridCsv ? layer.intGridCsv.slice() : new Array(mapWidth * mapHeight).fill(0);
236
- return {
237
- type: "tile",
238
- name: layer.__identifier,
239
- width: layer.__cWid,
240
- height: layer.__cHei,
241
- tiles,
242
- visible: layer.visible,
243
- opacity: layer.__opacity,
244
- offsetX: 0,
245
- offsetY: 0,
246
- properties: {}
247
- };
248
- }
249
- function parseTilesLayer(layer, mapWidth, mapHeight, gridSize) {
250
- const tiles = new Array(mapWidth * mapHeight).fill(0);
251
- const tileInstances = layer.gridTiles ?? layer.autoLayerTiles ?? [];
252
- for (const ti of tileInstances) {
253
- const col = Math.floor(ti.px[0] / gridSize);
254
- const row = Math.floor(ti.px[1] / gridSize);
255
- if (col >= 0 && col < mapWidth && row >= 0 && row < mapHeight) {
256
- tiles[row * mapWidth + col] = ti.t + 1;
257
- }
258
- }
259
- return {
260
- type: "tile",
261
- name: layer.__identifier,
262
- width: mapWidth,
263
- height: mapHeight,
264
- tiles,
265
- visible: layer.visible,
266
- opacity: layer.__opacity,
267
- offsetX: 0,
268
- offsetY: 0,
269
- properties: {}
270
- };
337
+ //#endregion
338
+ //#region src/tilemap-collider.ts
339
+ /**
340
+ * Extract collision shapes from solid tiles in a tilemap.
341
+ * A tile is considered solid if its tileset marks the local tile ID as solid.
342
+ *
343
+ * @param map The parsed tilemap data.
344
+ * @param layerName Optional: only extract from this layer. If omitted, extracts from all tile layers.
345
+ * @returns Array of TileCollider bodies.
346
+ */
347
+ function extractColliders(map, layerName) {
348
+ const colliders = [];
349
+ const tw = map.tileWidth;
350
+ const th = map.tileHeight;
351
+ for (const layer of map.layers) {
352
+ if (layer.type !== "tile") continue;
353
+ if (layerName !== void 0 && layer.name !== layerName) continue;
354
+ extractFromLayer(layer, map.tilesets, tw, th, colliders);
355
+ }
356
+ return colliders;
271
357
  }
272
- function parseEntitiesLayer(layer) {
273
- const objects = (layer.entityInstances ?? []).map((ent, idx) => {
274
- const props = {};
275
- for (const field of ent.fieldInstances) {
276
- props[field.__identifier] = field.__value;
277
- }
278
- return {
279
- id: idx + 1,
280
- name: ent.__identifier,
281
- type: ent.__identifier,
282
- x: ent.px[0],
283
- y: ent.px[1],
284
- width: ent.width,
285
- height: ent.height,
286
- rotation: 0,
287
- properties: props
288
- };
289
- });
290
- return {
291
- type: "object",
292
- name: layer.__identifier,
293
- objects,
294
- visible: layer.visible,
295
- opacity: layer.__opacity,
296
- properties: {}
297
- };
358
+ function extractFromLayer(layer, tilesets, tw, th, out) {
359
+ for (let row = 0; row < layer.height; row++) for (let col = 0; col < layer.width; col++) {
360
+ const gid = layer.tiles[row * layer.width + col] ?? 0;
361
+ if (gid === 0) continue;
362
+ const tileset = getTilesetForGid(tilesets, gid);
363
+ if (!tileset) continue;
364
+ const localId = (gid & GID_FLIP_MASK) - tileset.firstGid;
365
+ if (!tileset.solidTiles.has(localId)) continue;
366
+ out.push({
367
+ x: col * tw + tw * .5 + layer.offsetX,
368
+ y: row * th + th * .5 + layer.offsetY,
369
+ shape: (0, _flare_engine_physics.AABB)(tw, th),
370
+ col,
371
+ row,
372
+ gid: gid & GID_FLIP_MASK
373
+ });
374
+ }
298
375
  }
299
-
300
- // src/tilemap-renderer.ts
301
- var import_render = require("@flare-engine/render");
376
+ //#endregion
377
+ //#region src/tilemap-renderer.ts
378
+ /**
379
+ * TilemapRenderer — draws a tilemap with viewport culling.
380
+ * Only tiles visible to the camera are submitted to the SpriteBatch.
381
+ */
302
382
  var TilemapRenderer = class {
303
- /** The tilemap data to render. */
304
- map;
305
- /** SpriteBatch used for batched tile rendering. */
306
- batch;
307
- /** Map from tileset name → SkImage. Set via setTilesetImage(). */
308
- _images = /* @__PURE__ */ new Map();
309
- /** Reusable bounds rect — avoids per-frame allocation from camera.getBounds(). */
310
- _boundsBuf = { x: 0, y: 0, width: 0, height: 0 };
311
- constructor(map) {
312
- this.map = map;
313
- this.batch = new import_render.SpriteBatch();
314
- }
315
- /** Associate a loaded image with a tileset by name. */
316
- setTilesetImage(tilesetName, image) {
317
- this._images.set(tilesetName, image);
318
- }
319
- /**
320
- * Queue visible tile layers into a caller-owned `batch` using the camera for
321
- * culling. Does NOT flush — the caller owns the single flush so tiles z-order
322
- * under sprites. Zero-alloc: reuses the internal bounds buffer.
323
- */
324
- drawInto(camera, batch) {
325
- const bounds = camera.getBoundsInto(this._boundsBuf);
326
- const tw = this.map.tileWidth;
327
- const th = this.map.tileHeight;
328
- for (const layer of this.map.layers) {
329
- if (layer.type !== "tile" || !layer.visible) continue;
330
- this._drawTileLayer(layer, bounds.x, bounds.y, bounds.width, bounds.height, tw, th, batch);
331
- }
332
- }
333
- /**
334
- * Draw visible tile layers using the camera for culling.
335
- * Call `flush` on a callback to issue the actual draw calls.
336
- * Delegates to `drawInto` so culling and queuing logic live in one place.
337
- */
338
- draw(camera, flush) {
339
- this.drawInto(camera, this.batch);
340
- flush(this.batch);
341
- }
342
- _drawTileLayer(layer, viewX, viewY, viewW, viewH, tw, th, batch) {
343
- const offsetX = layer.offsetX;
344
- const offsetY = layer.offsetY;
345
- const startCol = Math.max(0, Math.floor((viewX - offsetX) / tw));
346
- const startRow = Math.max(0, Math.floor((viewY - offsetY) / th));
347
- const endCol = Math.min(layer.width - 1, Math.floor((viewX - offsetX + viewW) / tw));
348
- const endRow = Math.min(layer.height - 1, Math.floor((viewY - offsetY + viewH) / th));
349
- for (let row = startRow; row <= endRow; row++) {
350
- for (let col = startCol; col <= endCol; col++) {
351
- const gid = getTileAt(layer, col, row);
352
- if (gid === 0) continue;
353
- const tileset = getTilesetForGid(this.map.tilesets, gid);
354
- if (!tileset) continue;
355
- const image = this._images.get(tileset.name);
356
- if (!image) continue;
357
- const localId = gid - tileset.firstGid;
358
- const srcCol = localId % tileset.columns;
359
- const srcRow = (localId - srcCol) / tileset.columns;
360
- const srcX = srcCol * tileset.tileWidth;
361
- const srcY = srcRow * tileset.tileHeight;
362
- const dstX = col * tw + offsetX;
363
- const dstY = row * th + offsetY;
364
- batch.drawRaw(image, srcX, srcY, tileset.tileWidth, tileset.tileHeight, dstX, dstY, tw, th);
365
- }
366
- }
367
- }
383
+ /** The tilemap data to render. */
384
+ map;
385
+ /** SpriteBatch used for batched tile rendering. */
386
+ batch;
387
+ /** Map from tileset name → SkImage. Set via setTilesetImage(). */
388
+ _images = /* @__PURE__ */ new Map();
389
+ /** Reusable bounds rect — avoids per-frame allocation from camera.getBounds(). */
390
+ _boundsBuf = {
391
+ x: 0,
392
+ y: 0,
393
+ width: 0,
394
+ height: 0
395
+ };
396
+ constructor(map) {
397
+ this.map = map;
398
+ this.batch = new _flare_engine_render.SpriteBatch();
399
+ }
400
+ /** Associate a loaded image with a tileset by name. */
401
+ setTilesetImage(tilesetName, image) {
402
+ this._images.set(tilesetName, image);
403
+ }
404
+ /**
405
+ * Queue visible tile layers into a caller-owned `batch` using the camera for
406
+ * culling. Does NOT flush — the caller owns the single flush so tiles z-order
407
+ * under sprites. Zero-alloc: reuses the internal bounds buffer.
408
+ */
409
+ drawInto(camera, batch) {
410
+ const bounds = camera.getBoundsInto(this._boundsBuf);
411
+ const tw = this.map.tileWidth;
412
+ const th = this.map.tileHeight;
413
+ for (const layer of this.map.layers) {
414
+ if (layer.type !== "tile" || !layer.visible) continue;
415
+ this._drawTileLayer(layer, bounds.x, bounds.y, bounds.width, bounds.height, tw, th, batch);
416
+ }
417
+ }
418
+ /**
419
+ * Draw visible tile layers using the camera for culling.
420
+ * Call `flush` on a callback to issue the actual draw calls.
421
+ * Delegates to `drawInto` so culling and queuing logic live in one place.
422
+ */
423
+ draw(camera, flush) {
424
+ this.drawInto(camera, this.batch);
425
+ flush(this.batch);
426
+ }
427
+ _drawTileLayer(layer, viewX, viewY, viewW, viewH, tw, th, batch) {
428
+ const offsetX = layer.offsetX;
429
+ const offsetY = layer.offsetY;
430
+ const startCol = Math.max(0, Math.floor((viewX - offsetX) / tw));
431
+ const startRow = Math.max(0, Math.floor((viewY - offsetY) / th));
432
+ const endCol = Math.min(layer.width - 1, Math.floor((viewX - offsetX + viewW) / tw));
433
+ const endRow = Math.min(layer.height - 1, Math.floor((viewY - offsetY + viewH) / th));
434
+ for (let row = startRow; row <= endRow; row++) for (let col = startCol; col <= endCol; col++) {
435
+ const gid = getTileAt(layer, col, row);
436
+ if (gid === 0) continue;
437
+ const tileset = getTilesetForGid(this.map.tilesets, gid);
438
+ if (!tileset) continue;
439
+ const image = this._images.get(tileset.name);
440
+ if (!image) continue;
441
+ const localId = (gid & GID_FLIP_MASK) - tileset.firstGid;
442
+ const srcCol = localId % tileset.columns;
443
+ const srcRow = (localId - srcCol) / tileset.columns;
444
+ const srcX = srcCol * tileset.tileWidth;
445
+ const srcY = srcRow * tileset.tileHeight;
446
+ const dstX = col * tw + offsetX;
447
+ const dstY = row * th + offsetY;
448
+ batch.drawRaw(image, srcX, srcY, tileset.tileWidth, tileset.tileHeight, dstX, dstY, tw, th);
449
+ }
450
+ }
368
451
  };
452
+ //#endregion
453
+ exports.GID_FLIP_MASK = GID_FLIP_MASK;
454
+ exports.TilemapParseError = TilemapParseError;
455
+ exports.TilemapRenderer = TilemapRenderer;
456
+ exports.createTilemapData = createTilemapData;
457
+ exports.decodeGidFlags = decodeGidFlags;
458
+ exports.extractColliders = extractColliders;
459
+ exports.getTileAt = getTileAt;
460
+ exports.getTileSourceRect = getTileSourceRect;
461
+ exports.getTilesetForGid = getTilesetForGid;
462
+ exports.parseLDtk = parseLDtk;
463
+ exports.parseLDtkEntities = parseLDtkEntities;
464
+ exports.parseTiled = parseTiled;
465
+ exports.stripGidFlags = stripGidFlags;
369
466
 
370
- // src/tilemap-collider.ts
371
- var import_physics = require("@flare-engine/physics");
372
- function extractColliders(map, layerName) {
373
- const colliders = [];
374
- const tw = map.tileWidth;
375
- const th = map.tileHeight;
376
- for (const layer of map.layers) {
377
- if (layer.type !== "tile") continue;
378
- if (layerName !== void 0 && layer.name !== layerName) continue;
379
- extractFromLayer(layer, map.tilesets, tw, th, colliders);
380
- }
381
- return colliders;
382
- }
383
- function extractFromLayer(layer, tilesets, tw, th, out) {
384
- for (let row = 0; row < layer.height; row++) {
385
- for (let col = 0; col < layer.width; col++) {
386
- const gid = layer.tiles[row * layer.width + col] ?? 0;
387
- if (gid === 0) continue;
388
- const tileset = getTilesetForGid(tilesets, gid);
389
- if (!tileset) continue;
390
- const localId = gid - tileset.firstGid;
391
- if (!tileset.solidTiles.has(localId)) continue;
392
- out.push({
393
- x: col * tw + tw * 0.5 + layer.offsetX,
394
- y: row * th + th * 0.5 + layer.offsetY,
395
- shape: (0, import_physics.AABB)(tw, th),
396
- col,
397
- row,
398
- gid
399
- });
400
- }
401
- }
402
- }
403
- // Annotate the CommonJS export names for ESM import in node:
404
- 0 && (module.exports = {
405
- TilemapRenderer,
406
- createTilemapData,
407
- extractColliders,
408
- getTileAt,
409
- getTileSourceRect,
410
- getTilesetForGid,
411
- parseLDtk,
412
- parseTiled
413
- });
414
467
  //# sourceMappingURL=index.js.map