@ignifx/2d 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -64,7 +64,15 @@ const TwoDErrorCode = {
64
64
  /** A second `twoD()` extension was registered on one app. */
65
65
  duplicateExtension: "IGX-1112",
66
66
  /** A `SpriteLayerEffect` declared the `custom` kind without a WGSL fragment body. */
67
- missingShaderSource: "IGX-1113"
67
+ missingShaderSource: "IGX-1113",
68
+ /** `app.twoD.createSpriteBatch` was given a capacity that is not a positive whole number. */
69
+ invalidBatchCapacity: "IGX-1114",
70
+ /** A sprite batch was handed a slot index, or a `count`, outside `0 .. capacity`. */
71
+ batchIndexOutOfRange: "IGX-1115",
72
+ /** A sprite batch was written to, or resized, after `dispose()`. */
73
+ batchDisposed: "IGX-1116",
74
+ /** `app.twoD.createSpriteBatch` was given an atlas handle that has not finished loading. */
75
+ batchAtlasNotLoaded: "IGX-1117"
68
76
  };
69
77
  /**
70
78
  * The one-line message template of every code, as `ExtensionContext.registerErrorCodes` wants it.
@@ -84,7 +92,11 @@ const TWO_D_ERROR_MESSAGES = Object.freeze({
84
92
  "IGX-1110": "A tile object factory for {type} is already registered.",
85
93
  "IGX-1111": "Cell {x},{y} is outside layer {layer}.",
86
94
  "IGX-1112": "The twoD() extension is already registered on this app.",
87
- "IGX-1113": "A custom SpriteLayerEffect needs a WGSL fragment body in its shader field."
95
+ "IGX-1113": "A custom SpriteLayerEffect needs a WGSL fragment body in its shader field.",
96
+ "IGX-1114": "A sprite batch capacity must be a whole number of at least 1; got {capacity}.",
97
+ "IGX-1115": "{index} is outside the sprite batch's 0..{capacity} slots.",
98
+ "IGX-1116": "This sprite batch was disposed; create another one.",
99
+ "IGX-1117": "The atlas handle for a sprite batch is {state}, not loaded."
88
100
  });
89
101
  /**
90
102
  * Builds an `IgnifxError` carrying one of this package's codes.
@@ -597,6 +609,29 @@ function updateSprite(handle, scratch) {
597
609
  updateSprite2D(handle, scratch.props);
598
610
  }
599
611
  /**
612
+ * Builds the reusable visibility patch.
613
+ *
614
+ * @returns A fresh record; each owner keeps exactly one.
615
+ *
616
+ * @internal
617
+ */
618
+ function createSpriteVisibilityScratch() {
619
+ return { patch: { visible: true } };
620
+ }
621
+ /**
622
+ * Shows or hides one sprite, leaving every other field alone.
623
+ *
624
+ * @param handle - The sprite.
625
+ * @param scratch - The reusable visibility patch.
626
+ * @param visible - Whether the sprite draws.
627
+ *
628
+ * @internal
629
+ */
630
+ function updateSpriteVisibility(handle, scratch, visible) {
631
+ scratch.patch.visible = visible;
632
+ updateSprite2D(handle, scratch.patch);
633
+ }
634
+ /**
600
635
  * Removes a sprite, tolerating a handle whose sprite is already gone.
601
636
  *
602
637
  * @remarks
@@ -1696,16 +1731,9 @@ function spriteAnimatorSchema() {
1696
1731
  //#endregion
1697
1732
  //#region src/animation/animation-system.ts
1698
1733
  /**
1699
- * The 2D animation system (`docs/architecture/01-lifecycle-and-time.md` §3, ADR-0003).
1700
- *
1701
- * It runs in `PostUpdate` — after `update`, before `PreRender` — which is where every animation in
1702
- * ignifx advances, so a `lateUpdate` sees the posed frame and the render sync writes it in the same
1703
- * frame it was computed. It advances every `SpriteAnimator` and every animated tile on the same
1704
- * `ctx.dt`, which is `time.deltaTime`, already scaled by `time.timeScale`. Systems keep running
1705
- * while the app is paused and `dt` is **not** zeroed then (only scripts are filtered by
1706
- * `updateWhenPaused`), so the system checks `time.paused` itself: sprite animation does not advance
1707
- * while paused (`01-lifecycle-and-time.md` §7). Phase 6 shipped without this check and the sprites
1708
- * kept animating under a pause menu.
1734
+ * Advance sprite and tile animation in `PostUpdate` so `lateUpdate` sees the current frame.
1735
+ * Systems still run while paused with a nonzero delta, so this system checks `time.paused`
1736
+ * before advancing animation (docs/architecture/01-lifecycle-and-time.md §7).
1709
1737
  */
1710
1738
  /**
1711
1739
  * The `PostUpdate` order the 2D animation system runs at.
@@ -1752,18 +1780,8 @@ var TwoDAnimationSystem = class {
1752
1780
  //#endregion
1753
1781
  //#region src/atlas/importers.ts
1754
1782
  /**
1755
- * The atlas importers: pure functions that turn a third-party packer document — or a plain grid
1756
- * description — into an `ignifx.spriteatlas` document
1757
- * (`docs/architecture/11-2d-toolkit.md` §2.3).
1758
- *
1759
- * Nothing here does I/O. The CLI (`ignifx import atlas`) reads the file, hands the parsed JSON to
1760
- * one of these functions, and writes the returned document out; a game can equally call them at
1761
- * build time from a script. Every frame rectangle stays in **image pixels with a top-left origin**,
1762
- * which is what both TexturePacker and Aseprite emit and what the loader expects.
1763
- *
1764
- * Untrusted input is typed `unknown` and narrowed with the local guards below rather than asserted
1765
- * (coding standards §5.2), so a malformed document fails with `IGX-1109` instead of producing an
1766
- * atlas that only breaks later, at load.
1783
+ * Convert packer JSON or a grid description into an `ignifx.spriteatlas` document without I/O.
1784
+ * Frame rectangles use image pixels with a top-left origin. Invalid input throws `IGX-1109`.
1767
1785
  */
1768
1786
  /** The pivot a frame gets when neither the packer nor the caller names one. */
1769
1787
  const CENTRE_PIVOT$2 = Object.freeze({
@@ -1806,12 +1824,6 @@ function isObject$1(value) {
1806
1824
  function isUnknownArray$3(value) {
1807
1825
  return Array.isArray(value);
1808
1826
  }
1809
- /**
1810
- * Narrows an unknown value to a real number.
1811
- *
1812
- * @param value - The value to test.
1813
- * @returns Whether it is a finite number.
1814
- */
1815
1827
  function isFiniteNumber$1(value) {
1816
1828
  return typeof value === "number" && Number.isFinite(value);
1817
1829
  }
@@ -2322,12 +2334,6 @@ function isObject(value) {
2322
2334
  function isUnknownArray$2(value) {
2323
2335
  return Array.isArray(value);
2324
2336
  }
2325
- /**
2326
- * Narrows an unknown value to a real number.
2327
- *
2328
- * @param value - The value to test.
2329
- * @returns Whether it is a finite number.
2330
- */
2331
2337
  function isFiniteNumber(value) {
2332
2338
  return typeof value === "number" && Number.isFinite(value);
2333
2339
  }
@@ -3374,21 +3380,9 @@ function camera2DSchema() {
3374
3380
  //#endregion
3375
3381
  //#region src/camera/camera-2d-follow.ts
3376
3382
  /**
3377
- * `Camera2DFollow` (`docs/architecture/11-2d-toolkit.md` §2.1): the reference implementation of a
3378
- * smooth, dead-zoned camera follow.
3379
- *
3380
- * It is a `Script`, not part of `Camera2D`, on purpose: following is a *policy*, and a game that
3381
- * wants look-ahead, screen shake, or room-based snapping replaces this script without touching the
3382
- * camera. `Camera2D` holds the fields (`follow`, `followDamping`, `followOffset`, `deadZone`)
3383
- * because a scene file has to be able to author them; this script is what reads them.
3384
- *
3385
- * The move happens in `lateUpdate`, after every `update` has run, so the camera sees the frame's
3386
- * final player position rather than last frame's — the single most common cause of a camera that
3387
- * visibly lags its target by one frame. For a physics-driven target that position is the
3388
- * **display** pose: `@ignifx/physics-2d` writes `lerp(prev, cur, fixedStepAlpha)` at the top of
3389
- * `Update` (`01-lifecycle-and-time.md` §3, since 2026-09-08), so the camera frames the target where
3390
- * the sprite is drawn rather than where the last fixed step left it — which, through a pixel-perfect
3391
- * camera that quantises both independently, used to read as a shaking sprite.
3383
+ * Follow the camera's target in `lateUpdate`, after gameplay and physics interpolation have
3384
+ * written its display pose. Keeping follow behaviour in a script lets games replace it without
3385
+ * changing `Camera2D` (docs/architecture/11-2d-toolkit.md §2.1).
3392
3386
  */
3393
3387
  /**
3394
3388
  * A damped, dead-zoned camera follow.
@@ -3663,20 +3657,8 @@ function parallaxLayerSchema() {
3663
3657
  //#endregion
3664
3658
  //#region src/sprite/sprite-layer-effect.ts
3665
3659
  /**
3666
- * `SpriteLayerEffect` (`docs/architecture/11-2d-toolkit.md` §6): a per-layer custom fragment shader.
3667
- *
3668
- * Lite's 2D path has no lighting model, so effects are what a 2D game reaches for instead: a tint,
3669
- * a dissolve, water, a heat shimmer. A layer created with a `customShader`
3670
- * (`Sprite2DLayerOptions.customShader`, `index.d.ts` 11934) runs a WGSL fragment body with a
3671
- * built-in `fx.time` clock and a `fx.params` vec4 the component writes every frame through
3672
- * `setSprite2DShaderParams` (`index.d.ts` 11074).
3673
- *
3674
- * ## The one-shader-per-layer constraint
3675
- *
3676
- * `Sprite2DLayer.customShader` is `readonly` and is only set at creation. A layer's shader
3677
- * therefore cannot change once sprites are in it, so `SpriteLayerEffect` has to exist **before**
3678
- * the first sprite on its sorting layer is synced — put it in the scene file, or add it in
3679
- * `awake`, not halfway through a level.
3660
+ * Apply a custom fragment shader to a sorting layer. The shader is fixed when the layer is
3661
+ * created, so add the effect before that layer's first sprite sync, such as in the scene or `awake`.
3680
3662
  */
3681
3663
  /**
3682
3664
  * The built-in effects, in the order an inspector should list them.
@@ -3784,23 +3766,9 @@ function spriteLayerEffectSchema() {
3784
3766
  //#endregion
3785
3767
  //#region src/tilemap/definition.ts
3786
3768
  /**
3787
- * The `ignifx.tilemap` document — the `.tilemap.json` file that names tile sizes, tilesets, tile
3788
- * layers and object layers (`docs/architecture/06-serialization-and-scene-format.md` §6,
3789
- * `11-2d-toolkit.md` §2.5).
3790
- *
3791
- * Two coordinate conventions meet in this file and it is worth stating both loudly, because getting
3792
- * them backwards is the single easiest mistake to make in a tilemap pipeline:
3793
- *
3794
- * - **Authoring space** (everything on `TileColliderDefinition` and every editor this package
3795
- * imports from) is cell-normalised `[0, 1]` with the origin at the **top-left** of the cell and
3796
- * +Y pointing **down**. Tiled and LDtk both emit pixels in that orientation, and the importers
3797
- * divide by the tile size rather than flipping.
3798
- * - **Runtime space** (`TileCollisionShape`, `TilemapCollisionData`, and every world coordinate on
3799
- * `TilemapObjectDefinition`) is metres with the origin at the **bottom-left** and +Y pointing
3800
- * **up**, because that is the ignifx 2D world (ADR-0011).
3801
- *
3802
- * {@link tileCollisionInfo} is the one function that crosses between them, so the flip lives in
3803
- * exactly one place — the same discipline `../math/coords.ts` applies to the render path.
3769
+ * Tilemap file data uses top-left, Y-down coordinates; collider points are cell-normalised.
3770
+ * Runtime collision data uses bottom-left, Y-up coordinates in metres.
3771
+ * `tileCollisionInfo` converts between them (docs/architecture/11-2d-toolkit.md §2.5, ADR-0011).
3804
3772
  */
3805
3773
  /**
3806
3774
  * The `format` discriminator every `.tilemap.json` document carries.
@@ -4420,18 +4388,9 @@ function tilemapRendererSchema() {
4420
4388
  //#endregion
4421
4389
  //#region src/service/layer-registry.ts
4422
4390
  /**
4423
- * The pool of Lite sprite layers (`docs/architecture/11-2d-toolkit.md` §1).
4424
- *
4425
- * One `Sprite2DLayer` exists per **(sorting layer, atlas, blend mode, screen-space)** tuple,
4426
- * because Lite binds a layer to one atlas and one blend mode for its whole life (`index.d.ts` 11885
4427
- * declares both `readonly`). Layers are created on demand as sprites appear and torn down with the
4428
- * app; a sprite that changes any part of its key is removed from one layer and added to another,
4429
- * which replaces its handle.
4430
- *
4431
- * The registry also carries the **handle-index to component** map that picking needs. Lite has no
4432
- * per-sprite metadata slot and removes by swapping the last sprite into the freed index
4433
- * (`lib/sprite/sprite-2d-handle.js`), so the map is a dense array kept in step by applying the same
4434
- * swap rule.
4391
+ * Pool sprite layers by sorting layer, atlas, blend mode, and screen-space mode.
4392
+ * A changed key needs a new handle because a layer's atlas and blend mode cannot change.
4393
+ * The picking map mirrors Lite's swap removal so each index still identifies the right component.
4435
4394
  */
4436
4395
  /** How many sprites a new layer pre-allocates room for. */
4437
4396
  const INITIAL_LAYER_CAPACITY = 64;
@@ -4571,7 +4530,7 @@ var SpriteLayerRegistry = class {
4571
4530
  */
4572
4531
  place(component, atlas, scratch) {
4573
4532
  const key = spriteLayerKey(component.sortingLayer, atlas.address, component.blend, component.screenSpace);
4574
- const record = this.#ensure(key, component.sortingLayer, component.blend, component.screenSpace, atlas);
4533
+ const record = this.#ensure(key, component.sortingLayer, component.blend, component.screenSpace, atlas, INITIAL_LAYER_CAPACITY);
4575
4534
  const handle = addSprite(record.layer, scratch);
4576
4535
  const index = spriteIndexOf(handle);
4577
4536
  if (index >= 0) record.components[index] = component;
@@ -4618,7 +4577,7 @@ var SpriteLayerRegistry = class {
4618
4577
  */
4619
4578
  placeRaw(sortingLayer, atlas, blend, screenSpace, scratch) {
4620
4579
  const key = spriteLayerKey(sortingLayer, atlas.address, blend, screenSpace);
4621
- const record = this.#ensure(key, sortingLayer, blend, screenSpace, atlas);
4580
+ const record = this.#ensure(key, sortingLayer, blend, screenSpace, atlas, INITIAL_LAYER_CAPACITY);
4622
4581
  const handle = addSprite(record.layer, scratch);
4623
4582
  const index = spriteIndexOf(handle);
4624
4583
  if (index >= 0) record.components[index] = null;
@@ -4628,6 +4587,46 @@ var SpriteLayerRegistry = class {
4628
4587
  };
4629
4588
  }
4630
4589
  /**
4590
+ * Claims `capacity` sprite slots in one layer at once — what `app.twoD.createSpriteBatch` is
4591
+ * built on.
4592
+ *
4593
+ * @remarks
4594
+ * This is {@link SpriteLayerRegistry.placeRaw} `capacity` times with the key computed once and
4595
+ * the Lite layer pre-allocated for the whole crowd, so a 5 000-sprite batch neither builds 5 000
4596
+ * key strings nor makes Lite double its instance array nine times. Like `placeRaw` the slots take
4597
+ * no place in the pick map: a batch sprite has no component for `app.twoD.pickAt` to resolve.
4598
+ *
4599
+ * The `capacity` is only a pre-allocation for a layer this call **creates**. A batch that lands
4600
+ * in a layer some `SpriteRenderer` already opened gets Lite's growth-by-doubling instead, which
4601
+ * is correct but reallocates.
4602
+ *
4603
+ * @param sortingLayer - The sorting layer's name.
4604
+ * @param atlas - The atlas every slot draws from.
4605
+ * @param blend - The blend mode.
4606
+ * @param screenSpace - Whether the layer ignores the camera.
4607
+ * @param capacity - How many slots to claim.
4608
+ * @param scratch - The reusable props record every slot is created from, already written.
4609
+ * @param out - The array to fill with the handles; it is emptied first.
4610
+ * @returns The key of the layer the slots landed in, and the layer itself.
4611
+ *
4612
+ * @internal
4613
+ */
4614
+ placeBatch(sortingLayer, atlas, blend, screenSpace, capacity, scratch, out) {
4615
+ const key = spriteLayerKey(sortingLayer, atlas.address, blend, screenSpace);
4616
+ const record = this.#ensure(key, sortingLayer, blend, screenSpace, atlas, capacity);
4617
+ out.length = 0;
4618
+ for (let slot = 0; slot < capacity; slot += 1) {
4619
+ const handle = addSprite(record.layer, scratch);
4620
+ const index = spriteIndexOf(handle);
4621
+ if (index >= 0) record.components[index] = null;
4622
+ out.push(handle);
4623
+ }
4624
+ return {
4625
+ key,
4626
+ layer: record.layer
4627
+ };
4628
+ }
4629
+ /**
4631
4630
  * Removes a sprite added by {@link SpriteLayerRegistry.placeRaw}.
4632
4631
  *
4633
4632
  * @param key - The key the sprite was placed under.
@@ -4704,9 +4703,10 @@ var SpriteLayerRegistry = class {
4704
4703
  * @param blend - The blend mode the layer draws with.
4705
4704
  * @param screenSpace - Whether the layer ignores the camera.
4706
4705
  * @param atlas - The atlas to bind the layer to.
4706
+ * @param capacity - How many sprites a layer this call creates pre-allocates room for.
4707
4707
  * @returns The record.
4708
4708
  */
4709
- #ensure(key, sortingLayer, blend, screenSpace, atlas) {
4709
+ #ensure(key, sortingLayer, blend, screenSpace, atlas, capacity) {
4710
4710
  const existing = this.#records.get(key);
4711
4711
  if (existing !== void 0) return existing;
4712
4712
  const liteAtlas = atlas.lite.atlas;
@@ -4714,7 +4714,7 @@ var SpriteLayerRegistry = class {
4714
4714
  const layer = createLayer(liteAtlas, {
4715
4715
  blend,
4716
4716
  order: this.#sortingLayers.orderOf(sortingLayer) + this.#countIn(sortingLayer),
4717
- capacity: INITIAL_LAYER_CAPACITY,
4717
+ capacity,
4718
4718
  customShader: this.#shaderFor(sortingLayer)
4719
4719
  });
4720
4720
  const ySort = !screenSpace && this.#ySort[sortingLayer] === true;
@@ -5481,19 +5481,9 @@ function createTilemapLoader() {
5481
5481
  //#endregion
5482
5482
  //#region src/tilemap/tilemap.ts
5483
5483
  /**
5484
- * `Tilemap` (`docs/architecture/11-2d-toolkit.md` §2.5): the grid of tile ids a level is built
5485
- * from, its cell arithmetic, and the merged collision geometry `@ignifx/physics-2d` consumes.
5486
- *
5487
- * The component holds no Lite object — `TilemapRenderer` draws it — so a headless app carries the
5488
- * full grid and the full collision surface. That is what makes a level's collision testable
5489
- * without a GPU, and what lets a server run the same map the client draws.
5490
- *
5491
- * ## Coordinates
5492
- *
5493
- * Cell `(0, 0)` is the **bottom-left** of the map, because ignifx 2D is +Y up (ADR-0011). The
5494
- * document's own layers are stored top row first, as every editor writes them, and the component
5495
- * flips on the way in. `worldToCell`/`cellToWorld` are relative to the tilemap entity's own
5496
- * transform, so moving the entity moves the whole map.
5484
+ * Keep the tile grid and collision data available without a renderer or GPU.
5485
+ * Cell `(0, 0)` is the bottom-left; document rows are flipped from their top-first order.
5486
+ * Cell/world conversions include the tilemap entity's transform (ADR-0011).
5497
5487
  */
5498
5488
  /**
5499
5489
  * How many cells one chunk spans by default (`docs/architecture/11-2d-toolkit.md` §2.5).
@@ -5854,28 +5844,8 @@ function tilemapSchema() {
5854
5844
  //#endregion
5855
5845
  //#region src/service/sync-system.ts
5856
5846
  /**
5857
- * The 2D sync system (`docs/architecture/11-2d-toolkit.md` §2.2,
5858
- * `01-lifecycle-and-time.md` §3): once per frame, in `PreRender`, it selects the active
5859
- * `Camera2D`, writes every world layer's view, and pushes every sprite whose transform or fields
5860
- * changed into its Lite layer.
5861
- *
5862
- * ## Ordering
5863
- *
5864
- * `docs/architecture/11-2d-toolkit.md` §2.2 asks for `PreRender` order `-400`, but
5865
- * `@ignifx/audio`'s spatial pump already occupies that exact slot
5866
- * (`AUDIO_PUMP_ORDER`, `docs/architecture/10-audio.md` §5). Equal orders are broken by
5867
- * registration order, which makes the interleaving depend on the order a game lists its
5868
- * extensions in. The two systems touch nothing in common, so the tie would be harmless — but a
5869
- * frame order that changes with an argument list is not something to leave in place, so 2D takes
5870
- * {@link TWO_D_SYNC_ORDER} instead: after physics interpolation at `-500` has written the frame's
5871
- * final transforms, before audio at `-400`, and well before core's render sync at `900`.
5872
- *
5873
- * ## Cost
5874
- *
5875
- * A sprite that did not move and whose fields did not change costs one integer comparison
5876
- * (`Transform.worldMatrixVersion`), and an entity marked `isStatic` costs that comparison only
5877
- * until its first sync. That is what keeps a 100x100 tilemap at zero per-frame sync cost once its
5878
- * chunks are up (spike S6.1).
5847
+ * Sync changed sprites and camera views in `PreRender`, before audio and core render sync.
5848
+ * Unchanged sprites need only a transform-version check; static sprites sync once.
5879
5849
  */
5880
5850
  /**
5881
5851
  * The `PreRender` order the 2D sync system runs at.
@@ -6137,6 +6107,292 @@ function selectCamera(world) {
6137
6107
  return best;
6138
6108
  }
6139
6109
  //#endregion
6110
+ //#region src/service/sprite-batch.ts
6111
+ /**
6112
+ * `app.twoD.createSpriteBatch` (`docs/plan/2026-09-terrain-particles-shaders.md` §2.2): a
6113
+ * fixed-capacity crowd of sprites that no entity owns.
6114
+ *
6115
+ * A `SpriteRenderer` is the right tool for a sprite that is a *thing* in the world — it has a
6116
+ * transform, it can be picked, it serializes. It is the wrong tool for ten thousand bullets, sparks
6117
+ * or particles: each one would cost an entity, a component, a transform and a slot in the sync
6118
+ * system's walk. A batch is the other end of that trade. It claims `capacity` slots in one Lite
6119
+ * layer once, and from then on the caller addresses them by index with a single allocation-free
6120
+ * `write` per sprite per frame.
6121
+ *
6122
+ * ## Why writes flush eagerly
6123
+ *
6124
+ * The alternative — record the caller's values into a shadow typed array and push them into Lite
6125
+ * from a `PreRender` hook — buys nothing here. `updateSprite2D` writes straight into the layer's
6126
+ * own `Float32Array` and marks a dirty range that the renderer uploads once at draw time
6127
+ * (`lib/sprite/sprite-2d.js`, `writeInstance` and `markDirty`), so a deferred flush would be a
6128
+ * second copy of the same numbers and a second pass over them. Writing eagerly is one write per
6129
+ * `write()` call and needs no per-frame hook of its own — so the batch has no ordering requirement
6130
+ * beyond "before the frame draws", which every phase up to `PreRender` satisfies.
6131
+ *
6132
+ * The batch itself allocates nothing per write: one scratch props record, one scratch vector, and
6133
+ * the two flag arrays are built once. Lite's `updateSprite2DIndex` does take a `subarray` view of
6134
+ * the instance data on every call, so one small view object per written sprite per frame is
6135
+ * unavoidable through its public API — the same cost the sync system already pays for every sprite
6136
+ * that moved (`lib/sprite/sprite-2d.js`). It is an upstream ask, not something a shadow buffer here
6137
+ * would avoid, because a deferred flush would make the same call.
6138
+ *
6139
+ * ## What a batch does not do
6140
+ *
6141
+ * - **Picking.** Batch slots hold no component, so `app.twoD.pickAt` never resolves one. Address a
6142
+ * batch sprite by the index the caller already has.
6143
+ * - **Per-batch Y-sort.** A batch does not sort its own slots in v1. It inherits whatever the Lite
6144
+ * layer does: on a sorting layer the `ySort` setting names, Lite sorts the batch's sprites
6145
+ * together with every `SpriteRenderer` sharing that layer; otherwise slots draw in index order.
6146
+ * Y-sort is not free at this scale — any position change marks Lite's whole layer unsorted and
6147
+ * costs a merge sort and a full re-upload of it that frame (`lib/sprite/sprite-2d-y-sort.js`,
6148
+ * `observeDirty` and `ensureSorted`) — so a big moving batch belongs on a sorting layer that does
6149
+ * not Y-sort.
6150
+ * - **Pivots.** Every slot is centred on the `(x, y)` it is written at. Lite carries one pivot per
6151
+ * layer and `SpriteFrame.pivot` is not read by the 2D pipeline, so a batch skips the per-frame
6152
+ * pivot arithmetic a `SpriteRenderer` pays for (see `pivotedPositionToRef`).
6153
+ */
6154
+ /** Returned by a headless batch's `lite.handles`, so the getter allocates no array. */
6155
+ const NO_HANDLES = Object.freeze([]);
6156
+ /**
6157
+ * The one implementation of {@link SpriteBatch}.
6158
+ */
6159
+ var SpriteBatchImpl = class {
6160
+ capacity;
6161
+ #runtime;
6162
+ /** How many frames the atlas declares, so an out-of-range frame draws frame 0 as sprites do. */
6163
+ #frameCount;
6164
+ /** The key of the Lite layer holding the slots, or `null` under a headless app. */
6165
+ #key = null;
6166
+ /** The Lite layer holding the slots, so {@link SpriteBatchImpl.#live} can read its count. */
6167
+ #layer = null;
6168
+ /** One handle per slot, or `null` under a headless app and after disposal. */
6169
+ #handles = null;
6170
+ /** Per slot: `1` once written and not hidden, so raising `count` can reveal it again. */
6171
+ #wanted;
6172
+ /** Per slot: the visibility Lite currently holds, so a `count` change writes only what changed. */
6173
+ #applied;
6174
+ #count = 0;
6175
+ #isDisposed = false;
6176
+ #scratch = createSpriteScratch();
6177
+ #visibility = createSpriteVisibilityScratch();
6178
+ #pixels = new Vec2();
6179
+ /**
6180
+ * Claims the slots. `app.twoD.createSpriteBatch` does this; a game never constructs one.
6181
+ *
6182
+ * @param runtime - The app's 2D runtime state.
6183
+ * @param options - The atlas, the capacity, and the layer key's other parts.
6184
+ * @throws IgnifxError with code `IGX-1114` for a capacity that is not a whole number of at least
6185
+ * 1, `IGX-1117` for an atlas that has not finished loading, or `IGX-1107` for an undeclared
6186
+ * sorting layer.
6187
+ */
6188
+ constructor(runtime, options) {
6189
+ const capacity = options.capacity;
6190
+ if (!Number.isInteger(capacity) || capacity < 1) throw twoDError(TwoDErrorCode.invalidBatchCapacity, `A sprite batch capacity must be a whole number of at least 1; got ${String(capacity)}.`, {
6191
+ context: { capacity },
6192
+ hint: "Pass the largest number of sprites the batch will ever draw."
6193
+ });
6194
+ const handle = options.atlas;
6195
+ if (handle.state !== "loaded") throw twoDError(TwoDErrorCode.batchAtlasNotLoaded, `The atlas handle for a sprite batch is ${handle.state}, not loaded.`, {
6196
+ context: {
6197
+ address: handle.address,
6198
+ state: handle.state
6199
+ },
6200
+ hint: "Await the handle's promise before creating the batch."
6201
+ });
6202
+ const atlas = handle.value;
6203
+ const sortingLayer = options.sortingLayer ?? "Default";
6204
+ runtime.sortingLayers.require(sortingLayer);
6205
+ this.capacity = capacity;
6206
+ this.#runtime = runtime;
6207
+ this.#frameCount = atlas.frameCount;
6208
+ this.#wanted = new Uint8Array(capacity);
6209
+ this.#applied = new Uint8Array(capacity);
6210
+ if (atlas.lite.atlas === null) return;
6211
+ const handles = [];
6212
+ writeScratch(this.#scratch, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, false, false, false);
6213
+ const placed = runtime.layers.placeBatch(sortingLayer, atlas, options.blend ?? "alpha", options.screenSpace === true, capacity, this.#scratch, handles);
6214
+ this.#key = placed.key;
6215
+ this.#layer = placed.layer;
6216
+ this.#handles = handles;
6217
+ }
6218
+ /**
6219
+ * How many leading slots draw.
6220
+ *
6221
+ * @returns The count.
6222
+ */
6223
+ get count() {
6224
+ return this.#count;
6225
+ }
6226
+ /**
6227
+ * Sets how many leading slots draw.
6228
+ *
6229
+ * @param value - The new count, in `0 .. capacity`.
6230
+ */
6231
+ set count(value) {
6232
+ this.#requireNotDisposed();
6233
+ if (!Number.isInteger(value) || value < 0 || value > this.capacity) throw twoDError(TwoDErrorCode.batchIndexOutOfRange, `${String(value)} is outside the sprite batch's slots.`, {
6234
+ context: {
6235
+ index: value,
6236
+ capacity: this.capacity
6237
+ },
6238
+ hint: "A batch's count runs from 0 to its capacity."
6239
+ });
6240
+ const previous = this.#count;
6241
+ if (value === previous) return;
6242
+ this.#count = value;
6243
+ if (value < previous) {
6244
+ for (let index = value; index < previous; index += 1) this.#setVisible(index, false);
6245
+ return;
6246
+ }
6247
+ for (let index = previous; index < value; index += 1) if (this.#wanted[index] === 1) this.#setVisible(index, true);
6248
+ }
6249
+ /**
6250
+ * The Babylon Lite objects the batch owns.
6251
+ *
6252
+ * @returns The handles, in slot order.
6253
+ */
6254
+ get lite() {
6255
+ return { handles: this.#handles ?? NO_HANDLES };
6256
+ }
6257
+ /**
6258
+ * Writes one slot.
6259
+ *
6260
+ * @param index - The slot.
6261
+ * @param x - The centre, in world metres.
6262
+ * @param y - The centre, in world metres, +Y up.
6263
+ * @param width - The drawn width, in world metres.
6264
+ * @param height - The drawn height, in world metres.
6265
+ * @param frame - The atlas frame index.
6266
+ * @param rotation - The rotation, in degrees counter-clockwise.
6267
+ * @param r - The red tint.
6268
+ * @param g - The green tint.
6269
+ * @param b - The blue tint.
6270
+ * @param a - The alpha.
6271
+ * @param flipX - Whether the sprite is mirrored horizontally.
6272
+ * @param flipY - Whether the sprite is mirrored vertically.
6273
+ */
6274
+ write(index, x, y, width, height, frame, rotation, r, g, b, a, flipX = false, flipY = false) {
6275
+ this.#requireSlot(index);
6276
+ this.#wanted[index] = 1;
6277
+ const handle = this.#live()?.[index];
6278
+ if (handle === void 0) return;
6279
+ const pixelsPerUnit = this.#runtime.pixelsPerUnit;
6280
+ const position = worldToPixelsToRef(x, y, pixelsPerUnit, this.#pixels);
6281
+ const whole = Math.floor(frame);
6282
+ const safeFrame = whole >= 0 && whole < this.#frameCount ? whole : 0;
6283
+ const isVisible = index < this.#count;
6284
+ writeScratch(this.#scratch, position.x, position.y, width * pixelsPerUnit, height * pixelsPerUnit, safeFrame, spriteRotationToLite(rotation), r, g, b, a, flipX, flipY, isVisible);
6285
+ updateSprite(handle, this.#scratch);
6286
+ this.#applied[index] = isVisible ? 1 : 0;
6287
+ }
6288
+ /**
6289
+ * Hides one slot until it is written again.
6290
+ *
6291
+ * @param index - The slot.
6292
+ */
6293
+ hide(index) {
6294
+ this.#requireSlot(index);
6295
+ this.#wanted[index] = 0;
6296
+ this.#setVisible(index, false);
6297
+ }
6298
+ /**
6299
+ * Releases every slot back to its Lite layer.
6300
+ */
6301
+ dispose() {
6302
+ if (this.#isDisposed) return;
6303
+ this.#isDisposed = true;
6304
+ this.#count = 0;
6305
+ const handles = this.#handles;
6306
+ const key = this.#key;
6307
+ this.#handles = null;
6308
+ this.#key = null;
6309
+ this.#layer = null;
6310
+ if (handles === null || key === null) return;
6311
+ for (let index = handles.length - 1; index >= 0; index -= 1) {
6312
+ const handle = handles[index];
6313
+ if (handle !== void 0) this.#runtime.layers.removeRaw(key, handle);
6314
+ }
6315
+ handles.length = 0;
6316
+ }
6317
+ /**
6318
+ * Disposes the batch at the end of a `using` block.
6319
+ */
6320
+ [Symbol.dispose]() {
6321
+ this.dispose();
6322
+ }
6323
+ /**
6324
+ * Shows or hides one slot, skipping the write when Lite already agrees.
6325
+ *
6326
+ * @param index - The slot.
6327
+ * @param isVisible - Whether it should draw.
6328
+ */
6329
+ #setVisible(index, isVisible) {
6330
+ const handle = this.#live()?.[index];
6331
+ if (handle === void 0) return;
6332
+ const flag = isVisible ? 1 : 0;
6333
+ if (this.#applied[index] === flag) return;
6334
+ updateSpriteVisibility(handle, this.#visibility, isVisible);
6335
+ this.#applied[index] = flag;
6336
+ }
6337
+ /**
6338
+ * The handles, or `null` once the layer holding them is gone.
6339
+ *
6340
+ * @remarks
6341
+ * `app.dispose()` empties every layer, which kills the batch's handles — and writing through a
6342
+ * dead handle is a raw Lite throw, not an ignifx error. The check that catches it has to be free,
6343
+ * because it runs on every write: the batch's own slots are always in the layer, so the layer's
6344
+ * `count` can never fall below the batch's capacity while they live, and a smaller count means
6345
+ * they are gone. That is one property read, where asking Lite whether a handle is alive would be
6346
+ * another hash lookup per sprite per frame.
6347
+ *
6348
+ * @returns The handles, or `null`.
6349
+ */
6350
+ #live() {
6351
+ const layer = this.#layer;
6352
+ if (layer === null) return null;
6353
+ if (layer.count < this.capacity) {
6354
+ this.#layer = null;
6355
+ this.#handles = null;
6356
+ this.#key = null;
6357
+ return null;
6358
+ }
6359
+ return this.#handles;
6360
+ }
6361
+ /**
6362
+ * Refuses a slot index the batch does not have, and a batch that is gone.
6363
+ *
6364
+ * @param index - The slot.
6365
+ */
6366
+ #requireSlot(index) {
6367
+ this.#requireNotDisposed();
6368
+ if (!Number.isInteger(index) || index < 0 || index >= this.capacity) throw twoDError(TwoDErrorCode.batchIndexOutOfRange, `${String(index)} is outside the sprite batch's slots.`, {
6369
+ context: {
6370
+ index,
6371
+ capacity: this.capacity
6372
+ },
6373
+ hint: "Slots run from 0 to capacity - 1."
6374
+ });
6375
+ }
6376
+ /**
6377
+ * Refuses a batch that has been disposed.
6378
+ */
6379
+ #requireNotDisposed() {
6380
+ if (this.#isDisposed) throw twoDError(TwoDErrorCode.batchDisposed, "This sprite batch was disposed; create another one.", { hint: "Create a new batch with app.twoD.createSpriteBatch." });
6381
+ }
6382
+ };
6383
+ /**
6384
+ * Builds a sprite batch. `TwoDService.createSpriteBatch` is the public door.
6385
+ *
6386
+ * @param runtime - The app's 2D runtime state.
6387
+ * @param options - The atlas, the capacity, and the layer key's other parts.
6388
+ * @returns The batch.
6389
+ *
6390
+ * @internal
6391
+ */
6392
+ function createSpriteBatch(runtime, options) {
6393
+ return new SpriteBatchImpl(runtime, options);
6394
+ }
6395
+ //#endregion
6140
6396
  //#region src/service/two-d-service.ts
6141
6397
  /**
6142
6398
  * The 2D service.
@@ -6293,6 +6549,36 @@ var TwoDService = class {
6293
6549
  return null;
6294
6550
  }
6295
6551
  /**
6552
+ * Claims a fixed-capacity crowd of sprites that no entity owns
6553
+ * (`docs/plan/2026-09-terrain-particles-shaders.md` §2.2).
6554
+ *
6555
+ * @remarks
6556
+ * Use it when the sprites are not *things* — bullets, sparks, debris, 2D particles — and the
6557
+ * per-entity cost of a `SpriteRenderer` would dominate. The batch is not picked and does not sort
6558
+ * its own slots; see {@link SpriteBatch}. Dispose it when the crowd is gone, or take it with
6559
+ * `using`.
6560
+ *
6561
+ * @param options - The atlas, the capacity, the sorting layer, the blend, and the space.
6562
+ * @returns The batch.
6563
+ * @throws IgnifxError with code `IGX-1114` for a capacity that is not a whole number of at least
6564
+ * 1, `IGX-1117` for an atlas handle that has not finished loading, or `IGX-1107` for a sorting
6565
+ * layer the project does not declare.
6566
+ *
6567
+ * @example
6568
+ * ```ts
6569
+ * const atlas = app.assets.load<SpriteAtlasAsset>("2d/spark.atlas.json");
6570
+ * await atlas.promise;
6571
+ * const batch = app.twoD.createSpriteBatch({ atlas, capacity: 2048, blend: "additive" });
6572
+ * batch.count = 1;
6573
+ * batch.write(0, 0, 0, 0.2, 0.2, 0, 0, 1, 0.8, 0.3, 1);
6574
+ * ```
6575
+ *
6576
+ * @beta
6577
+ */
6578
+ createSpriteBatch(options) {
6579
+ return createSpriteBatch(this.#runtime, options);
6580
+ }
6581
+ /**
6296
6582
  * The world-space rectangle the camera can currently see.
6297
6583
  *
6298
6584
  * @param out - The box to write: its `min` takes the lower corner and its `max` the upper.
@@ -6469,17 +6755,8 @@ function spriteClearColor(app) {
6469
6755
  //#endregion
6470
6756
  //#region src/tilemap/spawn-objects.ts
6471
6757
  /**
6472
- * Spawning the entities a tilemap's objects layer describes
6473
- * (`docs/architecture/11-2d-toolkit.md` §2.5).
6474
- *
6475
- * A map editor's objects layer is a list of *intentions* — "a player starts here", "this rectangle
6476
- * is a trigger" — and only the game knows what each one becomes. `app.twoD.registerTileObjectFactory`
6477
- * is where a game says so, and this module is what runs those factories when a scene carrying a
6478
- * `Tilemap` finishes loading.
6479
- *
6480
- * Objects are spawned **once per scene load**, on `world.onSceneLoaded`, after `awake` and
6481
- * `onEnable` have flushed (`world.ts` 596-597), so a factory can reach any component the scene
6482
- * declared.
6758
+ * Run the game's tile-object factories once per scene load, on `world.onSceneLoaded`.
6759
+ * `awake` and `onEnable` have finished by then, so factories can use the scene's components.
6483
6760
  */
6484
6761
  /**
6485
6762
  * Runs the registered factory for every object in every `Tilemap` in a scene.
@@ -6772,16 +7049,8 @@ const twoD = defineExtension((raw) => {
6772
7049
  //#endregion
6773
7050
  //#region src/file-schemas.ts
6774
7051
  /**
6775
- * Declarative schemas for the three file formats `@ignifx/2d` reads
6776
- * (`docs/architecture/06-serialization-and-scene-format.md` §6).
6777
- *
6778
- * These exist for **documentation and tooling**, not for the loaders: a loader validates with its
6779
- * own `defineX` function, which produces an actionable `IGX-11##` message naming the offending
6780
- * frame or clip. The schema here is what `pnpm docs:schemas` renders into
6781
- * `skills/ignifx/references/formats/`, and what a JSON Schema for an editor is generated from.
6782
- *
6783
- * The two descriptions are deliberately kept in one package so they cannot drift apart in a
6784
- * release; a test asserts that a fixture accepted by the loader also validates against the schema.
7052
+ * Schemas for generated format docs and editor validation. Loaders validate through their own
7053
+ * `defineX` functions; tests check that accepted fixtures also satisfy these schemas.
6785
7054
  */
6786
7055
  /**
6787
7056
  * The `ignifx.spriteatlas` document schema.