@codexo/exojs-tilemap 0.16.2 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +28 -75
  2. package/dist/esm/ImageLayerNode.d.ts +6 -4
  3. package/dist/esm/ImageLayerNode.d.ts.map +1 -1
  4. package/dist/esm/ImageLayerNode.js +7 -2
  5. package/dist/esm/ImageLayerNode.js.map +1 -1
  6. package/dist/esm/MapSpawnSession.d.ts +0 -7
  7. package/dist/esm/MapSpawnSession.d.ts.map +1 -1
  8. package/dist/esm/MapWorldRuntime.d.ts +0 -2
  9. package/dist/esm/MapWorldRuntime.d.ts.map +1 -1
  10. package/dist/esm/TileChunk.d.ts +0 -58
  11. package/dist/esm/TileChunk.d.ts.map +1 -1
  12. package/dist/esm/TileChunkNode.d.ts +1 -73
  13. package/dist/esm/TileChunkNode.d.ts.map +1 -1
  14. package/dist/esm/TileChunkNode.js +1 -1
  15. package/dist/esm/TileChunkNode.js.map +1 -1
  16. package/dist/esm/TileLayer.d.ts +0 -63
  17. package/dist/esm/TileLayer.d.ts.map +1 -1
  18. package/dist/esm/TileLayerNode.d.ts +8 -8
  19. package/dist/esm/TileLayerNode.d.ts.map +1 -1
  20. package/dist/esm/TileLayerNode.js +9 -4
  21. package/dist/esm/TileLayerNode.js.map +1 -1
  22. package/dist/esm/TileMapBand.d.ts +0 -33
  23. package/dist/esm/TileMapBand.d.ts.map +1 -1
  24. package/dist/esm/TileMapNode.d.ts +7 -2
  25. package/dist/esm/TileMapNode.d.ts.map +1 -1
  26. package/dist/esm/TileMapNode.js +9 -4
  27. package/dist/esm/TileMapNode.js.map +1 -1
  28. package/dist/esm/TileMapView.d.ts +6 -1
  29. package/dist/esm/TileMapView.d.ts.map +1 -1
  30. package/dist/esm/TileMapView.js +9 -4
  31. package/dist/esm/TileMapView.js.map +1 -1
  32. package/dist/esm/TileSet.d.ts +3 -9
  33. package/dist/esm/TileSet.d.ts.map +1 -1
  34. package/dist/esm/TileSet.js +3 -3
  35. package/dist/esm/TileSet.js.map +1 -1
  36. package/dist/esm/WorkerSampledChunkSource.d.ts +4 -7
  37. package/dist/esm/WorkerSampledChunkSource.d.ts.map +1 -1
  38. package/dist/esm/WorkerSampledChunkSource.js +12 -18
  39. package/dist/esm/WorkerSampledChunkSource.js.map +1 -1
  40. package/dist/esm/chunkGeometry.d.ts +1 -71
  41. package/dist/esm/chunkGeometry.d.ts.map +1 -1
  42. package/dist/esm/nodeBounds.d.ts +1 -19
  43. package/dist/esm/nodeBounds.d.ts.map +1 -1
  44. package/dist/esm/pixelSnap.d.ts +1 -12
  45. package/dist/esm/pixelSnap.d.ts.map +1 -1
  46. package/dist/esm/tileWord.d.ts +1 -11
  47. package/dist/esm/tileWord.d.ts.map +1 -1
  48. package/dist/esm/tilemapExtension.d.ts.map +1 -1
  49. package/dist/esm/tilemapExtension.js +5 -8
  50. package/dist/esm/tilemapExtension.js.map +1 -1
  51. package/dist/esm/tilemapSerializers.d.ts +1 -19
  52. package/dist/esm/tilemapSerializers.d.ts.map +1 -1
  53. package/dist/esm/types.d.ts +0 -6
  54. package/dist/esm/types.d.ts.map +1 -1
  55. package/dist/esm/webgl2/WebGl2TileChunkRenderer.d.ts +1 -92
  56. package/dist/esm/webgl2/WebGl2TileChunkRenderer.d.ts.map +1 -1
  57. package/dist/esm/webgl2/WebGl2TileChunkRenderer.js +13 -13
  58. package/dist/esm/webgl2/WebGl2TileChunkRenderer.js.map +1 -1
  59. package/dist/esm/webgl2/shaders/tile-chunk.frag.js +1 -1
  60. package/dist/esm/webgl2/shaders/tile-chunk.frag.js.map +1 -1
  61. package/dist/esm/webgl2/shaders/tile-chunk.vert.js +1 -1
  62. package/dist/esm/webgl2/shaders/tile-chunk.vert.js.map +1 -1
  63. package/dist/esm/webgpu/WebGpuTileChunkRenderer.d.ts +1 -107
  64. package/dist/esm/webgpu/WebGpuTileChunkRenderer.d.ts.map +1 -1
  65. package/dist/esm/webgpu/WebGpuTileChunkRenderer.js +13 -13
  66. package/dist/esm/webgpu/WebGpuTileChunkRenderer.js.map +1 -1
  67. package/dist/esm/webgpu/shaders/tile-chunk.wgsl.js +1 -1
  68. package/dist/esm/webgpu/shaders/tile-chunk.wgsl.js.map +1 -1
  69. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"TileMapView.js","names":[],"sources":["../../src/TileMapView.ts"],"sourcesContent":["import { PixelSnapMode } from '@codexo/exojs/renderer-sdk';\n\nimport { ImageLayer } from './ImageLayer';\nimport { ImageLayerNode } from './ImageLayerNode';\nimport { assertPixelSnapMode } from './pixelSnap';\nimport type { TileLayer } from './TileLayer';\nimport { TileLayerNode } from './TileLayerNode';\nimport type { TileMap } from './TileMap';\nimport { TileMapBand } from './TileMapBand';\n\n/**\n * A layer selector inside a {@link TileMapBandDefinition}: either a stable\n * layer **id** (`number`) or a **unique** layer **name** (`string`). Selectors\n * resolve across the map's tile **and** image layers. Names that are shared by\n * more than one layer (of either kind) are rejected as ambiguous - reference\n * such layers by id. An id shared by a tile layer and an image layer (possible\n * only in fallback-ordered maps, which never validated cross-kind uniqueness)\n * is equally ambiguous - reference such layers by a unique name.\n * @advanced\n */\nexport type TileLayerSelector = number | string;\n\n/**\n * The layers composing one band, by id or unique name, in any order. Tile and\n * image layers may be freely mixed. Rendering order always follows the map's\n * combined document order ({@link import('./TileMap').TileMap.renderableLayers})\n * regardless of the order listed here - a definition *selects* layers, it never\n * reorders them. The band's name is the key it is registered under in\n * {@link TileMapViewOptions.bands}.\n * @advanced\n */\nexport type TileMapBandDefinition = readonly TileLayerSelector[];\n\n/**\n * Options for a {@link TileMapView}.\n * @advanced\n */\nexport interface TileMapViewOptions {\n /**\n * Named bands, keyed by band name (keys are unique, so duplicate band names\n * cannot occur). Each value lists the layers that compose the band - tile\n * and image layers alike. Layers not listed in any band remain reachable\n * through {@link TileMapView.getLayerNodeById} and friends and are owned\n * directly by the view (no implicit fallback band). The definition is copied\n * and frozen; mutating the caller's object afterwards does not change band\n * assignments.\n *\n * @throws (at construction) on an unknown layer id, an unknown or ambiguous\n * layer name, a cross-kind ambiguous layer id, a layer listed twice within\n * one band, or a layer assigned to more than one band.\n */\n readonly bands?: Readonly<Record<string, TileMapBandDefinition>>;\n /**\n * Whether the generated {@link TileLayerNode}s' chunks participate in\n * per-chunk view culling. Forwarded to every layer node. Default `true`.\n */\n readonly cullable?: boolean;\n}\n\ninterface ResolvedBandDef {\n readonly name: string;\n readonly selectors: TileMapBandDefinition;\n}\n\n/**\n * Groups a {@link TileMap}'s layers into independently placeable scene nodes so\n * application actors can be interleaved **between** tile layers.\n *\n * A view produces exactly one canonical {@link TileLayerNode} per map layer\n * (stable identity, map document order) and, optionally, named {@link TileMapBand}s\n * grouping subsets of those nodes. The application parents the bands / layer\n * nodes wherever it wants - typically as siblings of its own actor containers:\n *\n * ```ts\n * const view = map.createView({ bands: { ground: ['background', 'ground'], roof: ['roofs'] } });\n * worldRoot.addChild(view.band('ground'), actors, view.band('roof'));\n * // or without bands:\n * worldRoot.addChild(view.getLayerNodeById(groundId)!, actors, view.getLayerNodeById(roofId)!);\n * ```\n *\n * **Actors are application-owned siblings.** A `TileMapView` never adopts or\n * destroys actors. The view is a helper, not a scene node - it does not own the\n * world container, the {@link TileMap}, the {@link TileLayer}s, or tileset\n * textures.\n *\n * **Ownership:** the view owns its generated layer nodes and bands. A layer\n * assigned to a band is owned by that band; an unbanded layer is owned by the\n * view directly. {@link TileMapView.destroy} destroys every band and layer node\n * (detaching them from their application parents) but leaves actors, the map,\n * its layers, and Loader-owned textures untouched. There is no map-replacement\n * mutation API: to swap maps, destroy the old view, construct a new one, and\n * re-parent its bands - the actor tree is never involved.\n *\n * **Image layers.** A view also produces exactly one canonical\n * {@link ImageLayerNode} per {@link TileMap.imageLayers} entry (stable identity,\n * map document order), reachable through {@link imageLayerNodes},\n * {@link getImageLayerNodeById}, and {@link getImageLayerNodeByName}. Image\n * layers are selectable in {@link TileMapViewOptions.bands} exactly like tile\n * layers: a band member list may mix both kinds, and the band stacks its\n * members by the map's combined document order\n * ({@link import('./TileMap').TileMap.renderableLayers}). A banded image node\n * is owned by its band; an unbanded one is owned by the view directly, and the\n * application parents it wherever the image belongs in draw order - the same\n * way actors are interleaved.\n *\n * @advanced\n */\nexport class TileMapView {\n private readonly _map: TileMap;\n private readonly _cullable: boolean;\n\n /** All canonical tile-layer nodes, in map document order. */\n private readonly _layerNodes: TileLayerNode[] = [];\n /** Tile layer id → its canonical layer node. */\n private readonly _layerNodeById = new Map<number, TileLayerNode>();\n\n /** Bands in definition (insertion) order. */\n private readonly _bands: TileMapBand[] = [];\n /** Band name → band. */\n private readonly _bandByName = new Map<string, TileMapBand>();\n /** Original band definitions (frozen) for re-resolution on refresh. */\n private readonly _bandDefs: ResolvedBandDef[] = [];\n /** Layer node → its owning band (absent = view-owned / unbanded). */\n private readonly _nodeBand = new Map<TileLayerNode | ImageLayerNode, TileMapBand>();\n /** Unbanded tile-layer nodes owned directly by the view, in map document order. */\n private readonly _directLayerNodes: TileLayerNode[] = [];\n\n /** All canonical image layer nodes, in map document order. */\n private readonly _imageLayerNodes: ImageLayerNode[] = [];\n /** Image layer id → its canonical image layer node. */\n private readonly _imageLayerNodeById = new Map<number, ImageLayerNode>();\n\n private _destroyed = false;\n private _pixelSnapMode: PixelSnapMode = PixelSnapMode.None;\n\n /**\n * @param map The runtime map to compose. Referenced, never owned.\n * @param options Band definitions and culling.\n * @throws When a band definition references an unknown/ambiguous layer or\n * assigns a layer twice / to multiple bands.\n */\n public constructor(map: TileMap, options?: TileMapViewOptions) {\n this._map = map;\n this._cullable = options?.cullable ?? true;\n\n for (const layer of map.layers) {\n const node = new TileLayerNode(layer, { cullable: this._cullable });\n\n this._layerNodes.push(node);\n this._layerNodeById.set(layer.id, node);\n }\n\n for (const imageLayer of map.imageLayers) {\n const imageNode = new ImageLayerNode(imageLayer);\n\n this._imageLayerNodes.push(imageNode);\n this._imageLayerNodeById.set(imageLayer.id, imageNode);\n }\n\n if (options?.bands) {\n for (const [name, selectors] of Object.entries(options.bands)) {\n this._defineBand(name, selectors);\n }\n }\n\n for (const node of this._layerNodes) {\n if (!this._nodeBand.has(node)) {\n this._directLayerNodes.push(node);\n }\n }\n }\n\n /** The runtime map this view composes. Referenced, never owned. */\n public get map(): TileMap {\n return this._map;\n }\n\n /** All canonical tile-layer nodes, one per map tile layer, in map document order. */\n public get layers(): readonly TileLayerNode[] {\n return this._layerNodes;\n }\n\n /** The bands, in definition (insertion) order. */\n public get bands(): readonly TileMapBand[] {\n return this._bands;\n }\n\n /** Whether this view has been destroyed. */\n public get destroyed(): boolean {\n return this._destroyed;\n }\n\n /**\n * Render-only pixel-snap mode applied to every layer node this view owns (and\n * forwarded to every chunk drawable, current and rebuilt by\n * {@link refreshLayers}). Snaps tile chunk origins to the active render\n * target's device-pixel grid for crisp tiles; with integer tile pitch the grid\n * stays exact and adjacent chunks cannot drift apart. Purely visual - tile\n * data, layer offsets, chunk revisions, and culling are unchanged. Setting the\n * current value is a no-op; an invalid value throws and leaves the prior mode\n * 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 node of this._layerNodes) {\n node.pixelSnapMode = mode;\n }\n\n for (const node of this._imageLayerNodes) {\n node.pixelSnapMode = mode;\n }\n }\n\n /**\n * The canonical layer node for the **tile** layer with the given **id**, or\n * `undefined`. Tile ids are authoritative and unique - this is the\n * unambiguous lookup. The returned node may be reparented into the caller's\n * own containers; the view still tracks it for refresh and destruction.\n */\n public getLayerNodeById(id: number): TileLayerNode | undefined {\n return this._layerNodeById.get(id);\n }\n\n /**\n * Every canonical tile-layer node whose layer has the given **name**, in map\n * document order. Layer names are not guaranteed unique, so this returns an\n * array (empty when no layer matches). Prefer {@link getLayerNodeById} when\n * you have the id.\n */\n public getLayerNodesByName(name: string): readonly TileLayerNode[] {\n return this._layerNodes.filter(node => node.layer.name === name);\n }\n\n /** All canonical image layer nodes, one per map image layer, in map document order. */\n public get imageLayerNodes(): readonly ImageLayerNode[] {\n return this._imageLayerNodes;\n }\n\n /**\n * The canonical image layer node for the image layer with the given **id**,\n * or `undefined`. Ids are authoritative and unique - this is the unambiguous\n * lookup. The returned node may be reparented into the caller's own\n * containers; the view still tracks it for refresh and destruction.\n */\n public getImageLayerNodeById(id: number): ImageLayerNode | undefined {\n return this._imageLayerNodeById.get(id);\n }\n\n /**\n * The canonical image layer node for the image layer with the given\n * **name**, or `undefined` if no image layer has that name. Prefer\n * {@link getImageLayerNodeById} when you have the id.\n * @throws If more than one image layer shares that name (reference such\n * layers by id instead).\n */\n public getImageLayerNodeByName(name: string): ImageLayerNode | undefined {\n const matches = this._map.imageLayers.filter(layer => layer.name === name);\n\n if (matches.length === 0) {\n return undefined;\n }\n\n if (matches.length > 1) {\n throw new Error(`TileMapView image layer name \"${name}\" is ambiguous ` + `(${matches.length} image layers share it); reference it by id instead.`);\n }\n\n return this._imageLayerNodeById.get(matches[0]!.id);\n }\n\n /**\n * The band registered under `name`.\n * @throws If no band with that name was defined.\n */\n public band(name: string): TileMapBand {\n const band = this._bandByName.get(name);\n\n if (!band) {\n throw new Error(\n `TileMapView has no band named \"${name}\". Defined bands: ${this._bands.length > 0 ? this._bands.map(b => `\"${b.name}\"`).join(', ') : '(none)'}.`,\n );\n }\n\n return band;\n }\n\n /** Whether a band with the given name was defined. */\n public hasBand(name: string): boolean {\n return this._bandByName.has(name);\n }\n\n /**\n * Rebuild the view after **structural** map changes (tile or image layers\n * added to or removed from the map). Ordinary tile edits and chunk\n * creation/removal do NOT need this - those are handled by chunk revisions\n * and {@link TileLayerNode.refresh} respectively.\n *\n * - Removed layers (tile or image): their generated node is detached and\n * destroyed.\n * - Unchanged layers: keep their existing node (stable identity).\n * - Added layers (tile or image): a new node is created and assigned to the\n * first band whose definition selects it (by a currently-unambiguous id or\n * name), otherwise owned directly by the view.\n * - Every band's children are re-ordered to the map's combined document\n * order ({@link import('./TileMap').TileMap.renderableLayers}).\n *\n * Application actors are never touched, and bands keep their placement in the\n * application scene graph.\n *\n * @throws If the view has been destroyed.\n */\n public refreshLayers(): this {\n if (this._destroyed) {\n throw new Error('Cannot refresh a destroyed TileMapView.');\n }\n\n const currentLayers = this._map.layers;\n const currentIds = new Set<number>();\n\n for (const layer of currentLayers) {\n currentIds.add(layer.id);\n }\n\n // 1. Remove nodes whose layer no longer exists.\n for (const node of [...this._layerNodes]) {\n if (!currentIds.has(node.layer.id)) {\n this._removeTileNode(node);\n }\n }\n\n const currentImageLayers = new Set(this._map.imageLayers);\n\n for (const node of [...this._imageLayerNodes]) {\n if (!currentImageLayers.has(node.layer)) {\n this._removeImageNode(node);\n }\n }\n\n // 2. Re-derive the doc-ordered node lists, creating + assigning new nodes.\n const newOrder: TileLayerNode[] = [];\n\n for (const layer of currentLayers) {\n let node = this._layerNodeById.get(layer.id);\n\n if (!node) {\n node = new TileLayerNode(layer, { cullable: this._cullable });\n\n if (this._pixelSnapMode !== PixelSnapMode.None) {\n node.pixelSnapMode = this._pixelSnapMode;\n }\n\n this._layerNodeById.set(layer.id, node);\n this._assignNewNode(node, layer);\n }\n\n newOrder.push(node);\n }\n\n this._layerNodes.length = 0;\n this._layerNodes.push(...newOrder);\n\n const newImageOrder: ImageLayerNode[] = [];\n\n for (const imageLayer of this._map.imageLayers) {\n let node = this._imageLayerNodes.find(candidate => candidate.layer === imageLayer);\n\n if (!node) {\n node = new ImageLayerNode(imageLayer);\n\n if (this._pixelSnapMode !== PixelSnapMode.None) {\n node.pixelSnapMode = this._pixelSnapMode;\n }\n\n this._imageLayerNodeById.set(imageLayer.id, node);\n this._assignNewNode(node, imageLayer);\n }\n\n newImageOrder.push(node);\n }\n\n this._imageLayerNodes.length = 0;\n this._imageLayerNodes.push(...newImageOrder);\n\n // 3. Re-order each band's children to the combined document order. Keyed\n // by layer instance: fallback-ordered maps may share an id across kinds.\n const documentIndex = new Map<TileLayer | ImageLayer, number>();\n\n for (const [index, layer] of this._map.renderableLayers.entries()) {\n documentIndex.set(layer, index);\n }\n\n for (const band of this._bands) {\n band._reorder(documentIndex);\n }\n\n // 4. Rebuild the unbanded set in doc order.\n this._directLayerNodes.length = 0;\n\n for (const node of newOrder) {\n if (!this._nodeBand.has(node)) {\n this._directLayerNodes.push(node);\n }\n }\n\n return this;\n }\n\n /**\n * Destroy the view: every band, generated tile-layer node, and generated\n * {@link ImageLayerNode} is destroyed (and detached from its application\n * parent), freeing cached chunk geometry. Banded nodes are destroyed by\n * their band; unbanded ones by the view directly. Idempotent. Application\n * actors, sibling content, the {@link TileMap}, its {@link TileLayer}s and\n * image layers, and Loader-owned textures all survive.\n */\n public destroy(): void {\n if (this._destroyed) {\n return;\n }\n\n this._destroyed = true;\n\n for (const band of this._bands) {\n band.destroy();\n }\n\n for (const node of this._directLayerNodes) {\n node.parent?.removeChild(node);\n node.destroy();\n }\n\n for (const node of this._imageLayerNodes) {\n if (this._nodeBand.has(node)) {\n continue; // Owned and already destroyed by its band.\n }\n\n node.parent?.removeChild(node);\n node.destroy();\n }\n\n this._bands.length = 0;\n this._bandByName.clear();\n this._bandDefs.length = 0;\n this._directLayerNodes.length = 0;\n this._layerNodes.length = 0;\n this._layerNodeById.clear();\n this._nodeBand.clear();\n this._imageLayerNodes.length = 0;\n this._imageLayerNodeById.clear();\n }\n\n // ── Internals ──────────────────────────────────────────────────────────\n\n /** Resolve one band definition into a {@link TileMapBand} and record it. */\n private _defineBand(name: string, selectors: TileMapBandDefinition): void {\n const members = new Set<TileLayer | ImageLayer>();\n\n for (const selector of selectors) {\n const layer = this._resolveSelector(name, selector);\n\n if (members.has(layer)) {\n throw new Error(`TileMapView band \"${name}\" lists layer ${layer.id} more than once.`);\n }\n\n const existing = this._nodeFor(layer);\n\n if (existing && this._nodeBand.has(existing)) {\n throw new Error(`TileMapView layer ${layer.id} is assigned to multiple bands ` + `(\"${this._nodeBand.get(existing)!.name}\" and \"${name}\").`);\n }\n\n members.add(layer);\n }\n\n // Order members by combined document order (membership selects; doc order\n // renders - tile and image members interleave).\n const orderedNodes: Array<TileLayerNode | ImageLayerNode> = [];\n\n for (const layer of this._map.renderableLayers) {\n if (members.has(layer)) {\n orderedNodes.push(this._nodeFor(layer)!);\n }\n }\n\n const band = new TileMapBand(name, orderedNodes);\n\n for (const node of orderedNodes) {\n this._nodeBand.set(node, band);\n }\n\n this._bands.push(band);\n this._bandByName.set(name, band);\n this._bandDefs.push({ name, selectors: Object.freeze([...selectors]) });\n }\n\n /**\n * Resolve a single selector to a tile or image layer instance, throwing on\n * unknown/ambiguous. Instances (not ids) disambiguate fallback-ordered maps\n * in which a tile layer and an image layer share an id.\n */\n private _resolveSelector(bandName: string, selector: TileLayerSelector): TileLayer | ImageLayer {\n if (typeof selector === 'number') {\n const tileLayer = this._map.getTileLayerById(selector);\n const imageLayer = this._map.imageLayers.find(layer => layer.id === selector);\n\n if (tileLayer && imageLayer) {\n throw new Error(\n `TileMapView band \"${bandName}\": layer id ${selector} is ambiguous ` +\n `(a tile layer and an image layer share it); reference it by a unique name instead.`,\n );\n }\n\n const layer = tileLayer ?? imageLayer;\n\n if (!layer) {\n throw new Error(`TileMapView band \"${bandName}\": no layer with id ${selector} in map \"${this._map.name}\".`);\n }\n\n return layer;\n }\n\n const matches: Array<TileLayer | ImageLayer> = [\n ...this._map.layers.filter(layer => layer.name === selector),\n ...this._map.imageLayers.filter(layer => layer.name === selector),\n ];\n\n if (matches.length === 0) {\n throw new Error(`TileMapView band \"${bandName}\": no layer named \"${selector}\" in map \"${this._map.name}\".`);\n }\n\n if (matches.length > 1) {\n throw new Error(\n `TileMapView band \"${bandName}\": layer name \"${selector}\" is ambiguous ` + `(${matches.length} layers share it); reference it by id instead.`,\n );\n }\n\n return matches[0]!;\n }\n\n /** The canonical node for a tile or image layer instance, if one exists. */\n private _nodeFor(layer: TileLayer | ImageLayer): TileLayerNode | ImageLayerNode | undefined {\n if (layer instanceof ImageLayer) {\n // Instance scan rather than the id map: image ids are not validated\n // unique, and fallback maps may collide with tile ids anyway.\n return this._imageLayerNodes.find(node => node.layer === layer);\n }\n\n return this._layerNodeById.get(layer.id);\n }\n\n /** Assign a freshly created node to the first band that selects its layer. */\n private _assignNewNode(node: TileLayerNode | ImageLayerNode, layer: TileLayer | ImageLayer): void {\n for (const def of this._bandDefs) {\n if (this._definitionSelects(def, layer)) {\n const band = this._bandByName.get(def.name)!;\n\n band._adopt(node);\n this._nodeBand.set(node, band);\n\n return;\n }\n }\n }\n\n /**\n * Whether a band definition selects the given layer - only by a selector\n * that is currently unambiguous (a unique name, or an id not shared across\n * kinds), mirroring {@link _resolveSelector}'s construction-time rules.\n */\n private _definitionSelects(def: ResolvedBandDef, layer: TileLayer | ImageLayer): boolean {\n for (const selector of def.selectors) {\n if (typeof selector === 'number') {\n if (selector === layer.id && !this._isCrossKindId(selector)) {\n return true;\n }\n } else if (selector === layer.name) {\n const sameName =\n this._map.layers.filter(other => other.name === selector).length + this._map.imageLayers.filter(other => other.name === selector).length;\n\n if (sameName === 1) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /** Whether an id currently belongs to both a tile layer and an image layer. */\n private _isCrossKindId(id: number): boolean {\n return this._map.getTileLayerById(id) !== undefined && this._map.imageLayers.some(layer => layer.id === id);\n }\n\n /** Detach + destroy a tile node, dropping it from bands and registries. */\n private _removeTileNode(node: TileLayerNode): void {\n this._releaseFromOwner(node);\n\n node.parent?.removeChild(node);\n this._layerNodeById.delete(node.layer.id);\n\n const orderIndex = this._layerNodes.indexOf(node);\n\n if (orderIndex !== -1) {\n this._layerNodes.splice(orderIndex, 1);\n }\n\n node.destroy();\n }\n\n /** Detach + destroy an image node, dropping it from bands and registries. */\n private _removeImageNode(node: ImageLayerNode): void {\n this._releaseFromOwner(node);\n\n node.parent?.removeChild(node);\n\n if (this._imageLayerNodeById.get(node.layer.id) === node) {\n this._imageLayerNodeById.delete(node.layer.id);\n }\n\n const orderIndex = this._imageLayerNodes.indexOf(node);\n\n if (orderIndex !== -1) {\n this._imageLayerNodes.splice(orderIndex, 1);\n }\n\n node.destroy();\n }\n\n /** Release a node from its band, or from the view's direct-ownership list. */\n private _releaseFromOwner(node: TileLayerNode | ImageLayerNode): void {\n const band = this._nodeBand.get(node);\n\n if (band) {\n band._release(node);\n this._nodeBand.delete(node);\n } else if (node instanceof TileLayerNode) {\n const directIndex = this._directLayerNodes.indexOf(node);\n\n if (directIndex !== -1) {\n this._directLayerNodes.splice(directIndex, 1);\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,IAAa,cAAb,MAAyB;CACvB,AAAiB;CACjB,AAAiB;;CAGjB,AAAiB,cAA+B,CAAC;;CAEjD,AAAiB,iCAAiB,IAAI,IAA2B;;CAGjE,AAAiB,SAAwB,CAAC;;CAE1C,AAAiB,8BAAc,IAAI,IAAyB;;CAE5D,AAAiB,YAA+B,CAAC;;CAEjD,AAAiB,4BAAY,IAAI,IAAiD;;CAElF,AAAiB,oBAAqC,CAAC;;CAGvD,AAAiB,mBAAqC,CAAC;;CAEvD,AAAiB,sCAAsB,IAAI,IAA4B;CAEvE,AAAQ,aAAa;CACrB,AAAQ,iBAAgC,cAAc;;;;;;;CAQtD,AAAO,YAAY,KAAc,SAA8B;EAC7D,KAAK,OAAO;EACZ,KAAK,YAAY,SAAS,YAAY;EAEtC,KAAK,MAAM,SAAS,IAAI,QAAQ;GAC9B,MAAM,OAAO,IAAI,cAAc,OAAO,EAAE,UAAU,KAAK,UAAU,CAAC;GAElE,KAAK,YAAY,KAAK,IAAI;GAC1B,KAAK,eAAe,IAAI,MAAM,IAAI,IAAI;EACxC;EAEA,KAAK,MAAM,cAAc,IAAI,aAAa;GACxC,MAAM,YAAY,IAAI,eAAe,UAAU;GAE/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AAK,kBAAkB,OAAO,aAAa,CAAC;EAEhD;CACF;AACF"}
1
+ {"version":3,"file":"TileMapView.js","names":[],"sources":["../../src/TileMapView.ts"],"sourcesContent":["import { PixelSnapMode } from '@codexo/exojs/renderer-sdk';\n\nimport { ImageLayer } from './ImageLayer';\nimport { ImageLayerNode } from './ImageLayerNode';\nimport { assertPixelSnapMode } from './pixelSnap';\nimport type { TileLayer } from './TileLayer';\nimport { TileLayerNode } from './TileLayerNode';\nimport type { TileMap } from './TileMap';\nimport { TileMapBand } from './TileMapBand';\n\n/**\n * A layer selector inside a {@link TileMapBandDefinition}: either a stable\n * layer **id** (`number`) or a **unique** layer **name** (`string`). Selectors\n * resolve across the map's tile **and** image layers. Names that are shared by\n * more than one layer (of either kind) are rejected as ambiguous - reference\n * such layers by id. An id shared by a tile layer and an image layer (possible\n * only in fallback-ordered maps, which never validated cross-kind uniqueness)\n * is equally ambiguous - reference such layers by a unique name.\n * @advanced\n */\nexport type TileLayerSelector = number | string;\n\n/**\n * The layers composing one band, by id or unique name, in any order. Tile and\n * image layers may be freely mixed. Rendering order always follows the map's\n * combined document order ({@link import('./TileMap').TileMap.renderableLayers})\n * regardless of the order listed here - a definition *selects* layers, it never\n * reorders them. The band's name is the key it is registered under in\n * {@link TileMapViewOptions.bands}.\n * @advanced\n */\nexport type TileMapBandDefinition = readonly TileLayerSelector[];\n\n/**\n * Options for a {@link TileMapView}.\n * @advanced\n */\nexport interface TileMapViewOptions {\n /**\n * Named bands, keyed by band name (keys are unique, so duplicate band names\n * cannot occur). Each value lists the layers that compose the band - tile\n * and image layers alike. Layers not listed in any band remain reachable\n * through {@link TileMapView.getLayerNodeById} and friends and are owned\n * directly by the view (no implicit fallback band). The definition is copied\n * and frozen; mutating the caller's object afterwards does not change band\n * assignments.\n *\n * @throws (at construction) on an unknown layer id, an unknown or ambiguous\n * layer name, a cross-kind ambiguous layer id, a layer listed twice within\n * one band, or a layer assigned to more than one band.\n */\n readonly bands?: Readonly<Record<string, TileMapBandDefinition>>;\n /**\n * Whether the generated {@link TileLayerNode}s' chunks participate in\n * per-chunk view culling. Forwarded to every layer node. Default `true`.\n */\n readonly cullable?: boolean;\n}\n\ninterface ResolvedBandDef {\n readonly name: string;\n readonly selectors: TileMapBandDefinition;\n}\n\n/**\n * Groups a {@link TileMap}'s layers into independently placeable scene nodes so\n * application actors can be interleaved **between** tile layers.\n *\n * A view produces exactly one canonical {@link TileLayerNode} per map layer\n * (stable identity, map document order) and, optionally, named {@link TileMapBand}s\n * grouping subsets of those nodes. The application parents the bands / layer\n * nodes wherever it wants - typically as siblings of its own actor containers:\n *\n * ```ts\n * const view = map.createView({ bands: { ground: ['background', 'ground'], roof: ['roofs'] } });\n * worldRoot.addChild(view.band('ground'), actors, view.band('roof'));\n * // or without bands:\n * worldRoot.addChild(view.getLayerNodeById(groundId)!, actors, view.getLayerNodeById(roofId)!);\n * ```\n *\n * **Actors are application-owned siblings.** A `TileMapView` never adopts or\n * destroys actors. The view is a helper, not a scene node - it does not own the\n * world container, the {@link TileMap}, the {@link TileLayer}s, or tileset\n * textures.\n *\n * **Ownership:** the view owns its generated layer nodes and bands. A layer\n * assigned to a band is owned by that band; an unbanded layer is owned by the\n * view directly. {@link TileMapView.destroy} destroys every band and layer node\n * (detaching them from their application parents) but leaves actors, the map,\n * its layers, and Loader-owned textures untouched. There is no map-replacement\n * mutation API: to swap maps, destroy the old view, construct a new one, and\n * re-parent its bands - the actor tree is never involved.\n *\n * **Image layers.** A view also produces exactly one canonical\n * {@link ImageLayerNode} per {@link TileMap.imageLayers} entry (stable identity,\n * map document order), reachable through {@link imageLayerNodes},\n * {@link getImageLayerNodeById}, and {@link getImageLayerNodeByName}. Image\n * layers are selectable in {@link TileMapViewOptions.bands} exactly like tile\n * layers: a band member list may mix both kinds, and the band stacks its\n * members by the map's combined document order\n * ({@link import('./TileMap').TileMap.renderableLayers}). A banded image node\n * is owned by its band; an unbanded one is owned by the view directly, and the\n * application parents it wherever the image belongs in draw order - the same\n * way actors are interleaved.\n *\n * @advanced\n */\nexport class TileMapView {\n private readonly _map: TileMap;\n private readonly _cullable: boolean;\n\n /** All canonical tile-layer nodes, in map document order. */\n private readonly _layerNodes: TileLayerNode[] = [];\n /** Tile layer id → its canonical layer node. */\n private readonly _layerNodeById = new Map<number, TileLayerNode>();\n\n /** Bands in definition (insertion) order. */\n private readonly _bands: TileMapBand[] = [];\n /** Band name → band. */\n private readonly _bandByName = new Map<string, TileMapBand>();\n /** Original band definitions (frozen) for re-resolution on refresh. */\n private readonly _bandDefs: ResolvedBandDef[] = [];\n /** Layer node → its owning band (absent = view-owned / unbanded). */\n private readonly _nodeBand = new Map<TileLayerNode | ImageLayerNode, TileMapBand>();\n /** Unbanded tile-layer nodes owned directly by the view, in map document order. */\n private readonly _directLayerNodes: TileLayerNode[] = [];\n\n /** All canonical image layer nodes, in map document order. */\n private readonly _imageLayerNodes: ImageLayerNode[] = [];\n /** Image layer id → its canonical image layer node. */\n private readonly _imageLayerNodeById = new Map<number, ImageLayerNode>();\n\n private _destroyed = false;\n private _pixelSnapMode: PixelSnapMode = PixelSnapMode.Geometry;\n\n /**\n * @param map The runtime map to compose. Referenced, never owned.\n * @param options Band definitions and culling.\n * @throws When a band definition references an unknown/ambiguous layer or\n * assigns a layer twice / to multiple bands.\n */\n public constructor(map: TileMap, options?: TileMapViewOptions) {\n this._map = map;\n this._cullable = options?.cullable ?? true;\n\n for (const layer of map.layers) {\n const node = new TileLayerNode(layer, { cullable: this._cullable });\n\n this._layerNodes.push(node);\n this._layerNodeById.set(layer.id, node);\n }\n\n for (const imageLayer of map.imageLayers) {\n const imageNode = new ImageLayerNode(imageLayer);\n\n this._imageLayerNodes.push(imageNode);\n this._imageLayerNodeById.set(imageLayer.id, imageNode);\n }\n\n if (options?.bands) {\n for (const [name, selectors] of Object.entries(options.bands)) {\n this._defineBand(name, selectors);\n }\n }\n\n for (const node of this._layerNodes) {\n if (!this._nodeBand.has(node)) {\n this._directLayerNodes.push(node);\n }\n }\n }\n\n /** The runtime map this view composes. Referenced, never owned. */\n public get map(): TileMap {\n return this._map;\n }\n\n /** All canonical tile-layer nodes, one per map tile layer, in map document order. */\n public get layers(): readonly TileLayerNode[] {\n return this._layerNodes;\n }\n\n /** The bands, in definition (insertion) order. */\n public get bands(): readonly TileMapBand[] {\n return this._bands;\n }\n\n /** Whether this view has been destroyed. */\n public get destroyed(): boolean {\n return this._destroyed;\n }\n\n /**\n * Render-only pixel-snap mode applied to every layer node this view owns (and\n * forwarded to every chunk drawable, current and rebuilt by\n * {@link refreshLayers}). Snaps tile chunk origins to the active render\n * target's device-pixel grid for crisp tiles; with integer tile pitch the grid\n * stays exact and adjacent chunks cannot drift apart. Purely visual - tile\n * data, layer offsets, chunk revisions, and culling are unchanged. Setting the\n * current value is a no-op; an invalid value throws and leaves the prior mode\n * unchanged.\n *\n * Defaults to `Geometry` because a tile grid is made of quads that share\n * their edges: left unsnapped, a boundary landing between two device pixels\n * is sampled across both, so the seams blur and shimmer as the view moves.\n * Set `None` to opt out.\n *\n * @default PixelSnapMode.Geometry\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 node of this._layerNodes) {\n node.pixelSnapMode = mode;\n }\n\n for (const node of this._imageLayerNodes) {\n node.pixelSnapMode = mode;\n }\n }\n\n /**\n * The canonical layer node for the **tile** layer with the given **id**, or\n * `undefined`. Tile ids are authoritative and unique - this is the\n * unambiguous lookup. The returned node may be reparented into the caller's\n * own containers; the view still tracks it for refresh and destruction.\n */\n public getLayerNodeById(id: number): TileLayerNode | undefined {\n return this._layerNodeById.get(id);\n }\n\n /**\n * Every canonical tile-layer node whose layer has the given **name**, in map\n * document order. Layer names are not guaranteed unique, so this returns an\n * array (empty when no layer matches). Prefer {@link getLayerNodeById} when\n * you have the id.\n */\n public getLayerNodesByName(name: string): readonly TileLayerNode[] {\n return this._layerNodes.filter(node => node.layer.name === name);\n }\n\n /** All canonical image layer nodes, one per map image layer, in map document order. */\n public get imageLayerNodes(): readonly ImageLayerNode[] {\n return this._imageLayerNodes;\n }\n\n /**\n * The canonical image layer node for the image layer with the given **id**,\n * or `undefined`. Ids are authoritative and unique - this is the unambiguous\n * lookup. The returned node may be reparented into the caller's own\n * containers; the view still tracks it for refresh and destruction.\n */\n public getImageLayerNodeById(id: number): ImageLayerNode | undefined {\n return this._imageLayerNodeById.get(id);\n }\n\n /**\n * The canonical image layer node for the image layer with the given\n * **name**, or `undefined` if no image layer has that name. Prefer\n * {@link getImageLayerNodeById} when you have the id.\n * @throws If more than one image layer shares that name (reference such\n * layers by id instead).\n */\n public getImageLayerNodeByName(name: string): ImageLayerNode | undefined {\n const matches = this._map.imageLayers.filter(layer => layer.name === name);\n\n if (matches.length === 0) {\n return undefined;\n }\n\n if (matches.length > 1) {\n throw new Error(`TileMapView image layer name \"${name}\" is ambiguous ` + `(${matches.length} image layers share it); reference it by id instead.`);\n }\n\n return this._imageLayerNodeById.get(matches[0]!.id);\n }\n\n /**\n * The band registered under `name`.\n * @throws If no band with that name was defined.\n */\n public band(name: string): TileMapBand {\n const band = this._bandByName.get(name);\n\n if (!band) {\n throw new Error(\n `TileMapView has no band named \"${name}\". Defined bands: ${this._bands.length > 0 ? this._bands.map(b => `\"${b.name}\"`).join(', ') : '(none)'}.`,\n );\n }\n\n return band;\n }\n\n /** Whether a band with the given name was defined. */\n public hasBand(name: string): boolean {\n return this._bandByName.has(name);\n }\n\n /**\n * Rebuild the view after **structural** map changes (tile or image layers\n * added to or removed from the map). Ordinary tile edits and chunk\n * creation/removal do NOT need this - those are handled by chunk revisions\n * and {@link TileLayerNode.refresh} respectively.\n *\n * - Removed layers (tile or image): their generated node is detached and\n * destroyed.\n * - Unchanged layers: keep their existing node (stable identity).\n * - Added layers (tile or image): a new node is created and assigned to the\n * first band whose definition selects it (by a currently-unambiguous id or\n * name), otherwise owned directly by the view.\n * - Every band's children are re-ordered to the map's combined document\n * order ({@link import('./TileMap').TileMap.renderableLayers}).\n *\n * Application actors are never touched, and bands keep their placement in the\n * application scene graph.\n *\n * @throws If the view has been destroyed.\n */\n public refreshLayers(): this {\n if (this._destroyed) {\n throw new Error('Cannot refresh a destroyed TileMapView.');\n }\n\n const currentLayers = this._map.layers;\n const currentIds = new Set<number>();\n\n for (const layer of currentLayers) {\n currentIds.add(layer.id);\n }\n\n // 1. Remove nodes whose layer no longer exists.\n for (const node of [...this._layerNodes]) {\n if (!currentIds.has(node.layer.id)) {\n this._removeTileNode(node);\n }\n }\n\n const currentImageLayers = new Set(this._map.imageLayers);\n\n for (const node of [...this._imageLayerNodes]) {\n if (!currentImageLayers.has(node.layer)) {\n this._removeImageNode(node);\n }\n }\n\n // 2. Re-derive the doc-ordered node lists, creating + assigning new nodes.\n const newOrder: TileLayerNode[] = [];\n\n for (const layer of currentLayers) {\n let node = this._layerNodeById.get(layer.id);\n\n if (!node) {\n node = new TileLayerNode(layer, { cullable: this._cullable });\n // Unconditional: a node built after the view was set to `None` has to\n // inherit that too, not just a non-default mode.\n node.pixelSnapMode = this._pixelSnapMode;\n\n this._layerNodeById.set(layer.id, node);\n this._assignNewNode(node, layer);\n }\n\n newOrder.push(node);\n }\n\n this._layerNodes.length = 0;\n this._layerNodes.push(...newOrder);\n\n const newImageOrder: ImageLayerNode[] = [];\n\n for (const imageLayer of this._map.imageLayers) {\n let node = this._imageLayerNodes.find(candidate => candidate.layer === imageLayer);\n\n if (!node) {\n node = new ImageLayerNode(imageLayer);\n // Unconditional: a node built after the view was set to `None` has to\n // inherit that too, not just a non-default mode.\n node.pixelSnapMode = this._pixelSnapMode;\n\n this._imageLayerNodeById.set(imageLayer.id, node);\n this._assignNewNode(node, imageLayer);\n }\n\n newImageOrder.push(node);\n }\n\n this._imageLayerNodes.length = 0;\n this._imageLayerNodes.push(...newImageOrder);\n\n // 3. Re-order each band's children to the combined document order. Keyed\n // by layer instance: fallback-ordered maps may share an id across kinds.\n const documentIndex = new Map<TileLayer | ImageLayer, number>();\n\n for (const [index, layer] of this._map.renderableLayers.entries()) {\n documentIndex.set(layer, index);\n }\n\n for (const band of this._bands) {\n band._reorder(documentIndex);\n }\n\n // 4. Rebuild the unbanded set in doc order.\n this._directLayerNodes.length = 0;\n\n for (const node of newOrder) {\n if (!this._nodeBand.has(node)) {\n this._directLayerNodes.push(node);\n }\n }\n\n return this;\n }\n\n /**\n * Destroy the view: every band, generated tile-layer node, and generated\n * {@link ImageLayerNode} is destroyed (and detached from its application\n * parent), freeing cached chunk geometry. Banded nodes are destroyed by\n * their band; unbanded ones by the view directly. Idempotent. Application\n * actors, sibling content, the {@link TileMap}, its {@link TileLayer}s and\n * image layers, and Loader-owned textures all survive.\n */\n public destroy(): void {\n if (this._destroyed) {\n return;\n }\n\n this._destroyed = true;\n\n for (const band of this._bands) {\n band.destroy();\n }\n\n for (const node of this._directLayerNodes) {\n node.parent?.removeChild(node);\n node.destroy();\n }\n\n for (const node of this._imageLayerNodes) {\n if (this._nodeBand.has(node)) {\n continue; // Owned and already destroyed by its band.\n }\n\n node.parent?.removeChild(node);\n node.destroy();\n }\n\n this._bands.length = 0;\n this._bandByName.clear();\n this._bandDefs.length = 0;\n this._directLayerNodes.length = 0;\n this._layerNodes.length = 0;\n this._layerNodeById.clear();\n this._nodeBand.clear();\n this._imageLayerNodes.length = 0;\n this._imageLayerNodeById.clear();\n }\n\n // ── Internals ──────────────────────────────────────────────────────────\n\n /** Resolve one band definition into a {@link TileMapBand} and record it. */\n private _defineBand(name: string, selectors: TileMapBandDefinition): void {\n const members = new Set<TileLayer | ImageLayer>();\n\n for (const selector of selectors) {\n const layer = this._resolveSelector(name, selector);\n\n if (members.has(layer)) {\n throw new Error(`TileMapView band \"${name}\" lists layer ${layer.id} more than once.`);\n }\n\n const existing = this._nodeFor(layer);\n\n if (existing && this._nodeBand.has(existing)) {\n throw new Error(`TileMapView layer ${layer.id} is assigned to multiple bands ` + `(\"${this._nodeBand.get(existing)!.name}\" and \"${name}\").`);\n }\n\n members.add(layer);\n }\n\n // Order members by combined document order (membership selects; doc order\n // renders - tile and image members interleave).\n const orderedNodes: Array<TileLayerNode | ImageLayerNode> = [];\n\n for (const layer of this._map.renderableLayers) {\n if (members.has(layer)) {\n orderedNodes.push(this._nodeFor(layer)!);\n }\n }\n\n const band = new TileMapBand(name, orderedNodes);\n\n for (const node of orderedNodes) {\n this._nodeBand.set(node, band);\n }\n\n this._bands.push(band);\n this._bandByName.set(name, band);\n this._bandDefs.push({ name, selectors: Object.freeze([...selectors]) });\n }\n\n /**\n * Resolve a single selector to a tile or image layer instance, throwing on\n * unknown/ambiguous. Instances (not ids) disambiguate fallback-ordered maps\n * in which a tile layer and an image layer share an id.\n */\n private _resolveSelector(bandName: string, selector: TileLayerSelector): TileLayer | ImageLayer {\n if (typeof selector === 'number') {\n const tileLayer = this._map.getTileLayerById(selector);\n const imageLayer = this._map.imageLayers.find(layer => layer.id === selector);\n\n if (tileLayer && imageLayer) {\n throw new Error(\n `TileMapView band \"${bandName}\": layer id ${selector} is ambiguous ` +\n `(a tile layer and an image layer share it); reference it by a unique name instead.`,\n );\n }\n\n const layer = tileLayer ?? imageLayer;\n\n if (!layer) {\n throw new Error(`TileMapView band \"${bandName}\": no layer with id ${selector} in map \"${this._map.name}\".`);\n }\n\n return layer;\n }\n\n const matches: Array<TileLayer | ImageLayer> = [\n ...this._map.layers.filter(layer => layer.name === selector),\n ...this._map.imageLayers.filter(layer => layer.name === selector),\n ];\n\n if (matches.length === 0) {\n throw new Error(`TileMapView band \"${bandName}\": no layer named \"${selector}\" in map \"${this._map.name}\".`);\n }\n\n if (matches.length > 1) {\n throw new Error(\n `TileMapView band \"${bandName}\": layer name \"${selector}\" is ambiguous ` + `(${matches.length} layers share it); reference it by id instead.`,\n );\n }\n\n return matches[0]!;\n }\n\n /** The canonical node for a tile or image layer instance, if one exists. */\n private _nodeFor(layer: TileLayer | ImageLayer): TileLayerNode | ImageLayerNode | undefined {\n if (layer instanceof ImageLayer) {\n // Instance scan rather than the id map: image ids are not validated\n // unique, and fallback maps may collide with tile ids anyway.\n return this._imageLayerNodes.find(node => node.layer === layer);\n }\n\n return this._layerNodeById.get(layer.id);\n }\n\n /** Assign a freshly created node to the first band that selects its layer. */\n private _assignNewNode(node: TileLayerNode | ImageLayerNode, layer: TileLayer | ImageLayer): void {\n for (const def of this._bandDefs) {\n if (this._definitionSelects(def, layer)) {\n const band = this._bandByName.get(def.name)!;\n\n band._adopt(node);\n this._nodeBand.set(node, band);\n\n return;\n }\n }\n }\n\n /**\n * Whether a band definition selects the given layer - only by a selector\n * that is currently unambiguous (a unique name, or an id not shared across\n * kinds), mirroring {@link _resolveSelector}'s construction-time rules.\n */\n private _definitionSelects(def: ResolvedBandDef, layer: TileLayer | ImageLayer): boolean {\n for (const selector of def.selectors) {\n if (typeof selector === 'number') {\n if (selector === layer.id && !this._isCrossKindId(selector)) {\n return true;\n }\n } else if (selector === layer.name) {\n const sameName =\n this._map.layers.filter(other => other.name === selector).length + this._map.imageLayers.filter(other => other.name === selector).length;\n\n if (sameName === 1) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /** Whether an id currently belongs to both a tile layer and an image layer. */\n private _isCrossKindId(id: number): boolean {\n return this._map.getTileLayerById(id) !== undefined && this._map.imageLayers.some(layer => layer.id === id);\n }\n\n /** Detach + destroy a tile node, dropping it from bands and registries. */\n private _removeTileNode(node: TileLayerNode): void {\n this._releaseFromOwner(node);\n\n node.parent?.removeChild(node);\n this._layerNodeById.delete(node.layer.id);\n\n const orderIndex = this._layerNodes.indexOf(node);\n\n if (orderIndex !== -1) {\n this._layerNodes.splice(orderIndex, 1);\n }\n\n node.destroy();\n }\n\n /** Detach + destroy an image node, dropping it from bands and registries. */\n private _removeImageNode(node: ImageLayerNode): void {\n this._releaseFromOwner(node);\n\n node.parent?.removeChild(node);\n\n if (this._imageLayerNodeById.get(node.layer.id) === node) {\n this._imageLayerNodeById.delete(node.layer.id);\n }\n\n const orderIndex = this._imageLayerNodes.indexOf(node);\n\n if (orderIndex !== -1) {\n this._imageLayerNodes.splice(orderIndex, 1);\n }\n\n node.destroy();\n }\n\n /** Release a node from its band, or from the view's direct-ownership list. */\n private _releaseFromOwner(node: TileLayerNode | ImageLayerNode): void {\n const band = this._nodeBand.get(node);\n\n if (band) {\n band._release(node);\n this._nodeBand.delete(node);\n } else if (node instanceof TileLayerNode) {\n const directIndex = this._directLayerNodes.indexOf(node);\n\n if (directIndex !== -1) {\n this._directLayerNodes.splice(directIndex, 1);\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,IAAa,cAAb,MAAyB;CACvB,AAAiB;CACjB,AAAiB;;CAGjB,AAAiB,cAA+B,CAAC;;CAEjD,AAAiB,iCAAiB,IAAI,IAA2B;;CAGjE,AAAiB,SAAwB,CAAC;;CAE1C,AAAiB,8BAAc,IAAI,IAAyB;;CAE5D,AAAiB,YAA+B,CAAC;;CAEjD,AAAiB,4BAAY,IAAI,IAAiD;;CAElF,AAAiB,oBAAqC,CAAC;;CAGvD,AAAiB,mBAAqC,CAAC;;CAEvD,AAAiB,sCAAsB,IAAI,IAA4B;CAEvE,AAAQ,aAAa;CACrB,AAAQ,iBAAgC,cAAc;;;;;;;CAQtD,AAAO,YAAY,KAAc,SAA8B;EAC7D,KAAK,OAAO;EACZ,KAAK,YAAY,SAAS,YAAY;EAEtC,KAAK,MAAM,SAAS,IAAI,QAAQ;GAC9B,MAAM,OAAO,IAAI,cAAc,OAAO,EAAE,UAAU,KAAK,UAAU,CAAC;GAElE,KAAK,YAAY,KAAK,IAAI;GAC1B,KAAK,eAAe,IAAI,MAAM,IAAI,IAAI;EACxC;EAEA,KAAK,MAAM,cAAc,IAAI,aAAa;GACxC,MAAM,YAAY,IAAI,eAAe,UAAU;GAE/C,KAAK,iBAAiB,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TileSet {
78
78
  */
79
79
  constructor(options: TileSetOptions);
80
80
  /**
81
- * Set per-tile metadata for a local tile ID.
82
- * Copies input to prevent caller-owned mutation leaking into the tileset.
83
- * @internal
84
- */
85
- _setDefinition(localTileId: number, definition: Partial<TileDefinition>): void;
86
- /**
87
- * Build definitions from an array, replacing the internal definitions map.
88
- * Each entry's properties are copied and frozen.
81
+ * Replace all tile definitions with the given array. Each entry's
82
+ * properties are copied and frozen.
89
83
  *
90
84
  * Part of the tilemap SDK contract for extension packages that build
91
85
  * tilesets programmatically.
92
86
  */
93
- _setDefinitions(definitions: readonly TileDefinition[]): void;
87
+ setDefinitions(definitions: readonly TileDefinition[]): void;
94
88
  /**
95
89
  * Retrieve per-tile metadata, or undefined if none defined.
96
90
  * @advanced
@@ -1 +1 @@
1
- {"version":3,"file":"TileSet.d.ts","sourceRoot":"","sources":["../../src/TileSet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEnD,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAG9D;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,6DAA6D;IAC7D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,iEAAiE;IACjE,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC;IAChC,oCAAoC;IACpC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,qCAAqC;IACrC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,6CAA6C;IAC7C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,oGAAoG;IACpG,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,+DAA+D;IAC/D,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,oDAAoD;IACpD,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,mEAAmE;I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W,cAAc,IAAI,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,GAAG,SAAS,CAAC,CAAC,CAMhF;CACF"}
@@ -100,13 +100,13 @@ var TileSet = class {
100
100
  });
101
101
  }
102
102
  /**
103
- * Build definitions from an array, replacing the internal definitions map.
104
- * Each entry's properties are copied and frozen.
103
+ * Replace all tile definitions with the given array. Each entry's
104
+ * properties are copied and frozen.
105
105
  *
106
106
  * Part of the tilemap SDK contract for extension packages that build
107
107
  * tilesets programmatically.
108
108
  */
109
- _setDefinitions(definitions) {
109
+ setDefinitions(definitions) {
110
110
  const map = this._definitions;
111
111
  map.clear();
112
112
  for (const def of 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 *\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;EAC7C,2BAA2B,QAAQ,QAAQ;EAM3C,IAAI,QAAQ,QAAQ,SAAS,KAAK,QAAQ,QAAQ,UAAU,GAC1D,MAAM,IAAI,MACR,2DAA2D,QAAQ,KAAK,4BACnE,QAAQ,QAAQ,MAAM,GAAG,QAAQ,QAAQ,OAAO,kFACvD;EAGF,MAAM,aAAa,QAAQ,QAAQ,QAAQ,SAAS;EACpD,MAAM,cAAc,QAAQ,QAAQ,SAAS,SAAS;EAEtD,MAAM,UAAU,QAAQ,WAAW,KAAK,MAAM,aAAa,QAAQ,SAAS;EAE5E,wBAAwB,SAAS,S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OA,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 * Replace all tile definitions with the given array. Each entry's\n * 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;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OAAO,EAAE,GAAG,IAAI,WAAW,CAAC,IAAI;GACtE,MAAM,YAAY,IAAI,YAAY,OAAO,OAAO,IAAI,UAAU,KAAI,UAAS,OAAO,OAAO,EAAE,GAAG,MAAM,CAAC,CAAC,CAAC,IAAI;GAC3G,MAAM,YAAY,IAAI,YAAY,OAAO,OAAO,CAAC,GAAG,IAAI,SAAS,CAAC,IAAI;GACtE,IAAI,IAAI,IAAI,aAAa;IACvB,aAAa,IAAI;IACjB,GAAI,UAAU,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"}
@@ -82,13 +82,10 @@ export interface WorkerSampledChunkSourceOptions {
82
82
  * lifecycle hook, so nothing ties the two together automatically. Call it
83
83
  * yourself alongside your own `ChunkStreamer.destroy()` call.
84
84
  *
85
- * Implementation note: `workerSource` is Blob-URL'd into a real `Worker`
86
- * (`new Blob([workerSource])` → `URL.createObjectURL` → `new Worker(url)`) -
87
- * the same technique {@link import('@codexo/exojs').WorkletEffect} already
88
- * uses for AudioWorklet processors. This is bundler-agnostic (no special
89
- * config needed in Vite/webpack/etc.) but requires a Content-Security-Policy
90
- * that permits `blob:` in `worker-src` (or `script-src` as a fallback) if
91
- * your deployment sets one.
85
+ * `workerSource` runs through {@link import('@codexo/exojs').InlineWorker},
86
+ * so it needs no bundler support of its own but does need a
87
+ * Content-Security-Policy that permits `blob:` in `worker-src` if your
88
+ * deployment sets one; the constructor names that cause when it is refused.
92
89
  * @advanced
93
90
  */
94
91
  export declare const createWorkerSampledChunkSource: (layer: TileLayer, options: WorkerSampledChunkSourceOptions) => ChunkSource & {
@@ -1 +1 @@
1
- {"version":3,"file":"WorkerSampledChunkSource.d.ts","sourceRoot":"","sources":["../../src/WorkerSampledChunkSource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,WAAW,EAAE,MAAM,eAAe,CAAC;AAC/D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAG5C;;;GAGG;AACH,MAAM,WAAW,+BAA+B;IAC9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+BG;IACH,YAAY,EAAE,MAAM,CAAC;IACrB;;;;;;;;;;;;OAYG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;;;;;OAOG;IACH,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,CAAC;CAC5E;AAiCD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,eAAO,MAAM,8BAA8B,GAAI,OAAO,SAAS,EAAE,SAAS,+BAA+B,KAAG,WAAW,GAAG;IAAE,OAAO,IAAI,IAAI,CAAA;CA8F1I,CAAC"}
1
+ {"version":3,"file":"WorkerSampledChunkSource.d.ts","sourceRoot":"","sources":["../../src/WorkerSampledChunkSource.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAgB,WAAW,EAAE,MAAM,eAAe,CAAC;AAC/D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAG5C;;;GAGG;AACH,MAAM,WAAW,+BAA+B;IAC9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+BG;IACH,YAAY,EAAE,MAAM,CAAC;IACrB;;;;;;;;;;;;OAYG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;;;;;OAOG;IACH,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,CAAC;CAC5E;AAiCD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,8BAA8B,GAAI,OAAO,SAAS,EAAE,SAAS,+BAA+B,KAAG,WAAW,GAAG;IAAE,OAAO,IAAI,IAAI,CAAA;CA0F1I,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { packTile } from "./types.js";
2
+ import { InlineWorker } from "@codexo/exojs";
2
3
 
3
4
  //#region src/WorkerSampledChunkSource.ts
4
5
  const isWorkerErrorMessage = (message) => "error" in message;
@@ -21,25 +22,19 @@ const isWorkerErrorMessage = (message) => "error" in message;
21
22
  * lifecycle hook, so nothing ties the two together automatically. Call it
22
23
  * yourself alongside your own `ChunkStreamer.destroy()` call.
23
24
  *
24
- * Implementation note: `workerSource` is Blob-URL'd into a real `Worker`
25
- * (`new Blob([workerSource])` → `URL.createObjectURL` → `new Worker(url)`) -
26
- * the same technique {@link import('@codexo/exojs').WorkletEffect} already
27
- * uses for AudioWorklet processors. This is bundler-agnostic (no special
28
- * config needed in Vite/webpack/etc.) but requires a Content-Security-Policy
29
- * that permits `blob:` in `worker-src` (or `script-src` as a fallback) if
30
- * your deployment sets one.
25
+ * `workerSource` runs through {@link import('@codexo/exojs').InlineWorker},
26
+ * so it needs no bundler support of its own but does need a
27
+ * Content-Security-Policy that permits `blob:` in `worker-src` if your
28
+ * deployment sets one; the constructor names that cause when it is refused.
31
29
  * @advanced
32
30
  */
33
31
  const createWorkerSampledChunkSource = (layer, options) => {
34
32
  const mapValueToTile = options.mapValueToTile.bind(options);
35
- const blob = new Blob([options.workerSource], { type: "application/javascript" });
36
- const url = URL.createObjectURL(blob);
37
- const worker = new Worker(url);
38
- URL.revokeObjectURL(url);
39
- if (options.initMessage !== void 0) worker.postMessage(options.initMessage);
33
+ const inline = new InlineWorker(options.workerSource, { name: "exojs-tilemap-chunk-sampler" });
34
+ const worker = inline.worker;
35
+ if (options.initMessage !== void 0) inline.postMessage(options.initMessage);
40
36
  let requestCounter = 0;
41
37
  const pending = /* @__PURE__ */ new Map();
42
- let destroyed = false;
43
38
  const composePayload = (values, request) => {
44
39
  const { cx, cy, chunkWidth, chunkHeight } = request;
45
40
  const startTx = cx * chunkWidth;
@@ -80,7 +75,7 @@ const createWorkerSampledChunkSource = (layer, options) => {
80
75
  };
81
76
  return {
82
77
  getChunk(cx, cy) {
83
- if (destroyed) return Promise.reject(/* @__PURE__ */ new Error("WorkerSampledChunkSource: getChunk() called after destroy()."));
78
+ if (inline.destroyed) return Promise.reject(/* @__PURE__ */ new Error("WorkerSampledChunkSource: getChunk() called after destroy()."));
84
79
  const chunkWidth = layer.chunkWidth;
85
80
  const chunkHeight = layer.chunkHeight;
86
81
  const requestId = ++requestCounter;
@@ -100,16 +95,15 @@ const createWorkerSampledChunkSource = (layer, options) => {
100
95
  chunkWidth,
101
96
  chunkHeight
102
97
  };
103
- worker.postMessage(request);
98
+ inline.postMessage(request);
104
99
  });
105
100
  },
106
101
  destroy() {
107
- if (destroyed) return;
108
- destroyed = true;
102
+ if (inline.destroyed) return;
109
103
  const error = /* @__PURE__ */ new Error("WorkerSampledChunkSource destroyed.");
110
104
  for (const entry of pending.values()) entry.reject(error);
111
105
  pending.clear();
112
- worker.terminate();
106
+ inline.destroy();
113
107
  }
114
108
  };
115
109
  };
@@ -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 - 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,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OAAO,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"}
1
+ {"version":3,"file":"WorkerSampledChunkSource.js","names":[],"sources":["../../src/WorkerSampledChunkSource.ts"],"sourcesContent":["import { InlineWorker } from '@codexo/exojs';\n\nimport 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 * `workerSource` runs through {@link import('@codexo/exojs').InlineWorker},\n * so it needs no bundler support of its own but does need a\n * Content-Security-Policy that permits `blob:` in `worker-src` if your\n * deployment sets one; the constructor names that cause when it is refused.\n * @advanced\n */\nexport const createWorkerSampledChunkSource = (layer: TileLayer, options: WorkerSampledChunkSourceOptions): ChunkSource & { destroy(): void } => {\n const mapValueToTile = options.mapValueToTile.bind(options);\n\n const inline = new InlineWorker(options.workerSource, { name: 'exojs-tilemap-chunk-sampler' });\n const worker = inline.worker;\n\n if (options.initMessage !== undefined) {\n inline.postMessage(options.initMessage);\n }\n\n let requestCounter = 0;\n const pending = new Map<number, PendingRequest>();\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 (inline.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 inline.postMessage(request);\n });\n },\n\n destroy(): void {\n if (inline.destroyed) return;\n const error = new Error('WorkerSampledChunkSource destroyed.');\n for (const entry of pending.values()) {\n entry.reject(error);\n }\n pending.clear();\n inline.destroy();\n },\n };\n};\n"],"mappings":";;;;AA0FA,MAAM,wBAAwB,YAAkE,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;AAoC3G,MAAa,kCAAkC,OAAkB,YAAgF;CAC/I,MAAM,iBAAiB,QAAQ,eAAe,KAAK,OAAO;CAE1D,MAAM,SAAS,IAAI,aAAa,QAAQ,cAAc,EAAE,MAAM,8BAA8B,CAAC;CAC7F,MAAM,SAAS,OAAO;CAEtB,IAAI,QAAQ,gBAAgB,QAC1B,OAAO,YAAY,QAAQ,WAAW;CAGxC,IAAI,iBAAiB;CACrB,MAAM,0BAAU,IAAI,IAA4B;CAEhD,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,cAAc,KAAK;GACvD,MAAM,QAAQ,OAAO;GACrB,IAAI,UAAU,QAAW;GACzB,MAAM,WAA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AAK,MAAM,SAAS,QAAQ,OAAO,GACjC,MAAM,OAAO,KAAK;GAEpB,QAAQ,MAAM;GACd,OAAO,QAAQ;EACjB;CACF;AACF"}
@@ -1,72 +1,2 @@
1
- import type { Texture } from '@codexo/exojs';
2
- import type { ReadonlyTileChunk } from './TileChunk';
3
- import type { TileSet } from './TileSet';
4
- import type { TileTransform } from './types';
5
- /**
6
- * One textured tile quad in chunk-local pixel space.
7
- *
8
- * `u0/v0/u1/v1` are the raw (min/max) source UV bounds of the tile within its
9
- * tileset texture - flip/orientation is **not** baked here; it travels in
10
- * {@link TileQuad.orient} and is applied by the per-backend renderer (flipX/Y
11
- * via UV-corner swap, diagonal via an axis swap in the shader). Keeping the
12
- * geometry orientation-neutral lets both backends share one CPU builder.
13
- * @internal
14
- */
15
- export interface TileQuad {
16
- /** Local destination rect, left/top (chunk-local pixels). */
17
- readonly x0: number;
18
- readonly y0: number;
19
- /** Local destination rect, right/bottom (chunk-local pixels). */
20
- readonly x1: number;
21
- readonly y1: number;
22
- /** Normalised source UV bounds (always min ≤ max). */
23
- readonly u0: number;
24
- readonly v0: number;
25
- readonly u1: number;
26
- readonly v1: number;
27
- /** Orientation code: bit0 = flipX, bit1 = flipY, bit2 = diagonal. */
28
- readonly orient: number;
29
- }
30
- /**
31
- * Geometry for one tileset "page" within a chunk: every tile in the chunk that
32
- * draws from a single tileset texture, grouped so the renderer can batch by
33
- * `(shader, texture)`.
34
- * @internal
35
- */
36
- export interface ChunkPage {
37
- /** The tileset all quads in this page draw from. */
38
- readonly tileset: TileSet;
39
- /** The underlying GPU texture (the tileset's atlas), bound once per page. */
40
- readonly texture: Texture;
41
- /** The tile quads for this page, in deterministic row-major order. */
42
- readonly quads: readonly TileQuad[];
43
- }
44
- /** Pack a {@link TileTransform} into a 3-bit orientation code. @internal */
45
- export declare const orientCode: (transform: TileTransform) => number;
46
- /** Read the cumulative chunk-geometry rebuild count. @internal */
47
- export declare const getTileGeometryRebuildCount: () => number;
48
- /** Reset the chunk-geometry rebuild counter (call before a measured frame). @internal */
49
- export declare const resetTileGeometryRebuildCount: () => void;
50
- /**
51
- * Build per-tileset page geometry for a single chunk.
52
- *
53
- * Iterates the chunk's packed cells in deterministic row-major order, skipping
54
- * empties, out-of-range tilesets, and out-of-range local tile ids (all treated
55
- * as empty - this is the renderer's half of the G-GID contract). Each surviving
56
- * cell is resolved to its source UV rect (from `tileset.getTileRect` + the
57
- * tileset `TextureRegion`) and a chunk-local destination rect (bottom-left
58
- * aligned per Tiled orthogonal semantics, so tilesets whose tiles are taller
59
- * than the map grid extend upward).
60
- *
61
- * Allocation happens here only - the result is cached on the owning
62
- * {@link import('./TileChunkNode').TileChunkNode} keyed by `chunk.revision`, so
63
- * unchanged chunks never rebuild and the per-frame path stays allocation-free.
64
- *
65
- * @param chunk The readonly chunk view to build from.
66
- * @param tilesets The layer's tileset array (packed `tilesetIndex` selects one).
67
- * @param tileWidth Map/layer tile cell width in pixels.
68
- * @param tileHeight Map/layer tile cell height in pixels.
69
- * @internal
70
- */
71
- export declare const buildChunkPages: (chunk: ReadonlyTileChunk, tilesets: readonly TileSet[], tileWidth: number, tileHeight: number) => ChunkPage[];
1
+ export {};
72
2
  //# sourceMappingURL=chunkGeometry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"chunkGeometry.d.ts","sourceRoot":"","sources":["../../src/chunkGeometry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAE7C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAG7C;;;;;;;;;GASG;AACH,MAAM,WAAW,QAAQ;IACvB,6DAA6D;IAC7D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,iEAAiE;IACjE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,sDAAsD;IACtD,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,qEAAqE;IACrE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED;;;;;GAKG;AACH,MAAM,WAAW,SAAS;IACxB,oDAAoD;IACpD,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,6EAA6E;IAC7E,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,sEAAsE;IACtE,QAAQ,CAAC,KAAK,EAAE,SAAS,QAAQ,EAAE,CAAC;CACrC;AAED,4EAA4E;AAC5E,eAAO,MAAM,UAAU,GAAI,WAAW,aAAa,KAAG,MAA8F,CAAC;AASrJ,kEAAkE;AAClE,eAAO,MAAM,2BAA2B,QAAO,MAAkC,CAAC;AAElF,yFAAyF;AACzF,eAAO,MAAM,6BAA6B,QAAO,IAEhD,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,eAAe,GAAI,OAAO,iBAAiB,EAAE,UAAU,SAAS,OAAO,EAAE,EAAE,WAAW,MAAM,EAAE,YAAY,MAAM,KAAG,SAAS,EAyFxI,CAAC"}
1
+ {"version":3,"file":"chunkGeometry.d.ts","sourceRoot":"","sources":["../../src/chunkGeometry.ts"],"names":[],"mappings":""}
@@ -1,20 +1,2 @@
1
- import type { SceneNode } from '@codexo/exojs';
2
- import { Rectangle } from '@codexo/exojs';
3
- /**
4
- * Grow `out` to the union of `children`'s local bounds, each transformed by
5
- * the child's own (translation-only, in practice) local transform - i.e. the
6
- * children's combined extent expressed in the *parent's* local coordinate
7
- * space, not the parent's own position/scale/rotation.
8
- *
9
- * Used as the unbounded-layer/-map fallback for `getLocalBounds()`: `Container`
10
- * does not aggregate children into its own local bounds automatically (only
11
- * `getBounds()` - global - does that), so nodes that want a children-derived
12
- * local rect must compute it explicitly. Mirrors `Container.updateBounds()`'s
13
- * own aggregation semantics, including skipping invisible children. Callers
14
- * are expected to only invoke this when `children.length > 0`; `out` is left
15
- * untouched otherwise (also guarded internally in case a future call site
16
- * forgets to check).
17
- * @internal
18
- */
19
- export declare const aggregateChildLocalBounds: (children: readonly SceneNode[], out: Rectangle) => void;
1
+ export {};
20
2
  //# sourceMappingURL=nodeBounds.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"nodeBounds.d.ts","sourceRoot":"","sources":["../../src/nodeBounds.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1C;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,yBAAyB,GAAI,UAAU,SAAS,SAAS,EAAE,EAAE,KAAK,SAAS,KAAG,IA6B1F,CAAC"}
1
+ {"version":3,"file":"nodeBounds.d.ts","sourceRoot":"","sources":["../../src/nodeBounds.ts"],"names":[],"mappings":""}
@@ -1,13 +1,2 @@
1
- import { PixelSnapMode } from '@codexo/exojs/renderer-sdk';
2
- /**
3
- * Throw a deterministic error when `mode` is not a valid {@link PixelSnapMode}.
4
- *
5
- * Mirrors the core `Drawable` setter's guard so the tilemap node passthroughs
6
- * (`TileMapView` / `TileMapNode` / `TileLayerNode`) reject JavaScript-invalid
7
- * values atomically - even for an empty layer that has no chunk drawable to
8
- * delegate the validation to. Kept local because the core guard is not part of
9
- * the public API surface.
10
- * @internal
11
- */
12
- export declare const assertPixelSnapMode: (mode: PixelSnapMode) => void;
1
+ export {};
13
2
  //# sourceMappingURL=pixelSnap.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"pixelSnap.d.ts","sourceRoot":"","sources":["../../src/pixelSnap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAE3D;;;;;;;;;GASG;AACH,eAAO,MAAM,mBAAmB,GAAI,MAAM,aAAa,KAAG,IASzD,CAAC"}
1
+ {"version":3,"file":"pixelSnap.d.ts","sourceRoot":"","sources":["../../src/pixelSnap.ts"],"names":[],"mappings":""}
@@ -1,12 +1,2 @@
1
- /**
2
- * Tile word packing, shared by both backends and by the shader sources they
3
- * fill: transform-buffer row in the low 29 bits, diagonal flip in bit 29.
4
- * flipX/flipY are baked into the UV bounds at write time, so the shader only
5
- * needs the diagonal axis swap.
6
- *
7
- * @internal
8
- */
9
- export declare const TILE_ROW_MASK = 536870911;
10
- /** @internal */
11
- export declare const TILE_DIAGONAL_BIT = 536870912;
1
+ export {};
12
2
  //# sourceMappingURL=tileWord.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tileWord.d.ts","sourceRoot":"","sources":["../../src/tileWord.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,YAAa,CAAC;AAExC,gBAAgB;AAChB,eAAO,MAAM,iBAAiB,YAAa,CAAC"}
1
+ {"version":3,"file":"tileWord.d.ts","sourceRoot":"","sources":["../../src/tileWord.ts"],"names":[],"mappings":""}
@@ -1 +1 @@
1
- {"version":3,"file":"tilemapExtension.d.ts","sourceRoot":"","sources":["../../src/tilemapExtension.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAmB,MAAM,0BAA0B,CAAC;AAoC3E;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,gBAAgB,EAAE,SAI7B,CAAC"}
1
+ {"version":3,"file":"tilemapExtension.d.ts","sourceRoot":"","sources":["../../src/tilemapExtension.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAmB,MAAM,0BAA0B,CAAC;AAiC3E;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,gBAAgB,EAAE,SAI7B,CAAC"}
@@ -3,7 +3,7 @@ import { TileMapNode } from "./TileMapNode.js";
3
3
  import { tileMapNodeSerializer } from "./tilemapSerializers.js";
4
4
  import { WebGl2TileChunkRenderer } from "./webgl2/WebGl2TileChunkRenderer.js";
5
5
  import { WebGpuTileChunkRenderer } from "./webgpu/WebGpuTileChunkRenderer.js";
6
- import { RenderBackendType } from "@codexo/exojs/renderer-sdk";
6
+ import { RenderBackendType, defineRendererBinding } from "@codexo/exojs/renderer-sdk";
7
7
 
8
8
  //#region src/tilemapExtension.ts
9
9
  /** Per-tile instance batch size for the WebGL2 tile chunk renderer. */
@@ -16,13 +16,10 @@ const tileRendererBatchSize = 4096;
16
16
  * {@link import('./TileLayerNode').TileLayerNode}, whose chunk children resolve
17
17
  * to this renderer through the registry prototype walk.
18
18
  */
19
- const buildTileChunkRendererBinding = (batchSize) => ({
20
- targets: [TileChunkNode],
21
- create(backend) {
22
- if (backend.backendType === RenderBackendType.WebGl2) return new WebGl2TileChunkRenderer(batchSize);
23
- if (backend.backendType === RenderBackendType.WebGpu) return new WebGpuTileChunkRenderer();
24
- throw new Error(`Unsupported render backend: ${String(backend.backendType)}`);
25
- }
19
+ const buildTileChunkRendererBinding = (batchSize) => defineRendererBinding([TileChunkNode], (backend) => {
20
+ if (backend.backendType === RenderBackendType.WebGl2) return new WebGl2TileChunkRenderer(batchSize);
21
+ if (backend.backendType === RenderBackendType.WebGpu) return new WebGpuTileChunkRenderer();
22
+ throw new Error(`Unsupported render backend: ${String(backend.backendType)}`);
26
23
  });
27
24
  /**
28
25
  * Default immutable tilemap extension descriptor.