@flare-engine/ecs 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { Signal } from '@flare-engine/events';
2
- import { Vec2 } from '@flare-engine/math';
3
-
1
+ import { Signal } from "@flare-engine/events";
2
+ import { Vec2 } from "@flare-engine/math";
3
+ //#region src/component.d.ts
4
4
  /**
5
5
  * Component definition and factory.
6
6
  *
@@ -9,14 +9,14 @@ import { Vec2 } from '@flare-engine/math';
9
9
  */
10
10
  /** A unique component definition. */
11
11
  interface ComponentDef<T> {
12
- /** Internal unique ID (auto-assigned). */
13
- readonly id: number;
14
- /** Bitmask for this component (1 << id). */
15
- readonly bit: number;
16
- /** Component name for debugging. */
17
- readonly name: string;
18
- /** Create a new instance with default values. */
19
- create(): T;
12
+ /** Internal unique ID (auto-assigned). */
13
+ readonly id: number;
14
+ /** Bitmask for this component (1 << id). */
15
+ readonly bit: number;
16
+ /** Component name for debugging. */
17
+ readonly name: string;
18
+ /** Create a new instance with default values. */
19
+ create(): T;
20
20
  }
21
21
  /**
22
22
  * Define a new component type.
@@ -30,7 +30,74 @@ declare function defineComponent<T = undefined>(name: string, defaults?: () => T
30
30
  * @internal
31
31
  */
32
32
  declare function _resetComponentIds(): void;
33
-
33
+ //#endregion
34
+ //#region src/components.d.ts
35
+ /**
36
+ * Built-in ECS components using @flare-engine/math types.
37
+ */
38
+ /** 2D position component. */
39
+ declare const Position: ComponentDef<Vec2>;
40
+ /** 2D velocity component. */
41
+ declare const Velocity: ComponentDef<Vec2>;
42
+ /** Rotation in radians. */
43
+ declare const Rotation: ComponentDef<{
44
+ angle: number;
45
+ }>;
46
+ /** 2D scale component. */
47
+ declare const Scale: ComponentDef<Vec2>;
48
+ /** Parent entity reference. */
49
+ declare const Parent: ComponentDef<{
50
+ entity: number;
51
+ }>;
52
+ /** Countdown timer in seconds; entity expires when remaining reaches 0. */
53
+ declare const Lifetime: ComponentDef<{
54
+ remaining: number;
55
+ }>;
56
+ /** Pins an entity's position to a target entity plus a fixed offset. */
57
+ declare const Follower: ComponentDef<{
58
+ target: number;
59
+ offsetX: number;
60
+ offsetY: number;
61
+ }>;
62
+ //#endregion
63
+ //#region src/fsm.d.ts
64
+ /** A state in the FSM. */
65
+ interface State<C = undefined> {
66
+ readonly name: string;
67
+ onEnter?(context: C): void;
68
+ onExit?(context: C): void;
69
+ onUpdate?(dt: number, context: C): void;
70
+ }
71
+ /**
72
+ * Lightweight finite state machine. ~100 LOC.
73
+ *
74
+ * Manages named states with onEnter/onExit/onUpdate hooks
75
+ * and string-keyed transitions.
76
+ */
77
+ declare class FSM<C = undefined> {
78
+ private _current;
79
+ private _states;
80
+ private _transitions;
81
+ private _context;
82
+ constructor(...args: C extends undefined ? [] : [context: C]);
83
+ /** The currently active state, or undefined if none. */
84
+ get current(): State<C> | undefined;
85
+ /** Register a state. */
86
+ addState(state: State<C>): this;
87
+ /**
88
+ * Register a transition.
89
+ * When `trigger` fires in `fromState`, transition to `toState`.
90
+ */
91
+ addTransition(fromState: string, trigger: string, toState: string): this;
92
+ /** Set the initial state (calls onEnter). */
93
+ start(stateName: string): void;
94
+ /** Fire a trigger. If a matching transition exists, switch states. */
95
+ trigger(name: string): void;
96
+ /** Update the current state. */
97
+ update(dt: number): void;
98
+ }
99
+ //#endregion
100
+ //#region src/query.d.ts
34
101
  /**
35
102
  * Query matches entities based on component archetypes.
36
103
  *
@@ -38,42 +105,43 @@ declare function _resetComponentIds(): void;
38
105
  * and entity archetype & excludedMask === 0.
39
106
  */
40
107
  declare class Query {
41
- /** Bitmask of required components. */
42
- readonly requiredMask: number;
43
- /** Bitmask of excluded components. */
44
- readonly excludedMask: number;
45
- /** Fires when an entity is added to this query's results. */
46
- readonly onEntityAdded: Signal<number>;
47
- /** Fires when an entity is removed from this query's results. */
48
- readonly onEntityRemoved: Signal<number>;
49
- /** Sorted array of matching entity IDs. */
50
- private entities;
51
- /** Set for O(1) membership check. */
52
- private entitySet;
53
- constructor(requiredMask: number, excludedMask: number);
54
- /** Check if an archetype matches this query. */
55
- matches(archetype: number): boolean;
56
- /** @internal — called by World when an entity's archetype changes. */
57
- _check(entityId: number, archetype: number): void;
58
- /** @internal — called by World when an entity is removed entirely. */
59
- _remove(entityId: number): void;
60
- /** Iterate matching entity IDs. */
61
- [Symbol.iterator](): IterableIterator<number>;
62
- /** Number of matching entities. */
63
- get count(): number;
64
- /** Check if an entity matches this query. */
65
- has(entityId: number): boolean;
108
+ /** Bitmask of required components. */
109
+ readonly requiredMask: number;
110
+ /** Bitmask of excluded components. */
111
+ readonly excludedMask: number;
112
+ /** Fires when an entity is added to this query's results. */
113
+ readonly onEntityAdded: Signal<number>;
114
+ /** Fires when an entity is removed from this query's results. */
115
+ readonly onEntityRemoved: Signal<number>;
116
+ /** Sorted array of matching entity IDs. */
117
+ private entities;
118
+ /** Set for O(1) membership check. */
119
+ private entitySet;
120
+ constructor(requiredMask: number, excludedMask: number);
121
+ /** Check if an archetype matches this query. */
122
+ matches(archetype: number): boolean;
123
+ /** @internal — called by World when an entity's archetype changes. */
124
+ _check(entityId: number, archetype: number): void;
125
+ /** @internal — called by World when an entity is removed entirely. */
126
+ _remove(entityId: number): void;
127
+ /** Iterate matching entity IDs. */
128
+ [Symbol.iterator](): IterableIterator<number>;
129
+ /** Number of matching entities. */
130
+ get count(): number;
131
+ /** Check if an entity matches this query. */
132
+ has(entityId: number): boolean;
66
133
  }
67
134
  /** Builder for creating queries with .with() / .without() chaining. */
68
135
  declare class QueryBuilder {
69
- private required;
70
- private excluded;
71
- with(...components: ComponentDef<unknown>[]): this;
72
- without(...components: ComponentDef<unknown>[]): this;
73
- /** Build the query (called internally by World). */
74
- build(): Query;
136
+ private required;
137
+ private excluded;
138
+ with(...components: ComponentDef<unknown>[]): this;
139
+ without(...components: ComponentDef<unknown>[]): this;
140
+ /** Build the query (called internally by World). */
141
+ build(): Query;
75
142
  }
76
-
143
+ //#endregion
144
+ //#region src/world.d.ts
77
145
  /**
78
146
  * World is the central ECS container.
79
147
  *
@@ -81,54 +149,94 @@ declare class QueryBuilder {
81
149
  * Archetype bitmasks enable fast query matching.
82
150
  */
83
151
  declare class World {
84
- private nextId;
85
- private archetypes;
86
- private componentStores;
87
- private queries;
88
- private systems;
89
- private systemsSorted;
90
- /** Create a new entity. Returns the entity ID. */
91
- spawn(): number;
92
- /** Remove an entity and all its components. */
93
- destroy(entityId: number): void;
94
- /** Add a component to an entity. */
95
- add<T>(entityId: number, def: ComponentDef<T>, data?: T): void;
96
- /** Remove a component from an entity. */
97
- remove<T>(entityId: number, def: ComponentDef<T>): void;
98
- /** Get component data for an entity. */
99
- get<T>(entityId: number, def: ComponentDef<T>): T | undefined;
100
- /** Check if entity has a component. */
101
- has(entityId: number, def: ComponentDef<unknown>): boolean;
102
- /** Check if entity exists. */
103
- exists(entityId: number): boolean;
104
- /**
105
- * Create a query. Queries auto-update as entities change.
106
- * Use the QueryBuilder-style chaining:
107
- * world.query(Position, Velocity)
108
- * Or use the builder:
109
- * world.queryBuilder().with(Position).without(Dead).build()
110
- */
111
- query(...components: ComponentDef<unknown>[]): Query;
112
- /** Create a QueryBuilder for complex queries (with/without). */
113
- queryBuilder(): QueryBuilder;
114
- /** Register a system function. Lower priority runs first. */
115
- addSystem(fn: (world: World, dt: number) => void, priority?: number): void;
116
- /** Remove a system. */
117
- removeSystem(fn: (world: World, dt: number) => void): void;
118
- /** Run all systems in priority order. */
119
- step(dt: number): void;
120
- /** @internal Register a query for auto-update. */
121
- _registerQuery(q: Query): void;
152
+ private nextId;
153
+ private archetypes;
154
+ private componentStores;
155
+ private queries;
156
+ private queryIterDepth;
157
+ private pendingQueryRemove;
158
+ private systems;
159
+ private systemsSorted;
160
+ /** Create a new entity. Returns the entity ID. */
161
+ spawn(): number;
162
+ /** Remove an entity and all its components. */
163
+ destroy(entityId: number): void;
164
+ /** Add a component to an entity. */
165
+ add<T>(entityId: number, def: ComponentDef<T>, data?: T): void;
166
+ /** Remove a component from an entity. */
167
+ remove<T>(entityId: number, def: ComponentDef<T>): void;
168
+ /** Get component data for an entity. */
169
+ get<T>(entityId: number, def: ComponentDef<T>): T | undefined;
170
+ /** Check if entity has a component. */
171
+ has(entityId: number, def: ComponentDef<unknown>): boolean;
172
+ /** Check if entity exists. */
173
+ exists(entityId: number): boolean;
174
+ /** Number of live entities. */
175
+ get entityCount(): number;
176
+ /**
177
+ * Walk every live entity ID. Iterates the live archetype map directly, with no
178
+ * array snapshot. Archetype changes (add/remove component) keep the same entity
179
+ * keys, so iteration is stable across them. Destroying entities inside the
180
+ * callback is safe, but entities spawned inside it are visited in the same pass
181
+ * (live Map iteration) — don't spawn from within.
182
+ */
183
+ forEachEntity(cb: (entity: number) => void): void;
184
+ /**
185
+ * Create a query. Queries auto-update as entities change.
186
+ * Use the QueryBuilder-style chaining:
187
+ * world.query(Position, Velocity)
188
+ * Or use the builder:
189
+ * world.queryBuilder().with(Position).without(Dead).build()
190
+ */
191
+ query(...components: ComponentDef<unknown>[]): Query;
192
+ /** Create a QueryBuilder for complex queries (with/without). */
193
+ queryBuilder(): QueryBuilder;
194
+ /**
195
+ * Dispose a query created by `query()` or `queryBuilder().build()`. Afterwards
196
+ * the world stops updating it, so it no longer costs spawn/add/remove iteration
197
+ * time. The query is left inert — drop the reference to let it be collected.
198
+ *
199
+ * Safe to call from within a Query signal handler (e.g. a one-shot
200
+ * `onEntityAdded` that disposes its own query): the removal is deferred until
201
+ * the in-progress mutation finishes iterating, so no other query is skipped.
202
+ */
203
+ removeQuery(q: Query): void;
204
+ /** @internal End a query-notify loop; flush any removeQuery deferred during it. */
205
+ private endQueryIteration;
206
+ /** Register a system function. Lower priority runs first. */
207
+ addSystem(fn: (world: World, dt: number) => void, priority?: number): void;
208
+ /** Remove a system. */
209
+ removeSystem(fn: (world: World, dt: number) => void): void;
210
+ /** Run all systems in priority order. */
211
+ step(dt: number): void;
212
+ /** @internal Register a query for auto-update. */
213
+ _registerQuery(q: Query): void;
122
214
  }
123
-
215
+ //#endregion
216
+ //#region src/prefab.d.ts
217
+ /** A prefab factory that spawns entities with pre-defined components. */
218
+ interface Prefab {
219
+ readonly name: string;
220
+ /** Spawn an entity with this prefab's components. */
221
+ spawn(world: World, overrides?: Record<string, unknown>): number;
222
+ }
223
+ /**
224
+ * Define a prefab — a template for spawning entities with a fixed set of components.
225
+ *
226
+ * @param name Debug name.
227
+ * @param entries Array of [componentDef, data?] tuples.
228
+ */
229
+ declare function definePrefab(name: string, ...entries: [ComponentDef<unknown>, (unknown | (() => unknown))?][]): Prefab;
230
+ //#endregion
231
+ //#region src/system.d.ts
124
232
  /** A system function that processes entities matching a query. */
125
233
  type SystemFn = (entities: Query, dt: number, world: World) => void;
126
234
  /** A defined system with its query and function. */
127
235
  interface SystemDef {
128
- readonly query: Query;
129
- readonly fn: SystemFn;
130
- /** The wrapper registered on the World (used for removal). */
131
- readonly _worldFn: (world: World, dt: number) => void;
236
+ readonly query: Query;
237
+ readonly fn: SystemFn;
238
+ /** The wrapper registered on the World (used for removal). */
239
+ readonly _worldFn: (world: World, dt: number) => void;
132
240
  }
133
241
  /**
134
242
  * Define a system that processes entities matching a query.
@@ -144,94 +252,17 @@ interface SystemDef {
144
252
  * world.addSystem(moveSys._worldFn);
145
253
  */
146
254
  declare function defineSystem(query: Query, fn: SystemFn): SystemDef;
147
-
148
- /** A prefab factory that spawns entities with pre-defined components. */
149
- interface Prefab {
150
- readonly name: string;
151
- /** Spawn an entity with this prefab's components. */
152
- spawn(world: World, overrides?: Record<string, unknown>): number;
153
- }
154
- /**
155
- * Define a prefab — a template for spawning entities with a fixed set of components.
156
- *
157
- * @param name Debug name.
158
- * @param entries Array of [componentDef, data?] tuples.
159
- */
160
- declare function definePrefab(name: string, ...entries: [ComponentDef<unknown>, (unknown | (() => unknown))?][]): Prefab;
161
-
162
- /** A state in the FSM. */
163
- interface State<C = undefined> {
164
- readonly name: string;
165
- onEnter?(context: C): void;
166
- onExit?(context: C): void;
167
- onUpdate?(dt: number, context: C): void;
168
- }
169
- /**
170
- * Lightweight finite state machine. ~100 LOC.
171
- *
172
- * Manages named states with onEnter/onExit/onUpdate hooks
173
- * and string-keyed transitions.
174
- */
175
- declare class FSM<C = undefined> {
176
- private _current;
177
- private _states;
178
- private _transitions;
179
- private _context;
180
- constructor(...args: C extends undefined ? [] : [context: C]);
181
- /** The currently active state, or undefined if none. */
182
- get current(): State<C> | undefined;
183
- /** Register a state. */
184
- addState(state: State<C>): this;
185
- /**
186
- * Register a transition.
187
- * When `trigger` fires in `fromState`, transition to `toState`.
188
- */
189
- addTransition(fromState: string, trigger: string, toState: string): this;
190
- /** Set the initial state (calls onEnter). */
191
- start(stateName: string): void;
192
- /** Fire a trigger. If a matching transition exists, switch states. */
193
- trigger(name: string): void;
194
- /** Update the current state. */
195
- update(dt: number): void;
196
- }
197
-
198
- /**
199
- * Built-in ECS components using @flare-engine/math types.
200
- */
201
- /** 2D position component. */
202
- declare const Position: ComponentDef<Vec2>;
203
- /** 2D velocity component. */
204
- declare const Velocity: ComponentDef<Vec2>;
205
- /** Rotation in radians. */
206
- declare const Rotation: ComponentDef<{
207
- angle: number;
208
- }>;
209
- /** 2D scale component. */
210
- declare const Scale: ComponentDef<Vec2>;
211
- /** Parent entity reference. */
212
- declare const Parent: ComponentDef<{
213
- entity: number;
214
- }>;
215
- /** Countdown timer in seconds; entity expires when remaining reaches 0. */
216
- declare const Lifetime: ComponentDef<{
217
- remaining: number;
218
- }>;
219
- /** Pins an entity's position to a target entity plus a fixed offset. */
220
- declare const Follower: ComponentDef<{
221
- target: number;
222
- offsetX: number;
223
- offsetY: number;
224
- }>;
225
-
255
+ //#endregion
256
+ //#region src/systems.d.ts
226
257
  /**
227
258
  * Plain camera-space bounding box used by createBoundsCullSystem.
228
259
  * Keep plain numbers — do NOT import physics AABB/Bounds (layer inversion).
229
260
  */
230
261
  interface CullBounds {
231
- readonly minX: number;
232
- readonly minY: number;
233
- readonly maxX: number;
234
- readonly maxY: number;
262
+ readonly minX: number;
263
+ readonly minY: number;
264
+ readonly maxX: number;
265
+ readonly maxY: number;
235
266
  }
236
267
  /**
237
268
  * createMovementSystem — integrates Position by Velocity * dt each frame.
@@ -250,8 +281,13 @@ declare function createMovementSystem(world: World): SystemDef;
250
281
  * The scratch array is closure-owned and grow-only — zero steady-state alloc.
251
282
  *
252
283
  * @param onExpire Destroy / pool policy — ecs never destroys on its own.
284
+ * @param query Optional caller-supplied Query. When omitted the system
285
+ * registers world.query(Lifetime) itself. Pass a narrower
286
+ * query to avoid scanning unrelated Lifetime holders and to
287
+ * share an already-registered query (eliminates duplicate
288
+ * World.query registration cost).
253
289
  */
254
- declare function createLifetimeSystem(world: World, onExpire: (entity: number, world: World) => void): SystemDef;
290
+ declare function createLifetimeSystem(world: World, onExpire: (entity: number, world: World) => void, query?: Query): SystemDef;
255
291
  /**
256
292
  * createBoundsCullSystem — culls entities whose Position falls outside bounds.
257
293
  * Reads bounds LIVE each frame so callers can mutate it to follow a camera.
@@ -263,8 +299,14 @@ declare function createLifetimeSystem(world: World, onExpire: (entity: number, w
263
299
  *
264
300
  * @param bounds Mutable bounding box read each frame.
265
301
  * @param onCull Destroy / pool policy — ecs never destroys on its own.
302
+ * @param query Optional caller-supplied Query. When omitted the system
303
+ * registers world.query(Position) itself, scanning all
304
+ * Position holders. Pass a narrower query (e.g. bullets
305
+ * only) to avoid scanning unrelated entities such as
306
+ * scrolling backgrounds, and to share an already-registered
307
+ * query with the caller.
266
308
  */
267
- declare function createBoundsCullSystem(world: World, bounds: CullBounds, onCull: (entity: number, world: World) => void): SystemDef;
309
+ declare function createBoundsCullSystem(world: World, bounds: CullBounds, onCull: (entity: number, world: World) => void, query?: Query): SystemDef;
268
310
  /**
269
311
  * createFollowerSystem — pins each Follower entity's Position to
270
312
  * target.Position + (offsetX, offsetY).
@@ -289,5 +331,6 @@ declare function createFollowerSystem(world: World): SystemDef;
289
331
  * @param onOrphan Called once per orphaned entity after the read loop.
290
332
  */
291
333
  declare function createOrphanCullSystem(world: World, onOrphan: (entity: number, world: World) => void): SystemDef;
292
-
334
+ //#endregion
293
335
  export { type ComponentDef, type CullBounds, FSM, Follower, Lifetime, Parent, Position, type Prefab, Query, QueryBuilder, Rotation, Scale, type State, type SystemDef, type SystemFn, Velocity, World, _resetComponentIds, createBoundsCullSystem, createFollowerSystem, createLifetimeSystem, createMovementSystem, createOrphanCullSystem, defineComponent, definePrefab, defineSystem };
336
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +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,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;;WAEb,iBAAe;;UAGhB;;UAEA;cAEI,sBAAsB;;EAMlC,QAAQ;;EAOR,OAAO,kBAAkB;;EAiBzB,QAAQ;;GAUP,OAAO,aAAa;;MAKjB;;EAKJ,IAAI;;;cAMO;UACH;UACA;EAER,QAAQ,YAAY;EAOpB,WAAW,YAAY;;EAQvB,SAAS;;;;;;;;;;cC3FE;UACH;UACA;UACA;UACA;UACA;UACA;UACA;UAIA;;EAGR;;EAOA,QAAQ;;EAuBR,IAAI,GAAG,kBAAkB,KAAK,aAAa,IAAI,OAAO;;EA4BtD,OAAO,GAAG,kBAAkB,KAAK,aAAa;;EAsB9C,IAAI,GAAG,kBAAkB,KAAK,aAAa,KAAK;;EAMhD,IAAI,kBAAkB,KAAK;;EAM3B,OAAO;;MAKH;;;;;;;;EAWJ,cAAc,KAAK;;;;;;;;EAanB,SAAS,YAAY,0BAA0B;;EAiB/C,gBAAgB;;;;;;;;;;EAahB,YAAY,GAAG;;UAWP;;EAYR,UAAU,KAAK,OAAO,OAAO,qBAAqB;;EAMlD,aAAa,KAAK,OAAO,OAAO;;EAMhC,KAAK;;EAWL,eAAe,GAAG;;;;;UClNH;WACN;;EAET,MAAM,OAAO,OAAO,YAAY;;;;;;;;iBASlB,aACd,iBACG,UAAU,yDACZ;;;;KCrBS,YAAY,UAAU,OAAO,YAAY,OAAO;;UAG3C;WACN,OAAO;WACP,IAAI;;WAEJ,WAAW,OAAO,OAAO;;;;;;;;;;;;;;;iBAgBpB,aAAa,OAAO,OAAO,IAAI,WAAW;;;;;;;UCjBzC;WACN;WACA;WACA;WACA;;;;;;;iBAQK,qBAAqB,OAAO,QAAQ;;;;;;;;;;;;;;;;;;iBA6BpC,qBACd,OAAO,OACP,WAAW,gBAAgB,OAAO,gBAClC,QAAQ,QACP;;;;;;;;;;;;;;;;;;;iBAoCa,uBACd,OAAO,OACP,QAAQ,YACR,SAAS,gBAAgB,OAAO,gBAChC,QAAQ,QACP;;;;;;;;;iBA8Ba,qBAAqB,OAAO,QAAQ;;;;;;;;;;;;;;;iBA4BpC,uBACd,OAAO,OACP,WAAW,gBAAgB,OAAO,iBACjC"}