@codexo/exojs-tilemap 0.16.1 → 0.16.2

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.
@@ -79,6 +79,12 @@ export declare class ChunkStreamer {
79
79
  * Evict every chunk this instance has loaded and stop responding to
80
80
  * {@link update}. Does not affect chunks predating attachment or
81
81
  * installed by another source. Idempotent.
82
+ *
83
+ * Does not destroy the {@link ChunkSource} passed to the constructor: this
84
+ * class only reads from it and never took ownership. A source with its own
85
+ * `destroy()` (e.g. {@link import('./WorkerSampledChunkSource').createWorkerSampledChunkSource}'s,
86
+ * which tears down a real `Worker`) must be destroyed separately by
87
+ * whoever created it.
82
88
  */
83
89
  destroy(): void;
84
90
  private _computeCoreRange;
@@ -1 +1 @@
1
- {"version":3,"file":"ChunkStreamer.d.ts","sourceRoot":"","sources":["../../src/ChunkStreamer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,IAAI,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,KAAK,EAAgB,WAAW,EAAE,MAAM,eAAe,CAAC;AAC/D,OAAO,KAAK,EAAc,SAAS,EAAE,MAAM,aAAa,CAAC;AAGzD;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B;;;;;OAKG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B;;;;OAIG;IACH,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,CAAC;CACzC;AAWD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAY;IACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAc;IACtC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAO;IAC7B,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ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CAAY;IACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAc;IACtC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAO;IAC7B,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAS;IAEhD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAmE;IAC7F,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA6B;IACvD,OAAO,CAAC,eAAe,CAAK;IAC5B,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,UAAU,CAAS;gBAER,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,EAAE,oBAAoB;IAapG,0EAA0E;IAC1E,IAAW,aAAa,IAAI,MAAM,CAEjC;IAED;;;;;;;OAOG;IACI,MAAM,IAAI,IAAI;IA4CrB;;;;;;;;;;OAUG;IACI,OAAO,IAAI,IAAI;IAWtB,OAAO,CAAC,iBAAiB;IA6BzB,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,OAAO;IASf,OAAO,CAAC,QAAQ;IAqChB;;;;;;;OAOG;IACH,OAAO,CAAC,WAAW;CAUpB"}
@@ -103,6 +103,12 @@ var ChunkStreamer = class {
103
103
  * Evict every chunk this instance has loaded and stop responding to
104
104
  * {@link update}. Does not affect chunks predating attachment or
105
105
  * installed by another source. Idempotent.
106
+ *
107
+ * Does not destroy the {@link ChunkSource} passed to the constructor: this
108
+ * class only reads from it and never took ownership. A source with its own
109
+ * `destroy()` (e.g. {@link import('./WorkerSampledChunkSource').createWorkerSampledChunkSource}'s,
110
+ * which tears down a real `Worker`) must be destroyed separately by
111
+ * whoever created it.
106
112
  */
107
113
  destroy() {
108
114
  if (this._destroyed) return;
@@ -1 +1 @@
1
- {"version":3,"file":"ChunkStreamer.js","names":[],"sources":["../../src/ChunkStreamer.ts"],"sourcesContent":["import { logger, type View } from '@codexo/exojs';\n\nimport type { ChunkPayload, ChunkSource } from './ChunkSource';\nimport type { ChunkRange, TileLayer } from './TileLayer';\nimport { tileToChunkCoord } from './types';\n\n/**\n * Options for a {@link ChunkStreamer}. All optional.\n * @advanced\n */\nexport interface ChunkStreamerOptions {\n /**\n * Chunks within this many chunk-units (Chebyshev distance to the visible\n * chunk range) of the view are loaded. Default `1`.\n */\n readonly loadRadius?: number;\n /**\n * Own-resident chunks beyond this many chunk-units of the view are\n * evicted. Must be `>= loadRadius` - the gap between the two is\n * deliberate hysteresis that prevents load/unload thrashing when the\n * view sits near a chunk boundary. Default `2`.\n */\n readonly unloadRadius?: number;\n /**\n * Maximum number of new chunk loads issued per {@link ChunkStreamer.update}\n * call, after the very first call (which loads the entire initial wanted\n * set unbudgeted, so the starting view never pops in). Default `8`.\n */\n readonly maxChunkLoadsPerFrame?: number;\n}\n\nconst DEFAULT_LOAD_RADIUS = 1;\nconst DEFAULT_UNLOAD_RADIUS = 2;\nconst DEFAULT_MAX_CHUNK_LOADS_PER_FRAME = 8;\n\nconst chunkKey = (cx: number, cy: number): string => `${cx},${cy}`;\n\nconst isThenable = (value: unknown): value is Promise<ChunkPayload | null> =>\n value !== null && typeof value === 'object' && typeof (value as { then?: unknown }).then === 'function';\n\n/**\n * Drives {@link TileLayer._adoptChunk}/{@link TileLayer._evictChunk} calls\n * from a {@link View}'s position: chunks near the view are requested from a\n * {@link ChunkSource} and installed; chunks that scroll far enough away are\n * evicted. Works on both unbounded and bounded layers (a bounded-but-large\n * layer still benefits from not keeping every chunk resident at once) - for\n * a bounded layer, the wanted range is clamped to {@link TileLayer.chunkRange}.\n *\n * Touches only the {@link TileLayer} data layer -\n * {@link import('./TileLayerNode').TileLayerNode} reacts to\n * `_adoptChunk`/`_evictChunk` on its own via a structural listener, so this\n * class has no rendering dependency and no reference to any scene node.\n *\n * Tracks its own resident set (chunks *this instance* has loaded), never\n * touching chunks that predate its attachment or were installed by another\n * source.\n *\n * Tick it from your update loop, like {@link import('./TileAnimator').TileAnimator}:\n *\n * ```ts\n * const streamer = new ChunkStreamer(layer, mySource, view);\n * scene.systems.add({ update: () => streamer.update() });\n * ```\n *\n * @advanced\n */\nexport class ChunkStreamer {\n private readonly _layer: TileLayer;\n private readonly _source: ChunkSource;\n private readonly _view: View;\n private readonly _loadRadius: number;\n private readonly _unloadRadius: number;\n private readonly _maxChunkLoadsPerFrame: number;\n\n private readonly _resident = new Map<string, { readonly cx: number; readonly cy: number }>();\n private readonly _inFlight = new Map<string, number>();\n private _requestCounter = 0;\n private _primed = false;\n private _destroyed = false;\n\n public constructor(layer: TileLayer, source: ChunkSource, view: View, options?: ChunkStreamerOptions) {\n this._layer = layer;\n this._source = source;\n this._view = view;\n this._loadRadius = options?.loadRadius ?? DEFAULT_LOAD_RADIUS;\n this._unloadRadius = options?.unloadRadius ?? DEFAULT_UNLOAD_RADIUS;\n this._maxChunkLoadsPerFrame = options?.maxChunkLoadsPerFrame ?? DEFAULT_MAX_CHUNK_LOADS_PER_FRAME;\n\n if (this._unloadRadius < this._loadRadius) {\n throw new Error(`ChunkStreamer unloadRadius (${this._unloadRadius}) must be >= loadRadius (${this._loadRadius}).`);\n }\n }\n\n /** Number of chunks this instance currently has resident in the layer. */\n public get residentCount(): number {\n return this._resident.size;\n }\n\n /**\n * Recompute the wanted chunk set from the view's current position; evict\n * own-resident chunks that fell outside `unloadRadius`, then request\n * chunks newly inside `loadRadius`. The very first call loads the entire\n * initial wanted set unbudgeted; every later call is capped at\n * {@link ChunkStreamerOptions.maxChunkLoadsPerFrame}. No-op once\n * {@link destroy}ed.\n */\n public update(): void {\n if (this._destroyed) return;\n\n const core = this._computeCoreRange();\n\n this._unload(core);\n\n const range = this._layer.chunkRange();\n let minCx = core.minCx - this._loadRadius;\n let minCy = core.minCy - this._loadRadius;\n let maxCx = core.maxCx + this._loadRadius;\n let maxCy = core.maxCy + this._loadRadius;\n if (range !== null) {\n minCx = Math.max(minCx, range.minCx);\n minCy = Math.max(minCy, range.minCy);\n maxCx = Math.min(maxCx, range.maxCx);\n maxCy = Math.min(maxCy, range.maxCy);\n }\n\n const toLoad: Array<{ cx: number; cy: number }> = [];\n for (let cy = minCy; cy <= maxCy; cy++) {\n for (let cx = minCx; cx <= maxCx; cx++) {\n const key = chunkKey(cx, cy);\n if (this._resident.has(key) || this._inFlight.has(key)) continue;\n toLoad.push({ cx, cy });\n }\n }\n\n if (!this._primed) {\n this._primed = true;\n for (const { cx, cy } of toLoad) {\n this._request(cx, cy);\n }\n return;\n }\n\n toLoad.sort((a, b) => this._rangeDistance(a.cx, a.cy, core) - this._rangeDistance(b.cx, b.cy, core));\n\n const budget = Math.min(this._maxChunkLoadsPerFrame, toLoad.length);\n for (const { cx, cy } of toLoad.slice(0, budget)) {\n this._request(cx, cy);\n }\n }\n\n /**\n * Evict every chunk this instance has loaded and stop responding to\n * {@link update}. Does not affect chunks predating attachment or\n * installed by another source. Idempotent.\n */\n public destroy(): void {\n if (this._destroyed) return;\n this._destroyed = true;\n\n for (const { cx, cy } of this._resident.values()) {\n this._layer._evictChunk(cx, cy);\n }\n this._resident.clear();\n this._inFlight.clear();\n }\n\n private _computeCoreRange(): ChunkRange {\n const layer = this._layer;\n const view = this._view;\n const bounds = view.getBounds();\n const centerX = view.center.x;\n const centerY = view.center.y;\n\n const shiftX = centerX * (1 - layer.parallaxX);\n const shiftY = centerY * (1 - layer.parallaxY);\n const scale = layer.parallaxScale;\n\n const layerLeft = layer.offsetX + (bounds.left - shiftX - layer.offsetX) / scale;\n const layerTop = layer.offsetY + (bounds.top - shiftY - layer.offsetY) / scale;\n const layerRight = layer.offsetX + (bounds.right - shiftX - layer.offsetX) / scale;\n const layerBottom = layer.offsetY + (bounds.bottom - shiftY - layer.offsetY) / scale;\n const topLeftTile = layer.pixelToTile(layerLeft, layerTop);\n const bottomRightTile = layer.pixelToTile(layerRight, layerBottom);\n\n const topLeftChunk = tileToChunkCoord(topLeftTile.tx, topLeftTile.ty, layer.chunkWidth, layer.chunkHeight);\n const bottomRightChunk = tileToChunkCoord(bottomRightTile.tx, bottomRightTile.ty, layer.chunkWidth, layer.chunkHeight);\n\n return {\n minCx: topLeftChunk.cx,\n minCy: topLeftChunk.cy,\n maxCx: bottomRightChunk.cx,\n maxCy: bottomRightChunk.cy,\n };\n }\n\n private _rangeDistance(cx: number, cy: number, range: ChunkRange): number {\n const dx = Math.max(range.minCx - cx, 0, cx - range.maxCx);\n const dy = Math.max(range.minCy - cy, 0, cy - range.maxCy);\n return Math.max(dx, dy);\n }\n\n private _unload(core: ChunkRange): void {\n for (const [key, { cx, cy }] of this._resident) {\n if (this._rangeDistance(cx, cy, core) > this._unloadRadius) {\n this._layer._evictChunk(cx, cy);\n this._resident.delete(key);\n }\n }\n }\n\n private _request(cx: number, cy: number): void {\n const key = chunkKey(cx, cy);\n const token = ++this._requestCounter;\n this._inFlight.set(key, token);\n\n let result: ChunkPayload | null | Promise<ChunkPayload | null>;\n try {\n result = this._source.getChunk(cx, cy);\n } catch (error) {\n this._inFlight.delete(key);\n logger.warn(`ChunkStreamer: source.getChunk(${cx}, ${cy}) threw synchronously.`, {\n source: 'ChunkStreamer',\n error: error instanceof Error ? error : new Error(String(error)),\n });\n\n return;\n }\n\n if (isThenable(result)) {\n result.then(\n payload => {\n this._onResolved(key, cx, cy, token, payload);\n },\n (error: unknown) => {\n this._inFlight.delete(key);\n logger.warn(`ChunkStreamer: source.getChunk(${cx}, ${cy}) rejected.`, {\n source: 'ChunkStreamer',\n error: error instanceof Error ? error : new Error(String(error)),\n });\n },\n );\n return;\n }\n\n this._onResolved(key, cx, cy, token, result);\n }\n\n /**\n * Ignore-on-resolve: only the `_destroyed` and in-flight-token checks\n * guard installation - a chunk that scrolled out of the wanted set while\n * its request was in flight is still installed if it resolves (installing\n * it is cheap and self-correcting: the next {@link update} call's unload\n * pass evicts it again if it's genuinely no longer wanted). There is no\n * edit-persistence to protect, so discarding is never destructive.\n */\n private _onResolved(key: string, cx: number, cy: number, token: number, payload: ChunkPayload | null): void {\n if (this._destroyed) return;\n if (this._inFlight.get(key) !== token) return;\n this._inFlight.delete(key);\n\n if (payload === null) return;\n\n this._layer._adoptChunk(cx, cy, payload);\n this._resident.set(key, { cx, cy });\n }\n}\n"],"mappings":";;;;AA+BA,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAC9B,MAAM,oCAAoC;AAE1C,MAAM,YAAY,IAAY,OAAuB,GAAG,GAAG,GAAG;AAE9D,MAAM,cAAc,UAClB,UAAU,QAAQ,OAAO,UAAU,YAAY,OAAQ,MAA6B,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B/F,IAAa,gBAAb,MAA2B;CACzB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,AAAiB,4BAAY,IAAI,IAA0D;CAC3F,AAAiB,4BAAY,IAAI,IAAoB;CACrD,AAAQ,kBAAkB;CAC1B,AAAQ,UAAU;CAClB,AAAQ,aAAa;CAErB,AAAO,YAAY,OAAkB,QAAqB,MAAY,SAAgC;EACpG,KAAK,SAAS;EACd,KAAK,UAAU;EACf,KAAK,QAAQ;EACb,KAAK,cAAc,SAAS,cAAc;EAC1C,KAAK,gBAAgB,SAAS,gBAAgB;EAC9C,KAAK,yBAAyB,SAAS,yBAAyB;EAEhE,IAAI,KAAK,gBAAgB,KAAK,aAC5B,MAAM,IAAI,MAAM,+BAA+B,KAAK,cAAc,2BAA2B,KAAK,YAAY,GAAG;CAErH;;CAGA,IAAW,gBAAwB;EACjC,OAAO,KAAK,UAAU;CACxB;;;;;;;;;CAUA,AAAO,SAAe;EACpB,IAAI,KAAK,YAAY;EAErB,MAAM,OAAO,KAAK,kBAAkB;EAEpC,KAAK,QAAQ,IAAI;EAEjB,MAAM,QAAQ,KAAK,OAAO,WAAW;EACrC,IAAI,QAAQ,KAAK,QAAQ,KAAK;EAC9B,IAAI,QAAQ,KAAK,QAA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,UAAU,OAAO,GAAG;EAC3B;CAEJ;CAEA,AAAQ,SAAS,IAAY,IAAkB;EAC7C,MAAM,MAAM,SAAS,IAAI,EAAE;EAC3B,MAAM,QAAQ,EAAE,KAAK;EACrB,KAAK,UAAU,IAAI,KAAK,KAAK;EAE7B,IAAI;EACJ,IAAI;GACF,SAAS,KAAK,QAAQ,SAAS,IAAI,EAAE;EACvC,SAAS,OAAO;GACd,KAAK,UAAU,OAAO,GAAG;GACzB,OAAO,KAAK,kCAAkC,GAAG,IAAI,GAAG,yBAAyB;IAC/E,QAAQ;IACR,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;GACjE,CAAC;GAED;EACF;EAEA,IAAI,WAAW,MAAM,GAAG;GACtB,OAAO,MACL,YAAW;IACT,KAAK,YAAY,KAAK,IAAI,IAAI,OAAO,OAAO;GAC9C,IACC,UAAmB;IAClB,KAAK,UAAU,OAAO,GAAG;IACzB,OAAO,KAAK,kCAAkC,GAAG,IAAI,GAAG,cAAc;KACpE,QAAQ;KACR,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;IACjE,CAAC;GACH,CACF;GACA;EACF;EAEA,KAAK,YAAY,KAAK,IAAI,IAAI,OAAO,MAAM;CAC7C;;;;;;;;;CAUA,AAAQ,YAAY,KAAa,IAAY,IAAY,OAAe,SAAoC;EAC1G,IAAI,KAAK,YAAY;EACrB,IAAI,KAAK,UAAU,IAAI,GAAG,MAAM,OAAO;EACvC,KAAK,UAAU,OAAO,GAAG;EAEzB,IAAI,YAAY,MAAM;EAEtB,KAAK,OAAO,YAAY,IAAI,IAAI,OAAO;EACvC,KAAK,UAAU,IAAI,KAAK;GAAE;GAAI;EAAG,CAAC;CACpC;AACF"}
1
+ {"version":3,"file":"ChunkStreamer.js","names":[],"sources":["../../src/ChunkStreamer.ts"],"sourcesContent":["import { logger, type View } from '@codexo/exojs';\n\nimport type { ChunkPayload, ChunkSource } from './ChunkSource';\nimport type { ChunkRange, TileLayer } from './TileLayer';\nimport { tileToChunkCoord } from './types';\n\n/**\n * Options for a {@link ChunkStreamer}. All optional.\n * @advanced\n */\nexport interface ChunkStreamerOptions {\n /**\n * Chunks within this many chunk-units (Chebyshev distance to the visible\n * chunk range) of the view are loaded. Default `1`.\n */\n readonly loadRadius?: number;\n /**\n * Own-resident chunks beyond this many chunk-units of the view are\n * evicted. Must be `>= loadRadius` - the gap between the two is\n * deliberate hysteresis that prevents load/unload thrashing when the\n * view sits near a chunk boundary. Default `2`.\n */\n readonly unloadRadius?: number;\n /**\n * Maximum number of new chunk loads issued per {@link ChunkStreamer.update}\n * call, after the very first call (which loads the entire initial wanted\n * set unbudgeted, so the starting view never pops in). Default `8`.\n */\n readonly maxChunkLoadsPerFrame?: number;\n}\n\nconst DEFAULT_LOAD_RADIUS = 1;\nconst DEFAULT_UNLOAD_RADIUS = 2;\nconst DEFAULT_MAX_CHUNK_LOADS_PER_FRAME = 8;\n\nconst chunkKey = (cx: number, cy: number): string => `${cx},${cy}`;\n\nconst isThenable = (value: unknown): value is Promise<ChunkPayload | null> =>\n value !== null && typeof value === 'object' && typeof (value as { then?: unknown }).then === 'function';\n\n/**\n * Drives {@link TileLayer._adoptChunk}/{@link TileLayer._evictChunk} calls\n * from a {@link View}'s position: chunks near the view are requested from a\n * {@link ChunkSource} and installed; chunks that scroll far enough away are\n * evicted. Works on both unbounded and bounded layers (a bounded-but-large\n * layer still benefits from not keeping every chunk resident at once) - for\n * a bounded layer, the wanted range is clamped to {@link TileLayer.chunkRange}.\n *\n * Touches only the {@link TileLayer} data layer -\n * {@link import('./TileLayerNode').TileLayerNode} reacts to\n * `_adoptChunk`/`_evictChunk` on its own via a structural listener, so this\n * class has no rendering dependency and no reference to any scene node.\n *\n * Tracks its own resident set (chunks *this instance* has loaded), never\n * touching chunks that predate its attachment or were installed by another\n * source.\n *\n * Tick it from your update loop, like {@link import('./TileAnimator').TileAnimator}:\n *\n * ```ts\n * const streamer = new ChunkStreamer(layer, mySource, view);\n * scene.systems.add({ update: () => streamer.update() });\n * ```\n *\n * @advanced\n */\nexport class ChunkStreamer {\n private readonly _layer: TileLayer;\n private readonly _source: ChunkSource;\n private readonly _view: View;\n private readonly _loadRadius: number;\n private readonly _unloadRadius: number;\n private readonly _maxChunkLoadsPerFrame: number;\n\n private readonly _resident = new Map<string, { readonly cx: number; readonly cy: number }>();\n private readonly _inFlight = new Map<string, number>();\n private _requestCounter = 0;\n private _primed = false;\n private _destroyed = false;\n\n public constructor(layer: TileLayer, source: ChunkSource, view: View, options?: ChunkStreamerOptions) {\n this._layer = layer;\n this._source = source;\n this._view = view;\n this._loadRadius = options?.loadRadius ?? DEFAULT_LOAD_RADIUS;\n this._unloadRadius = options?.unloadRadius ?? DEFAULT_UNLOAD_RADIUS;\n this._maxChunkLoadsPerFrame = options?.maxChunkLoadsPerFrame ?? DEFAULT_MAX_CHUNK_LOADS_PER_FRAME;\n\n if (this._unloadRadius < this._loadRadius) {\n throw new Error(`ChunkStreamer unloadRadius (${this._unloadRadius}) must be >= loadRadius (${this._loadRadius}).`);\n }\n }\n\n /** Number of chunks this instance currently has resident in the layer. */\n public get residentCount(): number {\n return this._resident.size;\n }\n\n /**\n * Recompute the wanted chunk set from the view's current position; evict\n * own-resident chunks that fell outside `unloadRadius`, then request\n * chunks newly inside `loadRadius`. The very first call loads the entire\n * initial wanted set unbudgeted; every later call is capped at\n * {@link ChunkStreamerOptions.maxChunkLoadsPerFrame}. No-op once\n * {@link destroy}ed.\n */\n public update(): void {\n if (this._destroyed) return;\n\n const core = this._computeCoreRange();\n\n this._unload(core);\n\n const range = this._layer.chunkRange();\n let minCx = core.minCx - this._loadRadius;\n let minCy = core.minCy - this._loadRadius;\n let maxCx = core.maxCx + this._loadRadius;\n let maxCy = core.maxCy + this._loadRadius;\n if (range !== null) {\n minCx = Math.max(minCx, range.minCx);\n minCy = Math.max(minCy, range.minCy);\n maxCx = Math.min(maxCx, range.maxCx);\n maxCy = Math.min(maxCy, range.maxCy);\n }\n\n const toLoad: Array<{ cx: number; cy: number }> = [];\n for (let cy = minCy; cy <= maxCy; cy++) {\n for (let cx = minCx; cx <= maxCx; cx++) {\n const key = chunkKey(cx, cy);\n if (this._resident.has(key) || this._inFlight.has(key)) continue;\n toLoad.push({ cx, cy });\n }\n }\n\n if (!this._primed) {\n this._primed = true;\n for (const { cx, cy } of toLoad) {\n this._request(cx, cy);\n }\n return;\n }\n\n toLoad.sort((a, b) => this._rangeDistance(a.cx, a.cy, core) - this._rangeDistance(b.cx, b.cy, core));\n\n const budget = Math.min(this._maxChunkLoadsPerFrame, toLoad.length);\n for (const { cx, cy } of toLoad.slice(0, budget)) {\n this._request(cx, cy);\n }\n }\n\n /**\n * Evict every chunk this instance has loaded and stop responding to\n * {@link update}. Does not affect chunks predating attachment or\n * installed by another source. Idempotent.\n *\n * Does not destroy the {@link ChunkSource} passed to the constructor: this\n * class only reads from it and never took ownership. A source with its own\n * `destroy()` (e.g. {@link import('./WorkerSampledChunkSource').createWorkerSampledChunkSource}'s,\n * which tears down a real `Worker`) must be destroyed separately by\n * whoever created it.\n */\n public destroy(): void {\n if (this._destroyed) return;\n this._destroyed = true;\n\n for (const { cx, cy } of this._resident.values()) {\n this._layer._evictChunk(cx, cy);\n }\n this._resident.clear();\n this._inFlight.clear();\n }\n\n private _computeCoreRange(): ChunkRange {\n const layer = this._layer;\n const view = this._view;\n const bounds = view.getBounds();\n const centerX = view.center.x;\n const centerY = view.center.y;\n\n const shiftX = centerX * (1 - layer.parallaxX);\n const shiftY = centerY * (1 - layer.parallaxY);\n const scale = layer.parallaxScale;\n\n const layerLeft = layer.offsetX + (bounds.left - shiftX - layer.offsetX) / scale;\n const layerTop = layer.offsetY + (bounds.top - shiftY - layer.offsetY) / scale;\n const layerRight = layer.offsetX + (bounds.right - shiftX - layer.offsetX) / scale;\n const layerBottom = layer.offsetY + (bounds.bottom - shiftY - layer.offsetY) / scale;\n const topLeftTile = layer.pixelToTile(layerLeft, layerTop);\n const bottomRightTile = layer.pixelToTile(layerRight, layerBottom);\n\n const topLeftChunk = tileToChunkCoord(topLeftTile.tx, topLeftTile.ty, layer.chunkWidth, layer.chunkHeight);\n const bottomRightChunk = tileToChunkCoord(bottomRightTile.tx, bottomRightTile.ty, layer.chunkWidth, layer.chunkHeight);\n\n return {\n minCx: topLeftChunk.cx,\n minCy: topLeftChunk.cy,\n maxCx: bottomRightChunk.cx,\n maxCy: bottomRightChunk.cy,\n };\n }\n\n private _rangeDistance(cx: number, cy: number, range: ChunkRange): number {\n const dx = Math.max(range.minCx - cx, 0, cx - range.maxCx);\n const dy = Math.max(range.minCy - cy, 0, cy - range.maxCy);\n return Math.max(dx, dy);\n }\n\n private _unload(core: ChunkRange): void {\n for (const [key, { cx, cy }] of this._resident) {\n if (this._rangeDistance(cx, cy, core) > this._unloadRadius) {\n this._layer._evictChunk(cx, cy);\n this._resident.delete(key);\n }\n }\n }\n\n private _request(cx: number, cy: number): void {\n const key = chunkKey(cx, cy);\n const token = ++this._requestCounter;\n this._inFlight.set(key, token);\n\n let result: ChunkPayload | null | Promise<ChunkPayload | null>;\n try {\n result = this._source.getChunk(cx, cy);\n } catch (error) {\n this._inFlight.delete(key);\n logger.warn(`ChunkStreamer: source.getChunk(${cx}, ${cy}) threw synchronously.`, {\n source: 'ChunkStreamer',\n error: error instanceof Error ? error : new Error(String(error)),\n });\n\n return;\n }\n\n if (isThenable(result)) {\n result.then(\n payload => {\n this._onResolved(key, cx, cy, token, payload);\n },\n (error: unknown) => {\n this._inFlight.delete(key);\n logger.warn(`ChunkStreamer: source.getChunk(${cx}, ${cy}) rejected.`, {\n source: 'ChunkStreamer',\n error: error instanceof Error ? error : new Error(String(error)),\n });\n },\n );\n return;\n }\n\n this._onResolved(key, cx, cy, token, result);\n }\n\n /**\n * Ignore-on-resolve: only the `_destroyed` and in-flight-token checks\n * guard installation - a chunk that scrolled out of the wanted set while\n * its request was in flight is still installed if it resolves (installing\n * it is cheap and self-correcting: the next {@link update} call's unload\n * pass evicts it again if it's genuinely no longer wanted). There is no\n * edit-persistence to protect, so discarding is never destructive.\n */\n private _onResolved(key: string, cx: number, cy: number, token: number, payload: ChunkPayload | null): void {\n if (this._destroyed) return;\n if (this._inFlight.get(key) !== token) return;\n this._inFlight.delete(key);\n\n if (payload === null) return;\n\n this._layer._adoptChunk(cx, cy, payload);\n this._resident.set(key, { cx, cy });\n }\n}\n"],"mappings":";;;;AA+BA,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAC9B,MAAM,oCAAoC;AAE1C,MAAM,YAAY,IAAY,OAAuB,GAAG,GAAG,GAAG;AAE9D,MAAM,cAAc,UAClB,UAAU,QAAQ,OAAO,UAAU,YAAY,OAAQ,MAA6B,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B/F,IAAa,gBAAb,MAA2B;CACzB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,AAAiB,4BAAY,IAAI,IAA0D;CAC3F,AAAiB,4BAAY,IAAI,IAAoB;CACrD,AAAQ,kBAAkB;CAC1B,AAAQ,UAAU;CAClB,AAAQ,aAAa;CAErB,AAAO,YAAY,OAAkB,QAAqB,MAAY,SAAgC;EACpG,KAAK,SAAS;EACd,KAAK,UAAU;EACf,KAAK,QAAQ;EACb,KAAK,cAAc,SAAS,cAAc;EAC1C,KAAK,gBAAgB,SAAS,gBAAgB;EAC9C,KAAK,yBAAyB,SAAS,yBAAyB;EAEhE,IAAI,KAAK,gBAAgB,KAAK,aAC5B,MAAM,IAAI,MAAM,+BAA+B,KAAK,cAAc,2BAA2B,KAAK,YAAY,GAAG;CAErH;;CAGA,IAAW,gBAAwB;EACjC,OAAO,KAAK,UAAU;CACxB;;;;;;;;;CAUA,AAAO,SAAe;EACpB,IAAI,KAAK,YAAY;EAErB,MAAM,OAAO,KAAK,kBAAkB;EAEpC,KAAK,QAAQ,IAAI;EAEjB,MAAM,QAA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Options {
23
23
  * Each non-empty loaded chunk becomes one child positioned at its pixel
24
24
  * origin, so the engine's existing per-node culling drops individual chunks and
25
25
  * the render-plan optimiser batches them by tileset texture. The layer's pixel
26
- * `offset` is applied to this node's transform; `visible` and `opacity` are
27
- * read live from the runtime layer on every frame (no rebuild required).
26
+ * `offset`, `visible` and `opacity` are all read live from the runtime layer on
27
+ * every frame (no rebuild required).
28
28
  *
29
29
  * A `parallax` factor other than `1` makes this node's rendered position
30
30
  * camera-dependent, resolved per frame in {@link _collectContent} by patching
@@ -54,8 +54,6 @@ export declare class TileLayerNode extends Container {
54
54
  private _syncedOpacity;
55
55
  private _syncedTint;
56
56
  private _pixelSnapMode;
57
- private readonly _baseOffsetX;
58
- private readonly _baseOffsetY;
59
57
  /**
60
58
  * Bound once so `TileLayer._addStructuralListener`/`_removeStructuralListener`
61
59
  * add and remove the SAME function reference. Incrementally adds/removes
@@ -1 +1 @@
1
- {"version":3,"file":"TileLayerNode.d.ts","sourceRoot":"","sources":["../../src/TileLayerNode.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,KAAK,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAKnF,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,KAAK,EAAwB,SAAS,EAAE,MAAM,aAAa,CAAC;AAEnE;;;;GAIG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBAAa,aAAc,SAAQ,SAAS;IAC1C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAY;IACnC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAU;IACtC,OAAO,CA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origin, so the engine's existing per-node culling drops individual chunks and
14
14
  * the render-plan optimiser batches them by tileset texture. The layer's pixel
15
- * `offset` is applied to this node's transform; `visible` and `opacity` are
16
- * read live from the runtime layer on every frame (no rebuild required).
15
+ * `offset`, `visible` and `opacity` are all read live from the runtime layer on
16
+ * every frame (no rebuild required).
17
17
  *
18
18
  * A `parallax` factor other than `1` makes this node's rendered position
19
19
  * camera-dependent, resolved per frame in {@link _collectContent} by patching
@@ -43,8 +43,6 @@ var TileLayerNode = class extends Container {
43
43
  _syncedOpacity = -1;
44
44
  _syncedTint = void 0;
45
45
  _pixelSnapMode = PixelSnapMode.None;
46
- _baseOffsetX;
47
- _baseOffsetY;
48
46
  /**
49
47
  * Bound once so `TileLayer._addStructuralListener`/`_removeStructuralListener`
50
48
  * add and remove the SAME function reference. Incrementally adds/removes
@@ -70,8 +68,6 @@ var TileLayerNode = class extends Container {
70
68
  super();
71
69
  this._layer = layer;
72
70
  this._cullChunks = options?.cullable ?? true;
73
- this._baseOffsetX = layer.offsetX;
74
- this._baseOffsetY = layer.offsetY;
75
71
  this.setPosition(layer.offsetX, layer.offsetY);
76
72
  this._buildChunkNodes();
77
73
  if (!this._layer.bounded || layer.parallaxX !== 1 || layer.parallaxY !== 1 || layer.parallaxScale !== 1) this.cullable = false;
@@ -146,22 +142,23 @@ var TileLayerNode = class extends Container {
146
142
  const patchesScale = layer.parallaxScale !== 1;
147
143
  if (patchesPosition || patchesScale) {
148
144
  const camCenter = builder.view.center;
149
- const prevX = this.x;
150
- const prevY = this.y;
151
145
  const prevScaleX = this.scale.x;
152
146
  const prevScaleY = this.scale.y;
153
147
  if (patchesPosition) {
154
- this.x = this._baseOffsetX + camCenter.x * (1 - layer.parallaxX);
155
- this.y = this._baseOffsetY + camCenter.y * (1 - layer.parallaxY);
156
- }
148
+ this.x = layer.offsetX + camCenter.x * (1 - layer.parallaxX);
149
+ this.y = layer.offsetY + camCenter.y * (1 - layer.parallaxY);
150
+ } else this.setPosition(layer.offsetX, layer.offsetY);
157
151
  if (patchesScale) this.setScale(prevScaleX * layer.parallaxScale, prevScaleY * layer.parallaxScale);
158
152
  try {
159
153
  super._collectContent(builder);
160
154
  } finally {
161
- if (patchesPosition) this.setPosition(prevX, prevY);
155
+ if (patchesPosition) this.setPosition(layer.offsetX, layer.offsetY);
162
156
  if (patchesScale) this.setScale(prevScaleX, prevScaleY);
163
157
  }
164
- } else super._collectContent(builder);
158
+ } else {
159
+ this.setPosition(layer.offsetX, layer.offsetY);
160
+ super._collectContent(builder);
161
+ }
165
162
  }
166
163
  destroy() {
167
164
  this._layer._removeStructuralListener(this._onStructuralChange);
@@ -1 +1 @@
1
- {"version":3,"file":"TileLayerNode.js","names":[],"sources":["../../src/TileLayerNode.ts"],"sourcesContent":["import type { ReadonlyRectangle } from '@codexo/exojs';\nimport { Container } from '@codexo/exojs';\nimport { PixelSnapMode, type RenderPlanBuilder } from '@codexo/exojs/renderer-sdk';\n\nimport { aggregateChildLocalBounds } from './nodeBounds';\nimport { assertPixelSnapMode } from './pixelSnap';\nimport type { ReadonlyTileChunk } from './TileChunk';\nimport { TileChunkNode } from './TileChunkNode';\nimport type { ChunkStructuralEvent, TileLayer } from './TileLayer';\n\n/**\n * Options for a {@link TileLayerNode}. All optional; reserved for forward\n * compatibility.\n * @advanced\n */\nexport interface TileLayerNodeOptions {\n /**\n * Whether the layer's chunk nodes participate in per-chunk view culling.\n * Defaults to `true`. Disable only for tiny, always-on-screen layers where\n * the per-chunk bounds test is pure overhead.\n */\n readonly cullable?: boolean;\n}\n\n/**\n * A scene node that renders one generic {@link TileLayer} as a\n * {@link Container} of per-chunk {@link TileChunkNode} drawables.\n *\n * Each non-empty loaded chunk becomes one child positioned at its pixel\n * origin, so the engine's existing per-node culling drops individual chunks and\n * the render-plan optimiser batches them by tileset texture. The layer's pixel\n * `offset` is applied to this node's transform; `visible` and `opacity` are\n * read live from the runtime layer on every frame (no rebuild required).\n *\n * A `parallax` factor other than `1` makes this node's rendered position\n * camera-dependent, resolved per frame in {@link _collectContent} by patching\n * the node position against the camera centre, then restoring it - the cull\n * test runs before that patch, so a bounded layer with parallax would be\n * culled at its static base-offset bounds while actually rendering elsewhere.\n * Such a layer therefore opts out of view culling (`cullable = false`), same\n * as an unbounded layer (exactly like {@link import('./ImageLayerNode').ImageLayerNode}).\n *\n * The node references - but never owns - the {@link TileLayer}: destroying it\n * frees its chunk nodes and their cached geometry but leaves the layer, map,\n * and Loader-owned textures intact.\n *\n * Structural changes made via `_adoptChunk`/`_evictChunk` (chunk streaming)\n * are picked up incrementally as they happen, without a full rebuild.\n * {@link TileLayerNode.refresh} remains available for callers that mutate\n * chunk structure by other means (e.g. a bulk edit that bypasses\n * `_adoptChunk`/`_evictChunk`) and need a full resync. In-place tile edits to\n * existing chunks are picked up automatically via chunk revisions.\n *\n * @advanced\n */\nexport class TileLayerNode extends Container {\n private readonly _layer: TileLayer;\n private readonly _cullChunks: boolean;\n private readonly _chunkNodes: TileChunkNode[] = [];\n private _syncedOpacity = -1;\n private _syncedTint: number | null | undefined = undefined;\n private _pixelSnapMode: PixelSnapMode = PixelSnapMode.None;\n private readonly _baseOffsetX: number;\n private readonly _baseOffsetY: number;\n\n /**\n * Bound once so `TileLayer._addStructuralListener`/`_removeStructuralListener`\n * add and remove the SAME function reference. Incrementally adds/removes\n * the `TileChunkNode` child for exactly the chunk that changed - never\n * triggers a full {@link refresh}, so every other chunk node's\n * revision-cached geometry survives untouched.\n */\n private readonly _onStructuralChange = (event: ChunkStructuralEvent): void => {\n const existingIndex = this._chunkNodes.findIndex(n => n.chunkX === event.cx && n.chunkY === event.cy);\n\n const existing = this._chunkNodes[existingIndex];\n\n if (existing) {\n this._chunkNodes.splice(existingIndex, 1);\n this.removeChild(existing);\n existing.destroy();\n }\n\n if (event.chunk === null || event.chunk.empty) {\n return;\n }\n\n const node = this._createChunkNode(event.chunk);\n\n this._chunkNodes.push(node);\n this.addChild(node);\n this._applyTint(node);\n };\n\n public constructor(layer: TileLayer, options?: TileLayerNodeOptions) {\n super();\n\n this._layer = layer;\n this._cullChunks = options?.cullable ?? true;\n this._baseOffsetX = layer.offsetX;\n this._baseOffsetY = layer.offsetY;\n\n this.setPosition(layer.offsetX, layer.offsetY);\n this._buildChunkNodes();\n\n if (!this._layer.bounded || layer.parallaxX !== 1 || layer.parallaxY !== 1 || layer.parallaxScale !== 1) {\n this.cullable = false;\n }\n\n this._layer._addStructuralListener(this._onStructuralChange);\n }\n\n /** The runtime layer this node renders. */\n public get layer(): TileLayer {\n return this._layer;\n }\n\n /**\n * Render-only pixel-snap mode applied to every chunk node in this layer (and\n * to chunks rebuilt later by {@link refresh}). Each chunk's rendered origin is\n * snapped to the active render target's device-pixel grid; because chunk\n * origins are integer multiples of the integer tile pitch from the same layer\n * origin, the whole grid stays exact and adjacent chunks cannot drift apart.\n *\n * Purely visual: tile data, the layer offset, chunk content revisions, and\n * culling bounds are never changed. `PixelSnapMode.Geometry` and `PixelSnapMode.Position` both resolve\n * to coherent origin snapping for tile chunks (chunk quads are already on the\n * integer pixel grid by construction). Setting the current value is a no-op;\n * an invalid value throws and leaves the prior mode unchanged.\n *\n * @default PixelSnapMode.None\n * @stable\n */\n public get pixelSnapMode(): PixelSnapMode {\n return this._pixelSnapMode;\n }\n\n public set pixelSnapMode(mode: PixelSnapMode) {\n if (mode === this._pixelSnapMode) {\n return;\n }\n\n assertPixelSnapMode(mode);\n this._pixelSnapMode = mode;\n\n for (const chunk of this._chunkNodes) {\n chunk.pixelSnapMode = mode;\n }\n }\n\n /**\n * Rebuild the chunk-node children from the layer's current loaded chunks.\n * Call after structural mutation that creates or empties chunks. In-place\n * tile edits to existing chunks do not need a refresh.\n */\n public refresh(): this {\n const previous = [...this._chunkNodes];\n\n this.removeChildren();\n this._chunkNodes.length = 0;\n\n for (const child of previous) {\n child.destroy();\n }\n\n this._syncedOpacity = -1;\n this._syncedTint = undefined;\n this._buildChunkNodes();\n\n return this;\n }\n\n /** The chunk render nodes owned by this layer node, in build order. @internal */\n public get chunkNodes(): readonly TileChunkNode[] {\n return this._chunkNodes;\n }\n\n /**\n * Recomputed lazily on read, so it writes `_localBounds` directly rather than\n * going through `_setLocalBounds`: an invalidating write inside a getter\n * would re-dirty the node on every read.\n */\n public override getLocalBounds(): ReadonlyRectangle {\n const bounds = this._localBounds;\n\n // Reading the pixel extents directly (rather than gating on `bounded`)\n // is what narrows them to numbers - `bounded` is a plain boolean getter.\n const { pixelHeight, pixelWidth } = this._layer;\n\n if (pixelWidth !== undefined && pixelHeight !== undefined) {\n bounds.set(0, 0, pixelWidth, pixelHeight);\n } else if (this._chunkNodes.length > 0) {\n aggregateChildLocalBounds(this._chunkNodes, bounds);\n }\n\n return bounds;\n }\n\n /** @internal */\n protected override _collectContent(builder: RenderPlanBuilder): void {\n if (!this._layer.visible) {\n return;\n }\n\n this._syncTint();\n\n const layer = this._layer;\n\n const patchesPosition = layer.parallaxX !== 1 || layer.parallaxY !== 1;\n const patchesScale = layer.parallaxScale !== 1;\n\n if (patchesPosition || patchesScale) {\n const camCenter = builder.view.center;\n const prevX = this.x;\n const prevY = this.y;\n const prevScaleX = this.scale.x;\n const prevScaleY = this.scale.y;\n\n if (patchesPosition) {\n this.x = this._baseOffsetX + camCenter.x * (1 - layer.parallaxX);\n this.y = this._baseOffsetY + camCenter.y * (1 - layer.parallaxY);\n }\n\n if (patchesScale) {\n this.setScale(prevScaleX * layer.parallaxScale, prevScaleY * layer.parallaxScale);\n }\n\n try {\n super._collectContent(builder);\n } finally {\n if (patchesPosition) {\n this.setPosition(prevX, prevY);\n }\n\n if (patchesScale) {\n this.setScale(prevScaleX, prevScaleY);\n }\n }\n } else {\n super._collectContent(builder);\n }\n }\n\n public override destroy(): void {\n this._layer._removeStructuralListener(this._onStructuralChange);\n\n const children = [...this._chunkNodes];\n\n this._chunkNodes.length = 0;\n\n super.destroy();\n\n for (const child of children) {\n child.destroy();\n }\n }\n\n private _buildChunkNodes(): void {\n const layer = this._layer;\n\n for (const chunk of layer.loadedChunks()) {\n if (chunk.empty) {\n continue;\n }\n\n const node = this._createChunkNode(chunk);\n\n this._chunkNodes.push(node);\n this.addChild(node);\n }\n\n this._syncTint();\n }\n\n /**\n * Construct one configured {@link TileChunkNode} for `chunk` - shared by\n * the initial bulk build ({@link _buildChunkNodes}) and the incremental\n * structural-listener handler, so a future constructor argument or\n * per-node setting only needs to be added in one place.\n */\n private _createChunkNode(chunk: ReadonlyTileChunk): TileChunkNode {\n const layer = this._layer;\n const node = new TileChunkNode(chunk, layer.tilesets, layer.tileWidth, layer.tileHeight, layer.chunkWidth, layer.chunkHeight);\n\n node.cullable = this._cullChunks;\n\n if (this._pixelSnapMode !== PixelSnapMode.None) {\n node.pixelSnapMode = this._pixelSnapMode;\n }\n\n return node;\n }\n\n /**\n * Compute and apply this layer's live tint (opacity as alpha, `tintColor`\n * as RGB multiply) to a single chunk node. Used both by {@link _syncTint}'s\n * bulk pass and by the structural-listener handler for a freshly-added\n * node - a node added between two \"nothing changed\" full syncs must still\n * receive the current tint, which a change-detection-guarded bulk pass\n * alone would skip.\n */\n private _applyTint(node: TileChunkNode): void {\n const tintColor = this._layer.tintColor;\n const r = tintColor === null ? 255 : (tintColor >> 16) & 0xff;\n const g = tintColor === null ? 255 : (tintColor >> 8) & 0xff;\n const b = tintColor === null ? 255 : tintColor & 0xff;\n node.tint.set(r, g, b, this._layer.opacity);\n }\n\n /**\n * Propagate the layer's live opacity and tint colour onto every chunk\n * render tint if either changed since the last call. Opacity drives the\n * tint alpha; `tintColor` (`0xRRGGBB`) multiplies the RGB (white = no tint).\n */\n private _syncTint(): void {\n const opacity = this._layer.opacity;\n const tintColor = this._layer.tintColor;\n\n if (opacity === this._syncedOpacity && tintColor === this._syncedTint) {\n return;\n }\n\n for (const child of this._chunkNodes) {\n this._applyTint(child);\n }\n\n this._syncedOpacity = opacity;\n this._syncedTint = tintColor;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,IAAa,gB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EACtB,KAAK,cAAc;CACrB;AACF"}
1
+ {"version":3,"file":"TileLayerNode.js","names":[],"sources":["../../src/TileLayerNode.ts"],"sourcesContent":["import type { ReadonlyRectangle } from '@codexo/exojs';\nimport { Container } from '@codexo/exojs';\nimport { PixelSnapMode, type RenderPlanBuilder } from '@codexo/exojs/renderer-sdk';\n\nimport { aggregateChildLocalBounds } from './nodeBounds';\nimport { assertPixelSnapMode } from './pixelSnap';\nimport type { ReadonlyTileChunk } from './TileChunk';\nimport { TileChunkNode } from './TileChunkNode';\nimport type { ChunkStructuralEvent, TileLayer } from './TileLayer';\n\n/**\n * Options for a {@link TileLayerNode}. All optional; reserved for forward\n * compatibility.\n * @advanced\n */\nexport interface TileLayerNodeOptions {\n /**\n * Whether the layer's chunk nodes participate in per-chunk view culling.\n * Defaults to `true`. Disable only for tiny, always-on-screen layers where\n * the per-chunk bounds test is pure overhead.\n */\n readonly cullable?: boolean;\n}\n\n/**\n * A scene node that renders one generic {@link TileLayer} as a\n * {@link Container} of per-chunk {@link TileChunkNode} drawables.\n *\n * Each non-empty loaded chunk becomes one child positioned at its pixel\n * origin, so the engine's existing per-node culling drops individual chunks and\n * the render-plan optimiser batches them by tileset texture. The layer's pixel\n * `offset`, `visible` and `opacity` are all read live from the runtime layer on\n * every frame (no rebuild required).\n *\n * A `parallax` factor other than `1` makes this node's rendered position\n * camera-dependent, resolved per frame in {@link _collectContent} by patching\n * the node position against the camera centre, then restoring it - the cull\n * test runs before that patch, so a bounded layer with parallax would be\n * culled at its static base-offset bounds while actually rendering elsewhere.\n * Such a layer therefore opts out of view culling (`cullable = false`), same\n * as an unbounded layer (exactly like {@link import('./ImageLayerNode').ImageLayerNode}).\n *\n * The node references - but never owns - the {@link TileLayer}: destroying it\n * frees its chunk nodes and their cached geometry but leaves the layer, map,\n * and Loader-owned textures intact.\n *\n * Structural changes made via `_adoptChunk`/`_evictChunk` (chunk streaming)\n * are picked up incrementally as they happen, without a full rebuild.\n * {@link TileLayerNode.refresh} remains available for callers that mutate\n * chunk structure by other means (e.g. a bulk edit that bypasses\n * `_adoptChunk`/`_evictChunk`) and need a full resync. In-place tile edits to\n * existing chunks are picked up automatically via chunk revisions.\n *\n * @advanced\n */\nexport class TileLayerNode extends Container {\n private readonly _layer: TileLayer;\n private readonly _cullChunks: boolean;\n private readonly _chunkNodes: TileChunkNode[] = [];\n private _syncedOpacity = -1;\n private _syncedTint: number | null | undefined = undefined;\n private _pixelSnapMode: PixelSnapMode = PixelSnapMode.None;\n\n /**\n * Bound once so `TileLayer._addStructuralListener`/`_removeStructuralListener`\n * add and remove the SAME function reference. Incrementally adds/removes\n * the `TileChunkNode` child for exactly the chunk that changed - never\n * triggers a full {@link refresh}, so every other chunk node's\n * revision-cached geometry survives untouched.\n */\n private readonly _onStructuralChange = (event: ChunkStructuralEvent): void => {\n const existingIndex = this._chunkNodes.findIndex(n => n.chunkX === event.cx && n.chunkY === event.cy);\n\n const existing = this._chunkNodes[existingIndex];\n\n if (existing) {\n this._chunkNodes.splice(existingIndex, 1);\n this.removeChild(existing);\n existing.destroy();\n }\n\n if (event.chunk === null || event.chunk.empty) {\n return;\n }\n\n const node = this._createChunkNode(event.chunk);\n\n this._chunkNodes.push(node);\n this.addChild(node);\n this._applyTint(node);\n };\n\n public constructor(layer: TileLayer, options?: TileLayerNodeOptions) {\n super();\n\n this._layer = layer;\n this._cullChunks = options?.cullable ?? true;\n\n this.setPosition(layer.offsetX, layer.offsetY);\n this._buildChunkNodes();\n\n if (!this._layer.bounded || layer.parallaxX !== 1 || layer.parallaxY !== 1 || layer.parallaxScale !== 1) {\n this.cullable = false;\n }\n\n this._layer._addStructuralListener(this._onStructuralChange);\n }\n\n /** The runtime layer this node renders. */\n public get layer(): TileLayer {\n return this._layer;\n }\n\n /**\n * Render-only pixel-snap mode applied to every chunk node in this layer (and\n * to chunks rebuilt later by {@link refresh}). Each chunk's rendered origin is\n * snapped to the active render target's device-pixel grid; because chunk\n * origins are integer multiples of the integer tile pitch from the same layer\n * origin, the whole grid stays exact and adjacent chunks cannot drift apart.\n *\n * Purely visual: tile data, the layer offset, chunk content revisions, and\n * culling bounds are never changed. `PixelSnapMode.Geometry` and `PixelSnapMode.Position` both resolve\n * to coherent origin snapping for tile chunks (chunk quads are already on the\n * integer pixel grid by construction). Setting the current value is a no-op;\n * an invalid value throws and leaves the prior mode unchanged.\n *\n * @default PixelSnapMode.None\n * @stable\n */\n public get pixelSnapMode(): PixelSnapMode {\n return this._pixelSnapMode;\n }\n\n public set pixelSnapMode(mode: PixelSnapMode) {\n if (mode === this._pixelSnapMode) {\n return;\n }\n\n assertPixelSnapMode(mode);\n this._pixelSnapMode = mode;\n\n for (const chunk of this._chunkNodes) {\n chunk.pixelSnapMode = mode;\n }\n }\n\n /**\n * Rebuild the chunk-node children from the layer's current loaded chunks.\n * Call after structural mutation that creates or empties chunks. In-place\n * tile edits to existing chunks do not need a refresh.\n */\n public refresh(): this {\n const previous = [...this._chunkNodes];\n\n this.removeChildren();\n this._chunkNodes.length = 0;\n\n for (const child of previous) {\n child.destroy();\n }\n\n this._syncedOpacity = -1;\n this._syncedTint = undefined;\n this._buildChunkNodes();\n\n return this;\n }\n\n /** The chunk render nodes owned by this layer node, in build order. @internal */\n public get chunkNodes(): readonly TileChunkNode[] {\n return this._chunkNodes;\n }\n\n /**\n * Recomputed lazily on read, so it writes `_localBounds` directly rather than\n * going through `_setLocalBounds`: an invalidating write inside a getter\n * would re-dirty the node on every read.\n */\n public override getLocalBounds(): ReadonlyRectangle {\n const bounds = this._localBounds;\n\n // Reading the pixel extents directly (rather than gating on `bounded`)\n // is what narrows them to numbers - `bounded` is a plain boolean getter.\n const { pixelHeight, pixelWidth } = this._layer;\n\n if (pixelWidth !== undefined && pixelHeight !== undefined) {\n bounds.set(0, 0, pixelWidth, pixelHeight);\n } else if (this._chunkNodes.length > 0) {\n aggregateChildLocalBounds(this._chunkNodes, bounds);\n }\n\n return bounds;\n }\n\n /** @internal */\n protected override _collectContent(builder: RenderPlanBuilder): void {\n if (!this._layer.visible) {\n return;\n }\n\n this._syncTint();\n\n const layer = this._layer;\n\n const patchesPosition = layer.parallaxX !== 1 || layer.parallaxY !== 1;\n const patchesScale = layer.parallaxScale !== 1;\n\n // `offsetX`/`offsetY` are live, mutable fields (`TileColliderStreamer` and\n // `pixelToTile` already read them per call) - re-read here every frame so a\n // runtime-moved layer's rendering follows its collision rather than freezing\n // at the position it had when this node was constructed.\n if (patchesPosition || patchesScale) {\n const camCenter = builder.view.center;\n const prevScaleX = this.scale.x;\n const prevScaleY = this.scale.y;\n\n if (patchesPosition) {\n this.x = layer.offsetX + camCenter.x * (1 - layer.parallaxX);\n this.y = layer.offsetY + camCenter.y * (1 - layer.parallaxY);\n } else {\n this.setPosition(layer.offsetX, layer.offsetY);\n }\n\n if (patchesScale) {\n this.setScale(prevScaleX * layer.parallaxScale, prevScaleY * layer.parallaxScale);\n }\n\n try {\n super._collectContent(builder);\n } finally {\n if (patchesPosition) {\n this.setPosition(layer.offsetX, layer.offsetY);\n }\n\n if (patchesScale) {\n this.setScale(prevScaleX, prevScaleY);\n }\n }\n } else {\n this.setPosition(layer.offsetX, layer.offsetY);\n super._collectContent(builder);\n }\n }\n\n public override destroy(): void {\n this._layer._removeStructuralListener(this._onStructuralChange);\n\n const children = [...this._chunkNodes];\n\n this._chunkNodes.length = 0;\n\n super.destroy();\n\n for (const child of children) {\n child.destroy();\n }\n }\n\n private _buildChunkNodes(): void {\n const layer = this._layer;\n\n for (const chunk of layer.loadedChunks()) {\n if (chunk.empty) {\n continue;\n }\n\n const node = this._createChunkNode(chunk);\n\n this._chunkNodes.push(node);\n this.addChild(node);\n }\n\n this._syncTint();\n }\n\n /**\n * Construct one configured {@link TileChunkNode} for `chunk` - shared by\n * the initial bulk build ({@link _buildChunkNodes}) and the incremental\n * structural-listener handler, so a future constructor argument or\n * per-node setting only needs to be added in one place.\n */\n private _createChunkNode(chunk: ReadonlyTileChunk): TileChunkNode {\n const layer = this._layer;\n const node = new TileChunkNode(chunk, layer.tilesets, layer.tileWidth, layer.tileHeight, layer.chunkWidth, layer.chunkHeight);\n\n node.cullable = this._cullChunks;\n\n if (this._pixelSnapMode !== PixelSnapMode.None) {\n node.pixelSnapMode = this._pixelSnapMode;\n }\n\n return node;\n }\n\n /**\n * Compute and apply this layer's live tint (opacity as alpha, `tintColor`\n * as RGB multiply) to a single chunk node. Used both by {@link _syncTint}'s\n * bulk pass and by the structural-listener handler for a freshly-added\n * node - a node added between two \"nothing changed\" full syncs must still\n * receive the current tint, which a change-detection-guarded bulk pass\n * alone would skip.\n */\n private _applyTint(node: TileChunkNode): void {\n const tintColor = this._layer.tintColor;\n const r = tintColor === null ? 255 : (tintColor >> 16) & 0xff;\n const g = tintColor === null ? 255 : (tintColor >> 8) & 0xff;\n const b = tintColor === null ? 255 : tintColor & 0xff;\n node.tint.set(r, g, b, this._layer.opacity);\n }\n\n /**\n * Propagate the layer's live opacity and tint colour onto every chunk\n * render tint if either changed since the last call. Opacity drives the\n * tint alpha; `tintColor` (`0xRRGGBB`) multiplies the RGB (white = no tint).\n */\n private _syncTint(): void {\n const opacity = this._layer.opacity;\n const tintColor = this._layer.tintColor;\n\n if (opacity === this._syncedOpacity && tintColor === this._syncedTint) {\n return;\n }\n\n for (const child of this._chunkNodes) {\n this._applyTint(child);\n }\n\n this._syncedOpacity = opacity;\n this._syncedTint = tintColor;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,IAAa,gBAAb,cAAmC,UAAU;CAC3C,AAAiB;CACjB,AAAiB;CACjB,AAAiB,cAA+B,CAAC;CACjD,AAAQ,iBAAiB;CACzB,AAAQ,cAAyC;CACjD,AAAQ,iBAAgC,cAAc;;;;;;;;CAStD,AAAiB,uBAAuB,UAAsC;EAC5E,MAAM,gBAAgB,KAAK,YAAY,WAAU,MAAK,EAAE,WAAW,MAAM,MAAM,EAAE,WAAW,MAAM,EAAE;EAEpG,MAAM,WAAW,KAAK,Y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AAM,aAAa,GAAG;GACxC,IAAI,MAAM,OACR;GAGF,MAAM,OAAO,KAAK,iBAAiB,KAAK;GAExC,KAAK,YAAY,KAAK,IAAI;GAC1B,KAAK,SAAS,IAAI;EACpB;EAEA,KAAK,UAAU;CACjB;;;;;;;CAQA,AAAQ,iBAAiB,OAAyC;EAChE,MAAM,QAAQ,KAAK;EACnB,MAAM,OAAO,IAAI,cAAc,OAAO,MAAM,UAAU,MAAM,WAAW,MAAM,YAAY,MAAM,YAAY,MAAM,WAAW;EAE5H,KAAK,WAAW,KAAK;EAErB,IAAI,KAAK,mBAAmB,cAAc,MACxC,KAAK,gBAAgB,KAAK;EAG5B,OAAO;CACT;;;;;;;;;CAUA,AAAQ,WAAW,MAA2B;EAC5C,MAAM,YAAY,KAAK,OAAO;EAC9B,MAAM,IAAI,cAAc,OAAO,MAAO,aAAa,KAAM;EACzD,MAAM,IAAI,cAAc,OAAO,MAAO,aAAa,IAAK;EACxD,MAAM,IAAI,cAAc,OAAO,MAAM,YAAY;EACjD,KAAK,KAAK,IAAI,GAAG,GAAG,GAAG,KAAK,OAAO,OAAO;CAC5C;;;;;;CAOA,AAAQ,YAAkB;EACxB,MAAM,UAAU,KAAK,OAAO;EAC5B,MAAM,YAAY,KAAK,OAAO;EAE9B,IAAI,YAAY,KAAK,kBAAkB,cAAc,KAAK,aACxD;EAGF,KAAK,MAAM,SAAS,KAAK,aACvB,KAAK,WAAW,KAAK;EAGvB,KAAK,iBAAiB;EACtB,KAAK,cAAc;CACrB;AACF"}
@@ -86,7 +86,9 @@ export declare class TileSet {
86
86
  /**
87
87
  * Build definitions from an array, replacing the internal definitions map.
88
88
  * Each entry's properties are copied and frozen.
89
- * @internal
89
+ *
90
+ * Part of the tilemap SDK contract for extension packages that build
91
+ * tilesets programmatically.
90
92
  */
91
93
  _setDefinitions(definitions: readonly TileDefinition[]): void;
92
94
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"TileSet.d.ts","sourceRoot":"","sources":["../../src/Tile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MAAM,CAAC;IAE/B,+DAA+D;IAC/D,SAAgB,KAAK,EAAE,MAAM,CAAC;IAC9B;;;;;;;;OAQG;IACH,SAAgB,OAAO,EAAE,MAAM,CAAC;IAChC,yGAAyG;IACzG,SAAgB,OAAO,EAAE,MAAM,CAAC;IAEhC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAsC;IAEnE;;OAEG;gBACgB,OAAO,EAAE,cAAc;IAoE1C;;;;OAIG;IACI,cAAc,CAAC,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,IAAI;IAerF;;;;;;OAMG;IACI,eAAe,CAAC,WAAW,EAAE,SAAS,cAAc,EAAE,GAAG,IAAI;IAgBpE;;;OAGG;IACI,iBAAiB,CAAC,WAAW,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS;IAIzE;;;;OAIG;IACI,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG;QAAE,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE;IAchG;;;OAGG;IACI,YAAY,IAAI,gBAAgB,CAAC,cAAc,CAAC;IAIvD;;;;OAIG;IACH,IAAW,cAAc,IAAI,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,GAAG,SAAS,CAAC,CAAC,CAMhF;CACF"}
@@ -102,7 +102,9 @@ var TileSet = class {
102
102
  /**
103
103
  * Build definitions from an array, replacing the internal definitions map.
104
104
  * Each entry's properties are copied and frozen.
105
- * @internal
105
+ *
106
+ * Part of the tilemap SDK contract for extension packages that build
107
+ * tilesets programmatically.
106
108
  */
107
109
  _setDefinitions(definitions) {
108
110
  const map = this._definitions;
@@ -1 +1 @@
1
- {"version":3,"file":"TileSet.js","names":[],"sources":["../../src/TileSet.ts"],"sourcesContent":["import type { TextureRegion } from '@codexo/exojs';\n\nimport type { TileDefinition, TileProperties } from './types';\nimport { validateNonNegativeInteger, validatePositiveInteger } from './types';\n\n/**\n * Options for constructing a {@link TileSet}.\n * @advanced\n */\nexport interface TileSetOptions {\n /** Stable runtime name (unique within a {@link TileMap}). */\n readonly name: string;\n /** Texture atlas for this tileset. Textures are Loader-owned. */\n readonly texture: TextureRegion;\n /** Width of each tile in pixels. */\n readonly tileWidth: number;\n /** Height of each tile in pixels. */\n readonly tileHeight: number;\n /** Total number of tiles in this tileset. */\n readonly tileCount: number;\n /** Number of tile columns in the atlas grid. Computed from texture width / tileWidth if omitted. */\n readonly columns?: number;\n /** Pixel spacing between tiles in the atlas. Defaults to 0. */\n readonly spacing?: number;\n /** Pixel margin around the atlas. Defaults to 0. */\n readonly margin?: number;\n /** Tileset class/type string (Tiled `class`). Defaults to `''`. */\n readonly class?: string;\n /** Visual drawing offset in pixels applied to every tile of this set drawn by a tile layer. Defaults to 0. */\n readonly offsetX?: number;\n /** Visual drawing offset in pixels applied to every tile of this set drawn by a tile layer. Defaults to 0. */\n readonly offsetY?: number;\n}\n\n/**\n * A resolved tileset: a uniform grid of tiles within a texture atlas.\n *\n * Does **not** own its texture - the Loader or application code retains\n * texture ownership. Tileset dimensions are validated at construction and\n * frozen thereafter.\n *\n * Multiple tilesets are supported per {@link TileMap}; each carries its own\n * tile dimensions, spacing, and optional per-tile metadata.\n * @advanced\n */\nexport class TileSet {\n /** Stable runtime name. */\n public readonly name: string;\n\n /** Atlas texture region - Loader-owned, never destroyed by the tileset. */\n public readonly texture: TextureRegion;\n\n /** Tile width in pixels. */\n public readonly tileWidth: number;\n /** Tile height in pixels. */\n public readonly tileHeight: number;\n\n /** Total number of tiles in the tileset. */\n public readonly tileCount: number;\n\n /** Number of columns in the atlas grid. */\n public readonly columns: number;\n /** Number of rows implied by tileCount and columns. */\n public readonly rows: number;\n\n /** Pixel spacing between tiles in the atlas. */\n public readonly spacing: number;\n /** Pixel margin around the atlas. */\n public readonly margin: number;\n\n /** Tileset class/type string (Tiled `class`; may be empty). */\n public readonly class: string;\n /**\n * Visual drawing offset X in pixels (Tiled `tileoffset`).\n *\n * Applied by the tile-layer geometry builder and by the tile-collision\n * helpers - i.e. wherever this package places a tile on a grid. It is **not**\n * folded into a {@link TileObject}'s `x`/`y`: object layers are data-only, so\n * code that draws a tile object itself has to add this offset the way a tile\n * layer would.\n */\n public readonly offsetX: number;\n /** Visual drawing offset Y in pixels (Tiled `tileoffset`) - see {@link offsetX} for where it applies. */\n public readonly offsetY: number;\n\n private readonly _definitions: ReadonlyMap<number, TileDefinition>;\n\n /**\n * @throws When dimensions, counts, or spacing values are invalid.\n */\n public constructor(options: TileSetOptions) {\n if (!options.name || typeof options.name !== 'string') {\n throw new Error('TileSet name must be a non-empty string.');\n }\n\n if (!options.texture) {\n throw new Error('TileSet requires a valid TextureRegion.');\n }\n\n validatePositiveInteger(options.tileWidth, 'tileWidth');\n validatePositiveInteger(options.tileHeight, 'tileHeight');\n validatePositiveInteger(options.tileCount, 'tileCount');\n\n const spacing = options.spacing ?? 0;\n const margin = options.margin ?? 0;\n validateNonNegativeInteger(spacing, 'spacing');\n validateNonNegativeInteger(margin, 'margin');\n\n // A tile grid is derived from the atlas dimensions and then fixed, so it\n // cannot be built against a texture that has not loaded yet - and the\n // dimension checks below would otherwise report the resulting zeros as a\n // bad tile size rather than as the real cause.\n if (options.texture.width <= 0 || options.texture.height <= 0) {\n throw new Error(\n `TileSet needs a loaded texture to derive its grid, but \"${options.name}\" was given one measuring ` +\n `${options.texture.width}x${options.texture.height}. Await it (loader.load(...) or texture.loaded) before constructing the tile set.`,\n );\n }\n\n const atlasWidth = options.texture.width - margin * 2;\n const atlasHeight = options.texture.height - margin * 2;\n\n const columns = options.columns ?? Math.floor(atlasWidth / options.tileWidth);\n\n validatePositiveInteger(columns, 'columns');\n if (columns <= 0) {\n throw new Error(`TileSet columns must be positive (got ${columns}).`);\n }\n\n if (options.tileWidth * columns + spacing * (columns - 1) > atlasWidth) {\n throw new Error(`TileSet grid width exceeds atlas: ${options.tileWidth}*${columns}` + ` + ${spacing}*${columns - 1} > ${atlasWidth}.`);\n }\n\n const rows = Math.ceil(options.tileCount / columns);\n if (rows > 0 && options.tileHeight * rows + spacing * (rows - 1) > atlasHeight) {\n throw new Error(`TileSet grid height exceeds atlas: ${options.tileHeight}*${rows}` + ` + ${spacing}*${rows - 1} > ${atlasHeight}.`);\n }\n\n this.name = options.name;\n this.texture = options.texture;\n this.tileWidth = options.tileWidth;\n this.tileHeight = options.tileHeight;\n this.tileCount = options.tileCount;\n this.columns = columns;\n this.rows = rows;\n this.spacing = spacing;\n this.margin = margin;\n this.class = options.class ?? '';\n this.offsetX = options.offsetX ?? 0;\n this.offsetY = options.offsetY ?? 0;\n\n this._definitions = new Map();\n\n if (__DEV__) {\n Object.freeze(this);\n }\n }\n\n /**\n * Set per-tile metadata for a local tile ID.\n * Copies input to prevent caller-owned mutation leaking into the tileset.\n * @internal\n */\n public _setDefinition(localTileId: number, definition: Partial<TileDefinition>): void {\n if (localTileId < 0 || localTileId >= this.tileCount) {\n throw new Error(`Tile definition localTileId ${localTileId} out of range [0, ${this.tileCount - 1}].`);\n }\n const props = definition.properties ? Object.freeze({ ...definition.properties }) : undefined;\n const animation = definition.animation ? Object.freeze(definition.animation.map(frame => Object.freeze({ ...frame }))) : undefined;\n const collision = definition.collision ? Object.freeze([...definition.collision]) : undefined;\n (this._definitions as Map<number, TileDefinition>).set(localTileId, {\n localTileId,\n ...(props !== undefined && { properties: props }),\n ...(animation !== undefined && { animation }),\n ...(collision !== undefined && { collision }),\n });\n }\n\n /**\n * Build definitions from an array, replacing the internal definitions map.\n * Each entry's properties are copied and frozen.\n * @internal\n */\n public _setDefinitions(definitions: readonly TileDefinition[]): void {\n const map = this._definitions as Map<number, TileDefinition>;\n map.clear();\n for (const def of definitions) {\n const props = def.properties ? Object.freeze({ ...def.properties }) : undefined;\n const animation = def.animation ? Object.freeze(def.animation.map(frame => Object.freeze({ ...frame }))) : undefined;\n const collision = def.collision ? Object.freeze([...def.collision]) : undefined;\n map.set(def.localTileId, {\n localTileId: def.localTileId,\n ...(props !== undefined && { properties: props }),\n ...(animation !== undefined && { animation }),\n ...(collision !== undefined && { collision }),\n });\n }\n }\n\n /**\n * Retrieve per-tile metadata, or undefined if none defined.\n * @advanced\n */\n public getTileDefinition(localTileId: number): TileDefinition | undefined {\n return this._definitions.get(localTileId);\n }\n\n /**\n * Compute the pixel-space source rectangle for a local tile ID\n * within the atlas, accounting for columns, spacing, and margin.\n * @advanced\n */\n public getTileRect(localTileId: number): { x: number; y: number; width: number; height: number } {\n if (localTileId < 0 || localTileId >= this.tileCount) {\n throw new Error(`getTileRect: localTileId ${localTileId} out of range [0, ${this.tileCount - 1}].`);\n }\n const col = localTileId % this.columns;\n const row = Math.floor(localTileId / this.columns);\n return {\n x: this.margin + col * (this.tileWidth + this.spacing),\n y: this.margin + row * (this.tileHeight + this.spacing),\n width: this.tileWidth,\n height: this.tileHeight,\n };\n }\n\n /**\n * Iterate over all defined tiles (sparse).\n * @advanced\n */\n public definedTiles(): IterableIterator<TileDefinition> {\n return this._definitions.values();\n }\n\n /**\n * Read-only snapshot of all per-tile definitions.\n * The returned record is a caller-owned copy.\n * @advanced\n */\n public get allDefinitions(): Readonly<Record<number, TileProperties | undefined>> {\n const result: Record<number, TileProperties | undefined> = {};\n for (const [id, def] of this._definitions) {\n result[id] = def.properties;\n }\n return Object.freeze(result);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA6CA,IAAa,UAAb,MAAqB;;CAEnB,AAAgB;;CAGhB,AAAgB;;CAGhB,AAAgB;;CAEhB,AAAgB;;CAGhB,AAAgB;;CAGhB,AAAgB;;CAEhB,AAAgB;;CAGhB,AAAgB;;CAEhB,AAAgB;;CAGhB,AAAgB;;;;;;;;;;CAUhB,AAAgB;;CAEhB,AAAgB;CAEhB,AAAiB;;;;CAKjB,AAAO,YAAY,SAAyB;EAC1C,IAAI,CAAC,QAAQ,QAAQ,OAAO,QAAQ,SAAS,UAC3C,MAAM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U,UAAa,EAAE,YAAY,MAAM;IAC/C,GAAI,cAAc,UAAa,EAAE,UAAU;IAC3C,GAAI,cAAc,UAAa,EAAE,UAAU;GAC7C,CAAC;EACH;CACF;;;;;CAMA,AAAO,kBAAkB,aAAiD;EACxE,OAAO,KAAK,aAAa,IAAI,WAAW;CAC1C;;;;;;CAOA,AAAO,YAAY,aAA8E;EAC/F,IAAI,cAAc,KAAK,eAAe,KAAK,WACzC,MAAM,IAAI,MAAM,4BAA4B,YAAY,oBAAoB,KAAK,YAAY,EAAE,GAAG;EAEpG,MAAM,MAAM,cAAc,KAAK;EAC/B,MAAM,MAAM,KAAK,MAAM,cAAc,KAAK,OAAO;EACjD,OAAO;GACL,GAAG,KAAK,SAAS,OAAO,KAAK,YAAY,KAAK;GAC9C,GAAG,KAAK,SAAS,OAAO,KAAK,aAAa,KAAK;GAC/C,OAAO,KAAK;GACZ,QAAQ,KAAK;EACf;CACF;;;;;CAMA,AAAO,eAAiD;EACtD,OAAO,KAAK,aAAa,OAAO;CAClC;;;;;;CAOA,IAAW,iBAAuE;EAChF,MAAM,SAAqD,CAAC;EAC5D,KAAK,MAAM,CAAC,IAAI,QAAQ,KAAK,cAC3B,OAAO,MAAM,IAAI;EAEnB,OAAO,OAAO,OAAO,MAAM;CAC7B;AACF"}
1
+ {"version":3,"file":"TileSet.js","names":[],"sources":["../../src/TileSet.ts"],"sourcesContent":["import type { TextureRegion } from '@codexo/exojs';\n\nimport type { TileDefinition, TileProperties } from './types';\nimport { validateNonNegativeInteger, validatePositiveInteger } from './types';\n\n/**\n * Options for constructing a {@link TileSet}.\n * @advanced\n */\nexport interface TileSetOptions {\n /** Stable runtime name (unique within a {@link TileMap}). */\n readonly name: string;\n /** Texture atlas for this tileset. Textures are Loader-owned. */\n readonly texture: TextureRegion;\n /** Width of each tile in pixels. */\n readonly tileWidth: number;\n /** Height of each tile in pixels. */\n readonly tileHeight: number;\n /** Total number of tiles in this tileset. */\n readonly tileCount: number;\n /** Number of tile columns in the atlas grid. Computed from texture width / tileWidth if omitted. */\n readonly columns?: number;\n /** Pixel spacing between tiles in the atlas. Defaults to 0. */\n readonly spacing?: number;\n /** Pixel margin around the atlas. Defaults to 0. */\n readonly margin?: number;\n /** Tileset class/type string (Tiled `class`). Defaults to `''`. */\n readonly class?: string;\n /** Visual drawing offset in pixels applied to every tile of this set drawn by a tile layer. Defaults to 0. */\n readonly offsetX?: number;\n /** Visual drawing offset in pixels applied to every tile of this set drawn by a tile layer. Defaults to 0. */\n readonly offsetY?: number;\n}\n\n/**\n * A resolved tileset: a uniform grid of tiles within a texture atlas.\n *\n * Does **not** own its texture - the Loader or application code retains\n * texture ownership. Tileset dimensions are validated at construction and\n * frozen thereafter.\n *\n * Multiple tilesets are supported per {@link TileMap}; each carries its own\n * tile dimensions, spacing, and optional per-tile metadata.\n * @advanced\n */\nexport class TileSet {\n /** Stable runtime name. */\n public readonly name: string;\n\n /** Atlas texture region - Loader-owned, never destroyed by the tileset. */\n public readonly texture: TextureRegion;\n\n /** Tile width in pixels. */\n public readonly tileWidth: number;\n /** Tile height in pixels. */\n public readonly tileHeight: number;\n\n /** Total number of tiles in the tileset. */\n public readonly tileCount: number;\n\n /** Number of columns in the atlas grid. */\n public readonly columns: number;\n /** Number of rows implied by tileCount and columns. */\n public readonly rows: number;\n\n /** Pixel spacing between tiles in the atlas. */\n public readonly spacing: number;\n /** Pixel margin around the atlas. */\n public readonly margin: number;\n\n /** Tileset class/type string (Tiled `class`; may be empty). */\n public readonly class: string;\n /**\n * Visual drawing offset X in pixels (Tiled `tileoffset`).\n *\n * Applied by the tile-layer geometry builder and by the tile-collision\n * helpers - i.e. wherever this package places a tile on a grid. It is **not**\n * folded into a {@link TileObject}'s `x`/`y`: object layers are data-only, so\n * code that draws a tile object itself has to add this offset the way a tile\n * layer would.\n */\n public readonly offsetX: number;\n /** Visual drawing offset Y in pixels (Tiled `tileoffset`) - see {@link offsetX} for where it applies. */\n public readonly offsetY: number;\n\n private readonly _definitions: ReadonlyMap<number, TileDefinition>;\n\n /**\n * @throws When dimensions, counts, or spacing values are invalid.\n */\n public constructor(options: TileSetOptions) {\n if (!options.name || typeof options.name !== 'string') {\n throw new Error('TileSet name must be a non-empty string.');\n }\n\n if (!options.texture) {\n throw new Error('TileSet requires a valid TextureRegion.');\n }\n\n validatePositiveInteger(options.tileWidth, 'tileWidth');\n validatePositiveInteger(options.tileHeight, 'tileHeight');\n validatePositiveInteger(options.tileCount, 'tileCount');\n\n const spacing = options.spacing ?? 0;\n const margin = options.margin ?? 0;\n validateNonNegativeInteger(spacing, 'spacing');\n validateNonNegativeInteger(margin, 'margin');\n\n // A tile grid is derived from the atlas dimensions and then fixed, so it\n // cannot be built against a texture that has not loaded yet - and the\n // dimension checks below would otherwise report the resulting zeros as a\n // bad tile size rather than as the real cause.\n if (options.texture.width <= 0 || options.texture.height <= 0) {\n throw new Error(\n `TileSet needs a loaded texture to derive its grid, but \"${options.name}\" was given one measuring ` +\n `${options.texture.width}x${options.texture.height}. Await it (loader.load(...) or texture.loaded) before constructing the tile set.`,\n );\n }\n\n const atlasWidth = options.texture.width - margin * 2;\n const atlasHeight = options.texture.height - margin * 2;\n\n const columns = options.columns ?? Math.floor(atlasWidth / options.tileWidth);\n\n validatePositiveInteger(columns, 'columns');\n if (columns <= 0) {\n throw new Error(`TileSet columns must be positive (got ${columns}).`);\n }\n\n if (options.tileWidth * columns + spacing * (columns - 1) > atlasWidth) {\n throw new Error(`TileSet grid width exceeds atlas: ${options.tileWidth}*${columns}` + ` + ${spacing}*${columns - 1} > ${atlasWidth}.`);\n }\n\n const rows = Math.ceil(options.tileCount / columns);\n if (rows > 0 && options.tileHeight * rows + spacing * (rows - 1) > atlasHeight) {\n throw new Error(`TileSet grid height exceeds atlas: ${options.tileHeight}*${rows}` + ` + ${spacing}*${rows - 1} > ${atlasHeight}.`);\n }\n\n this.name = options.name;\n this.texture = options.texture;\n this.tileWidth = options.tileWidth;\n this.tileHeight = options.tileHeight;\n this.tileCount = options.tileCount;\n this.columns = columns;\n this.rows = rows;\n this.spacing = spacing;\n this.margin = margin;\n this.class = options.class ?? '';\n this.offsetX = options.offsetX ?? 0;\n this.offsetY = options.offsetY ?? 0;\n\n this._definitions = new Map();\n\n if (__DEV__) {\n Object.freeze(this);\n }\n }\n\n /**\n * Set per-tile metadata for a local tile ID.\n * Copies input to prevent caller-owned mutation leaking into the tileset.\n * @internal\n */\n public _setDefinition(localTileId: number, definition: Partial<TileDefinition>): void {\n if (localTileId < 0 || localTileId >= this.tileCount) {\n throw new Error(`Tile definition localTileId ${localTileId} out of range [0, ${this.tileCount - 1}].`);\n }\n const props = definition.properties ? Object.freeze({ ...definition.properties }) : undefined;\n const animation = definition.animation ? Object.freeze(definition.animation.map(frame => Object.freeze({ ...frame }))) : undefined;\n const collision = definition.collision ? Object.freeze([...definition.collision]) : undefined;\n (this._definitions as Map<number, TileDefinition>).set(localTileId, {\n localTileId,\n ...(props !== undefined && { properties: props }),\n ...(animation !== undefined && { animation }),\n ...(collision !== undefined && { collision }),\n });\n }\n\n /**\n * Build definitions from an array, replacing the internal definitions map.\n * Each entry's properties are copied and frozen.\n *\n * Part of the tilemap SDK contract for extension packages that build\n * tilesets programmatically.\n */\n public _setDefinitions(definitions: readonly TileDefinition[]): void {\n const map = this._definitions as Map<number, TileDefinition>;\n map.clear();\n for (const def of definitions) {\n const props = def.properties ? Object.freeze({ ...def.properties }) : undefined;\n const animation = def.animation ? Object.freeze(def.animation.map(frame => Object.freeze({ ...frame }))) : undefined;\n const collision = def.collision ? Object.freeze([...def.collision]) : undefined;\n map.set(def.localTileId, {\n localTileId: def.localTileId,\n ...(props !== undefined && { properties: props }),\n ...(animation !== undefined && { animation }),\n ...(collision !== undefined && { collision }),\n });\n }\n }\n\n /**\n * Retrieve per-tile metadata, or undefined if none defined.\n * @advanced\n */\n public getTileDefinition(localTileId: number): TileDefinition | undefined {\n return this._definitions.get(localTileId);\n }\n\n /**\n * Compute the pixel-space source rectangle for a local tile ID\n * within the atlas, accounting for columns, spacing, and margin.\n * @advanced\n */\n public getTileRect(localTileId: number): { x: number; y: number; width: number; height: number } {\n if (localTileId < 0 || localTileId >= this.tileCount) {\n throw new Error(`getTileRect: localTileId ${localTileId} out of range [0, ${this.tileCount - 1}].`);\n }\n const col = localTileId % this.columns;\n const row = Math.floor(localTileId / this.columns);\n return {\n x: this.margin + col * (this.tileWidth + this.spacing),\n y: this.margin + row * (this.tileHeight + this.spacing),\n width: this.tileWidth,\n height: this.tileHeight,\n };\n }\n\n /**\n * Iterate over all defined tiles (sparse).\n * @advanced\n */\n public definedTiles(): IterableIterator<TileDefinition> {\n return this._definitions.values();\n }\n\n /**\n * Read-only snapshot of all per-tile definitions.\n * The returned record is a caller-owned copy.\n * @advanced\n */\n public get allDefinitions(): Readonly<Record<number, TileProperties | undefined>> {\n const result: Record<number, TileProperties | undefined> = {};\n for (const [id, def] of this._definitions) {\n result[id] = def.properties;\n }\n return Object.freeze(result);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA6CA,IAAa,UAAb,MAAqB;;CAEnB,AAAgB;;CAGhB,AAAgB;;CAGhB,AAAgB;;CAEhB,AAAgB;;CAGhB,AAAgB;;CAGhB,AAAgB;;CAEhB,AAAgB;;CAGhB,AAAgB;;CAEhB,AAAgB;;CAGhB,AAAgB;;;;;;;;;;CAUhB,AAAgB;;CAEhB,AAAgB;CAEhB,AAAiB;;;;CAKjB,AAAO,YAAY,SAAyB;EAC1C,IAAI,CAAC,QAAQ,QAAQ,OAAO,QAAQ,SAAS,UAC3C,MAAM,IAAI,MAAM,0CAA0C;EAG5D,IAAI,CAAC,QAAQ,SACX,MAAM,IAAI,MAAM,yCAAyC;EAG3D,wBAAwB,QAAQ,WAAW,WAAW;EACtD,wBAAwB,QAAQ,YAAY,YAAY;EACxD,wBAAwB,QAAQ,WAAW,WAAW;EAEtD,MAAM,UAAU,QAAQ,WAAW;EACnC,MAAM,SAAS,QAAQ,UAAU;EACjC,2BAA2B,SAAS,SAAS;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zC,MAAM,IAAI,MAAM,4BAA4B,YAAY,oBAAoB,KAAK,YAAY,EAAE,GAAG;EAEpG,MAAM,MAAM,cAAc,KAAK;EAC/B,MAAM,MAAM,KAAK,MAAM,cAAc,KAAK,OAAO;EACjD,OAAO;GACL,GAAG,KAAK,SAAS,OAAO,KAAK,YAAY,KAAK;GAC9C,GAAG,KAAK,SAAS,OAAO,KAAK,aAAa,KAAK;GAC/C,OAAO,KAAK;GACZ,QAAQ,KAAK;EACf;CACF;;;;;CAMA,AAAO,eAAiD;EACtD,OAAO,KAAK,aAAa,OAAO;CAClC;;;;;;CAOA,IAAW,iBAAuE;EAChF,MAAM,SAAqD,CAAC;EAC5D,KAAK,MAAM,CAAC,IAAI,QAAQ,KAAK,cAC3B,OAAO,MAAM,IAAI;EAEnB,OAAO,OAAO,OAAO,MAAM;CAC7B;AACF"}
@@ -75,10 +75,12 @@ export interface WorkerSampledChunkSourceOptions {
75
75
  * {@link WorkerSampledChunkSourceOptions.workerSource} is a self-contained
76
76
  * worker script string; see its documentation for the protocol.
77
77
  *
78
- * The returned value's `destroy()` MUST be called when done with it (e.g.
79
- * alongside your `ChunkStreamer.destroy()` call) - the underlying `Worker`
80
- * is a real resource that leaks otherwise. `ChunkSource` itself has no
81
- * lifecycle hook, so this is not automatic.
78
+ * The returned value's `destroy()` MUST be called when done with it - the
79
+ * underlying `Worker` is a real resource that leaks otherwise.
80
+ * {@link import('./ChunkStreamer').ChunkStreamer} does not own the source it
81
+ * is given and never calls this for you: `ChunkSource` itself has no
82
+ * lifecycle hook, so nothing ties the two together automatically. Call it
83
+ * yourself alongside your own `ChunkStreamer.destroy()` call.
82
84
  *
83
85
  * Implementation note: `workerSource` is Blob-URL'd into a real `Worker`
84
86
  * (`new Blob([workerSource])` → `URL.createObjectURL` → `new Worker(url)`) -
@@ -1 +1 @@
1
- {"version":3,"file":"WorkerSampledChunkSource.d.ts","sourceRoot":"","sources":["../../src/WorkerSampledChunkSource.ts"],"names":[],"mappings":"AA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E;AAiCD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,eAAO,MAAM,8BAA8B,GAAI,OAAO,SAAS,EAAE,SAAS,+BAA+B,KAAG,WAAW,GAAG;IAAE,OAAO,IAAI,IAAI,CAAA;CA8F1I,CAAC"}
@@ -14,10 +14,12 @@ const isWorkerErrorMessage = (message) => "error" in message;
14
14
  * {@link WorkerSampledChunkSourceOptions.workerSource} is a self-contained
15
15
  * worker script string; see its documentation for the protocol.
16
16
  *
17
- * The returned value's `destroy()` MUST be called when done with it (e.g.
18
- * alongside your `ChunkStreamer.destroy()` call) - the underlying `Worker`
19
- * is a real resource that leaks otherwise. `ChunkSource` itself has no
20
- * lifecycle hook, so this is not automatic.
17
+ * The returned value's `destroy()` MUST be called when done with it - the
18
+ * underlying `Worker` is a real resource that leaks otherwise.
19
+ * {@link import('./ChunkStreamer').ChunkStreamer} does not own the source it
20
+ * is given and never calls this for you: `ChunkSource` itself has no
21
+ * lifecycle hook, so nothing ties the two together automatically. Call it
22
+ * yourself alongside your own `ChunkStreamer.destroy()` call.
21
23
  *
22
24
  * Implementation note: `workerSource` is Blob-URL'd into a real `Worker`
23
25
  * (`new Blob([workerSource])` → `URL.createObjectURL` → `new Worker(url)`) -
@@ -1 +1 @@
1
- {"version":3,"file":"WorkerSampledChunkSource.js","names":[],"sources":["../../src/WorkerSampledChunkSource.ts"],"sourcesContent":["import type { ChunkPayload, ChunkSource } from './ChunkSource';\nimport type { TileLayer } from './TileLayer';\nimport type { ResolvedTile } from './types';\nimport { packTile } from './types';\n\n/**\n * Options for {@link createWorkerSampledChunkSource}.\n * @advanced\n */\nexport interface WorkerSampledChunkSourceOptions {\n /**\n * Complete worker script source as a single self-contained string, Blob-URL'd\n * into a real `Worker` at construction time - the same technique\n * {@link import('@codexo/exojs').WorkletEffect} uses for AudioWorklet\n * processors. No separate worker asset is fetched and no bundler-specific\n * worker-import syntax is involved.\n *\n * Producing that string by hand-writing JavaScript into a template literal\n * works but gives up type checking, linting and shared code. Prefer a build\n * step that bundles a real module into a string: this repository's own\n * examples are authored as `*.worker.ts` and imported through a `?worker`\n * query, which is why they can `import` the sampling functions the main\n * thread uses instead of restating them.\n *\n * Must implement this request/response protocol:\n * - Request (received via `self.onmessage`):\n * `{ requestId: number; cx: number; cy: number; chunkWidth: number; chunkHeight: number }`.\n * - Response, success (send via `self.postMessage`, transferring the\n * buffer for a zero-copy handoff - `postMessage(response, [response.values.buffer])`):\n * `{ requestId: number; values: Float64Array }`, `values.length ===\n * chunkWidth * chunkHeight`, row-major (`localTy * chunkWidth + localTx`),\n * one sampled value per tile in the requested chunk. Compute each tile's\n * absolute coordinate as `cx * chunkWidth + localTx` /\n * `cy * chunkHeight + localTy`.\n * - Response, error (one request failed without crashing the worker):\n * `{ requestId: number; error: string }`.\n *\n * Your worker must reply to every request with exactly one success or\n * error message bearing the same `requestId`. A request left unanswered\n * leaves that chunk permanently unfetched - there is no timeout - since\n * `ChunkStreamer` tracks it as still in flight and never retries it.\n */\n workerSource: string;\n /**\n * Posted to the worker once, before any chunk request, when present.\n *\n * The transport for whatever the sampler needs to know that is not per-chunk\n * - a seed, a feature size, a cost knob. Without it those values would have\n * to be interpolated into {@link WorkerSampledChunkSourceOptions.workerSource}\n * as literals, which turns every parameter change into a source rebuild and a\n * new `Worker`.\n *\n * `postMessage` delivery is ordered, so the worker is guaranteed to see this\n * before the first request. Distinguish it from a chunk request by its own\n * shape; requests carry a `requestId`.\n */\n initMessage?: unknown;\n /**\n * Convert a sampled value (and its absolute tile coordinate) into a\n * resolved tile, or `null` for an empty cell. Always runs on the main\n * thread - a `ResolvedTile` references a `TileSet`/`Texture`, neither of\n * which can cross a `postMessage` boundary. Must be pure and\n * deterministic, same requirement as\n * {@link import('./SampledChunkSource').SampledChunkSourceOptions.mapValueToTile}.\n */\n mapValueToTile(value: number, tx: number, ty: number): ResolvedTile | null;\n}\n\ninterface WorkerRequestMessage {\n readonly requestId: number;\n readonly cx: number;\n readonly cy: number;\n readonly chunkWidth: number;\n readonly chunkHeight: number;\n}\n\ninterface WorkerSuccessMessage {\n readonly requestId: number;\n readonly values: Float64Array;\n}\n\ninterface WorkerErrorMessage {\n readonly requestId: number;\n readonly error: string;\n}\n\ntype WorkerResponseMessage = WorkerSuccessMessage | WorkerErrorMessage;\n\nconst isWorkerErrorMessage = (message: WorkerResponseMessage): message is WorkerErrorMessage => 'error' in message;\n\ninterface PendingRequest {\n readonly resolve: (payload: ChunkPayload | null) => void;\n readonly reject: (error: Error) => void;\n readonly cx: number;\n readonly cy: number;\n readonly chunkWidth: number;\n readonly chunkHeight: number;\n}\n\n/**\n * Build a {@link import('./ChunkStreamer').ChunkStreamer}-ready\n * {@link ChunkSource} that samples off the main thread via a Web Worker -\n * the async counterpart to\n * {@link import('./SampledChunkSource').createSampledChunkSource}, for\n * sampling functions expensive enough to want off-thread execution.\n *\n * Unlike the synchronous provider, sampling logic cannot be passed as a\n * live function - functions cannot cross a `postMessage` boundary. Instead\n * {@link WorkerSampledChunkSourceOptions.workerSource} is a self-contained\n * worker script string; see its documentation for the protocol.\n *\n * The returned value's `destroy()` MUST be called when done with it (e.g.\n * alongside your `ChunkStreamer.destroy()` call) - the underlying `Worker`\n * is a real resource that leaks otherwise. `ChunkSource` itself has no\n * lifecycle hook, so this is not automatic.\n *\n * Implementation note: `workerSource` is Blob-URL'd into a real `Worker`\n * (`new Blob([workerSource])` → `URL.createObjectURL` → `new Worker(url)`) -\n * the same technique {@link import('@codexo/exojs').WorkletEffect} already\n * uses for AudioWorklet processors. This is bundler-agnostic (no special\n * config needed in Vite/webpack/etc.) but requires a Content-Security-Policy\n * that permits `blob:` in `worker-src` (or `script-src` as a fallback) if\n * your deployment sets one.\n * @advanced\n */\nexport const createWorkerSampledChunkSource = (layer: TileLayer, options: WorkerSampledChunkSourceOptions): ChunkSource & { destroy(): void } => {\n const mapValueToTile = options.mapValueToTile.bind(options);\n\n const blob = new Blob([options.workerSource], { type: 'application/javascript' });\n const url = URL.createObjectURL(blob);\n const worker = new Worker(url);\n URL.revokeObjectURL(url);\n\n if (options.initMessage !== undefined) {\n worker.postMessage(options.initMessage);\n }\n\n let requestCounter = 0;\n const pending = new Map<number, PendingRequest>();\n let destroyed = false;\n\n const composePayload = (values: Float64Array, request: PendingRequest): ChunkPayload | null => {\n const { cx, cy, chunkWidth, chunkHeight } = request;\n const startTx = cx * chunkWidth;\n const startTy = cy * chunkHeight;\n\n let out: Uint32Array | null = null;\n for (let ty = startTy; ty < startTy + chunkHeight; ty++) {\n for (let tx = startTx; tx < startTx + chunkWidth; tx++) {\n // Bounded-layer edge chunks may be smaller than a full chunk - same\n // clamp createSampledChunkSource applies, computed here (not asked\n // of the worker) since only this side knows the layer's bounds.\n if (layer.width !== undefined && layer.height !== undefined && (tx >= layer.width || ty >= layer.height)) continue;\n\n const localIndex = (ty - startTy) * chunkWidth + (tx - startTx);\n const value = values[localIndex];\n if (value === undefined) continue; // defensive: malformed/short values array\n const resolved = mapValueToTile(value, tx, ty);\n if (!resolved) continue;\n\n out ??= new Uint32Array(chunkWidth * chunkHeight);\n const tilesetIndex = layer.tilesets.indexOf(resolved.tileset);\n out[localIndex] = packTile(tilesetIndex, resolved.localTileId, resolved.transform);\n }\n }\n\n return out === null ? null : { width: chunkWidth, height: chunkHeight, tiles: out };\n };\n\n worker.onmessage = (event: MessageEvent<WorkerResponseMessage>): void => {\n const message = event.data;\n const entry = pending.get(message.requestId);\n if (!entry) return; // stale/unknown requestId (e.g. arrived after destroy())\n pending.delete(message.requestId);\n\n if (isWorkerErrorMessage(message)) {\n entry.reject(new Error(message.error));\n return;\n }\n\n entry.resolve(composePayload(message.values, entry));\n };\n\n worker.onerror = (event: ErrorEvent): void => {\n const error = new Error(`WorkerSampledChunkSource worker error: ${event.message}`);\n for (const entry of pending.values()) {\n entry.reject(error);\n }\n pending.clear();\n };\n\n return {\n getChunk(cx: number, cy: number): Promise<ChunkPayload | null> {\n if (destroyed) {\n return Promise.reject(new Error('WorkerSampledChunkSource: getChunk() called after destroy().'));\n }\n\n const chunkWidth = layer.chunkWidth;\n const chunkHeight = layer.chunkHeight;\n const requestId = ++requestCounter;\n\n return new Promise<ChunkPayload | null>((resolve, reject) => {\n pending.set(requestId, { resolve, reject, cx, cy, chunkWidth, chunkHeight });\n const request: WorkerRequestMessage = { requestId, cx, cy, chunkWidth, chunkHeight };\n worker.postMessage(request);\n });\n },\n\n destroy(): void {\n if (destroyed) return;\n destroyed = true;\n const error = new Error('WorkerSampledChunkSource destroyed.');\n for (const entry of pending.values()) {\n entry.reject(error);\n }\n pending.clear();\n worker.terminate();\n },\n };\n};\n"],"mappings":";;;AAwFA,MAAM,wBAAwB,YAAkE,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqC3G,MAAa,kCAAkC,OAAkB,YAAgF;CAC/I,MAAM,iBAAiB,QAAQ,eAAe,KAAK,OAAO;CAE1D,MAAM,OAAO,IAAI,KAAK,CAAC,QAAQ,YAAY,GAAG,EAAE,MAAM,yBAAyB,CAAC;CAChF,MAAM,MAAM,IAAI,gBAAgB,IAAI;CACpC,MAAM,SAAS,IAAI,OAAO,GAAG;CAC7B,IAAI,gBAAgB,GAAG;CAEvB,IAAI,QAAQ,gBAAgB,QAC1B,OAAO,YAAY,QAAQ,WAAW;CAGxC,IAAI,iBAAiB;CACrB,MAAM,0BAAU,IAAI,IAA4B;CAChD,IAAI,YAAY;CAEhB,MAAM,kBAAkB,QAAsB,YAAiD;EAC7F,MAAM,EAAE,IAAI,IAAI,YAAY,gBAAgB;EAC5C,MAAM,UAAU,KAAK;EACrB,MAAM,UAAU,KAAK;EAErB,IAAI,MAA0B;EAC9B,KAAK,IAAI,KAAK,SAAS,KAAK,UAAU,aAAa,MACjD,KAAK,IAAI,KAAK,SAAS,KAAK,UAAU,YAAY,MAAM;GAItD,IAAI,MAAM,UAAU,UAAa,MAAM,WAAW,WAAc,MAAM,MAAM,SAAS,MAAM,MAAM,SAAS;GAE1G,MAAM,cAAc,KAAK,WAAW,cA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,IAAI,WAAW;GACf,YAAY;GACZ,MAAM,wBAAQ,IAAI,MAAM,qCAAqC;GAC7D,KAAK,MAAM,SAAS,QAAQ,OAAO,GACjC,MAAM,OAAO,KAAK;GAEpB,QAAQ,MAAM;GACd,OAAO,UAAU;EACnB;CACF;AACF"}
1
+ {"version":3,"file":"WorkerSampledChunkSource.js","names":[],"sources":["../../src/WorkerSampledChunkSource.ts"],"sourcesContent":["import type { ChunkPayload, ChunkSource } from './ChunkSource';\nimport type { TileLayer } from './TileLayer';\nimport type { ResolvedTile } from './types';\nimport { packTile } from './types';\n\n/**\n * Options for {@link createWorkerSampledChunkSource}.\n * @advanced\n */\nexport interface WorkerSampledChunkSourceOptions {\n /**\n * Complete worker script source as a single self-contained string, Blob-URL'd\n * into a real `Worker` at construction time - the same technique\n * {@link import('@codexo/exojs').WorkletEffect} uses for AudioWorklet\n * processors. No separate worker asset is fetched and no bundler-specific\n * worker-import syntax is involved.\n *\n * Producing that string by hand-writing JavaScript into a template literal\n * works but gives up type checking, linting and shared code. Prefer a build\n * step that bundles a real module into a string: this repository's own\n * examples are authored as `*.worker.ts` and imported through a `?worker`\n * query, which is why they can `import` the sampling functions the main\n * thread uses instead of restating them.\n *\n * Must implement this request/response protocol:\n * - Request (received via `self.onmessage`):\n * `{ requestId: number; cx: number; cy: number; chunkWidth: number; chunkHeight: number }`.\n * - Response, success (send via `self.postMessage`, transferring the\n * buffer for a zero-copy handoff - `postMessage(response, [response.values.buffer])`):\n * `{ requestId: number; values: Float64Array }`, `values.length ===\n * chunkWidth * chunkHeight`, row-major (`localTy * chunkWidth + localTx`),\n * one sampled value per tile in the requested chunk. Compute each tile's\n * absolute coordinate as `cx * chunkWidth + localTx` /\n * `cy * chunkHeight + localTy`.\n * - Response, error (one request failed without crashing the worker):\n * `{ requestId: number; error: string }`.\n *\n * Your worker must reply to every request with exactly one success or\n * error message bearing the same `requestId`. A request left unanswered\n * leaves that chunk permanently unfetched - there is no timeout - since\n * `ChunkStreamer` tracks it as still in flight and never retries it.\n */\n workerSource: string;\n /**\n * Posted to the worker once, before any chunk request, when present.\n *\n * The transport for whatever the sampler needs to know that is not per-chunk\n * - a seed, a feature size, a cost knob. Without it those values would have\n * to be interpolated into {@link WorkerSampledChunkSourceOptions.workerSource}\n * as literals, which turns every parameter change into a source rebuild and a\n * new `Worker`.\n *\n * `postMessage` delivery is ordered, so the worker is guaranteed to see this\n * before the first request. Distinguish it from a chunk request by its own\n * shape; requests carry a `requestId`.\n */\n initMessage?: unknown;\n /**\n * Convert a sampled value (and its absolute tile coordinate) into a\n * resolved tile, or `null` for an empty cell. Always runs on the main\n * thread - a `ResolvedTile` references a `TileSet`/`Texture`, neither of\n * which can cross a `postMessage` boundary. Must be pure and\n * deterministic, same requirement as\n * {@link import('./SampledChunkSource').SampledChunkSourceOptions.mapValueToTile}.\n */\n mapValueToTile(value: number, tx: number, ty: number): ResolvedTile | null;\n}\n\ninterface WorkerRequestMessage {\n readonly requestId: number;\n readonly cx: number;\n readonly cy: number;\n readonly chunkWidth: number;\n readonly chunkHeight: number;\n}\n\ninterface WorkerSuccessMessage {\n readonly requestId: number;\n readonly values: Float64Array;\n}\n\ninterface WorkerErrorMessage {\n readonly requestId: number;\n readonly error: string;\n}\n\ntype WorkerResponseMessage = WorkerSuccessMessage | WorkerErrorMessage;\n\nconst isWorkerErrorMessage = (message: WorkerResponseMessage): message is WorkerErrorMessage => 'error' in message;\n\ninterface PendingRequest {\n readonly resolve: (payload: ChunkPayload | null) => void;\n readonly reject: (error: Error) => void;\n readonly cx: number;\n readonly cy: number;\n readonly chunkWidth: number;\n readonly chunkHeight: number;\n}\n\n/**\n * Build a {@link import('./ChunkStreamer').ChunkStreamer}-ready\n * {@link ChunkSource} that samples off the main thread via a Web Worker -\n * the async counterpart to\n * {@link import('./SampledChunkSource').createSampledChunkSource}, for\n * sampling functions expensive enough to want off-thread execution.\n *\n * Unlike the synchronous provider, sampling logic cannot be passed as a\n * live function - functions cannot cross a `postMessage` boundary. Instead\n * {@link WorkerSampledChunkSourceOptions.workerSource} is a self-contained\n * worker script string; see its documentation for the protocol.\n *\n * The returned value's `destroy()` MUST be called when done with it - the\n * underlying `Worker` is a real resource that leaks otherwise.\n * {@link import('./ChunkStreamer').ChunkStreamer} does not own the source it\n * is given and never calls this for you: `ChunkSource` itself has no\n * lifecycle hook, so nothing ties the two together automatically. Call it\n * yourself alongside your own `ChunkStreamer.destroy()` call.\n *\n * Implementation note: `workerSource` is Blob-URL'd into a real `Worker`\n * (`new Blob([workerSource])` → `URL.createObjectURL` → `new Worker(url)`) -\n * the same technique {@link import('@codexo/exojs').WorkletEffect} already\n * uses for AudioWorklet processors. This is bundler-agnostic (no special\n * config needed in Vite/webpack/etc.) but requires a Content-Security-Policy\n * that permits `blob:` in `worker-src` (or `script-src` as a fallback) if\n * your deployment sets one.\n * @advanced\n */\nexport const createWorkerSampledChunkSource = (layer: TileLayer, options: WorkerSampledChunkSourceOptions): ChunkSource & { destroy(): void } => {\n const mapValueToTile = options.mapValueToTile.bind(options);\n\n const blob = new Blob([options.workerSource], { type: 'application/javascript' });\n const url = URL.createObjectURL(blob);\n const worker = new Worker(url);\n URL.revokeObjectURL(url);\n\n if (options.initMessage !== undefined) {\n worker.postMessage(options.initMessage);\n }\n\n let requestCounter = 0;\n const pending = new Map<number, PendingRequest>();\n let destroyed = false;\n\n const composePayload = (values: Float64Array, request: PendingRequest): ChunkPayload | null => {\n const { cx, cy, chunkWidth, chunkHeight } = request;\n const startTx = cx * chunkWidth;\n const startTy = cy * chunkHeight;\n\n let out: Uint32Array | null = null;\n for (let ty = startTy; ty < startTy + chunkHeight; ty++) {\n for (let tx = startTx; tx < startTx + chunkWidth; tx++) {\n // Bounded-layer edge chunks may be smaller than a full chunk - same\n // clamp createSampledChunkSource applies, computed here (not asked\n // of the worker) since only this side knows the layer's bounds.\n if (layer.width !== undefined && layer.height !== undefined && (tx >= layer.width || ty >= layer.height)) continue;\n\n const localIndex = (ty - startTy) * chunkWidth + (tx - startTx);\n const value = values[localIndex];\n if (value === undefined) continue; // defensive: malformed/short values array\n const resolved = mapValueToTile(value, tx, ty);\n if (!resolved) continue;\n\n out ??= new Uint32Array(chunkWidth * chunkHeight);\n const tilesetIndex = layer.tilesets.indexOf(resolved.tileset);\n out[localIndex] = packTile(tilesetIndex, resolved.localTileId, resolved.transform);\n }\n }\n\n return out === null ? null : { width: chunkWidth, height: chunkHeight, tiles: out };\n };\n\n worker.onmessage = (event: MessageEvent<WorkerResponseMessage>): void => {\n const message = event.data;\n const entry = pending.get(message.requestId);\n if (!entry) return; // stale/unknown requestId (e.g. arrived after destroy())\n pending.delete(message.requestId);\n\n if (isWorkerErrorMessage(message)) {\n entry.reject(new Error(message.error));\n return;\n }\n\n entry.resolve(composePayload(message.values, entry));\n };\n\n worker.onerror = (event: ErrorEvent): void => {\n const error = new Error(`WorkerSampledChunkSource worker error: ${event.message}`);\n for (const entry of pending.values()) {\n entry.reject(error);\n }\n pending.clear();\n };\n\n return {\n getChunk(cx: number, cy: number): Promise<ChunkPayload | null> {\n if (destroyed) {\n return Promise.reject(new Error('WorkerSampledChunkSource: getChunk() called after destroy().'));\n }\n\n const chunkWidth = layer.chunkWidth;\n const chunkHeight = layer.chunkHeight;\n const requestId = ++requestCounter;\n\n return new Promise<ChunkPayload | null>((resolve, reject) => {\n pending.set(requestId, { resolve, reject, cx, cy, chunkWidth, chunkHeight });\n const request: WorkerRequestMessage = { requestId, cx, cy, chunkWidth, chunkHeight };\n worker.postMessage(request);\n });\n },\n\n destroy(): void {\n if (destroyed) return;\n destroyed = true;\n const error = new Error('WorkerSampledChunkSource destroyed.');\n for (const entry of pending.values()) {\n entry.reject(error);\n }\n pending.clear();\n worker.terminate();\n },\n };\n};\n"],"mappings":";;;AAwFA,MAAM,wBAAwB,YAAkE,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuC3G,MAAa,kCAAkC,OAAkB,YAAgF;CAC/I,MAAM,iBAAiB,QAAQ,eAAe,KAAK,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GAAG;GACjC,MAAM,OAAO,IAAI,MAAM,QAAQ,KAAK,CAAC;GACrC;EACF;EAEA,MAAM,QAAQ,eAAe,QAAQ,QAAQ,KAAK,CAAC;CACrD;CAEA,OAAO,WAAW,UAA4B;EAC5C,MAAM,wBAAQ,IAAI,MAAM,0CAA0C,MAAM,SAAS;EACjF,KAAK,MAAM,SAAS,QAAQ,OAAO,GACjC,MAAM,OAAO,KAAK;EAEpB,QAAQ,MAAM;CAChB;CAEA,OAAO;EACL,SAAS,IAAY,IAA0C;GAC7D,IAAI,WACF,OAAO,QAAQ,uBAAO,IAAI,MAAM,8DAA8D,CAAC;GAGjG,MAAM,aAAa,MAAM;GACzB,MAAM,cAAc,MAAM;GAC1B,MAAM,YAAY,EAAE;GAEpB,OAAO,IAAI,SAA8B,SAAS,WAAW;IAC3D,QAAQ,IAAI,WAAW;KAAE;KAAS;KAAQ;KAAI;KAAI;KAAY;IAAY,CAAC;IAC3E,MAAM,UAAgC;KAAE;KAAW;KAAI;KAAI;KAAY;IAAY;IACnF,OAAO,YAAY,OAAO;GAC5B,CAAC;EACH;EAEA,UAAgB;GACd,IAAI,WAAW;GACf,YAAY;GACZ,MAAM,wBAAQ,IAAI,MAAM,qCAAqC;GAC7D,KAAK,MAAM,SAAS,QAAQ,OAAO,GACjC,MAAM,OAAO,KAAK;GAEpB,QAAQ,MAAM;GACd,OAAO,UAAU;EACnB;CACF;AACF"}
@@ -46,6 +46,12 @@ export declare class WebGl2TileChunkRenderer extends AbstractWebGl2Renderer<Tile
46
46
  private _renderPage;
47
47
  private _writeRun;
48
48
  flush(): void;
49
+ /**
50
+ * Scope the batch memos to one batch: they describe what is accumulating, not
51
+ * what GL holds, so a memo that outlived its flush would let the next batch
52
+ * skip establishing state another renderer has since changed.
53
+ */
54
+ private _resetBatchState;
49
55
  /**
50
56
  * Stage `u_projection` (live view) and `u_group` (live composed group
51
57
  * matrix) on the shader, guarded by cached view/group stamps. Shared by the
@@ -1 +1 @@
1
- {"version":3,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MG;IACI,qBAAqB,CAAC,OAAO,EAAE,0BAA0B,GAAG,IAAI;IAkBvE;;;;;;;;;;OAUG;IACI,oBAAoB,CAAC,OAAO,EAAE,0BAA0B,GAAG,IAAI;IAkCtE,SAAS,CAAC,SAAS,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI;IAkBjD,SAAS,CAAC,YAAY,IAAI,IAAI;IAkBvB,OAAO,IAAI,IAAI;IAKtB,OAAO,CAAC,iBAAiB;IAUzB,OAAO,CAAC,oBAAoB;IAiC5B,OAAO,CAAC,iBAAiB;CA8C1B"}
@@ -79,21 +79,15 @@ var WebGl2TileChunkRenderer = class extends AbstractWebGl2Renderer {
79
79
  const tintRgba = node.tint.toRgba8();
80
80
  const command = backend.activeDrawCommand;
81
81
  const nodeIndex = command !== null ? command.nodeIndex : backend._pushTransform(node);
82
- for (const page of pages) this._renderPage(backend, page.texture, page.quads, blendMode, tintRgba, nodeIndex);
82
+ for (const page of pages) this._renderPage(page.texture, page.quads, blendMode, tintRgba, nodeIndex);
83
83
  }
84
- _renderPage(backend, texture, quads, blendMode, tintRgba, nodeIndex) {
84
+ _renderPage(texture, quads, blendMode, tintRgba, nodeIndex) {
85
85
  if (quads.length === 0) return;
86
86
  const textureChanged = this._currentTexture !== null && texture !== this._currentTexture;
87
- const blendModeChanged = blendMode !== this._currentBlendMode;
87
+ const blendModeChanged = this._currentBlendMode !== null && blendMode !== this._currentBlendMode;
88
88
  if (this._quadIndex > 0 && (blendModeChanged || textureChanged || this._quadIndex + quads.length > this._batchSize)) this.flush();
89
- if (this._currentBlendMode === null || this._currentBlendMode !== blendMode) {
90
- this._currentBlendMode = blendMode;
91
- backend.setBlendMode(blendMode);
92
- }
93
- if (this._currentTexture !== texture) {
94
- this._currentTexture = texture;
95
- backend.bindTexture(texture, 0);
96
- }
89
+ this._currentBlendMode = blendMode;
90
+ this._currentTexture = texture;
97
91
  const flipY = texture.flipY;
98
92
  let offset = 0;
99
93
  while (offset < quads.length) {
@@ -104,9 +98,7 @@ var WebGl2TileChunkRenderer = class extends AbstractWebGl2Renderer {
104
98
  if (offset < quads.length) {
105
99
  this.flush();
106
100
  this._currentBlendMode = blendMode;
107
- backend.setBlendMode(blendMode);
108
101
  this._currentTexture = texture;
109
- backend.bindTexture(texture, 0);
110
102
  }
111
103
  }
112
104
  }
@@ -154,18 +146,20 @@ var WebGl2TileChunkRenderer = class extends AbstractWebGl2Renderer {
154
146
  const instanceBuffer = this._instanceBuffer;
155
147
  const vao = this._vao;
156
148
  if (this._quadIndex === 0 || backend === null || instanceBuffer === null || vao === null) {
157
- this._quadIndex = 0;
158
- this._maxNodeIndex = 0;
159
- this._batchNodeCount = 0;
149
+ this._resetBatchState();
160
150
  return;
161
151
  }
162
152
  this._stageViewUniforms(backend);
163
- if (this._currentTexture !== null) this._shader.getUniform("u_texture").setValue(this._baseTextureUnitScratch);
153
+ if (this._currentTexture !== null) {
154
+ backend.bindTexture(this._currentTexture, 0);
155
+ this._shader.getUniform("u_texture").setValue(this._baseTextureUnitScratch);
156
+ }
164
157
  backend.bindTransformBufferTexture(transformTextureUnit, this._maxNodeIndex + 1);
165
158
  this._shader.getUniform("u_transforms").setValue(this._transformUnitScratch);
166
159
  this._shader.sync();
167
160
  backend.bindVertexArrayObject(vao);
168
161
  instanceBuffer.upload(this._instanceFloat32, 0, this._quadIndex * wordsPerInstance);
162
+ backend.setBlendMode(this._currentBlendMode ?? BlendModes.Normal);
169
163
  vao.drawInstanced(4, 0, this._quadIndex, RenderingPrimitives.TriangleStrip);
170
164
  backend.stats.batches++;
171
165
  backend.stats.drawCalls++;
@@ -173,9 +167,19 @@ var WebGl2TileChunkRenderer = class extends AbstractWebGl2Renderer {
173
167
  this._recordTextures[0] = this._currentTexture;
174
168
  backend._recordRetainedBatch(this, this._instanceUint32.subarray(0, this._quadIndex * wordsPerInstance), this._quadIndex, this._currentBlendMode ?? BlendModes.Normal, this._recordTextures, 1, null, null, this._batchNodeCount);
175
169
  }
170
+ this._resetBatchState();
171
+ }
172
+ /**
173
+ * Scope the batch memos to one batch: they describe what is accumulating, not
174
+ * what GL holds, so a memo that outlived its flush would let the next batch
175
+ * skip establishing state another renderer has since changed.
176
+ */
177
+ _resetBatchState() {
176
178
  this._quadIndex = 0;
177
179
  this._maxNodeIndex = 0;
178
180
  this._batchNodeCount = 0;
181
+ this._currentBlendMode = null;
182
+ this._currentTexture = null;
179
183
  }
180
184
  /**
181
185
  * Stage `u_projection` (live view) and `u_group` (live composed group
@@ -250,12 +254,10 @@ var WebGl2TileChunkRenderer = class extends AbstractWebGl2Renderer {
250
254
  const vao = payload.vao;
251
255
  const transformTexture = payload.bundle.transformTexture;
252
256
  if (backend === null || vao === null || transformTexture === null) return;
253
- if (payload.blendMode !== this._currentBlendMode) this._currentBlendMode = payload.blendMode;
254
257
  backend.setBlendMode(payload.blendMode);
255
258
  this._stageViewUniforms(backend);
256
259
  const textures = payload.textures;
257
260
  for (let i = 0; i < textures.length; i++) backend.bindTexture(textures[i], i);
258
- if (textures.length > 0) this._currentTexture = textures[0];
259
261
  this._shader.getUniform("u_texture").setValue(this._baseTextureUnitScratch);
260
262
  backend.bindTexture(transformTexture, transformTextureUnit);
261
263
  this._shader.getUniform("u_transforms").setValue(this._transformUnitScratch);
@@ -1 +1 @@
1
- {"version":3,"file":"WebGl2TileChunkRenderer.js","names":["tileVertexTemplate","tileFragmentSource"],"sources":["../../../src/webgl2/WebGl2TileChunkRenderer.ts"],"sourcesContent":["import type {\n RenderTexture,\n Texture,\n View,\n WebGl2Backend,\n WebGl2RenderBufferRuntime,\n WebGl2RetainedBatchPayload,\n WebGl2RetainedBatchReplayer,\n WebGl2RetainedNodeIndexRange,\n WebGl2VertexArrayObjectRuntime,\n} from '@codexo/exojs/renderer-sdk';\nimport {\n AbstractWebGl2Renderer,\n BlendModes,\n BufferTypes,\n BufferUsage,\n createWebGl2ShaderProgram,\n fillShaderSource,\n packedGroupChanged,\n RenderingPrimitives,\n Shader,\n uploadBufferRange,\n uploadBufferStore,\n WebGl2RenderBuffer,\n WebGl2VertexArrayObject,\n} from '@codexo/exojs/renderer-sdk';\n\nimport type { TileQuad } from '../chunkGeometry';\nimport type { TileChunkNode } from '../TileChunkNode';\nimport { TILE_DIAGONAL_BIT, TILE_ROW_MASK } from '../tileWord';\nimport tileFragmentSource from './shaders/tile-chunk.frag';\nimport tileVertexTemplate from './shaders/tile-chunk.vert';\n\n// One instance = one tile quad. Layout matches the engine's instanced-quad\n// convention (NineSlice/Repeating): float32x4 local rect, unorm16x4 UV bounds,\n// unorm8x4 tint, uint32 tile word (transform row + diagonal bit).\nconst instanceStrideBytes = 32;\nconst wordsPerInstance = instanceStrideBytes / Uint32Array.BYTES_PER_ELEMENT;\nconst transformTextureUnit = 1;\nconst identityGroupMat3 = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);\n\nconst tileVertexSource = fillShaderSource(tileVertexTemplate, { tileRowMask: TILE_ROW_MASK, tileDiagonalBit: TILE_DIAGONAL_BIT });\n\ninterface TileRendererConnection {\n readonly gl: WebGL2RenderingContext;\n readonly buffers: Map<WebGl2RenderBuffer, { handle: WebGLBuffer; dataByteLength: number }>;\n readonly vaoHandle: WebGLVertexArrayObject;\n}\n\n/**\n * Instanced WebGL2 renderer for {@link TileChunkNode}. Each tile is one\n * instanced quad; tiles are batched by `(shader, tileset texture)` and one\n * `drawArraysInstanced` is issued per batch. Per-chunk transforms ride on the\n * shared transform buffer (one row per chunk node), so the chunk geometry is\n * orientation-neutral and never re-uploaded for a camera pan.\n * @internal\n */\nexport class WebGl2TileChunkRenderer extends AbstractWebGl2Renderer<TileChunkNode> implements WebGl2RetainedBatchReplayer {\n /**\n * Retained-batch capability opt-in: a tile chunk's per-flush\n * instanced batches (fixed 32-byte layout, tile word at word 7) can be\n * recorded into a group's instruction set and replayed from group-owned\n * resources. Pixel-snapped draws are excluded by the collect-time\n * recordability predicate (and belt-and-braces poisoning in {@link render});\n * tile chunks have no custom-material path to exclude.\n * @internal\n */\n public readonly _supportsRetainedBatches = true;\n\n private readonly _shader: Shader;\n private readonly _batchSize: number;\n private readonly _instanceData: ArrayBuffer;\n private readonly _instanceFloat32: Float32Array;\n private readonly _instanceUint32: Uint32Array;\n\n private readonly _transformUnitScratch: Int32Array = new Int32Array([transformTextureUnit]);\n // Pinned unit index for the single tileset texture sampler (unit 0), reused\n // by the live flush and retained replay so both stay allocation-free.\n private readonly _baseTextureUnitScratch: Int32Array = new Int32Array([0]);\n // Reused single-slot texture list handed to the backend at record time; a\n // tile chunk batch always binds exactly one tileset texture (slot 0).\n private readonly _recordTextures: Array<Texture | RenderTexture | null> = [null];\n\n private _quadIndex = 0;\n private _maxNodeIndex = 0;\n // Chunk nodes booked against the PENDING batch, and whether the chunk being\n // rendered right now has already been booked. One chunk emits one tile\n // instance per tile, so the recorded batch's `submittedNodes` contribution is\n // this count and not `_quadIndex`. A chunk whose pages/runs span several\n // batches is booked once, against the batch its first run lands in.\n private _batchNodeCount = 0;\n private _nodeBooked = false;\n private _currentBlendMode: BlendModes | null = null;\n private _currentTexture: Texture | null = null;\n private _currentView: View | null = null;\n private _currentViewId = -1;\n private _hasWrittenGroup = false;\n private readonly _writtenGroupData = new Float32Array(9);\n\n private _instanceBuffer: WebGl2RenderBuffer | null = null;\n private _vao: WebGl2VertexArrayObject | null = null;\n private _connection: TileRendererConnection | null = null;\n\n public constructor(batchSize: number) {\n super();\n\n this._batchSize = batchSize;\n this._shader = new Shader(tileVertexSource, tileFragmentSource);\n this._instanceData = new ArrayBuffer(batchSize * instanceStrideBytes);\n this._instanceFloat32 = new Float32Array(this._instanceData);\n this._instanceUint32 = new Uint32Array(this._instanceData);\n }\n\n public render(node: TileChunkNode): void {\n const pages = node.pages;\n\n this._nodeBooked = false;\n\n if (pages.length === 0) {\n return;\n }\n\n const backend = this.getBackend();\n\n const blendMode = node.blendMode;\n const tintRgba = node.tint.toRgba8();\n\n const command = backend.activeDrawCommand;\n const nodeIndex = command !== null ? command.nodeIndex : backend._pushTransform(node);\n\n for (const page of pages) {\n this._renderPage(backend, page.texture, page.quads, blendMode, tintRgba, nodeIndex);\n }\n }\n\n private _renderPage(backend: WebGl2Backend, texture: Texture, quads: readonly TileQuad[], blendMode: BlendModes, tintRgba: number, nodeIndex: number): void {\n if (quads.length === 0) {\n return;\n }\n\n const textureChanged = this._currentTexture !== null && texture !== this._currentTexture;\n const blendModeChanged = blendMode !== this._currentBlendMode;\n\n if (this._quadIndex > 0 && (blendModeChanged || textureChanged || this._quadIndex + quads.length > this._batchSize)) {\n this.flush();\n }\n\n if (this._currentBlendMode === null || this._currentBlendMode !== blendMode) {\n this._currentBlendMode = blendMode;\n backend.setBlendMode(blendMode);\n }\n\n if (this._currentTexture !== texture) {\n this._currentTexture = texture;\n backend.bindTexture(texture, 0);\n }\n\n const flipY = texture.flipY;\n\n // A chunk page may hold more tiles than the fixed batch buffer; write in\n // batch-sized runs, flushing (and re-establishing state) between runs.\n let offset = 0;\n\n while (offset < quads.length) {\n const remaining = quads.length - offset;\n const runSize = Math.min(remaining, this._batchSize);\n\n this._writeRun(quads, offset, runSize, flipY, tintRgba, nodeIndex);\n\n offset += runSize;\n\n if (offset < quads.length) {\n this.flush();\n this._currentBlendMode = blendMode;\n backend.setBlendMode(blendMode);\n this._currentTexture = texture;\n backend.bindTexture(texture, 0);\n }\n }\n }\n\n private _writeRun(quads: readonly TileQuad[], offset: number, count: number, flipY: boolean, tintRgba: number, nodeIndex: number): void {\n const f32 = this._instanceFloat32;\n const u32 = this._instanceUint32;\n const baseWord = nodeIndex & TILE_ROW_MASK;\n\n // Booked here rather than in render(): any flush the page/run loops trigger\n // has already happened, so the chunk lands on the batch that actually holds\n // its first tile.\n if (!this._nodeBooked) {\n this._nodeBooked = true;\n this._batchNodeCount++;\n }\n\n for (let i = 0; i < count; i++) {\n const q = quads[offset + i]!;\n const idx = this._quadIndex * wordsPerInstance;\n\n f32[idx + 0] = q.x0;\n f32[idx + 1] = q.y0;\n f32[idx + 2] = q.x1;\n f32[idx + 3] = q.y1;\n\n // Bake flipX/flipY into the UV corner ordering; the diagonal axis swap is\n // resolved in the shader. Texture flipY (uploaded-flipped atlases) is an\n // additional vertical swap that composes with the tile flipY.\n const flipX = (q.orient & 1) !== 0;\n const tileFlipY = (q.orient & 2) !== 0;\n const diagonal = (q.orient & 4) !== 0;\n\n const uA = flipX ? q.u1 : q.u0;\n const uB = flipX ? q.u0 : q.u1;\n let vA = tileFlipY ? q.v1 : q.v0;\n let vB = tileFlipY ? q.v0 : q.v1;\n\n if (flipY) {\n const swap = vA;\n vA = vB;\n vB = swap;\n }\n\n const uMin = (uA * 0xffff) & 0xffff;\n const vMin = (vA * 0xffff) & 0xffff;\n const uMax = (uB * 0xffff) & 0xffff;\n const vMax = (vB * 0xffff) & 0xffff;\n\n u32[idx + 4] = uMin | (vMin << 16);\n u32[idx + 5] = uMax | (vMax << 16);\n u32[idx + 6] = tintRgba;\n u32[idx + 7] = (diagonal ? baseWord | TILE_DIAGONAL_BIT : baseWord) >>> 0;\n\n this._quadIndex++;\n }\n\n if (nodeIndex > this._maxNodeIndex) {\n this._maxNodeIndex = nodeIndex;\n }\n }\n\n public flush(): void {\n const backend = this.getBackendOrNull();\n const instanceBuffer = this._instanceBuffer;\n const vao = this._vao;\n\n if (this._quadIndex === 0 || backend === null || instanceBuffer === null || vao === null) {\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n return;\n }\n\n this._stageViewUniforms(backend);\n\n if (this._currentTexture !== null) {\n this._shader.getUniform('u_texture').setValue(this._baseTextureUnitScratch);\n }\n\n backend.bindTransformBufferTexture(transformTextureUnit, this._maxNodeIndex + 1);\n this._shader.getUniform('u_transforms').setValue(this._transformUnitScratch);\n\n this._shader.sync();\n backend.bindVertexArrayObject(vao);\n instanceBuffer.upload(this._instanceFloat32, 0, this._quadIndex * wordsPerInstance);\n vao.drawInstanced(4, 0, this._quadIndex, RenderingPrimitives.TriangleStrip);\n backend.stats.batches++;\n backend.stats.drawCalls++;\n\n // Retained recording: while a capture window is open, hand the\n // exact packed instance words of this flush to the backend - byte-\n // identical to what just drew. A batch always binds a single tileset\n // texture (slot 0); a pixel-snapped node already poisoned the capture in\n // render().\n if (backend._isRetainedCapturing && this._currentTexture !== null) {\n this._recordTextures[0] = this._currentTexture;\n backend._recordRetainedBatch(\n this,\n this._instanceUint32.subarray(0, this._quadIndex * wordsPerInstance),\n this._quadIndex,\n this._currentBlendMode ?? BlendModes.Normal,\n this._recordTextures,\n 1,\n null,\n null,\n this._batchNodeCount,\n );\n }\n\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n }\n\n /**\n * Stage `u_projection` (live view) and `u_group` (live composed group\n * matrix) on the shader, guarded by cached view/group stamps. Shared by the\n * live flush path and retained-batch replay - replay resolves exactly the\n * same live state a slow-path flush would.\n */\n private _stageViewUniforms(backend: WebGl2Backend): void {\n const view = backend.view;\n\n if (this._currentView !== view || this._currentViewId !== view.updateId) {\n this._currentView = view;\n this._currentViewId = view.updateId;\n this._shader.getUniform('u_projection').setValue(view.getTransform().toArray(false));\n }\n\n const groupTransform = backend.renderGroupTransform;\n const groupData = groupTransform !== null ? groupTransform.toArray(false) : identityGroupMat3;\n\n if (!this._hasWrittenGroup || packedGroupChanged(groupData, this._writtenGroupData, 0)) {\n this._shader.getUniform('u_group').setValue(groupData);\n this._writtenGroupData.set(groupData);\n this._hasWrittenGroup = true;\n }\n\n backend._stageViewportUniform(this._shader);\n }\n\n // ── Retained-batch record/replay ──────────────────────────────────────────\n // The bundle stores raw instance bytes; this renderer owns the 32-byte\n // layout (tile word at word 7: transform row in bits 0..28, diagonal flip in\n // bit 29), so the layout-aware finalize steps (node-index scan/rebase, VAO\n // attribute wiring) and the replay dispatch live here - mirroring\n // WebGl2NineSliceSpriteRenderer's seam.\n\n /** @internal See {@link WebGl2RetainedBatchReplayer._scanRetainedNodeIndexRange}. */\n public _scanRetainedNodeIndexRange(payload: WebGl2RetainedBatchPayload, range: WebGl2RetainedNodeIndexRange): void {\n const words = payload.bundle.instanceWords;\n const start = payload.byteOffset / Uint32Array.BYTES_PER_ELEMENT;\n\n for (let i = 0; i < payload.instanceCount; i++) {\n // In-bounds: the payload's word range was appended to the bundle store.\n // The tile word is the last word of the 32-byte (8-word) instance\n // layout; only the low 29 bits address the transform buffer row - the\n // diagonal-flip flag (bit 29) is orientation, not a row index.\n const row = words[start + i * wordsPerInstance + 7]! & TILE_ROW_MASK;\n\n if (row < range.min) {\n range.min = row;\n }\n\n if (row > range.max) {\n range.max = row;\n }\n }\n }\n\n /** @internal See {@link WebGl2RetainedBatchReplayer._rebaseRetainedNodeIndices} (group-local indices). */\n public _rebaseRetainedNodeIndices(payload: WebGl2RetainedBatchPayload, base: number): void {\n const words = payload.bundle.instanceWords;\n const start = payload.byteOffset / Uint32Array.BYTES_PER_ELEMENT;\n\n for (let i = 0; i < payload.instanceCount; i++) {\n const index = start + i * wordsPerInstance + 7;\n // In-bounds: see the scan above. Rebase ONLY the row field; the\n // diagonal-flip bit must survive untouched or tile orientation corrupts.\n const word = words[index]!;\n const diagonal = word & TILE_DIAGONAL_BIT;\n const row = word & TILE_ROW_MASK;\n\n words[index] = (diagonal | ((row - base) & TILE_ROW_MASK)) >>> 0;\n }\n }\n\n /**\n * Point the batch VAO's per-instance attributes at the bundle's persistent\n * instance buffer, based at the batch's byte offset (WebGL2 has no\n * baseInstance, hence one small VAO per recorded batch). Same attribute\n * set/locations as the live VAO in {@link onConnect}.\n * @internal\n */\n public _configureRetainedVao(payload: WebGl2RetainedBatchPayload): void {\n const gl = this.getBackend().context;\n const buffer = payload.bundle.instanceBuffer;\n const vao = payload.vao;\n\n if (buffer === null || vao === null) {\n throw new Error('WebGl2TileChunkRenderer: retained batch VAO configuration requires an uploaded bundle.');\n }\n\n const base = payload.byteOffset;\n\n vao\n .addAttribute(buffer, this._shader.getAttribute('a_quadBounds'), gl.FLOAT, false, instanceStrideBytes, base + 0, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_uvBounds'), gl.UNSIGNED_SHORT, true, instanceStrideBytes, base + 16, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_color'), gl.UNSIGNED_BYTE, true, instanceStrideBytes, base + 24, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_tileWord'), gl.UNSIGNED_INT, false, instanceStrideBytes, base + 28, true, 1);\n }\n\n /**\n * Replay one recorded batch: all STATE is resolved live - blend mode via\n * the backend's dedup, `u_projection`/`u_group` from the live view + live\n * composed group matrix (the camera-pan / group-move win), the single\n * tileset texture bound to unit 0 by recorded slot order - and only the\n * DATA is cached: the instance bytes in the bundle buffer (bound through\n * the per-batch VAO) and the group-owned transform texture on the shared\n * transform unit. The backend hook flushed any pending live batch before\n * dispatching here and bumps the stats from the instruction descriptor.\n * @internal\n */\n public _replayRetainedBatch(payload: WebGl2RetainedBatchPayload): void {\n const backend = this.getBackendOrNull();\n const vao = payload.vao;\n const transformTexture = payload.bundle.transformTexture;\n\n if (backend === null || vao === null || transformTexture === null) {\n // Defensive: a bundle in this state never validates (generation), so a\n // spliced replay cannot reach here; skip rather than crash mid-frame.\n return;\n }\n\n if (payload.blendMode !== this._currentBlendMode) {\n this._currentBlendMode = payload.blendMode;\n }\n\n backend.setBlendMode(payload.blendMode);\n this._stageViewUniforms(backend);\n\n const textures = payload.textures;\n\n for (let i = 0; i < textures.length; i++) {\n // In-bounds: i < textures.length.\n backend.bindTexture(textures[i]!, i);\n }\n\n // Keep the live path's redundant-bind-skip cache coherent (a live\n // TileChunkNode outside the group and the replayed batches inside it\n // share this one renderer instance): unit 0 now actually holds this\n // batch's texture, bypassing render()'s `_currentTexture` check, so the\n // NEXT live draw must see the true bound texture or it wrongly skips its\n // own bind and renders with this batch's leftover texture.\n if (textures.length > 0) {\n this._currentTexture = textures[0] as Texture;\n }\n\n this._shader.getUniform('u_texture').setValue(this._baseTextureUnitScratch);\n\n // The group-owned transform store replaces the shared frame buffer on the\n // SAME unit/sampler - zero GLSL changes. The next live flush re-binds the\n // shared texture through bindTransformBufferTexture.\n backend.bindTexture(transformTexture, transformTextureUnit);\n this._shader.getUniform('u_transforms').setValue(this._transformUnitScratch);\n\n this._shader.sync();\n backend.bindVertexArrayObject(vao);\n vao.drawInstanced(4, 0, payload.instanceCount, RenderingPrimitives.TriangleStrip);\n }\n\n protected onConnect(backend: WebGl2Backend): void {\n const gl = backend.context;\n\n this._shader.connect(createWebGl2ShaderProgram(gl));\n this._connection = this._createConnection(gl);\n this._instanceBuffer = new WebGl2RenderBuffer(BufferTypes.ArrayBuffer, this._instanceData, BufferUsage.DynamicDraw).connect(\n this._createBufferRuntime(this._connection),\n );\n this._shader.sync();\n\n this._vao = new WebGl2VertexArrayObject(RenderingPrimitives.TriangleStrip)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_quadBounds'), gl.FLOAT, false, instanceStrideBytes, 0, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_uvBounds'), gl.UNSIGNED_SHORT, true, instanceStrideBytes, 16, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_color'), gl.UNSIGNED_BYTE, true, instanceStrideBytes, 24, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_tileWord'), gl.UNSIGNED_INT, false, instanceStrideBytes, 28, true, 1)\n .connect(this._createVaoRuntime(this._connection));\n }\n\n protected onDisconnect(): void {\n this._shader.disconnect();\n this._instanceBuffer?.destroy();\n this._instanceBuffer = null;\n this._vao?.destroy();\n this._vao = null;\n this._connection = null;\n this._currentBlendMode = null;\n this._currentTexture = null;\n this._currentView = null;\n this._currentViewId = -1;\n this._hasWrittenGroup = false;\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._nodeBooked = false;\n }\n\n public destroy(): void {\n this.disconnect();\n this._shader.destroy();\n }\n\n private _createConnection(gl: WebGL2RenderingContext): TileRendererConnection {\n const vaoHandle = gl.createVertexArray();\n\n if (vaoHandle === null) {\n throw new Error('WebGl2TileChunkRenderer: could not create vertex array object.');\n }\n\n return { gl, buffers: new Map(), vaoHandle };\n }\n\n private _createBufferRuntime(connection: TileRendererConnection): WebGl2RenderBufferRuntime {\n const handle = connection.gl.createBuffer();\n\n if (handle === null) {\n throw new Error('WebGl2TileChunkRenderer: could not create render buffer.');\n }\n\n return {\n bind: (buffer): void => {\n connection.gl.bindBuffer(buffer.type, handle);\n },\n upload: (buffer, offset): void => {\n const gl = connection.gl;\n const state = connection.buffers.get(buffer);\n\n gl.bindBuffer(buffer.type, handle);\n\n if (state && state.dataByteLength >= buffer.uploadByteLength) {\n uploadBufferRange(gl, buffer, offset);\n state.dataByteLength = buffer.uploadByteLength;\n } else {\n uploadBufferStore(gl, buffer);\n connection.buffers.set(buffer, { handle, dataByteLength: buffer.uploadByteLength });\n }\n },\n destroy: (buffer): void => {\n connection.gl.deleteBuffer(handle);\n connection.buffers.delete(buffer);\n buffer.disconnect();\n },\n };\n }\n\n private _createVaoRuntime(connection: TileRendererConnection): WebGl2VertexArrayObjectRuntime {\n let appliedVersion = -1;\n\n return {\n bind: (vao): void => {\n const gl = connection.gl;\n\n gl.bindVertexArray(connection.vaoHandle);\n\n if (appliedVersion !== vao.version) {\n let lastBuffer: WebGl2RenderBuffer | null = null;\n\n for (const attribute of vao.attributes) {\n if (lastBuffer !== attribute.buffer) {\n attribute.buffer.bind();\n lastBuffer = attribute.buffer;\n }\n\n if (attribute.integer) {\n gl.vertexAttribIPointer(attribute.location, attribute.size, attribute.type, attribute.stride, attribute.start);\n } else {\n gl.vertexAttribPointer(attribute.location, attribute.size, attribute.type, attribute.normalized, attribute.stride, attribute.start);\n }\n\n gl.enableVertexAttribArray(attribute.location);\n gl.vertexAttribDivisor(attribute.location, attribute.divisor);\n }\n\n appliedVersion = vao.version;\n }\n },\n unbind: (): void => {\n connection.gl.bindVertexArray(null);\n },\n draw: (_vao, size, start, type): void => {\n connection.gl.drawArrays(type, start, size);\n },\n drawInstanced: (_vao, count, start, instanceCount, type): void => {\n connection.gl.drawArraysInstanced(type, start, count, instanceCount);\n },\n destroy: (vao): void => {\n connection.gl.deleteVertexArray(connection.vaoHandle);\n vao.disconnect();\n },\n };\n }\n}\n"],"mappings":";;;;;;AAoCA,MAAM,sBAAsB;AAC5B,MAAM,mBAAmB,sBAAsB,YAAY;AAC3D,MAAM,uBAAuB;AAC7B,MAAM,oBAAoB,IAAI,aAAa;CAAC;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;AAAC,CAAC;AAEtE,MAAM,mBAAmB,iBAAiBA,sBAAoB;CAAE,aAAa;CAAe,iBAAiB;AAAkB,CAAC;;;;;;;;;AAgBhI,IAAa,0BAAb,cAA6C,uBAA6E;;;;;;;;;;CAUxH,AAAgB,2BAA2B;CAE3C,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,AAAiB,wBAAoC,IAAI,WAAW,CAAC,oBAAoB,CAAC;CAG1F,AAAiB,0BAAsC,IAAI,WAAW,CAAC,CAAC,CAAC;CAGzE,AAAiB,kBAAyD,CAAC,IAAI;CAE/E,AAAQ,aAAa;CACrB,AAAQ,gBAAgB;CAMxB,AAAQ,kBAAkB;CAC1B,AAAQ,cAAc;CACtB,AAAQ,oBAAuC;CAC/C,AAAQ,kBAAkC;CAC1C,AAAQ,eAA4B;CACpC,AAAQ,iBAAiB;CACzB,AAAQ,mBAAmB;CAC3B,AAAiB,oCAAoB,IAAI,aAAa,CAAC;CAEvD,AAAQ,kBAA6C;CACrD,AAAQ,OAAuC;CAC/C,AAAQ,cAA6C;CAErD,AAAO,YAAY,WAAmB;EACpC,MAAM;EAEN,KAAK,aAAa;EAClB,KAAK,UAAU,IAAI,OAAO,kBAAkBC,kBAAkB;EAC9D,KAAK,gCAAgB,IAAI,YAAY,YAAY,mBAAmB;EACpE,KAAK,mBAAmB,IAAI,aAAa,KAAK,aAAa;EAC3D,KAAK,kBAAkB,IAAI,YAAY,KAAK,aAAa;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MAC7C,GAAG,oBAAoB,UAAU,UAAU,UAAU,OAAO;KAC9D;KAEA,iBAAiB,IAAI;IACvB;GACF;GACA,cAAoB;IAClB,WAAW,GAAG,gBAAgB,IAAI;GACpC;GACA,OAAO,MAAM,MAAM,OAAO,SAAe;IACvC,WAAW,GAAG,WAAW,MAAM,OAAO,IAAI;GAC5C;GACA,gBAAgB,MAAM,OAAO,OAAO,eAAe,SAAe;IAChE,WAAW,GAAG,oBAAoB,MAAM,OAAO,OAAO,aAAa;GACrE;GACA,UAAU,QAAc;IACtB,WAAW,GAAG,kBAAkB,WAAW,SAAS;IACpD,IAAI,WAAW;GACjB;EACF;CACF;AACF"}
1
+ {"version":3,"file":"WebGl2TileChunkRenderer.js","names":["tileVertexTemplate","tileFragmentSource"],"sources":["../../../src/webgl2/WebGl2TileChunkRenderer.ts"],"sourcesContent":["import type {\n RenderTexture,\n Texture,\n View,\n WebGl2Backend,\n WebGl2RenderBufferRuntime,\n WebGl2RetainedBatchPayload,\n WebGl2RetainedBatchReplayer,\n WebGl2RetainedNodeIndexRange,\n WebGl2VertexArrayObjectRuntime,\n} from '@codexo/exojs/renderer-sdk';\nimport {\n AbstractWebGl2Renderer,\n BlendModes,\n BufferTypes,\n BufferUsage,\n createWebGl2ShaderProgram,\n fillShaderSource,\n packedGroupChanged,\n RenderingPrimitives,\n Shader,\n uploadBufferRange,\n uploadBufferStore,\n WebGl2RenderBuffer,\n WebGl2VertexArrayObject,\n} from '@codexo/exojs/renderer-sdk';\n\nimport type { TileQuad } from '../chunkGeometry';\nimport type { TileChunkNode } from '../TileChunkNode';\nimport { TILE_DIAGONAL_BIT, TILE_ROW_MASK } from '../tileWord';\nimport tileFragmentSource from './shaders/tile-chunk.frag';\nimport tileVertexTemplate from './shaders/tile-chunk.vert';\n\n// One instance = one tile quad. Layout matches the engine's instanced-quad\n// convention (NineSlice/Repeating): float32x4 local rect, unorm16x4 UV bounds,\n// unorm8x4 tint, uint32 tile word (transform row + diagonal bit).\nconst instanceStrideBytes = 32;\nconst wordsPerInstance = instanceStrideBytes / Uint32Array.BYTES_PER_ELEMENT;\nconst transformTextureUnit = 1;\nconst identityGroupMat3 = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);\n\nconst tileVertexSource = fillShaderSource(tileVertexTemplate, { tileRowMask: TILE_ROW_MASK, tileDiagonalBit: TILE_DIAGONAL_BIT });\n\ninterface TileRendererConnection {\n readonly gl: WebGL2RenderingContext;\n readonly buffers: Map<WebGl2RenderBuffer, { handle: WebGLBuffer; dataByteLength: number }>;\n readonly vaoHandle: WebGLVertexArrayObject;\n}\n\n/**\n * Instanced WebGL2 renderer for {@link TileChunkNode}. Each tile is one\n * instanced quad; tiles are batched by `(shader, tileset texture)` and one\n * `drawArraysInstanced` is issued per batch. Per-chunk transforms ride on the\n * shared transform buffer (one row per chunk node), so the chunk geometry is\n * orientation-neutral and never re-uploaded for a camera pan.\n * @internal\n */\nexport class WebGl2TileChunkRenderer extends AbstractWebGl2Renderer<TileChunkNode> implements WebGl2RetainedBatchReplayer {\n /**\n * Retained-batch capability opt-in: a tile chunk's per-flush\n * instanced batches (fixed 32-byte layout, tile word at word 7) can be\n * recorded into a group's instruction set and replayed from group-owned\n * resources. Pixel-snapped draws are excluded by the collect-time\n * recordability predicate (and belt-and-braces poisoning in {@link render});\n * tile chunks have no custom-material path to exclude.\n * @internal\n */\n public readonly _supportsRetainedBatches = true;\n\n private readonly _shader: Shader;\n private readonly _batchSize: number;\n private readonly _instanceData: ArrayBuffer;\n private readonly _instanceFloat32: Float32Array;\n private readonly _instanceUint32: Uint32Array;\n\n private readonly _transformUnitScratch: Int32Array = new Int32Array([transformTextureUnit]);\n // Pinned unit index for the single tileset texture sampler (unit 0), reused\n // by the live flush and retained replay so both stay allocation-free.\n private readonly _baseTextureUnitScratch: Int32Array = new Int32Array([0]);\n // Reused single-slot texture list handed to the backend at record time; a\n // tile chunk batch always binds exactly one tileset texture (slot 0).\n private readonly _recordTextures: Array<Texture | RenderTexture | null> = [null];\n\n private _quadIndex = 0;\n private _maxNodeIndex = 0;\n // Chunk nodes booked against the PENDING batch, and whether the chunk being\n // rendered right now has already been booked. One chunk emits one tile\n // instance per tile, so the recorded batch's `submittedNodes` contribution is\n // this count and not `_quadIndex`. A chunk whose pages/runs span several\n // batches is booked once, against the batch its first run lands in.\n private _batchNodeCount = 0;\n private _nodeBooked = false;\n // Blend mode and tileset texture of the batch currently accumulating, used to\n // detect a batch break. Neither is a mirror of backend state: `flush()`\n // establishes both at the draw (see {@link _resetBatchState}).\n private _currentBlendMode: BlendModes | null = null;\n private _currentTexture: Texture | null = null;\n private _currentView: View | null = null;\n private _currentViewId = -1;\n private _hasWrittenGroup = false;\n private readonly _writtenGroupData = new Float32Array(9);\n\n private _instanceBuffer: WebGl2RenderBuffer | null = null;\n private _vao: WebGl2VertexArrayObject | null = null;\n private _connection: TileRendererConnection | null = null;\n\n public constructor(batchSize: number) {\n super();\n\n this._batchSize = batchSize;\n this._shader = new Shader(tileVertexSource, tileFragmentSource);\n this._instanceData = new ArrayBuffer(batchSize * instanceStrideBytes);\n this._instanceFloat32 = new Float32Array(this._instanceData);\n this._instanceUint32 = new Uint32Array(this._instanceData);\n }\n\n public render(node: TileChunkNode): void {\n const pages = node.pages;\n\n this._nodeBooked = false;\n\n if (pages.length === 0) {\n return;\n }\n\n const backend = this.getBackend();\n\n const blendMode = node.blendMode;\n const tintRgba = node.tint.toRgba8();\n\n const command = backend.activeDrawCommand;\n const nodeIndex = command !== null ? command.nodeIndex : backend._pushTransform(node);\n\n for (const page of pages) {\n this._renderPage(page.texture, page.quads, blendMode, tintRgba, nodeIndex);\n }\n }\n\n private _renderPage(texture: Texture, quads: readonly TileQuad[], blendMode: BlendModes, tintRgba: number, nodeIndex: number): void {\n if (quads.length === 0) {\n return;\n }\n\n const textureChanged = this._currentTexture !== null && texture !== this._currentTexture;\n const blendModeChanged = this._currentBlendMode !== null && blendMode !== this._currentBlendMode;\n\n if (this._quadIndex > 0 && (blendModeChanged || textureChanged || this._quadIndex + quads.length > this._batchSize)) {\n this.flush();\n }\n\n this._currentBlendMode = blendMode;\n this._currentTexture = texture;\n\n const flipY = texture.flipY;\n\n // A chunk page may hold more tiles than the fixed batch buffer; write in\n // batch-sized runs, flushing (and re-establishing state) between runs.\n let offset = 0;\n\n while (offset < quads.length) {\n const remaining = quads.length - offset;\n const runSize = Math.min(remaining, this._batchSize);\n\n this._writeRun(quads, offset, runSize, flipY, tintRgba, nodeIndex);\n\n offset += runSize;\n\n if (offset < quads.length) {\n this.flush();\n this._currentBlendMode = blendMode;\n this._currentTexture = texture;\n }\n }\n }\n\n private _writeRun(quads: readonly TileQuad[], offset: number, count: number, flipY: boolean, tintRgba: number, nodeIndex: number): void {\n const f32 = this._instanceFloat32;\n const u32 = this._instanceUint32;\n const baseWord = nodeIndex & TILE_ROW_MASK;\n\n // Booked here rather than in render(): any flush the page/run loops trigger\n // has already happened, so the chunk lands on the batch that actually holds\n // its first tile.\n if (!this._nodeBooked) {\n this._nodeBooked = true;\n this._batchNodeCount++;\n }\n\n for (let i = 0; i < count; i++) {\n const q = quads[offset + i]!;\n const idx = this._quadIndex * wordsPerInstance;\n\n f32[idx + 0] = q.x0;\n f32[idx + 1] = q.y0;\n f32[idx + 2] = q.x1;\n f32[idx + 3] = q.y1;\n\n // Bake flipX/flipY into the UV corner ordering; the diagonal axis swap is\n // resolved in the shader. Texture flipY (uploaded-flipped atlases) is an\n // additional vertical swap that composes with the tile flipY.\n const flipX = (q.orient & 1) !== 0;\n const tileFlipY = (q.orient & 2) !== 0;\n const diagonal = (q.orient & 4) !== 0;\n\n const uA = flipX ? q.u1 : q.u0;\n const uB = flipX ? q.u0 : q.u1;\n let vA = tileFlipY ? q.v1 : q.v0;\n let vB = tileFlipY ? q.v0 : q.v1;\n\n if (flipY) {\n const swap = vA;\n vA = vB;\n vB = swap;\n }\n\n const uMin = (uA * 0xffff) & 0xffff;\n const vMin = (vA * 0xffff) & 0xffff;\n const uMax = (uB * 0xffff) & 0xffff;\n const vMax = (vB * 0xffff) & 0xffff;\n\n u32[idx + 4] = uMin | (vMin << 16);\n u32[idx + 5] = uMax | (vMax << 16);\n u32[idx + 6] = tintRgba;\n u32[idx + 7] = (diagonal ? baseWord | TILE_DIAGONAL_BIT : baseWord) >>> 0;\n\n this._quadIndex++;\n }\n\n if (nodeIndex > this._maxNodeIndex) {\n this._maxNodeIndex = nodeIndex;\n }\n }\n\n public flush(): void {\n const backend = this.getBackendOrNull();\n const instanceBuffer = this._instanceBuffer;\n const vao = this._vao;\n\n if (this._quadIndex === 0 || backend === null || instanceBuffer === null || vao === null) {\n this._resetBatchState();\n return;\n }\n\n this._stageViewUniforms(backend);\n\n // Blend state and texture unit 0 are global and shared with every other\n // renderer - a sprite drawn between two tile layers binds its own texture\n // to the same unit - so this batch establishes both at its own draw. The\n // backend collapses a redundant call.\n if (this._currentTexture !== null) {\n backend.bindTexture(this._currentTexture, 0);\n this._shader.getUniform('u_texture').setValue(this._baseTextureUnitScratch);\n }\n\n backend.bindTransformBufferTexture(transformTextureUnit, this._maxNodeIndex + 1);\n this._shader.getUniform('u_transforms').setValue(this._transformUnitScratch);\n\n this._shader.sync();\n backend.bindVertexArrayObject(vao);\n instanceBuffer.upload(this._instanceFloat32, 0, this._quadIndex * wordsPerInstance);\n backend.setBlendMode(this._currentBlendMode ?? BlendModes.Normal);\n vao.drawInstanced(4, 0, this._quadIndex, RenderingPrimitives.TriangleStrip);\n backend.stats.batches++;\n backend.stats.drawCalls++;\n\n // Retained recording: while a capture window is open, hand the\n // exact packed instance words of this flush to the backend - byte-\n // identical to what just drew. A batch always binds a single tileset\n // texture (slot 0); a pixel-snapped node already poisoned the capture in\n // render().\n if (backend._isRetainedCapturing && this._currentTexture !== null) {\n this._recordTextures[0] = this._currentTexture;\n backend._recordRetainedBatch(\n this,\n this._instanceUint32.subarray(0, this._quadIndex * wordsPerInstance),\n this._quadIndex,\n this._currentBlendMode ?? BlendModes.Normal,\n this._recordTextures,\n 1,\n null,\n null,\n this._batchNodeCount,\n );\n }\n\n this._resetBatchState();\n }\n\n /**\n * Scope the batch memos to one batch: they describe what is accumulating, not\n * what GL holds, so a memo that outlived its flush would let the next batch\n * skip establishing state another renderer has since changed.\n */\n private _resetBatchState(): void {\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._currentBlendMode = null;\n this._currentTexture = null;\n }\n\n /**\n * Stage `u_projection` (live view) and `u_group` (live composed group\n * matrix) on the shader, guarded by cached view/group stamps. Shared by the\n * live flush path and retained-batch replay - replay resolves exactly the\n * same live state a slow-path flush would.\n */\n private _stageViewUniforms(backend: WebGl2Backend): void {\n const view = backend.view;\n\n if (this._currentView !== view || this._currentViewId !== view.updateId) {\n this._currentView = view;\n this._currentViewId = view.updateId;\n this._shader.getUniform('u_projection').setValue(view.getTransform().toArray(false));\n }\n\n const groupTransform = backend.renderGroupTransform;\n const groupData = groupTransform !== null ? groupTransform.toArray(false) : identityGroupMat3;\n\n if (!this._hasWrittenGroup || packedGroupChanged(groupData, this._writtenGroupData, 0)) {\n this._shader.getUniform('u_group').setValue(groupData);\n this._writtenGroupData.set(groupData);\n this._hasWrittenGroup = true;\n }\n\n backend._stageViewportUniform(this._shader);\n }\n\n // ── Retained-batch record/replay ──────────────────────────────────────────\n // The bundle stores raw instance bytes; this renderer owns the 32-byte\n // layout (tile word at word 7: transform row in bits 0..28, diagonal flip in\n // bit 29), so the layout-aware finalize steps (node-index scan/rebase, VAO\n // attribute wiring) and the replay dispatch live here - mirroring\n // WebGl2NineSliceSpriteRenderer's seam.\n\n /** @internal See {@link WebGl2RetainedBatchReplayer._scanRetainedNodeIndexRange}. */\n public _scanRetainedNodeIndexRange(payload: WebGl2RetainedBatchPayload, range: WebGl2RetainedNodeIndexRange): void {\n const words = payload.bundle.instanceWords;\n const start = payload.byteOffset / Uint32Array.BYTES_PER_ELEMENT;\n\n for (let i = 0; i < payload.instanceCount; i++) {\n // In-bounds: the payload's word range was appended to the bundle store.\n // The tile word is the last word of the 32-byte (8-word) instance\n // layout; only the low 29 bits address the transform buffer row - the\n // diagonal-flip flag (bit 29) is orientation, not a row index.\n const row = words[start + i * wordsPerInstance + 7]! & TILE_ROW_MASK;\n\n if (row < range.min) {\n range.min = row;\n }\n\n if (row > range.max) {\n range.max = row;\n }\n }\n }\n\n /** @internal See {@link WebGl2RetainedBatchReplayer._rebaseRetainedNodeIndices} (group-local indices). */\n public _rebaseRetainedNodeIndices(payload: WebGl2RetainedBatchPayload, base: number): void {\n const words = payload.bundle.instanceWords;\n const start = payload.byteOffset / Uint32Array.BYTES_PER_ELEMENT;\n\n for (let i = 0; i < payload.instanceCount; i++) {\n const index = start + i * wordsPerInstance + 7;\n // In-bounds: see the scan above. Rebase ONLY the row field; the\n // diagonal-flip bit must survive untouched or tile orientation corrupts.\n const word = words[index]!;\n const diagonal = word & TILE_DIAGONAL_BIT;\n const row = word & TILE_ROW_MASK;\n\n words[index] = (diagonal | ((row - base) & TILE_ROW_MASK)) >>> 0;\n }\n }\n\n /**\n * Point the batch VAO's per-instance attributes at the bundle's persistent\n * instance buffer, based at the batch's byte offset (WebGL2 has no\n * baseInstance, hence one small VAO per recorded batch). Same attribute\n * set/locations as the live VAO in {@link onConnect}.\n * @internal\n */\n public _configureRetainedVao(payload: WebGl2RetainedBatchPayload): void {\n const gl = this.getBackend().context;\n const buffer = payload.bundle.instanceBuffer;\n const vao = payload.vao;\n\n if (buffer === null || vao === null) {\n throw new Error('WebGl2TileChunkRenderer: retained batch VAO configuration requires an uploaded bundle.');\n }\n\n const base = payload.byteOffset;\n\n vao\n .addAttribute(buffer, this._shader.getAttribute('a_quadBounds'), gl.FLOAT, false, instanceStrideBytes, base + 0, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_uvBounds'), gl.UNSIGNED_SHORT, true, instanceStrideBytes, base + 16, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_color'), gl.UNSIGNED_BYTE, true, instanceStrideBytes, base + 24, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_tileWord'), gl.UNSIGNED_INT, false, instanceStrideBytes, base + 28, true, 1);\n }\n\n /**\n * Replay one recorded batch: all STATE is resolved live - blend mode via\n * the backend's dedup, `u_projection`/`u_group` from the live view + live\n * composed group matrix (the camera-pan / group-move win), the single\n * tileset texture bound to unit 0 by recorded slot order - and only the\n * DATA is cached: the instance bytes in the bundle buffer (bound through\n * the per-batch VAO) and the group-owned transform texture on the shared\n * transform unit. The backend hook flushed any pending live batch before\n * dispatching here and bumps the stats from the instruction descriptor.\n * @internal\n */\n public _replayRetainedBatch(payload: WebGl2RetainedBatchPayload): void {\n const backend = this.getBackendOrNull();\n const vao = payload.vao;\n const transformTexture = payload.bundle.transformTexture;\n\n if (backend === null || vao === null || transformTexture === null) {\n // Defensive: a bundle in this state never validates (generation), so a\n // spliced replay cannot reach here; skip rather than crash mid-frame.\n return;\n }\n\n backend.setBlendMode(payload.blendMode);\n this._stageViewUniforms(backend);\n\n const textures = payload.textures;\n\n for (let i = 0; i < textures.length; i++) {\n // In-bounds: i < textures.length.\n backend.bindTexture(textures[i]!, i);\n }\n\n this._shader.getUniform('u_texture').setValue(this._baseTextureUnitScratch);\n\n // The group-owned transform store replaces the shared frame buffer on the\n // SAME unit/sampler - zero GLSL changes. The next live flush re-binds the\n // shared texture through bindTransformBufferTexture.\n backend.bindTexture(transformTexture, transformTextureUnit);\n this._shader.getUniform('u_transforms').setValue(this._transformUnitScratch);\n\n this._shader.sync();\n backend.bindVertexArrayObject(vao);\n vao.drawInstanced(4, 0, payload.instanceCount, RenderingPrimitives.TriangleStrip);\n }\n\n protected onConnect(backend: WebGl2Backend): void {\n const gl = backend.context;\n\n this._shader.connect(createWebGl2ShaderProgram(gl));\n this._connection = this._createConnection(gl);\n this._instanceBuffer = new WebGl2RenderBuffer(BufferTypes.ArrayBuffer, this._instanceData, BufferUsage.DynamicDraw).connect(\n this._createBufferRuntime(this._connection),\n );\n this._shader.sync();\n\n this._vao = new WebGl2VertexArrayObject(RenderingPrimitives.TriangleStrip)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_quadBounds'), gl.FLOAT, false, instanceStrideBytes, 0, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_uvBounds'), gl.UNSIGNED_SHORT, true, instanceStrideBytes, 16, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_color'), gl.UNSIGNED_BYTE, true, instanceStrideBytes, 24, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_tileWord'), gl.UNSIGNED_INT, false, instanceStrideBytes, 28, true, 1)\n .connect(this._createVaoRuntime(this._connection));\n }\n\n protected onDisconnect(): void {\n this._shader.disconnect();\n this._instanceBuffer?.destroy();\n this._instanceBuffer = null;\n this._vao?.destroy();\n this._vao = null;\n this._connection = null;\n this._currentBlendMode = null;\n this._currentTexture = null;\n this._currentView = null;\n this._currentViewId = -1;\n this._hasWrittenGroup = false;\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._nodeBooked = false;\n }\n\n public destroy(): void {\n this.disconnect();\n this._shader.destroy();\n }\n\n private _createConnection(gl: WebGL2RenderingContext): TileRendererConnection {\n const vaoHandle = gl.createVertexArray();\n\n if (vaoHandle === null) {\n throw new Error('WebGl2TileChunkRenderer: could not create vertex array object.');\n }\n\n return { gl, buffers: new Map(), vaoHandle };\n }\n\n private _createBufferRuntime(connection: TileRendererConnection): WebGl2RenderBufferRuntime {\n const handle = connection.gl.createBuffer();\n\n if (handle === null) {\n throw new Error('WebGl2TileChunkRenderer: could not create render buffer.');\n }\n\n return {\n bind: (buffer): void => {\n connection.gl.bindBuffer(buffer.type, handle);\n },\n upload: (buffer, offset): void => {\n const gl = connection.gl;\n const state = connection.buffers.get(buffer);\n\n gl.bindBuffer(buffer.type, handle);\n\n if (state && state.dataByteLength >= buffer.uploadByteLength) {\n uploadBufferRange(gl, buffer, offset);\n state.dataByteLength = buffer.uploadByteLength;\n } else {\n uploadBufferStore(gl, buffer);\n connection.buffers.set(buffer, { handle, dataByteLength: buffer.uploadByteLength });\n }\n },\n destroy: (buffer): void => {\n connection.gl.deleteBuffer(handle);\n connection.buffers.delete(buffer);\n buffer.disconnect();\n },\n };\n }\n\n private _createVaoRuntime(connection: TileRendererConnection): WebGl2VertexArrayObjectRuntime {\n let appliedVersion = -1;\n\n return {\n bind: (vao): void => {\n const gl = connection.gl;\n\n gl.bindVertexArray(connection.vaoHandle);\n\n if (appliedVersion !== vao.version) {\n let lastBuffer: WebGl2RenderBuffer | null = null;\n\n for (const attribute of vao.attributes) {\n if (lastBuffer !== attribute.buffer) {\n attribute.buffer.bind();\n lastBuffer = attribute.buffer;\n }\n\n if (attribute.integer) {\n gl.vertexAttribIPointer(attribute.location, attribute.size, attribute.type, attribute.stride, attribute.start);\n } else {\n gl.vertexAttribPointer(attribute.location, attribute.size, attribute.type, attribute.normalized, attribute.stride, attribute.start);\n }\n\n gl.enableVertexAttribArray(attribute.location);\n gl.vertexAttribDivisor(attribute.location, attribute.divisor);\n }\n\n appliedVersion = vao.version;\n }\n },\n unbind: (): void => {\n connection.gl.bindVertexArray(null);\n },\n draw: (_vao, size, start, type): void => {\n connection.gl.drawArrays(type, start, size);\n },\n drawInstanced: (_vao, count, start, instanceCount, type): void => {\n connection.gl.drawArraysInstanced(type, start, count, instanceCount);\n },\n destroy: (vao): void => {\n connection.gl.deleteVertexArray(connection.vaoHandle);\n vao.disconnect();\n },\n };\n }\n}\n"],"mappings":";;;;;;AAoCA,MAAM,sBAAsB;AAC5B,MAAM,mBAAmB,sBAAsB,YAAY;AAC3D,MAAM,uBAAuB;AAC7B,MAAM,oBAAoB,IAAI,aAAa;CAAC;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;AAAC,CAAC;AAEtE,MAAM,mBAAmB,iBAAiBA,sBAAoB;CAAE,aAAa;CAAe,iBAAiB;AAAkB,CAAC;;;;;;;;;AAgBhI,IAA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ACA,UAAU,WAAiB;IACzB,WAAW,GAAG,aAAa,MAAM;IACjC,WAAW,QAAQ,OAAO,MAAM;IAChC,OAAO,WAAW;GACpB;EACF;CACF;CAEA,AAAQ,kBAAkB,YAAoE;EAC5F,IAAI,iBAAiB;EAErB,OAAO;GACL,OAAO,QAAc;IACnB,MAAM,KAAK,WAAW;IAEtB,GAAG,gBAAgB,WAAW,SAAS;IAEvC,IAAI,mBAAmB,IAAI,SAAS;KAClC,IAAI,aAAwC;KAE5C,KAAK,MAAM,aAAa,IAAI,YAAY;MACtC,IAAI,eAAe,UAAU,QAAQ;OACnC,UAAU,OAAO,KAAK;OACtB,aAAa,UAAU;MACzB;MAEA,IAAI,UAAU,SACZ,GAAG,qBAAqB,UAAU,UAAU,UAAU,MAAM,UAAU,MAAM,UAAU,QAAQ,UAAU,KAAK;WAE7G,GAAG,oBAAoB,UAAU,UAAU,UAAU,MAAM,UAAU,MAAM,UAAU,YAAY,UAAU,QAAQ,UAAU,KAAK;MAGpI,GAAG,wBAAwB,UAAU,QAAQ;MAC7C,GAAG,oBAAoB,UAAU,UAAU,UAAU,OAAO;KAC9D;KAEA,iBAAiB,IAAI;IACvB;GACF;GACA,cAAoB;IAClB,WAAW,GAAG,gBAAgB,IAAI;GACpC;GACA,OAAO,MAAM,MAAM,OAAO,SAAe;IACvC,WAAW,GAAG,WAAW,MAAM,OAAO,IAAI;GAC5C;GACA,gBAAgB,MAAM,OAAO,OAAO,eAAe,SAAe;IAChE,WAAW,GAAG,oBAAoB,MAAM,OAAO,OAAO,aAAa;GACrE;GACA,UAAU,QAAc;IACtB,WAAW,GAAG,kBAAkB,WAAW,SAAS;IACpD,IAAI,WAAW;GACjB;EACF;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codexo/exojs-tilemap",
3
- "version": "0.16.1",
3
+ "version": "0.16.2",
4
4
  "description": "Generic, format-independent tilemap runtime for ExoJS.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,7 +29,7 @@
29
29
  "@codexo/exojs": "0.16.x"
30
30
  },
31
31
  "devDependencies": {
32
- "@codexo/exojs": "0.16.1",
32
+ "@codexo/exojs": "0.16.2",
33
33
  "@codexo/exojs-config": "0.0.0"
34
34
  },
35
35
  "license": "MIT",