@codexo/exojs-tilemap 0.18.0 → 0.19.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.
Files changed (75) hide show
  1. package/README.md +56 -34
  2. package/dist/esm/ChunkStreamer.d.ts.map +1 -1
  3. package/dist/esm/ChunkStreamer.js +28 -6
  4. package/dist/esm/ChunkStreamer.js.map +1 -1
  5. package/dist/esm/ImageLayer.d.ts +1 -1
  6. package/dist/esm/ImageLayer.d.ts.map +1 -1
  7. package/dist/esm/ImageLayerNode.d.ts.map +1 -1
  8. package/dist/esm/MapObject.d.ts +2 -2
  9. package/dist/esm/MapObject.d.ts.map +1 -1
  10. package/dist/esm/MapObject.js.map +1 -1
  11. package/dist/esm/MapObjectSpawner.d.ts.map +1 -1
  12. package/dist/esm/MapSpawnSession.d.ts.map +1 -1
  13. package/dist/esm/MapWorld.d.ts +8 -8
  14. package/dist/esm/MapWorld.d.ts.map +1 -1
  15. package/dist/esm/MapWorldRuntime.d.ts.map +1 -1
  16. package/dist/esm/ObjectLayer.d.ts +26 -10
  17. package/dist/esm/ObjectLayer.d.ts.map +1 -1
  18. package/dist/esm/ObjectLayer.js +28 -0
  19. package/dist/esm/ObjectLayer.js.map +1 -1
  20. package/dist/esm/SampledChunkSource.d.ts.map +1 -1
  21. package/dist/esm/TileAnimator.d.ts.map +1 -1
  22. package/dist/esm/TileChunk.d.ts.map +1 -1
  23. package/dist/esm/TileChunkNode.js +47 -10
  24. package/dist/esm/TileChunkNode.js.map +1 -1
  25. package/dist/esm/TileLayer.d.ts +11 -2
  26. package/dist/esm/TileLayer.d.ts.map +1 -1
  27. package/dist/esm/TileLayer.js +20 -10
  28. package/dist/esm/TileLayer.js.map +1 -1
  29. package/dist/esm/TileLayerNode.d.ts +6 -4
  30. package/dist/esm/TileLayerNode.d.ts.map +1 -1
  31. package/dist/esm/TileLayerNode.js +36 -21
  32. package/dist/esm/TileLayerNode.js.map +1 -1
  33. package/dist/esm/TileMap.d.ts +6 -2
  34. package/dist/esm/TileMap.d.ts.map +1 -1
  35. package/dist/esm/TileMap.js +13 -12
  36. package/dist/esm/TileMap.js.map +1 -1
  37. package/dist/esm/TileMapBand.d.ts.map +1 -1
  38. package/dist/esm/TileMapNode.d.ts.map +1 -1
  39. package/dist/esm/TileMapNode.js +4 -1
  40. package/dist/esm/TileMapNode.js.map +1 -1
  41. package/dist/esm/TileMapView.d.ts.map +1 -1
  42. package/dist/esm/TileProjection.d.ts +59 -0
  43. package/dist/esm/TileProjection.d.ts.map +1 -0
  44. package/dist/esm/TileProjection.js +106 -0
  45. package/dist/esm/TileProjection.js.map +1 -0
  46. package/dist/esm/TileSet.d.ts.map +1 -1
  47. package/dist/esm/WangSet.d.ts.map +1 -1
  48. package/dist/esm/WorkerSampledChunkSource.d.ts.map +1 -1
  49. package/dist/esm/autoTile.d.ts.map +1 -1
  50. package/dist/esm/chunkGeometry.js +78 -50
  51. package/dist/esm/chunkGeometry.js.map +1 -1
  52. package/dist/esm/index.js +2 -1
  53. package/dist/esm/projectObject.d.ts +4 -0
  54. package/dist/esm/projectObject.d.ts.map +1 -0
  55. package/dist/esm/projectObject.js +87 -0
  56. package/dist/esm/projectObject.js.map +1 -0
  57. package/dist/esm/public.d.ts +1 -0
  58. package/dist/esm/public.d.ts.map +1 -1
  59. package/dist/esm/tileCollision.d.ts +2 -2
  60. package/dist/esm/tileCollision.d.ts.map +1 -1
  61. package/dist/esm/tileCollision.js +48 -16
  62. package/dist/esm/tileCollision.js.map +1 -1
  63. package/dist/esm/tilemapSerializers.js +1 -1
  64. package/dist/esm/tilemapSerializers.js.map +1 -1
  65. package/dist/esm/types.d.ts +3 -3
  66. package/dist/esm/types.d.ts.map +1 -1
  67. package/dist/esm/webgl2/WebGl2TileChunkRenderer.js +5 -4
  68. package/dist/esm/webgl2/WebGl2TileChunkRenderer.js.map +1 -1
  69. package/dist/esm/webgl2/shaders/tile-chunk.vert.js +1 -1
  70. package/dist/esm/webgl2/shaders/tile-chunk.vert.js.map +1 -1
  71. package/dist/esm/webgpu/WebGpuTileChunkRenderer.js +63 -27
  72. package/dist/esm/webgpu/WebGpuTileChunkRenderer.js.map +1 -1
  73. package/dist/esm/webgpu/shaders/tile-chunk.wgsl.js +1 -1
  74. package/dist/esm/webgpu/shaders/tile-chunk.wgsl.js.map +1 -1
  75. package/package.json +4 -4
@@ -72,10 +72,13 @@ const mapLocalPoint = (px, py, boxWidth, boxHeight, transform) => {
72
72
  * every tile, and a tile taller than the layer's cell is bottom-aligned within
73
73
  * it, so collision geometry lands exactly where the tile is drawn.
74
74
  */
75
- const tileAnchor = (layer, tileset, tx, ty) => ({
76
- x: tx * layer.tileWidth + layer.offsetX + tileset.offsetX,
77
- y: ty * layer.tileHeight + layer.offsetY + layer.tileHeight - tileset.tileHeight + tileset.offsetY
78
- });
75
+ const tileAnchor = (layer, tileset, tx, ty) => {
76
+ const point = layer.tileToPixel(tx, ty);
77
+ return {
78
+ x: point.x + tileset.offsetX - (layer.projection.orientation === "isometric" ? layer.tileWidth / 2 : 0),
79
+ y: point.y + layer.tileHeight - tileset.tileHeight + tileset.offsetY
80
+ };
81
+ };
79
82
  /**
80
83
  * Place one tile-local collision object into layer pixel space, applying the
81
84
  * tile's flip/rotation transform, the tileset draw offset and the layer offset.
@@ -157,6 +160,34 @@ const placeShape = (object, layer, tileset, transform, tx, ty) => {
157
160
  rotation
158
161
  };
159
162
  };
163
+ /** Undo display geometry before merging cells or handing shapes to simulation. */
164
+ const logicalShape = (shape, object, layer) => {
165
+ const p = layer.projection;
166
+ if (p.orientation === "orthogonal" && p.originX === 0 && p.originY === 0) return shape;
167
+ const geometry = {
168
+ ...object,
169
+ ...shape
170
+ };
171
+ const mapped = p.unprojectObject(geometry);
172
+ if (mapped.kind === "tile" || mapped.kind === "text") return shape;
173
+ if (mapped.kind === "polygon" && mapped.points.length === 4) {
174
+ const xs = mapped.points.map((point) => point.x);
175
+ const ys = mapped.points.map((point) => point.y);
176
+ const left = Math.min(...xs);
177
+ const top = Math.min(...ys);
178
+ const right = Math.max(...xs);
179
+ const bottom = Math.max(...ys);
180
+ if (new Set(mapped.points.map((point) => `${point.x},${point.y}`)).size === 4 && mapped.points.every((point) => (point.x === left || point.x === right) && (point.y === top || point.y === bottom))) return {
181
+ kind: "rectangle",
182
+ x: mapped.x + left,
183
+ y: mapped.y + top,
184
+ width: right - left,
185
+ height: bottom - top,
186
+ rotation: 0
187
+ };
188
+ }
189
+ return mapped;
190
+ };
160
191
  /** The tile-coordinate bounding box of the layer's loaded chunks, or `null`. */
161
192
  const loadedTileRegion = (layer) => {
162
193
  let minTx = Number.POSITIVE_INFINITY;
@@ -217,17 +248,17 @@ const cellKey = (tx, ty) => `${tx},${ty}`;
217
248
  * `true` when a placed shape is an axis-aligned rectangle covering exactly the
218
249
  * tile cell at `(cellX, cellY)` - the only geometry the merging pass handles.
219
250
  */
220
- const coversWholeCell = (placed, layer, cellX, cellY) => placed.kind === ObjectKind.Rectangle && placed.rotation === 0 && placed.x === cellX && placed.y === cellY && placed.width === layer.tileWidth && placed.height === layer.tileHeight;
251
+ const coversWholeCell = (placed, layer, cellX, cellY) => placed.kind === ObjectKind.Rectangle && placed.rotation === 0 && placed.x === cellX && placed.y === cellY && placed.width === layer.projection.logicalTileWidth && placed.height === layer.projection.logicalTileHeight;
221
252
  /** One single-cell rectangle per claimed cell, for `merge: false`. */
222
253
  const unmergedCells = (cells, layer) => {
223
254
  const rects = [];
224
255
  for (const [key, type] of cells) {
225
256
  const [tx, ty] = key.split(",").map(Number);
226
257
  rects.push({
227
- x: tx * layer.tileWidth + layer.offsetX,
228
- y: ty * layer.tileHeight + layer.offsetY,
229
- width: layer.tileWidth,
230
- height: layer.tileHeight,
258
+ x: tx * layer.projection.logicalTileWidth + layer.logicalOffset.x,
259
+ y: ty * layer.projection.logicalTileHeight + layer.logicalOffset.y,
260
+ width: layer.projection.logicalTileWidth,
261
+ height: layer.projection.logicalTileHeight,
231
262
  type
232
263
  });
233
264
  }
@@ -260,10 +291,10 @@ const mergeCells = (cells, region, layer) => {
260
291
  }
261
292
  for (let row = 0; row < height; row++) for (let column = 0; column < width; column++) consumed.add(cellKey(tx + column, ty + row));
262
293
  rects.push({
263
- x: tx * layer.tileWidth + layer.offsetX,
264
- y: ty * layer.tileHeight + layer.offsetY,
265
- width: width * layer.tileWidth,
266
- height: height * layer.tileHeight,
294
+ x: tx * layer.projection.logicalTileWidth + layer.logicalOffset.x,
295
+ y: ty * layer.projection.logicalTileHeight + layer.logicalOffset.y,
296
+ width: width * layer.projection.logicalTileWidth,
297
+ height: height * layer.projection.logicalTileHeight,
267
298
  type: key
268
299
  });
269
300
  }
@@ -327,11 +358,12 @@ const buildTileCollisionGeometry = (layer, options = {}) => {
327
358
  for (const { tx, ty, tile } of layer.tilesInRect(region.x, region.y, region.width, region.height)) {
328
359
  const definition = tile.tileset.getTileDefinition(tile.localTileId);
329
360
  if (definition?.collision === void 0) continue;
330
- const cellX = tx * layer.tileWidth + layer.offsetX;
331
- const cellY = ty * layer.tileHeight + layer.offsetY;
361
+ const cellX = tx * layer.projection.logicalTileWidth + layer.logicalOffset.x;
362
+ const cellY = ty * layer.projection.logicalTileHeight + layer.logicalOffset.y;
332
363
  for (const object of definition.collision) {
333
364
  if (accept !== void 0 && !accept(object, tx, ty)) continue;
334
- const placed = placeShape(object, layer, tile.tileset, tile.transform, tx, ty);
365
+ const visual = placeShape(object, layer, tile.tileset, tile.transform, tx, ty);
366
+ const placed = visual === null ? null : logicalShape(visual, object, layer);
335
367
  if (placed === null) continue;
336
368
  const key = cellKey(tx, ty);
337
369
  if (coversWholeCell(placed, layer, cellX, cellY) && !cells.has(key)) {
@@ -1 +1 @@
1
- {"version":3,"file":"tileCollision.js","names":[],"sources":["../../src/tileCollision.ts"],"sourcesContent":["import type { ObjectPoint, TileMapObject } from './ObjectLayer';\nimport { ObjectKind } from './ObjectLayer';\nimport type { TileLayer } from './TileLayer';\nimport type { TileSet } from './TileSet';\nimport type { TileTransform } from './types';\n\n/**\n * The geometry kinds a {@link TileCollisionShape} can carry. Tile (GID) and\n * text objects describe no collision area and are never emitted, so they are\n * excluded from the union.\n * @advanced\n */\nexport type TileCollisionShapeKind =\n typeof ObjectKind.Rectangle | typeof ObjectKind.Ellipse | typeof ObjectKind.Polygon | typeof ObjectKind.Polyline | typeof ObjectKind.Point;\n\n/**\n * A half-open tile-coordinate rectangle covering\n * `[x, x + width)` × `[y, y + height)`.\n *\n * Used to scope {@link buildTileCollisionGeometry} to part of a layer - a\n * streamed chunk, the tiles around the player, a hand-picked room - instead of\n * always rebuilding the whole map.\n * @advanced\n */\nexport interface TileRegion {\n /** Leftmost tile column (inclusive). */\n readonly x: number;\n /** Topmost tile row (inclusive). */\n readonly y: number;\n /** Width in tiles. */\n readonly width: number;\n /** Height in tiles. */\n readonly height: number;\n}\n\n/**\n * An axis-aligned collision rectangle in tile-layer pixel space (+Y down),\n * covering one or more whole tile cells.\n *\n * Rectangles are synthesized geometry, not source objects: a merged run has no\n * single originating object, so it carries no object `id`/`name`/`properties` -\n * only the `type` string shared by every shape merged into it. Anything that\n * does not exactly cover whole cells stays a {@link TileCollisionShape}, which\n * does keep its source object.\n * @advanced\n */\nexport interface TileCollisionRect {\n /** Left edge in layer pixel space. */\n readonly x: number;\n /** Top edge in layer pixel space. */\n readonly y: number;\n /** Width in pixels (a whole number of tile cells). */\n readonly width: number;\n /** Height in pixels (a whole number of tile cells). */\n readonly height: number;\n /** Class/type string shared by every source shape merged into this rectangle. */\n readonly type: string;\n}\n\n/**\n * A per-tile collision shape placed in tile-layer pixel space (+Y down).\n *\n * Emitted for every collision shape that does not exactly cover a whole tile\n * cell: partial boxes, ellipses, polygons, polylines, points, and rotated\n * geometry. Shapes are never merged with one another.\n * @advanced\n */\nexport interface TileCollisionShape {\n /** Geometry discriminant. */\n readonly kind: TileCollisionShapeKind;\n /** X of the shape origin in layer pixel space. */\n readonly x: number;\n /** Y of the shape origin in layer pixel space. */\n readonly y: number;\n /** Bounding width in px (`0` for polygons, polylines and points). */\n readonly width: number;\n /** Bounding height in px (`0` for polygons, polylines and points). */\n readonly height: number;\n /**\n * Rotation in degrees, clockwise, about `(x, y)`, normalised to `[0, 360)`.\n * Always `0` for polygons and polylines - their rotation is baked into\n * {@link points}.\n */\n readonly rotation: number;\n /** Polygon/polyline vertices relative to `(x, y)`; absent for other kinds. */\n readonly points?: readonly ObjectPoint[];\n /** Tile column the shape came from. */\n readonly tx: number;\n /** Tile row the shape came from. */\n readonly ty: number;\n /** The tile-local source object, for `name`/`type`/`properties` lookups. */\n readonly source: TileMapObject;\n}\n\n/**\n * Collision geometry extracted from a tile layer: whole-cell boxes merged into\n * as few {@link TileCollisionRect}s as a greedy pass can manage, plus every\n * other shape passed through individually.\n * @advanced\n */\nexport interface TileCollisionGeometry {\n /** Merged whole-cell rectangles, in row-major order. */\n readonly rects: readonly TileCollisionRect[];\n /** Non-whole-cell shapes, in the order their tiles were walked. */\n readonly shapes: readonly TileCollisionShape[];\n}\n\n/**\n * Per-cell collision classification for a tile layer, independent of the tiles\n * the layer renders.\n *\n * Returns the class/type string for the cell, or `null` when the cell carries\n * no collision. The string is opaque: it is the merge key for adjacent cells\n * and reaches the consumer unchanged, exactly like the `type` of a tile\n * collision object.\n *\n * A source is sampled while geometry is being built and is expected to answer\n * identically for as long as the geometry is used. Changing what it returns\n * does not invalidate geometry that was already built; rebuild instead.\n * @advanced\n */\nexport type TileCellSource = (tx: number, ty: number) => string | null;\n\n/**\n * Options for {@link buildTileCollisionGeometry}.\n * @advanced\n */\nexport interface TileCollisionOptions {\n /**\n * Tile-coordinate region to walk. Defaults to the bounding box of the\n * layer's currently loaded chunks, so an unbounded (streamed) layer works\n * without the caller computing anything - or, with {@link cells} on a\n * bounded layer, to the layer's full tile extent.\n */\n readonly region?: TileRegion;\n /**\n * Second occupancy source, consulted once per cell of the walked region in\n * addition to the tiles' own collision shapes. Lets collision authored per\n * cell rather than per tile reach the same geometry, without the layer\n * having to render a tile there.\n */\n readonly cells?: TileCellSource | undefined;\n /**\n * Merge adjacent whole-cell boxes that share a `type` into larger\n * rectangles. Default `true`. With `false`, every whole-cell box becomes its\n * own single-cell rectangle.\n */\n readonly merge?: boolean;\n /**\n * Drop source shapes before any geometry is built (e.g. by a custom\n * property). Return `true` to keep a shape. Default keeps all of them.\n */\n readonly accept?: (object: TileMapObject, tx: number, ty: number) => boolean;\n}\n\nconst DEGREES_TO_RADIANS = Math.PI / 180;\n\n/** Normalise degrees into `[0, 360)`. */\nconst normaliseDegrees = (degrees: number): number => {\n const wrapped = degrees % 360;\n\n return wrapped < 0 ? wrapped + 360 : wrapped;\n};\n\n/**\n * Cosine of an angle in degrees, exact on the quadrant multiples.\n * `Math.cos(Math.PI / 2)` is `6.1e-17`, not `0`; tile transforms produce those\n * quadrant angles constantly, and the whole-cell test below compares\n * coordinates exactly, so the noise has to stay out of the arithmetic.\n */\nconst cosDegrees = (degrees: number): number => {\n const angle = normaliseDegrees(degrees);\n\n if (angle === 0) return 1;\n if (angle === 90 || angle === 270) return 0;\n if (angle === 180) return -1;\n\n return Math.cos(angle * DEGREES_TO_RADIANS);\n};\n\n/** Sine of an angle in degrees, exact on the quadrant multiples. */\nconst sinDegrees = (degrees: number): number => {\n const angle = normaliseDegrees(degrees);\n\n if (angle === 0 || angle === 180) return 0;\n if (angle === 90) return 1;\n if (angle === 270) return -1;\n\n return Math.sin(angle * DEGREES_TO_RADIANS);\n};\n\n/** `true` when the transform mirrors (an odd number of reflections). */\nconst isMirrored = (transform: TileTransform): boolean => {\n const flags = (transform.flipX ? 1 : 0) + (transform.flipY ? 1 : 0) + (transform.diagonal ? 1 : 0);\n\n return flags % 2 === 1;\n};\n\n/**\n * Rotation in degrees contributed by a non-mirroring transform. Only the four\n * even-parity transforms are rotations: identity, `flipX+flipY` (180°),\n * `diagonal+flipX` (90°) and `diagonal+flipY` (270°).\n */\nconst transformRotation = (transform: TileTransform): number => {\n if (transform.diagonal) {\n return transform.flipX ? 90 : 270;\n }\n\n return transform.flipX ? 180 : 0;\n};\n\n/**\n * Map a point from tile-local pixel space into the transformed tile-local\n * space of a placed tile. The diagonal flip (a transpose of the axes, which\n * also swaps the box dimensions) is applied first, then the axis mirrors -\n * the same order the renderer's orientation code implies.\n */\nconst mapLocalPoint = (px: number, py: number, boxWidth: number, boxHeight: number, transform: TileTransform): ObjectPoint => {\n let x = px;\n let y = py;\n let width = boxWidth;\n let height = boxHeight;\n\n if (transform.diagonal) {\n const swapped = x;\n\n x = y;\n y = swapped;\n width = boxHeight;\n height = boxWidth;\n }\n\n if (transform.flipX) x = width - x;\n if (transform.flipY) y = height - y;\n\n return { x, y };\n};\n\n/**\n * Layer-space position of a placed tile's top-left image corner. Mirrors the\n * renderer's placement (see `chunkGeometry`): the tileset's draw offset shifts\n * every tile, and a tile taller than the layer's cell is bottom-aligned within\n * it, so collision geometry lands exactly where the tile is drawn.\n */\nconst tileAnchor = (layer: TileLayer, tileset: TileSet, tx: number, ty: number): ObjectPoint => ({\n x: tx * layer.tileWidth + layer.offsetX + tileset.offsetX,\n y: ty * layer.tileHeight + layer.offsetY + layer.tileHeight - tileset.tileHeight + tileset.offsetY,\n});\n\n/** A shape in layer pixel space, before it is classified as cell or shape. */\ninterface PlacedShape {\n readonly kind: TileCollisionShapeKind;\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n readonly rotation: number;\n readonly points?: readonly ObjectPoint[];\n}\n\n/**\n * Place one tile-local collision object into layer pixel space, applying the\n * tile's flip/rotation transform, the tileset draw offset and the layer offset.\n * Returns `null` for kinds that carry no collision geometry.\n */\nconst placeShape = (object: TileMapObject, layer: TileLayer, tileset: TileSet, transform: TileTransform, tx: number, ty: number): PlacedShape | null => {\n if (object.kind === ObjectKind.Tile || object.kind === ObjectKind.Text) {\n return null;\n }\n\n const anchor = tileAnchor(layer, tileset, tx, ty);\n const boxWidth = tileset.tileWidth;\n const boxHeight = tileset.tileHeight;\n const mirrored = isMirrored(transform);\n const sourceCos = cosDegrees(object.rotation);\n const sourceSin = sinDegrees(object.rotation);\n\n if (object.kind === ObjectKind.Polygon || object.kind === ObjectKind.Polyline) {\n // Rotation is baked into the vertices: the source rotation pivots about the\n // object origin, and the tile transform may mirror the whole tile, so an\n // origin-plus-angle form would need a second angle convention. Absolute\n // vertices are exact under both.\n const origin = mapLocalPoint(object.x, object.y, boxWidth, boxHeight, transform);\n const originX = anchor.x + origin.x;\n const originY = anchor.y + origin.y;\n const points = object.points.map(point => {\n const localX = object.x + (sourceCos * point.x - sourceSin * point.y);\n const localY = object.y + (sourceSin * point.x + sourceCos * point.y);\n const mapped = mapLocalPoint(localX, localY, boxWidth, boxHeight, transform);\n\n return { x: anchor.x + mapped.x - originX, y: anchor.y + mapped.y - originY };\n });\n\n return {\n kind: object.kind,\n x: originX,\n y: originY,\n width: 0,\n height: 0,\n rotation: 0,\n // A mirror reverses the winding order; reversing the vertices restores\n // the source orientation, which convex-hull/polygon consumers rely on.\n points: mirrored ? points.reverse() : points,\n };\n }\n\n if (object.kind === ObjectKind.Point) {\n const mapped = mapLocalPoint(object.x, object.y, boxWidth, boxHeight, transform);\n\n return {\n kind: ObjectKind.Point,\n x: anchor.x + mapped.x,\n y: anchor.y + mapped.y,\n width: 0,\n height: 0,\n rotation: 0,\n };\n }\n\n // Rectangles and ellipses are symmetric about their centre, so placing the\n // centre and re-deriving the origin handles every transform uniformly.\n const halfWidth = object.width / 2;\n const halfHeight = object.height / 2;\n const centreLocalX = object.x + (sourceCos * halfWidth - sourceSin * halfHeight);\n const centreLocalY = object.y + (sourceSin * halfWidth + sourceCos * halfHeight);\n const centre = mapLocalPoint(centreLocalX, centreLocalY, boxWidth, boxHeight, transform);\n const centreX = anchor.x + centre.x;\n const centreY = anchor.y + centre.y;\n\n // Conjugating a rotation by a mirror negates it; a non-mirroring transform is\n // itself a rotation and simply adds. Only a mirror can swap the local axes,\n // and then only when the diagonal flip is part of it.\n const rotation = normaliseDegrees(mirrored ? -object.rotation : object.rotation + transformRotation(transform));\n const swapAxes = mirrored && transform.diagonal;\n const width = swapAxes ? object.height : object.width;\n const height = swapAxes ? object.width : object.height;\n\n if (rotation % 90 === 0) {\n // Quadrant-aligned geometry is axis-aligned; re-express it without a\n // rotation so whole-cell boxes on rotated tiles stay mergeable.\n const axisWidth = rotation % 180 === 0 ? width : height;\n const axisHeight = rotation % 180 === 0 ? height : width;\n\n return {\n kind: object.kind,\n x: centreX - axisWidth / 2,\n y: centreY - axisHeight / 2,\n width: axisWidth,\n height: axisHeight,\n rotation: 0,\n };\n }\n\n const cos = cosDegrees(rotation);\n const sin = sinDegrees(rotation);\n\n return {\n kind: object.kind,\n x: centreX - (cos * (width / 2) - sin * (height / 2)),\n y: centreY - (sin * (width / 2) + cos * (height / 2)),\n width,\n height,\n rotation,\n };\n};\n\n/** The tile-coordinate bounding box of the layer's loaded chunks, or `null`. */\nconst loadedTileRegion = (layer: TileLayer): TileRegion | null => {\n let minTx = Number.POSITIVE_INFINITY;\n let minTy = Number.POSITIVE_INFINITY;\n let maxTx = Number.NEGATIVE_INFINITY;\n let maxTy = Number.NEGATIVE_INFINITY;\n\n for (const chunk of layer.loadedChunks()) {\n const startTx = chunk.cx * layer.chunkWidth;\n const startTy = chunk.cy * layer.chunkHeight;\n\n minTx = Math.min(minTx, startTx);\n minTy = Math.min(minTy, startTy);\n maxTx = Math.max(maxTx, startTx + chunk.width - 1);\n maxTy = Math.max(maxTy, startTy + chunk.height - 1);\n }\n\n if (!Number.isFinite(minTx) || !Number.isFinite(minTy)) {\n return null;\n }\n\n return { x: minTx, y: minTy, width: maxTx - minTx + 1, height: maxTy - minTy + 1 };\n};\n\n/**\n * Region a cell source spans on `layer`: the full tile extent of a bounded\n * layer, `null` when the layer is unbounded and the caller must scope the\n * walk itself. Chunk residency deliberately plays no part - the classification\n * lives outside the layer, so loaded chunks cannot define its domain.\n */\nconst cellSourceRegion = (layer: TileLayer): TileRegion | null => {\n if (layer.width === undefined || layer.height === undefined) {\n return null;\n }\n\n return { x: 0, y: 0, width: layer.width, height: layer.height };\n};\n\n/**\n * The region to walk: the caller's, else the extent a cell source spans, else\n * whatever is currently resident. `null` when there is nothing to walk.\n */\nconst resolveRegion = (layer: TileLayer, options: TileCollisionOptions): TileRegion | null => {\n if (options.region !== undefined) return options.region;\n\n const fromCells = options.cells !== undefined ? cellSourceRegion(layer) : null;\n\n return fromCells ?? loadedTileRegion(layer);\n};\n\n/** Claim every cell of `region` the source classifies, into the occupancy grid. */\nconst claimSourceCells = (cells: Map<string, string>, region: TileRegion, source: TileCellSource): void => {\n const endTx = region.x + region.width;\n const endTy = region.y + region.height;\n\n for (let ty = region.y; ty < endTy; ty++) {\n for (let tx = region.x; tx < endTx; tx++) {\n const type = source(tx, ty);\n\n if (type !== null) cells.set(cellKey(tx, ty), type);\n }\n }\n};\n\n/** Key of a claimed cell in the occupancy grid. */\nconst cellKey = (tx: number, ty: number): string => `${tx},${ty}`;\n\n/**\n * `true` when a placed shape is an axis-aligned rectangle covering exactly the\n * tile cell at `(cellX, cellY)` - the only geometry the merging pass handles.\n */\nconst coversWholeCell = (placed: PlacedShape, layer: TileLayer, cellX: number, cellY: number): boolean =>\n placed.kind === ObjectKind.Rectangle &&\n placed.rotation === 0 &&\n placed.x === cellX &&\n placed.y === cellY &&\n placed.width === layer.tileWidth &&\n placed.height === layer.tileHeight;\n\n/** One single-cell rectangle per claimed cell, for `merge: false`. */\nconst unmergedCells = (cells: ReadonlyMap<string, string>, layer: TileLayer): TileCollisionRect[] => {\n const rects: TileCollisionRect[] = [];\n\n for (const [key, type] of cells) {\n const [tx, ty] = key.split(',').map(Number) as [number, number];\n\n rects.push({\n x: tx * layer.tileWidth + layer.offsetX,\n y: ty * layer.tileHeight + layer.offsetY,\n width: layer.tileWidth,\n height: layer.tileHeight,\n type,\n });\n }\n\n return rects;\n};\n\n/**\n * Greedy rectangle merging over the claimed cells: walk row-major, grow each\n * unconsumed cell as far right as the type key allows, then as far down as a\n * full row of that width allows, and consume the block. Deliberately the plain\n * textbook pass - it is linear in the number of cells and always produces a\n * valid, non-overlapping cover, which matters more here than minimality.\n */\nconst mergeCells = (cells: ReadonlyMap<string, string>, region: TileRegion, layer: TileLayer): TileCollisionRect[] => {\n const consumed = new Set<string>();\n const rects: TileCollisionRect[] = [];\n const endTx = region.x + region.width;\n const endTy = region.y + region.height;\n\n for (let ty = region.y; ty < endTy; ty++) {\n for (let tx = region.x; tx < endTx; tx++) {\n const key = cells.get(cellKey(tx, ty));\n\n if (key === undefined || consumed.has(cellKey(tx, ty))) {\n continue;\n }\n\n let width = 1;\n\n while (tx + width < endTx && cells.get(cellKey(tx + width, ty)) === key && !consumed.has(cellKey(tx + width, ty))) {\n width++;\n }\n\n let height = 1;\n\n growDown: while (ty + height < endTy) {\n for (let column = 0; column < width; column++) {\n const candidate = cellKey(tx + column, ty + height);\n\n if (cells.get(candidate) !== key || consumed.has(candidate)) {\n break growDown;\n }\n }\n\n height++;\n }\n\n for (let row = 0; row < height; row++) {\n for (let column = 0; column < width; column++) {\n consumed.add(cellKey(tx + column, ty + row));\n }\n }\n\n rects.push({\n x: tx * layer.tileWidth + layer.offsetX,\n y: ty * layer.tileHeight + layer.offsetY,\n width: width * layer.tileWidth,\n height: height * layer.tileHeight,\n type: key,\n });\n }\n }\n\n return rects;\n};\n\n/**\n * Extract collision geometry from a tile layer's per-tile\n * {@link import('./types').TileDefinition.collision} shapes.\n *\n * Every placed tile in `region` is resolved back to its tileset definition, and\n * each collision shape is transformed from tile-local pixel space into layer\n * pixel space (+Y down) - applying the tile's flip/rotation transform, the\n * tileset draw offset, and the layer's pixel offset, so the geometry lands\n * exactly where the tile is drawn.\n *\n * Shapes that end up covering exactly one whole tile cell are collected into an\n * occupancy grid and merged into as few {@link TileCollisionRect}s as a greedy\n * pass manages - a 200×200 solid region becomes one rectangle instead of 40 000.\n * Cells only merge with neighbours whose source object carries the same `type`\n * string, so a `water` run never fuses into an adjacent `solid` run. Everything\n * else (partial boxes, ellipses, polygons, polylines, points, rotated geometry)\n * passes through individually as a {@link TileCollisionShape}.\n *\n * A {@link TileCollisionOptions.cells} source feeds the same occupancy grid\n * from outside the tiles, for collision authored per cell rather than per tile.\n * It is consulted first, so a whole-cell tile box landing on a cell the source\n * already claimed passes through as a shape rather than overwriting it. With a\n * cell source and no explicit region, a bounded layer walks its full tile\n * extent - a layer that renders nothing at all still produces geometry.\n *\n * This package has no physics dependency and builds no bodies: the result is\n * plain geometry. Turning it into colliders is a short loop in application code.\n *\n * @param layer - The layer to walk.\n * @param options - Region scoping, merge toggle, a source-shape filter, and an\n * optional per-cell occupancy source.\n * @returns Merged rectangles plus pass-through shapes; both empty when the\n * region holds no tile carrying collision data.\n *\n * @example\n * ```ts\n * const { rects, shapes } = buildTileCollisionGeometry(layer);\n *\n * for (const rect of rects) {\n * world.add(makeStaticBox(rect.x, rect.y, rect.width, rect.height));\n * }\n * ```\n * @advanced\n */\nexport const buildTileCollisionGeometry = (layer: TileLayer, options: TileCollisionOptions = {}): TileCollisionGeometry => {\n const cellSource = options.cells;\n const region = resolveRegion(layer, options);\n\n if (region === null || region.width <= 0 || region.height <= 0) {\n return { rects: [], shapes: [] };\n }\n\n const accept = options.accept;\n const cells = new Map<string, string>();\n const shapes: TileCollisionShape[] = [];\n\n if (cellSource !== undefined) claimSourceCells(cells, region, cellSource);\n\n for (const { tx, ty, tile } of layer.tilesInRect(region.x, region.y, region.width, region.height)) {\n const definition = tile.tileset.getTileDefinition(tile.localTileId);\n\n if (definition?.collision === undefined) {\n continue;\n }\n\n const cellX = tx * layer.tileWidth + layer.offsetX;\n const cellY = ty * layer.tileHeight + layer.offsetY;\n\n for (const object of definition.collision) {\n if (accept !== undefined && !accept(object, tx, ty)) {\n continue;\n }\n\n const placed = placeShape(object, layer, tile.tileset, tile.transform, tx, ty);\n\n if (placed === null) {\n continue;\n }\n\n const key = cellKey(tx, ty);\n\n // A second whole-cell box on the same tile cannot claim the cell twice;\n // it falls through to the shape list so no geometry is silently dropped.\n if (coversWholeCell(placed, layer, cellX, cellY) && !cells.has(key)) {\n cells.set(key, object.type);\n continue;\n }\n\n shapes.push({\n kind: placed.kind,\n x: placed.x,\n y: placed.y,\n width: placed.width,\n height: placed.height,\n rotation: placed.rotation,\n ...(placed.points !== undefined && { points: placed.points }),\n tx,\n ty,\n source: object,\n });\n }\n }\n\n if (cells.size === 0) {\n return { rects: [], shapes };\n }\n\n const rects = options.merge === false ? unmergedCells(cells, layer) : mergeCells(cells, region, layer);\n\n return { rects, shapes };\n};\n"],"mappings":";;;AA2JA,MAAM,qBAAqB,KAAK,KAAK;;AAGrC,MAAM,oBAAoB,YAA4B;CACpD,MAAM,UAAU,UAAU;CAE1B,OAAO,UAAU,IAAI,UAAU,MAAM;AACvC;;;;;;;AAQA,MAAM,cAAc,YAA4B;CAC9C,MAAM,QAAQ,iBAAiB,OAAO;CAEtC,IAAI,UAAU,GAAG,OAAO;CACxB,IAAI,UAAU,MAAM,UAAU,KAAK,OAAO;CAC1C,IAAI,UAAU,KAAK,OAAO;CAE1B,OAAO,KAAK,IAAI,QAAQ,kBAAkB;AAC5C;;AAGA,MAAM,cAAc,YAA4B;CAC9C,MAAM,QAAQ,iBAAiB,OAAO;CAEtC,IAAI,UAAU,KAAK,UAAU,KAAK,OAAO;CACzC,IAAI,UAAU,IAAI,OAAO;CACzB,IAAI,UAAU,KAAK,OAAO;CAE1B,OAAO,KAAK,IAAI,QAAQ,kBAAkB;AAC5C;;AAGA,MAAM,cAAc,cAAsC;CAGxD,SAFe,UAAU,QAAQ,IAAI,MAAM,UAAU,QAAQ,IAAI,MAAM,UAAU,WAAW,IAAI,MAEjF,MAAM;AACvB;;;;;;AAOA,MAAM,qBAAqB,cAAqC;CAC9D,IAAI,UAAU,UACZ,OAAO,UAAU,QAAQ,KAAK;CAGhC,OAAO,UAAU,QAAQ,MAAM;AACjC;;;;;;;AAQA,MAAM,iBAAiB,IAAY,IAAY,UAAkB,WAAmB,cAA0C;CAC5H,IAAI,IAAI;CACR,IAAI,IA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AAM,aAAa,KAAK,QAAQ,kBAAkB,KAAK,WAAW;EAElE,IAAI,YAAY,cAAc,QAC5B;EAGF,MAAM,QAAQ,KAAK,MAAM,YAAY,MAAM;EAC3C,MAAM,QAAQ,KAAK,MAAM,aAAa,MAAM;EAE5C,KAAK,MAAM,UAAU,WAAW,WAAW;GACzC,IAAI,WAAW,UAAa,CAAC,OAAO,QAAQ,IAAI,EAAE,GAChD;GAGF,MAAM,SAAS,WAAW,QAAQ,OAAO,KAAK,SAAS,KAAK,WAAW,IAAI,EAAE;GAE7E,IAAI,WAAW,MACb;GAGF,MAAM,MAAM,QAAQ,IAAI,EAAE;GAI1B,IAAI,gBAAgB,QAAQ,OAAO,OAAO,KAAK,KAAK,CAAC,MAAM,IAAI,GAAG,GAAG;IACnE,MAAM,IAAI,KAAK,OAAO,IAAI;IAC1B;GACF;GAEA,OAAO,KAAK;IACV,MAAM,OAAO;IACb,GAAG,OAAO;IACV,GAAG,OAAO;IACV,OAAO,OAAO;IACd,QAAQ,OAAO;IACf,UAAU,OAAO;IACjB,GAAI,OAAO,WAAW,UAAa,EAAE,QAAQ,OAAO,OAAO;IAC3D;IACA;IACA,QAAQ;GACV,CAAC;EACH;CACF;CAEA,IAAI,MAAM,SAAS,GACjB,OAAO;EAAE,OAAO,CAAC;EAAG;CAAO;CAK7B,OAAO;EAAE,OAFK,QAAQ,UAAU,QAAQ,cAAc,OAAO,KAAK,IAAI,WAAW,OAAO,QAAQ,KAAK;EAErF;CAAO;AACzB"}
1
+ {"version":3,"file":"tileCollision.js","names":[],"sources":["../../src/tileCollision.ts"],"sourcesContent":["import type { ObjectPoint, TileMapObject } from './ObjectLayer';\nimport { ObjectKind } from './ObjectLayer';\nimport type { TileLayer } from './TileLayer';\nimport type { TileSet } from './TileSet';\nimport type { TileTransform } from './types';\n\n/**\n * The geometry kinds a {@link TileCollisionShape} can carry. Tile (GID) and\n * text objects describe no collision area and are never emitted, so they are\n * excluded from the union.\n * @advanced\n */\nexport type TileCollisionShapeKind =\n typeof ObjectKind.Rectangle | typeof ObjectKind.Ellipse | typeof ObjectKind.Polygon | typeof ObjectKind.Polyline | typeof ObjectKind.Point;\n\n/**\n * A half-open tile-coordinate rectangle covering\n * `[x, x + width)` × `[y, y + height)`.\n *\n * Used to scope {@link buildTileCollisionGeometry} to part of a layer - a\n * streamed chunk, the tiles around the player, a hand-picked room - instead of\n * always rebuilding the whole map.\n * @advanced\n */\nexport interface TileRegion {\n /** Leftmost tile column (inclusive). */\n readonly x: number;\n /** Topmost tile row (inclusive). */\n readonly y: number;\n /** Width in tiles. */\n readonly width: number;\n /** Height in tiles. */\n readonly height: number;\n}\n\n/**\n * An axis-aligned collision rectangle in logical tile-layer pixel space (+Y down),\n * covering one or more whole tile cells.\n *\n * Rectangles are synthesized geometry, not source objects: a merged run has no\n * single originating object, so it carries no object `id`/`name`/`properties` -\n * only the `type` string shared by every shape merged into it. Anything that\n * does not exactly cover whole cells stays a {@link TileCollisionShape}, which\n * does keep its source object.\n * @advanced\n */\nexport interface TileCollisionRect {\n /** Left edge in layer pixel space. */\n readonly x: number;\n /** Top edge in layer pixel space. */\n readonly y: number;\n /** Width in pixels (a whole number of tile cells). */\n readonly width: number;\n /** Height in pixels (a whole number of tile cells). */\n readonly height: number;\n /** Class/type string shared by every source shape merged into this rectangle. */\n readonly type: string;\n}\n\n/**\n * A per-tile collision shape placed in logical tile-layer pixel space (+Y down).\n *\n * Emitted for every collision shape that does not exactly cover a whole tile\n * cell: partial boxes, ellipses, polygons, polylines, points, and rotated\n * geometry. Shapes are never merged with one another.\n * @advanced\n */\nexport interface TileCollisionShape {\n /** Geometry discriminant. */\n readonly kind: TileCollisionShapeKind;\n /** X of the shape origin in layer pixel space. */\n readonly x: number;\n /** Y of the shape origin in layer pixel space. */\n readonly y: number;\n /** Bounding width in px (`0` for polygons, polylines and points). */\n readonly width: number;\n /** Bounding height in px (`0` for polygons, polylines and points). */\n readonly height: number;\n /**\n * Rotation in degrees, clockwise, about `(x, y)`, normalised to `[0, 360)`.\n * Always `0` for polygons and polylines - their rotation is baked into\n * {@link points}.\n */\n readonly rotation: number;\n /** Polygon/polyline vertices relative to `(x, y)`; absent for other kinds. */\n readonly points?: readonly ObjectPoint[];\n /** Tile column the shape came from. */\n readonly tx: number;\n /** Tile row the shape came from. */\n readonly ty: number;\n /** The tile-local source object, for `name`/`type`/`properties` lookups. */\n readonly source: TileMapObject;\n}\n\n/**\n * Collision geometry extracted from a tile layer: whole-cell boxes merged into\n * as few {@link TileCollisionRect}s as a greedy pass can manage, plus every\n * other shape passed through individually.\n * @advanced\n */\nexport interface TileCollisionGeometry {\n /** Merged whole-cell rectangles, in row-major order. */\n readonly rects: readonly TileCollisionRect[];\n /** Non-whole-cell shapes, in the order their tiles were walked. */\n readonly shapes: readonly TileCollisionShape[];\n}\n\n/**\n * Per-cell collision classification for a tile layer, independent of the tiles\n * the layer renders.\n *\n * Returns the class/type string for the cell, or `null` when the cell carries\n * no collision. The string is opaque: it is the merge key for adjacent cells\n * and reaches the consumer unchanged, exactly like the `type` of a tile\n * collision object.\n *\n * A source is sampled while geometry is being built and is expected to answer\n * identically for as long as the geometry is used. Changing what it returns\n * does not invalidate geometry that was already built; rebuild instead.\n * @advanced\n */\nexport type TileCellSource = (tx: number, ty: number) => string | null;\n\n/**\n * Options for {@link buildTileCollisionGeometry}.\n * @advanced\n */\nexport interface TileCollisionOptions {\n /**\n * Tile-coordinate region to walk. Defaults to the bounding box of the\n * layer's currently loaded chunks, so an unbounded (streamed) layer works\n * without the caller computing anything - or, with {@link cells} on a\n * bounded layer, to the layer's full tile extent.\n */\n readonly region?: TileRegion;\n /**\n * Second occupancy source, consulted once per cell of the walked region in\n * addition to the tiles' own collision shapes. Lets collision authored per\n * cell rather than per tile reach the same geometry, without the layer\n * having to render a tile there.\n */\n readonly cells?: TileCellSource | undefined;\n /**\n * Merge adjacent whole-cell boxes that share a `type` into larger\n * rectangles. Default `true`. With `false`, every whole-cell box becomes its\n * own single-cell rectangle.\n */\n readonly merge?: boolean;\n /**\n * Drop source shapes before any geometry is built (e.g. by a custom\n * property). Return `true` to keep a shape. Default keeps all of them.\n */\n readonly accept?: (object: TileMapObject, tx: number, ty: number) => boolean;\n}\n\nconst DEGREES_TO_RADIANS = Math.PI / 180;\n\n/** Normalise degrees into `[0, 360)`. */\nconst normaliseDegrees = (degrees: number): number => {\n const wrapped = degrees % 360;\n\n return wrapped < 0 ? wrapped + 360 : wrapped;\n};\n\n/**\n * Cosine of an angle in degrees, exact on the quadrant multiples.\n * `Math.cos(Math.PI / 2)` is `6.1e-17`, not `0`; tile transforms produce those\n * quadrant angles constantly, and the whole-cell test below compares\n * coordinates exactly, so the noise has to stay out of the arithmetic.\n */\nconst cosDegrees = (degrees: number): number => {\n const angle = normaliseDegrees(degrees);\n\n if (angle === 0) return 1;\n if (angle === 90 || angle === 270) return 0;\n if (angle === 180) return -1;\n\n return Math.cos(angle * DEGREES_TO_RADIANS);\n};\n\n/** Sine of an angle in degrees, exact on the quadrant multiples. */\nconst sinDegrees = (degrees: number): number => {\n const angle = normaliseDegrees(degrees);\n\n if (angle === 0 || angle === 180) return 0;\n if (angle === 90) return 1;\n if (angle === 270) return -1;\n\n return Math.sin(angle * DEGREES_TO_RADIANS);\n};\n\n/** `true` when the transform mirrors (an odd number of reflections). */\nconst isMirrored = (transform: TileTransform): boolean => {\n const flags = (transform.flipX ? 1 : 0) + (transform.flipY ? 1 : 0) + (transform.diagonal ? 1 : 0);\n\n return flags % 2 === 1;\n};\n\n/**\n * Rotation in degrees contributed by a non-mirroring transform. Only the four\n * even-parity transforms are rotations: identity, `flipX+flipY` (180°),\n * `diagonal+flipX` (90°) and `diagonal+flipY` (270°).\n */\nconst transformRotation = (transform: TileTransform): number => {\n if (transform.diagonal) {\n return transform.flipX ? 90 : 270;\n }\n\n return transform.flipX ? 180 : 0;\n};\n\n/**\n * Map a point from tile-local pixel space into the transformed tile-local\n * space of a placed tile. The diagonal flip (a transpose of the axes, which\n * also swaps the box dimensions) is applied first, then the axis mirrors -\n * the same order the renderer's orientation code implies.\n */\nconst mapLocalPoint = (px: number, py: number, boxWidth: number, boxHeight: number, transform: TileTransform): ObjectPoint => {\n let x = px;\n let y = py;\n let width = boxWidth;\n let height = boxHeight;\n\n if (transform.diagonal) {\n const swapped = x;\n\n x = y;\n y = swapped;\n width = boxHeight;\n height = boxWidth;\n }\n\n if (transform.flipX) x = width - x;\n if (transform.flipY) y = height - y;\n\n return { x, y };\n};\n\n/**\n * Layer-space position of a placed tile's top-left image corner. Mirrors the\n * renderer's placement (see `chunkGeometry`): the tileset's draw offset shifts\n * every tile, and a tile taller than the layer's cell is bottom-aligned within\n * it, so collision geometry lands exactly where the tile is drawn.\n */\nconst tileAnchor = (layer: TileLayer, tileset: TileSet, tx: number, ty: number): ObjectPoint => {\n const point = layer.tileToPixel(tx, ty);\n return {\n x: point.x + tileset.offsetX - (layer.projection.orientation === 'isometric' ? layer.tileWidth / 2 : 0),\n y: point.y + layer.tileHeight - tileset.tileHeight + tileset.offsetY,\n };\n};\n\n/** A shape in layer pixel space, before it is classified as cell or shape. */\ninterface PlacedShape {\n readonly kind: TileCollisionShapeKind;\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n readonly rotation: number;\n readonly points?: readonly ObjectPoint[];\n}\n\n/**\n * Place one tile-local collision object into layer pixel space, applying the\n * tile's flip/rotation transform, the tileset draw offset and the layer offset.\n * Returns `null` for kinds that carry no collision geometry.\n */\nconst placeShape = (object: TileMapObject, layer: TileLayer, tileset: TileSet, transform: TileTransform, tx: number, ty: number): PlacedShape | null => {\n if (object.kind === ObjectKind.Tile || object.kind === ObjectKind.Text) {\n return null;\n }\n\n const anchor = tileAnchor(layer, tileset, tx, ty);\n const boxWidth = tileset.tileWidth;\n const boxHeight = tileset.tileHeight;\n const mirrored = isMirrored(transform);\n const sourceCos = cosDegrees(object.rotation);\n const sourceSin = sinDegrees(object.rotation);\n\n if (object.kind === ObjectKind.Polygon || object.kind === ObjectKind.Polyline) {\n // Rotation is baked into the vertices: the source rotation pivots about the\n // object origin, and the tile transform may mirror the whole tile, so an\n // origin-plus-angle form would need a second angle convention. Absolute\n // vertices are exact under both.\n const origin = mapLocalPoint(object.x, object.y, boxWidth, boxHeight, transform);\n const originX = anchor.x + origin.x;\n const originY = anchor.y + origin.y;\n const points = object.points.map(point => {\n const localX = object.x + (sourceCos * point.x - sourceSin * point.y);\n const localY = object.y + (sourceSin * point.x + sourceCos * point.y);\n const mapped = mapLocalPoint(localX, localY, boxWidth, boxHeight, transform);\n\n return { x: anchor.x + mapped.x - originX, y: anchor.y + mapped.y - originY };\n });\n\n return {\n kind: object.kind,\n x: originX,\n y: originY,\n width: 0,\n height: 0,\n rotation: 0,\n // A mirror reverses the winding order; reversing the vertices restores\n // the source orientation, which convex-hull/polygon consumers rely on.\n points: mirrored ? points.reverse() : points,\n };\n }\n\n if (object.kind === ObjectKind.Point) {\n const mapped = mapLocalPoint(object.x, object.y, boxWidth, boxHeight, transform);\n\n return {\n kind: ObjectKind.Point,\n x: anchor.x + mapped.x,\n y: anchor.y + mapped.y,\n width: 0,\n height: 0,\n rotation: 0,\n };\n }\n\n // Rectangles and ellipses are symmetric about their centre, so placing the\n // centre and re-deriving the origin handles every transform uniformly.\n const halfWidth = object.width / 2;\n const halfHeight = object.height / 2;\n const centreLocalX = object.x + (sourceCos * halfWidth - sourceSin * halfHeight);\n const centreLocalY = object.y + (sourceSin * halfWidth + sourceCos * halfHeight);\n const centre = mapLocalPoint(centreLocalX, centreLocalY, boxWidth, boxHeight, transform);\n const centreX = anchor.x + centre.x;\n const centreY = anchor.y + centre.y;\n\n // Conjugating a rotation by a mirror negates it; a non-mirroring transform is\n // itself a rotation and simply adds. Only a mirror can swap the local axes,\n // and then only when the diagonal flip is part of it.\n const rotation = normaliseDegrees(mirrored ? -object.rotation : object.rotation + transformRotation(transform));\n const swapAxes = mirrored && transform.diagonal;\n const width = swapAxes ? object.height : object.width;\n const height = swapAxes ? object.width : object.height;\n\n if (rotation % 90 === 0) {\n // Quadrant-aligned geometry is axis-aligned; re-express it without a\n // rotation so whole-cell boxes on rotated tiles stay mergeable.\n const axisWidth = rotation % 180 === 0 ? width : height;\n const axisHeight = rotation % 180 === 0 ? height : width;\n\n return {\n kind: object.kind,\n x: centreX - axisWidth / 2,\n y: centreY - axisHeight / 2,\n width: axisWidth,\n height: axisHeight,\n rotation: 0,\n };\n }\n\n const cos = cosDegrees(rotation);\n const sin = sinDegrees(rotation);\n\n return {\n kind: object.kind,\n x: centreX - (cos * (width / 2) - sin * (height / 2)),\n y: centreY - (sin * (width / 2) + cos * (height / 2)),\n width,\n height,\n rotation,\n };\n};\n\n/** Undo display geometry before merging cells or handing shapes to simulation. */\nconst logicalShape = (shape: PlacedShape, object: TileMapObject, layer: TileLayer): PlacedShape => {\n const p = layer.projection;\n if (p.orientation === 'orthogonal' && p.originX === 0 && p.originY === 0) return shape;\n const geometry = { ...object, ...shape };\n const mapped = p.unprojectObject(geometry as TileMapObject);\n if (mapped.kind === 'tile' || mapped.kind === 'text') return shape;\n if (mapped.kind === 'polygon' && mapped.points.length === 4) {\n const xs = mapped.points.map(point => point.x);\n const ys = mapped.points.map(point => point.y);\n const left = Math.min(...xs);\n const top = Math.min(...ys);\n const right = Math.max(...xs);\n const bottom = Math.max(...ys);\n const corners = new Set(mapped.points.map(point => `${point.x},${point.y}`));\n if (corners.size === 4 && mapped.points.every(point => (point.x === left || point.x === right) && (point.y === top || point.y === bottom))) {\n return { kind: 'rectangle', x: mapped.x + left, y: mapped.y + top, width: right - left, height: bottom - top, rotation: 0 };\n }\n }\n return mapped;\n};\n\n/** The tile-coordinate bounding box of the layer's loaded chunks, or `null`. */\nconst loadedTileRegion = (layer: TileLayer): TileRegion | null => {\n let minTx = Number.POSITIVE_INFINITY;\n let minTy = Number.POSITIVE_INFINITY;\n let maxTx = Number.NEGATIVE_INFINITY;\n let maxTy = Number.NEGATIVE_INFINITY;\n\n for (const chunk of layer.loadedChunks()) {\n const startTx = chunk.cx * layer.chunkWidth;\n const startTy = chunk.cy * layer.chunkHeight;\n\n minTx = Math.min(minTx, startTx);\n minTy = Math.min(minTy, startTy);\n maxTx = Math.max(maxTx, startTx + chunk.width - 1);\n maxTy = Math.max(maxTy, startTy + chunk.height - 1);\n }\n\n if (!Number.isFinite(minTx) || !Number.isFinite(minTy)) {\n return null;\n }\n\n return { x: minTx, y: minTy, width: maxTx - minTx + 1, height: maxTy - minTy + 1 };\n};\n\n/**\n * Region a cell source spans on `layer`: the full tile extent of a bounded\n * layer, `null` when the layer is unbounded and the caller must scope the\n * walk itself. Chunk residency deliberately plays no part - the classification\n * lives outside the layer, so loaded chunks cannot define its domain.\n */\nconst cellSourceRegion = (layer: TileLayer): TileRegion | null => {\n if (layer.width === undefined || layer.height === undefined) {\n return null;\n }\n\n return { x: 0, y: 0, width: layer.width, height: layer.height };\n};\n\n/**\n * The region to walk: the caller's, else the extent a cell source spans, else\n * whatever is currently resident. `null` when there is nothing to walk.\n */\nconst resolveRegion = (layer: TileLayer, options: TileCollisionOptions): TileRegion | null => {\n if (options.region !== undefined) return options.region;\n\n const fromCells = options.cells !== undefined ? cellSourceRegion(layer) : null;\n\n return fromCells ?? loadedTileRegion(layer);\n};\n\n/** Claim every cell of `region` the source classifies, into the occupancy grid. */\nconst claimSourceCells = (cells: Map<string, string>, region: TileRegion, source: TileCellSource): void => {\n const endTx = region.x + region.width;\n const endTy = region.y + region.height;\n\n for (let ty = region.y; ty < endTy; ty++) {\n for (let tx = region.x; tx < endTx; tx++) {\n const type = source(tx, ty);\n\n if (type !== null) cells.set(cellKey(tx, ty), type);\n }\n }\n};\n\n/** Key of a claimed cell in the occupancy grid. */\nconst cellKey = (tx: number, ty: number): string => `${tx},${ty}`;\n\n/**\n * `true` when a placed shape is an axis-aligned rectangle covering exactly the\n * tile cell at `(cellX, cellY)` - the only geometry the merging pass handles.\n */\nconst coversWholeCell = (placed: PlacedShape, layer: TileLayer, cellX: number, cellY: number): boolean =>\n placed.kind === ObjectKind.Rectangle &&\n placed.rotation === 0 &&\n placed.x === cellX &&\n placed.y === cellY &&\n placed.width === layer.projection.logicalTileWidth &&\n placed.height === layer.projection.logicalTileHeight;\n\n/** One single-cell rectangle per claimed cell, for `merge: false`. */\nconst unmergedCells = (cells: ReadonlyMap<string, string>, layer: TileLayer): TileCollisionRect[] => {\n const rects: TileCollisionRect[] = [];\n\n for (const [key, type] of cells) {\n const [tx, ty] = key.split(',').map(Number) as [number, number];\n\n rects.push({\n x: tx * layer.projection.logicalTileWidth + layer.logicalOffset.x,\n y: ty * layer.projection.logicalTileHeight + layer.logicalOffset.y,\n width: layer.projection.logicalTileWidth,\n height: layer.projection.logicalTileHeight,\n type,\n });\n }\n\n return rects;\n};\n\n/**\n * Greedy rectangle merging over the claimed cells: walk row-major, grow each\n * unconsumed cell as far right as the type key allows, then as far down as a\n * full row of that width allows, and consume the block. Deliberately the plain\n * textbook pass - it is linear in the number of cells and always produces a\n * valid, non-overlapping cover, which matters more here than minimality.\n */\nconst mergeCells = (cells: ReadonlyMap<string, string>, region: TileRegion, layer: TileLayer): TileCollisionRect[] => {\n const consumed = new Set<string>();\n const rects: TileCollisionRect[] = [];\n const endTx = region.x + region.width;\n const endTy = region.y + region.height;\n\n for (let ty = region.y; ty < endTy; ty++) {\n for (let tx = region.x; tx < endTx; tx++) {\n const key = cells.get(cellKey(tx, ty));\n\n if (key === undefined || consumed.has(cellKey(tx, ty))) {\n continue;\n }\n\n let width = 1;\n\n while (tx + width < endTx && cells.get(cellKey(tx + width, ty)) === key && !consumed.has(cellKey(tx + width, ty))) {\n width++;\n }\n\n let height = 1;\n\n growDown: while (ty + height < endTy) {\n for (let column = 0; column < width; column++) {\n const candidate = cellKey(tx + column, ty + height);\n\n if (cells.get(candidate) !== key || consumed.has(candidate)) {\n break growDown;\n }\n }\n\n height++;\n }\n\n for (let row = 0; row < height; row++) {\n for (let column = 0; column < width; column++) {\n consumed.add(cellKey(tx + column, ty + row));\n }\n }\n\n rects.push({\n x: tx * layer.projection.logicalTileWidth + layer.logicalOffset.x,\n y: ty * layer.projection.logicalTileHeight + layer.logicalOffset.y,\n width: width * layer.projection.logicalTileWidth,\n height: height * layer.projection.logicalTileHeight,\n type: key,\n });\n }\n }\n\n return rects;\n};\n\n/**\n * Extract collision geometry from a tile layer's per-tile\n * {@link import('./types').TileDefinition.collision} shapes.\n *\n * Every placed tile in `region` is resolved back to its tileset definition, and\n * each collision shape is transformed from tile-local pixel space into layer\n * pixel space (+Y down) - applying the tile's flip/rotation transform, the\n * tileset draw offset, and the layer's pixel offset, so the geometry lands\n * exactly where the tile is drawn.\n *\n * Shapes that end up covering exactly one whole tile cell are collected into an\n * occupancy grid and merged into as few {@link TileCollisionRect}s as a greedy\n * pass manages - a 200×200 solid region becomes one rectangle instead of 40 000.\n * Cells only merge with neighbours whose source object carries the same `type`\n * string, so a `water` run never fuses into an adjacent `solid` run. Everything\n * else (partial boxes, ellipses, polygons, polylines, points, rotated geometry)\n * passes through individually as a {@link TileCollisionShape}.\n *\n * A {@link TileCollisionOptions.cells} source feeds the same occupancy grid\n * from outside the tiles, for collision authored per cell rather than per tile.\n * It is consulted first, so a whole-cell tile box landing on a cell the source\n * already claimed passes through as a shape rather than overwriting it. With a\n * cell source and no explicit region, a bounded layer walks its full tile\n * extent - a layer that renders nothing at all still produces geometry.\n *\n * This package has no physics dependency and builds no bodies: the result is\n * plain geometry. Turning it into colliders is a short loop in application code.\n *\n * @param layer - The layer to walk.\n * @param options - Region scoping, merge toggle, a source-shape filter, and an\n * optional per-cell occupancy source.\n * @returns Merged rectangles plus pass-through shapes; both empty when the\n * region holds no tile carrying collision data.\n *\n * @example\n * ```ts\n * const { rects, shapes } = buildTileCollisionGeometry(layer);\n *\n * for (const rect of rects) {\n * world.add(makeStaticBox(rect.x, rect.y, rect.width, rect.height));\n * }\n * ```\n * @advanced\n */\nexport const buildTileCollisionGeometry = (layer: TileLayer, options: TileCollisionOptions = {}): TileCollisionGeometry => {\n const cellSource = options.cells;\n const region = resolveRegion(layer, options);\n\n if (region === null || region.width <= 0 || region.height <= 0) {\n return { rects: [], shapes: [] };\n }\n\n const accept = options.accept;\n const cells = new Map<string, string>();\n const shapes: TileCollisionShape[] = [];\n\n if (cellSource !== undefined) claimSourceCells(cells, region, cellSource);\n\n for (const { tx, ty, tile } of layer.tilesInRect(region.x, region.y, region.width, region.height)) {\n const definition = tile.tileset.getTileDefinition(tile.localTileId);\n\n if (definition?.collision === undefined) {\n continue;\n }\n\n const cellX = tx * layer.projection.logicalTileWidth + layer.logicalOffset.x;\n const cellY = ty * layer.projection.logicalTileHeight + layer.logicalOffset.y;\n\n for (const object of definition.collision) {\n if (accept !== undefined && !accept(object, tx, ty)) {\n continue;\n }\n\n const visual = placeShape(object, layer, tile.tileset, tile.transform, tx, ty);\n const placed = visual === null ? null : logicalShape(visual, object, layer);\n\n if (placed === null) {\n continue;\n }\n\n const key = cellKey(tx, ty);\n\n // A second whole-cell box on the same tile cannot claim the cell twice;\n // it falls through to the shape list so no geometry is silently dropped.\n if (coversWholeCell(placed, layer, cellX, cellY) && !cells.has(key)) {\n cells.set(key, object.type);\n continue;\n }\n\n shapes.push({\n kind: placed.kind,\n x: placed.x,\n y: placed.y,\n width: placed.width,\n height: placed.height,\n rotation: placed.rotation,\n ...(placed.points !== undefined && { points: placed.points }),\n tx,\n ty,\n source: object,\n });\n }\n }\n\n if (cells.size === 0) {\n return { rects: [], shapes };\n }\n\n const rects = options.merge === false ? unmergedCells(cells, layer) : mergeCells(cells, region, layer);\n\n return { rects, shapes };\n};\n"],"mappings":";;;AA2JA,MAAM,qBAAqB,KAAK,KAAK;;AAGrC,MAAM,oBAAoB,YAA4B;CACpD,MAAM,UAAU,UAAU;CAE1B,OAAO,UAAU,IAAI,UAAU,MAAM;AACvC;;;;;;;AAQA,MAAM,cAAc,YAA4B;CAC9C,MAAM,QAAQ,iBAAiB,OAAO;CAEtC,IAAI,UAAU,GAAG,OAAO;CACxB,IAAI,UAAU,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;IACV,MAAM,OAAO;IACb,GAAG,OAAO;IACV,GAAG,OAAO;IACV,OAAO,OAAO;IACd,QAAQ,OAAO;IACf,UAAU,OAAO;IACjB,GAAI,OAAO,WAAW,UAAa,EAAE,QAAQ,OAAO,OAAO;IAC3D;IACA;IACA,QAAQ;GACV,CAAC;EACH;CACF;CAEA,IAAI,MAAM,SAAS,GACjB,OAAO;EAAE,OAAO,CAAC;EAAG;CAAO;CAK7B,OAAO;EAAE,OAFK,QAAQ,UAAU,QAAQ,cAAc,OAAO,KAAK,IAAI,WAAW,OAAO,QAAQ,KAAK;EAErF;CAAO;AACzB"}
@@ -38,7 +38,7 @@ const tileMapNodeSerializer = {
38
38
  return out;
39
39
  },
40
40
  read(data, ctx) {
41
- const map = ctx.resolveAsset(typeof data.map === "string" ? data.map : null, TileMap);
41
+ const map = ctx.resolveAsset(data.map, TileMap);
42
42
  if (map === null) throw new Error("TileMapNode deserialize requires its TileMap to be pre-loaded into the Loader (procedural maps have no source key).");
43
43
  const node = new TileMapNode(map);
44
44
  if (typeof data.pixelSnapMode === "string") {
@@ -1 +1 @@
1
- {"version":3,"file":"tilemapSerializers.js","names":[],"sources":["../../src/tilemapSerializers.ts"],"sourcesContent":["import type { NodeSerializer } from '@codexo/exojs';\nimport { PixelSnapMode } from '@codexo/exojs/renderer-sdk';\n\nimport { TileMap } from './TileMap';\nimport { TileMapNode } from './TileMapNode';\n\n// On-disk format: the mode is persisted as its NAME (readable JSON, robust\n// against enum renumbering), mapped to/from the numeric enum here.\nconst pixelSnapModeNames: Record<PixelSnapMode, string> = {\n [PixelSnapMode.None]: 'none',\n [PixelSnapMode.Position]: 'position',\n [PixelSnapMode.Geometry]: 'geometry',\n};\n\nconst pixelSnapModeFromName: Record<string, PixelSnapMode> = {\n none: PixelSnapMode.None,\n position: PixelSnapMode.Position,\n geometry: PixelSnapMode.Geometry,\n};\n\n/**\n * Scene serializer for {@link TileMapNode} - the convenience node that renders a\n * whole {@link TileMap}.\n *\n * Captures the **map reference** (its Loader source key) plus the render-only\n * `pixelSnapMode`; the per-layer / per-chunk nodes are derived from the map and\n * rebuilt on construction, so they are never written. The referenced `TileMap`\n * must be pre-loaded into the target Loader (e.g. `loader.load(Asset.type('tileMap', 'world.tmj'))`)\n * before deserialize - procedurally-built maps have no source key and cannot be\n * referenced.\n *\n * Standalone `TileLayerNode` / `TileMapBand` placement (the actor-interleaving\n * cases) is not yet covered.\n *\n * @internal - registered via {@link tilemapExtension}'s `serializers` binding.\n */\nexport const tileMapNodeSerializer: NodeSerializer<TileMapNode> = {\n write(node, ctx) {\n const out: Record<string, unknown> = {};\n const source = ctx.keyFor(node.map);\n\n if (source !== null) {\n out.map = source;\n }\n\n if (node.pixelSnapMode !== PixelSnapMode.None) {\n out.pixelSnapMode = pixelSnapModeNames[node.pixelSnapMode];\n }\n\n return out;\n },\n read(data, ctx) {\n const map = ctx.resolveAsset(typeof data.map === 'string' ? data.map : null, TileMap);\n\n if (map === null) {\n throw new Error('TileMapNode deserialize requires its TileMap to be pre-loaded into the Loader (procedural maps have no source key).');\n }\n\n const node = new TileMapNode(map);\n\n if (typeof data.pixelSnapMode === 'string') {\n const mode = pixelSnapModeFromName[data.pixelSnapMode];\n\n if (mode !== undefined) {\n node.pixelSnapMode = mode;\n }\n }\n\n return node;\n },\n};\n"],"mappings":";;;;;AAQA,MAAM,qBAAoD;EACvD,cAAc,OAAO;EACrB,cAAc,WAAW;EACzB,cAAc,WAAW;AAC5B;AAEA,MAAM,wBAAuD;CAC3D,MAAM,cAAc;CACpB,UAAU,cAAc;CACxB,UAAU,cAAc;AAC1B;;;;;;;;;;;;;;;;;AAkBA,MAAa,wBAAqD;CAChE,MAAM,MAAM,KAAK;EACf,MAAM,MAA+B,CAAC;EACtC,MAAM,SAAS,IAAI,OAAO,KAAK,GAAG;EAElC,IAAI,WAAW,MACb,IAAI,MAAM;EAGZ,IAAI,KAAK,kBAAkB,cAAc,MACvC,IAAI,gBAAgB,mBAAmB,KAAK;EAG9C,OAAO;CACT;CACA,KAAK,MAAM,KAAK;EACd,MAAM,MAAM,IAAI,aAAa,OAAO,KAAK,QAAQ,WAAW,KAAK,MAAM,MAAM,OAAO;EAEpF,IAAI,QAAQ,MACV,MAAM,IAAI,MAAM,qHAAqH;EAGvI,MAAM,OAAO,IAAI,YAAY,GAAG;EAEhC,IAAI,OAAO,KAAK,kBAAkB,UAAU;GAC1C,MAAM,OAAO,sBAAsB,KAAK;GAExC,IAAI,SAAS,QACX,KAAK,gBAAgB;EAEzB;EAEA,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"tilemapSerializers.js","names":[],"sources":["../../src/tilemapSerializers.ts"],"sourcesContent":["import type { NodeSerializer } from '@codexo/exojs';\nimport { PixelSnapMode } from '@codexo/exojs/renderer-sdk';\n\nimport { TileMap } from './TileMap';\nimport { TileMapNode } from './TileMapNode';\n\n// On-disk format: the mode is persisted as its NAME (readable JSON, robust\n// against enum renumbering), mapped to/from the numeric enum here.\nconst pixelSnapModeNames: Record<PixelSnapMode, string> = {\n [PixelSnapMode.None]: 'none',\n [PixelSnapMode.Position]: 'position',\n [PixelSnapMode.Geometry]: 'geometry',\n};\n\nconst pixelSnapModeFromName: Record<string, PixelSnapMode> = {\n none: PixelSnapMode.None,\n position: PixelSnapMode.Position,\n geometry: PixelSnapMode.Geometry,\n};\n\n/**\n * Scene serializer for {@link TileMapNode} - the convenience node that renders a\n * whole {@link TileMap}.\n *\n * Captures the **map reference** (its Loader source key) plus the render-only\n * `pixelSnapMode`; the per-layer / per-chunk nodes are derived from the map and\n * rebuilt on construction, so they are never written. The referenced `TileMap`\n * must be pre-loaded into the target Loader (e.g. `loader.load(Asset.type('tileMap', 'world.tmj'))`)\n * before deserialize - procedurally-built maps have no source key and cannot be\n * referenced.\n *\n * Standalone `TileLayerNode` / `TileMapBand` placement (the actor-interleaving\n * cases) is not yet covered.\n *\n * @internal - registered via {@link tilemapExtension}'s `serializers` binding.\n */\nexport const tileMapNodeSerializer: NodeSerializer<TileMapNode> = {\n write(node, ctx) {\n const out: Record<string, unknown> = {};\n const source = ctx.keyFor(node.map);\n\n if (source !== null) {\n out.map = source;\n }\n\n if (node.pixelSnapMode !== PixelSnapMode.None) {\n out.pixelSnapMode = pixelSnapModeNames[node.pixelSnapMode];\n }\n\n return out;\n },\n read(data, ctx) {\n const map = ctx.resolveAsset(data.map, TileMap);\n\n if (map === null) {\n throw new Error('TileMapNode deserialize requires its TileMap to be pre-loaded into the Loader (procedural maps have no source key).');\n }\n\n const node = new TileMapNode(map);\n\n if (typeof data.pixelSnapMode === 'string') {\n const mode = pixelSnapModeFromName[data.pixelSnapMode];\n\n if (mode !== undefined) {\n node.pixelSnapMode = mode;\n }\n }\n\n return node;\n },\n};\n"],"mappings":";;;;;AAQA,MAAM,qBAAoD;EACvD,cAAc,OAAO;EACrB,cAAc,WAAW;EACzB,cAAc,WAAW;AAC5B;AAEA,MAAM,wBAAuD;CAC3D,MAAM,cAAc;CACpB,UAAU,cAAc;CACxB,UAAU,cAAc;AAC1B;;;;;;;;;;;;;;;;;AAkBA,MAAa,wBAAqD;CAChE,MAAM,MAAM,KAAK;EACf,MAAM,MAA+B,CAAC;EACtC,MAAM,SAAS,IAAI,OAAO,KAAK,GAAG;EAElC,IAAI,WAAW,MACb,IAAI,MAAM;EAGZ,IAAI,KAAK,kBAAkB,cAAc,MACvC,IAAI,gBAAgB,mBAAmB,KAAK;EAG9C,OAAO;CACT;CACA,KAAK,MAAM,KAAK;EACd,MAAM,MAAM,IAAI,aAAa,KAAK,KAAK,OAAO;EAE9C,IAAI,QAAQ,MACV,MAAM,IAAI,MAAM,qHAAqH;EAGvI,MAAM,OAAO,IAAI,YAAY,GAAG;EAEhC,IAAI,OAAO,KAAK,kBAAkB,UAAU;GAC1C,MAAM,OAAO,sBAAsB,KAAK;GAExC,IAAI,SAAS,QACX,KAAK,gBAAgB;EAEzB;EAEA,OAAO;CACT;AACF"}
@@ -12,9 +12,9 @@ import type { TileSet } from './TileSet';
12
12
  * @stable
13
13
  */
14
14
  export declare const TilePropertyKind: {
15
- readonly Point: "point";
16
- readonly ObjectRef: "objectRef";
17
- readonly TileRef: "tileRef";
15
+ readonly Point: 'point';
16
+ readonly ObjectRef: 'objectRef';
17
+ readonly TileRef: 'tileRef';
18
18
  };
19
19
  /** Structured-value discriminant for {@link TilePropertyValue}. */
20
20
  export type TilePropertyKind = (typeof TilePropertyKind)[keyof typeof TilePropertyKind];
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAIzC;;;;;;;;;;GAUG;AACH,eAAO,MAAM,gBAAgB;;;;CAInB,CAAC;AAEX,mEAAmE;AACnE,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,OAAO,gBAAgB,CAAC,CAAC;AAExF,oEAAoE;AACpE,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,IAAI,EAAE,OAAO,gBAAgB,CAAC,KAAK,CAAC;IAC7C,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,IAAI,EAAE,OAAO,gBAAgB,CAAC,SAAS,CAAC;IACjD,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,2EAA2E;AAC3E,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,IAAI,EAAE,OAAO,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;GASG;AACH,eAAO,MAAM,wBAAwB,UAAW,MAAM,GAAG,SAAS,UAAU,MAAM,GAAG,SAAS,cAAc,MAAM,eAAe,MAAM,KAAG,IAQzI,CAAC"}
@@ -1,7 +1,7 @@
1
1
  import { TILE_DIAGONAL_BIT, TILE_ROW_MASK } from "../tileWord.js";
2
2
  import tile_chunk_default from "./shaders/tile-chunk.frag.js";
3
3
  import tile_chunk_default$1 from "./shaders/tile-chunk.vert.js";
4
- import { AbstractWebGl2Renderer, BlendModes, BufferTypes, BufferUsage, RenderingPrimitives, WebGl2RenderBuffer, WebGl2Shader, WebGl2VertexArrayObject, createWebGl2ShaderProgram, fillShaderSource, packedGroupChanged, uploadBufferRange, uploadBufferStore } from "@codexo/exojs/renderer-sdk";
4
+ import { AbstractWebGl2Renderer, BlendModes, BufferTypes, BufferUsage, RenderingPrimitives, WebGl2RenderBuffer, WebGl2Shader, WebGl2VertexArrayObject, colorShaderSourcesGlsl, createWebGl2ShaderProgram, fillShaderSource, packedGroupChanged, spliceGlslPrologue, uploadBufferRange, uploadBufferStore } from "@codexo/exojs/renderer-sdk";
5
5
 
6
6
  //#region src/webgl2/WebGl2TileChunkRenderer.ts
7
7
  const instanceStrideBytes = 32;
@@ -18,10 +18,10 @@ const identityGroupMat3 = new Float32Array([
18
18
  0,
19
19
  1
20
20
  ]);
21
- const tileVertexSource = fillShaderSource(tile_chunk_default$1, {
21
+ const tileVertexSource = spliceGlslPrologue(fillShaderSource(tile_chunk_default$1, {
22
22
  tileRowMask: TILE_ROW_MASK,
23
23
  tileDiagonalBit: TILE_DIAGONAL_BIT
24
- });
24
+ }), colorShaderSourcesGlsl);
25
25
  /**
26
26
  * Instanced WebGL2 renderer for {@link TileChunkNode}. Each tile is one
27
27
  * instanced quad; tiles are batched by `(shader, tileset texture)` and one
@@ -253,7 +253,7 @@ var WebGl2TileChunkRenderer = class extends AbstractWebGl2Renderer {
253
253
  const backend = this.getBackendOrNull();
254
254
  const vao = payload.vao;
255
255
  const transformTexture = payload.bundle.transformTexture;
256
- if (backend === null || vao === null || transformTexture === null) return;
256
+ if (backend === null || vao === null || transformTexture === null) return false;
257
257
  backend.setBlendMode(payload.blendMode);
258
258
  this._stageViewUniforms(backend);
259
259
  const textures = payload.textures;
@@ -264,6 +264,7 @@ var WebGl2TileChunkRenderer = class extends AbstractWebGl2Renderer {
264
264
  this._shader.sync();
265
265
  backend.bindVertexArrayObject(vao);
266
266
  vao.drawInstanced(4, 0, payload.instanceCount, RenderingPrimitives.TriangleStrip);
267
+ return true;
267
268
  }
268
269
  onConnect(backend) {
269
270
  const gl = backend.context;
@@ -1 +1 @@
1
- {"version":3,"file":"WebGl2TileChunkRenderer.js","names":["tileVertexTemplate","tileFragmentSource"],"sources":["../../../src/webgl2/WebGl2TileChunkRenderer.ts"],"sourcesContent":["import type {\n RenderTexture,\n Texture,\n View,\n WebGl2Backend,\n WebGl2RenderBufferRuntime,\n WebGl2RetainedBatchPayload,\n WebGl2RetainedBatchReplayer,\n WebGl2RetainedNodeIndexRange,\n WebGl2VertexArrayObjectRuntime,\n} from '@codexo/exojs/renderer-sdk';\nimport {\n AbstractWebGl2Renderer,\n BlendModes,\n BufferTypes,\n BufferUsage,\n createWebGl2ShaderProgram,\n fillShaderSource,\n packedGroupChanged,\n RenderingPrimitives,\n uploadBufferRange,\n uploadBufferStore,\n WebGl2RenderBuffer,\n WebGl2Shader,\n WebGl2VertexArrayObject,\n} from '@codexo/exojs/renderer-sdk';\n\nimport type { TileQuad } from '../chunkGeometry';\nimport type { TileChunkNode } from '../TileChunkNode';\nimport { TILE_DIAGONAL_BIT, TILE_ROW_MASK } from '../tileWord';\nimport tileFragmentSource from './shaders/tile-chunk.frag';\nimport tileVertexTemplate from './shaders/tile-chunk.vert';\n\n// One instance = one tile quad. Layout matches the engine's instanced-quad\n// convention (NineSlice/Repeating): float32x4 local rect, unorm16x4 UV bounds,\n// unorm8x4 tint, uint32 tile word (transform row + diagonal bit).\nconst instanceStrideBytes = 32;\nconst wordsPerInstance = instanceStrideBytes / Uint32Array.BYTES_PER_ELEMENT;\nconst transformTextureUnit = 1;\nconst identityGroupMat3 = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);\n\nconst tileVertexSource = fillShaderSource(tileVertexTemplate, { tileRowMask: TILE_ROW_MASK, tileDiagonalBit: TILE_DIAGONAL_BIT });\n\ninterface TileRendererConnection {\n readonly gl: WebGL2RenderingContext;\n readonly buffers: Map<WebGl2RenderBuffer, { handle: WebGLBuffer; dataByteLength: number }>;\n readonly vaoHandle: WebGLVertexArrayObject;\n}\n\n/**\n * Instanced WebGL2 renderer for {@link TileChunkNode}. Each tile is one\n * instanced quad; tiles are batched by `(shader, tileset texture)` and one\n * `drawArraysInstanced` is issued per batch. Per-chunk transforms ride on the\n * shared transform buffer (one row per chunk node), so the chunk geometry is\n * orientation-neutral and never re-uploaded for a camera pan.\n * @internal\n */\nexport class WebGl2TileChunkRenderer extends AbstractWebGl2Renderer<TileChunkNode> implements WebGl2RetainedBatchReplayer {\n /**\n * Retained-batch capability opt-in: a tile chunk's per-flush\n * instanced batches (fixed 32-byte layout, tile word at word 7) can be\n * recorded into a group's instruction set and replayed from group-owned\n * resources. Pixel-snapped draws are excluded by the collect-time\n * recordability predicate (and belt-and-braces poisoning in {@link render});\n * tile chunks have no custom-material path to exclude.\n * @internal\n */\n public readonly supportsRetainedBatches = true;\n\n private readonly _shader: WebGl2Shader;\n private readonly _batchSize: number;\n private readonly _instanceData: ArrayBuffer;\n private readonly _instanceFloat32: Float32Array;\n private readonly _instanceUint32: Uint32Array;\n\n private readonly _transformUnitScratch: Int32Array = new Int32Array([transformTextureUnit]);\n // Pinned unit index for the single tileset texture sampler (unit 0), reused\n // by the live flush and retained replay so both stay allocation-free.\n private readonly _baseTextureUnitScratch: Int32Array = new Int32Array([0]);\n // Reused single-slot texture list handed to the backend at record time; a\n // tile chunk batch always binds exactly one tileset texture (slot 0).\n private readonly _recordTextures: Array<Texture | RenderTexture | null> = [null];\n\n private _quadIndex = 0;\n private _maxNodeIndex = 0;\n // Chunk nodes booked against the PENDING batch, and whether the chunk being\n // rendered right now has already been booked. One chunk emits one tile\n // instance per tile, so the recorded batch's `submittedNodes` contribution is\n // this count and not `_quadIndex`. A chunk whose pages/runs span several\n // batches is booked once, against the batch its first run lands in.\n private _batchNodeCount = 0;\n private _nodeBooked = false;\n // Blend mode and tileset texture of the batch currently accumulating, used to\n // detect a batch break. Neither is a mirror of backend state: `flush()`\n // establishes both at the draw (see {@link _resetBatchState}).\n private _currentBlendMode: BlendModes | null = null;\n private _currentTexture: Texture | null = null;\n private _currentView: View | null = null;\n private _currentViewId = -1;\n private _hasWrittenGroup = false;\n private readonly _writtenGroupData = new Float32Array(9);\n\n private _instanceBuffer: WebGl2RenderBuffer | null = null;\n private _vao: WebGl2VertexArrayObject | null = null;\n private _connection: TileRendererConnection | null = null;\n\n public constructor(batchSize: number) {\n super();\n\n this._batchSize = batchSize;\n this._shader = new WebGl2Shader(tileVertexSource, tileFragmentSource);\n this._instanceData = new ArrayBuffer(batchSize * instanceStrideBytes);\n this._instanceFloat32 = new Float32Array(this._instanceData);\n this._instanceUint32 = new Uint32Array(this._instanceData);\n }\n\n public render(node: TileChunkNode): void {\n const pages = node.pages;\n\n this._nodeBooked = false;\n\n if (pages.length === 0) {\n return;\n }\n\n const backend = this.getBackend();\n\n const blendMode = node.blendMode;\n const tintRgba = node.tint.toRgba8();\n\n const command = backend.activeDrawCommand;\n const nodeIndex = command !== null ? command.nodeIndex : backend.pushTransform(node);\n\n for (const page of pages) {\n this._renderPage(page.texture, page.quads, blendMode, tintRgba, nodeIndex);\n }\n }\n\n private _renderPage(texture: Texture, quads: readonly TileQuad[], blendMode: BlendModes, tintRgba: number, nodeIndex: number): void {\n if (quads.length === 0) {\n return;\n }\n\n const textureChanged = this._currentTexture !== null && texture !== this._currentTexture;\n const blendModeChanged = this._currentBlendMode !== null && blendMode !== this._currentBlendMode;\n\n if (this._quadIndex > 0 && (blendModeChanged || textureChanged || this._quadIndex + quads.length > this._batchSize)) {\n this.flush();\n }\n\n this._currentBlendMode = blendMode;\n this._currentTexture = texture;\n\n const flipY = texture.flipY;\n\n // A chunk page may hold more tiles than the fixed batch buffer; write in\n // batch-sized runs, flushing (and re-establishing state) between runs.\n let offset = 0;\n\n while (offset < quads.length) {\n const remaining = quads.length - offset;\n const runSize = Math.min(remaining, this._batchSize);\n\n this._writeRun(quads, offset, runSize, flipY, tintRgba, nodeIndex);\n\n offset += runSize;\n\n if (offset < quads.length) {\n this.flush();\n this._currentBlendMode = blendMode;\n this._currentTexture = texture;\n }\n }\n }\n\n private _writeRun(quads: readonly TileQuad[], offset: number, count: number, flipY: boolean, tintRgba: number, nodeIndex: number): void {\n const f32 = this._instanceFloat32;\n const u32 = this._instanceUint32;\n const baseWord = nodeIndex & TILE_ROW_MASK;\n\n // Booked here rather than in render(): any flush the page/run loops trigger\n // has already happened, so the chunk lands on the batch that actually holds\n // its first tile.\n if (!this._nodeBooked) {\n this._nodeBooked = true;\n this._batchNodeCount++;\n }\n\n for (let i = 0; i < count; i++) {\n const q = quads[offset + i]!;\n const idx = this._quadIndex * wordsPerInstance;\n\n f32[idx + 0] = q.x0;\n f32[idx + 1] = q.y0;\n f32[idx + 2] = q.x1;\n f32[idx + 3] = q.y1;\n\n // Bake flipX/flipY into the UV corner ordering; the diagonal axis swap is\n // resolved in the shader. Texture flipY (uploaded-flipped atlases) is an\n // additional vertical swap that composes with the tile flipY.\n const flipX = (q.orient & 1) !== 0;\n const tileFlipY = (q.orient & 2) !== 0;\n const diagonal = (q.orient & 4) !== 0;\n\n const uA = flipX ? q.u1 : q.u0;\n const uB = flipX ? q.u0 : q.u1;\n let vA = tileFlipY ? q.v1 : q.v0;\n let vB = tileFlipY ? q.v0 : q.v1;\n\n if (flipY) {\n const swap = vA;\n vA = vB;\n vB = swap;\n }\n\n const uMin = (uA * 0xffff) & 0xffff;\n const vMin = (vA * 0xffff) & 0xffff;\n const uMax = (uB * 0xffff) & 0xffff;\n const vMax = (vB * 0xffff) & 0xffff;\n\n u32[idx + 4] = uMin | (vMin << 16);\n u32[idx + 5] = uMax | (vMax << 16);\n u32[idx + 6] = tintRgba;\n u32[idx + 7] = (diagonal ? baseWord | TILE_DIAGONAL_BIT : baseWord) >>> 0;\n\n this._quadIndex++;\n }\n\n if (nodeIndex > this._maxNodeIndex) {\n this._maxNodeIndex = nodeIndex;\n }\n }\n\n public flush(): void {\n const backend = this.getBackendOrNull();\n const instanceBuffer = this._instanceBuffer;\n const vao = this._vao;\n\n if (this._quadIndex === 0 || backend === null || instanceBuffer === null || vao === null) {\n this._resetBatchState();\n return;\n }\n\n this._stageViewUniforms(backend);\n\n // Blend state and texture unit 0 are global and shared with every other\n // renderer - a sprite drawn between two tile layers binds its own texture\n // to the same unit - so this batch establishes both at its own draw. The\n // backend collapses a redundant call.\n if (this._currentTexture !== null) {\n backend.bindTexture(this._currentTexture, 0);\n this._shader.getUniform('u_texture').setValue(this._baseTextureUnitScratch);\n }\n\n backend.bindTransformBufferTexture(transformTextureUnit, this._maxNodeIndex + 1);\n this._shader.getUniform('u_transforms').setValue(this._transformUnitScratch);\n\n this._shader.sync();\n backend.bindVertexArrayObject(vao);\n instanceBuffer.upload(this._instanceFloat32, 0, this._quadIndex * wordsPerInstance);\n backend.setBlendMode(this._currentBlendMode ?? BlendModes.Normal);\n vao.drawInstanced(4, 0, this._quadIndex, RenderingPrimitives.TriangleStrip);\n backend.stats.batches++;\n backend.stats.drawCalls++;\n\n // Retained recording: while a capture window is open, hand the\n // exact packed instance words of this flush to the backend - byte-\n // identical to what just drew. A batch always binds a single tileset\n // texture (slot 0); a pixel-snapped node already poisoned the capture in\n // render().\n if (backend._isRetainedCapturing && this._currentTexture !== null) {\n this._recordTextures[0] = this._currentTexture;\n backend.recordRetainedBatch(\n this,\n this._instanceUint32.subarray(0, this._quadIndex * wordsPerInstance),\n this._quadIndex,\n this._currentBlendMode ?? BlendModes.Normal,\n this._recordTextures,\n 1,\n null,\n null,\n this._batchNodeCount,\n );\n }\n\n this._resetBatchState();\n }\n\n /**\n * Scope the batch memos to one batch: they describe what is accumulating, not\n * what GL holds, so a memo that outlived its flush would let the next batch\n * skip establishing state another renderer has since changed.\n */\n private _resetBatchState(): void {\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._currentBlendMode = null;\n this._currentTexture = null;\n }\n\n /**\n * Stage `u_projection` (live view) and `u_group` (live composed group\n * matrix) on the shader, guarded by cached view/group stamps. Shared by the\n * live flush path and retained-batch replay - replay resolves exactly the\n * same live state a slow-path flush would.\n */\n private _stageViewUniforms(backend: WebGl2Backend): void {\n const view = backend.view;\n\n if (this._currentView !== view || this._currentViewId !== view.updateId) {\n this._currentView = view;\n this._currentViewId = view.updateId;\n this._shader.getUniform('u_projection').setValue(view.getTransform().toArray(false));\n }\n\n const groupTransform = backend.renderGroupTransform;\n const groupData = groupTransform !== null ? groupTransform.toArray(false) : identityGroupMat3;\n\n if (!this._hasWrittenGroup || packedGroupChanged(groupData, this._writtenGroupData, 0)) {\n this._shader.getUniform('u_group').setValue(groupData);\n this._writtenGroupData.set(groupData);\n this._hasWrittenGroup = true;\n }\n\n backend.stageViewportUniform(this._shader);\n }\n\n // ── Retained-batch record/replay ──────────────────────────────────────────\n // The bundle stores raw instance bytes; this renderer owns the 32-byte\n // layout (tile word at word 7: transform row in bits 0..28, diagonal flip in\n // bit 29), so the layout-aware finalize steps (node-index scan/rebase, VAO\n // attribute wiring) and the replay dispatch live here - mirroring\n // WebGl2NineSliceSpriteRenderer's seam.\n\n /** @internal See {@link WebGl2RetainedBatchReplayer.scanRetainedNodeIndexRange}. */\n public scanRetainedNodeIndexRange(payload: WebGl2RetainedBatchPayload, range: WebGl2RetainedNodeIndexRange): void {\n const words = payload.bundle.instanceWords;\n const start = payload.byteOffset / Uint32Array.BYTES_PER_ELEMENT;\n\n for (let i = 0; i < payload.instanceCount; i++) {\n // In-bounds: the payload's word range was appended to the bundle store.\n // The tile word is the last word of the 32-byte (8-word) instance\n // layout; only the low 29 bits address the transform buffer row - the\n // diagonal-flip flag (bit 29) is orientation, not a row index.\n const row = words[start + i * wordsPerInstance + 7]! & TILE_ROW_MASK;\n\n if (row < range.min) {\n range.min = row;\n }\n\n if (row > range.max) {\n range.max = row;\n }\n }\n }\n\n /** @internal See {@link WebGl2RetainedBatchReplayer.rebaseRetainedNodeIndices} (group-local indices). */\n public rebaseRetainedNodeIndices(payload: WebGl2RetainedBatchPayload, base: number): void {\n const words = payload.bundle.instanceWords;\n const start = payload.byteOffset / Uint32Array.BYTES_PER_ELEMENT;\n\n for (let i = 0; i < payload.instanceCount; i++) {\n const index = start + i * wordsPerInstance + 7;\n // In-bounds: see the scan above. Rebase ONLY the row field; the\n // diagonal-flip bit must survive untouched or tile orientation corrupts.\n const word = words[index]!;\n const diagonal = word & TILE_DIAGONAL_BIT;\n const row = word & TILE_ROW_MASK;\n\n words[index] = (diagonal | ((row - base) & TILE_ROW_MASK)) >>> 0;\n }\n }\n\n /**\n * Point the batch VAO's per-instance attributes at the bundle's persistent\n * instance buffer, based at the batch's byte offset (WebGL2 has no\n * baseInstance, hence one small VAO per recorded batch). Same attribute\n * set/locations as the live VAO in {@link onConnect}.\n * @internal\n */\n public configureRetainedVao(payload: WebGl2RetainedBatchPayload): void {\n const gl = this.getBackend().context;\n const buffer = payload.bundle.instanceBuffer;\n const vao = payload.vao;\n\n if (buffer === null || vao === null) {\n throw new Error('WebGl2TileChunkRenderer: retained batch VAO configuration requires an uploaded bundle.');\n }\n\n const base = payload.byteOffset;\n\n vao\n .addAttribute(buffer, this._shader.getAttribute('a_quadBounds'), gl.FLOAT, false, instanceStrideBytes, base + 0, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_uvBounds'), gl.UNSIGNED_SHORT, true, instanceStrideBytes, base + 16, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_color'), gl.UNSIGNED_BYTE, true, instanceStrideBytes, base + 24, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_tileWord'), gl.UNSIGNED_INT, false, instanceStrideBytes, base + 28, true, 1);\n }\n\n /**\n * Replay one recorded batch: all STATE is resolved live - blend mode via\n * the backend's dedup, `u_projection`/`u_group` from the live view + live\n * composed group matrix (the camera-pan / group-move win), the single\n * tileset texture bound to unit 0 by recorded slot order - and only the\n * DATA is cached: the instance bytes in the bundle buffer (bound through\n * the per-batch VAO) and the group-owned transform texture on the shared\n * transform unit. The backend hook flushed any pending live batch before\n * dispatching here and bumps the stats from the instruction descriptor.\n * @internal\n */\n public replayRetainedBatch(payload: WebGl2RetainedBatchPayload): void {\n const backend = this.getBackendOrNull();\n const vao = payload.vao;\n const transformTexture = payload.bundle.transformTexture;\n\n if (backend === null || vao === null || transformTexture === null) {\n // Defensive: a bundle in this state never validates (generation), so a\n // spliced replay cannot reach here; skip rather than crash mid-frame.\n return;\n }\n\n backend.setBlendMode(payload.blendMode);\n this._stageViewUniforms(backend);\n\n const textures = payload.textures;\n\n for (let i = 0; i < textures.length; i++) {\n // In-bounds: i < textures.length.\n backend.bindTexture(textures[i]!, i);\n }\n\n this._shader.getUniform('u_texture').setValue(this._baseTextureUnitScratch);\n\n // The group-owned transform store replaces the shared frame buffer on the\n // SAME unit/sampler - zero GLSL changes. The next live flush re-binds the\n // shared texture through bindTransformBufferTexture.\n backend.bindTexture(transformTexture, transformTextureUnit);\n this._shader.getUniform('u_transforms').setValue(this._transformUnitScratch);\n\n this._shader.sync();\n backend.bindVertexArrayObject(vao);\n vao.drawInstanced(4, 0, payload.instanceCount, RenderingPrimitives.TriangleStrip);\n }\n\n protected onConnect(backend: WebGl2Backend): void {\n const gl = backend.context;\n\n this._shader.connect(createWebGl2ShaderProgram(gl));\n this._connection = this._createConnection(gl);\n this._instanceBuffer = new WebGl2RenderBuffer(BufferTypes.ArrayBuffer, this._instanceData, BufferUsage.DynamicDraw).connect(\n this._createBufferRuntime(this._connection),\n );\n this._shader.sync();\n\n this._vao = new WebGl2VertexArrayObject(RenderingPrimitives.TriangleStrip)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_quadBounds'), gl.FLOAT, false, instanceStrideBytes, 0, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_uvBounds'), gl.UNSIGNED_SHORT, true, instanceStrideBytes, 16, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_color'), gl.UNSIGNED_BYTE, true, instanceStrideBytes, 24, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_tileWord'), gl.UNSIGNED_INT, false, instanceStrideBytes, 28, true, 1)\n .connect(this._createVaoRuntime(this._connection));\n }\n\n protected onDisconnect(): void {\n this._shader.destroy();\n this._instanceBuffer?.destroy();\n this._instanceBuffer = null;\n this._vao?.destroy();\n this._vao = null;\n this._connection = null;\n this._currentBlendMode = null;\n this._currentTexture = null;\n this._currentView = null;\n this._currentViewId = -1;\n this._hasWrittenGroup = false;\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._nodeBooked = false;\n }\n\n public destroy(): void {\n this.disconnect();\n this._shader.destroy();\n }\n\n private _createConnection(gl: WebGL2RenderingContext): TileRendererConnection {\n const vaoHandle = gl.createVertexArray();\n\n if (vaoHandle === null) {\n throw new Error('WebGl2TileChunkRenderer: could not create vertex array object.');\n }\n\n return { gl, buffers: new Map(), vaoHandle };\n }\n\n private _createBufferRuntime(connection: TileRendererConnection): WebGl2RenderBufferRuntime {\n const handle = connection.gl.createBuffer();\n\n if (handle === null) {\n throw new Error('WebGl2TileChunkRenderer: could not create render buffer.');\n }\n\n return {\n bind: (buffer): void => {\n connection.gl.bindBuffer(buffer.type, handle);\n },\n upload: (buffer, offset): void => {\n const gl = connection.gl;\n const state = connection.buffers.get(buffer);\n\n gl.bindBuffer(buffer.type, handle);\n\n if (state && state.dataByteLength >= buffer.uploadByteLength) {\n uploadBufferRange(gl, buffer, offset);\n state.dataByteLength = buffer.uploadByteLength;\n } else {\n uploadBufferStore(gl, buffer);\n connection.buffers.set(buffer, { handle, dataByteLength: buffer.uploadByteLength });\n }\n },\n destroy: (buffer): void => {\n connection.gl.deleteBuffer(handle);\n connection.buffers.delete(buffer);\n buffer.disconnect();\n },\n };\n }\n\n private _createVaoRuntime(connection: TileRendererConnection): WebGl2VertexArrayObjectRuntime {\n let appliedVersion = -1;\n\n return {\n bind: (vao): void => {\n const gl = connection.gl;\n\n gl.bindVertexArray(connection.vaoHandle);\n\n if (appliedVersion !== vao.version) {\n let lastBuffer: WebGl2RenderBuffer | null = null;\n\n for (const attribute of vao.attributes) {\n if (lastBuffer !== attribute.buffer) {\n attribute.buffer.bind();\n lastBuffer = attribute.buffer;\n }\n\n if (attribute.integer) {\n gl.vertexAttribIPointer(attribute.location, attribute.size, attribute.type, attribute.stride, attribute.start);\n } else {\n gl.vertexAttribPointer(attribute.location, attribute.size, attribute.type, attribute.normalized, attribute.stride, attribute.start);\n }\n\n gl.enableVertexAttribArray(attribute.location);\n gl.vertexAttribDivisor(attribute.location, attribute.divisor);\n }\n\n appliedVersion = vao.version;\n }\n },\n unbind: (): void => {\n connection.gl.bindVertexArray(null);\n },\n draw: (_vao, size, start, type): void => {\n connection.gl.drawArrays(type, start, size);\n },\n drawInstanced: (_vao, count, start, instanceCount, type): void => {\n connection.gl.drawArraysInstanced(type, start, count, instanceCount);\n },\n destroy: (vao): void => {\n connection.gl.deleteVertexArray(connection.vaoHandle);\n vao.disconnect();\n },\n };\n }\n}\n"],"mappings":";;;;;;AAoCA,MAAM,sBAAsB;AAC5B,MAAM,mBAAmB,sBAAsB,YAAY;AAC3D,MAAM,uBAAuB;AAC7B,MAAM,oBAAoB,IAAI,aAAa;CAAC;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;AAAC,CAAC;AAEtE,MAAM,mBAAmB,iBAAiBA,sBAAoB;CAAE,aAAa;CAAe,iBAAiB;AAAkB,CAAC;;;;;;;;;AAgBhI,IAAa,0BAAb,cAA6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B;IACzB,WAAW,GAAG,aAAa,MAAM;IACjC,WAAW,QAAQ,OAAO,MAAM;IAChC,OAAO,WAAW;GACpB;EACF;CACF;CAEA,AAAQ,kBAAkB,YAAoE;EAC5F,IAAI,iBAAiB;EAErB,OAAO;GACL,OAAO,QAAc;IACnB,MAAM,KAAK,WAAW;IAEtB,GAAG,gBAAgB,WAAW,SAAS;IAEvC,IAAI,mBAAmB,IAAI,SAAS;KAClC,IAAI,aAAwC;KAE5C,KAAK,MAAM,aAAa,IAAI,YAAY;MACtC,IAAI,eAAe,UAAU,QAAQ;OACnC,UAAU,OAAO,KAAK;OACtB,aAAa,UAAU;MACzB;MAEA,IAAI,UAAU,SACZ,GAAG,qBAAqB,UAAU,UAAU,UAAU,MAAM,UAAU,MAAM,UAAU,QAAQ,UAAU,KAAK;WAE7G,GAAG,oBAAoB,UAAU,UAAU,UAAU,MAAM,UAAU,MAAM,UAAU,YAAY,UAAU,QAAQ,UAAU,KAAK;MAGpI,GAAG,wBAAwB,UAAU,QAAQ;MAC7C,GAAG,oBAAoB,UAAU,UAAU,UAAU,OAAO;KAC9D;KAEA,iBAAiB,IAAI;IACvB;GACF;GACA,cAAoB;IAClB,WAAW,GAAG,gBAAgB,IAAI;GACpC;GACA,OAAO,MAAM,MAAM,OAAO,SAAe;IACvC,WAAW,GAAG,WAAW,MAAM,OAAO,IAAI;GAC5C;GACA,gBAAgB,MAAM,OAAO,OAAO,eAAe,SAAe;IAChE,WAAW,GAAG,oBAAoB,MAAM,OAAO,OAAO,aAAa;GACrE;GACA,UAAU,QAAc;IACtB,WAAW,GAAG,kBAAkB,WAAW,SAAS;IACpD,IAAI,WAAW;GACjB;EACF;CACF;AACF"}
1
+ {"version":3,"file":"WebGl2TileChunkRenderer.js","names":["tileVertexTemplate","tileFragmentSource"],"sources":["../../../src/webgl2/WebGl2TileChunkRenderer.ts"],"sourcesContent":["import type {\n RenderTexture,\n Texture,\n View,\n WebGl2Backend,\n WebGl2RenderBufferRuntime,\n WebGl2RetainedBatchPayload,\n WebGl2RetainedBatchReplayer,\n WebGl2RetainedNodeIndexRange,\n WebGl2VertexArrayObjectRuntime,\n} from '@codexo/exojs/renderer-sdk';\nimport {\n AbstractWebGl2Renderer,\n BlendModes,\n BufferTypes,\n BufferUsage,\n colorShaderSourcesGlsl,\n createWebGl2ShaderProgram,\n fillShaderSource,\n packedGroupChanged,\n RenderingPrimitives,\n spliceGlslPrologue,\n uploadBufferRange,\n uploadBufferStore,\n WebGl2RenderBuffer,\n WebGl2Shader,\n WebGl2VertexArrayObject,\n} from '@codexo/exojs/renderer-sdk';\n\nimport type { TileQuad } from '../chunkGeometry';\nimport type { TileChunkNode } from '../TileChunkNode';\nimport { TILE_DIAGONAL_BIT, TILE_ROW_MASK } from '../tileWord';\nimport tileFragmentSource from './shaders/tile-chunk.frag';\nimport tileVertexTemplate from './shaders/tile-chunk.vert';\n\n// One instance = one tile quad. Layout matches the engine's instanced-quad\n// convention (NineSlice/Repeating): float32x4 local rect, unorm16x4 UV bounds,\n// unorm8x4 tint, uint32 tile word (transform row + diagonal bit).\nconst instanceStrideBytes = 32;\nconst wordsPerInstance = instanceStrideBytes / Uint32Array.BYTES_PER_ELEMENT;\nconst transformTextureUnit = 1;\nconst identityGroupMat3 = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]);\n\nconst tileVertexSource = spliceGlslPrologue(\n fillShaderSource(tileVertexTemplate, { tileRowMask: TILE_ROW_MASK, tileDiagonalBit: TILE_DIAGONAL_BIT }),\n colorShaderSourcesGlsl,\n);\n\ninterface TileRendererConnection {\n readonly gl: WebGL2RenderingContext;\n readonly buffers: Map<WebGl2RenderBuffer, { handle: WebGLBuffer; dataByteLength: number }>;\n readonly vaoHandle: WebGLVertexArrayObject;\n}\n\n/**\n * Instanced WebGL2 renderer for {@link TileChunkNode}. Each tile is one\n * instanced quad; tiles are batched by `(shader, tileset texture)` and one\n * `drawArraysInstanced` is issued per batch. Per-chunk transforms ride on the\n * shared transform buffer (one row per chunk node), so the chunk geometry is\n * orientation-neutral and never re-uploaded for a camera pan.\n * @internal\n */\nexport class WebGl2TileChunkRenderer extends AbstractWebGl2Renderer<TileChunkNode> implements WebGl2RetainedBatchReplayer {\n /**\n * Retained-batch capability opt-in: a tile chunk's per-flush\n * instanced batches (fixed 32-byte layout, tile word at word 7) can be\n * recorded into a group's instruction set and replayed from group-owned\n * resources. Pixel-snapped draws are excluded by the collect-time\n * recordability predicate (and belt-and-braces poisoning in {@link render});\n * tile chunks have no custom-material path to exclude.\n * @internal\n */\n public readonly supportsRetainedBatches = true;\n\n private readonly _shader: WebGl2Shader;\n private readonly _batchSize: number;\n private readonly _instanceData: ArrayBuffer;\n private readonly _instanceFloat32: Float32Array;\n private readonly _instanceUint32: Uint32Array;\n\n private readonly _transformUnitScratch: Int32Array = new Int32Array([transformTextureUnit]);\n // Pinned unit index for the single tileset texture sampler (unit 0), reused\n // by the live flush and retained replay so both stay allocation-free.\n private readonly _baseTextureUnitScratch: Int32Array = new Int32Array([0]);\n // Reused single-slot texture list handed to the backend at record time; a\n // tile chunk batch always binds exactly one tileset texture (slot 0).\n private readonly _recordTextures: Array<Texture | RenderTexture | null> = [null];\n\n private _quadIndex = 0;\n private _maxNodeIndex = 0;\n // Chunk nodes booked against the PENDING batch, and whether the chunk being\n // rendered right now has already been booked. One chunk emits one tile\n // instance per tile, so the recorded batch's `submittedNodes` contribution is\n // this count and not `_quadIndex`. A chunk whose pages/runs span several\n // batches is booked once, against the batch its first run lands in.\n private _batchNodeCount = 0;\n private _nodeBooked = false;\n // Blend mode and tileset texture of the batch currently accumulating, used to\n // detect a batch break. Neither is a mirror of backend state: `flush()`\n // establishes both at the draw (see {@link _resetBatchState}).\n private _currentBlendMode: BlendModes | null = null;\n private _currentTexture: Texture | null = null;\n private _currentView: View | null = null;\n private _currentViewId = -1;\n private _hasWrittenGroup = false;\n private readonly _writtenGroupData = new Float32Array(9);\n\n private _instanceBuffer: WebGl2RenderBuffer | null = null;\n private _vao: WebGl2VertexArrayObject | null = null;\n private _connection: TileRendererConnection | null = null;\n\n public constructor(batchSize: number) {\n super();\n\n this._batchSize = batchSize;\n this._shader = new WebGl2Shader(tileVertexSource, tileFragmentSource);\n this._instanceData = new ArrayBuffer(batchSize * instanceStrideBytes);\n this._instanceFloat32 = new Float32Array(this._instanceData);\n this._instanceUint32 = new Uint32Array(this._instanceData);\n }\n\n public render(node: TileChunkNode): void {\n const pages = node.pages;\n\n this._nodeBooked = false;\n\n if (pages.length === 0) {\n return;\n }\n\n const backend = this.getBackend();\n\n const blendMode = node.blendMode;\n const tintRgba = node.tint.toRgba8();\n\n const command = backend.activeDrawCommand;\n const nodeIndex = command !== null ? command.nodeIndex : backend.pushTransform(node);\n\n for (const page of pages) {\n this._renderPage(page.texture, page.quads, blendMode, tintRgba, nodeIndex);\n }\n }\n\n private _renderPage(texture: Texture, quads: readonly TileQuad[], blendMode: BlendModes, tintRgba: number, nodeIndex: number): void {\n if (quads.length === 0) {\n return;\n }\n\n const textureChanged = this._currentTexture !== null && texture !== this._currentTexture;\n const blendModeChanged = this._currentBlendMode !== null && blendMode !== this._currentBlendMode;\n\n if (this._quadIndex > 0 && (blendModeChanged || textureChanged || this._quadIndex + quads.length > this._batchSize)) {\n this.flush();\n }\n\n this._currentBlendMode = blendMode;\n this._currentTexture = texture;\n\n const flipY = texture.flipY;\n\n // A chunk page may hold more tiles than the fixed batch buffer; write in\n // batch-sized runs, flushing (and re-establishing state) between runs.\n let offset = 0;\n\n while (offset < quads.length) {\n const remaining = quads.length - offset;\n const runSize = Math.min(remaining, this._batchSize);\n\n this._writeRun(quads, offset, runSize, flipY, tintRgba, nodeIndex);\n\n offset += runSize;\n\n if (offset < quads.length) {\n this.flush();\n this._currentBlendMode = blendMode;\n this._currentTexture = texture;\n }\n }\n }\n\n private _writeRun(quads: readonly TileQuad[], offset: number, count: number, flipY: boolean, tintRgba: number, nodeIndex: number): void {\n const f32 = this._instanceFloat32;\n const u32 = this._instanceUint32;\n const baseWord = nodeIndex & TILE_ROW_MASK;\n\n // Booked here rather than in render(): any flush the page/run loops trigger\n // has already happened, so the chunk lands on the batch that actually holds\n // its first tile.\n if (!this._nodeBooked) {\n this._nodeBooked = true;\n this._batchNodeCount++;\n }\n\n for (let i = 0; i < count; i++) {\n const q = quads[offset + i]!;\n const idx = this._quadIndex * wordsPerInstance;\n\n f32[idx + 0] = q.x0;\n f32[idx + 1] = q.y0;\n f32[idx + 2] = q.x1;\n f32[idx + 3] = q.y1;\n\n // Bake flipX/flipY into the UV corner ordering; the diagonal axis swap is\n // resolved in the shader. Texture flipY (uploaded-flipped atlases) is an\n // additional vertical swap that composes with the tile flipY.\n const flipX = (q.orient & 1) !== 0;\n const tileFlipY = (q.orient & 2) !== 0;\n const diagonal = (q.orient & 4) !== 0;\n\n const uA = flipX ? q.u1 : q.u0;\n const uB = flipX ? q.u0 : q.u1;\n let vA = tileFlipY ? q.v1 : q.v0;\n let vB = tileFlipY ? q.v0 : q.v1;\n\n if (flipY) {\n const swap = vA;\n vA = vB;\n vB = swap;\n }\n\n const uMin = (uA * 0xffff) & 0xffff;\n const vMin = (vA * 0xffff) & 0xffff;\n const uMax = (uB * 0xffff) & 0xffff;\n const vMax = (vB * 0xffff) & 0xffff;\n\n u32[idx + 4] = uMin | (vMin << 16);\n u32[idx + 5] = uMax | (vMax << 16);\n u32[idx + 6] = tintRgba;\n u32[idx + 7] = (diagonal ? baseWord | TILE_DIAGONAL_BIT : baseWord) >>> 0;\n\n this._quadIndex++;\n }\n\n if (nodeIndex > this._maxNodeIndex) {\n this._maxNodeIndex = nodeIndex;\n }\n }\n\n public flush(): void {\n const backend = this.getBackendOrNull();\n const instanceBuffer = this._instanceBuffer;\n const vao = this._vao;\n\n if (this._quadIndex === 0 || backend === null || instanceBuffer === null || vao === null) {\n this._resetBatchState();\n return;\n }\n\n this._stageViewUniforms(backend);\n\n // Blend state and texture unit 0 are global and shared with every other\n // renderer - a sprite drawn between two tile layers binds its own texture\n // to the same unit - so this batch establishes both at its own draw. The\n // backend collapses a redundant call.\n if (this._currentTexture !== null) {\n backend.bindTexture(this._currentTexture, 0);\n this._shader.getUniform('u_texture').setValue(this._baseTextureUnitScratch);\n }\n\n backend.bindTransformBufferTexture(transformTextureUnit, this._maxNodeIndex + 1);\n this._shader.getUniform('u_transforms').setValue(this._transformUnitScratch);\n\n this._shader.sync();\n backend.bindVertexArrayObject(vao);\n instanceBuffer.upload(this._instanceFloat32, 0, this._quadIndex * wordsPerInstance);\n backend.setBlendMode(this._currentBlendMode ?? BlendModes.Normal);\n vao.drawInstanced(4, 0, this._quadIndex, RenderingPrimitives.TriangleStrip);\n backend.stats.batches++;\n backend.stats.drawCalls++;\n\n // Retained recording: while a capture window is open, hand the\n // exact packed instance words of this flush to the backend - byte-\n // identical to what just drew. A batch always binds a single tileset\n // texture (slot 0); a pixel-snapped node already poisoned the capture in\n // render().\n if (backend._isRetainedCapturing && this._currentTexture !== null) {\n this._recordTextures[0] = this._currentTexture;\n backend.recordRetainedBatch(\n this,\n this._instanceUint32.subarray(0, this._quadIndex * wordsPerInstance),\n this._quadIndex,\n this._currentBlendMode ?? BlendModes.Normal,\n this._recordTextures,\n 1,\n null,\n null,\n this._batchNodeCount,\n );\n }\n\n this._resetBatchState();\n }\n\n /**\n * Scope the batch memos to one batch: they describe what is accumulating, not\n * what GL holds, so a memo that outlived its flush would let the next batch\n * skip establishing state another renderer has since changed.\n */\n private _resetBatchState(): void {\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._currentBlendMode = null;\n this._currentTexture = null;\n }\n\n /**\n * Stage `u_projection` (live view) and `u_group` (live composed group\n * matrix) on the shader, guarded by cached view/group stamps. Shared by the\n * live flush path and retained-batch replay - replay resolves exactly the\n * same live state a slow-path flush would.\n */\n private _stageViewUniforms(backend: WebGl2Backend): void {\n const view = backend.view;\n\n if (this._currentView !== view || this._currentViewId !== view.updateId) {\n this._currentView = view;\n this._currentViewId = view.updateId;\n this._shader.getUniform('u_projection').setValue(view.getTransform().toArray(false));\n }\n\n const groupTransform = backend.renderGroupTransform;\n const groupData = groupTransform !== null ? groupTransform.toArray(false) : identityGroupMat3;\n\n if (!this._hasWrittenGroup || packedGroupChanged(groupData, this._writtenGroupData, 0)) {\n this._shader.getUniform('u_group').setValue(groupData);\n this._writtenGroupData.set(groupData);\n this._hasWrittenGroup = true;\n }\n\n backend.stageViewportUniform(this._shader);\n }\n\n // ── Retained-batch record/replay ──────────────────────────────────────────\n // The bundle stores raw instance bytes; this renderer owns the 32-byte\n // layout (tile word at word 7: transform row in bits 0..28, diagonal flip in\n // bit 29), so the layout-aware finalize steps (node-index scan/rebase, VAO\n // attribute wiring) and the replay dispatch live here - mirroring\n // WebGl2NineSliceSpriteRenderer's seam.\n\n /** @internal See {@link WebGl2RetainedBatchReplayer.scanRetainedNodeIndexRange}. */\n public scanRetainedNodeIndexRange(payload: WebGl2RetainedBatchPayload, range: WebGl2RetainedNodeIndexRange): void {\n const words = payload.bundle.instanceWords;\n const start = payload.byteOffset / Uint32Array.BYTES_PER_ELEMENT;\n\n for (let i = 0; i < payload.instanceCount; i++) {\n // In-bounds: the payload's word range was appended to the bundle store.\n // The tile word is the last word of the 32-byte (8-word) instance\n // layout; only the low 29 bits address the transform buffer row - the\n // diagonal-flip flag (bit 29) is orientation, not a row index.\n const row = words[start + i * wordsPerInstance + 7]! & TILE_ROW_MASK;\n\n if (row < range.min) {\n range.min = row;\n }\n\n if (row > range.max) {\n range.max = row;\n }\n }\n }\n\n /** @internal See {@link WebGl2RetainedBatchReplayer.rebaseRetainedNodeIndices} (group-local indices). */\n public rebaseRetainedNodeIndices(payload: WebGl2RetainedBatchPayload, base: number): void {\n const words = payload.bundle.instanceWords;\n const start = payload.byteOffset / Uint32Array.BYTES_PER_ELEMENT;\n\n for (let i = 0; i < payload.instanceCount; i++) {\n const index = start + i * wordsPerInstance + 7;\n // In-bounds: see the scan above. Rebase ONLY the row field; the\n // diagonal-flip bit must survive untouched or tile orientation corrupts.\n const word = words[index]!;\n const diagonal = word & TILE_DIAGONAL_BIT;\n const row = word & TILE_ROW_MASK;\n\n words[index] = (diagonal | ((row - base) & TILE_ROW_MASK)) >>> 0;\n }\n }\n\n /**\n * Point the batch VAO's per-instance attributes at the bundle's persistent\n * instance buffer, based at the batch's byte offset (WebGL2 has no\n * baseInstance, hence one small VAO per recorded batch). Same attribute\n * set/locations as the live VAO in {@link onConnect}.\n * @internal\n */\n public configureRetainedVao(payload: WebGl2RetainedBatchPayload): void {\n const gl = this.getBackend().context;\n const buffer = payload.bundle.instanceBuffer;\n const vao = payload.vao;\n\n if (buffer === null || vao === null) {\n throw new Error('WebGl2TileChunkRenderer: retained batch VAO configuration requires an uploaded bundle.');\n }\n\n const base = payload.byteOffset;\n\n vao\n .addAttribute(buffer, this._shader.getAttribute('a_quadBounds'), gl.FLOAT, false, instanceStrideBytes, base + 0, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_uvBounds'), gl.UNSIGNED_SHORT, true, instanceStrideBytes, base + 16, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_color'), gl.UNSIGNED_BYTE, true, instanceStrideBytes, base + 24, false, 1)\n .addAttribute(buffer, this._shader.getAttribute('a_tileWord'), gl.UNSIGNED_INT, false, instanceStrideBytes, base + 28, true, 1);\n }\n\n /**\n * Replay one recorded batch: all STATE is resolved live - blend mode via\n * the backend's dedup, `u_projection`/`u_group` from the live view + live\n * composed group matrix (the camera-pan / group-move win), the single\n * tileset texture bound to unit 0 by recorded slot order - and only the\n * DATA is cached: the instance bytes in the bundle buffer (bound through\n * the per-batch VAO) and the group-owned transform texture on the shared\n * transform unit. The backend hook flushed any pending live batch before\n * dispatching here and bumps the stats from the instruction descriptor.\n * @internal\n */\n public replayRetainedBatch(payload: WebGl2RetainedBatchPayload): boolean {\n const backend = this.getBackendOrNull();\n const vao = payload.vao;\n const transformTexture = payload.bundle.transformTexture;\n\n if (backend === null || vao === null || transformTexture === null) {\n // Defensive: a bundle in this state never validates (generation), so a\n // spliced replay cannot reach here; skip rather than crash mid-frame.\n return false;\n }\n\n backend.setBlendMode(payload.blendMode);\n this._stageViewUniforms(backend);\n\n const textures = payload.textures;\n\n for (let i = 0; i < textures.length; i++) {\n // In-bounds: i < textures.length.\n backend.bindTexture(textures[i]!, i);\n }\n\n this._shader.getUniform('u_texture').setValue(this._baseTextureUnitScratch);\n\n // The group-owned transform store replaces the shared frame buffer on the\n // SAME unit/sampler - zero GLSL changes. The next live flush re-binds the\n // shared texture through bindTransformBufferTexture.\n backend.bindTexture(transformTexture, transformTextureUnit);\n this._shader.getUniform('u_transforms').setValue(this._transformUnitScratch);\n\n this._shader.sync();\n backend.bindVertexArrayObject(vao);\n vao.drawInstanced(4, 0, payload.instanceCount, RenderingPrimitives.TriangleStrip);\n\n return true;\n }\n\n protected onConnect(backend: WebGl2Backend): void {\n const gl = backend.context;\n\n this._shader.connect(createWebGl2ShaderProgram(gl));\n this._connection = this._createConnection(gl);\n this._instanceBuffer = new WebGl2RenderBuffer(BufferTypes.ArrayBuffer, this._instanceData, BufferUsage.DynamicDraw).connect(\n this._createBufferRuntime(this._connection),\n );\n this._shader.sync();\n\n this._vao = new WebGl2VertexArrayObject(RenderingPrimitives.TriangleStrip)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_quadBounds'), gl.FLOAT, false, instanceStrideBytes, 0, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_uvBounds'), gl.UNSIGNED_SHORT, true, instanceStrideBytes, 16, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_color'), gl.UNSIGNED_BYTE, true, instanceStrideBytes, 24, false, 1)\n .addAttribute(this._instanceBuffer, this._shader.getAttribute('a_tileWord'), gl.UNSIGNED_INT, false, instanceStrideBytes, 28, true, 1)\n .connect(this._createVaoRuntime(this._connection));\n }\n\n protected onDisconnect(): void {\n this._shader.destroy();\n this._instanceBuffer?.destroy();\n this._instanceBuffer = null;\n this._vao?.destroy();\n this._vao = null;\n this._connection = null;\n this._currentBlendMode = null;\n this._currentTexture = null;\n this._currentView = null;\n this._currentViewId = -1;\n this._hasWrittenGroup = false;\n this._quadIndex = 0;\n this._maxNodeIndex = 0;\n this._batchNodeCount = 0;\n this._nodeBooked = false;\n }\n\n public destroy(): void {\n this.disconnect();\n this._shader.destroy();\n }\n\n private _createConnection(gl: WebGL2RenderingContext): TileRendererConnection {\n const vaoHandle = gl.createVertexArray();\n\n if (vaoHandle === null) {\n throw new Error('WebGl2TileChunkRenderer: could not create vertex array object.');\n }\n\n return { gl, buffers: new Map(), vaoHandle };\n }\n\n private _createBufferRuntime(connection: TileRendererConnection): WebGl2RenderBufferRuntime {\n const handle = connection.gl.createBuffer();\n\n if (handle === null) {\n throw new Error('WebGl2TileChunkRenderer: could not create render buffer.');\n }\n\n return {\n bind: (buffer): void => {\n connection.gl.bindBuffer(buffer.type, handle);\n },\n upload: (buffer, offset): void => {\n const gl = connection.gl;\n const state = connection.buffers.get(buffer);\n\n gl.bindBuffer(buffer.type, handle);\n\n if (state && state.dataByteLength >= buffer.uploadByteLength) {\n uploadBufferRange(gl, buffer, offset);\n state.dataByteLength = buffer.uploadByteLength;\n } else {\n uploadBufferStore(gl, buffer);\n connection.buffers.set(buffer, { handle, dataByteLength: buffer.uploadByteLength });\n }\n },\n destroy: (buffer): void => {\n connection.gl.deleteBuffer(handle);\n connection.buffers.delete(buffer);\n buffer.disconnect();\n },\n };\n }\n\n private _createVaoRuntime(connection: TileRendererConnection): WebGl2VertexArrayObjectRuntime {\n let appliedVersion = -1;\n\n return {\n bind: (vao): void => {\n const gl = connection.gl;\n\n gl.bindVertexArray(connection.vaoHandle);\n\n if (appliedVersion !== vao.version) {\n let lastBuffer: WebGl2RenderBuffer | null = null;\n\n for (const attribute of vao.attributes) {\n if (lastBuffer !== attribute.buffer) {\n attribute.buffer.bind();\n lastBuffer = attribute.buffer;\n }\n\n if (attribute.integer) {\n gl.vertexAttribIPointer(attribute.location, attribute.size, attribute.type, attribute.stride, attribute.start);\n } else {\n gl.vertexAttribPointer(attribute.location, attribute.size, attribute.type, attribute.normalized, attribute.stride, attribute.start);\n }\n\n gl.enableVertexAttribArray(attribute.location);\n gl.vertexAttribDivisor(attribute.location, attribute.divisor);\n }\n\n appliedVersion = vao.version;\n }\n },\n unbind: (): void => {\n connection.gl.bindVertexArray(null);\n },\n draw: (_vao, size, start, type): void => {\n connection.gl.drawArrays(type, start, size);\n },\n drawInstanced: (_vao, count, start, instanceCount, type): void => {\n connection.gl.drawArraysInstanced(type, start, count, instanceCount);\n },\n destroy: (vao): void => {\n connection.gl.deleteVertexArray(connection.vaoHandle);\n vao.disconnect();\n },\n };\n }\n}\n"],"mappings":";;;;;;AAsCA,MAAM,sBAAsB;AAC5B,MAAM,mBAAmB,sBAAsB,YAAY;AAC3D,MAAM,uBAAuB;AAC7B,MAAM,oBAAoB,IAAI,aAAa;CAAC;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;CAAG;AAAC,CAAC;AAEtE,MAAM,mBAAmB,mBACvB,iBAAiBA,sBAAoB;CAAE,aAAa;CAAe,iBAAiB;AAAkB,CAAC,GACvG,sBACF;;;;;;;;;AAgBA,IAAa,0BAAb,cAA6C,uBAA6E;;;;;;;;;;CAUxH,AAAgB,0BAA0B;CAE1C,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,AAAiB,wBAAoC,IAAI,WAAW,CAAC,oBAAoB,CAAC;CAG1F,AAAiB,0BAAsC,IAAI,WAAW,CAAC,CAAC,CAAC;CAGzE,AAAiB,kBAAyD,CAAC,IAAI;CAE/E,AAAQ,aAAa;CACrB,AAAQ,gBAAgB;CAMxB,AAAQ,kBAAkB;CAC1B,AAAQ,cAAc;CAItB,AAAQ,oBAAuC;CAC/C,AAAQ,kBAAkC;CAC1C,AAAQ,eAA4B;CACpC,AAAQ,iBAAiB;CACzB,AAAQ,mBAAmB;CAC3B,AAAiB,oCA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AAU,UAAU,MAAM,UAAU,MAAM,UAAU,QAAQ,UAAU,KAAK;WAE7G,GAAG,oBAAoB,UAAU,UAAU,UAAU,MAAM,UAAU,MAAM,UAAU,YAAY,UAAU,QAAQ,UAAU,KAAK;MAGpI,GAAG,wBAAwB,UAAU,QAAQ;MAC7C,GAAG,oBAAoB,UAAU,UAAU,UAAU,OAAO;KAC9D;KAEA,iBAAiB,IAAI;IACvB;GACF;GACA,cAAoB;IAClB,WAAW,GAAG,gBAAgB,IAAI;GACpC;GACA,OAAO,MAAM,MAAM,OAAO,SAAe;IACvC,WAAW,GAAG,WAAW,MAAM,OAAO,IAAI;GAC5C;GACA,gBAAgB,MAAM,OAAO,OAAO,eAAe,SAAe;IAChE,WAAW,GAAG,oBAAoB,MAAM,OAAO,OAAO,aAAa;GACrE;GACA,UAAU,QAAc;IACtB,WAAW,GAAG,kBAAkB,WAAW,SAAS;IACpD,IAAI,WAAW;GACjB;EACF;CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  //#region src/webgl2/shaders/tile-chunk.vert
2
- var tile_chunk_default = "#version 300 es\nprecision highp float;\nprecision highp int;\nlayout(location = 0) in vec4 a_quadBounds;\nlayout(location = 1) in vec4 a_uvBounds;\nlayout(location = 2) in vec4 a_color;\nlayout(location = 3) in uint a_tileWord;\nuniform mat3 u_projection;\nuniform mat3 u_group;\nuniform vec4 u_viewport;\nuniform sampler2D u_transforms;\n// #exo-include transform-texture\nout vec2 v_texcoord;\nout vec4 v_color;\nvoid main(void) {\nint vid = gl_VertexID;\nint cornerX = vid & 1;\nint cornerY = (vid >> 1) & 1;\nfloat localX = (cornerX == 0) ? a_quadBounds.x : a_quadBounds.z;\nfloat localY = (cornerY == 0) ? a_quadBounds.y : a_quadBounds.w;\nint row = int(a_tileWord & {{tileRowMask}}u);\nbool diagonal = (a_tileWord & {{tileDiagonalBit}}u) != 0u;\nvec4 m0 = texelFetch(u_transforms, exoTransformTexel(row, 0), 0);\nvec4 m1 = texelFetch(u_transforms, exoTransformTexel(row, 1), 0);\nfloat worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\nfloat worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\nvec2 clip = (u_projection * u_group * vec3(worldX, worldY, 1.0)).xy;\nif (m1.z != 0.0) {\nvec2 originClip = (u_projection * u_group * vec3(m1.x, m1.y, 1.0)).xy;\nvec2 originDevice = u_viewport.xy + (originClip * 0.5 + 0.5) * u_viewport.zw;\nclip += (floor(originDevice + 0.5) - originDevice) * 2.0 / max(u_viewport.zw, vec2(1.0));\n}\ngl_Position = vec4(clip, 0.0, 1.0);\nint su = cornerX;\nint sv = cornerY;\nif (diagonal) { int t = su; su = sv; sv = t; }\nfloat u = (su == 0) ? a_uvBounds.x : a_uvBounds.z;\nfloat v = (sv == 0) ? a_uvBounds.y : a_uvBounds.w;\nv_texcoord = vec2(u, v);\nv_color = vec4(a_color.rgb * a_color.a, a_color.a);\n}";
2
+ var tile_chunk_default = "#version 300 es\nprecision highp float;\nprecision highp int;\nlayout(location = 0) in vec4 a_quadBounds;\nlayout(location = 1) in vec4 a_uvBounds;\nlayout(location = 2) in vec4 a_color;\nlayout(location = 3) in uint a_tileWord;\nuniform mat3 u_projection;\nuniform mat3 u_group;\nuniform vec4 u_viewport;\nuniform sampler2D u_transforms;\n// #exo-include transform-texture\nout vec2 v_texcoord;\nout vec4 v_color;\nvoid main(void) {\nint vid = gl_VertexID;\nint cornerX = vid & 1;\nint cornerY = (vid >> 1) & 1;\nfloat localX = (cornerX == 0) ? a_quadBounds.x : a_quadBounds.z;\nfloat localY = (cornerY == 0) ? a_quadBounds.y : a_quadBounds.w;\nint row = int(a_tileWord & {{tileRowMask}}u);\nbool diagonal = (a_tileWord & {{tileDiagonalBit}}u) != 0u;\nvec4 m0 = texelFetch(u_transforms, exoTransformTexel(row, 0), 0);\nvec4 m1 = texelFetch(u_transforms, exoTransformTexel(row, 1), 0);\nfloat worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\nfloat worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\nvec2 clip = (u_projection * u_group * vec3(worldX, worldY, 1.0)).xy;\nif (m1.z != 0.0) {\nvec2 originClip = (u_projection * u_group * vec3(m1.x, m1.y, 1.0)).xy;\nvec2 originDevice = u_viewport.xy + (originClip * 0.5 + 0.5) * u_viewport.zw;\nclip += (floor(originDevice + 0.5) - originDevice) * 2.0 / max(u_viewport.zw, vec2(1.0));\n}\ngl_Position = vec4(clip, 0.0, 1.0);\nint su = cornerX;\nint sv = cornerY;\nif (diagonal) { int t = su; su = sv; sv = t; }\nfloat u = (su == 0) ? a_uvBounds.x : a_uvBounds.z;\nfloat v = (sv == 0) ? a_uvBounds.y : a_uvBounds.w;\nv_texcoord = vec2(u, v);\nhighp vec3 linearTint = srgbToLinear(a_color.rgb);\nv_color = vec4(linearTint * a_color.a, a_color.a);\n}";
3
3
 
4
4
  //#endregion
5
5
  export { tile_chunk_default as default };
@@ -1 +1 @@
1
- {"version":3,"file":"tile-chunk.vert.js","names":[],"sources":["../../../../src/webgl2/shaders/tile-chunk.vert"],"sourcesContent":["export default \"#version 300 es\\nprecision highp float;\\nprecision highp int;\\nlayout(location = 0) in vec4 a_quadBounds;\\nlayout(location = 1) in vec4 a_uvBounds;\\nlayout(location = 2) in vec4 a_color;\\nlayout(location = 3) in uint a_tileWord;\\nuniform mat3 u_projection;\\nuniform mat3 u_group;\\nuniform vec4 u_viewport;\\nuniform sampler2D u_transforms;\\n// #exo-include transform-texture\\nout vec2 v_texcoord;\\nout vec4 v_color;\\nvoid main(void) {\\nint vid = gl_VertexID;\\nint cornerX = vid & 1;\\nint cornerY = (vid >> 1) & 1;\\nfloat localX = (cornerX == 0) ? a_quadBounds.x : a_quadBounds.z;\\nfloat localY = (cornerY == 0) ? a_quadBounds.y : a_quadBounds.w;\\nint row = int(a_tileWord & {{tileRowMask}}u);\\nbool diagonal = (a_tileWord & {{tileDiagonalBit}}u) != 0u;\\nvec4 m0 = texelFetch(u_transforms, exoTransformTexel(row, 0), 0);\\nvec4 m1 = texelFetch(u_transforms, exoTransformTexel(row, 1), 0);\\nfloat worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\\nfloat worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\\nvec2 clip = (u_projection * u_group * vec3(worldX, worldY, 1.0)).xy;\\nif (m1.z != 0.0) {\\nvec2 originClip = (u_projection * u_group * vec3(m1.x, m1.y, 1.0)).xy;\\nvec2 originDevice = u_viewport.xy + (originClip * 0.5 + 0.5) * u_viewport.zw;\\nclip += (floor(originDevice + 0.5) - originDevice) * 2.0 / max(u_viewport.zw, vec2(1.0));\\n}\\ngl_Position = vec4(clip, 0.0, 1.0);\\nint su = cornerX;\\nint sv = cornerY;\\nif (diagonal) { int t = su; su = sv; sv = t; }\\nfloat u = (su == 0) ? a_uvBounds.x : a_uvBounds.z;\\nfloat v = (sv == 0) ? a_uvBounds.y : a_uvBounds.w;\\nv_texcoord = vec2(u, v);\\nv_color = vec4(a_color.rgb * a_color.a, a_color.a);\\n}\";"],"mappings":";AAAA,yBAAe"}
1
+ {"version":3,"file":"tile-chunk.vert.js","names":[],"sources":["../../../../src/webgl2/shaders/tile-chunk.vert"],"sourcesContent":["export default \"#version 300 es\\nprecision highp float;\\nprecision highp int;\\nlayout(location = 0) in vec4 a_quadBounds;\\nlayout(location = 1) in vec4 a_uvBounds;\\nlayout(location = 2) in vec4 a_color;\\nlayout(location = 3) in uint a_tileWord;\\nuniform mat3 u_projection;\\nuniform mat3 u_group;\\nuniform vec4 u_viewport;\\nuniform sampler2D u_transforms;\\n// #exo-include transform-texture\\nout vec2 v_texcoord;\\nout vec4 v_color;\\nvoid main(void) {\\nint vid = gl_VertexID;\\nint cornerX = vid & 1;\\nint cornerY = (vid >> 1) & 1;\\nfloat localX = (cornerX == 0) ? a_quadBounds.x : a_quadBounds.z;\\nfloat localY = (cornerY == 0) ? a_quadBounds.y : a_quadBounds.w;\\nint row = int(a_tileWord & {{tileRowMask}}u);\\nbool diagonal = (a_tileWord & {{tileDiagonalBit}}u) != 0u;\\nvec4 m0 = texelFetch(u_transforms, exoTransformTexel(row, 0), 0);\\nvec4 m1 = texelFetch(u_transforms, exoTransformTexel(row, 1), 0);\\nfloat worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\\nfloat worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\\nvec2 clip = (u_projection * u_group * vec3(worldX, worldY, 1.0)).xy;\\nif (m1.z != 0.0) {\\nvec2 originClip = (u_projection * u_group * vec3(m1.x, m1.y, 1.0)).xy;\\nvec2 originDevice = u_viewport.xy + (originClip * 0.5 + 0.5) * u_viewport.zw;\\nclip += (floor(originDevice + 0.5) - originDevice) * 2.0 / max(u_viewport.zw, vec2(1.0));\\n}\\ngl_Position = vec4(clip, 0.0, 1.0);\\nint su = cornerX;\\nint sv = cornerY;\\nif (diagonal) { int t = su; su = sv; sv = t; }\\nfloat u = (su == 0) ? a_uvBounds.x : a_uvBounds.z;\\nfloat v = (sv == 0) ? a_uvBounds.y : a_uvBounds.w;\\nv_texcoord = vec2(u, v);\\nhighp vec3 linearTint = srgbToLinear(a_color.rgb);\\nv_color = vec4(linearTint * a_color.a, a_color.a);\\n}\";"],"mappings":";AAAA,yBAAe"}