@flare-engine/ecs 0.3.0 → 0.4.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @flare-engine/ecs
2
2
 
3
- Archetype-bitmask ECS — `World` (spawn/destroy, `query` + `removeQuery`, `forEachEntity`, `entityCount`), `Query` with `onEntityAdded` / `onEntityRemoved` signals, `defineComponent`, `defineSystem`, `definePrefab`, `FSM`. Built-in components: `Position`, `Velocity`, `Rotation`, `Scale`, `Parent`, `Lifetime`, `Follower`. Five system factories: `createMovementSystem`, `createLifetimeSystem`, `createBoundsCullSystem`, `createFollowerSystem`, `createOrphanCullSystem`. Max 32 component types total — the component-id bitmask is module-global, shared across all `World` instances.
3
+ Archetype-bitmask ECS — `World` (spawn/destroy, `query` + `queryBuilder` + `removeQuery`, `forEachEntity`, `entityCount`), `Query` with a zero-alloc `entities` walk and `onEntityAdded` / `onEntityRemoved` signals, `defineComponent`, `defineSystem`, `definePrefab`, `FSM`. Built-in components: `Position`, `Velocity`, `Rotation`, `Scale`, `Parent`, `Lifetime`, `Follower`. Five system factories: `createMovementSystem`, `createLifetimeSystem`, `createBoundsCullSystem`, `createFollowerSystem`, `createOrphanCullSystem`. Max 32 component types total — the component-id bitmask is module-global, shared across all `World` instances.
4
4
 
5
5
  ## Install
6
6
 
@@ -22,7 +22,30 @@ world.add(e, Velocity, { x: 1, y: 0 });
22
22
  world.add(e, Health);
23
23
 
24
24
  const movers = world.query(Position, Velocity);
25
- for (const id of movers) { /* ... */ }
25
+ const ids = movers.entities;
26
+ for (let i = 0; i < ids.length; i++) {
27
+ const id = ids[i]!;
28
+ /* ... */
29
+ }
30
+ ```
31
+
32
+ ## Walking a query
33
+
34
+ `query.entities` is the live `readonly number[]` of matching ids — walk it by index, as above, and nothing is allocated. `for (const id of query)` also works and is fine outside the frame, but it creates an iterator per loop and, on Hermes (React Native), one result object per entity, so keep it out of systems and render code. The array is live: destroying an entity or changing its components mid-walk moves another entity into the slot under you — collect first, act after.
35
+
36
+ ## Prefab data
37
+
38
+ `definePrefab` plain-object data is stored by reference and shared by every spawn; pass `() => T` for per-entity mutable state:
39
+
40
+ ```ts
41
+ import { definePrefab, Position, Velocity } from '@flare-engine/ecs';
42
+
43
+ // Every bullet gets its own Position and Velocity object.
44
+ const Bullet = definePrefab(
45
+ 'Bullet',
46
+ [Position, () => ({ x: 0, y: 0 })],
47
+ [Velocity, () => ({ x: 0, y: -300 })],
48
+ );
26
49
  ```
27
50
 
28
51
  See [API spec](https://github.com/grzott/flare-engine/blob/main/docs/design/api-specs.md#flare-engineecs--8kb-gzip).
package/dist/index.d.mts CHANGED
@@ -103,6 +103,13 @@ declare class FSM<C = undefined> {
103
103
  *
104
104
  * Uses bitmask matching: entity archetype & requiredMask === requiredMask
105
105
  * and entity archetype & excludedMask === 0.
106
+ *
107
+ * Two ways to walk the matches:
108
+ * - `entities` — the live id array, for an indexed `for` loop. Allocates
109
+ * nothing; this is the form for systems and anything else that runs per frame.
110
+ * - `for...of` — the convenience form. It creates an iterator, and on Hermes
111
+ * (React Native) one `{ value, done }` object per entity per pass, so keep
112
+ * it off the frame path.
106
113
  */
107
114
  declare class Query {
108
115
  /** Bitmask of required components. */
@@ -113,10 +120,14 @@ declare class Query {
113
120
  readonly onEntityAdded: Signal<number>;
114
121
  /** Fires when an entity is removed from this query's results. */
115
122
  readonly onEntityRemoved: Signal<number>;
116
- /** Sorted array of matching entity IDs. */
117
- private entities;
118
- /** Set for O(1) membership check. */
119
- private entitySet;
123
+ private ids;
124
+ /**
125
+ * `entityId -> index into ids`. Serves membership *and* position, which
126
+ * is what makes removal O(1): the previous pair of a `Set` plus `indexOf`
127
+ * made every removal a linear scan, so churn cost grew as `n * removals`
128
+ * rather than with the number of removals.
129
+ */
130
+ private index;
120
131
  constructor(requiredMask: number, excludedMask: number);
121
132
  /** Check if an archetype matches this query. */
122
133
  matches(archetype: number): boolean;
@@ -124,20 +135,69 @@ declare class Query {
124
135
  _check(entityId: number, archetype: number): void;
125
136
  /** @internal — called by World when an entity is removed entirely. */
126
137
  _remove(entityId: number): void;
127
- /** Iterate matching entity IDs. */
138
+ /**
139
+ * O(1) removal: move the last element into the hole and shorten by one.
140
+ *
141
+ * Order-preserving removal cannot be O(1) here — `splice` shifts every later
142
+ * element, and a position map would then need every shifted index rewritten,
143
+ * so it costs the same scan it was meant to remove. A tombstone would keep
144
+ * order but puts a branch in iteration, which at realistic churn runs far
145
+ * more often than removal and would slow the steady-state path to speed up
146
+ * the rare one.
147
+ */
148
+ private swapRemove;
149
+ /**
150
+ * Matching entity IDs — the live array, not a copy, so reading it allocates
151
+ * nothing and it reflects every add and remove as it happens. Walk it by
152
+ * index on hot paths:
153
+ *
154
+ * const ids = query.entities;
155
+ * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }
156
+ *
157
+ * Because it is live, destroying an entity or changing its components mid-walk
158
+ * swap-removes from this array under the loop and skips an entity: collect
159
+ * first and act after, as the built-in systems do.
160
+ *
161
+ * Order is not guaranteed. Entities are appended as they begin matching and
162
+ * removed by swapping the last element into the hole, so the order reflects
163
+ * match history, not id. It was previously documented as "sorted", which was
164
+ * never true: `_check` has always plain-`push`ed, so an entity that starts
165
+ * matching later lands after entities with higher ids (spawn 1,2,3 then add
166
+ * the missing component to 3 first and the array reads `[3, 1, 2]`).
167
+ *
168
+ * The one consumer that cares is `render-system`, whose `sortByDrawOrder` is
169
+ * a *stable* insertion sort on `z` alone — so this order is the tie-break
170
+ * between equal-`z` sprites. It is deliberately not a guarantee: depend on
171
+ * `z`, not on the order entities happen to occupy here.
172
+ */
173
+ get entities(): readonly number[];
174
+ /**
175
+ * Iterate matching entity IDs. Convenience form: it allocates an iterator,
176
+ * and on Hermes a result object per entity — walk `entities` by index on
177
+ * hot paths.
178
+ */
128
179
  [Symbol.iterator](): IterableIterator<number>;
129
180
  /** Number of matching entities. */
130
181
  get count(): number;
131
182
  /** Check if an entity matches this query. */
132
183
  has(entityId: number): boolean;
133
184
  }
134
- /** Builder for creating queries with .with() / .without() chaining. */
185
+ /**
186
+ * Builder for creating queries with .with() / .without() chaining.
187
+ *
188
+ * Obtain one from `world.queryBuilder()`. `build()` hands the finished Query to
189
+ * the World it came from, which is what keeps it populated; the registration
190
+ * hook is a required constructor argument so a builder cannot exist without a
191
+ * World behind it, and the orphan `new QueryBuilder().build()` does not compile.
192
+ */
135
193
  declare class QueryBuilder {
136
194
  private required;
137
195
  private excluded;
196
+ private readonly register;
197
+ constructor(register: (q: Query) => void);
138
198
  with(...components: ComponentDef<unknown>[]): this;
139
199
  without(...components: ComponentDef<unknown>[]): this;
140
- /** Build the query (called internally by World). */
200
+ /** Build the query and register it with the owning World. */
141
201
  build(): Query;
142
202
  }
143
203
  //#endregion
@@ -191,6 +251,8 @@ declare class World {
191
251
  query(...components: ComponentDef<unknown>[]): Query;
192
252
  /** Create a QueryBuilder for complex queries (with/without). */
193
253
  queryBuilder(): QueryBuilder;
254
+ /** Track a query and populate it with the entities that already match. */
255
+ private register;
194
256
  /**
195
257
  * Dispose a query created by `query()` or `queryBuilder().build()`. Afterwards
196
258
  * the world stops updating it, so it no longer costs spawn/add/remove iteration
@@ -209,8 +271,6 @@ declare class World {
209
271
  removeSystem(fn: (world: World, dt: number) => void): void;
210
272
  /** Run all systems in priority order. */
211
273
  step(dt: number): void;
212
- /** @internal Register a query for auto-update. */
213
- _registerQuery(q: Query): void;
214
274
  }
215
275
  //#endregion
216
276
  //#region src/prefab.d.ts
@@ -218,11 +278,16 @@ declare class World {
218
278
  interface Prefab {
219
279
  readonly name: string;
220
280
  /** Spawn an entity with this prefab's components. */
221
- spawn(world: World, overrides?: Record<string, unknown>): number;
281
+ spawn(world: World): number;
222
282
  }
223
283
  /**
224
284
  * Define a prefab — a template for spawning entities with a fixed set of components.
225
285
  *
286
+ * Plain-object data is stored by reference and shared by every spawn; pass
287
+ * `() => T` for per-entity mutable state. This mirrors `world.add(entity, def,
288
+ * data)`, which stores the object it is given — so the object form is for
289
+ * data no entity will mutate, and the factory runs once per spawn.
290
+ *
226
291
  * @param name Debug name.
227
292
  * @param entries Array of [componentDef, data?] tuples.
228
293
  */
@@ -230,7 +295,7 @@ declare function definePrefab(name: string, ...entries: [ComponentDef<unknown>,
230
295
  //#endregion
231
296
  //#region src/system.d.ts
232
297
  /** A system function that processes entities matching a query. */
233
- type SystemFn = (entities: Query, dt: number, world: World) => void;
298
+ type SystemFn = (query: Query, dt: number, world: World) => void;
234
299
  /** A defined system with its query and function. */
235
300
  interface SystemDef {
236
301
  readonly query: Query;
@@ -246,10 +311,16 @@ interface SystemDef {
246
311
  *
247
312
  * Usage:
248
313
  * const q = world.query(Position, Velocity);
249
- * const moveSys = defineSystem(q, (entities, dt, world) => {
250
- * for (const id of entities) { ... }
314
+ * const moveSys = defineSystem(q, (query, dt, world) => {
315
+ * const ids = query.entities;
316
+ * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }
251
317
  * });
252
318
  * world.addSystem(moveSys._worldFn);
319
+ *
320
+ * Walk `query.entities` by index — that is the zero-alloc form. `for...of`
321
+ * over the query works too but allocates an iterator per loop (and, on
322
+ * Hermes, a result object per entity), which per system per frame is exactly
323
+ * what a system must not do.
253
324
  */
254
325
  declare function defineSystem(query: Query, fn: SystemFn): SystemDef;
255
326
  //#endregion
@@ -275,14 +346,19 @@ declare function createMovementSystem(world: World): SystemDef;
275
346
  * Entities whose remaining reaches <= 0 are collected, then onExpire is called
276
347
  * for each AFTER the read loop.
277
348
  *
278
- * Deferred removal: destroying inside a live for…of over query.entities splices
279
- * the array mid-iteration and would skip entities. Collect first, act after.
349
+ * Deferred removal: destroying inside a live walk of query.entities swap-removes
350
+ * from the array mid-iteration and would skip entities. Collect first, act after.
280
351
  *
281
352
  * The scratch array is closure-owned and grow-only — zero steady-state alloc.
282
353
  *
283
354
  * @param onExpire Destroy / pool policy — ecs never destroys on its own.
355
+ * @param query Optional caller-supplied Query. When omitted the system
356
+ * registers world.query(Lifetime) itself. Pass a narrower
357
+ * query to avoid scanning unrelated Lifetime holders and to
358
+ * share an already-registered query (eliminates duplicate
359
+ * World.query registration cost).
284
360
  */
285
- declare function createLifetimeSystem(world: World, onExpire: (entity: number, world: World) => void): SystemDef;
361
+ declare function createLifetimeSystem(world: World, onExpire: (entity: number, world: World) => void, query?: Query): SystemDef;
286
362
  /**
287
363
  * createBoundsCullSystem — culls entities whose Position falls outside bounds.
288
364
  * Reads bounds LIVE each frame so callers can mutate it to follow a camera.
@@ -294,8 +370,14 @@ declare function createLifetimeSystem(world: World, onExpire: (entity: number, w
294
370
  *
295
371
  * @param bounds Mutable bounding box read each frame.
296
372
  * @param onCull Destroy / pool policy — ecs never destroys on its own.
373
+ * @param query Optional caller-supplied Query. When omitted the system
374
+ * registers world.query(Position) itself, scanning all
375
+ * Position holders. Pass a narrower query (e.g. bullets
376
+ * only) to avoid scanning unrelated entities such as
377
+ * scrolling backgrounds, and to share an already-registered
378
+ * query with the caller.
297
379
  */
298
- declare function createBoundsCullSystem(world: World, bounds: CullBounds, onCull: (entity: number, world: World) => void): SystemDef;
380
+ declare function createBoundsCullSystem(world: World, bounds: CullBounds, onCull: (entity: number, world: World) => void, query?: Query): SystemDef;
299
381
  /**
300
382
  * createFollowerSystem — pins each Follower entity's Position to
301
383
  * target.Position + (offsetX, offsetY).
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/query.ts","../src/world.ts","../src/prefab.ts","../src/system.ts","../src/systems.ts"],"mappings":";;;;;;;;;;UAQiB,aAAa;;WAEnB;;WAEA;;WAEA;;EAET,UAAU;;;;;;;;iBAWI,gBAAgB,eAAe,cAAc,iBAAiB,IAAI,aAAa;;;;;iBAiB/E;;;;;;;cCpCH,UAAQ,aAAA;;cAMR,UAAQ,aAAA;;cAMR,UAAA;EAAQ;;;cAKR,OAAK,aAAA;;cAGL,QAAA;EAAM;;;cAKN,UAA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AAO;;;;;;;;;;;;;;;iBAgBpB,aAAa,OAAO,OAAO,IAAI,WAAW;;;;;;;UClBzC;WACN;WACA;WACA;WACA;;;;;;;iBAQK,qBAAqB,OAAO,QAAQ;;;;;;;;;;;;;iBAwBpC,qBACd,OAAO,OACP,WAAW,gBAAgB,OAAO,iBACjC;;;;;;;;;;;;;iBA8Ba,uBACd,OAAO,OACP,QAAQ,YACR,SAAS,gBAAgB,OAAO,iBAC/B;;;;;;;;;iBA8Ba,qBAAqB,OAAO,QAAQ;;;;;;;;;;;;;;;iBA4BpC,uBACd,OAAO,OACP,WAAW,gBAAgB,OAAO,iBACjC"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/query.ts","../src/world.ts","../src/prefab.ts","../src/system.ts","../src/systems.ts"],"mappings":";;;;;;;;;;UAQiB,aAAa;;WAEnB;;WAEA;;WAEA;;EAET,UAAU;;;;;;;;iBAWI,gBAAgB,eAAe,cAAc,iBAAiB,IAAI,aAAa;;;;;iBAiB/E;;;;;;;cCpCH,UAAQ,aAAA;;cAMR,UAAQ,aAAA;;cAMR,UAAA;EAAQ;;;cAKR,OAAK,aAAA;;cAGL,QAAA;EAAM;;;cAKN,UAAA;EAAQ;;;cAKR,UAAA;;;;;;;;UCrCI,MAAM;WACZ;EACT,SAAS,SAAS;EAClB,QAAQ,SAAS;EACjB,UAAU,YAAY,SAAS;;;;;;;;cASpB,IAAI;UACP;UACA;UACA;UACA;iBAEO,MAAM,4BAA4B,SAAS;;MAKtD,WAAW,MAAM;;EAKrB,SAAS,OAAO,MAAM;;;;;EAStB,cAAc,mBAAmB,iBAAiB;;EAWlD,MAAM;;EAQN,QAAQ;;EAcR,OAAO;;;;;;;;;;;;;;;;;cCxDI;;WAEF;;WAEA;;WAGA,eAAa;;WAEb,iBAAe;UAEhB;;;;;;;UAOA;cAEI,sBAAsB;;EAMlC,QAAQ;;EAOR,OAAO,kBAAkB;;EAezB,QAAQ;;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;;;;;;;;;iBA8BpC,uBACd,OAAO,OACP,WAAW,gBAAgB,OAAO,iBACjC"}
package/dist/index.d.ts CHANGED
@@ -103,6 +103,13 @@ declare class FSM<C = undefined> {
103
103
  *
104
104
  * Uses bitmask matching: entity archetype & requiredMask === requiredMask
105
105
  * and entity archetype & excludedMask === 0.
106
+ *
107
+ * Two ways to walk the matches:
108
+ * - `entities` — the live id array, for an indexed `for` loop. Allocates
109
+ * nothing; this is the form for systems and anything else that runs per frame.
110
+ * - `for...of` — the convenience form. It creates an iterator, and on Hermes
111
+ * (React Native) one `{ value, done }` object per entity per pass, so keep
112
+ * it off the frame path.
106
113
  */
107
114
  declare class Query {
108
115
  /** Bitmask of required components. */
@@ -113,10 +120,14 @@ declare class Query {
113
120
  readonly onEntityAdded: Signal<number>;
114
121
  /** Fires when an entity is removed from this query's results. */
115
122
  readonly onEntityRemoved: Signal<number>;
116
- /** Sorted array of matching entity IDs. */
117
- private entities;
118
- /** Set for O(1) membership check. */
119
- private entitySet;
123
+ private ids;
124
+ /**
125
+ * `entityId -> index into ids`. Serves membership *and* position, which
126
+ * is what makes removal O(1): the previous pair of a `Set` plus `indexOf`
127
+ * made every removal a linear scan, so churn cost grew as `n * removals`
128
+ * rather than with the number of removals.
129
+ */
130
+ private index;
120
131
  constructor(requiredMask: number, excludedMask: number);
121
132
  /** Check if an archetype matches this query. */
122
133
  matches(archetype: number): boolean;
@@ -124,20 +135,69 @@ declare class Query {
124
135
  _check(entityId: number, archetype: number): void;
125
136
  /** @internal — called by World when an entity is removed entirely. */
126
137
  _remove(entityId: number): void;
127
- /** Iterate matching entity IDs. */
138
+ /**
139
+ * O(1) removal: move the last element into the hole and shorten by one.
140
+ *
141
+ * Order-preserving removal cannot be O(1) here — `splice` shifts every later
142
+ * element, and a position map would then need every shifted index rewritten,
143
+ * so it costs the same scan it was meant to remove. A tombstone would keep
144
+ * order but puts a branch in iteration, which at realistic churn runs far
145
+ * more often than removal and would slow the steady-state path to speed up
146
+ * the rare one.
147
+ */
148
+ private swapRemove;
149
+ /**
150
+ * Matching entity IDs — the live array, not a copy, so reading it allocates
151
+ * nothing and it reflects every add and remove as it happens. Walk it by
152
+ * index on hot paths:
153
+ *
154
+ * const ids = query.entities;
155
+ * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }
156
+ *
157
+ * Because it is live, destroying an entity or changing its components mid-walk
158
+ * swap-removes from this array under the loop and skips an entity: collect
159
+ * first and act after, as the built-in systems do.
160
+ *
161
+ * Order is not guaranteed. Entities are appended as they begin matching and
162
+ * removed by swapping the last element into the hole, so the order reflects
163
+ * match history, not id. It was previously documented as "sorted", which was
164
+ * never true: `_check` has always plain-`push`ed, so an entity that starts
165
+ * matching later lands after entities with higher ids (spawn 1,2,3 then add
166
+ * the missing component to 3 first and the array reads `[3, 1, 2]`).
167
+ *
168
+ * The one consumer that cares is `render-system`, whose `sortByDrawOrder` is
169
+ * a *stable* insertion sort on `z` alone — so this order is the tie-break
170
+ * between equal-`z` sprites. It is deliberately not a guarantee: depend on
171
+ * `z`, not on the order entities happen to occupy here.
172
+ */
173
+ get entities(): readonly number[];
174
+ /**
175
+ * Iterate matching entity IDs. Convenience form: it allocates an iterator,
176
+ * and on Hermes a result object per entity — walk `entities` by index on
177
+ * hot paths.
178
+ */
128
179
  [Symbol.iterator](): IterableIterator<number>;
129
180
  /** Number of matching entities. */
130
181
  get count(): number;
131
182
  /** Check if an entity matches this query. */
132
183
  has(entityId: number): boolean;
133
184
  }
134
- /** Builder for creating queries with .with() / .without() chaining. */
185
+ /**
186
+ * Builder for creating queries with .with() / .without() chaining.
187
+ *
188
+ * Obtain one from `world.queryBuilder()`. `build()` hands the finished Query to
189
+ * the World it came from, which is what keeps it populated; the registration
190
+ * hook is a required constructor argument so a builder cannot exist without a
191
+ * World behind it, and the orphan `new QueryBuilder().build()` does not compile.
192
+ */
135
193
  declare class QueryBuilder {
136
194
  private required;
137
195
  private excluded;
196
+ private readonly register;
197
+ constructor(register: (q: Query) => void);
138
198
  with(...components: ComponentDef<unknown>[]): this;
139
199
  without(...components: ComponentDef<unknown>[]): this;
140
- /** Build the query (called internally by World). */
200
+ /** Build the query and register it with the owning World. */
141
201
  build(): Query;
142
202
  }
143
203
  //#endregion
@@ -191,6 +251,8 @@ declare class World {
191
251
  query(...components: ComponentDef<unknown>[]): Query;
192
252
  /** Create a QueryBuilder for complex queries (with/without). */
193
253
  queryBuilder(): QueryBuilder;
254
+ /** Track a query and populate it with the entities that already match. */
255
+ private register;
194
256
  /**
195
257
  * Dispose a query created by `query()` or `queryBuilder().build()`. Afterwards
196
258
  * the world stops updating it, so it no longer costs spawn/add/remove iteration
@@ -209,8 +271,6 @@ declare class World {
209
271
  removeSystem(fn: (world: World, dt: number) => void): void;
210
272
  /** Run all systems in priority order. */
211
273
  step(dt: number): void;
212
- /** @internal Register a query for auto-update. */
213
- _registerQuery(q: Query): void;
214
274
  }
215
275
  //#endregion
216
276
  //#region src/prefab.d.ts
@@ -218,11 +278,16 @@ declare class World {
218
278
  interface Prefab {
219
279
  readonly name: string;
220
280
  /** Spawn an entity with this prefab's components. */
221
- spawn(world: World, overrides?: Record<string, unknown>): number;
281
+ spawn(world: World): number;
222
282
  }
223
283
  /**
224
284
  * Define a prefab — a template for spawning entities with a fixed set of components.
225
285
  *
286
+ * Plain-object data is stored by reference and shared by every spawn; pass
287
+ * `() => T` for per-entity mutable state. This mirrors `world.add(entity, def,
288
+ * data)`, which stores the object it is given — so the object form is for
289
+ * data no entity will mutate, and the factory runs once per spawn.
290
+ *
226
291
  * @param name Debug name.
227
292
  * @param entries Array of [componentDef, data?] tuples.
228
293
  */
@@ -230,7 +295,7 @@ declare function definePrefab(name: string, ...entries: [ComponentDef<unknown>,
230
295
  //#endregion
231
296
  //#region src/system.d.ts
232
297
  /** A system function that processes entities matching a query. */
233
- type SystemFn = (entities: Query, dt: number, world: World) => void;
298
+ type SystemFn = (query: Query, dt: number, world: World) => void;
234
299
  /** A defined system with its query and function. */
235
300
  interface SystemDef {
236
301
  readonly query: Query;
@@ -246,10 +311,16 @@ interface SystemDef {
246
311
  *
247
312
  * Usage:
248
313
  * const q = world.query(Position, Velocity);
249
- * const moveSys = defineSystem(q, (entities, dt, world) => {
250
- * for (const id of entities) { ... }
314
+ * const moveSys = defineSystem(q, (query, dt, world) => {
315
+ * const ids = query.entities;
316
+ * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }
251
317
  * });
252
318
  * world.addSystem(moveSys._worldFn);
319
+ *
320
+ * Walk `query.entities` by index — that is the zero-alloc form. `for...of`
321
+ * over the query works too but allocates an iterator per loop (and, on
322
+ * Hermes, a result object per entity), which per system per frame is exactly
323
+ * what a system must not do.
253
324
  */
254
325
  declare function defineSystem(query: Query, fn: SystemFn): SystemDef;
255
326
  //#endregion
@@ -275,14 +346,19 @@ declare function createMovementSystem(world: World): SystemDef;
275
346
  * Entities whose remaining reaches <= 0 are collected, then onExpire is called
276
347
  * for each AFTER the read loop.
277
348
  *
278
- * Deferred removal: destroying inside a live for…of over query.entities splices
279
- * the array mid-iteration and would skip entities. Collect first, act after.
349
+ * Deferred removal: destroying inside a live walk of query.entities swap-removes
350
+ * from the array mid-iteration and would skip entities. Collect first, act after.
280
351
  *
281
352
  * The scratch array is closure-owned and grow-only — zero steady-state alloc.
282
353
  *
283
354
  * @param onExpire Destroy / pool policy — ecs never destroys on its own.
355
+ * @param query Optional caller-supplied Query. When omitted the system
356
+ * registers world.query(Lifetime) itself. Pass a narrower
357
+ * query to avoid scanning unrelated Lifetime holders and to
358
+ * share an already-registered query (eliminates duplicate
359
+ * World.query registration cost).
284
360
  */
285
- declare function createLifetimeSystem(world: World, onExpire: (entity: number, world: World) => void): SystemDef;
361
+ declare function createLifetimeSystem(world: World, onExpire: (entity: number, world: World) => void, query?: Query): SystemDef;
286
362
  /**
287
363
  * createBoundsCullSystem — culls entities whose Position falls outside bounds.
288
364
  * Reads bounds LIVE each frame so callers can mutate it to follow a camera.
@@ -294,8 +370,14 @@ declare function createLifetimeSystem(world: World, onExpire: (entity: number, w
294
370
  *
295
371
  * @param bounds Mutable bounding box read each frame.
296
372
  * @param onCull Destroy / pool policy — ecs never destroys on its own.
373
+ * @param query Optional caller-supplied Query. When omitted the system
374
+ * registers world.query(Position) itself, scanning all
375
+ * Position holders. Pass a narrower query (e.g. bullets
376
+ * only) to avoid scanning unrelated entities such as
377
+ * scrolling backgrounds, and to share an already-registered
378
+ * query with the caller.
297
379
  */
298
- declare function createBoundsCullSystem(world: World, bounds: CullBounds, onCull: (entity: number, world: World) => void): SystemDef;
380
+ declare function createBoundsCullSystem(world: World, bounds: CullBounds, onCull: (entity: number, world: World) => void, query?: Query): SystemDef;
299
381
  /**
300
382
  * createFollowerSystem — pins each Follower entity's Position to
301
383
  * target.Position + (offsetX, offsetY).
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/query.ts","../src/world.ts","../src/prefab.ts","../src/system.ts","../src/systems.ts"],"mappings":";;;;;;;;;;UAQiB,aAAa;;WAEnB;;WAEA;;WAEA;;EAET,UAAU;;;;;;;;iBAWI,gBAAgB,eAAe,cAAc,iBAAiB,IAAI,aAAa;;;;;iBAiB/E;;;;;;;cCpCH,UAAQ,aAAA;;cAMR,UAAQ,aAAA;;cAMR,UAAA;EAAQ;;;cAKR,OAAK,aAAA;;cAGL,QAAA;EAAM;;;cAKN,UAAA;EAAQ;;;cAKR,UAAA;;;;;;;;UCrCI,MAAM;WACZ;EACT,SAAS,SAAS;EAClB,QAAQ,SAAS;EACjB,UAAU,YAAY,SAAS;;;;;;;;cASpB,IAAI;UACP;UACA;UACA;UACA;iBAEO,MAAM,4BAA4B,SAAS;;MAKtD,WAAW,MAAM;;EAKrB,SAAS,OAAO,MAAM;;;;;EAStB,cAAc,mBAAmB,iBAAiB;;EAWlD,MAAM;;EAQN,QAAQ;;EAcR,OAAO;;;;;;;;;;cC/DI;;WAEF;;WAEA;;WAGA,eAAa;;WAE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d,OAAO,OACP,WAAW,gBAAgB,OAAO,iBACjC"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/query.ts","../src/world.ts","../src/prefab.ts","../src/system.ts","../src/systems.ts"],"mappings":";;;;;;;;;;UAQiB,aAAa;;WAEnB;;WAEA;;WAEA;;EAET,UAAU;;;;;;;;iBAWI,gBAAgB,eAAe,cAAc,iBAAiB,IAAI,aAAa;;;;;iBAiB/E;;;;;;;cCpCH,UAAQ,aAAA;;cAMR,UAAQ,aAAA;;cAMR,UAAA;EAAQ;;;cAKR,OAAK,aAAA;;cAGL,QAAA;EAAM;;;cAKN,UAAA;EAAQ;;;cAKR,UAAA;;;;;;;;UCrCI,MAAM;WACZ;EACT,SAAS,SAAS;EAClB,QAAQ,SAAS;EACjB,UAAU,YAAY,SAAS;;;;;;;;cASpB,IAAI;UACP;UACA;UACA;UACA;iBAEO,MAAM,4BAA4B,SAAS;;MAKtD,WAAW,MAAM;;EAKrB,SAAS,OAAO,MAAM;;;;;EAStB,cAAc,mBAAmB,iBAAiB;;EAWlD,MAAM;;EAQN,QAAQ;;EAcR,OAAO;;;;;;;;;;;;;;;;;cCxDI;;WAEF;;WAEA;;WAGA,eAAa;;WAEb,iBAAe;UAEhB;;;;;;;UAOA;cAEI,sBAAsB;;EAMlC,QAAQ;;EAOR,OAAO,kBAAkB;;EAezB,QAAQ;;;;;;;;;;;UAiBA;;;;;;;;;;;;;;;;;;;;;;;;;MAkCJ;;;;;;GASH,OAAO,aAAa;;MAKjB;;EAKJ,IAAI;;;;;;;;;;cAaO;UACH;UACA;mBACS;cAEL,WAAW,GAAG;EAI1B,QAAQ,YAAY;EAOpB,WAAW,YAAY;;EAQvB,SAAS;;;;;;;;;;cClKE;UACH;UACA;UACA;UACA;UACA;UACA;UACA;UAIA;;EAGR;;EAOA,QAAQ;;EAuBR,IAAI,GAAG,kBAAkB,KAAK,aAAa,IAAI,OAAO;;EA4BtD,OAAO,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