@flare-engine/ecs 0.3.1 → 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/dist/index.mjs CHANGED
@@ -124,6 +124,11 @@ var FSM = class {
124
124
  /**
125
125
  * Define a prefab — a template for spawning entities with a fixed set of components.
126
126
  *
127
+ * Plain-object data is stored by reference and shared by every spawn; pass
128
+ * `() => T` for per-entity mutable state. This mirrors `world.add(entity, def,
129
+ * data)`, which stores the object it is given — so the object form is for
130
+ * data no entity will mutate, and the factory runs once per spawn.
131
+ *
127
132
  * @param name Debug name.
128
133
  * @param entries Array of [componentDef, data?] tuples.
129
134
  */
@@ -151,6 +156,13 @@ function definePrefab(name, ...entries) {
151
156
  *
152
157
  * Uses bitmask matching: entity archetype & requiredMask === requiredMask
153
158
  * and entity archetype & excludedMask === 0.
159
+ *
160
+ * Two ways to walk the matches:
161
+ * - `entities` — the live id array, for an indexed `for` loop. Allocates
162
+ * nothing; this is the form for systems and anything else that runs per frame.
163
+ * - `for...of` — the convenience form. It creates an iterator, and on Hermes
164
+ * (React Native) one `{ value, done }` object per entity per pass, so keep
165
+ * it off the frame path.
154
166
  */
155
167
  var Query = class {
156
168
  /** Bitmask of required components. */
@@ -161,10 +173,14 @@ var Query = class {
161
173
  onEntityAdded = new Signal();
162
174
  /** Fires when an entity is removed from this query's results. */
163
175
  onEntityRemoved = new Signal();
164
- /** Sorted array of matching entity IDs. */
165
- entities = [];
166
- /** Set for O(1) membership check. */
167
- entitySet = /* @__PURE__ */ new Set();
176
+ ids = [];
177
+ /**
178
+ * `entityId -> index into ids`. Serves membership *and* position, which
179
+ * is what makes removal O(1): the previous pair of a `Set` plus `indexOf`
180
+ * made every removal a linear scan, so churn cost grew as `n * removals`
181
+ * rather than with the number of removals.
182
+ */
183
+ index = /* @__PURE__ */ new Map();
168
184
  constructor(requiredMask, excludedMask) {
169
185
  this.requiredMask = requiredMask;
170
186
  this.excludedMask = excludedMask;
@@ -176,44 +192,101 @@ var Query = class {
176
192
  /** @internal — called by World when an entity's archetype changes. */
177
193
  _check(entityId, archetype) {
178
194
  const isMatch = this.matches(archetype);
179
- const wasMatch = this.entitySet.has(entityId);
195
+ const wasMatch = this.index.has(entityId);
180
196
  if (isMatch && !wasMatch) {
181
- this.entitySet.add(entityId);
182
- this.entities.push(entityId);
197
+ this.index.set(entityId, this.ids.length);
198
+ this.ids.push(entityId);
183
199
  this.onEntityAdded.emit(entityId);
184
200
  } else if (!isMatch && wasMatch) {
185
- this.entitySet.delete(entityId);
186
- const idx = this.entities.indexOf(entityId);
187
- if (idx !== -1) this.entities.splice(idx, 1);
201
+ this.swapRemove(entityId);
188
202
  this.onEntityRemoved.emit(entityId);
189
203
  }
190
204
  }
191
205
  /** @internal — called by World when an entity is removed entirely. */
192
206
  _remove(entityId) {
193
- if (this.entitySet.has(entityId)) {
194
- this.entitySet.delete(entityId);
195
- const idx = this.entities.indexOf(entityId);
196
- if (idx !== -1) this.entities.splice(idx, 1);
207
+ if (this.index.has(entityId)) {
208
+ this.swapRemove(entityId);
197
209
  this.onEntityRemoved.emit(entityId);
198
210
  }
199
211
  }
200
- /** Iterate matching entity IDs. */
212
+ /**
213
+ * O(1) removal: move the last element into the hole and shorten by one.
214
+ *
215
+ * Order-preserving removal cannot be O(1) here — `splice` shifts every later
216
+ * element, and a position map would then need every shifted index rewritten,
217
+ * so it costs the same scan it was meant to remove. A tombstone would keep
218
+ * order but puts a branch in iteration, which at realistic churn runs far
219
+ * more often than removal and would slow the steady-state path to speed up
220
+ * the rare one.
221
+ */
222
+ swapRemove(entityId) {
223
+ const idx = this.index.get(entityId);
224
+ const last = this.ids.length - 1;
225
+ const lastId = this.ids[last];
226
+ this.ids[idx] = lastId;
227
+ this.index.set(lastId, idx);
228
+ this.ids.pop();
229
+ this.index.delete(entityId);
230
+ }
231
+ /**
232
+ * Matching entity IDs — the live array, not a copy, so reading it allocates
233
+ * nothing and it reflects every add and remove as it happens. Walk it by
234
+ * index on hot paths:
235
+ *
236
+ * const ids = query.entities;
237
+ * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }
238
+ *
239
+ * Because it is live, destroying an entity or changing its components mid-walk
240
+ * swap-removes from this array under the loop and skips an entity: collect
241
+ * first and act after, as the built-in systems do.
242
+ *
243
+ * Order is not guaranteed. Entities are appended as they begin matching and
244
+ * removed by swapping the last element into the hole, so the order reflects
245
+ * match history, not id. It was previously documented as "sorted", which was
246
+ * never true: `_check` has always plain-`push`ed, so an entity that starts
247
+ * matching later lands after entities with higher ids (spawn 1,2,3 then add
248
+ * the missing component to 3 first and the array reads `[3, 1, 2]`).
249
+ *
250
+ * The one consumer that cares is `render-system`, whose `sortByDrawOrder` is
251
+ * a *stable* insertion sort on `z` alone — so this order is the tie-break
252
+ * between equal-`z` sprites. It is deliberately not a guarantee: depend on
253
+ * `z`, not on the order entities happen to occupy here.
254
+ */
255
+ get entities() {
256
+ return this.ids;
257
+ }
258
+ /**
259
+ * Iterate matching entity IDs. Convenience form: it allocates an iterator,
260
+ * and on Hermes a result object per entity — walk `entities` by index on
261
+ * hot paths.
262
+ */
201
263
  [Symbol.iterator]() {
202
- return this.entities[Symbol.iterator]();
264
+ return this.ids[Symbol.iterator]();
203
265
  }
204
266
  /** Number of matching entities. */
205
267
  get count() {
206
- return this.entities.length;
268
+ return this.ids.length;
207
269
  }
208
270
  /** Check if an entity matches this query. */
209
271
  has(entityId) {
210
- return this.entitySet.has(entityId);
272
+ return this.index.has(entityId);
211
273
  }
212
274
  };
213
- /** Builder for creating queries with .with() / .without() chaining. */
275
+ /**
276
+ * Builder for creating queries with .with() / .without() chaining.
277
+ *
278
+ * Obtain one from `world.queryBuilder()`. `build()` hands the finished Query to
279
+ * the World it came from, which is what keeps it populated; the registration
280
+ * hook is a required constructor argument so a builder cannot exist without a
281
+ * World behind it, and the orphan `new QueryBuilder().build()` does not compile.
282
+ */
214
283
  var QueryBuilder = class {
215
284
  required = 0;
216
285
  excluded = 0;
286
+ register;
287
+ constructor(register) {
288
+ this.register = register;
289
+ }
217
290
  with(...components) {
218
291
  for (const c of components) this.required |= c.bit;
219
292
  return this;
@@ -222,9 +295,11 @@ var QueryBuilder = class {
222
295
  for (const c of components) this.excluded |= c.bit;
223
296
  return this;
224
297
  }
225
- /** Build the query (called internally by World). */
298
+ /** Build the query and register it with the owning World. */
226
299
  build() {
227
- return new Query(this.required, this.excluded);
300
+ const q = new Query(this.required, this.excluded);
301
+ this.register(q);
302
+ return q;
228
303
  }
229
304
  };
230
305
  //#endregion
@@ -237,10 +312,16 @@ var QueryBuilder = class {
237
312
  *
238
313
  * Usage:
239
314
  * const q = world.query(Position, Velocity);
240
- * const moveSys = defineSystem(q, (entities, dt, world) => {
241
- * for (const id of entities) { ... }
315
+ * const moveSys = defineSystem(q, (query, dt, world) => {
316
+ * const ids = query.entities;
317
+ * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }
242
318
  * });
243
319
  * world.addSystem(moveSys._worldFn);
320
+ *
321
+ * Walk `query.entities` by index — that is the zero-alloc form. `for...of`
322
+ * over the query works too but allocates an iterator per loop (and, on
323
+ * Hermes, a result object per entity), which per system per frame is exactly
324
+ * what a system must not do.
244
325
  */
245
326
  function defineSystem(query, fn) {
246
327
  const worldFn = (world, dt) => {
@@ -260,8 +341,10 @@ function defineSystem(query, fn) {
260
341
  * Recommended priority: run BEFORE createFollowerSystem (0).
261
342
  */
262
343
  function createMovementSystem(world) {
263
- return defineSystem(world.query(Position, Velocity), (entities, dt, w) => {
264
- for (const id of entities) {
344
+ return defineSystem(world.query(Position, Velocity), (query, dt, w) => {
345
+ const ids = query.entities;
346
+ for (let i = 0; i < ids.length; i++) {
347
+ const id = ids[i];
265
348
  const pos = w.get(id, Position);
266
349
  const vel = w.get(id, Velocity);
267
350
  pos.x += vel.x * dt;
@@ -274,8 +357,8 @@ function createMovementSystem(world) {
274
357
  * Entities whose remaining reaches <= 0 are collected, then onExpire is called
275
358
  * for each AFTER the read loop.
276
359
  *
277
- * Deferred removal: destroying inside a live for…of over query.entities splices
278
- * the array mid-iteration and would skip entities. Collect first, act after.
360
+ * Deferred removal: destroying inside a live walk of query.entities swap-removes
361
+ * from the array mid-iteration and would skip entities. Collect first, act after.
279
362
  *
280
363
  * The scratch array is closure-owned and grow-only — zero steady-state alloc.
281
364
  *
@@ -289,9 +372,11 @@ function createMovementSystem(world) {
289
372
  function createLifetimeSystem(world, onExpire, query) {
290
373
  const q = query ?? world.query(Lifetime);
291
374
  const scratch = [];
292
- return defineSystem(q, (entities, dt, w) => {
375
+ return defineSystem(q, (query, dt, w) => {
293
376
  scratch.length = 0;
294
- for (const id of entities) {
377
+ const ids = query.entities;
378
+ for (let i = 0; i < ids.length; i++) {
379
+ const id = ids[i];
295
380
  const life = w.get(id, Lifetime);
296
381
  life.remaining -= dt;
297
382
  if (life.remaining <= 0) scratch.push(id);
@@ -320,9 +405,11 @@ function createLifetimeSystem(world, onExpire, query) {
320
405
  function createBoundsCullSystem(world, bounds, onCull, query) {
321
406
  const q = query ?? world.query(Position);
322
407
  const scratch = [];
323
- return defineSystem(q, (entities, _dt, w) => {
408
+ return defineSystem(q, (query, _dt, w) => {
324
409
  scratch.length = 0;
325
- for (const id of entities) {
410
+ const ids = query.entities;
411
+ for (let i = 0; i < ids.length; i++) {
412
+ const id = ids[i];
326
413
  const pos = w.get(id, Position);
327
414
  if (pos.x < bounds.minX || pos.x > bounds.maxX || pos.y < bounds.minY || pos.y > bounds.maxY) scratch.push(id);
328
415
  }
@@ -338,8 +425,10 @@ function createBoundsCullSystem(world, bounds, onCull, query) {
338
425
  * position is already integrated before the follower snaps to it.
339
426
  */
340
427
  function createFollowerSystem(world) {
341
- return defineSystem(world.query(Position, Follower), (entities, _dt, w) => {
342
- for (const id of entities) {
428
+ return defineSystem(world.query(Position, Follower), (query, _dt, w) => {
429
+ const ids = query.entities;
430
+ for (let i = 0; i < ids.length; i++) {
431
+ const id = ids[i];
343
432
  const follower = w.get(id, Follower);
344
433
  const t = w.get(follower.target, Position);
345
434
  if (t === void 0) continue;
@@ -366,9 +455,11 @@ function createFollowerSystem(world) {
366
455
  function createOrphanCullSystem(world, onOrphan) {
367
456
  const q = world.query(Follower);
368
457
  const scratch = [];
369
- return defineSystem(q, (entities, _dt, w) => {
458
+ return defineSystem(q, (query, _dt, w) => {
370
459
  scratch.length = 0;
371
- for (const id of entities) {
460
+ const ids = query.entities;
461
+ for (let i = 0; i < ids.length; i++) {
462
+ const id = ids[i];
372
463
  const follower = w.get(id, Follower);
373
464
  if (!w.exists(follower.target)) scratch.push(id);
374
465
  }
@@ -482,13 +573,17 @@ var World = class {
482
573
  let mask = 0;
483
574
  for (const c of components) mask |= c.bit;
484
575
  const q = new Query(mask, 0);
485
- this.queries.push(q);
486
- for (const [entityId, arch] of this.archetypes) q._check(entityId, arch);
576
+ this.register(q);
487
577
  return q;
488
578
  }
489
579
  /** Create a QueryBuilder for complex queries (with/without). */
490
580
  queryBuilder() {
491
- return new _WorldQueryBuilder(this);
581
+ return new QueryBuilder((q) => this.register(q));
582
+ }
583
+ /** Track a query and populate it with the entities that already match. */
584
+ register(q) {
585
+ this.queries.push(q);
586
+ for (const [entityId, arch] of this.archetypes) q._check(entityId, arch);
492
587
  }
493
588
  /**
494
589
  * Dispose a query created by `query()` or `queryBuilder().build()`. Afterwards
@@ -540,26 +635,6 @@ var World = class {
540
635
  }
541
636
  for (const sys of this.systems) sys.fn(this, dt);
542
637
  }
543
- /** @internal Register a query for auto-update. */
544
- _registerQuery(q) {
545
- this.queries.push(q);
546
- for (const [entityId, arch] of this.archetypes) q._check(entityId, arch);
547
- }
548
- };
549
- /**
550
- * Internal query builder that auto-registers with a World.
551
- */
552
- var _WorldQueryBuilder = class extends QueryBuilder {
553
- world;
554
- constructor(world) {
555
- super();
556
- this.world = world;
557
- }
558
- build() {
559
- const q = super.build();
560
- this.world._registerQuery(q);
561
- return q;
562
- }
563
638
  };
564
639
  //#endregion
565
640
  export { FSM, Follower, Lifetime, Parent, Position, Query, QueryBuilder, Rotation, Scale, Velocity, World, _resetComponentIds, createBoundsCullSystem, createFollowerSystem, createLifetimeSystem, createMovementSystem, createOrphanCullSystem, defineComponent, definePrefab, defineSystem };
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/prefab.ts","../src/query.ts","../src/system.ts","../src/systems.ts","../src/world.ts"],"sourcesContent":["/**\n * Component definition and factory.\n *\n * Components are plain data objects. Each component type gets a unique\n * bit for archetype-based query matching.\n */\n\n/** A unique component definition. */\nexport interface ComponentDef<T> {\n /** Internal unique ID (auto-assigned). */\n readonly id: number;\n /** Bitmask for this component (1 << id). */\n readonly bit: number;\n /** Component name for debugging. */\n readonly name: string;\n /** Create a new instance with default values. */\n create(): T;\n}\n\nlet nextComponentId = 0;\n\n/**\n * Define a new component type.\n *\n * @param name Debug name for the component.\n * @param defaults Factory function returning default values, or undefined for tag components.\n */\nexport function defineComponent<T = undefined>(name: string, defaults?: () => T): ComponentDef<T> {\n const id = nextComponentId++;\n if (id >= 32) {\n throw new Error(`Maximum 32 component types exceeded (defining \"${name}\")`);\n }\n return {\n id,\n bit: 1 << id,\n name,\n create: defaults ?? (() => undefined as T),\n };\n}\n\n/**\n * Reset the component ID counter. Only for testing.\n * @internal\n */\nexport function _resetComponentIds(): void {\n nextComponentId = 0;\n}\n","import type { Vec2 } from '@flare-engine/math';\nimport { defineComponent } from './component.js';\n\n/**\n * Built-in ECS components using @flare-engine/math types.\n */\n\n/** 2D position component. */\nexport const Position = defineComponent<Vec2>('Position', () => ({\n x: 0,\n y: 0,\n}));\n\n/** 2D velocity component. */\nexport const Velocity = defineComponent<Vec2>('Velocity', () => ({\n x: 0,\n y: 0,\n}));\n\n/** Rotation in radians. */\nexport const Rotation = defineComponent<{ angle: number }>('Rotation', () => ({\n angle: 0,\n}));\n\n/** 2D scale component. */\nexport const Scale = defineComponent<Vec2>('Scale', () => ({ x: 1, y: 1 }));\n\n/** Parent entity reference. */\nexport const Parent = defineComponent<{ entity: number }>('Parent', () => ({\n entity: 0,\n}));\n\n/** Countdown timer in seconds; entity expires when remaining reaches 0. */\nexport const Lifetime = defineComponent<{ remaining: number }>('Lifetime', () => ({\n remaining: 0,\n}));\n\n/** Pins an entity's position to a target entity plus a fixed offset. */\nexport const Follower = defineComponent<{ target: number; offsetX: number; offsetY: number }>(\n 'Follower',\n () => ({ target: 0, offsetX: 0, offsetY: 0 }),\n);\n","/** A state in the FSM. */\nexport interface State<C = undefined> {\n readonly name: string;\n onEnter?(context: C): void;\n onExit?(context: C): void;\n onUpdate?(dt: number, context: C): void;\n}\n\n/**\n * Lightweight finite state machine. ~100 LOC.\n *\n * Manages named states with onEnter/onExit/onUpdate hooks\n * and string-keyed transitions.\n */\nexport class FSM<C = undefined> {\n private _current: State<C> | undefined;\n private _states = new Map<string, State<C>>();\n private _transitions = new Map<string, Map<string, string>>();\n private _context: C;\n\n constructor(...args: C extends undefined ? [] : [context: C]) {\n this._context = args[0] as C;\n }\n\n /** The currently active state, or undefined if none. */\n get current(): State<C> | undefined {\n return this._current;\n }\n\n /** Register a state. */\n addState(state: State<C>): this {\n this._states.set(state.name, state);\n return this;\n }\n\n /**\n * Register a transition.\n * When `trigger` fires in `fromState`, transition to `toState`.\n */\n addTransition(fromState: string, trigger: string, toState: string): this {\n let map = this._transitions.get(fromState);\n if (!map) {\n map = new Map();\n this._transitions.set(fromState, map);\n }\n map.set(trigger, toState);\n return this;\n }\n\n /** Set the initial state (calls onEnter). */\n start(stateName: string): void {\n const state = this._states.get(stateName);\n if (!state) return;\n this._current = state;\n state.onEnter?.(this._context);\n }\n\n /** Fire a trigger. If a matching transition exists, switch states. */\n trigger(name: string): void {\n if (!this._current) return;\n const transitions = this._transitions.get(this._current.name);\n if (!transitions) return;\n const target = transitions.get(name);\n if (target === undefined) return;\n const next = this._states.get(target);\n if (!next) return;\n this._current.onExit?.(this._context);\n this._current = next;\n next.onEnter?.(this._context);\n }\n\n /** Update the current state. */\n update(dt: number): void {\n this._current?.onUpdate?.(dt, this._context);\n }\n}\n","import type { ComponentDef } from './component.js';\nimport type { World } from './world.js';\n\n/** A component entry in a prefab definition. */\ninterface PrefabEntry<T> {\n def: ComponentDef<T>;\n data?: T | (() => T);\n}\n\n/** A prefab factory that spawns entities with pre-defined components. */\nexport interface Prefab {\n readonly name: string;\n /** Spawn an entity with this prefab's components. */\n spawn(world: World, overrides?: Record<string, unknown>): number;\n}\n\n/**\n * Define a prefab — a template for spawning entities with a fixed set of components.\n *\n * @param name Debug name.\n * @param entries Array of [componentDef, data?] tuples.\n */\nexport function definePrefab(\n name: string,\n ...entries: [ComponentDef<unknown>, (unknown | (() => unknown))?][]\n): Prefab {\n const components: PrefabEntry<unknown>[] = entries.map(([def, data]) => ({\n def,\n data,\n }));\n\n return {\n name,\n spawn(world: World): number {\n const entity = world.spawn();\n for (const entry of components) {\n const data =\n typeof entry.data === 'function' ? (entry.data as () => unknown)() : entry.data;\n world.add(entity, entry.def, data);\n }\n return entity;\n },\n };\n}\n","import { Signal } from '@flare-engine/events';\nimport type { ComponentDef } from './component.js';\n\n/**\n * Query matches entities based on component archetypes.\n *\n * Uses bitmask matching: entity archetype & requiredMask === requiredMask\n * and entity archetype & excludedMask === 0.\n */\nexport class Query {\n /** Bitmask of required components. */\n readonly requiredMask: number;\n /** Bitmask of excluded components. */\n readonly excludedMask: number;\n\n /** Fires when an entity is added to this query's results. */\n readonly onEntityAdded = new Signal<number>();\n /** Fires when an entity is removed from this query's results. */\n readonly onEntityRemoved = new Signal<number>();\n\n /** Sorted array of matching entity IDs. */\n private entities: number[] = [];\n /** Set for O(1) membership check. */\n private entitySet = new Set<number>();\n\n constructor(requiredMask: number, excludedMask: number) {\n this.requiredMask = requiredMask;\n this.excludedMask = excludedMask;\n }\n\n /** Check if an archetype matches this query. */\n matches(archetype: number): boolean {\n return (\n (archetype & this.requiredMask) === this.requiredMask && (archetype & this.excludedMask) === 0\n );\n }\n\n /** @internal — called by World when an entity's archetype changes. */\n _check(entityId: number, archetype: number): void {\n const isMatch = this.matches(archetype);\n const wasMatch = this.entitySet.has(entityId);\n\n if (isMatch && !wasMatch) {\n this.entitySet.add(entityId);\n this.entities.push(entityId);\n this.onEntityAdded.emit(entityId);\n } else if (!isMatch && wasMatch) {\n this.entitySet.delete(entityId);\n const idx = this.entities.indexOf(entityId);\n if (idx !== -1) this.entities.splice(idx, 1);\n this.onEntityRemoved.emit(entityId);\n }\n }\n\n /** @internal — called by World when an entity is removed entirely. */\n _remove(entityId: number): void {\n if (this.entitySet.has(entityId)) {\n this.entitySet.delete(entityId);\n const idx = this.entities.indexOf(entityId);\n if (idx !== -1) this.entities.splice(idx, 1);\n this.onEntityRemoved.emit(entityId);\n }\n }\n\n /** Iterate matching entity IDs. */\n [Symbol.iterator](): IterableIterator<number> {\n return this.entities[Symbol.iterator]();\n }\n\n /** Number of matching entities. */\n get count(): number {\n return this.entities.length;\n }\n\n /** Check if an entity matches this query. */\n has(entityId: number): boolean {\n return this.entitySet.has(entityId);\n }\n}\n\n/** Builder for creating queries with .with() / .without() chaining. */\nexport class QueryBuilder {\n private required = 0;\n private excluded = 0;\n\n with(...components: ComponentDef<unknown>[]): this {\n for (const c of components) {\n this.required |= c.bit;\n }\n return this;\n }\n\n without(...components: ComponentDef<unknown>[]): this {\n for (const c of components) {\n this.excluded |= c.bit;\n }\n return this;\n }\n\n /** Build the query (called internally by World). */\n build(): Query {\n return new Query(this.required, this.excluded);\n }\n}\n","import type { Query } from './query.js';\nimport type { World } from './world.js';\n\n/** A system function that processes entities matching a query. */\nexport type SystemFn = (entities: Query, dt: number, world: World) => void;\n\n/** A defined system with its query and function. */\nexport interface SystemDef {\n readonly query: Query;\n readonly fn: SystemFn;\n /** The wrapper registered on the World (used for removal). */\n readonly _worldFn: (world: World, dt: number) => void;\n}\n\n/**\n * Define a system that processes entities matching a query.\n *\n * Returns a SystemDef that can be added to a World via world.addSystem().\n * The system function receives the query's matching entities, dt, and world.\n *\n * Usage:\n * const q = world.query(Position, Velocity);\n * const moveSys = defineSystem(q, (entities, dt, world) => {\n * for (const id of entities) { ... }\n * });\n * world.addSystem(moveSys._worldFn);\n */\nexport function defineSystem(query: Query, fn: SystemFn): SystemDef {\n const worldFn = (world: World, dt: number) => {\n fn(query, dt, world);\n };\n return { query, fn, _worldFn: worldFn };\n}\n","import { Follower, Lifetime, Position, Velocity } from './components.js';\nimport type { Query } from './query.js';\nimport type { SystemDef } from './system.js';\nimport { defineSystem } from './system.js';\nimport type { World } from './world.js';\n\n/**\n * Plain camera-space bounding box used by createBoundsCullSystem.\n * Keep plain numbers — do NOT import physics AABB/Bounds (layer inversion).\n */\nexport interface CullBounds {\n readonly minX: number;\n readonly minY: number;\n readonly maxX: number;\n readonly maxY: number;\n}\n\n/**\n * createMovementSystem — integrates Position by Velocity * dt each frame.\n *\n * Recommended priority: run BEFORE createFollowerSystem (0).\n */\nexport function createMovementSystem(world: World): SystemDef {\n const q = world.query(Position, Velocity);\n return defineSystem(q, (entities, dt, w) => {\n for (const id of entities) {\n const pos = w.get(id, Position)!;\n const vel = w.get(id, Velocity)!;\n pos.x += vel.x * dt;\n pos.y += vel.y * dt;\n }\n });\n}\n\n/**\n * createLifetimeSystem — decrements Lifetime.remaining each frame.\n * Entities whose remaining reaches <= 0 are collected, then onExpire is called\n * for each AFTER the read loop.\n *\n * Deferred removal: destroying inside a live for…of over query.entities splices\n * the array mid-iteration and would skip entities. Collect first, act after.\n *\n * The scratch array is closure-owned and grow-only — zero steady-state alloc.\n *\n * @param onExpire Destroy / pool policy — ecs never destroys on its own.\n * @param query Optional caller-supplied Query. When omitted the system\n * registers world.query(Lifetime) itself. Pass a narrower\n * query to avoid scanning unrelated Lifetime holders and to\n * share an already-registered query (eliminates duplicate\n * World.query registration cost).\n */\nexport function createLifetimeSystem(\n world: World,\n onExpire: (entity: number, world: World) => void,\n query?: Query,\n): SystemDef {\n const q = query ?? world.query(Lifetime);\n const scratch: number[] = [];\n return defineSystem(q, (entities, dt, w) => {\n scratch.length = 0;\n for (const id of entities) {\n const life = w.get(id, Lifetime)!;\n life.remaining -= dt;\n if (life.remaining <= 0) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onExpire(scratch[i]!, w);\n }\n });\n}\n\n/**\n * createBoundsCullSystem — culls entities whose Position falls outside bounds.\n * Reads bounds LIVE each frame so callers can mutate it to follow a camera.\n * Entities outside are collected, then onCull is called for each after the read loop.\n *\n * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.\n *\n * Recommended priority: run AFTER createMovementSystem and createFollowerSystem.\n *\n * @param bounds Mutable bounding box read each frame.\n * @param onCull Destroy / pool policy — ecs never destroys on its own.\n * @param query Optional caller-supplied Query. When omitted the system\n * registers world.query(Position) itself, scanning all\n * Position holders. Pass a narrower query (e.g. bullets\n * only) to avoid scanning unrelated entities such as\n * scrolling backgrounds, and to share an already-registered\n * query with the caller.\n */\nexport function createBoundsCullSystem(\n world: World,\n bounds: CullBounds,\n onCull: (entity: number, world: World) => void,\n query?: Query,\n): SystemDef {\n const q = query ?? world.query(Position);\n const scratch: number[] = [];\n return defineSystem(q, (entities, _dt, w) => {\n scratch.length = 0;\n for (const id of entities) {\n const pos = w.get(id, Position)!;\n if (\n pos.x < bounds.minX ||\n pos.x > bounds.maxX ||\n pos.y < bounds.minY ||\n pos.y > bounds.maxY\n ) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onCull(scratch[i]!, w);\n }\n });\n}\n\n/**\n * createFollowerSystem — pins each Follower entity's Position to\n * target.Position + (offsetX, offsetY).\n * If the target is gone or has no Position, the entity is silently skipped.\n *\n * Recommended priority: run AFTER createMovementSystem (1) so the target's\n * position is already integrated before the follower snaps to it.\n */\nexport function createFollowerSystem(world: World): SystemDef {\n const q = world.query(Position, Follower);\n return defineSystem(q, (entities, _dt, w) => {\n for (const id of entities) {\n const follower = w.get(id, Follower)!;\n const t = w.get(follower.target, Position);\n if (t === undefined) continue;\n const pos = w.get(id, Position)!;\n pos.x = t.x + follower.offsetX;\n pos.y = t.y + follower.offsetY;\n }\n });\n}\n\n/**\n * createOrphanCullSystem — fires onOrphan for each Follower whose target entity\n * no longer exists. Does NOT move or destroy anything itself.\n *\n * Split from createFollowerSystem so games that want to orphan-cull can opt in\n * without coupling destruction to the follower pin logic.\n *\n * Recommended priority: run AFTER createFollowerSystem (2) so the follower is\n * pinned before orphans are detected.\n *\n * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.\n *\n * @param onOrphan Called once per orphaned entity after the read loop.\n */\nexport function createOrphanCullSystem(\n world: World,\n onOrphan: (entity: number, world: World) => void,\n): SystemDef {\n const q = world.query(Follower);\n const scratch: number[] = [];\n return defineSystem(q, (entities, _dt, w) => {\n scratch.length = 0;\n for (const id of entities) {\n const follower = w.get(id, Follower)!;\n if (!w.exists(follower.target)) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onOrphan(scratch[i]!, w);\n }\n });\n}\n","import type { ComponentDef } from './component.js';\nimport { Query, QueryBuilder } from './query.js';\n\n/**\n * World is the central ECS container.\n *\n * Entities are integer IDs. Components are stored in per-component Maps.\n * Archetype bitmasks enable fast query matching.\n */\nexport class World {\n private nextId = 1;\n private archetypes = new Map<number, number>(); // entityId → bitmask\n private componentStores = new Map<number, Map<number, unknown>>(); // componentId → (entityId → data)\n private queries: Query[] = [];\n private queryIterDepth = 0;\n private pendingQueryRemove: Query[] | null = null;\n private systems: {\n fn: (world: World, dt: number) => void;\n priority: number;\n }[] = [];\n private systemsSorted = false;\n\n /** Create a new entity. Returns the entity ID. */\n spawn(): number {\n const id = this.nextId++;\n this.archetypes.set(id, 0);\n return id;\n }\n\n /** Remove an entity and all its components. */\n destroy(entityId: number): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n // Remove from all component stores\n for (const [, store] of this.componentStores) {\n store.delete(entityId);\n }\n\n this.archetypes.delete(entityId);\n\n // Notify queries (deferring any removeQuery until the loop unwinds)\n this.queryIterDepth++;\n try {\n for (const query of this.queries) {\n query._remove(entityId);\n }\n } finally {\n this.endQueryIteration();\n }\n }\n\n /** Add a component to an entity. */\n add<T>(entityId: number, def: ComponentDef<T>, data?: T): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n // Store component data\n let store = this.componentStores.get(def.id);\n if (!store) {\n store = new Map();\n this.componentStores.set(def.id, store);\n }\n store.set(entityId, data !== undefined ? data : def.create());\n\n // Update archetype\n const newArch = arch | def.bit;\n this.archetypes.set(entityId, newArch);\n\n // Notify queries (deferring any removeQuery until the loop unwinds)\n this.queryIterDepth++;\n try {\n for (const query of this.queries) {\n query._check(entityId, newArch);\n }\n } finally {\n this.endQueryIteration();\n }\n }\n\n /** Remove a component from an entity. */\n remove<T>(entityId: number, def: ComponentDef<T>): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n const store = this.componentStores.get(def.id);\n if (store) store.delete(entityId);\n\n const newArch = arch & ~def.bit;\n this.archetypes.set(entityId, newArch);\n\n // Notify queries (deferring any removeQuery until the loop unwinds)\n this.queryIterDepth++;\n try {\n for (const query of this.queries) {\n query._check(entityId, newArch);\n }\n } finally {\n this.endQueryIteration();\n }\n }\n\n /** Get component data for an entity. */\n get<T>(entityId: number, def: ComponentDef<T>): T | undefined {\n const store = this.componentStores.get(def.id);\n return store?.get(entityId) as T | undefined;\n }\n\n /** Check if entity has a component. */\n has(entityId: number, def: ComponentDef<unknown>): boolean {\n const arch = this.archetypes.get(entityId);\n return arch !== undefined && (arch & def.bit) !== 0;\n }\n\n /** Check if entity exists. */\n exists(entityId: number): boolean {\n return this.archetypes.has(entityId);\n }\n\n /** Number of live entities. */\n get entityCount(): number {\n return this.archetypes.size;\n }\n\n /**\n * Walk every live entity ID. Iterates the live archetype map directly, with no\n * array snapshot. Archetype changes (add/remove component) keep the same entity\n * keys, so iteration is stable across them. Destroying entities inside the\n * callback is safe, but entities spawned inside it are visited in the same pass\n * (live Map iteration) — don't spawn from within.\n */\n forEachEntity(cb: (entity: number) => void): void {\n for (const entityId of this.archetypes.keys()) {\n cb(entityId);\n }\n }\n\n /**\n * Create a query. Queries auto-update as entities change.\n * Use the QueryBuilder-style chaining:\n * world.query(Position, Velocity)\n * Or use the builder:\n * world.queryBuilder().with(Position).without(Dead).build()\n */\n query(...components: ComponentDef<unknown>[]): Query {\n let mask = 0;\n for (const c of components) {\n mask |= c.bit;\n }\n const q = new Query(mask, 0);\n this.queries.push(q);\n\n // Populate with existing entities\n for (const [entityId, arch] of this.archetypes) {\n q._check(entityId, arch);\n }\n\n return q;\n }\n\n /** Create a QueryBuilder for complex queries (with/without). */\n queryBuilder(): QueryBuilder {\n return new _WorldQueryBuilder(this);\n }\n\n /**\n * Dispose a query created by `query()` or `queryBuilder().build()`. Afterwards\n * the world stops updating it, so it no longer costs spawn/add/remove iteration\n * time. The query is left inert — drop the reference to let it be collected.\n *\n * Safe to call from within a Query signal handler (e.g. a one-shot\n * `onEntityAdded` that disposes its own query): the removal is deferred until\n * the in-progress mutation finishes iterating, so no other query is skipped.\n */\n removeQuery(q: Query): void {\n if (this.queryIterDepth > 0) {\n if (this.pendingQueryRemove === null) this.pendingQueryRemove = [];\n this.pendingQueryRemove.push(q);\n return;\n }\n const idx = this.queries.indexOf(q);\n if (idx !== -1) this.queries.splice(idx, 1);\n }\n\n /** @internal End a query-notify loop; flush any removeQuery deferred during it. */\n private endQueryIteration(): void {\n this.queryIterDepth--;\n if (this.queryIterDepth === 0 && this.pendingQueryRemove !== null) {\n for (const q of this.pendingQueryRemove) {\n const idx = this.queries.indexOf(q);\n if (idx !== -1) this.queries.splice(idx, 1);\n }\n this.pendingQueryRemove.length = 0;\n }\n }\n\n /** Register a system function. Lower priority runs first. */\n addSystem(fn: (world: World, dt: number) => void, priority = 0): void {\n this.systems.push({ fn, priority });\n this.systemsSorted = false;\n }\n\n /** Remove a system. */\n removeSystem(fn: (world: World, dt: number) => void): void {\n const idx = this.systems.findIndex((s) => s.fn === fn);\n if (idx !== -1) this.systems.splice(idx, 1);\n }\n\n /** Run all systems in priority order. */\n step(dt: number): void {\n if (!this.systemsSorted) {\n this.systems.sort((a, b) => a.priority - b.priority);\n this.systemsSorted = true;\n }\n for (const sys of this.systems) {\n sys.fn(this, dt);\n }\n }\n\n /** @internal Register a query for auto-update. */\n _registerQuery(q: Query): void {\n this.queries.push(q);\n // Populate with existing entities\n for (const [entityId, arch] of this.archetypes) {\n q._check(entityId, arch);\n }\n }\n}\n\n/**\n * Internal query builder that auto-registers with a World.\n */\nclass _WorldQueryBuilder extends QueryBuilder {\n private world: World;\n\n constructor(world: World) {\n super();\n this.world = world;\n }\n\n override build(): Query {\n const q = super.build();\n this.world._registerQuery(q);\n return q;\n }\n}\n"],"mappings":";;AAmBA,IAAI,kBAAkB;;;;;;;AAQtB,SAAgB,gBAA+B,MAAc,UAAqC;CAChG,MAAM,KAAK;CACX,IAAI,MAAM,IACR,MAAM,IAAI,MAAM,kDAAkD,KAAK,GAAG;CAE5E,OAAO;EACL;EACA,KAAK,KAAK;EACV;EACA,QAAQ,mBAAmB,KAAA;CAC7B;AACF;;;;;AAMA,SAAgB,qBAA2B;CACzC,kBAAkB;AACpB;;;;;;;ACtCA,MAAa,WAAW,gBAAsB,mBAAmB;CAC/D,GAAG;CACH,GAAG;AACL,EAAE;;AAGF,MAAa,WAAW,gBAAsB,mBAAmB;CAC/D,GAAG;CACH,GAAG;AACL,EAAE;;AAGF,MAAa,WAAW,gBAAmC,mBAAmB,EAC5E,OAAO,EACT,EAAE;;AAGF,MAAa,QAAQ,gBAAsB,gBAAgB;CAAE,GAAG;CAAG,GAAG;AAAE,EAAE;;AAG1E,MAAa,SAAS,gBAAoC,iBAAiB,EACzE,QAAQ,EACV,EAAE;;AAGF,MAAa,WAAW,gBAAuC,mBAAmB,EAChF,WAAW,EACb,EAAE;;AAGF,MAAa,WAAW,gBACtB,mBACO;CAAE,QAAQ;CAAG,SAAS;CAAG,SAAS;A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Y,OAAc;EACxB,MAAM;EACN,KAAK,QAAQ;CACf;CAEA,QAAwB;EACtB,MAAM,IAAI,MAAM,MAAM;EACtB,KAAK,MAAM,eAAe,CAAC;EAC3B,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/component.ts","../src/components.ts","../src/fsm.ts","../src/prefab.ts","../src/query.ts","../src/system.ts","../src/systems.ts","../src/world.ts"],"sourcesContent":["/**\n * Component definition and factory.\n *\n * Components are plain data objects. Each component type gets a unique\n * bit for archetype-based query matching.\n */\n\n/** A unique component definition. */\nexport interface ComponentDef<T> {\n /** Internal unique ID (auto-assigned). */\n readonly id: number;\n /** Bitmask for this component (1 << id). */\n readonly bit: number;\n /** Component name for debugging. */\n readonly name: string;\n /** Create a new instance with default values. */\n create(): T;\n}\n\nlet nextComponentId = 0;\n\n/**\n * Define a new component type.\n *\n * @param name Debug name for the component.\n * @param defaults Factory function returning default values, or undefined for tag components.\n */\nexport function defineComponent<T = undefined>(name: string, defaults?: () => T): ComponentDef<T> {\n const id = nextComponentId++;\n if (id >= 32) {\n throw new Error(`Maximum 32 component types exceeded (defining \"${name}\")`);\n }\n return {\n id,\n bit: 1 << id,\n name,\n create: defaults ?? (() => undefined as T),\n };\n}\n\n/**\n * Reset the component ID counter. Only for testing.\n * @internal\n */\nexport function _resetComponentIds(): void {\n nextComponentId = 0;\n}\n","import type { Vec2 } from '@flare-engine/math';\nimport { defineComponent } from './component.js';\n\n/**\n * Built-in ECS components using @flare-engine/math types.\n */\n\n/** 2D position component. */\nexport const Position = defineComponent<Vec2>('Position', () => ({\n x: 0,\n y: 0,\n}));\n\n/** 2D velocity component. */\nexport const Velocity = defineComponent<Vec2>('Velocity', () => ({\n x: 0,\n y: 0,\n}));\n\n/** Rotation in radians. */\nexport const Rotation = defineComponent<{ angle: number }>('Rotation', () => ({\n angle: 0,\n}));\n\n/** 2D scale component. */\nexport const Scale = defineComponent<Vec2>('Scale', () => ({ x: 1, y: 1 }));\n\n/** Parent entity reference. */\nexport const Parent = defineComponent<{ entity: number }>('Parent', () => ({\n entity: 0,\n}));\n\n/** Countdown timer in seconds; entity expires when remaining reaches 0. */\nexport const Lifetime = defineComponent<{ remaining: number }>('Lifetime', () => ({\n remaining: 0,\n}));\n\n/** Pins an entity's position to a target entity plus a fixed offset. */\nexport const Follower = defineComponent<{ target: number; offsetX: number; offsetY: number }>(\n 'Follower',\n () => ({ target: 0, offsetX: 0, offsetY: 0 }),\n);\n","/** A state in the FSM. */\nexport interface State<C = undefined> {\n readonly name: string;\n onEnter?(context: C): void;\n onExit?(context: C): void;\n onUpdate?(dt: number, context: C): void;\n}\n\n/**\n * Lightweight finite state machine. ~100 LOC.\n *\n * Manages named states with onEnter/onExit/onUpdate hooks\n * and string-keyed transitions.\n */\nexport class FSM<C = undefined> {\n private _current: State<C> | undefined;\n private _states = new Map<string, State<C>>();\n private _transitions = new Map<string, Map<string, string>>();\n private _context: C;\n\n constructor(...args: C extends undefined ? [] : [context: C]) {\n this._context = args[0] as C;\n }\n\n /** The currently active state, or undefined if none. */\n get current(): State<C> | undefined {\n return this._current;\n }\n\n /** Register a state. */\n addState(state: State<C>): this {\n this._states.set(state.name, state);\n return this;\n }\n\n /**\n * Register a transition.\n * When `trigger` fires in `fromState`, transition to `toState`.\n */\n addTransition(fromState: string, trigger: string, toState: string): this {\n let map = this._transitions.get(fromState);\n if (!map) {\n map = new Map();\n this._transitions.set(fromState, map);\n }\n map.set(trigger, toState);\n return this;\n }\n\n /** Set the initial state (calls onEnter). */\n start(stateName: string): void {\n const state = this._states.get(stateName);\n if (!state) return;\n this._current = state;\n state.onEnter?.(this._context);\n }\n\n /** Fire a trigger. If a matching transition exists, switch states. */\n trigger(name: string): void {\n if (!this._current) return;\n const transitions = this._transitions.get(this._current.name);\n if (!transitions) return;\n const target = transitions.get(name);\n if (target === undefined) return;\n const next = this._states.get(target);\n if (!next) return;\n this._current.onExit?.(this._context);\n this._current = next;\n next.onEnter?.(this._context);\n }\n\n /** Update the current state. */\n update(dt: number): void {\n this._current?.onUpdate?.(dt, this._context);\n }\n}\n","import type { ComponentDef } from './component.js';\nimport type { World } from './world.js';\n\n/** A component entry in a prefab definition. */\ninterface PrefabEntry<T> {\n def: ComponentDef<T>;\n data?: T | (() => T);\n}\n\n/** A prefab factory that spawns entities with pre-defined components. */\nexport interface Prefab {\n readonly name: string;\n /** Spawn an entity with this prefab's components. */\n spawn(world: World): number;\n}\n\n/**\n * Define a prefab — a template for spawning entities with a fixed set of components.\n *\n * Plain-object data is stored by reference and shared by every spawn; pass\n * `() => T` for per-entity mutable state. This mirrors `world.add(entity, def,\n * data)`, which stores the object it is given — so the object form is for\n * data no entity will mutate, and the factory runs once per spawn.\n *\n * @param name Debug name.\n * @param entries Array of [componentDef, data?] tuples.\n */\nexport function definePrefab(\n name: string,\n ...entries: [ComponentDef<unknown>, (unknown | (() => unknown))?][]\n): Prefab {\n const components: PrefabEntry<unknown>[] = entries.map(([def, data]) => ({\n def,\n data,\n }));\n\n return {\n name,\n spawn(world: World): number {\n const entity = world.spawn();\n for (const entry of components) {\n const data =\n typeof entry.data === 'function' ? (entry.data as () => unknown)() : entry.data;\n world.add(entity, entry.def, data);\n }\n return entity;\n },\n };\n}\n","import { Signal } from '@flare-engine/events';\nimport type { ComponentDef } from './component.js';\n\n/**\n * Query matches entities based on component archetypes.\n *\n * Uses bitmask matching: entity archetype & requiredMask === requiredMask\n * and entity archetype & excludedMask === 0.\n *\n * Two ways to walk the matches:\n * - `entities` — the live id array, for an indexed `for` loop. Allocates\n * nothing; this is the form for systems and anything else that runs per frame.\n * - `for...of` — the convenience form. It creates an iterator, and on Hermes\n * (React Native) one `{ value, done }` object per entity per pass, so keep\n * it off the frame path.\n */\nexport class Query {\n /** Bitmask of required components. */\n readonly requiredMask: number;\n /** Bitmask of excluded components. */\n readonly excludedMask: number;\n\n /** Fires when an entity is added to this query's results. */\n readonly onEntityAdded = new Signal<number>();\n /** Fires when an entity is removed from this query's results. */\n readonly onEntityRemoved = new Signal<number>();\n\n private ids: number[] = [];\n /**\n * `entityId -> index into ids`. Serves membership *and* position, which\n * is what makes removal O(1): the previous pair of a `Set` plus `indexOf`\n * made every removal a linear scan, so churn cost grew as `n * removals`\n * rather than with the number of removals.\n */\n private index = new Map<number, number>();\n\n constructor(requiredMask: number, excludedMask: number) {\n this.requiredMask = requiredMask;\n this.excludedMask = excludedMask;\n }\n\n /** Check if an archetype matches this query. */\n matches(archetype: number): boolean {\n return (\n (archetype & this.requiredMask) === this.requiredMask && (archetype & this.excludedMask) === 0\n );\n }\n\n /** @internal — called by World when an entity's archetype changes. */\n _check(entityId: number, archetype: number): void {\n const isMatch = this.matches(archetype);\n const wasMatch = this.index.has(entityId);\n\n if (isMatch && !wasMatch) {\n this.index.set(entityId, this.ids.length);\n this.ids.push(entityId);\n this.onEntityAdded.emit(entityId);\n } else if (!isMatch && wasMatch) {\n this.swapRemove(entityId);\n this.onEntityRemoved.emit(entityId);\n }\n }\n\n /** @internal — called by World when an entity is removed entirely. */\n _remove(entityId: number): void {\n if (this.index.has(entityId)) {\n this.swapRemove(entityId);\n this.onEntityRemoved.emit(entityId);\n }\n }\n\n /**\n * O(1) removal: move the last element into the hole and shorten by one.\n *\n * Order-preserving removal cannot be O(1) here — `splice` shifts every later\n * element, and a position map would then need every shifted index rewritten,\n * so it costs the same scan it was meant to remove. A tombstone would keep\n * order but puts a branch in iteration, which at realistic churn runs far\n * more often than removal and would slow the steady-state path to speed up\n * the rare one.\n */\n private swapRemove(entityId: number): void {\n const idx = this.index.get(entityId) as number;\n const last = this.ids.length - 1;\n const lastId = this.ids[last] as number;\n this.ids[idx] = lastId;\n this.index.set(lastId, idx);\n this.ids.pop();\n this.index.delete(entityId);\n }\n\n /**\n * Matching entity IDs — the live array, not a copy, so reading it allocates\n * nothing and it reflects every add and remove as it happens. Walk it by\n * index on hot paths:\n *\n * const ids = query.entities;\n * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }\n *\n * Because it is live, destroying an entity or changing its components mid-walk\n * swap-removes from this array under the loop and skips an entity: collect\n * first and act after, as the built-in systems do.\n *\n * Order is not guaranteed. Entities are appended as they begin matching and\n * removed by swapping the last element into the hole, so the order reflects\n * match history, not id. It was previously documented as \"sorted\", which was\n * never true: `_check` has always plain-`push`ed, so an entity that starts\n * matching later lands after entities with higher ids (spawn 1,2,3 then add\n * the missing component to 3 first and the array reads `[3, 1, 2]`).\n *\n * The one consumer that cares is `render-system`, whose `sortByDrawOrder` is\n * a *stable* insertion sort on `z` alone — so this order is the tie-break\n * between equal-`z` sprites. It is deliberately not a guarantee: depend on\n * `z`, not on the order entities happen to occupy here.\n */\n get entities(): readonly number[] {\n return this.ids;\n }\n\n /**\n * Iterate matching entity IDs. Convenience form: it allocates an iterator,\n * and on Hermes a result object per entity — walk `entities` by index on\n * hot paths.\n */\n [Symbol.iterator](): IterableIterator<number> {\n return this.ids[Symbol.iterator]();\n }\n\n /** Number of matching entities. */\n get count(): number {\n return this.ids.length;\n }\n\n /** Check if an entity matches this query. */\n has(entityId: number): boolean {\n return this.index.has(entityId);\n }\n}\n\n/**\n * Builder for creating queries with .with() / .without() chaining.\n *\n * Obtain one from `world.queryBuilder()`. `build()` hands the finished Query to\n * the World it came from, which is what keeps it populated; the registration\n * hook is a required constructor argument so a builder cannot exist without a\n * World behind it, and the orphan `new QueryBuilder().build()` does not compile.\n */\nexport class QueryBuilder {\n private required = 0;\n private excluded = 0;\n private readonly register: (q: Query) => void;\n\n constructor(register: (q: Query) => void) {\n this.register = register;\n }\n\n with(...components: ComponentDef<unknown>[]): this {\n for (const c of components) {\n this.required |= c.bit;\n }\n return this;\n }\n\n without(...components: ComponentDef<unknown>[]): this {\n for (const c of components) {\n this.excluded |= c.bit;\n }\n return this;\n }\n\n /** Build the query and register it with the owning World. */\n build(): Query {\n const q = new Query(this.required, this.excluded);\n this.register(q);\n return q;\n }\n}\n","import type { Query } from './query.js';\nimport type { World } from './world.js';\n\n/** A system function that processes entities matching a query. */\nexport type SystemFn = (query: Query, dt: number, world: World) => void;\n\n/** A defined system with its query and function. */\nexport interface SystemDef {\n readonly query: Query;\n readonly fn: SystemFn;\n /** The wrapper registered on the World (used for removal). */\n readonly _worldFn: (world: World, dt: number) => void;\n}\n\n/**\n * Define a system that processes entities matching a query.\n *\n * Returns a SystemDef that can be added to a World via world.addSystem().\n * The system function receives the query's matching entities, dt, and world.\n *\n * Usage:\n * const q = world.query(Position, Velocity);\n * const moveSys = defineSystem(q, (query, dt, world) => {\n * const ids = query.entities;\n * for (let i = 0; i < ids.length; i++) { const id = ids[i]!; ... }\n * });\n * world.addSystem(moveSys._worldFn);\n *\n * Walk `query.entities` by index — that is the zero-alloc form. `for...of`\n * over the query works too but allocates an iterator per loop (and, on\n * Hermes, a result object per entity), which per system per frame is exactly\n * what a system must not do.\n */\nexport function defineSystem(query: Query, fn: SystemFn): SystemDef {\n const worldFn = (world: World, dt: number) => {\n fn(query, dt, world);\n };\n return { query, fn, _worldFn: worldFn };\n}\n","import { Follower, Lifetime, Position, Velocity } from './components.js';\nimport type { Query } from './query.js';\nimport type { SystemDef } from './system.js';\nimport { defineSystem } from './system.js';\nimport type { World } from './world.js';\n\n/**\n * Plain camera-space bounding box used by createBoundsCullSystem.\n * Keep plain numbers — do NOT import physics AABB/Bounds (layer inversion).\n */\nexport interface CullBounds {\n readonly minX: number;\n readonly minY: number;\n readonly maxX: number;\n readonly maxY: number;\n}\n\n/**\n * createMovementSystem — integrates Position by Velocity * dt each frame.\n *\n * Recommended priority: run BEFORE createFollowerSystem (0).\n */\nexport function createMovementSystem(world: World): SystemDef {\n const q = world.query(Position, Velocity);\n return defineSystem(q, (query, dt, w) => {\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const pos = w.get(id, Position)!;\n const vel = w.get(id, Velocity)!;\n pos.x += vel.x * dt;\n pos.y += vel.y * dt;\n }\n });\n}\n\n/**\n * createLifetimeSystem — decrements Lifetime.remaining each frame.\n * Entities whose remaining reaches <= 0 are collected, then onExpire is called\n * for each AFTER the read loop.\n *\n * Deferred removal: destroying inside a live walk of query.entities swap-removes\n * from the array mid-iteration and would skip entities. Collect first, act after.\n *\n * The scratch array is closure-owned and grow-only — zero steady-state alloc.\n *\n * @param onExpire Destroy / pool policy — ecs never destroys on its own.\n * @param query Optional caller-supplied Query. When omitted the system\n * registers world.query(Lifetime) itself. Pass a narrower\n * query to avoid scanning unrelated Lifetime holders and to\n * share an already-registered query (eliminates duplicate\n * World.query registration cost).\n */\nexport function createLifetimeSystem(\n world: World,\n onExpire: (entity: number, world: World) => void,\n query?: Query,\n): SystemDef {\n const q = query ?? world.query(Lifetime);\n const scratch: number[] = [];\n return defineSystem(q, (query, dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const life = w.get(id, Lifetime)!;\n life.remaining -= dt;\n if (life.remaining <= 0) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onExpire(scratch[i]!, w);\n }\n });\n}\n\n/**\n * createBoundsCullSystem — culls entities whose Position falls outside bounds.\n * Reads bounds LIVE each frame so callers can mutate it to follow a camera.\n * Entities outside are collected, then onCull is called for each after the read loop.\n *\n * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.\n *\n * Recommended priority: run AFTER createMovementSystem and createFollowerSystem.\n *\n * @param bounds Mutable bounding box read each frame.\n * @param onCull Destroy / pool policy — ecs never destroys on its own.\n * @param query Optional caller-supplied Query. When omitted the system\n * registers world.query(Position) itself, scanning all\n * Position holders. Pass a narrower query (e.g. bullets\n * only) to avoid scanning unrelated entities such as\n * scrolling backgrounds, and to share an already-registered\n * query with the caller.\n */\nexport function createBoundsCullSystem(\n world: World,\n bounds: CullBounds,\n onCull: (entity: number, world: World) => void,\n query?: Query,\n): SystemDef {\n const q = query ?? world.query(Position);\n const scratch: number[] = [];\n return defineSystem(q, (query, _dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const pos = w.get(id, Position)!;\n if (\n pos.x < bounds.minX ||\n pos.x > bounds.maxX ||\n pos.y < bounds.minY ||\n pos.y > bounds.maxY\n ) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onCull(scratch[i]!, w);\n }\n });\n}\n\n/**\n * createFollowerSystem — pins each Follower entity's Position to\n * target.Position + (offsetX, offsetY).\n * If the target is gone or has no Position, the entity is silently skipped.\n *\n * Recommended priority: run AFTER createMovementSystem (1) so the target's\n * position is already integrated before the follower snaps to it.\n */\nexport function createFollowerSystem(world: World): SystemDef {\n const q = world.query(Position, Follower);\n return defineSystem(q, (query, _dt, w) => {\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const follower = w.get(id, Follower)!;\n const t = w.get(follower.target, Position);\n if (t === undefined) continue;\n const pos = w.get(id, Position)!;\n pos.x = t.x + follower.offsetX;\n pos.y = t.y + follower.offsetY;\n }\n });\n}\n\n/**\n * createOrphanCullSystem — fires onOrphan for each Follower whose target entity\n * no longer exists. Does NOT move or destroy anything itself.\n *\n * Split from createFollowerSystem so games that want to orphan-cull can opt in\n * without coupling destruction to the follower pin logic.\n *\n * Recommended priority: run AFTER createFollowerSystem (2) so the follower is\n * pinned before orphans are detected.\n *\n * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.\n *\n * @param onOrphan Called once per orphaned entity after the read loop.\n */\nexport function createOrphanCullSystem(\n world: World,\n onOrphan: (entity: number, world: World) => void,\n): SystemDef {\n const q = world.query(Follower);\n const scratch: number[] = [];\n return defineSystem(q, (query, _dt, w) => {\n scratch.length = 0;\n const ids = query.entities;\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n const follower = w.get(id, Follower)!;\n if (!w.exists(follower.target)) {\n scratch.push(id);\n }\n }\n for (let i = 0; i < scratch.length; i++) {\n onOrphan(scratch[i]!, w);\n }\n });\n}\n","import type { ComponentDef } from './component.js';\nimport { Query, QueryBuilder } from './query.js';\n\n/**\n * World is the central ECS container.\n *\n * Entities are integer IDs. Components are stored in per-component Maps.\n * Archetype bitmasks enable fast query matching.\n */\nexport class World {\n private nextId = 1;\n private archetypes = new Map<number, number>(); // entityId → bitmask\n private componentStores = new Map<number, Map<number, unknown>>(); // componentId → (entityId → data)\n private queries: Query[] = [];\n private queryIterDepth = 0;\n private pendingQueryRemove: Query[] | null = null;\n private systems: {\n fn: (world: World, dt: number) => void;\n priority: number;\n }[] = [];\n private systemsSorted = false;\n\n /** Create a new entity. Returns the entity ID. */\n spawn(): number {\n const id = this.nextId++;\n this.archetypes.set(id, 0);\n return id;\n }\n\n /** Remove an entity and all its components. */\n destroy(entityId: number): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n // Remove from all component stores\n for (const [, store] of this.componentStores) {\n store.delete(entityId);\n }\n\n this.archetypes.delete(entityId);\n\n // Notify queries (deferring any removeQuery until the loop unwinds)\n this.queryIterDepth++;\n try {\n for (const query of this.queries) {\n query._remove(entityId);\n }\n } finally {\n this.endQueryIteration();\n }\n }\n\n /** Add a component to an entity. */\n add<T>(entityId: number, def: ComponentDef<T>, data?: T): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n // Store component data\n let store = this.componentStores.get(def.id);\n if (!store) {\n store = new Map();\n this.componentStores.set(def.id, store);\n }\n store.set(entityId, data !== undefined ? data : def.create());\n\n // Update archetype\n const newArch = arch | def.bit;\n this.archetypes.set(entityId, newArch);\n\n // Notify queries (deferring any removeQuery until the loop unwinds)\n this.queryIterDepth++;\n try {\n for (const query of this.queries) {\n query._check(entityId, newArch);\n }\n } finally {\n this.endQueryIteration();\n }\n }\n\n /** Remove a component from an entity. */\n remove<T>(entityId: number, def: ComponentDef<T>): void {\n const arch = this.archetypes.get(entityId);\n if (arch === undefined) return;\n\n const store = this.componentStores.get(def.id);\n if (store) store.delete(entityId);\n\n const newArch = arch & ~def.bit;\n this.archetypes.set(entityId, newArch);\n\n // Notify queries (deferring any removeQuery until the loop unwinds)\n this.queryIterDepth++;\n try {\n for (const query of this.queries) {\n query._check(entityId, newArch);\n }\n } finally {\n this.endQueryIteration();\n }\n }\n\n /** Get component data for an entity. */\n get<T>(entityId: number, def: ComponentDef<T>): T | undefined {\n const store = this.componentStores.get(def.id);\n return store?.get(entityId) as T | undefined;\n }\n\n /** Check if entity has a component. */\n has(entityId: number, def: ComponentDef<unknown>): boolean {\n const arch = this.archetypes.get(entityId);\n return arch !== undefined && (arch & def.bit) !== 0;\n }\n\n /** Check if entity exists. */\n exists(entityId: number): boolean {\n return this.archetypes.has(entityId);\n }\n\n /** Number of live entities. */\n get entityCount(): number {\n return this.archetypes.size;\n }\n\n /**\n * Walk every live entity ID. Iterates the live archetype map directly, with no\n * array snapshot. Archetype changes (add/remove component) keep the same entity\n * keys, so iteration is stable across them. Destroying entities inside the\n * callback is safe, but entities spawned inside it are visited in the same pass\n * (live Map iteration) — don't spawn from within.\n */\n forEachEntity(cb: (entity: number) => void): void {\n for (const entityId of this.archetypes.keys()) {\n cb(entityId);\n }\n }\n\n /**\n * Create a query. Queries auto-update as entities change.\n * Use the QueryBuilder-style chaining:\n * world.query(Position, Velocity)\n * Or use the builder:\n * world.queryBuilder().with(Position).without(Dead).build()\n */\n query(...components: ComponentDef<unknown>[]): Query {\n let mask = 0;\n for (const c of components) {\n mask |= c.bit;\n }\n const q = new Query(mask, 0);\n this.register(q);\n return q;\n }\n\n /** Create a QueryBuilder for complex queries (with/without). */\n queryBuilder(): QueryBuilder {\n return new QueryBuilder((q) => this.register(q));\n }\n\n /** Track a query and populate it with the entities that already match. */\n private register(q: Query): void {\n this.queries.push(q);\n for (const [entityId, arch] of this.archetypes) {\n q._check(entityId, arch);\n }\n }\n\n /**\n * Dispose a query created by `query()` or `queryBuilder().build()`. Afterwards\n * the world stops updating it, so it no longer costs spawn/add/remove iteration\n * time. The query is left inert — drop the reference to let it be collected.\n *\n * Safe to call from within a Query signal handler (e.g. a one-shot\n * `onEntityAdded` that disposes its own query): the removal is deferred until\n * the in-progress mutation finishes iterating, so no other query is skipped.\n */\n removeQuery(q: Query): void {\n if (this.queryIterDepth > 0) {\n if (this.pendingQueryRemove === null) this.pendingQueryRemove = [];\n this.pendingQueryRemove.push(q);\n return;\n }\n const idx = this.queries.indexOf(q);\n if (idx !== -1) this.queries.splice(idx, 1);\n }\n\n /** @internal End a query-notify loop; flush any removeQuery deferred during it. */\n private endQueryIteration(): void {\n this.queryIterDepth--;\n if (this.queryIterDepth === 0 && this.pendingQueryRemove !== null) {\n for (const q of this.pendingQueryRemove) {\n const idx = this.queries.indexOf(q);\n if (idx !== -1) this.queries.splice(idx, 1);\n }\n this.pendingQueryRemove.length = 0;\n }\n }\n\n /** Register a system function. Lower priority runs first. */\n addSystem(fn: (world: World, dt: number) => void, priority = 0): void {\n this.systems.push({ fn, priority });\n this.systemsSorted = false;\n }\n\n /** Remove a system. */\n removeSystem(fn: (world: World, dt: number) => void): void {\n const idx = this.systems.findIndex((s) => s.fn === fn);\n if (idx !== -1) this.systems.splice(idx, 1);\n }\n\n /** Run all systems in priority order. */\n step(dt: number): void {\n if (!this.systemsSorted) {\n this.systems.sort((a, b) => a.priority - b.priority);\n this.systemsSorted = true;\n }\n for (const sys of this.systems) {\n sys.fn(this, dt);\n }\n }\n}\n"],"mappings":";;AAmBA,IAAI,kBAAkB;;;;;;;AAQtB,SAAgB,gBAA+B,MAAc,UAAqC;CAChG,MAAM,KAAK;CACX,IAAI,MAAM,IACR,MAAM,IAAI,MAAM,kDAAkD,KAAK,GAAG;CAE5E,OAAO;EACL;EACA,KAAK,KAAK;EACV;EACA,QAAQ,mBAAmB,KAAA;CAC7B;AACF;;;;;AAMA,SAAgB,qBAA2B;CACzC,kBAAkB;AACpB;;;;;;;ACtCA,MAAa,WAAW,gBAAsB,mBAAmB;CAC/D,GAAG;CACH,GAAG;AACL,EAAE;;AAGF,MAAa,WAAW,gBAAsB,mBAAmB;CAC/D,GA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AAC;GAC9B;EACF;EACA,MAAM,MAAM,KAAK,QAAQ,QAAQ,CAAC;EAClC,IAAI,QAAQ,IAAI,KAAK,QAAQ,OAAO,KAAK,CAAC;CAC5C;;CAGA,oBAAkC;EAChC,KAAK;EACL,IAAI,KAAK,mBAAmB,KAAK,KAAK,uBAAuB,MAAM;GACjE,KAAK,MAAM,KAAK,KAAK,oBAAoB;IACvC,MAAM,MAAM,KAAK,QAAQ,QAAQ,CAAC;IAClC,IAAI,QAAQ,IAAI,KAAK,QAAQ,OAAO,KAAK,CAAC;GAC5C;GACA,KAAK,mBAAmB,SAAS;EACnC;CACF;;CAGA,UAAU,IAAwC,WAAW,GAAS;EACpE,KAAK,QAAQ,KAAK;GAAE;GAAI;EAAS,CAAC;EAClC,KAAK,gBAAgB;CACvB;;CAGA,aAAa,IAA8C;EACzD,MAAM,MAAM,KAAK,QAAQ,WAAW,MAAM,EAAE,OAAO,EAAE;EACrD,IAAI,QAAQ,IAAI,KAAK,QAAQ,OAAO,KAAK,CAAC;CAC5C;;CAGA,KAAK,IAAkB;EACrB,IAAI,CAAC,KAAK,eAAe;GACvB,KAAK,QAAQ,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;GACnD,KAAK,gBAAgB;EACvB;EACA,KAAK,MAAM,OAAO,KAAK,SACrB,IAAI,GAAG,MAAM,EAAE;CAEnB;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flare-engine/ecs",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Entity-Component-System with archetype queries",
5
5
  "keywords": ["flare-engine", "ecs", "entity-component-system"],
6
6
  "license": "Apache-2.0",
@@ -37,8 +37,8 @@
37
37
  "typecheck": "tsc --noEmit"
38
38
  },
39
39
  "dependencies": {
40
- "@flare-engine/events": "^0.3.1",
41
- "@flare-engine/math": "^0.3.1"
40
+ "@flare-engine/events": "^0.4.0",
41
+ "@flare-engine/math": "^0.4.0"
42
42
  },
43
43
  "engines": {
44
44
  "node": ">=20"