@eva/plugin-renderer-tilemap 2.1.0-beta.4 → 2.1.0-beta.6

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.
@@ -154,6 +154,7 @@ var _EVA_IIFE_tilemap = function (exports, eva_js, pluginRenderer, pixi_js) {
154
154
  this.tilesetSpacing = 0;
155
155
  this.tilesetMargin = 0;
156
156
  this.layers = [];
157
+ this.tilemapRef = '';
157
158
  }
158
159
  init(obj) {
159
160
  if (obj) _extends(this, obj);
@@ -165,78 +166,758 @@ var _EVA_IIFE_tilemap = function (exports, eva_js, pluginRenderer, pixi_js) {
165
166
  __decorate([type('number'), __metadata("design:type", Number)], Tilemap.prototype, "tileHeight", void 0);
166
167
  __decorate([type('number'), __metadata("design:type", Number)], Tilemap.prototype, "tilesetSpacing", void 0);
167
168
  __decorate([type('number'), __metadata("design:type", Number)], Tilemap.prototype, "tilesetMargin", void 0);
169
+ __decorate([type('string'), __metadata("design:type", String)], Tilemap.prototype, "tilemapRef", void 0);
170
+ const CHUNK_SIZE$2 = 16;
171
+ const CHUNK_CELL_COUNT = CHUNK_SIZE$2 * CHUNK_SIZE$2;
172
+ function unpackCell(packed) {
173
+ return {
174
+ sourceSlot: packed & 0xff,
175
+ col: packed >>> 8 & 0xff,
176
+ row: packed >>> 16 & 0xff,
177
+ altIdx: packed >>> 24 & 0x1f,
178
+ flipH: (packed >>> 29 & 1) === 1,
179
+ flipV: (packed >>> 30 & 1) === 1,
180
+ transpose: (packed >>> 31 & 1) === 1
181
+ };
182
+ }
183
+ function isEmptyCellValue(packed) {
184
+ return (packed & 0xff) === 0;
185
+ }
186
+ function decodeChunk(blob) {
187
+ const bytes = base64Decode(blob.blob);
188
+ if (bytes.byteLength !== CHUNK_CELL_COUNT * 4) {
189
+ throw new Error(`decodeChunk: expected ${CHUNK_CELL_COUNT * 4} bytes, got ${bytes.byteLength}`);
190
+ }
191
+ const copy = new Uint8Array(bytes.byteLength);
192
+ copy.set(bytes);
193
+ return new Int32Array(copy.buffer);
194
+ }
195
+ const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
196
+ function base64Decode(s) {
197
+ if (typeof atob === 'function') {
198
+ const bin = atob(s);
199
+ const out = new Uint8Array(bin.length);
200
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
201
+ return out;
202
+ }
203
+ const bufCtor = globalThis.Buffer;
204
+ if (bufCtor) {
205
+ return new Uint8Array(bufCtor.from(s, 'base64'));
206
+ }
207
+ const clean = s.replace(/[^A-Za-z0-9+/]/g, '');
208
+ const padding = s.endsWith('==') ? 2 : s.endsWith('=') ? 1 : 0;
209
+ const len = Math.floor(clean.length * 3 / 4) - padding;
210
+ const out = new Uint8Array(len);
211
+ let p = 0;
212
+ for (let i = 0; i < clean.length; i += 4) {
213
+ const v0 = BASE64_ALPHABET.indexOf(clean[i]);
214
+ const v1 = BASE64_ALPHABET.indexOf(clean[i + 1]);
215
+ const v2 = clean[i + 2] ? BASE64_ALPHABET.indexOf(clean[i + 2]) : 0;
216
+ const v3 = clean[i + 3] ? BASE64_ALPHABET.indexOf(clean[i + 3]) : 0;
217
+ const w = v0 << 18 | v1 << 12 | v2 << 6 | v3;
218
+ if (p < len) out[p++] = w >> 16 & 0xff;
219
+ if (p < len) out[p++] = w >> 8 & 0xff;
220
+ if (p < len) out[p++] = w & 0xff;
221
+ }
222
+ return out;
223
+ }
224
+ function makeLoadedTileset(raw) {
225
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
226
+ const slotByIdMap = new Map();
227
+ const sourcesBySlot = [];
228
+ const seenByAsset = new Map();
229
+ for (let i = 0; i < raw.sources.length; i++) {
230
+ const src = raw.sources[i];
231
+ sourcesBySlot.push(src);
232
+ slotByIdMap.set(src.id, i + 1);
233
+ if (src.kind === 'atlas' && src.textureAsset) {
234
+ const prev = seenByAsset.get(src.textureAsset);
235
+ if (prev) {
236
+ const sameRegion = prev.regionSize.width === src.regionSize.width && prev.regionSize.height === src.regionSize.height;
237
+ const sameMargins = ((_b = (_a = prev.margins) === null || _a === void 0 ? void 0 : _a.x) !== null && _b !== void 0 ? _b : 0) === ((_d = (_c = src.margins) === null || _c === void 0 ? void 0 : _c.x) !== null && _d !== void 0 ? _d : 0) && ((_f = (_e = prev.margins) === null || _e === void 0 ? void 0 : _e.y) !== null && _f !== void 0 ? _f : 0) === ((_h = (_g = src.margins) === null || _g === void 0 ? void 0 : _g.y) !== null && _h !== void 0 ? _h : 0);
238
+ const sameSep = ((_k = (_j = prev.separation) === null || _j === void 0 ? void 0 : _j.x) !== null && _k !== void 0 ? _k : 0) === ((_m = (_l = src.separation) === null || _l === void 0 ? void 0 : _l.x) !== null && _m !== void 0 ? _m : 0) && ((_p = (_o = prev.separation) === null || _o === void 0 ? void 0 : _o.y) !== null && _p !== void 0 ? _p : 0) === ((_r = (_q = src.separation) === null || _q === void 0 ? void 0 : _q.y) !== null && _r !== void 0 ? _r : 0);
239
+ if (!sameRegion || !sameMargins || !sameSep) {
240
+ if (typeof console !== 'undefined') {
241
+ console.warn(`[Tilemap] Atlas sources '${prev.sourceId}' and '${src.id}' share textureAsset='${src.textureAsset}' ` + `but differ in regionSize/margins/separation. Frame texture cache may collide and render wrong frames. ` + `Use distinct textureAssets per atlas source.`);
242
+ }
243
+ }
244
+ } else {
245
+ seenByAsset.set(src.textureAsset, {
246
+ regionSize: src.regionSize,
247
+ margins: src.margins,
248
+ separation: src.separation,
249
+ sourceId: src.id
250
+ });
251
+ }
252
+ }
253
+ }
254
+ return {
255
+ raw,
256
+ sourcesBySlot,
257
+ slotByIdMap,
258
+ tileWidth: raw.tileSize.width,
259
+ tileHeight: raw.tileSize.height
260
+ };
261
+ }
262
+ class TileAnimationDriver {
263
+ constructor() {
264
+ this.animations = [];
265
+ this.lastFrameIdxByKey = new Map();
266
+ }
267
+ loadFromTileset(raw) {
268
+ var _a;
269
+ this.animations = [];
270
+ this.lastFrameIdxByKey.clear();
271
+ for (let slotIdx = 0; slotIdx < raw.sources.length; slotIdx++) {
272
+ const src = raw.sources[slotIdx];
273
+ if (src.kind !== 'atlas') continue;
274
+ const slot = slotIdx + 1;
275
+ for (const tile of src.tiles) {
276
+ const anim = tile.animation;
277
+ if (!anim || !anim.frames || anim.frames.length === 0) continue;
278
+ const frames = anim.frames.map(f => {
279
+ var _a;
280
+ return {
281
+ col: f.atlasCoords.col,
282
+ row: f.atlasCoords.row,
283
+ durationMs: anim.stepMs * ((_a = f.durationFactor) !== null && _a !== void 0 ? _a : 1)
284
+ };
285
+ });
286
+ const totalDurationMs = frames.reduce((s, f) => s + f.durationMs, 0);
287
+ if (totalDurationMs <= 0) continue;
288
+ const phaseOffsetMs = anim.phase === 'randomStart' ? deterministicPhaseOffset(slot, tile.atlasCoords.col, tile.atlasCoords.row, totalDurationMs) : 0;
289
+ this.animations.push({
290
+ sourceSlot: slot,
291
+ col: tile.atlasCoords.col,
292
+ row: tile.atlasCoords.row,
293
+ frames,
294
+ totalDurationMs,
295
+ phase: (_a = anim.phase) !== null && _a !== void 0 ? _a : 'sync',
296
+ phaseOffsetMs
297
+ });
298
+ }
299
+ }
300
+ }
301
+ get animationCount() {
302
+ return this.animations.length;
303
+ }
304
+ isAnimatedSource(slot, col, row) {
305
+ for (const a of this.animations) {
306
+ if (a.sourceSlot === slot && a.col === col && a.row === row) return true;
307
+ }
308
+ return false;
309
+ }
310
+ advance(nowMs) {
311
+ const currentFrames = new Map();
312
+ const dirtyKeys = new Set();
313
+ for (const anim of this.animations) {
314
+ const key = `${anim.sourceSlot},${anim.col},${anim.row}`;
315
+ const t = ((nowMs + anim.phaseOffsetMs) % anim.totalDurationMs + anim.totalDurationMs) % anim.totalDurationMs;
316
+ let acc = 0;
317
+ let idx = 0;
318
+ for (; idx < anim.frames.length; idx++) {
319
+ acc += anim.frames[idx].durationMs;
320
+ if (t < acc) break;
321
+ }
322
+ if (idx >= anim.frames.length) idx = anim.frames.length - 1;
323
+ const frame = anim.frames[idx];
324
+ currentFrames.set(key, {
325
+ col: frame.col,
326
+ row: frame.row
327
+ });
328
+ const prev = this.lastFrameIdxByKey.get(key);
329
+ if (prev !== idx) {
330
+ dirtyKeys.add(key);
331
+ this.lastFrameIdxByKey.set(key, idx);
332
+ }
333
+ }
334
+ return {
335
+ currentFrames,
336
+ dirtyKeys
337
+ };
338
+ }
339
+ reset() {
340
+ this.lastFrameIdxByKey.clear();
341
+ }
342
+ }
343
+ function deterministicPhaseOffset(slot, col, row, total) {
344
+ let h = slot * 73856093 ^ col * 19349663 ^ row * 83492791;
345
+ h = (h ^ h >>> 13) * 1274126177;
346
+ h = h ^ h >>> 16;
347
+ const t = (h >>> 0) / 0xffffffff;
348
+ return Math.floor(t * total);
349
+ }
350
+ const TILEMAP_PROBE_NAMES = {
351
+ DIRTY_REBUILD_MS: 'tilemap.dirtyRebuild.ms',
352
+ CULL_CHECK_MS: 'tilemap.cullCheck.ms',
353
+ ANIM_TICK_MS: 'tilemap.animTick.ms',
354
+ DRAWCALLS_COUNT: 'tilemap.drawcalls.count',
355
+ DRAWCALLS_BY_ATLAS: 'tilemap.drawcalls.byAtlas',
356
+ PHYSICS_REBAKE_MS: 'tilemap.physicsRebake.ms',
357
+ GPU_UPLOAD_MS: 'tilemap.gpuUpload.ms',
358
+ GPU_UPLOAD_BYTES: 'tilemap.gpuUpload.bytes',
359
+ AUTOTILE_MS: 'tilemap.autotile.ms',
360
+ PATCH_APPLY_MS: 'tilemap.patchApply.ms',
361
+ DIRTY_PENDING: 'tilemap.dirty.pending',
362
+ DIRTY_FRAMES_BEHIND: 'tilemap.dirty.framesBehind',
363
+ BODIES_TOTAL: 'tilemap.bodies.total',
364
+ BODIES_CREATED: 'tilemap.bodies.created',
365
+ BODIES_DESTROYED: 'tilemap.bodies.destroyed',
366
+ STRATEGY_SPRITE_COUNT: 'tilemap.strategy.sprite.count',
367
+ STRATEGY_MESH_COUNT: 'tilemap.strategy.mesh.count',
368
+ STRATEGY_MESH_FALLBACK_COUNT: 'tilemap.strategy.meshFallback.count',
369
+ SCENECOLLECTION_SKIPPED_COUNT: 'tilemap.sceneCollection.skipped.count',
370
+ CULL_HITS_COUNT: 'tilemap.cull.hits',
371
+ MODE_SWITCH_FAILED_COUNT: 'tilemap.modeSwitch.failed',
372
+ ANIM_TICK_ERROR_COUNT: 'tilemap.animTick.error.count',
373
+ CONTEXT_LOST_COUNT: 'tilemap.context.lost'
374
+ };
375
+ function createInMemoryProbeRegistry() {
376
+ const inFlight = new Map();
377
+ const timings = new Map();
378
+ const counts = new Map();
379
+ const gauges = new Map();
380
+ return {
381
+ beginTiming(name) {
382
+ inFlight.set(name, nowMs());
383
+ },
384
+ endTiming(name) {
385
+ const t0 = inFlight.get(name);
386
+ if (t0 === undefined) return;
387
+ inFlight.delete(name);
388
+ const dur = nowMs() - t0;
389
+ if (!timings.has(name)) timings.set(name, []);
390
+ timings.get(name).push(dur);
391
+ },
392
+ count(name, delta = 1) {
393
+ var _a;
394
+ counts.set(name, ((_a = counts.get(name)) !== null && _a !== void 0 ? _a : 0) + delta);
395
+ },
396
+ gauge(name, value) {
397
+ gauges.set(name, value);
398
+ },
399
+ histogram(name, value) {
400
+ this.count(`${name}.histN`);
401
+ this.count(`${name}.histSum`, value);
402
+ },
403
+ timings,
404
+ counts,
405
+ gauges
406
+ };
407
+ }
408
+ function nowMs() {
409
+ if (typeof performance !== 'undefined' && performance.now) return performance.now();
410
+ return 0;
411
+ }
412
+ function adaptGamePerfProbes(game) {
413
+ var _a, _b, _c, _d;
414
+ const p = game === null || game === void 0 ? void 0 : game.perfProbes;
415
+ if (!p) return null;
416
+ return {
417
+ beginTiming: (_a = p.beginTiming) !== null && _a !== void 0 ? _a : () => {},
418
+ endTiming: (_b = p.endTiming) !== null && _b !== void 0 ? _b : () => {},
419
+ count: (_c = p.count) !== null && _c !== void 0 ? _c : () => {},
420
+ gauge: (_d = p.gauge) !== null && _d !== void 0 ? _d : () => {},
421
+ histogram: p.histogram
422
+ };
423
+ }
424
+ function getRequiredTilemapProbes() {
425
+ return Object.values(TILEMAP_PROBE_NAMES);
426
+ }
427
+ function resolveChunkRenderStrategy(ctx) {
428
+ if (ctx.preference && ctx.preference !== 'auto') return ctx.preference;
429
+ if (ctx.atlasesInChunk > 1) return 'sprite';
430
+ if (ctx.nonEmptyCellsInChunk >= 192) return 'mesh';
431
+ return 'sprite';
432
+ }
433
+ function estimateSpriteNodes(nonEmptyCellsInChunk) {
434
+ return 1 + nonEmptyCellsInChunk;
435
+ }
436
+ function buildChunkMesh(_config) {
437
+ const container = new pixi_js.Container();
438
+ container.label = `chunk-mesh-stub-${_config.chunkKey}`;
439
+ return container;
440
+ }
441
+ function isMeshPathAvailable() {
442
+ return false;
443
+ }
444
+ function estimateChunkMeshMemoryKB(config) {
445
+ const cellsBytes = 256 * (32 + 12);
446
+ return Math.ceil(cellsBytes / 1024);
447
+ }
168
448
  let TilemapSystem = class TilemapSystem extends pluginRenderer.Renderer {
169
449
  constructor() {
170
450
  super(...arguments);
171
451
  this.name = 'Tilemap';
172
452
  this.records = {};
453
+ this.animationDrivers = new Map();
454
+ this.probes = null;
455
+ this.isHidden = false;
456
+ this.contextLost = false;
457
+ this.canvasWithCtxListeners = null;
173
458
  }
174
459
  init() {
175
460
  this.renderSystem = this.game.getSystem(pluginRenderer.RendererSystem);
176
461
  this.renderSystem.rendererManager.register(this);
462
+ this.probes = adaptGamePerfProbes(this.game);
463
+ this.installVisibilityHandlers();
464
+ }
465
+ installVisibilityHandlers() {
466
+ var _a, _b, _c;
467
+ if (typeof document === 'undefined') return;
468
+ try {
469
+ this.visibilityListener = () => {
470
+ this.isHidden = !!document.hidden;
471
+ };
472
+ document.addEventListener('visibilitychange', this.visibilityListener);
473
+ } catch (_d) {}
474
+ try {
475
+ const canvas = (_c = (_b = (_a = this.renderSystem) === null || _a === void 0 ? void 0 : _a.application) === null || _b === void 0 ? void 0 : _b.canvas) !== null && _c !== void 0 ? _c : null;
476
+ if (canvas && typeof canvas.addEventListener === 'function') {
477
+ this.contextLostListener = () => {
478
+ this.contextLost = true;
479
+ this.probeCount(TILEMAP_PROBE_NAMES.CONTEXT_LOST_COUNT, 1);
480
+ if (typeof console !== 'undefined') {
481
+ console.warn('[Tilemap] WebGL context lost — pausing animation tick');
482
+ }
483
+ };
484
+ this.contextRestoredListener = () => {
485
+ this.contextLost = false;
486
+ if (typeof console !== 'undefined') {
487
+ console.info('[Tilemap] WebGL context restored — resuming animation tick');
488
+ }
489
+ };
490
+ canvas.addEventListener('webglcontextlost', this.contextLostListener);
491
+ canvas.addEventListener('webglcontextrestored', this.contextRestoredListener);
492
+ this.canvasWithCtxListeners = canvas;
493
+ }
494
+ } catch (_e) {}
495
+ }
496
+ uninstallVisibilityHandlers() {
497
+ if (typeof document !== 'undefined' && this.visibilityListener) {
498
+ try {
499
+ document.removeEventListener('visibilitychange', this.visibilityListener);
500
+ } catch (_a) {}
501
+ this.visibilityListener = undefined;
502
+ }
503
+ if (this.canvasWithCtxListeners) {
504
+ try {
505
+ if (this.contextLostListener) {
506
+ this.canvasWithCtxListeners.removeEventListener('webglcontextlost', this.contextLostListener);
507
+ }
508
+ if (this.contextRestoredListener) {
509
+ this.canvasWithCtxListeners.removeEventListener('webglcontextrestored', this.contextRestoredListener);
510
+ }
511
+ } catch (_b) {}
512
+ this.contextLostListener = undefined;
513
+ this.contextRestoredListener = undefined;
514
+ this.canvasWithCtxListeners = null;
515
+ }
516
+ }
517
+ attachPerfProbes(probes) {
518
+ this.probes = probes;
519
+ }
520
+ setCullingBoundsHint(gameObjectId, bounds) {
521
+ const record = this.records[gameObjectId];
522
+ if (!record) return;
523
+ if (bounds === null) {
524
+ record.cullingBoundsHint = undefined;
525
+ } else {
526
+ record.cullingBoundsHint = bounds;
527
+ }
528
+ }
529
+ invalidateChunks(gameObjectId, layerId, chunkKeys) {
530
+ const record = this.records[gameObjectId];
531
+ if (!record || chunkKeys.length === 0) return;
532
+ let bucket = record.dirtyChunkKeys.get(layerId);
533
+ if (!bucket) {
534
+ bucket = new Set();
535
+ record.dirtyChunkKeys.set(layerId, bucket);
536
+ }
537
+ for (const k of chunkKeys) bucket.add(k);
538
+ let total = 0;
539
+ for (const s of record.dirtyChunkKeys.values()) total += s.size;
540
+ this.probeGauge(TILEMAP_PROBE_NAMES.DIRTY_PENDING, total);
541
+ if (!record.flushScheduled) {
542
+ record.flushScheduled = true;
543
+ const sched = typeof requestAnimationFrame !== 'undefined' ? requestAnimationFrame : cb => setTimeout(() => cb(0), 16);
544
+ sched(() => this.flushDirtyChunks(gameObjectId));
545
+ }
546
+ }
547
+ flushDirtyChunks(gameObjectId) {
548
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
549
+ const record = this.records[gameObjectId];
550
+ if (!record) return;
551
+ record.flushScheduled = false;
552
+ if (record.dirtyChunkKeys.size === 0) return;
553
+ if (record.mode !== 'v2' || !record.loadedTileset) {
554
+ record.dirtyChunkKeys.clear();
555
+ this.probeGauge(TILEMAP_PROBE_NAMES.DIRTY_PENDING, 0);
556
+ return;
557
+ }
558
+ this.probeCount(TILEMAP_PROBE_NAMES.DIRTY_FRAMES_BEHIND, 1);
559
+ const loaded = record.loadedTileset;
560
+ const animDriver = (_a = this.animationDrivers.get(gameObjectId)) !== null && _a !== void 0 ? _a : null;
561
+ const game = this.game;
562
+ let component = null;
563
+ if (game === null || game === void 0 ? void 0 : game.gameObjects) {
564
+ for (const go of game.gameObjects) {
565
+ if (go.id !== gameObjectId) continue;
566
+ const c = (_b = go.components) === null || _b === void 0 ? void 0 : _b.find(cc => (cc === null || cc === void 0 ? void 0 : cc.name) === 'Tilemap');
567
+ if (c) {
568
+ component = c;
569
+ break;
570
+ }
571
+ }
572
+ }
573
+ const cellW = (_d = (_c = component === null || component === void 0 ? void 0 : component.cellSize) === null || _c === void 0 ? void 0 : _c.width) !== null && _d !== void 0 ? _d : loaded.tileWidth;
574
+ const cellH = (_f = (_e = component === null || component === void 0 ? void 0 : component.cellSize) === null || _e === void 0 ? void 0 : _e.height) !== null && _f !== void 0 ? _f : loaded.tileHeight;
575
+ const originX = (_h = (_g = component === null || component === void 0 ? void 0 : component.mapOrigin) === null || _g === void 0 ? void 0 : _g.x) !== null && _h !== void 0 ? _h : 0;
576
+ const originY = (_k = (_j = component === null || component === void 0 ? void 0 : component.mapOrigin) === null || _j === void 0 ? void 0 : _j.y) !== null && _k !== void 0 ? _k : 0;
577
+ this.probeBegin(TILEMAP_PROBE_NAMES.DIRTY_REBUILD_MS);
578
+ try {
579
+ for (const [layerId, chunkKeys] of record.dirtyChunkKeys) {
580
+ const layerEntry = record.layerContainersV2.get(layerId);
581
+ if (!layerEntry) continue;
582
+ const layerSpec = (_m = (_l = component === null || component === void 0 ? void 0 : component.layersV2) === null || _l === void 0 ? void 0 : _l.find(l => l.id === layerId)) !== null && _m !== void 0 ? _m : null;
583
+ if (!layerSpec) continue;
584
+ for (const chunkKey of chunkKeys) {
585
+ const oldChunkContainer = layerEntry.chunkContainers.get(chunkKey);
586
+ if (oldChunkContainer) {
587
+ layerEntry.container.removeChild(oldChunkContainer);
588
+ try {
589
+ oldChunkContainer.destroy({
590
+ children: true
591
+ });
592
+ } catch (_q) {}
593
+ layerEntry.chunkContainers.delete(chunkKey);
594
+ }
595
+ const blob = (_p = (_o = layerSpec.cellData) === null || _o === void 0 ? void 0 : _o.chunks) === null || _p === void 0 ? void 0 : _p[chunkKey];
596
+ if (!blob || blob.nonEmpty <= 0) continue;
597
+ const chunkContainer = new pixi_js.Container();
598
+ chunkContainer.label = `chunk-${chunkKey}`;
599
+ this.populateChunkSprites(chunkContainer, chunkKey, blob, record, loaded, cellW, cellH, originX, originY, layerSpec, animDriver);
600
+ layerEntry.container.addChild(chunkContainer);
601
+ layerEntry.chunkContainers.set(chunkKey, chunkContainer);
602
+ }
603
+ }
604
+ } finally {
605
+ this.probeEnd(TILEMAP_PROBE_NAMES.DIRTY_REBUILD_MS);
606
+ }
607
+ record.dirtyChunkKeys.clear();
608
+ this.probeGauge(TILEMAP_PROBE_NAMES.DIRTY_PENDING, 0);
609
+ this.requestRedraw();
610
+ }
611
+ probeBegin(name) {
612
+ var _a;
613
+ (_a = this.probes) === null || _a === void 0 ? void 0 : _a.beginTiming(name);
614
+ }
615
+ probeEnd(name) {
616
+ var _a;
617
+ (_a = this.probes) === null || _a === void 0 ? void 0 : _a.endTiming(name);
618
+ }
619
+ probeCount(name, delta = 1) {
620
+ var _a;
621
+ (_a = this.probes) === null || _a === void 0 ? void 0 : _a.count(name, delta);
622
+ }
623
+ probeGauge(name, value) {
624
+ var _a;
625
+ (_a = this.probes) === null || _a === void 0 ? void 0 : _a.gauge(name, value);
177
626
  }
178
627
  rendererUpdate(_gameObject) {}
628
+ update(_frame) {
629
+ if (this.isHidden || this.contextLost) return;
630
+ if (this.animationDrivers.size === 0) return;
631
+ this.probeBegin(TILEMAP_PROBE_NAMES.ANIM_TICK_MS);
632
+ let totalSpritesSwapped = 0;
633
+ try {
634
+ const now = typeof performance !== 'undefined' && performance.now ? performance.now() : 0;
635
+ for (const [gameObjectId, driver] of this.animationDrivers) {
636
+ const record = this.records[gameObjectId];
637
+ if (!record || record.mode !== 'v2') continue;
638
+ try {
639
+ const result = driver.advance(now);
640
+ if (result.dirtyKeys.size === 0) continue;
641
+ const loaded = record.loadedTileset;
642
+ if (!loaded) continue;
643
+ let anyApplied = false;
644
+ for (const animKey of result.dirtyKeys) {
645
+ const sprites = record.animatedSpritesByAnimKey.get(animKey);
646
+ if (!sprites || sprites.length === 0) continue;
647
+ const nextFrame = result.currentFrames.get(animKey);
648
+ if (!nextFrame) continue;
649
+ const parts = animKey.split(',');
650
+ const slot = Number.parseInt(parts[0], 10);
651
+ const newTex = this.getAtlasFrameTexture(record, loaded, {
652
+ sourceSlot: slot,
653
+ col: nextFrame.col,
654
+ row: nextFrame.row
655
+ });
656
+ if (!newTex) continue;
657
+ for (const sp of sprites) {
658
+ sp.texture = newTex;
659
+ anyApplied = true;
660
+ totalSpritesSwapped++;
661
+ }
662
+ }
663
+ if (anyApplied) this.requestRedraw();
664
+ } catch (e) {
665
+ this.probeCount(TILEMAP_PROBE_NAMES.ANIM_TICK_ERROR_COUNT, 1);
666
+ if (typeof console !== 'undefined') {
667
+ console.error(`[Tilemap] animation tick failed for entity ${gameObjectId}`, e);
668
+ }
669
+ }
670
+ }
671
+ } finally {
672
+ this.probeEnd(TILEMAP_PROBE_NAMES.ANIM_TICK_MS);
673
+ if (totalSpritesSwapped > 0) this.probeCount('tilemap.anim.spritesSwapped', totalSpritesSwapped);
674
+ }
675
+ }
179
676
  componentChanged(changed) {
180
- var _a, _b, _c;
181
677
  return __awaiter(this, void 0, void 0, function* () {
182
678
  if (changed.componentName !== 'Tilemap') return;
183
679
  const component = changed.component;
184
680
  const gameObjectId = changed.gameObject.id;
185
681
  if (changed.type === eva_js.OBSERVER_TYPE.ADD) {
682
+ yield this.handleAdd(gameObjectId, changed.gameObject, component);
683
+ } else if (changed.type === eva_js.OBSERVER_TYPE.CHANGE) {
684
+ yield this.handleChange(gameObjectId, component, changed);
685
+ } else if (changed.type === eva_js.OBSERVER_TYPE.REMOVE) {
686
+ this.handleRemove(gameObjectId);
687
+ }
688
+ });
689
+ }
690
+ handleAdd(gameObjectId, gameObject, component) {
691
+ return __awaiter(this, void 0, void 0, function* () {
692
+ this.probeBegin(TILEMAP_PROBE_NAMES.DIRTY_REBUILD_MS);
693
+ try {
186
694
  const asyncId = this.increaseAsyncId(gameObjectId);
187
- let texture = null;
188
- if (component.tileset) {
189
- const {
190
- instance
191
- } = yield eva_js.resource.getResource(component.tileset);
192
- if (!this.validateAsyncId(gameObjectId, asyncId)) return;
193
- if (!instance) {
194
- console.error(`GameObject:${changed.gameObject.name}'s Tilemap tileset load error`);
195
- return;
196
- }
197
- texture = instance;
198
- }
199
- if (!texture) return;
695
+ const mode = this.detectMode(component);
200
696
  const root = new pixi_js.Container();
201
- const container = this.containerManager.getContainer(gameObjectId);
202
- if (container) container.addChildAt(root, 0);
697
+ const containerHost = this.containerManager.getContainer(gameObjectId);
698
+ if (containerHost) containerHost.addChildAt(root, 0);
203
699
  const record = {
204
700
  root,
205
701
  layerContainers: [],
702
+ layerContainersV2: new Map(),
206
703
  frameTextures: [],
207
- baseTexture: texture
704
+ frameTexturesV2: new Map(),
705
+ baseTexture: null,
706
+ atlasTextures: new Map(),
707
+ loadedTileset: null,
708
+ mode,
709
+ animatedSpritesByAnimKey: new Map(),
710
+ sceneCollectionWarnedSourceIds: new Set(),
711
+ dirtyChunkKeys: new Map(),
712
+ flushScheduled: false
208
713
  };
209
714
  this.records[gameObjectId] = record;
210
- this.buildLayers(record, component);
211
- } else if (changed.type === eva_js.OBSERVER_TYPE.CHANGE) {
212
- const record = this.records[gameObjectId];
213
- if (!record) return;
214
- if (((_b = (_a = changed.prop) === null || _a === void 0 ? void 0 : _a.prop) === null || _b === void 0 ? void 0 : _b[0]) === 'tileset') {
715
+ if (mode === 'v1') {
716
+ yield this.ensureV1Built(record, gameObjectId, gameObject, component, asyncId);
717
+ } else if (mode === 'v2') {
718
+ yield this.ensureV2Built(record, gameObjectId, gameObject, component, asyncId);
719
+ }
720
+ } finally {
721
+ this.probeEnd(TILEMAP_PROBE_NAMES.DIRTY_REBUILD_MS);
722
+ }
723
+ });
724
+ }
725
+ ensureV1Built(record, gameObjectId, gameObject, component, asyncId) {
726
+ return __awaiter(this, void 0, void 0, function* () {
727
+ const texture = yield this.loadV1Texture(component);
728
+ if (!this.validateAsyncId(gameObjectId, asyncId)) return;
729
+ if (!texture) {
730
+ if (typeof console !== 'undefined') {
731
+ console.error(`GameObject:${gameObject.name}'s Tilemap tileset load error`);
732
+ }
733
+ return;
734
+ }
735
+ record.baseTexture = texture;
736
+ this.buildLayersV1(record, component);
737
+ this.requestRedraw();
738
+ });
739
+ }
740
+ ensureV2Built(record, gameObjectId, gameObject, component, asyncId) {
741
+ return __awaiter(this, void 0, void 0, function* () {
742
+ const loaded = yield this.loadV2Tileset(component);
743
+ if (!this.validateAsyncId(gameObjectId, asyncId)) return;
744
+ if (!loaded) {
745
+ if (typeof console !== 'undefined') {
746
+ console.error(`GameObject:${gameObject.name}'s Tilemap tilemapRef load error`);
747
+ }
748
+ return;
749
+ }
750
+ record.loadedTileset = loaded;
751
+ yield this.loadAtlasTextures(record, loaded);
752
+ if (!this.validateAsyncId(gameObjectId, asyncId)) return;
753
+ const animDriver = new TileAnimationDriver();
754
+ animDriver.loadFromTileset(loaded.raw);
755
+ const driverForBuild = animDriver.animationCount > 0 ? animDriver : null;
756
+ if (driverForBuild) this.animationDrivers.set(gameObjectId, driverForBuild);
757
+ this.buildLayersV2(record, component, driverForBuild);
758
+ this.requestRedraw();
759
+ });
760
+ }
761
+ requestRedraw() {
762
+ var _a;
763
+ try {
764
+ const app = (_a = this.renderSystem) === null || _a === void 0 ? void 0 : _a.application;
765
+ if ((app === null || app === void 0 ? void 0 : app.renderer) && app.stage) {
766
+ app.renderer.render(app.stage);
767
+ }
768
+ } catch (e) {
769
+ if (typeof console !== 'undefined') {
770
+ console.warn('[Tilemap] requestRedraw failed', e);
771
+ }
772
+ }
773
+ }
774
+ handleChange(gameObjectId, component, changed) {
775
+ var _a, _b;
776
+ return __awaiter(this, void 0, void 0, function* () {
777
+ const record = this.records[gameObjectId];
778
+ if (!record) return;
779
+ const prop = (_b = (_a = changed.prop) === null || _a === void 0 ? void 0 : _a.prop) === null || _b === void 0 ? void 0 : _b[0];
780
+ this.probeBegin(TILEMAP_PROBE_NAMES.PATCH_APPLY_MS);
781
+ try {
782
+ const newMode = this.detectMode(component);
783
+ if (newMode !== record.mode) {
784
+ const asyncId = this.increaseAsyncId(gameObjectId);
785
+ try {
786
+ if (record.mode === 'v1') {
787
+ this.tearDownChildrenV1(record);
788
+ } else if (record.mode === 'v2') {
789
+ this.tearDownChildrenV2(record);
790
+ this.animationDrivers.delete(gameObjectId);
791
+ }
792
+ record.baseTexture = null;
793
+ record.loadedTileset = null;
794
+ if (newMode === 'v1') {
795
+ const texture = yield this.loadV1Texture(component);
796
+ if (!this.validateAsyncId(gameObjectId, asyncId)) return;
797
+ if (!texture) {
798
+ record.mode = 'unknown';
799
+ this.probeCount(TILEMAP_PROBE_NAMES.MODE_SWITCH_FAILED_COUNT, 1);
800
+ if (typeof console !== 'undefined') {
801
+ console.error(`GameObject:${changed.gameObject.name}'s Tilemap mode-switch v→v1 failed (tileset load returned null)`);
802
+ }
803
+ return;
804
+ }
805
+ record.mode = 'v1';
806
+ record.baseTexture = texture;
807
+ this.buildLayersV1(record, component);
808
+ this.requestRedraw();
809
+ } else if (newMode === 'v2') {
810
+ const loaded = yield this.loadV2Tileset(component);
811
+ if (!this.validateAsyncId(gameObjectId, asyncId)) return;
812
+ if (!loaded) {
813
+ record.mode = 'unknown';
814
+ this.probeCount(TILEMAP_PROBE_NAMES.MODE_SWITCH_FAILED_COUNT, 1);
815
+ if (typeof console !== 'undefined') {
816
+ console.error(`GameObject:${changed.gameObject.name}'s Tilemap mode-switch v→v2 failed (tilemapRef load returned null)`);
817
+ }
818
+ return;
819
+ }
820
+ yield this.loadAtlasTextures(record, loaded);
821
+ if (!this.validateAsyncId(gameObjectId, asyncId)) return;
822
+ record.mode = 'v2';
823
+ record.loadedTileset = loaded;
824
+ const animDriver = new TileAnimationDriver();
825
+ animDriver.loadFromTileset(loaded.raw);
826
+ const driverForBuild = animDriver.animationCount > 0 ? animDriver : null;
827
+ if (driverForBuild) this.animationDrivers.set(gameObjectId, driverForBuild);
828
+ this.buildLayersV2(record, component, driverForBuild);
829
+ this.requestRedraw();
830
+ } else {
831
+ record.mode = 'unknown';
832
+ }
833
+ } catch (e) {
834
+ record.mode = 'unknown';
835
+ this.probeCount(TILEMAP_PROBE_NAMES.MODE_SWITCH_FAILED_COUNT, 1);
836
+ if (typeof console !== 'undefined') {
837
+ console.error('[Tilemap] mode switch threw', e);
838
+ }
839
+ }
840
+ return;
841
+ }
842
+ if (prop === 'tileset' && record.mode === 'v1') {
843
+ const asyncId = this.increaseAsyncId(gameObjectId);
844
+ const texture = yield this.loadV1Texture(component);
845
+ if (!this.validateAsyncId(gameObjectId, asyncId)) return;
846
+ if (!texture) return;
847
+ this.tearDownChildrenV1(record);
848
+ record.baseTexture = texture;
849
+ this.buildLayersV1(record, component);
850
+ this.requestRedraw();
851
+ } else if (prop === 'tilemapRef' && record.mode === 'v2') {
215
852
  const asyncId = this.increaseAsyncId(gameObjectId);
216
- const {
217
- instance
218
- } = yield eva_js.resource.getResource(component.tileset);
853
+ const loaded = yield this.loadV2Tileset(component);
854
+ if (!this.validateAsyncId(gameObjectId, asyncId)) return;
855
+ if (!loaded) return;
856
+ this.tearDownChildrenV2(record);
857
+ record.loadedTileset = loaded;
858
+ yield this.loadAtlasTextures(record, loaded);
219
859
  if (!this.validateAsyncId(gameObjectId, asyncId)) return;
220
- if (!instance) return;
221
- this.tearDownChildren(record);
222
- record.baseTexture = instance;
223
- this.buildLayers(record, component);
860
+ this.animationDrivers.delete(gameObjectId);
861
+ const animDriver = new TileAnimationDriver();
862
+ animDriver.loadFromTileset(loaded.raw);
863
+ const driverForBuild = animDriver.animationCount > 0 ? animDriver : null;
864
+ if (driverForBuild) this.animationDrivers.set(gameObjectId, driverForBuild);
865
+ this.buildLayersV2(record, component, driverForBuild);
866
+ this.requestRedraw();
867
+ } else if (prop === 'layersV2' && record.mode === 'v2') {
868
+ this.tearDownChildrenV2(record);
869
+ this.animationDrivers.delete(gameObjectId);
870
+ record.dirtyChunkKeys.clear();
871
+ const loaded = record.loadedTileset;
872
+ let driverForBuild = null;
873
+ if (loaded) {
874
+ const animDriver = new TileAnimationDriver();
875
+ animDriver.loadFromTileset(loaded.raw);
876
+ if (animDriver.animationCount > 0) {
877
+ driverForBuild = animDriver;
878
+ this.animationDrivers.set(gameObjectId, animDriver);
879
+ }
880
+ }
881
+ this.buildLayersV2(record, component, driverForBuild);
882
+ this.requestRedraw();
224
883
  }
225
- } else if (changed.type === eva_js.OBSERVER_TYPE.REMOVE) {
226
- this.increaseAsyncId(gameObjectId);
227
- const record = this.records[gameObjectId];
228
- if (!record) return;
229
- this.tearDownChildren(record);
230
- const container = (_c = this.containerManager) === null || _c === void 0 ? void 0 : _c.getContainer(gameObjectId);
231
- if (container) container.removeChild(record.root);
232
- record.root.destroy({
233
- children: true
234
- });
235
- delete this.records[gameObjectId];
884
+ } finally {
885
+ this.probeEnd(TILEMAP_PROBE_NAMES.PATCH_APPLY_MS);
236
886
  }
237
887
  });
238
888
  }
239
- tearDownChildren(record) {
889
+ handleRemove(gameObjectId) {
890
+ var _a;
891
+ this.increaseAsyncId(gameObjectId);
892
+ const record = this.records[gameObjectId];
893
+ if (!record) return;
894
+ this.tearDownChildrenV1(record);
895
+ this.tearDownChildrenV2(record);
896
+ const containerHost = (_a = this.containerManager) === null || _a === void 0 ? void 0 : _a.getContainer(gameObjectId);
897
+ if (containerHost) containerHost.removeChild(record.root);
898
+ record.root.destroy({
899
+ children: true
900
+ });
901
+ delete this.records[gameObjectId];
902
+ this.animationDrivers.delete(gameObjectId);
903
+ this.probeGauge('tilemap.records.alive', Object.keys(this.records).length);
904
+ }
905
+ detectMode(component) {
906
+ if (component.tilemapRef) return 'v2';
907
+ if (component.tileset) return 'v1';
908
+ return 'unknown';
909
+ }
910
+ loadV1Texture(component) {
911
+ var _a;
912
+ return __awaiter(this, void 0, void 0, function* () {
913
+ if (!component.tileset) return null;
914
+ const {
915
+ instance
916
+ } = yield eva_js.resource.getResource(component.tileset);
917
+ return (_a = instance) !== null && _a !== void 0 ? _a : null;
918
+ });
919
+ }
920
+ tearDownChildrenV1(record) {
240
921
  for (const layer of record.layerContainers) {
241
922
  record.root.removeChild(layer);
242
923
  layer.destroy({
@@ -251,7 +932,7 @@ var _EVA_IIFE_tilemap = function (exports, eva_js, pluginRenderer, pixi_js) {
251
932
  }
252
933
  record.frameTextures = [];
253
934
  }
254
- buildLayers(record, component) {
935
+ buildLayersV1(record, component) {
255
936
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
256
937
  const base = record.baseTexture;
257
938
  if (!base) return;
@@ -264,12 +945,12 @@ var _EVA_IIFE_tilemap = function (exports, eva_js, pluginRenderer, pixi_js) {
264
945
  const sourceWidth = (_j = (_g = (_f = (_d = (_c = base.orig) === null || _c === void 0 ? void 0 : _c.width) !== null && _d !== void 0 ? _d : (_e = base.source) === null || _e === void 0 ? void 0 : _e.width) !== null && _f !== void 0 ? _f : base.width) !== null && _g !== void 0 ? _g : (_h = base.frame) === null || _h === void 0 ? void 0 : _h.width) !== null && _j !== void 0 ? _j : 0;
265
946
  const inferredCols = sourceWidth > 0 ? Math.max(1, Math.floor((sourceWidth - margin + spacing) / (tileW + spacing))) : 1;
266
947
  const cols = component.tilesetColumns && component.tilesetColumns > 0 ? component.tilesetColumns : inferredCols;
267
- const tilesetCache = new Map();
948
+ const cache = new Map();
268
949
  const getFrameTexture = tileId => {
269
950
  var _a, _b;
270
951
  if (tileId <= 0) return null;
271
952
  const idx = tileId - 1;
272
- const cached = tilesetCache.get(idx);
953
+ const cached = cache.get(idx);
273
954
  if (cached) return cached;
274
955
  const col = idx % cols;
275
956
  const row = Math.floor(idx / cols);
@@ -281,7 +962,7 @@ var _EVA_IIFE_tilemap = function (exports, eva_js, pluginRenderer, pixi_js) {
281
962
  source,
282
963
  frame: new pixi_js.Rectangle(x, y, tileW, tileH)
283
964
  });
284
- tilesetCache.set(idx, sub);
965
+ cache.set(idx, sub);
285
966
  record.frameTextures.push(sub);
286
967
  return sub;
287
968
  } catch (e) {
@@ -321,12 +1002,274 @@ var _EVA_IIFE_tilemap = function (exports, eva_js, pluginRenderer, pixi_js) {
321
1002
  record.layerContainers.push(layerContainer);
322
1003
  }
323
1004
  }
1005
+ loadV2Tileset(component) {
1006
+ var _a, _b;
1007
+ return __awaiter(this, void 0, void 0, function* () {
1008
+ if (!component.tilemapRef) return null;
1009
+ const res = yield eva_js.resource.getResource(component.tilemapRef);
1010
+ if (!res) return null;
1011
+ const json = (_a = res.instance) !== null && _a !== void 0 ? _a : (_b = res.data) === null || _b === void 0 ? void 0 : _b.json;
1012
+ if (!json || json.kind !== 'tileset') {
1013
+ if (typeof console !== 'undefined') {
1014
+ console.error(`[Tilemap] resource '${component.tilemapRef}' is not a TileSet document`);
1015
+ }
1016
+ return null;
1017
+ }
1018
+ return makeLoadedTileset(json);
1019
+ });
1020
+ }
1021
+ loadAtlasTextures(record, loaded) {
1022
+ return __awaiter(this, void 0, void 0, function* () {
1023
+ const assetsToLoad = new Set();
1024
+ for (const src of loaded.sourcesBySlot) {
1025
+ if (src.kind === 'atlas' && src.textureAsset) assetsToLoad.add(src.textureAsset);
1026
+ }
1027
+ yield Promise.all(Array.from(assetsToLoad).map(assetId => __awaiter(this, void 0, void 0, function* () {
1028
+ var _a, _b, _c;
1029
+ try {
1030
+ const res = yield eva_js.resource.getResource(assetId);
1031
+ const texture = (_c = (_a = res === null || res === void 0 ? void 0 : res.instance) !== null && _a !== void 0 ? _a : (_b = res === null || res === void 0 ? void 0 : res.data) === null || _b === void 0 ? void 0 : _b.image) !== null && _c !== void 0 ? _c : null;
1032
+ if (texture) record.atlasTextures.set(assetId, texture);
1033
+ } catch (e) {
1034
+ if (typeof console !== 'undefined') {
1035
+ console.warn(`[Tilemap] failed to load atlas asset '${assetId}'`, e);
1036
+ }
1037
+ }
1038
+ })));
1039
+ });
1040
+ }
1041
+ tearDownChildrenV2(record) {
1042
+ for (const {
1043
+ container
1044
+ } of record.layerContainersV2.values()) {
1045
+ record.root.removeChild(container);
1046
+ container.destroy({
1047
+ children: true
1048
+ });
1049
+ }
1050
+ record.layerContainersV2.clear();
1051
+ for (const tex of record.frameTexturesV2.values()) {
1052
+ try {
1053
+ tex.destroy(false);
1054
+ } catch (_a) {}
1055
+ }
1056
+ record.frameTexturesV2.clear();
1057
+ record.animatedSpritesByAnimKey.clear();
1058
+ }
1059
+ buildLayersV2(record, component, animDriver) {
1060
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
1061
+ const loaded = record.loadedTileset;
1062
+ if (!loaded) return;
1063
+ const cellW = (_b = (_a = component.cellSize) === null || _a === void 0 ? void 0 : _a.width) !== null && _b !== void 0 ? _b : loaded.tileWidth;
1064
+ const cellH = (_d = (_c = component.cellSize) === null || _c === void 0 ? void 0 : _c.height) !== null && _d !== void 0 ? _d : loaded.tileHeight;
1065
+ const originX = (_f = (_e = component.mapOrigin) === null || _e === void 0 ? void 0 : _e.x) !== null && _f !== void 0 ? _f : 0;
1066
+ const originY = (_h = (_g = component.mapOrigin) === null || _g === void 0 ? void 0 : _g.y) !== null && _h !== void 0 ? _h : 0;
1067
+ const layers = (_j = component.layersV2) !== null && _j !== void 0 ? _j : [];
1068
+ const sorted = layers.map((l, i) => ({
1069
+ layer: l,
1070
+ idx: i
1071
+ })).sort((a, b) => {
1072
+ var _a, _b;
1073
+ return ((_a = a.layer.zIndex) !== null && _a !== void 0 ? _a : 0) - ((_b = b.layer.zIndex) !== null && _b !== void 0 ? _b : 0);
1074
+ });
1075
+ for (const {
1076
+ layer
1077
+ } of sorted) {
1078
+ if (layer.enabled === false) continue;
1079
+ const container = new pixi_js.Container();
1080
+ container.label = (_k = layer.name) !== null && _k !== void 0 ? _k : layer.id;
1081
+ container.alpha = (_l = layer.opacity) !== null && _l !== void 0 ? _l : 1;
1082
+ container.visible = layer.visible !== false;
1083
+ const chunkContainers = new Map();
1084
+ this.buildChunksForLayer(record, container, chunkContainers, layer, loaded, cellW, cellH, originX, originY, animDriver);
1085
+ record.root.addChild(container);
1086
+ record.layerContainersV2.set(layer.id, {
1087
+ container,
1088
+ chunkContainers
1089
+ });
1090
+ }
1091
+ }
1092
+ buildChunksForLayer(record, layerContainer, chunkContainers, layer, loaded, cellW, cellH, originX, originY, animDriver) {
1093
+ var _a;
1094
+ const cellData = layer.cellData;
1095
+ if (!cellData || !cellData.chunks) return;
1096
+ const visibleChunks = Object.entries(cellData.chunks).filter(([, b]) => b && b.nonEmpty > 0);
1097
+ const totalChunksVisible = visibleChunks.length;
1098
+ const cullingHint = (_a = record.cullingBoundsHint) !== null && _a !== void 0 ? _a : null;
1099
+ let culledCount = 0;
1100
+ this.probeBegin(TILEMAP_PROBE_NAMES.CULL_CHECK_MS);
1101
+ for (const [chunkKey, blob] of visibleChunks) {
1102
+ if (cullingHint) {
1103
+ const parts = chunkKey.split(',');
1104
+ const ckX = Number.parseInt(parts[0], 10);
1105
+ const ckY = Number.parseInt(parts[1], 10);
1106
+ const chunkMinX = originX + ckX * CHUNK_SIZE$2 * cellW;
1107
+ const chunkMinY = originY + ckY * CHUNK_SIZE$2 * cellH;
1108
+ const chunkMaxX = chunkMinX + CHUNK_SIZE$2 * cellW;
1109
+ const chunkMaxY = chunkMinY + CHUNK_SIZE$2 * cellH;
1110
+ const intersects = chunkMaxX > cullingHint.minX && chunkMinX < cullingHint.maxX && chunkMaxY > cullingHint.minY && chunkMinY < cullingHint.maxY;
1111
+ if (!intersects) {
1112
+ culledCount++;
1113
+ continue;
1114
+ }
1115
+ }
1116
+ const chunkContainer = new pixi_js.Container();
1117
+ chunkContainer.label = `chunk-${chunkKey}`;
1118
+ let atlasesInChunk = 1;
1119
+ let preDecoded = null;
1120
+ try {
1121
+ preDecoded = decodeChunk(blob);
1122
+ const seenAtlasSlots = new Set();
1123
+ for (let i = 0; i < preDecoded.length; i++) {
1124
+ const v = preDecoded[i];
1125
+ if (isEmptyCellValue(v)) continue;
1126
+ const slot = v & 0xff;
1127
+ const src = loaded.sourcesBySlot[slot - 1];
1128
+ if (src && src.kind === 'atlas') seenAtlasSlots.add(slot);
1129
+ }
1130
+ atlasesInChunk = Math.max(1, seenAtlasSlots.size);
1131
+ } catch (_b) {
1132
+ atlasesInChunk = 1;
1133
+ preDecoded = null;
1134
+ }
1135
+ const strategy = resolveChunkRenderStrategy({
1136
+ nonEmptyCellsInChunk: blob.nonEmpty,
1137
+ atlasesInChunk,
1138
+ totalChunksVisible
1139
+ });
1140
+ let dispatched = 'sprite';
1141
+ if (strategy === 'mesh') {
1142
+ if (this.tryBuildMeshChunk(chunkContainer, chunkKey, blob, loaded, cellW, cellH, originX, originY, layer)) {
1143
+ dispatched = 'mesh';
1144
+ } else {
1145
+ dispatched = 'meshFallback';
1146
+ this.probeCount(TILEMAP_PROBE_NAMES.STRATEGY_MESH_FALLBACK_COUNT, 1);
1147
+ this.populateChunkSprites(chunkContainer, chunkKey, blob, record, loaded, cellW, cellH, originX, originY, layer, animDriver, preDecoded);
1148
+ }
1149
+ } else {
1150
+ this.populateChunkSprites(chunkContainer, chunkKey, blob, record, loaded, cellW, cellH, originX, originY, layer, animDriver, preDecoded);
1151
+ }
1152
+ if (dispatched === 'sprite') this.probeCount(TILEMAP_PROBE_NAMES.STRATEGY_SPRITE_COUNT, 1);else if (dispatched === 'mesh') this.probeCount(TILEMAP_PROBE_NAMES.STRATEGY_MESH_COUNT, 1);
1153
+ layerContainer.addChild(chunkContainer);
1154
+ chunkContainers.set(chunkKey, chunkContainer);
1155
+ }
1156
+ this.probeEnd(TILEMAP_PROBE_NAMES.CULL_CHECK_MS);
1157
+ if (culledCount > 0) this.probeCount(TILEMAP_PROBE_NAMES.CULL_HITS_COUNT, culledCount);
1158
+ }
1159
+ tryBuildMeshChunk(chunkContainer, chunkKey, blob, loaded, cellW, cellH, _originX, _originY, _layer) {
1160
+ return false;
1161
+ }
1162
+ populateChunkSprites(chunkContainer, chunkKey, blob, record, loaded, cellW, cellH, originX, originY, layer, animDriver, decoded) {
1163
+ let arr;
1164
+ if (decoded) {
1165
+ arr = decoded;
1166
+ } else {
1167
+ try {
1168
+ arr = decodeChunk(blob);
1169
+ } catch (e) {
1170
+ if (typeof console !== 'undefined') {
1171
+ console.warn(`[Tilemap] chunk decode failed for ${chunkKey}`, e);
1172
+ }
1173
+ return;
1174
+ }
1175
+ }
1176
+ const parts = chunkKey.split(',');
1177
+ const ckX = Number.parseInt(parts[0], 10);
1178
+ const ckY = Number.parseInt(parts[1], 10);
1179
+ const baseCx = ckX * CHUNK_SIZE$2;
1180
+ const baseCy = ckY * CHUNK_SIZE$2;
1181
+ const tintNum = parseHexTint(layer.modulate);
1182
+ let spritesInChunk = 0;
1183
+ for (let ly = 0; ly < CHUNK_SIZE$2; ly++) {
1184
+ for (let lx = 0; lx < CHUNK_SIZE$2; lx++) {
1185
+ const packed = arr[ly * CHUNK_SIZE$2 + lx];
1186
+ if (isEmptyCellValue(packed)) continue;
1187
+ const cell = unpackCell(packed);
1188
+ const tex = this.getAtlasFrameTexture(record, loaded, cell);
1189
+ if (!tex) continue;
1190
+ const sprite = new pixi_js.Sprite(tex);
1191
+ spritesInChunk++;
1192
+ sprite.x = originX + (baseCx + lx) * cellW;
1193
+ sprite.y = originY + (baseCy + ly) * cellH;
1194
+ sprite.width = cellW;
1195
+ sprite.height = cellH;
1196
+ if (cell.flipH) sprite.scale.x = -Math.abs(sprite.scale.x || 1);
1197
+ if (cell.flipV) sprite.scale.y = -Math.abs(sprite.scale.y || 1);
1198
+ if (cell.transpose) sprite.rotation = Math.PI / 2;
1199
+ if (cell.flipH) sprite.x += cellW;
1200
+ if (cell.flipV) sprite.y += cellH;
1201
+ if (tintNum != null) sprite.tint = tintNum;
1202
+ chunkContainer.addChild(sprite);
1203
+ if (animDriver && animDriver.isAnimatedSource(cell.sourceSlot, cell.col, cell.row)) {
1204
+ const animKey = `${cell.sourceSlot},${cell.col},${cell.row}`;
1205
+ let bucket = record.animatedSpritesByAnimKey.get(animKey);
1206
+ if (!bucket) {
1207
+ bucket = [];
1208
+ record.animatedSpritesByAnimKey.set(animKey, bucket);
1209
+ }
1210
+ bucket.push(sprite);
1211
+ }
1212
+ }
1213
+ }
1214
+ if (spritesInChunk > 0) {
1215
+ this.probeCount(TILEMAP_PROBE_NAMES.DRAWCALLS_COUNT, spritesInChunk);
1216
+ }
1217
+ }
1218
+ getAtlasFrameTexture(record, loaded, cell) {
1219
+ var _a, _b, _c, _d;
1220
+ const src = loaded.sourcesBySlot[cell.sourceSlot - 1];
1221
+ if (!src) return null;
1222
+ if (src.kind !== 'atlas') {
1223
+ if (src.kind === 'sceneCollection') {
1224
+ this.probeCount(TILEMAP_PROBE_NAMES.SCENECOLLECTION_SKIPPED_COUNT, 1);
1225
+ if (!record.sceneCollectionWarnedSourceIds.has(src.id)) {
1226
+ record.sceneCollectionWarnedSourceIds.add(src.id);
1227
+ if (typeof console !== 'undefined') {
1228
+ console.warn(`[Tilemap] sceneCollection source '${src.id}' cells are not yet rendered ` + `(prefab instantiation pending). Skipped cell at slot=${cell.sourceSlot} col=${cell.col} row=${cell.row}.`);
1229
+ }
1230
+ }
1231
+ }
1232
+ return null;
1233
+ }
1234
+ const atlas = record.atlasTextures.get(src.textureAsset);
1235
+ if (!atlas) return null;
1236
+ const margins = (_a = src.margins) !== null && _a !== void 0 ? _a : {
1237
+ x: 0,
1238
+ y: 0
1239
+ };
1240
+ const sep = (_b = src.separation) !== null && _b !== void 0 ? _b : {
1241
+ x: 0,
1242
+ y: 0
1243
+ };
1244
+ const fw = src.regionSize.width;
1245
+ const fh = src.regionSize.height;
1246
+ const cacheKey = `${src.textureAsset}#${fw}x${fh}|${margins.x},${margins.y}|${sep.x},${sep.y}#${cell.col},${cell.row}`;
1247
+ const cached = record.frameTexturesV2.get(cacheKey);
1248
+ if (cached) return cached;
1249
+ const fx = margins.x + cell.col * (fw + sep.x);
1250
+ const fy = margins.y + cell.row * (fh + sep.y);
1251
+ try {
1252
+ const source = (_d = (_c = atlas.source) !== null && _c !== void 0 ? _c : atlas.baseTexture) !== null && _d !== void 0 ? _d : atlas;
1253
+ const sub = new pixi_js.Texture({
1254
+ source,
1255
+ frame: new pixi_js.Rectangle(fx, fy, fw, fh)
1256
+ });
1257
+ record.frameTexturesV2.set(cacheKey, sub);
1258
+ return sub;
1259
+ } catch (e) {
1260
+ if (typeof console !== 'undefined') {
1261
+ console.warn(`[Tilemap] frame slice failed for ${cacheKey}`, e);
1262
+ }
1263
+ return null;
1264
+ }
1265
+ }
324
1266
  destroy() {
325
1267
  var _a;
326
1268
  for (const key in this.records) {
327
1269
  const id = parseInt(key);
328
1270
  const record = this.records[id];
329
- this.tearDownChildren(record);
1271
+ this.tearDownChildrenV1(record);
1272
+ this.tearDownChildrenV2(record);
330
1273
  const container = (_a = this.containerManager) === null || _a === void 0 ? void 0 : _a.getContainer(id);
331
1274
  if (container) container.removeChild(record.root);
332
1275
  record.root.destroy({
@@ -334,6 +1277,7 @@ var _EVA_IIFE_tilemap = function (exports, eva_js, pluginRenderer, pixi_js) {
334
1277
  });
335
1278
  delete this.records[id];
336
1279
  }
1280
+ this.uninstallVisibilityHandlers();
337
1281
  }
338
1282
  };
339
1283
  TilemapSystem.systemName = 'Tilemap';
@@ -341,11 +1285,646 @@ var _EVA_IIFE_tilemap = function (exports, eva_js, pluginRenderer, pixi_js) {
341
1285
  Tilemap: [{
342
1286
  prop: ['tileset'],
343
1287
  deep: false
1288
+ }, {
1289
+ prop: ['tilemapRef'],
1290
+ deep: false
1291
+ }, {
1292
+ prop: ['layersV2'],
1293
+ deep: false
344
1294
  }]
345
1295
  })], TilemapSystem);
346
1296
  var TilemapSystem$1 = TilemapSystem;
1297
+ function parseHexTint(modulate) {
1298
+ if (!modulate) return undefined;
1299
+ const m = /^#?([0-9a-fA-F]{6})(?:[0-9a-fA-F]{2})?$/.exec(modulate);
1300
+ if (!m) return undefined;
1301
+ return parseInt(m[1], 16);
1302
+ }
1303
+ const NEIGHBOR_DIRECTIONS = ["topLeft", "top", "topRight", "right", "bottomRight", "bottom", "bottomLeft", "left"];
1304
+ const NO_NEIGHBOR = 0xf;
1305
+ const MAX_TERRAIN_ID = 14;
1306
+ function packBits(values) {
1307
+ var _a;
1308
+ let key = 0;
1309
+ for (let i = 0; i < 8; i++) {
1310
+ const v = ((_a = values[i]) !== null && _a !== void 0 ? _a : NO_NEIGHBOR) & 0xf;
1311
+ key |= v << i * 4;
1312
+ }
1313
+ return key >>> 0;
1314
+ }
1315
+ function readNibble(key, slot) {
1316
+ return key >>> slot * 4 & 0xf;
1317
+ }
1318
+ class PeeringBitIndex {
1319
+ constructor(terrainSetIndex) {
1320
+ this.terrainSetIndex = terrainSetIndex;
1321
+ this.exact = new Map();
1322
+ this.wildcards = [];
1323
+ }
1324
+ add(candidate, bits) {
1325
+ var _a;
1326
+ const present = [];
1327
+ const mask = [];
1328
+ for (let i = 0; i < 8; i++) {
1329
+ const dir = NEIGHBOR_DIRECTIONS[i];
1330
+ const v = bits === null || bits === void 0 ? void 0 : bits[dir];
1331
+ if (v === undefined) {
1332
+ present.push(NO_NEIGHBOR);
1333
+ mask.push(0);
1334
+ } else {
1335
+ present.push(v & 0xf);
1336
+ mask.push(0xf);
1337
+ }
1338
+ }
1339
+ const key = packBits(present);
1340
+ const maskKey = packBits(mask);
1341
+ const isFullExact = mask.every(m => m === 0xf);
1342
+ if (isFullExact) {
1343
+ const list = (_a = this.exact.get(key)) !== null && _a !== void 0 ? _a : [];
1344
+ list.push(candidate);
1345
+ this.exact.set(key, list);
1346
+ } else {
1347
+ this.wildcards.push({
1348
+ key,
1349
+ mask: maskKey,
1350
+ candidate
1351
+ });
1352
+ }
1353
+ }
1354
+ match(actual) {
1355
+ const key = packBits(actual);
1356
+ const exact = this.exact.get(key);
1357
+ if (exact && exact.length > 0) {
1358
+ return {
1359
+ candidates: exact.slice(),
1360
+ exactMatch: true,
1361
+ bestHammingDistance: 0
1362
+ };
1363
+ }
1364
+ let bestDist = Infinity;
1365
+ let pool = [];
1366
+ for (const {
1367
+ key: candKey,
1368
+ mask,
1369
+ candidate
1370
+ } of this.wildcards) {
1371
+ let dist = 0;
1372
+ let viable = true;
1373
+ for (let slot = 0; slot < 8; slot++) {
1374
+ const m = readNibble(mask, slot);
1375
+ if (m === 0) continue;
1376
+ const a = readNibble(key, slot);
1377
+ const b = readNibble(candKey, slot);
1378
+ if (a !== b) {
1379
+ dist++;
1380
+ if (dist > bestDist) {
1381
+ viable = false;
1382
+ break;
1383
+ }
1384
+ }
1385
+ }
1386
+ if (!viable) continue;
1387
+ if (dist < bestDist) {
1388
+ bestDist = dist;
1389
+ pool = [candidate];
1390
+ } else if (dist === bestDist) {
1391
+ pool.push(candidate);
1392
+ }
1393
+ }
1394
+ return {
1395
+ candidates: pool,
1396
+ exactMatch: false,
1397
+ bestHammingDistance: bestDist === Infinity ? -1 : bestDist
1398
+ };
1399
+ }
1400
+ get exactBucketCount() {
1401
+ return this.exact.size;
1402
+ }
1403
+ get wildcardCount() {
1404
+ return this.wildcards.length;
1405
+ }
1406
+ }
1407
+ function pickAutotileCandidate(candidates, rng) {
1408
+ if (candidates.length === 0) return null;
1409
+ if (candidates.length === 1) return candidates[0];
1410
+ const totalProb = candidates.reduce((sum, c) => sum + (c.probability > 0 ? c.probability : 1), 0);
1411
+ const t = rng() * totalProb;
1412
+ let acc = 0;
1413
+ for (const c of candidates) {
1414
+ acc += c.probability > 0 ? c.probability : 1;
1415
+ if (t < acc) return c;
1416
+ }
1417
+ return candidates[candidates.length - 1];
1418
+ }
1419
+ const TILE_VERT_SHADER = `#version 300 es
1420
+ precision highp float;
1421
+
1422
+ in vec2 aPosition;
1423
+ in vec2 aTexCoord;
1424
+ in vec4 aFlags;
1425
+
1426
+ uniform mat3 uProjectionMatrix;
1427
+ uniform mat3 uWorldTransformMatrix;
1428
+
1429
+ out vec2 vTexCoord;
1430
+
1431
+ void main() {
1432
+ vec3 worldPos = uWorldTransformMatrix * vec3(aPosition, 1.0);
1433
+ gl_Position = vec4((uProjectionMatrix * worldPos).xy, 0.0, 1.0);
1434
+
1435
+ vec2 uv = aTexCoord;
1436
+ if (aFlags.x > 0.5) uv.x = 1.0 - uv.x;
1437
+ if (aFlags.y > 0.5) uv.y = 1.0 - uv.y;
1438
+ if (aFlags.z > 0.5) { float t = uv.x; uv.x = uv.y; uv.y = t; }
1439
+ vTexCoord = uv;
1440
+ }
1441
+ `;
1442
+ const TILE_FRAG_SHADER = `#version 300 es
1443
+ precision highp float;
1444
+
1445
+ in vec2 vTexCoord;
1446
+ out vec4 fragColor;
1447
+
1448
+ uniform sampler2D uTexture;
1449
+ uniform vec4 uModulate;
1450
+
1451
+ void main() {
1452
+ vec4 sampled = texture(uTexture, vTexCoord);
1453
+ fragColor = sampled * uModulate;
1454
+ if (fragColor.a < 0.01) discard;
1455
+ }
1456
+ `;
1457
+ const TILE_SHADER_SOURCES = {
1458
+ vertex: TILE_VERT_SHADER,
1459
+ fragment: TILE_FRAG_SHADER
1460
+ };
1461
+ const CHUNK_SIZE$1 = 16;
1462
+ const VERTS_PER_QUAD = 4;
1463
+ const FLOATS_PER_VERT = 8;
1464
+ function buildChunkGeometry(args) {
1465
+ const {
1466
+ cells,
1467
+ chunkWorldX,
1468
+ chunkWorldY,
1469
+ cellWidth,
1470
+ cellHeight,
1471
+ atlasInfo
1472
+ } = args;
1473
+ if (cells.length !== CHUNK_SIZE$1 * CHUNK_SIZE$1) {
1474
+ throw new Error(`buildChunkGeometry: cells length ${cells.length} != ${CHUNK_SIZE$1 * CHUNK_SIZE$1}`);
1475
+ }
1476
+ let nonEmpty = 0;
1477
+ for (let i = 0; i < cells.length; i++) if (!isEmptyCellValue(cells[i])) nonEmpty++;
1478
+ const vertexData = new Float32Array(nonEmpty * VERTS_PER_QUAD * FLOATS_PER_VERT);
1479
+ const indices = new Uint16Array(nonEmpty * 6);
1480
+ let v = 0;
1481
+ let i = 0;
1482
+ let quadIdx = 0;
1483
+ for (let ly = 0; ly < CHUNK_SIZE$1; ly++) {
1484
+ for (let lx = 0; lx < CHUNK_SIZE$1; lx++) {
1485
+ const packed = cells[ly * CHUNK_SIZE$1 + lx];
1486
+ if (isEmptyCellValue(packed)) continue;
1487
+ const cell = unpackCell(packed);
1488
+ const x0 = chunkWorldX + lx * cellWidth;
1489
+ const y0 = chunkWorldY + ly * cellHeight;
1490
+ const x1 = x0 + cellWidth;
1491
+ const y1 = y0 + cellHeight;
1492
+ const u0 = (atlasInfo.margins.x + cell.col * (atlasInfo.regionWidth + atlasInfo.separation.x)) / atlasInfo.textureWidth;
1493
+ const u1 = u0 + atlasInfo.regionWidth / atlasInfo.textureWidth;
1494
+ const v0 = (atlasInfo.margins.y + cell.row * (atlasInfo.regionHeight + atlasInfo.separation.y)) / atlasInfo.textureHeight;
1495
+ const v1 = v0 + atlasInfo.regionHeight / atlasInfo.textureHeight;
1496
+ const fh = cell.flipH ? 1 : 0;
1497
+ const fv = cell.flipV ? 1 : 0;
1498
+ const tr = cell.transpose ? 1 : 0;
1499
+ const animPhase = 0;
1500
+ const writeVert = (x, y, u, vv) => {
1501
+ vertexData[v++] = x;
1502
+ vertexData[v++] = y;
1503
+ vertexData[v++] = u;
1504
+ vertexData[v++] = vv;
1505
+ vertexData[v++] = fh;
1506
+ vertexData[v++] = fv;
1507
+ vertexData[v++] = tr;
1508
+ vertexData[v++] = animPhase;
1509
+ };
1510
+ writeVert(x0, y0, u0, v0);
1511
+ writeVert(x1, y0, u1, v0);
1512
+ writeVert(x1, y1, u1, v1);
1513
+ writeVert(x0, y1, u0, v1);
1514
+ const base = quadIdx * VERTS_PER_QUAD;
1515
+ indices[i++] = base;
1516
+ indices[i++] = base + 1;
1517
+ indices[i++] = base + 2;
1518
+ indices[i++] = base;
1519
+ indices[i++] = base + 2;
1520
+ indices[i++] = base + 3;
1521
+ quadIdx++;
1522
+ }
1523
+ }
1524
+ return {
1525
+ vertexData,
1526
+ indices,
1527
+ quadCount: quadIdx
1528
+ };
1529
+ }
1530
+ function diffTilesetForChunkRebuild(prev, next) {
1531
+ const prevSources = new Map();
1532
+ const nextSources = new Map();
1533
+ for (const s of prev.sources) prevSources.set(s.id, s);
1534
+ for (const s of next.sources) nextSources.set(s.id, s);
1535
+ const addedSources = [];
1536
+ const removedSourceIds = [];
1537
+ const changedSourceIds = [];
1538
+ for (const id of nextSources.keys()) {
1539
+ if (!prevSources.has(id)) addedSources.push(nextSources.get(id));else if (JSON.stringify(prevSources.get(id)) !== JSON.stringify(nextSources.get(id))) changedSourceIds.push(id);
1540
+ }
1541
+ for (const id of prevSources.keys()) {
1542
+ if (!nextSources.has(id)) removedSourceIds.push(id);
1543
+ }
1544
+ const addedTilesByKey = new Set();
1545
+ const removedTilesByKey = new Set();
1546
+ const changedTilesByKey = new Set();
1547
+ const indexTiles = src => {
1548
+ const m = new Map();
1549
+ if (src.kind !== "atlas") return m;
1550
+ for (const t of src.tiles) m.set(`${src.id}/${t.atlasCoords.col},${t.atlasCoords.row}`, t);
1551
+ return m;
1552
+ };
1553
+ for (const [id, src] of nextSources) {
1554
+ const prevSrc = prevSources.get(id);
1555
+ if (!prevSrc) {
1556
+ const tiles = indexTiles(src);
1557
+ for (const k of tiles.keys()) addedTilesByKey.add(k);
1558
+ continue;
1559
+ }
1560
+ const a = indexTiles(prevSrc);
1561
+ const b = indexTiles(src);
1562
+ for (const k of b.keys()) {
1563
+ if (!a.has(k)) addedTilesByKey.add(k);else if (JSON.stringify(a.get(k)) !== JSON.stringify(b.get(k))) changedTilesByKey.add(k);
1564
+ }
1565
+ for (const k of a.keys()) {
1566
+ if (!b.has(k)) removedTilesByKey.add(k);
1567
+ }
1568
+ }
1569
+ for (const id of removedSourceIds) {
1570
+ const a = indexTiles(prevSources.get(id));
1571
+ for (const k of a.keys()) removedTilesByKey.add(k);
1572
+ }
1573
+ return {
1574
+ addedSources,
1575
+ removedSourceIds,
1576
+ changedSourceIds,
1577
+ addedTilesByKey,
1578
+ removedTilesByKey,
1579
+ changedTilesByKey
1580
+ };
1581
+ }
1582
+ const diffTilesetDocuments = diffTilesetForChunkRebuild;
1583
+ function computeAffectedChunks(chunks, sourceIdBySlot, diff) {
1584
+ const dirty = new Set();
1585
+ const cellKeyMatches = (cellSlot, col, row) => {
1586
+ const sourceId = sourceIdBySlot.get(cellSlot);
1587
+ if (!sourceId) return false;
1588
+ const k = `${sourceId}/${col},${row}`;
1589
+ return diff.changedTilesByKey.has(k) || diff.removedTilesByKey.has(k) || diff.addedTilesByKey.has(k);
1590
+ };
1591
+ for (const [chunkKey, arr] of Object.entries(chunks)) {
1592
+ for (let i = 0; i < arr.length; i++) {
1593
+ const packed = arr[i];
1594
+ const slot = packed & 0xff;
1595
+ if (slot === 0) continue;
1596
+ const col = packed >>> 8 & 0xff;
1597
+ const row = packed >>> 16 & 0xff;
1598
+ if (cellKeyMatches(slot, col, row)) {
1599
+ dirty.add(chunkKey);
1600
+ break;
1601
+ }
1602
+ }
1603
+ }
1604
+ return dirty;
1605
+ }
1606
+ function expandSceneCollectionSource(src) {
1607
+ if (src.kind !== "sceneCollection") return [];
1608
+ return src.prefabRefs.map((p, i) => ({
1609
+ sourceId: src.id,
1610
+ prefabName: p,
1611
+ index: i
1612
+ }));
1613
+ }
1614
+ function resolveCellPrefabName(packed, sourcesBySlot) {
1615
+ var _a;
1616
+ const slot = packed & 0xff;
1617
+ if (slot === 0) return null;
1618
+ const src = sourcesBySlot[slot - 1];
1619
+ if (!src || src.kind !== "sceneCollection") return null;
1620
+ const col = packed >>> 8 & 0xff;
1621
+ return (_a = src.prefabRefs[col]) !== null && _a !== void 0 ? _a : null;
1622
+ }
1623
+ function cacheKeyOf(k) {
1624
+ return `${k.sourceSlot},${k.col},${k.row},${k.altIdx},${k.layerId}`;
1625
+ }
1626
+ class DecompositionCache {
1627
+ constructor(maxEntries = 1000) {
1628
+ this.cache = new Map();
1629
+ this.accessOrder = new Map();
1630
+ this.accessCounter = 0;
1631
+ this.maxEntries = maxEntries;
1632
+ }
1633
+ get(key) {
1634
+ const k = cacheKeyOf(key);
1635
+ const cached = this.cache.get(k);
1636
+ if (cached) this.accessOrder.set(k, ++this.accessCounter);
1637
+ return cached;
1638
+ }
1639
+ set(key, value) {
1640
+ const k = cacheKeyOf(key);
1641
+ this.cache.set(k, value);
1642
+ this.accessOrder.set(k, ++this.accessCounter);
1643
+ if (this.cache.size > this.maxEntries) this.evictLRU();
1644
+ }
1645
+ has(key) {
1646
+ return this.cache.has(cacheKeyOf(key));
1647
+ }
1648
+ clear() {
1649
+ this.cache.clear();
1650
+ this.accessOrder.clear();
1651
+ this.accessCounter = 0;
1652
+ }
1653
+ get size() {
1654
+ return this.cache.size;
1655
+ }
1656
+ evictLRU() {
1657
+ let oldestKey;
1658
+ let oldestAccess = Infinity;
1659
+ for (const [k, c] of this.accessOrder) {
1660
+ if (c < oldestAccess) {
1661
+ oldestAccess = c;
1662
+ oldestKey = k;
1663
+ }
1664
+ }
1665
+ if (oldestKey) {
1666
+ this.cache.delete(oldestKey);
1667
+ this.accessOrder.delete(oldestKey);
1668
+ }
1669
+ }
1670
+ }
1671
+ function translateConvexParts(parts, dx, dy) {
1672
+ return parts.map(p => ({
1673
+ vertices: p.vertices.map(v => ({
1674
+ x: v.x + dx,
1675
+ y: v.y + dy
1676
+ }))
1677
+ }));
1678
+ }
1679
+ function isConvex(polygon) {
1680
+ if (polygon.length < 3) return true;
1681
+ let sign = 0;
1682
+ const n = polygon.length;
1683
+ for (let i = 0; i < n; i++) {
1684
+ const a = polygon[i];
1685
+ const b = polygon[(i + 1) % n];
1686
+ const c = polygon[(i + 2) % n];
1687
+ const ex1 = b.x - a.x;
1688
+ const ey1 = b.y - a.y;
1689
+ const ex2 = c.x - b.x;
1690
+ const ey2 = c.y - b.y;
1691
+ const cross = ex1 * ey2 - ey1 * ex2;
1692
+ if (cross !== 0) {
1693
+ if (sign === 0) sign = cross > 0 ? 1 : -1;else if ((cross > 0 ? 1 : -1) !== sign) return false;
1694
+ }
1695
+ }
1696
+ return true;
1697
+ }
1698
+ function decomposePolygon(polygon) {
1699
+ if (polygon.length < 3) return [];
1700
+ if (!isConvex(polygon)) {
1701
+ const err = new Error(`decomposePolygon: input polygon (${polygon.length} vertices) is non-convex. ` + `This is a placeholder implementation that assumes convex input — concave polygons silently produce ` + `invalid Matter.js bodies. Real concave decomposition requires the 'poly-decomp' npm dependency ` + `(see ADR-0019 Phase 1). If you need concave physics tiles right now, split into convex parts manually.`);
1702
+ if (typeof console !== 'undefined') console.error('[Tilemap]', err.message);
1703
+ throw err;
1704
+ }
1705
+ return [{
1706
+ vertices: polygon.slice()
1707
+ }];
1708
+ }
1709
+ function cacheKeyOfNum(slot, col, row, altIdx) {
1710
+ return ((slot & 0xff) << 24 | (altIdx & 0x3f) << 18 | (row & 0x1ff) << 9 | col & 0x1ff) >>> 0;
1711
+ }
1712
+ DecompositionCache.prototype.getNum = function (key) {
1713
+ return this.get({
1714
+ sourceSlot: key >>> 24 & 0xff,
1715
+ altIdx: key >>> 18 & 0x3f,
1716
+ row: key >>> 9 & 0x1ff,
1717
+ col: key & 0x1ff,
1718
+ layerId: "__num__"
1719
+ });
1720
+ };
1721
+ DecompositionCache.prototype.setNum = function (key, value) {
1722
+ this.set({
1723
+ sourceSlot: key >>> 24 & 0xff,
1724
+ altIdx: key >>> 18 & 0x3f,
1725
+ row: key >>> 9 & 0x1ff,
1726
+ col: key & 0x1ff,
1727
+ layerId: "__num__"
1728
+ }, value);
1729
+ };
1730
+ class BodySourceRegistryImpl {
1731
+ constructor() {
1732
+ this.builders = new Map();
1733
+ }
1734
+ register(name, builder) {
1735
+ this.builders.set(name, builder);
1736
+ }
1737
+ unregister(name) {
1738
+ this.builders.delete(name);
1739
+ }
1740
+ has(name) {
1741
+ return this.builders.has(name);
1742
+ }
1743
+ build(name, ctx) {
1744
+ const b = this.builders.get(name);
1745
+ if (!b) return null;
1746
+ return b(ctx);
1747
+ }
1748
+ listRegisteredNames() {
1749
+ return Array.from(this.builders.keys());
1750
+ }
1751
+ clear() {
1752
+ this.builders.clear();
1753
+ }
1754
+ }
1755
+ const TILEMAP_BODY_SOURCE_REGISTRY = new BodySourceRegistryImpl();
1756
+ const CHUNK_SIZE = 16;
1757
+ function unpackSlot(packed) {
1758
+ return packed & 0xff;
1759
+ }
1760
+ function unpackCol(packed) {
1761
+ return packed >>> 8 & 0xff;
1762
+ }
1763
+ function unpackRow(packed) {
1764
+ return packed >>> 16 & 0xff;
1765
+ }
1766
+ function unpackAlt(packed) {
1767
+ return packed >>> 24 & 0x1f;
1768
+ }
1769
+ function buildTileMapStaticBodies(input, ctx) {
1770
+ var _a;
1771
+ const out = [];
1772
+ for (const [chunkKey, arr] of Object.entries(input.chunksByKey)) {
1773
+ const [ckxStr, ckyStr] = chunkKey.split(",");
1774
+ const ckx = Number.parseInt(ckxStr, 10);
1775
+ const cky = Number.parseInt(ckyStr, 10);
1776
+ if (!Number.isFinite(ckx) || !Number.isFinite(cky)) continue;
1777
+ for (let ly = 0; ly < CHUNK_SIZE; ly++) {
1778
+ for (let lx = 0; lx < CHUNK_SIZE; lx++) {
1779
+ const packed = arr[ly * CHUNK_SIZE + lx];
1780
+ const slot = unpackSlot(packed);
1781
+ if (slot === 0) continue;
1782
+ const col = unpackCol(packed);
1783
+ const row = unpackRow(packed);
1784
+ const altIdx = unpackAlt(packed);
1785
+ const physicsKey = `${slot},${col},${row},${altIdx}`;
1786
+ const physicsEntries = input.physicsByCellKey.get(physicsKey);
1787
+ if (!physicsEntries || physicsEntries.length === 0) continue;
1788
+ const cellWorldX = input.mapOriginX + (ckx * CHUNK_SIZE + lx) * input.cellWidth + ctx.worldX;
1789
+ const cellWorldY = input.mapOriginY + (cky * CHUNK_SIZE + ly) * input.cellHeight + ctx.worldY;
1790
+ for (const entry of physicsEntries) {
1791
+ for (const poly of entry.polygons) {
1792
+ const cacheKeyNum = cacheKeyOfNum(slot, col, row, altIdx);
1793
+ let parts = (_a = input.cache.getNum(cacheKeyNum)) === null || _a === void 0 ? void 0 : _a.parts;
1794
+ if (!parts) {
1795
+ parts = decomposePolygon(poly.points);
1796
+ input.cache.setNum(cacheKeyNum, {
1797
+ parts
1798
+ });
1799
+ }
1800
+ const translated = translateConvexParts(parts, cellWorldX, cellWorldY);
1801
+ for (let pi = 0; pi < translated.length; pi++) {
1802
+ out.push({
1803
+ id: `tile-${chunkKey}-${lx}-${ly}-${entry.layerId}-${pi}`,
1804
+ vertices: translated[pi].vertices,
1805
+ centerX: cellWorldX + input.cellWidth / 2,
1806
+ centerY: cellWorldY + input.cellHeight / 2,
1807
+ isStatic: true,
1808
+ oneWay: entry.oneWay,
1809
+ friction: entry.friction,
1810
+ restitution: entry.restitution,
1811
+ metadata: {
1812
+ layerId: entry.layerId,
1813
+ chunkKey,
1814
+ cellLocal: [lx, ly]
1815
+ }
1816
+ });
1817
+ }
1818
+ }
1819
+ }
1820
+ }
1821
+ }
1822
+ }
1823
+ return out;
1824
+ }
1825
+ function buildTileMapStaticBodyDefinitions(input, ctx, probes) {
1826
+ var _a, _b;
1827
+ probes === null || probes === void 0 ? void 0 : probes.beginTiming(TILEMAP_PROBE_NAMES.PHYSICS_REBAKE_MS);
1828
+ let bodies;
1829
+ try {
1830
+ bodies = buildTileMapStaticBodies(input, ctx);
1831
+ } finally {
1832
+ probes === null || probes === void 0 ? void 0 : probes.endTiming(TILEMAP_PROBE_NAMES.PHYSICS_REBAKE_MS);
1833
+ }
1834
+ const bodiesByLayerId = new Map();
1835
+ for (const b of bodies) {
1836
+ const layerId = (_b = (_a = b.metadata) === null || _a === void 0 ? void 0 : _a.layerId) !== null && _b !== void 0 ? _b : "<unlabeled>";
1837
+ let bucket = bodiesByLayerId.get(layerId);
1838
+ if (!bucket) {
1839
+ bucket = [];
1840
+ bodiesByLayerId.set(layerId, bucket);
1841
+ }
1842
+ bucket.push(b);
1843
+ }
1844
+ const totalBodyCount = bodies.length;
1845
+ probes === null || probes === void 0 ? void 0 : probes.gauge(TILEMAP_PROBE_NAMES.BODIES_TOTAL, totalBodyCount);
1846
+ if (totalBodyCount > 0) {
1847
+ probes === null || probes === void 0 ? void 0 : probes.count(TILEMAP_PROBE_NAMES.BODIES_CREATED, totalBodyCount);
1848
+ }
1849
+ return {
1850
+ bodies,
1851
+ totalBodyCount,
1852
+ bodiesByLayerId
1853
+ };
1854
+ }
1855
+ function extractPhysicsByCellKey(tilesetRaw) {
1856
+ const out = new Map();
1857
+ for (let slotIdx = 0; slotIdx < tilesetRaw.sources.length; slotIdx++) {
1858
+ const src = tilesetRaw.sources[slotIdx];
1859
+ if (!src || src.kind !== "atlas" || !src.tiles) continue;
1860
+ const slot = slotIdx + 1;
1861
+ for (const tile of src.tiles) {
1862
+ const {
1863
+ col,
1864
+ row
1865
+ } = tile.atlasCoords;
1866
+ for (const alt of tile.alternatives) {
1867
+ if (!alt.physics || alt.physics.length === 0) continue;
1868
+ const key = `${slot},${col},${row},${alt.altId & 0x1f}`;
1869
+ out.set(key, alt.physics);
1870
+ }
1871
+ }
1872
+ }
1873
+ return out;
1874
+ }
1875
+ const ADR_0019_NATIVE_REGISTRY_AVAILABLE = false;
1876
+ try {
1877
+ eva_js.resource.registerResourceType('TILESET');
1878
+ } catch (_a) {}
1879
+ try {
1880
+ eva_js.resource.registerInstance('TILESET', res => {
1881
+ var _a, _b, _c, _d;
1882
+ const fromData = (_a = res.data) === null || _a === void 0 ? void 0 : _a.json;
1883
+ const fromSrc = (_c = (_b = res.src) === null || _b === void 0 ? void 0 : _b.json) === null || _c === void 0 ? void 0 : _c.data;
1884
+ return (_d = fromData !== null && fromData !== void 0 ? fromData : fromSrc) !== null && _d !== void 0 ? _d : null;
1885
+ });
1886
+ } catch (_b) {}
1887
+ exports.ADR_0019_NATIVE_REGISTRY_AVAILABLE = ADR_0019_NATIVE_REGISTRY_AVAILABLE;
1888
+ exports.CHUNK_SIZE = CHUNK_SIZE$2;
1889
+ exports.DecompositionCache = DecompositionCache;
1890
+ exports.MAX_TERRAIN_ID = MAX_TERRAIN_ID;
1891
+ exports.NEIGHBOR_DIRECTIONS = NEIGHBOR_DIRECTIONS;
1892
+ exports.NO_NEIGHBOR = NO_NEIGHBOR;
1893
+ exports.PeeringBitIndex = PeeringBitIndex;
1894
+ exports.TILEMAP_BODY_SOURCE_REGISTRY = TILEMAP_BODY_SOURCE_REGISTRY;
1895
+ exports.TILEMAP_PROBE_NAMES = TILEMAP_PROBE_NAMES;
1896
+ exports.TILE_FRAG_SHADER = TILE_FRAG_SHADER;
1897
+ exports.TILE_SHADER_SOURCES = TILE_SHADER_SOURCES;
1898
+ exports.TILE_VERT_SHADER = TILE_VERT_SHADER;
1899
+ exports.TileAnimationDriver = TileAnimationDriver;
347
1900
  exports.Tilemap = Tilemap;
348
1901
  exports.TilemapSystem = TilemapSystem$1;
1902
+ exports.adaptGamePerfProbes = adaptGamePerfProbes;
1903
+ exports.buildChunkGeometry = buildChunkGeometry;
1904
+ exports.buildChunkMesh = buildChunkMesh;
1905
+ exports.buildTileMapStaticBodies = buildTileMapStaticBodies;
1906
+ exports.buildTileMapStaticBodyDefinitions = buildTileMapStaticBodyDefinitions;
1907
+ exports.cacheKeyOf = cacheKeyOf;
1908
+ exports.cacheKeyOfNum = cacheKeyOfNum;
1909
+ exports.computeAffectedChunks = computeAffectedChunks;
1910
+ exports.createInMemoryProbeRegistry = createInMemoryProbeRegistry;
1911
+ exports.decodeChunk = decodeChunk;
1912
+ exports.decomposePolygon = decomposePolygon;
1913
+ exports.diffTilesetDocuments = diffTilesetDocuments;
1914
+ exports.diffTilesetForChunkRebuild = diffTilesetForChunkRebuild;
1915
+ exports.estimateChunkMeshMemoryKB = estimateChunkMeshMemoryKB;
1916
+ exports.estimateSpriteNodes = estimateSpriteNodes;
1917
+ exports.expandSceneCollectionSource = expandSceneCollectionSource;
1918
+ exports.extractPhysicsByCellKey = extractPhysicsByCellKey;
1919
+ exports.getRequiredTilemapProbes = getRequiredTilemapProbes;
1920
+ exports.isEmptyCellValue = isEmptyCellValue;
1921
+ exports.isMeshPathAvailable = isMeshPathAvailable;
1922
+ exports.makeLoadedTileset = makeLoadedTileset;
1923
+ exports.pickAutotileCandidate = pickAutotileCandidate;
1924
+ exports.resolveCellPrefabName = resolveCellPrefabName;
1925
+ exports.resolveChunkRenderStrategy = resolveChunkRenderStrategy;
1926
+ exports.translateConvexParts = translateConvexParts;
1927
+ exports.unpackCell = unpackCell;
349
1928
  Object.defineProperty(exports, '__esModule', {
350
1929
  value: true
351
1930
  });