@codexo/exojs-tilemap 0.16.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/TileSet.d.ts.map +1 -1
- package/dist/esm/TileSet.js +1 -0
- package/dist/esm/TileSet.js.map +1 -1
- package/dist/esm/webgpu/WebGpuTileChunkRenderer.d.ts.map +1 -1
- package/dist/esm/webgpu/WebGpuTileChunkRenderer.js +2 -2
- package/dist/esm/webgpu/WebGpuTileChunkRenderer.js.map +1 -1
- package/package.json +3 -3
|
@@ -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;IACnE,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,8GAA8G;IAC9G,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC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OAAO,CAAC,QAAQ,CAAC,YAAY,CAAsC;IAEnE;;OAEG;gBACgB,OAAO,EAAE,cAAc;IAoE1C;;;;OAIG;IACI,cAAc,CAAC,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,IAAI;IAerF;;;;OAIG;IACI,eAAe,CAAC,WAAW,EAAE,SAAS,cAAc,EAAE,GAAG,IAAI;IAgBpE;;;OAGG;IACI,iBAAiB,CAAC,WAAW,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS;IAIzE;;;;OAIG;IACI,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG;QAAE,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE;IAchG;;;OAGG;IACI,YAAY,IAAI,gBAAgB,CAAC,cAAc,CAAC;IAIvD;;;;OAIG;IACH,IAAW,cAAc,IAAI,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,GAAG,SAAS,CAAC,CAAC,CAMhF;CACF"}
|
package/dist/esm/TileSet.js
CHANGED
|
@@ -59,6 +59,7 @@ var TileSet = class {
|
|
|
59
59
|
const margin = options.margin ?? 0;
|
|
60
60
|
validateNonNegativeInteger(spacing, "spacing");
|
|
61
61
|
validateNonNegativeInteger(margin, "margin");
|
|
62
|
+
if (options.texture.width <= 0 || options.texture.height <= 0) throw new Error(`TileSet needs a loaded texture to derive its grid, but "${options.name}" was given one measuring ${options.texture.width}x${options.texture.height}. Await it (loader.load(...) or texture.loaded) before constructing the tile set.`);
|
|
62
63
|
const atlasWidth = options.texture.width - margin * 2;
|
|
63
64
|
const atlasHeight = options.texture.height - margin * 2;
|
|
64
65
|
const columns = options.columns ?? Math.floor(atlasWidth / options.tileWidth);
|
package/dist/esm/TileSet.js.map
CHANGED
|
@@ -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 const atlasWidth = options.texture.width - margin * 2;\n const atlasHeight = options.texture.height - margin * 2;\n\n const columns = options.columns ?? Math.floor(atlasWidth / options.tileWidth);\n\n validatePositiveInteger(columns, 'columns');\n if (columns <= 0) {\n throw new Error(`TileSet columns must be positive (got ${columns}).`);\n }\n\n if (options.tileWidth * columns + spacing * (columns - 1) > atlasWidth) {\n throw new Error(`TileSet grid width exceeds atlas: ${options.tileWidth}*${columns}` + ` + ${spacing}*${columns - 1} > ${atlasWidth}.`);\n }\n\n const rows = Math.ceil(options.tileCount / columns);\n if (rows > 0 && options.tileHeight * rows + spacing * (rows - 1) > atlasHeight) {\n throw new Error(`TileSet grid height exceeds atlas: ${options.tileHeight}*${rows}` + ` + ${spacing}*${rows - 1} > ${atlasHeight}.`);\n }\n\n this.name = options.name;\n this.texture = options.texture;\n this.tileWidth = options.tileWidth;\n this.tileHeight = options.tileHeight;\n this.tileCount = options.tileCount;\n this.columns = columns;\n this.rows = rows;\n this.spacing = spacing;\n this.margin = margin;\n this.class = options.class ?? '';\n this.offsetX = options.offsetX ?? 0;\n this.offsetY = options.offsetY ?? 0;\n\n this._definitions = new Map();\n\n if (__DEV__) {\n Object.freeze(this);\n }\n }\n\n /**\n * Set per-tile metadata for a local tile ID.\n * Copies input to prevent caller-owned mutation leaking into the tileset.\n * @internal\n */\n public _setDefinition(localTileId: number, definition: Partial<TileDefinition>): void {\n if (localTileId < 0 || localTileId >= this.tileCount) {\n throw new Error(`Tile definition localTileId ${localTileId} out of range [0, ${this.tileCount - 1}].`);\n }\n const props = definition.properties ? Object.freeze({ ...definition.properties }) : undefined;\n const animation = definition.animation ? Object.freeze(definition.animation.map(frame => Object.freeze({ ...frame }))) : undefined;\n const collision = definition.collision ? Object.freeze([...definition.collision]) : undefined;\n (this._definitions as Map<number, TileDefinition>).set(localTileId, {\n localTileId,\n ...(props !== undefined && { properties: props }),\n ...(animation !== undefined && { animation }),\n ...(collision !== undefined && { collision }),\n });\n }\n\n /**\n * Build definitions from an array, replacing the internal definitions map.\n * Each entry's properties are copied and frozen.\n * @internal\n */\n public _setDefinitions(definitions: readonly TileDefinition[]): void {\n const map = this._definitions as Map<number, TileDefinition>;\n map.clear();\n for (const def of definitions) {\n const props = def.properties ? Object.freeze({ ...def.properties }) : undefined;\n const animation = def.animation ? Object.freeze(def.animation.map(frame => Object.freeze({ ...frame }))) : undefined;\n const collision = def.collision ? Object.freeze([...def.collision]) : undefined;\n map.set(def.localTileId, {\n localTileId: def.localTileId,\n ...(props !== undefined && { properties: props }),\n ...(animation !== undefined && { animation }),\n ...(collision !== undefined && { collision }),\n });\n }\n }\n\n /**\n * Retrieve per-tile metadata, or undefined if none defined.\n * @advanced\n */\n public getTileDefinition(localTileId: number): TileDefinition | undefined {\n return this._definitions.get(localTileId);\n }\n\n /**\n * Compute the pixel-space source rectangle for a local tile ID\n * within the atlas, accounting for columns, spacing, and margin.\n * @advanced\n */\n public getTileRect(localTileId: number): { x: number; y: number; width: number; height: number } {\n if (localTileId < 0 || localTileId >= this.tileCount) {\n throw new Error(`getTileRect: localTileId ${localTileId} out of range [0, ${this.tileCount - 1}].`);\n }\n const col = localTileId % this.columns;\n const row = Math.floor(localTileId / this.columns);\n return {\n x: this.margin + col * (this.tileWidth + this.spacing),\n y: this.margin + row * (this.tileHeight + this.spacing),\n width: this.tileWidth,\n height: this.tileHeight,\n };\n }\n\n /**\n * Iterate over all defined tiles (sparse).\n * @advanced\n */\n public definedTiles(): IterableIterator<TileDefinition> {\n return this._definitions.values();\n }\n\n /**\n * Read-only snapshot of all per-tile definitions.\n * The returned record is a caller-owned copy.\n * @advanced\n */\n public get allDefinitions(): Readonly<Record<number, TileProperties | undefined>> {\n const result: Record<number, TileProperties | undefined> = {};\n for (const [id, def] of this._definitions) {\n result[id] = def.properties;\n }\n return Object.freeze(result);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA6CA,IAAa,UAAb,MAAqB;;CAEnB,AAAgB;;CAGhB,AAAgB;;CAGhB,AAAgB;;CAEhB,AAAgB;;CAGhB,AAAgB;;CAGhB,AAAgB;;CAEhB,AAAgB;;CAGhB,AAAgB;;CAEhB,AAAgB;;CAGhB,AAAgB;;;;;;;;;;CAUhB,AAAgB;;CAEhB,AAAgB;CAEhB,AAAiB;;;;CAKjB,AAAO,YAAY,SAAyB;EAC1C,IAAI,CAAC,QAAQ,QAAQ,OAAO,QAAQ,SAAS,UAC3C,MAAM,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;EA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M,MAAM,cAAc,KAAK;EAC/B,MAAM,MAAM,KAAK,MAAM,cAAc,KAAK,OAAO;EACjD,OAAO;GACL,GAAG,KAAK,SAAS,OAAO,KAAK,YAAY,KAAK;GAC9C,GAAG,KAAK,SAAS,OAAO,KAAK,aAAa,KAAK;GAC/C,OAAO,KAAK;GACZ,QAAQ,KAAK;EACf;CACF;;;;;CAMA,AAAO,eAAiD;EACtD,OAAO,KAAK,aAAa,OAAO;CAClC;;;;;;CAOA,IAAW,iBAAuE;EAChF,MAAM,SAAqD,CAAC;EAC5D,KAAK,MAAM,CAAC,IAAI,QAAQ,KAAK,cAC3B,OAAO,MAAM,IAAI;EAEnB,OAAO,OAAO,OAAO,MAAM;CAC7B;AACF"}
|
|
1
|
+
{"version":3,"file":"TileSet.js","names":[],"sources":["../../src/TileSet.ts"],"sourcesContent":["import type { TextureRegion } from '@codexo/exojs';\n\nimport type { TileDefinition, TileProperties } from './types';\nimport { validateNonNegativeInteger, validatePositiveInteger } from './types';\n\n/**\n * Options for constructing a {@link TileSet}.\n * @advanced\n */\nexport interface TileSetOptions {\n /** Stable runtime name (unique within a {@link TileMap}). */\n readonly name: string;\n /** Texture atlas for this tileset. Textures are Loader-owned. */\n readonly texture: TextureRegion;\n /** Width of each tile in pixels. */\n readonly tileWidth: number;\n /** Height of each tile in pixels. */\n readonly tileHeight: number;\n /** Total number of tiles in this tileset. */\n readonly tileCount: number;\n /** Number of tile columns in the atlas grid. Computed from texture width / tileWidth if omitted. */\n readonly columns?: number;\n /** Pixel spacing between tiles in the atlas. Defaults to 0. */\n readonly spacing?: number;\n /** Pixel margin around the atlas. Defaults to 0. */\n readonly margin?: number;\n /** Tileset class/type string (Tiled `class`). Defaults to `''`. */\n readonly class?: string;\n /** Visual drawing offset in pixels applied to every tile of this set drawn by a tile layer. Defaults to 0. */\n readonly offsetX?: number;\n /** Visual drawing offset in pixels applied to every tile of this set drawn by a tile layer. Defaults to 0. */\n readonly offsetY?: number;\n}\n\n/**\n * A resolved tileset: a uniform grid of tiles within a texture atlas.\n *\n * Does **not** own its texture - the Loader or application code retains\n * texture ownership. Tileset dimensions are validated at construction and\n * frozen thereafter.\n *\n * Multiple tilesets are supported per {@link TileMap}; each carries its own\n * tile dimensions, spacing, and optional per-tile metadata.\n * @advanced\n */\nexport class TileSet {\n /** Stable runtime name. */\n public readonly name: string;\n\n /** Atlas texture region - Loader-owned, never destroyed by the tileset. */\n public readonly texture: TextureRegion;\n\n /** Tile width in pixels. */\n public readonly tileWidth: number;\n /** Tile height in pixels. */\n public readonly tileHeight: number;\n\n /** Total number of tiles in the tileset. */\n public readonly tileCount: number;\n\n /** Number of columns in the atlas grid. */\n public readonly columns: number;\n /** Number of rows implied by tileCount and columns. */\n public readonly rows: number;\n\n /** Pixel spacing between tiles in the atlas. */\n public readonly spacing: number;\n /** Pixel margin around the atlas. */\n public readonly margin: number;\n\n /** Tileset class/type string (Tiled `class`; may be empty). */\n public readonly class: string;\n /**\n * Visual drawing offset X in pixels (Tiled `tileoffset`).\n *\n * Applied by the tile-layer geometry builder and by the tile-collision\n * helpers - i.e. wherever this package places a tile on a grid. It is **not**\n * folded into a {@link TileObject}'s `x`/`y`: object layers are data-only, so\n * code that draws a tile object itself has to add this offset the way a tile\n * layer would.\n */\n public readonly offsetX: number;\n /** Visual drawing offset Y in pixels (Tiled `tileoffset`) - see {@link offsetX} for where it applies. */\n public readonly offsetY: number;\n\n private readonly _definitions: ReadonlyMap<number, TileDefinition>;\n\n /**\n * @throws When dimensions, counts, or spacing values are invalid.\n */\n public constructor(options: TileSetOptions) {\n if (!options.name || typeof options.name !== 'string') {\n throw new Error('TileSet name must be a non-empty string.');\n }\n\n if (!options.texture) {\n throw new Error('TileSet requires a valid TextureRegion.');\n }\n\n validatePositiveInteger(options.tileWidth, 'tileWidth');\n validatePositiveInteger(options.tileHeight, 'tileHeight');\n validatePositiveInteger(options.tileCount, 'tileCount');\n\n const spacing = options.spacing ?? 0;\n const margin = options.margin ?? 0;\n validateNonNegativeInteger(spacing, 'spacing');\n validateNonNegativeInteger(margin, 'margin');\n\n // A tile grid is derived from the atlas dimensions and then fixed, so it\n // cannot be built against a texture that has not loaded yet - and the\n // dimension checks below would otherwise report the resulting zeros as a\n // bad tile size rather than as the real cause.\n if (options.texture.width <= 0 || options.texture.height <= 0) {\n throw new Error(\n `TileSet needs a loaded texture to derive its grid, but \"${options.name}\" was given one measuring ` +\n `${options.texture.width}x${options.texture.height}. Await it (loader.load(...) or texture.loaded) before constructing the tile set.`,\n );\n }\n\n const atlasWidth = options.texture.width - margin * 2;\n const atlasHeight = options.texture.height - margin * 2;\n\n const columns = options.columns ?? Math.floor(atlasWidth / options.tileWidth);\n\n validatePositiveInteger(columns, 'columns');\n if (columns <= 0) {\n throw new Error(`TileSet columns must be positive (got ${columns}).`);\n }\n\n if (options.tileWidth * columns + spacing * (columns - 1) > atlasWidth) {\n throw new Error(`TileSet grid width exceeds atlas: ${options.tileWidth}*${columns}` + ` + ${spacing}*${columns - 1} > ${atlasWidth}.`);\n }\n\n const rows = Math.ceil(options.tileCount / columns);\n if (rows > 0 && options.tileHeight * rows + spacing * (rows - 1) > atlasHeight) {\n throw new Error(`TileSet grid height exceeds atlas: ${options.tileHeight}*${rows}` + ` + ${spacing}*${rows - 1} > ${atlasHeight}.`);\n }\n\n this.name = options.name;\n this.texture = options.texture;\n this.tileWidth = options.tileWidth;\n this.tileHeight = options.tileHeight;\n this.tileCount = options.tileCount;\n this.columns = columns;\n this.rows = rows;\n this.spacing = spacing;\n this.margin = margin;\n this.class = options.class ?? '';\n this.offsetX = options.offsetX ?? 0;\n this.offsetY = options.offsetY ?? 0;\n\n this._definitions = new Map();\n\n if (__DEV__) {\n Object.freeze(this);\n }\n }\n\n /**\n * Set per-tile metadata for a local tile ID.\n * Copies input to prevent caller-owned mutation leaking into the tileset.\n * @internal\n */\n public _setDefinition(localTileId: number, definition: Partial<TileDefinition>): void {\n if (localTileId < 0 || localTileId >= this.tileCount) {\n throw new Error(`Tile definition localTileId ${localTileId} out of range [0, ${this.tileCount - 1}].`);\n }\n const props = definition.properties ? Object.freeze({ ...definition.properties }) : undefined;\n const animation = definition.animation ? Object.freeze(definition.animation.map(frame => Object.freeze({ ...frame }))) : undefined;\n const collision = definition.collision ? Object.freeze([...definition.collision]) : undefined;\n (this._definitions as Map<number, TileDefinition>).set(localTileId, {\n localTileId,\n ...(props !== undefined && { properties: props }),\n ...(animation !== undefined && { animation }),\n ...(collision !== undefined && { collision }),\n });\n }\n\n /**\n * Build definitions from an array, replacing the internal definitions map.\n * Each entry's properties are copied and frozen.\n * @internal\n */\n public _setDefinitions(definitions: readonly TileDefinition[]): void {\n const map = this._definitions as Map<number, TileDefinition>;\n map.clear();\n for (const def of definitions) {\n const props = def.properties ? Object.freeze({ ...def.properties }) : undefined;\n const animation = def.animation ? Object.freeze(def.animation.map(frame => Object.freeze({ ...frame }))) : undefined;\n const collision = def.collision ? Object.freeze([...def.collision]) : undefined;\n map.set(def.localTileId, {\n localTileId: def.localTileId,\n ...(props !== undefined && { properties: props }),\n ...(animation !== undefined && { animation }),\n ...(collision !== undefined && { collision }),\n });\n }\n }\n\n /**\n * Retrieve per-tile metadata, or undefined if none defined.\n * @advanced\n */\n public getTileDefinition(localTileId: number): TileDefinition | undefined {\n return this._definitions.get(localTileId);\n }\n\n /**\n * Compute the pixel-space source rectangle for a local tile ID\n * within the atlas, accounting for columns, spacing, and margin.\n * @advanced\n */\n public getTileRect(localTileId: number): { x: number; y: number; width: number; height: number } {\n if (localTileId < 0 || localTileId >= this.tileCount) {\n throw new Error(`getTileRect: localTileId ${localTileId} out of range [0, ${this.tileCount - 1}].`);\n }\n const col = localTileId % this.columns;\n const row = Math.floor(localTileId / this.columns);\n return {\n x: this.margin + col * (this.tileWidth + this.spacing),\n y: this.margin + row * (this.tileHeight + this.spacing),\n width: this.tileWidth,\n height: this.tileHeight,\n };\n }\n\n /**\n * Iterate over all defined tiles (sparse).\n * @advanced\n */\n public definedTiles(): IterableIterator<TileDefinition> {\n return this._definitions.values();\n }\n\n /**\n * Read-only snapshot of all per-tile definitions.\n * The returned record is a caller-owned copy.\n * @advanced\n */\n public get allDefinitions(): Readonly<Record<number, TileProperties | undefined>> {\n const result: Record<number, TileProperties | undefined> = {};\n for (const [id, def] of this._definitions) {\n result[id] = def.properties;\n }\n return Object.freeze(result);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA6CA,IAAa,UAAb,MAAqB;;CAEnB,AAAgB;;CAGhB,AAAgB;;CAGhB,AAAgB;;CAEhB,AAAgB;;CAGhB,AAAgB;;CAGhB,AAAgB;;CAEhB,AAAgB;;CAGhB,AAAgB;;CAEhB,AAAgB;;CAGhB,AAAgB;;;;;;;;;;CAUhB,AAAgB;;CAEhB,AAAgB;CAEhB,AAAiB;;;;CAKjB,AAAO,YAAY,SAAyB;EAC1C,IAAI,CAAC,QAAQ,QAAQ,OAAO,QAAQ,SAAS,UAC3C,MAAM,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,SAAS;EA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,iBAAuE;EAChF,MAAM,SAAqD,CAAC;EAC5D,KAAK,MAAM,CAAC,IAAI,QAAQ,KAAK,cAC3B,OAAO,MAAM,IAAI;EAEnB,OAAO,OAAO,OAAO,MAAM;CAC7B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebGpuTileChunkRenderer.d.ts","sourceRoot":"","sources":["../../../src/webgpu/WebGpuTileChunkRenderer.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAGV,0BAA0B,EAC1B,2BAA2B,EAC3B,4BAA4B,EAC7B,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAQ,aAAa,EAAE,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"WebGpuTileChunkRenderer.d.ts","sourceRoot":"","sources":["../../../src/webgpu/WebGpuTileChunkRenderer.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAGV,0BAA0B,EAC1B,2BAA2B,EAC3B,4BAA4B,EAC7B,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAQ,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAEtE,OAAO,EACL,sBAAsB,EAWvB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AActD;;;;;;GAMG;AACH,qBAAa,uBAAwB,SAAQ,sBAAsB,CAAC,aAAa,CAAE,YAAW,2BAA2B;IACvH;;;;;;;OAOG;IACH,SAAgB,wBAAwB,QAAQ;IAEhD,OAAO,CAAC,QAAQ,CAAC,eAAe,CAA2E;IAW3G,OAAO,CAAC,YAAY,CAAqB;IACzC,OAAO,CAAC,oBAAoB,CAAM;IAClC,OAAO,CAAC,qBAAqB,CAAS;IACtC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAwB;IAEzD,OAAO,CAAC,OAAO,CAA0B;IACzC,OAAO,CAAC,aAAa,CAAgC;IACrD,OAAO,CAAC,uBAAuB,CAAmC;IAClE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4BAA4B,GAAG,IAAI;IAmBhG,0GAA0G;IACnG,0BAA0B,CAAC,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI;IAexE;;;;;;;;;;;OAWG;IACI,oBAAoB,CAAC,OAAO,EAAE,0BAA0B,GAAG,IAAI;IAkGtE,OAAO,CAAC,YAAY;IAyDpB;;;;OAIG;IACH,OAAO,CAAC,sBAAsB;IAyB9B;;;;;;OAMG;IACH,OAAO,CAAC,6BAA6B;CAqBtC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { TILE_DIAGONAL_BIT, TILE_ROW_MASK } from "../tileWord.js";
|
|
2
2
|
import tile_chunk_default from "./shaders/tile-chunk.wgsl.js";
|
|
3
|
-
import { AbstractWebGpuRenderer, DataTexture, Texture, fillShaderSource, getWebGpuBlendState, packAffineMat4, packSnapViewport, packedGroupChanged, retainedGroupUniformBytes, stencilContentDepthStencilState } from "@codexo/exojs/renderer-sdk";
|
|
3
|
+
import { AbstractWebGpuRenderer, DataTexture, Texture, fillShaderSource, getWebGpuBlendState, isSampleableTexture, packAffineMat4, packSnapViewport, packedGroupChanged, retainedGroupUniformBytes, stencilContentDepthStencilState } from "@codexo/exojs/renderer-sdk";
|
|
4
4
|
import { Matrix } from "@codexo/exojs";
|
|
5
5
|
|
|
6
6
|
//#region src/webgpu/WebGpuTileChunkRenderer.ts
|
|
@@ -153,7 +153,7 @@ var WebGpuTileChunkRenderer = class extends AbstractWebGpuRenderer {
|
|
|
153
153
|
}
|
|
154
154
|
_renderPage(backend, texture, quads, blendMode, tintRgba, nodeIndex) {
|
|
155
155
|
if (quads.length === 0) return;
|
|
156
|
-
if (texture
|
|
156
|
+
if (!isSampleableTexture(texture)) return;
|
|
157
157
|
if (texture instanceof Texture && !(texture instanceof DataTexture) && texture.source === null) return;
|
|
158
158
|
const blendModeChanged = this._currentBlendMode !== null && blendMode !== this._currentBlendMode;
|
|
159
159
|
const textureChanged = this._currentTexture !== null && texture !== this._currentTexture;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebGpuTileChunkRenderer.js","names":["tileShaderTemplate"],"sources":["../../../src/webgpu/WebGpuTileChunkRenderer.ts"],"sourcesContent":["/// <reference types=\"@webgpu/types\" />\n\nimport { Matrix } from '@codexo/exojs';\nimport type {\n RenderTexture,\n WebGpuActiveRenderPass,\n WebGpuRetainedBatchPayload,\n WebGpuRetainedBatchReplayer,\n WebGpuRetainedNodeIndexRange,\n} from '@codexo/exojs/renderer-sdk';\nimport type { View, WebGpuBackend } from '@codexo/exojs/renderer-sdk';\nimport {\n AbstractWebGpuRenderer,\n type BlendModes,\n DataTexture,\n fillShaderSource,\n getWebGpuBlendState,\n packAffineMat4,\n packedGroupChanged,\n packSnapViewport,\n retainedGroupUniformBytes,\n stencilContentDepthStencilState,\n Texture,\n} from '@codexo/exojs/renderer-sdk';\n\nimport type { TileQuad } from '../chunkGeometry';\nimport type { TileChunkNode } from '../TileChunkNode';\nimport { TILE_DIAGONAL_BIT, TILE_ROW_MASK } from '../tileWord';\nimport tileShaderTemplate from './shaders/tile-chunk.wgsl';\n\nconst instanceStrideBytes = 32;\nconst wordsPerInstance = instanceStrideBytes / Uint32Array.BYTES_PER_ELEMENT; // = 8\n// mat4x4 projection + mat4x4 group + vec4 snap viewport (aligned 16, total 144).\nconst projectionByteLength = 144;\nconst initialBatchCapacity = 256;\nconst indicesPerInstance = 6;\nconst quadIndices = new Uint16Array([0, 1, 2, 0, 2, 3]);\n\nconst tileShaderSource = fillShaderSource(tileShaderTemplate, { tileRowMask: TILE_ROW_MASK, tileDiagonalBit: TILE_DIAGONAL_BIT });\n\n/**\n * Instanced WebGPU renderer for {@link TileChunkNode}, the parity counterpart of\n * the WebGL2 renderer. Same instance layout and orientation handling; per-chunk\n * transforms ride on the backend's shared transform storage buffer, and the\n * instance buffer grows on demand rather than flushing in fixed runs.\n * @internal\n */\nexport class WebGpuTileChunkRenderer extends AbstractWebGpuRenderer<TileChunkNode> implements WebGpuRetainedBatchReplayer {\n /**\n * Retained-batch capability opt-in: a tile chunk's per-flush\n * instanced batches (fixed 32-byte layout, tile word at word 7) record and\n * replay from group-owned resources. Pixel-snapped draws are excluded by\n * the collect-time recordability predicate (and belt-and-braces poisoning\n * in {@link render}); tile chunks have no custom-material path to exclude.\n * @internal\n */\n public readonly _supportsRetainedBatches = true;\n\n private readonly _projectionData = new Float32Array(projectionByteLength / Float32Array.BYTES_PER_ELEMENT);\n // Projection-uniform skip state: a matching (view identity, view.updateId)\n // pair AND unchanged group-matrix CONTENT (compared against the packed floats\n // at [16, 32), staged into `_stagedGroupData` by `_groupContentChanged`) mean\n // the shared UBO already holds this flush's projection, so the 128-byte write\n // is skipped.\n //\n // Content comparison, not the backend's group-transform id: a projection\n // rewrite is a PASS boundary below, so a group boundary that restores\n // byte-identical group bytes must not read as a change - otherwise a retained\n // group entered and left around tile chunks splits the single-submit frame.\n private _writtenView: View | null = null;\n private _writtenViewUpdateId = -1;\n private _hasWrittenProjection = false;\n private readonly _stagedGroupData = new Float32Array(16);\n\n private _device: GPUDevice | null = null;\n private _shaderModule: GPUShaderModule | null = null;\n private _uniformBindGroupLayout: GPUBindGroupLayout | null = null;\n private _textureBindGroupLayout: GPUBindGroupLayout | null = null;\n private _pipelineLayout: GPUPipelineLayout | null = null;\n private _uniformBuffer: GPUBuffer | null = null;\n private _transformBindGroup: GPUBindGroup | null = null;\n private _transformStorageBuffer: GPUBuffer | null = null;\n private _indexBuffer: GPUBuffer | null = null;\n private _instanceBuffer: GPUBuffer | null = null;\n // Capacity of the GPU instance buffer, in BYTES: it carries every flush the\n // open pass has taken, not just the pending one. The CPU staging array is\n // sized separately (in instances) because it only ever holds one flush.\n private _instanceBufferCapacity = 0;\n private _instanceStagingCapacity = 0;\n private _instanceData: ArrayBuffer = new ArrayBuffer(0);\n private _instanceFloat32 = new Float32Array(this._instanceData);\n private _instanceUint32 = new Uint32Array(this._instanceData);\n private readonly _pipelines = new Map<string, GPURenderPipeline>();\n // group(1) texture bind groups cached per texture (mirrors the sprite/\n // nine-slice renderers): resolving `backend.getTextureBinding` is what\n // syncs a dirty/mutated texture's content to the GPU, so it must run every\n // flush/replay even when the bind group itself is served from cache.\n private _textureBindGroups = new WeakMap<Texture | RenderTexture, { group: GPUBindGroup; view: GPUTextureView; sampler: GPUSampler }>();\n\n private _quadIndex = 0;\n private _maxNodeIndex = 0;\n // Chunk nodes booked against the PENDING batch, and whether the chunk being\n // rendered right now has already been booked. One chunk emits one tile\n // instance per tile, so the recorded batch's `submittedNodes` contribution is\n // this count and not `_quadIndex`. A chunk whose pages span several batches is\n // booked once, against the batch its first page lands in.\n private _batchNodeCount = 0;\n private _nodeBooked = false;\n private _currentBlendMode: BlendModes | null = null;\n private _currentTexture: Texture | null = null;\n\n // ── Pass-scoped write cursor ──────────────────────────────────────────────\n // `flush()` no longer ends the pass, so consecutive flushes record into ONE\n // open pass and ONE submit. Everything written into the shared instance\n // buffer is therefore scoped to that pass, not to a single flush: a flush\n // that rewrote the buffer from offset 0 would have the earlier flushes' draws\n // read this flush's bytes, because `queue.writeBuffer` is ordered against the\n // submit and not against the individual draws inside it. Each flush appends\n // at `_instancePassBytes` instead and adds the base at bind time.\n //\n // `_passDraws` is the open pass this renderer has actually RECORDED draws\n // into. Pass identity is the key: the coordinator builds a fresh active-pass\n // object on every acquire, so a pass ended by anyone else (a target switch, a\n // stencil clip, another renderer) is distinguished automatically.\n private _passDraws: WebGpuActiveRenderPass | null = null;\n private _instancePassBytes = 0;\n\n // ── Retained-batch replay state ───────────────────────────────────────────\n private readonly _stagedReplayGroupData = new Float32Array(16);\n // Reused single-slot texture list handed to the backend at record time; a\n // tile chunk batch always binds exactly one tileset texture (slot 0).\n private readonly _recordTextures: Array<Texture | RenderTexture | null> = [null];\n\n protected onConnect(backend: WebGpuBackend): void {\n if (this._device) {\n return;\n }\n\n this._device = backend.device;\n this._shaderModule = this._device.createShaderModule({ code: tileShaderSource });\n\n this._uniformBindGroupLayout = this._device.createBindGroupLayout({\n entries: [\n { binding: 0, visibility: GPUShaderStage.VERTEX, buffer: { type: 'uniform' } },\n { binding: 1, visibility: GPUShaderStage.VERTEX, buffer: { type: 'read-only-storage' } },\n ],\n });\n\n this._textureBindGroupLayout = this._device.createBindGroupLayout({\n entries: [\n { binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },\n { binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: { type: 'filtering' } },\n ],\n });\n\n this._pipelineLayout = this._device.createPipelineLayout({\n bindGroupLayouts: [this._uniformBindGroupLayout, this._textureBindGroupLayout],\n });\n\n this._uniformBuffer = this._device.createBuffer({\n size: projectionByteLength,\n usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,\n });\n\n this._indexBuffer = this._device.createBuffer({\n size: quadIndices.byteLength,\n usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,\n });\n this._device.queue.writeBuffer(this._indexBuffer, 0, quadIndices.buffer, quadIndices.byteOffset, quadIndices.byteLength);\n }\n\n protected onDisconnect(): void {\n // The teardown below destroys the very buffers a draw of ours left in the\n // open pass still binds, and the pass no longer ends at the tail of a\n // flush. Submit it first so those draws reach the queue against live\n // buffers. Backend destroy and device loss drop the pass before disconnecting\n // renderers, so this only fires when a renderer is disconnected on its own.\n const coordinator = this._backend?._passCoordinator ?? null;\n\n if (coordinator !== null && this._passDraws !== null && this._passDraws === coordinator.activePass) {\n coordinator.endPass();\n }\n\n this._instanceBuffer?.destroy();\n this._indexBuffer?.destroy();\n this._uniformBuffer?.destroy();\n this._pipelines.clear();\n this._instanceBuffer = null;\n this._indexBuffer = null;\n this._transformBindGroup = null;\n this._transformStorageBuffer = null;\n // Bind groups belong to the (possibly lost) device; drop the cache so\n // reconnect rebuilds them against the fresh device.\n this._textureBindGroups = new WeakMap<Texture | RenderTexture, { group: GPUBindGroup; view: GPUTextureView; sampler: GPUSampler }>();\n this._uniformBuffer = null;\n this._pipelineLayout = null;\n this._textureBindGroupLayout = null;\n this._uniformBindGroupLayout = null;\n this._shaderModule = null;\n this._device = null;\n this._backend = null;\n this._instanceBufferCapacity = 0;\n this._instanceStagingCapacity = 0;\n this._instanceData = new ArrayBuffer(0);\n this._instanceFloat32 = new Float32Array(this._instanceData);\n this._instanceUint32 = new Uint32Array(this._instanceData);\n this._passDraws = null;\n this._instancePassBytes = 0;\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._nodeBooked = false;\n this._currentBlendMode = null;\n this._currentTexture = null;\n this._writtenView = null;\n this._writtenViewUpdateId = -1;\n this._hasWrittenProjection = false;\n }\n\n public render(node: TileChunkNode): void {\n const backend = this._backend;\n\n if (backend === null) {\n return;\n }\n\n const pages = node.pages;\n\n this._nodeBooked = false;\n\n if (pages.length === 0) {\n return;\n }\n\n const blendMode = node.blendMode;\n const tintRgba = node.tint.toRgba8();\n\n const command = backend.activeDrawCommand;\n const nodeIndex = command !== null ? command.nodeIndex : backend._pushTransform(node);\n\n for (const page of pages) {\n this._renderPage(backend, page.texture, page.quads, blendMode, tintRgba, nodeIndex);\n }\n }\n\n private _renderPage(backend: WebGpuBackend, texture: Texture, quads: readonly TileQuad[], blendMode: BlendModes, tintRgba: number, nodeIndex: number): void {\n if (quads.length === 0) {\n return;\n }\n\n if (texture.width === 0 || texture.height === 0) {\n return;\n }\n\n // A null `source` means a Texture still waiting on its image - but\n // DataTexture extends Texture and keeps its pixels in a CPU buffer, so it\n // has none by design. Without the exemption a procedurally-generated\n // tileset renders as nothing here while WebGL2, which has no such guard,\n // draws it.\n if (texture instanceof Texture && !(texture instanceof DataTexture) && texture.source === null) {\n return;\n }\n\n const blendModeChanged = this._currentBlendMode !== null && blendMode !== this._currentBlendMode;\n const textureChanged = this._currentTexture !== null && texture !== this._currentTexture;\n // Overflowing the CPU staging array flushes the accumulated run rather than\n // growing it. The GPU buffer is NOT what this asks about: it now carries\n // every flush in the pass, so flushing frees no room there - its capacity is\n // resolved in `flush()` against the pass total.\n const willExceed = this._quadIndex + quads.length > this._instanceStagingCapacity && this._instanceStagingCapacity > 0;\n\n if ((blendModeChanged || textureChanged || willExceed) && this._quadIndex > 0) {\n this.flush();\n }\n\n this._currentBlendMode = blendMode;\n this._currentTexture = texture;\n backend.setBlendMode(blendMode);\n\n this._ensureStagingCapacity(this._quadIndex + quads.length);\n\n // Booked after the flush decision above, so the chunk lands on the batch\n // that actually holds its first tile; the flag keeps a multi-page chunk from\n // being booked once per page.\n if (!this._nodeBooked) {\n this._nodeBooked = true;\n this._batchNodeCount++;\n }\n\n const f32 = this._instanceFloat32;\n const u32 = this._instanceUint32;\n const flipYTexture = texture.flipY;\n const baseWord = nodeIndex & TILE_ROW_MASK;\n\n for (const q of quads) {\n const idx = this._quadIndex * wordsPerInstance;\n\n f32[idx + 0] = q.x0;\n f32[idx + 1] = q.y0;\n f32[idx + 2] = q.x1;\n f32[idx + 3] = q.y1;\n\n const flipX = (q.orient & 1) !== 0;\n const tileFlipY = (q.orient & 2) !== 0;\n const diagonal = (q.orient & 4) !== 0;\n\n const uA = flipX ? q.u1 : q.u0;\n const uB = flipX ? q.u0 : q.u1;\n let vA = tileFlipY ? q.v1 : q.v0;\n let vB = tileFlipY ? q.v0 : q.v1;\n\n if (flipYTexture) {\n const swap = vA;\n vA = vB;\n vB = swap;\n }\n\n const uMin = (uA * 0xffff) & 0xffff;\n const vMin = (vA * 0xffff) & 0xffff;\n const uMax = (uB * 0xffff) & 0xffff;\n const vMax = (vB * 0xffff) & 0xffff;\n\n u32[idx + 4] = uMin | (vMin << 16);\n u32[idx + 5] = uMax | (vMax << 16);\n u32[idx + 6] = tintRgba;\n u32[idx + 7] = (diagonal ? baseWord | TILE_DIAGONAL_BIT : baseWord) >>> 0;\n\n this._quadIndex++;\n }\n\n if (nodeIndex > this._maxNodeIndex) {\n this._maxNodeIndex = nodeIndex;\n }\n }\n\n public flush(): void {\n const backend = this._backend;\n const device = this._device;\n const uniformBuffer = this._uniformBuffer;\n\n if (!backend || !device || !uniformBuffer) {\n return;\n }\n\n if (this._quadIndex === 0 && !backend.clearRequested) {\n return;\n }\n\n // ProjectionUniforms layout: mat4x4 projection + mat4x4 group + vec4 snap\n // viewport, packed via the shared canonical (non-transposed) column order\n // (same layout as the sprite/nine-slice renderers' group UBO). The write\n // is skipped when the UBO already holds this exact\n // (view, updateId, group bytes, snap-rect) state.\n const view = backend.view;\n const viewportChanged = packSnapViewport(backend, this._projectionData, 32);\n const projectionChanged =\n !this._hasWrittenProjection ||\n this._writtenView !== view ||\n this._writtenViewUpdateId !== view.updateId ||\n viewportChanged ||\n this._groupContentChanged(backend);\n\n const scissor = backend.getScissorRect();\n const maskClipsAll = scissor !== null && (scissor.width <= 0 || scissor.height <= 0);\n\n const coordinator = backend._passCoordinator;\n // Aliased as consts so the `willDraw` predicate narrows them for the draw\n // block below (the same narrowing the inlined condition used to provide).\n const texture = this._currentTexture;\n const blendMode = this._currentBlendMode;\n const indexBuffer = this._indexBuffer;\n const willDraw = this._quadIndex > 0 && !maskClipsAll && texture !== null && blendMode !== null && indexBuffer !== null;\n\n const flushBytes = this._quadIndex * instanceStrideBytes;\n // Sized for everything this pass has taken SO FAR plus this flush, captured\n // BEFORE the guard below may reset the cursor - and used to size the buffer\n // even when it does split. Sizing to the lone flush that remains after a\n // split would peg the buffer at one flush forever: the guard would split,\n // the split would shrink the requirement back, the capacity would never\n // ratchet, and every flush would open its own pass again.\n const targetInstanceBytes = this._instancePassBytes + flushBytes;\n const ownDrawsInPass = this._passDraws !== null && this._passDraws === coordinator.activePass;\n\n // Two predicates, deliberately different. The first gates the hazards\n // against resources only THIS renderer binds - the projection UBO (rewritten\n // at offset 0, which would retroactively re-project our earlier draws) and\n // the instance buffer (whose reallocation frees what those draws read) - so\n // it asks this renderer's own cursor. The second gates the two SHARED ones\n // (transform storage, managed texture content), which the pass may hold\n // another renderer's draws against, so it asks the coordinator. Both land on\n // the queue timeline ahead of the deferred submit, and both are answered by\n // ending (submitting) the pass first.\n if (\n (ownDrawsInPass && (projectionChanged || (willDraw && targetInstanceBytes > this._instanceBufferCapacity))) ||\n (willDraw && coordinator.passHasDraws && (backend._textureUploadWouldMutate(texture) || backend._transformStorageWouldGrow(this._maxNodeIndex + 1)))\n ) {\n coordinator.endPass();\n }\n\n // Any boundary above - or one another renderer hit since our last flush -\n // means the open pass no longer holds our draws, so the cursor restarts.\n if (this._passDraws !== coordinator.activePass) {\n this._passDraws = null;\n this._instancePassBytes = 0;\n }\n\n if (projectionChanged) {\n packAffineMat4(view.getTransform(), this._projectionData, 0);\n packAffineMat4(backend.renderGroupTransform ?? Matrix.identity, this._projectionData, 16);\n\n this._writtenView = view;\n this._writtenViewUpdateId = view.updateId;\n this._hasWrittenProjection = true;\n\n device.queue.writeBuffer(uniformBuffer, 0, this._projectionData.buffer, this._projectionData.byteOffset, this._projectionData.byteLength);\n }\n\n // A flush whose quads are entirely clipped away by the mask draws nothing,\n // so it only needs a pass at all when a clear is still pending - opened\n // here so `createColorAttachment` consumes the clear-state once. With no\n // clear pending, skip `acquirePass` entirely rather than open (and count)\n // a pass no draw will land in.\n if (willDraw || backend.clearRequested) {\n const active = coordinator.acquirePass();\n const pass = active.pass;\n\n if (willDraw) {\n const instanceBuffer = this._ensureInstanceBufferCapacity(device, targetInstanceBytes);\n const instanceByteOffset = this._instancePassBytes;\n\n device.queue.writeBuffer(instanceBuffer, instanceByteOffset, this._instanceData, 0, flushBytes);\n\n const storage = backend.getTransformStorageBuffer(this._maxNodeIndex + 1);\n const transformBindGroup = this._getOrCreateTransformBindGroup(device, uniformBuffer, storage.buffer);\n const textureBindGroup = this._getOrCreateTextureBindGroup(device, backend, texture);\n\n const stencil = coordinator.stencilActive;\n const pipeline = this._getPipeline(blendMode, backend.renderTargetFormat, stencil);\n\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, transformBindGroup);\n pass.setBindGroup(1, textureBindGroup);\n pass.setVertexBuffer(0, instanceBuffer, instanceByteOffset);\n pass.setIndexBuffer(indexBuffer, 'uint16');\n pass.drawIndexed(indicesPerInstance, this._quadIndex, 0, 0, 0);\n\n // The pass stays open; the cursor carries this flush's consumption forward\n // so the next flush in the same pass appends AFTER the slice these draws\n // read instead of overwriting it.\n this._instancePassBytes = instanceByteOffset + flushBytes;\n this._passDraws = active;\n coordinator.markPassDraws();\n backend.stats.batches++;\n backend.stats.drawCalls++;\n }\n }\n\n // Retained capture: while a capture window is active, additionally stage\n // this batch's exact packed bytes into the group-owned bundle - the\n // recorded data IS the drawn data, byte-identical by construction.\n // Recorded regardless of the live visibility decision above (mask/\n // scissor), since visibility is re-evaluated live at replay. A batch\n // always binds a single tileset texture (slot 0); a pixel-snapped node\n // already poisoned the capture in render().\n if (this._quadIndex > 0 && backend._retainedCaptureActive && blendMode !== null && texture !== null) {\n this._recordTextures[0] = texture;\n backend._recordRetainedBatch(this, this._instanceData, flushBytes, this._quadIndex, blendMode, this._recordTextures, 1, null, null, this._batchNodeCount);\n }\n\n // The pass is deliberately left OPEN. It ends at genuine boundaries only\n // (the backend's frame/plan end, a target or view switch, a stencil clip)\n // and at the hazard splits above, so N tile-chunk flushes in a frame cost\n // one pass and one submit rather than N.\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._currentBlendMode = null;\n this._currentTexture = null;\n }\n\n /**\n * Whether the packed floats of the active group matrix differ from what the\n * shared projection UBO currently holds at [16, 32). Stages the packed matrix\n * into `_stagedGroupData` as a side effect (idempotent - safe to call more\n * than once per flush).\n */\n private _groupContentChanged(backend: WebGpuBackend): boolean {\n packAffineMat4(backend.renderGroupTransform ?? Matrix.identity, this._stagedGroupData, 0);\n\n if (!this._hasWrittenProjection) {\n return true;\n }\n\n return packedGroupChanged(this._stagedGroupData, this._projectionData, 16);\n }\n\n public destroy(): void {\n this.disconnect();\n }\n\n private _getOrCreateTransformBindGroup(device: GPUDevice, uniformBuffer: GPUBuffer, storageBuffer: GPUBuffer): GPUBindGroup {\n if (this._transformBindGroup !== null && this._transformStorageBuffer === storageBuffer) {\n return this._transformBindGroup;\n }\n\n this._transformStorageBuffer = storageBuffer;\n this._transformBindGroup = device.createBindGroup({\n layout: this._uniformBindGroupLayout!,\n entries: [\n { binding: 0, resource: { buffer: uniformBuffer } },\n { binding: 1, resource: { buffer: storageBuffer } },\n ],\n });\n\n return this._transformBindGroup;\n }\n\n /**\n * Build (or reuse) the group(1) texture bind group for `texture`. The\n * binding is resolved BEFORE the cache lookup on purpose: resolving is what\n * syncs a dirty/mutated texture's content to the GPU, so it must run every\n * flush/replay even when the bind group itself is served from cache.\n */\n private _getOrCreateTextureBindGroup(device: GPUDevice, backend: WebGpuBackend, texture: Texture | RenderTexture): GPUBindGroup {\n const { view, sampler } = backend.getTextureBinding(texture);\n const cached = this._textureBindGroups.get(texture);\n\n if (cached?.view === view && cached.sampler === sampler) {\n return cached.group;\n }\n\n const group = device.createBindGroup({\n layout: this._textureBindGroupLayout!,\n entries: [\n { binding: 0, resource: view },\n { binding: 1, resource: sampler },\n ],\n });\n\n this._textureBindGroups.set(texture, { group, view, sampler });\n\n return group;\n }\n\n // ── Retained-batch record/replay ──────────────────────────────────────────\n // The bundle/stage stores raw instance bytes; this renderer owns the\n // 32-byte (8-word) layout (tile word at word 7: transform row in bits\n // 0..28, diagonal flip in bit 29), so the layout-aware finalize steps\n // (node-index scan/rebase) and the replay dispatch live here - mirroring\n // WebGpuNineSliceSpriteRenderer's seam.\n\n /** @internal See {@link WebGpuRetainedBatchReplayer._scanRetainedNodeIndexRange}. */\n public _scanRetainedNodeIndexRange(bytes: Uint8Array, range: WebGpuRetainedNodeIndexRange): void {\n const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / Uint32Array.BYTES_PER_ELEMENT);\n\n for (let i = 7; i < words.length; i += 8) {\n // In-bounds: i < words.length via the loop guard. The tile word is the\n // last word of the 32-byte (8-word) instance layout; only the low 29\n // bits address the transform buffer row.\n const row = words[i]! & TILE_ROW_MASK;\n\n if (row < range.min) {\n range.min = row;\n }\n\n if (row > range.max) {\n range.max = row;\n }\n }\n }\n\n /** @internal See {@link WebGpuRetainedBatchReplayer._rebaseRetainedNodeIndices} (group-local indices). */\n public _rebaseRetainedNodeIndices(bytes: Uint8Array, base: number): void {\n const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / Uint32Array.BYTES_PER_ELEMENT);\n\n for (let i = 7; i < words.length; i += 8) {\n // In-bounds: i < words.length via the loop guard. Rebase ONLY the row\n // field; the diagonal-flip bit must survive untouched or tile\n // orientation corrupts.\n const word = words[i]!;\n const diagonal = word & TILE_DIAGONAL_BIT;\n const row = word & TILE_ROW_MASK;\n\n words[i] = (diagonal | ((row - base) & TILE_ROW_MASK)) >>> 0;\n }\n }\n\n /**\n * Replay one recorded batch from its group-owned bundle into the OPEN pass.\n * Reuses only recorded DATA (instance bytes, transform rows, texture, blend\n * mode); every piece of STATE is resolved live - pipeline via the\n * `_getPipeline` cache, the group(1) texture bind group via the live\n * texture-set cache (resolving re-syncs dirty content), and the group's\n * 128-byte UBO (projection from the live view + the live composed group\n * matrix) written only when its content changed. The same-frame\n * double-replay hazard (one group under two views while the open pass\n * already holds this bundle's draws) ends the pass first.\n * @internal\n */\n public _replayRetainedBatch(payload: WebGpuRetainedBatchPayload): void {\n const backend = this._backend;\n const device = this._device;\n const bundle = payload.bundle;\n\n if (!backend || !device || this._indexBuffer === null || !bundle.isReady) {\n return;\n }\n\n // Drain any pending live batch first (defensive - the group boundary\n // already flushed; flush() is a no-op when nothing is pending).\n this.flush();\n\n // Match the live path's visibility handling: a fully-clipped scissor\n // draws nothing (the batch stays recorded; visibility is live per frame).\n const scissor = backend.getScissorRect();\n\n if (scissor !== null && (scissor.width <= 0 || scissor.height <= 0)) {\n return;\n }\n\n const coordinator = backend._passCoordinator;\n\n // Same-frame texture mutation guard: resolving the bindings below\n // re-uploads mutated content on the queue timeline BEFORE the deferred\n // submit, which would retroactively change draws already recorded into\n // the open pass. End (submit) the pass first so they keep the\n // pre-mutation content. The texture cache is shared and the pass survives\n // a renderer switch, so any recorded draw is at risk, not just one of ours.\n if (coordinator.passHasDraws) {\n for (const texture of payload.textures) {\n if (backend._textureUploadWouldMutate(texture)) {\n coordinator.endPass();\n break;\n }\n }\n }\n\n // Resolve the single tileset texture LIVE through the texture bind-group\n // cache (syncs dirty content, adopts refreshed views/samplers). The\n // recorded batch always has exactly one texture (slot 0).\n const textureBindGroup = this._getOrCreateTextureBindGroup(device, backend, payload.textures[0]!);\n\n // Group UBO: skip the write while (view, updateId, group bytes) match\n // what the buffer holds; guard the double-replay aliasing case first.\n const view = backend.view;\n const scratch = this._stagedReplayGroupData;\n\n packAffineMat4(backend.renderGroupTransform ?? Matrix.identity, scratch, 0);\n\n // Staged unconditionally: an unchanged rect makes this an identity write,\n // while a changed one forces the rewrite the skip state cannot see.\n const viewportChanged = packSnapViewport(backend, bundle.uboData, 32);\n\n let uboDirty = !bundle.uboWritten || bundle.uboView !== view || bundle.uboViewUpdateId !== view.updateId || viewportChanged;\n\n if (!uboDirty) {\n for (let i = 0; i < 16; i++) {\n if (scratch[i] !== bundle.uboData[16 + i]) {\n uboDirty = true;\n break;\n }\n }\n }\n\n if (uboDirty) {\n const activePass = coordinator.activePass;\n\n if (activePass !== null && bundle.drawsInPass === activePass) {\n // Rewriting the UBO would retroactively re-project this bundle's\n // draws already recorded into the open pass: end it first.\n coordinator.endPass();\n }\n\n packAffineMat4(view.getTransform(), bundle.uboData, 0);\n bundle.uboData.set(scratch, 16);\n bundle.uboView = view;\n bundle.uboViewUpdateId = view.updateId;\n bundle.uboWritten = true;\n device.queue.writeBuffer(bundle.uniformBuffer!, 0, bundle.uboData.buffer, bundle.uboData.byteOffset, retainedGroupUniformBytes);\n }\n\n const active = coordinator.acquirePass();\n const pass = active.pass;\n\n pass.setPipeline(this._getPipeline(payload.blendMode, backend.renderTargetFormat, coordinator.stencilActive));\n pass.setBindGroup(0, bundle.getBindGroup(device, this._uniformBindGroupLayout!, false));\n pass.setBindGroup(1, textureBindGroup);\n pass.setVertexBuffer(0, bundle.instanceBuffer, payload.byteOffset);\n pass.setIndexBuffer(this._indexBuffer, 'uint16');\n pass.drawIndexed(indicesPerInstance, payload.instanceCount, 0, 0, 0);\n\n bundle.drawsInPass = active;\n coordinator.markPassDraws();\n backend.stats.batches++;\n backend.stats.drawCalls++;\n }\n\n private _getPipeline(blendMode: BlendModes, format: GPUTextureFormat, stencil: boolean): GPURenderPipeline {\n const key = `${blendMode}:${format}:${stencil ? 's' : 'n'}`;\n const existing = this._pipelines.get(key);\n\n if (existing) {\n return existing;\n }\n\n if (!this._device || !this._shaderModule || !this._pipelineLayout) {\n throw new Error('WebGpuTileChunkRenderer: renderer must be connected first.');\n }\n\n const descriptor: GPURenderPipelineDescriptor = {\n layout: this._pipelineLayout,\n vertex: {\n module: this._shaderModule,\n entryPoint: 'vertexMain',\n buffers: [\n {\n arrayStride: instanceStrideBytes,\n stepMode: 'instance',\n attributes: [\n { shaderLocation: 0, offset: 0, format: 'float32x4' },\n { shaderLocation: 1, offset: 16, format: 'unorm16x4' },\n { shaderLocation: 2, offset: 24, format: 'unorm8x4' },\n { shaderLocation: 3, offset: 28, format: 'uint32' },\n ],\n },\n ],\n },\n fragment: {\n module: this._shaderModule,\n entryPoint: 'fragmentMain',\n targets: [\n {\n format,\n blend: getWebGpuBlendState(blendMode),\n writeMask: GPUColorWrite.ALL,\n },\n ],\n },\n primitive: {\n topology: 'triangle-list',\n },\n };\n\n if (stencil) {\n descriptor.depthStencil = stencilContentDepthStencilState();\n }\n\n const pipeline = this._device.createRenderPipeline(descriptor);\n\n this._pipelines.set(key, pipeline);\n\n return pipeline;\n }\n\n /**\n * Grow the CPU staging array to hold `instanceCount` instances, carrying the\n * quads packed so far. Flush-local: the array only ever holds the pending\n * batch, so it is sized independently of the pass-scoped GPU buffer.\n */\n private _ensureStagingCapacity(instanceCount: number): void {\n if (instanceCount <= this._instanceStagingCapacity) {\n return;\n }\n\n let nextCapacity = Math.max(this._instanceStagingCapacity, initialBatchCapacity);\n\n while (nextCapacity < instanceCount) {\n nextCapacity *= 2;\n }\n\n const oldData = this._instanceData;\n const carryBytes = Math.min(this._quadIndex * instanceStrideBytes, oldData.byteLength);\n const instanceData = new ArrayBuffer(nextCapacity * instanceStrideBytes);\n\n if (carryBytes > 0) {\n new Uint8Array(instanceData).set(new Uint8Array(oldData, 0, carryBytes));\n }\n\n this._instanceStagingCapacity = nextCapacity;\n this._instanceData = instanceData;\n this._instanceFloat32 = new Float32Array(instanceData);\n this._instanceUint32 = new Uint32Array(instanceData);\n }\n\n /**\n * Resolve the GPU instance buffer for `requiredBytes` - the total this pass\n * would reach by appending, not this flush's own bytes. Reallocation frees the\n * buffer earlier draws in the open pass read, so the caller must have ended\n * that pass (and restarted the cursor) before a growing call. Capacity\n * doubles, so the split a growth costs converges away within a frame or two.\n */\n private _ensureInstanceBufferCapacity(device: GPUDevice, requiredBytes: number): GPUBuffer {\n const existing = this._instanceBuffer;\n\n if (existing !== null && requiredBytes <= this._instanceBufferCapacity) {\n return existing;\n }\n\n const nextCapacity = Math.max(this._instanceBufferCapacity * 2, requiredBytes, initialBatchCapacity * instanceStrideBytes);\n const instanceBuffer = device.createBuffer({\n label: 'tile-chunk:instance-buffer',\n size: nextCapacity,\n usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,\n });\n\n existing?.destroy();\n\n this._instanceBufferCapacity = nextCapacity;\n this._instanceBuffer = instanceBuffer;\n\n return instanceBuffer;\n }\n}\n"],"mappings":";;;;;;AA8BA,MAAM,sBAAsB;AAC5B,MAAM,mBAAmB,sBAAsB,YAAY;AAE3D,MAAM,uBAAuB;AAC7B,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AAC3B,MAAM,cAAc,IAAI,YAAY;CAAC;CAAG;CAAG;CAAG;CAAG;CAAG;AAAC,CAAC;AAEtD,MAAM,mBAAmB,iBAAiBA,oBAAoB;CAAE,aAAa;CAAe,iBAAiB;AAAkB,CAAC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G,eAAe,uBAAuB,mBAAmB;EACzH,MAAM,iBAAiB,OAAO,aAAa;GACzC,OAAO;GACP,MAAM;GACN,OAAO,eAAe,SAAS,eAAe;EAChD,CAAC;EAED,UAAU,QAAQ;EAElB,KAAK,0BAA0B;EAC/B,KAAK,kBAAkB;EAEvB,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"WebGpuTileChunkRenderer.js","names":["tileShaderTemplate"],"sources":["../../../src/webgpu/WebGpuTileChunkRenderer.ts"],"sourcesContent":["/// <reference types=\"@webgpu/types\" />\n\nimport { Matrix } from '@codexo/exojs';\nimport type {\n RenderTexture,\n WebGpuActiveRenderPass,\n WebGpuRetainedBatchPayload,\n WebGpuRetainedBatchReplayer,\n WebGpuRetainedNodeIndexRange,\n} from '@codexo/exojs/renderer-sdk';\nimport type { View, WebGpuBackend } from '@codexo/exojs/renderer-sdk';\nimport { isSampleableTexture } from '@codexo/exojs/renderer-sdk';\nimport {\n AbstractWebGpuRenderer,\n type BlendModes,\n DataTexture,\n fillShaderSource,\n getWebGpuBlendState,\n packAffineMat4,\n packedGroupChanged,\n packSnapViewport,\n retainedGroupUniformBytes,\n stencilContentDepthStencilState,\n Texture,\n} from '@codexo/exojs/renderer-sdk';\n\nimport type { TileQuad } from '../chunkGeometry';\nimport type { TileChunkNode } from '../TileChunkNode';\nimport { TILE_DIAGONAL_BIT, TILE_ROW_MASK } from '../tileWord';\nimport tileShaderTemplate from './shaders/tile-chunk.wgsl';\n\nconst instanceStrideBytes = 32;\nconst wordsPerInstance = instanceStrideBytes / Uint32Array.BYTES_PER_ELEMENT; // = 8\n// mat4x4 projection + mat4x4 group + vec4 snap viewport (aligned 16, total 144).\nconst projectionByteLength = 144;\nconst initialBatchCapacity = 256;\nconst indicesPerInstance = 6;\nconst quadIndices = new Uint16Array([0, 1, 2, 0, 2, 3]);\n\nconst tileShaderSource = fillShaderSource(tileShaderTemplate, { tileRowMask: TILE_ROW_MASK, tileDiagonalBit: TILE_DIAGONAL_BIT });\n\n/**\n * Instanced WebGPU renderer for {@link TileChunkNode}, the parity counterpart of\n * the WebGL2 renderer. Same instance layout and orientation handling; per-chunk\n * transforms ride on the backend's shared transform storage buffer, and the\n * instance buffer grows on demand rather than flushing in fixed runs.\n * @internal\n */\nexport class WebGpuTileChunkRenderer extends AbstractWebGpuRenderer<TileChunkNode> implements WebGpuRetainedBatchReplayer {\n /**\n * Retained-batch capability opt-in: a tile chunk's per-flush\n * instanced batches (fixed 32-byte layout, tile word at word 7) record and\n * replay from group-owned resources. Pixel-snapped draws are excluded by\n * the collect-time recordability predicate (and belt-and-braces poisoning\n * in {@link render}); tile chunks have no custom-material path to exclude.\n * @internal\n */\n public readonly _supportsRetainedBatches = true;\n\n private readonly _projectionData = new Float32Array(projectionByteLength / Float32Array.BYTES_PER_ELEMENT);\n // Projection-uniform skip state: a matching (view identity, view.updateId)\n // pair AND unchanged group-matrix CONTENT (compared against the packed floats\n // at [16, 32), staged into `_stagedGroupData` by `_groupContentChanged`) mean\n // the shared UBO already holds this flush's projection, so the 128-byte write\n // is skipped.\n //\n // Content comparison, not the backend's group-transform id: a projection\n // rewrite is a PASS boundary below, so a group boundary that restores\n // byte-identical group bytes must not read as a change - otherwise a retained\n // group entered and left around tile chunks splits the single-submit frame.\n private _writtenView: View | null = null;\n private _writtenViewUpdateId = -1;\n private _hasWrittenProjection = false;\n private readonly _stagedGroupData = new Float32Array(16);\n\n private _device: GPUDevice | null = null;\n private _shaderModule: GPUShaderModule | null = null;\n private _uniformBindGroupLayout: GPUBindGroupLayout | null = null;\n private _textureBindGroupLayout: GPUBindGroupLayout | null = null;\n private _pipelineLayout: GPUPipelineLayout | null = null;\n private _uniformBuffer: GPUBuffer | null = null;\n private _transformBindGroup: GPUBindGroup | null = null;\n private _transformStorageBuffer: GPUBuffer | null = null;\n private _indexBuffer: GPUBuffer | null = null;\n private _instanceBuffer: GPUBuffer | null = null;\n // Capacity of the GPU instance buffer, in BYTES: it carries every flush the\n // open pass has taken, not just the pending one. The CPU staging array is\n // sized separately (in instances) because it only ever holds one flush.\n private _instanceBufferCapacity = 0;\n private _instanceStagingCapacity = 0;\n private _instanceData: ArrayBuffer = new ArrayBuffer(0);\n private _instanceFloat32 = new Float32Array(this._instanceData);\n private _instanceUint32 = new Uint32Array(this._instanceData);\n private readonly _pipelines = new Map<string, GPURenderPipeline>();\n // group(1) texture bind groups cached per texture (mirrors the sprite/\n // nine-slice renderers): resolving `backend.getTextureBinding` is what\n // syncs a dirty/mutated texture's content to the GPU, so it must run every\n // flush/replay even when the bind group itself is served from cache.\n private _textureBindGroups = new WeakMap<Texture | RenderTexture, { group: GPUBindGroup; view: GPUTextureView; sampler: GPUSampler }>();\n\n private _quadIndex = 0;\n private _maxNodeIndex = 0;\n // Chunk nodes booked against the PENDING batch, and whether the chunk being\n // rendered right now has already been booked. One chunk emits one tile\n // instance per tile, so the recorded batch's `submittedNodes` contribution is\n // this count and not `_quadIndex`. A chunk whose pages span several batches is\n // booked once, against the batch its first page lands in.\n private _batchNodeCount = 0;\n private _nodeBooked = false;\n private _currentBlendMode: BlendModes | null = null;\n private _currentTexture: Texture | null = null;\n\n // ── Pass-scoped write cursor ──────────────────────────────────────────────\n // `flush()` no longer ends the pass, so consecutive flushes record into ONE\n // open pass and ONE submit. Everything written into the shared instance\n // buffer is therefore scoped to that pass, not to a single flush: a flush\n // that rewrote the buffer from offset 0 would have the earlier flushes' draws\n // read this flush's bytes, because `queue.writeBuffer` is ordered against the\n // submit and not against the individual draws inside it. Each flush appends\n // at `_instancePassBytes` instead and adds the base at bind time.\n //\n // `_passDraws` is the open pass this renderer has actually RECORDED draws\n // into. Pass identity is the key: the coordinator builds a fresh active-pass\n // object on every acquire, so a pass ended by anyone else (a target switch, a\n // stencil clip, another renderer) is distinguished automatically.\n private _passDraws: WebGpuActiveRenderPass | null = null;\n private _instancePassBytes = 0;\n\n // ── Retained-batch replay state ───────────────────────────────────────────\n private readonly _stagedReplayGroupData = new Float32Array(16);\n // Reused single-slot texture list handed to the backend at record time; a\n // tile chunk batch always binds exactly one tileset texture (slot 0).\n private readonly _recordTextures: Array<Texture | RenderTexture | null> = [null];\n\n protected onConnect(backend: WebGpuBackend): void {\n if (this._device) {\n return;\n }\n\n this._device = backend.device;\n this._shaderModule = this._device.createShaderModule({ code: tileShaderSource });\n\n this._uniformBindGroupLayout = this._device.createBindGroupLayout({\n entries: [\n { binding: 0, visibility: GPUShaderStage.VERTEX, buffer: { type: 'uniform' } },\n { binding: 1, visibility: GPUShaderStage.VERTEX, buffer: { type: 'read-only-storage' } },\n ],\n });\n\n this._textureBindGroupLayout = this._device.createBindGroupLayout({\n entries: [\n { binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float' } },\n { binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: { type: 'filtering' } },\n ],\n });\n\n this._pipelineLayout = this._device.createPipelineLayout({\n bindGroupLayouts: [this._uniformBindGroupLayout, this._textureBindGroupLayout],\n });\n\n this._uniformBuffer = this._device.createBuffer({\n size: projectionByteLength,\n usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,\n });\n\n this._indexBuffer = this._device.createBuffer({\n size: quadIndices.byteLength,\n usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,\n });\n this._device.queue.writeBuffer(this._indexBuffer, 0, quadIndices.buffer, quadIndices.byteOffset, quadIndices.byteLength);\n }\n\n protected onDisconnect(): void {\n // The teardown below destroys the very buffers a draw of ours left in the\n // open pass still binds, and the pass no longer ends at the tail of a\n // flush. Submit it first so those draws reach the queue against live\n // buffers. Backend destroy and device loss drop the pass before disconnecting\n // renderers, so this only fires when a renderer is disconnected on its own.\n const coordinator = this._backend?._passCoordinator ?? null;\n\n if (coordinator !== null && this._passDraws !== null && this._passDraws === coordinator.activePass) {\n coordinator.endPass();\n }\n\n this._instanceBuffer?.destroy();\n this._indexBuffer?.destroy();\n this._uniformBuffer?.destroy();\n this._pipelines.clear();\n this._instanceBuffer = null;\n this._indexBuffer = null;\n this._transformBindGroup = null;\n this._transformStorageBuffer = null;\n // Bind groups belong to the (possibly lost) device; drop the cache so\n // reconnect rebuilds them against the fresh device.\n this._textureBindGroups = new WeakMap<Texture | RenderTexture, { group: GPUBindGroup; view: GPUTextureView; sampler: GPUSampler }>();\n this._uniformBuffer = null;\n this._pipelineLayout = null;\n this._textureBindGroupLayout = null;\n this._uniformBindGroupLayout = null;\n this._shaderModule = null;\n this._device = null;\n this._backend = null;\n this._instanceBufferCapacity = 0;\n this._instanceStagingCapacity = 0;\n this._instanceData = new ArrayBuffer(0);\n this._instanceFloat32 = new Float32Array(this._instanceData);\n this._instanceUint32 = new Uint32Array(this._instanceData);\n this._passDraws = null;\n this._instancePassBytes = 0;\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._nodeBooked = false;\n this._currentBlendMode = null;\n this._currentTexture = null;\n this._writtenView = null;\n this._writtenViewUpdateId = -1;\n this._hasWrittenProjection = false;\n }\n\n public render(node: TileChunkNode): void {\n const backend = this._backend;\n\n if (backend === null) {\n return;\n }\n\n const pages = node.pages;\n\n this._nodeBooked = false;\n\n if (pages.length === 0) {\n return;\n }\n\n const blendMode = node.blendMode;\n const tintRgba = node.tint.toRgba8();\n\n const command = backend.activeDrawCommand;\n const nodeIndex = command !== null ? command.nodeIndex : backend._pushTransform(node);\n\n for (const page of pages) {\n this._renderPage(backend, page.texture, page.quads, blendMode, tintRgba, nodeIndex);\n }\n }\n\n private _renderPage(backend: WebGpuBackend, texture: Texture, quads: readonly TileQuad[], blendMode: BlendModes, tintRgba: number, nodeIndex: number): void {\n if (quads.length === 0) {\n return;\n }\n\n if (!isSampleableTexture(texture)) {\n return;\n }\n\n // A null `source` means a Texture still waiting on its image - but\n // DataTexture extends Texture and keeps its pixels in a CPU buffer, so it\n // has none by design. Without the exemption a procedurally-generated\n // tileset renders as nothing here while WebGL2, which has no such guard,\n // draws it.\n if (texture instanceof Texture && !(texture instanceof DataTexture) && texture.source === null) {\n return;\n }\n\n const blendModeChanged = this._currentBlendMode !== null && blendMode !== this._currentBlendMode;\n const textureChanged = this._currentTexture !== null && texture !== this._currentTexture;\n // Overflowing the CPU staging array flushes the accumulated run rather than\n // growing it. The GPU buffer is NOT what this asks about: it now carries\n // every flush in the pass, so flushing frees no room there - its capacity is\n // resolved in `flush()` against the pass total.\n const willExceed = this._quadIndex + quads.length > this._instanceStagingCapacity && this._instanceStagingCapacity > 0;\n\n if ((blendModeChanged || textureChanged || willExceed) && this._quadIndex > 0) {\n this.flush();\n }\n\n this._currentBlendMode = blendMode;\n this._currentTexture = texture;\n backend.setBlendMode(blendMode);\n\n this._ensureStagingCapacity(this._quadIndex + quads.length);\n\n // Booked after the flush decision above, so the chunk lands on the batch\n // that actually holds its first tile; the flag keeps a multi-page chunk from\n // being booked once per page.\n if (!this._nodeBooked) {\n this._nodeBooked = true;\n this._batchNodeCount++;\n }\n\n const f32 = this._instanceFloat32;\n const u32 = this._instanceUint32;\n const flipYTexture = texture.flipY;\n const baseWord = nodeIndex & TILE_ROW_MASK;\n\n for (const q of quads) {\n const idx = this._quadIndex * wordsPerInstance;\n\n f32[idx + 0] = q.x0;\n f32[idx + 1] = q.y0;\n f32[idx + 2] = q.x1;\n f32[idx + 3] = q.y1;\n\n const flipX = (q.orient & 1) !== 0;\n const tileFlipY = (q.orient & 2) !== 0;\n const diagonal = (q.orient & 4) !== 0;\n\n const uA = flipX ? q.u1 : q.u0;\n const uB = flipX ? q.u0 : q.u1;\n let vA = tileFlipY ? q.v1 : q.v0;\n let vB = tileFlipY ? q.v0 : q.v1;\n\n if (flipYTexture) {\n const swap = vA;\n vA = vB;\n vB = swap;\n }\n\n const uMin = (uA * 0xffff) & 0xffff;\n const vMin = (vA * 0xffff) & 0xffff;\n const uMax = (uB * 0xffff) & 0xffff;\n const vMax = (vB * 0xffff) & 0xffff;\n\n u32[idx + 4] = uMin | (vMin << 16);\n u32[idx + 5] = uMax | (vMax << 16);\n u32[idx + 6] = tintRgba;\n u32[idx + 7] = (diagonal ? baseWord | TILE_DIAGONAL_BIT : baseWord) >>> 0;\n\n this._quadIndex++;\n }\n\n if (nodeIndex > this._maxNodeIndex) {\n this._maxNodeIndex = nodeIndex;\n }\n }\n\n public flush(): void {\n const backend = this._backend;\n const device = this._device;\n const uniformBuffer = this._uniformBuffer;\n\n if (!backend || !device || !uniformBuffer) {\n return;\n }\n\n if (this._quadIndex === 0 && !backend.clearRequested) {\n return;\n }\n\n // ProjectionUniforms layout: mat4x4 projection + mat4x4 group + vec4 snap\n // viewport, packed via the shared canonical (non-transposed) column order\n // (same layout as the sprite/nine-slice renderers' group UBO). The write\n // is skipped when the UBO already holds this exact\n // (view, updateId, group bytes, snap-rect) state.\n const view = backend.view;\n const viewportChanged = packSnapViewport(backend, this._projectionData, 32);\n const projectionChanged =\n !this._hasWrittenProjection ||\n this._writtenView !== view ||\n this._writtenViewUpdateId !== view.updateId ||\n viewportChanged ||\n this._groupContentChanged(backend);\n\n const scissor = backend.getScissorRect();\n const maskClipsAll = scissor !== null && (scissor.width <= 0 || scissor.height <= 0);\n\n const coordinator = backend._passCoordinator;\n // Aliased as consts so the `willDraw` predicate narrows them for the draw\n // block below (the same narrowing the inlined condition used to provide).\n const texture = this._currentTexture;\n const blendMode = this._currentBlendMode;\n const indexBuffer = this._indexBuffer;\n const willDraw = this._quadIndex > 0 && !maskClipsAll && texture !== null && blendMode !== null && indexBuffer !== null;\n\n const flushBytes = this._quadIndex * instanceStrideBytes;\n // Sized for everything this pass has taken SO FAR plus this flush, captured\n // BEFORE the guard below may reset the cursor - and used to size the buffer\n // even when it does split. Sizing to the lone flush that remains after a\n // split would peg the buffer at one flush forever: the guard would split,\n // the split would shrink the requirement back, the capacity would never\n // ratchet, and every flush would open its own pass again.\n const targetInstanceBytes = this._instancePassBytes + flushBytes;\n const ownDrawsInPass = this._passDraws !== null && this._passDraws === coordinator.activePass;\n\n // Two predicates, deliberately different. The first gates the hazards\n // against resources only THIS renderer binds - the projection UBO (rewritten\n // at offset 0, which would retroactively re-project our earlier draws) and\n // the instance buffer (whose reallocation frees what those draws read) - so\n // it asks this renderer's own cursor. The second gates the two SHARED ones\n // (transform storage, managed texture content), which the pass may hold\n // another renderer's draws against, so it asks the coordinator. Both land on\n // the queue timeline ahead of the deferred submit, and both are answered by\n // ending (submitting) the pass first.\n if (\n (ownDrawsInPass && (projectionChanged || (willDraw && targetInstanceBytes > this._instanceBufferCapacity))) ||\n (willDraw && coordinator.passHasDraws && (backend._textureUploadWouldMutate(texture) || backend._transformStorageWouldGrow(this._maxNodeIndex + 1)))\n ) {\n coordinator.endPass();\n }\n\n // Any boundary above - or one another renderer hit since our last flush -\n // means the open pass no longer holds our draws, so the cursor restarts.\n if (this._passDraws !== coordinator.activePass) {\n this._passDraws = null;\n this._instancePassBytes = 0;\n }\n\n if (projectionChanged) {\n packAffineMat4(view.getTransform(), this._projectionData, 0);\n packAffineMat4(backend.renderGroupTransform ?? Matrix.identity, this._projectionData, 16);\n\n this._writtenView = view;\n this._writtenViewUpdateId = view.updateId;\n this._hasWrittenProjection = true;\n\n device.queue.writeBuffer(uniformBuffer, 0, this._projectionData.buffer, this._projectionData.byteOffset, this._projectionData.byteLength);\n }\n\n // A flush whose quads are entirely clipped away by the mask draws nothing,\n // so it only needs a pass at all when a clear is still pending - opened\n // here so `createColorAttachment` consumes the clear-state once. With no\n // clear pending, skip `acquirePass` entirely rather than open (and count)\n // a pass no draw will land in.\n if (willDraw || backend.clearRequested) {\n const active = coordinator.acquirePass();\n const pass = active.pass;\n\n if (willDraw) {\n const instanceBuffer = this._ensureInstanceBufferCapacity(device, targetInstanceBytes);\n const instanceByteOffset = this._instancePassBytes;\n\n device.queue.writeBuffer(instanceBuffer, instanceByteOffset, this._instanceData, 0, flushBytes);\n\n const storage = backend.getTransformStorageBuffer(this._maxNodeIndex + 1);\n const transformBindGroup = this._getOrCreateTransformBindGroup(device, uniformBuffer, storage.buffer);\n const textureBindGroup = this._getOrCreateTextureBindGroup(device, backend, texture);\n\n const stencil = coordinator.stencilActive;\n const pipeline = this._getPipeline(blendMode, backend.renderTargetFormat, stencil);\n\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, transformBindGroup);\n pass.setBindGroup(1, textureBindGroup);\n pass.setVertexBuffer(0, instanceBuffer, instanceByteOffset);\n pass.setIndexBuffer(indexBuffer, 'uint16');\n pass.drawIndexed(indicesPerInstance, this._quadIndex, 0, 0, 0);\n\n // The pass stays open; the cursor carries this flush's consumption forward\n // so the next flush in the same pass appends AFTER the slice these draws\n // read instead of overwriting it.\n this._instancePassBytes = instanceByteOffset + flushBytes;\n this._passDraws = active;\n coordinator.markPassDraws();\n backend.stats.batches++;\n backend.stats.drawCalls++;\n }\n }\n\n // Retained capture: while a capture window is active, additionally stage\n // this batch's exact packed bytes into the group-owned bundle - the\n // recorded data IS the drawn data, byte-identical by construction.\n // Recorded regardless of the live visibility decision above (mask/\n // scissor), since visibility is re-evaluated live at replay. A batch\n // always binds a single tileset texture (slot 0); a pixel-snapped node\n // already poisoned the capture in render().\n if (this._quadIndex > 0 && backend._retainedCaptureActive && blendMode !== null && texture !== null) {\n this._recordTextures[0] = texture;\n backend._recordRetainedBatch(this, this._instanceData, flushBytes, this._quadIndex, blendMode, this._recordTextures, 1, null, null, this._batchNodeCount);\n }\n\n // The pass is deliberately left OPEN. It ends at genuine boundaries only\n // (the backend's frame/plan end, a target or view switch, a stencil clip)\n // and at the hazard splits above, so N tile-chunk flushes in a frame cost\n // one pass and one submit rather than N.\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._currentBlendMode = null;\n this._currentTexture = null;\n }\n\n /**\n * Whether the packed floats of the active group matrix differ from what the\n * shared projection UBO currently holds at [16, 32). Stages the packed matrix\n * into `_stagedGroupData` as a side effect (idempotent - safe to call more\n * than once per flush).\n */\n private _groupContentChanged(backend: WebGpuBackend): boolean {\n packAffineMat4(backend.renderGroupTransform ?? Matrix.identity, this._stagedGroupData, 0);\n\n if (!this._hasWrittenProjection) {\n return true;\n }\n\n return packedGroupChanged(this._stagedGroupData, this._projectionData, 16);\n }\n\n public destroy(): void {\n this.disconnect();\n }\n\n private _getOrCreateTransformBindGroup(device: GPUDevice, uniformBuffer: GPUBuffer, storageBuffer: GPUBuffer): GPUBindGroup {\n if (this._transformBindGroup !== null && this._transformStorageBuffer === storageBuffer) {\n return this._transformBindGroup;\n }\n\n this._transformStorageBuffer = storageBuffer;\n this._transformBindGroup = device.createBindGroup({\n layout: this._uniformBindGroupLayout!,\n entries: [\n { binding: 0, resource: { buffer: uniformBuffer } },\n { binding: 1, resource: { buffer: storageBuffer } },\n ],\n });\n\n return this._transformBindGroup;\n }\n\n /**\n * Build (or reuse) the group(1) texture bind group for `texture`. The\n * binding is resolved BEFORE the cache lookup on purpose: resolving is what\n * syncs a dirty/mutated texture's content to the GPU, so it must run every\n * flush/replay even when the bind group itself is served from cache.\n */\n private _getOrCreateTextureBindGroup(device: GPUDevice, backend: WebGpuBackend, texture: Texture | RenderTexture): GPUBindGroup {\n const { view, sampler } = backend.getTextureBinding(texture);\n const cached = this._textureBindGroups.get(texture);\n\n if (cached?.view === view && cached.sampler === sampler) {\n return cached.group;\n }\n\n const group = device.createBindGroup({\n layout: this._textureBindGroupLayout!,\n entries: [\n { binding: 0, resource: view },\n { binding: 1, resource: sampler },\n ],\n });\n\n this._textureBindGroups.set(texture, { group, view, sampler });\n\n return group;\n }\n\n // ── Retained-batch record/replay ──────────────────────────────────────────\n // The bundle/stage stores raw instance bytes; this renderer owns the\n // 32-byte (8-word) layout (tile word at word 7: transform row in bits\n // 0..28, diagonal flip in bit 29), so the layout-aware finalize steps\n // (node-index scan/rebase) and the replay dispatch live here - mirroring\n // WebGpuNineSliceSpriteRenderer's seam.\n\n /** @internal See {@link WebGpuRetainedBatchReplayer._scanRetainedNodeIndexRange}. */\n public _scanRetainedNodeIndexRange(bytes: Uint8Array, range: WebGpuRetainedNodeIndexRange): void {\n const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / Uint32Array.BYTES_PER_ELEMENT);\n\n for (let i = 7; i < words.length; i += 8) {\n // In-bounds: i < words.length via the loop guard. The tile word is the\n // last word of the 32-byte (8-word) instance layout; only the low 29\n // bits address the transform buffer row.\n const row = words[i]! & TILE_ROW_MASK;\n\n if (row < range.min) {\n range.min = row;\n }\n\n if (row > range.max) {\n range.max = row;\n }\n }\n }\n\n /** @internal See {@link WebGpuRetainedBatchReplayer._rebaseRetainedNodeIndices} (group-local indices). */\n public _rebaseRetainedNodeIndices(bytes: Uint8Array, base: number): void {\n const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / Uint32Array.BYTES_PER_ELEMENT);\n\n for (let i = 7; i < words.length; i += 8) {\n // In-bounds: i < words.length via the loop guard. Rebase ONLY the row\n // field; the diagonal-flip bit must survive untouched or tile\n // orientation corrupts.\n const word = words[i]!;\n const diagonal = word & TILE_DIAGONAL_BIT;\n const row = word & TILE_ROW_MASK;\n\n words[i] = (diagonal | ((row - base) & TILE_ROW_MASK)) >>> 0;\n }\n }\n\n /**\n * Replay one recorded batch from its group-owned bundle into the OPEN pass.\n * Reuses only recorded DATA (instance bytes, transform rows, texture, blend\n * mode); every piece of STATE is resolved live - pipeline via the\n * `_getPipeline` cache, the group(1) texture bind group via the live\n * texture-set cache (resolving re-syncs dirty content), and the group's\n * 128-byte UBO (projection from the live view + the live composed group\n * matrix) written only when its content changed. The same-frame\n * double-replay hazard (one group under two views while the open pass\n * already holds this bundle's draws) ends the pass first.\n * @internal\n */\n public _replayRetainedBatch(payload: WebGpuRetainedBatchPayload): void {\n const backend = this._backend;\n const device = this._device;\n const bundle = payload.bundle;\n\n if (!backend || !device || this._indexBuffer === null || !bundle.isReady) {\n return;\n }\n\n // Drain any pending live batch first (defensive - the group boundary\n // already flushed; flush() is a no-op when nothing is pending).\n this.flush();\n\n // Match the live path's visibility handling: a fully-clipped scissor\n // draws nothing (the batch stays recorded; visibility is live per frame).\n const scissor = backend.getScissorRect();\n\n if (scissor !== null && (scissor.width <= 0 || scissor.height <= 0)) {\n return;\n }\n\n const coordinator = backend._passCoordinator;\n\n // Same-frame texture mutation guard: resolving the bindings below\n // re-uploads mutated content on the queue timeline BEFORE the deferred\n // submit, which would retroactively change draws already recorded into\n // the open pass. End (submit) the pass first so they keep the\n // pre-mutation content. The texture cache is shared and the pass survives\n // a renderer switch, so any recorded draw is at risk, not just one of ours.\n if (coordinator.passHasDraws) {\n for (const texture of payload.textures) {\n if (backend._textureUploadWouldMutate(texture)) {\n coordinator.endPass();\n break;\n }\n }\n }\n\n // Resolve the single tileset texture LIVE through the texture bind-group\n // cache (syncs dirty content, adopts refreshed views/samplers). The\n // recorded batch always has exactly one texture (slot 0).\n const textureBindGroup = this._getOrCreateTextureBindGroup(device, backend, payload.textures[0]!);\n\n // Group UBO: skip the write while (view, updateId, group bytes) match\n // what the buffer holds; guard the double-replay aliasing case first.\n const view = backend.view;\n const scratch = this._stagedReplayGroupData;\n\n packAffineMat4(backend.renderGroupTransform ?? Matrix.identity, scratch, 0);\n\n // Staged unconditionally: an unchanged rect makes this an identity write,\n // while a changed one forces the rewrite the skip state cannot see.\n const viewportChanged = packSnapViewport(backend, bundle.uboData, 32);\n\n let uboDirty = !bundle.uboWritten || bundle.uboView !== view || bundle.uboViewUpdateId !== view.updateId || viewportChanged;\n\n if (!uboDirty) {\n for (let i = 0; i < 16; i++) {\n if (scratch[i] !== bundle.uboData[16 + i]) {\n uboDirty = true;\n break;\n }\n }\n }\n\n if (uboDirty) {\n const activePass = coordinator.activePass;\n\n if (activePass !== null && bundle.drawsInPass === activePass) {\n // Rewriting the UBO would retroactively re-project this bundle's\n // draws already recorded into the open pass: end it first.\n coordinator.endPass();\n }\n\n packAffineMat4(view.getTransform(), bundle.uboData, 0);\n bundle.uboData.set(scratch, 16);\n bundle.uboView = view;\n bundle.uboViewUpdateId = view.updateId;\n bundle.uboWritten = true;\n device.queue.writeBuffer(bundle.uniformBuffer!, 0, bundle.uboData.buffer, bundle.uboData.byteOffset, retainedGroupUniformBytes);\n }\n\n const active = coordinator.acquirePass();\n const pass = active.pass;\n\n pass.setPipeline(this._getPipeline(payload.blendMode, backend.renderTargetFormat, coordinator.stencilActive));\n pass.setBindGroup(0, bundle.getBindGroup(device, this._uniformBindGroupLayout!, false));\n pass.setBindGroup(1, textureBindGroup);\n pass.setVertexBuffer(0, bundle.instanceBuffer, payload.byteOffset);\n pass.setIndexBuffer(this._indexBuffer, 'uint16');\n pass.drawIndexed(indicesPerInstance, payload.instanceCount, 0, 0, 0);\n\n bundle.drawsInPass = active;\n coordinator.markPassDraws();\n backend.stats.batches++;\n backend.stats.drawCalls++;\n }\n\n private _getPipeline(blendMode: BlendModes, format: GPUTextureFormat, stencil: boolean): GPURenderPipeline {\n const key = `${blendMode}:${format}:${stencil ? 's' : 'n'}`;\n const existing = this._pipelines.get(key);\n\n if (existing) {\n return existing;\n }\n\n if (!this._device || !this._shaderModule || !this._pipelineLayout) {\n throw new Error('WebGpuTileChunkRenderer: renderer must be connected first.');\n }\n\n const descriptor: GPURenderPipelineDescriptor = {\n layout: this._pipelineLayout,\n vertex: {\n module: this._shaderModule,\n entryPoint: 'vertexMain',\n buffers: [\n {\n arrayStride: instanceStrideBytes,\n stepMode: 'instance',\n attributes: [\n { shaderLocation: 0, offset: 0, format: 'float32x4' },\n { shaderLocation: 1, offset: 16, format: 'unorm16x4' },\n { shaderLocation: 2, offset: 24, format: 'unorm8x4' },\n { shaderLocation: 3, offset: 28, format: 'uint32' },\n ],\n },\n ],\n },\n fragment: {\n module: this._shaderModule,\n entryPoint: 'fragmentMain',\n targets: [\n {\n format,\n blend: getWebGpuBlendState(blendMode),\n writeMask: GPUColorWrite.ALL,\n },\n ],\n },\n primitive: {\n topology: 'triangle-list',\n },\n };\n\n if (stencil) {\n descriptor.depthStencil = stencilContentDepthStencilState();\n }\n\n const pipeline = this._device.createRenderPipeline(descriptor);\n\n this._pipelines.set(key, pipeline);\n\n return pipeline;\n }\n\n /**\n * Grow the CPU staging array to hold `instanceCount` instances, carrying the\n * quads packed so far. Flush-local: the array only ever holds the pending\n * batch, so it is sized independently of the pass-scoped GPU buffer.\n */\n private _ensureStagingCapacity(instanceCount: number): void {\n if (instanceCount <= this._instanceStagingCapacity) {\n return;\n }\n\n let nextCapacity = Math.max(this._instanceStagingCapacity, initialBatchCapacity);\n\n while (nextCapacity < instanceCount) {\n nextCapacity *= 2;\n }\n\n const oldData = this._instanceData;\n const carryBytes = Math.min(this._quadIndex * instanceStrideBytes, oldData.byteLength);\n const instanceData = new ArrayBuffer(nextCapacity * instanceStrideBytes);\n\n if (carryBytes > 0) {\n new Uint8Array(instanceData).set(new Uint8Array(oldData, 0, carryBytes));\n }\n\n this._instanceStagingCapacity = nextCapacity;\n this._instanceData = instanceData;\n this._instanceFloat32 = new Float32Array(instanceData);\n this._instanceUint32 = new Uint32Array(instanceData);\n }\n\n /**\n * Resolve the GPU instance buffer for `requiredBytes` - the total this pass\n * would reach by appending, not this flush's own bytes. Reallocation frees the\n * buffer earlier draws in the open pass read, so the caller must have ended\n * that pass (and restarted the cursor) before a growing call. Capacity\n * doubles, so the split a growth costs converges away within a frame or two.\n */\n private _ensureInstanceBufferCapacity(device: GPUDevice, requiredBytes: number): GPUBuffer {\n const existing = this._instanceBuffer;\n\n if (existing !== null && requiredBytes <= this._instanceBufferCapacity) {\n return existing;\n }\n\n const nextCapacity = Math.max(this._instanceBufferCapacity * 2, requiredBytes, initialBatchCapacity * instanceStrideBytes);\n const instanceBuffer = device.createBuffer({\n label: 'tile-chunk:instance-buffer',\n size: nextCapacity,\n usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,\n });\n\n existing?.destroy();\n\n this._instanceBufferCapacity = nextCapacity;\n this._instanceBuffer = instanceBuffer;\n\n return instanceBuffer;\n }\n}\n"],"mappings":";;;;;;AA+BA,MAAM,sBAAsB;AAC5B,MAAM,mBAAmB,sBAAsB,YAAY;AAE3D,M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BAAkB,IAAI,YAAY,YAAY;CACrD;;;;;;;;CASA,AAAQ,8BAA8B,QAAmB,eAAkC;EACzF,MAAM,WAAW,KAAK;EAEtB,IAAI,aAAa,QAAQ,iBAAiB,KAAK,yBAC7C,OAAO;EAGT,MAAM,eAAe,KAAK,IAAI,KAAK,0BAA0B,GAAG,eAAe,uBAAuB,mBAAmB;EACzH,MAAM,iBAAiB,OAAO,aAAa;GACzC,OAAO;GACP,MAAM;GACN,OAAO,eAAe,SAAS,eAAe;EAChD,CAAC;EAED,UAAU,QAAQ;EAElB,KAAK,0BAA0B;EAC/B,KAAK,kBAAkB;EAEvB,OAAO;CACT;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codexo/exojs-tilemap",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.1",
|
|
4
4
|
"description": "Generic, format-independent tilemap runtime for ExoJS.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -29,8 +29,8 @@
|
|
|
29
29
|
"@codexo/exojs": "0.16.x"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
|
-
"@codexo/exojs
|
|
33
|
-
"@codexo/exojs": "0.
|
|
32
|
+
"@codexo/exojs": "0.16.1",
|
|
33
|
+
"@codexo/exojs-config": "0.0.0"
|
|
34
34
|
},
|
|
35
35
|
"license": "MIT",
|
|
36
36
|
"publishConfig": {
|