@flare-engine/ecs 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,484 +1,576 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- FSM: () => FSM,
24
- Follower: () => Follower,
25
- Lifetime: () => Lifetime,
26
- Parent: () => Parent,
27
- Position: () => Position,
28
- Query: () => Query,
29
- QueryBuilder: () => QueryBuilder,
30
- Rotation: () => Rotation,
31
- Scale: () => Scale,
32
- Velocity: () => Velocity,
33
- World: () => World,
34
- _resetComponentIds: () => _resetComponentIds,
35
- createBoundsCullSystem: () => createBoundsCullSystem,
36
- createFollowerSystem: () => createFollowerSystem,
37
- createLifetimeSystem: () => createLifetimeSystem,
38
- createMovementSystem: () => createMovementSystem,
39
- createOrphanCullSystem: () => createOrphanCullSystem,
40
- defineComponent: () => defineComponent,
41
- definePrefab: () => definePrefab,
42
- defineSystem: () => defineSystem
43
- });
44
- module.exports = __toCommonJS(index_exports);
45
-
46
- // src/component.ts
47
- var nextComponentId = 0;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _flare_engine_events = require("@flare-engine/events");
3
+ //#region src/component.ts
4
+ let nextComponentId = 0;
5
+ /**
6
+ * Define a new component type.
7
+ *
8
+ * @param name Debug name for the component.
9
+ * @param defaults Factory function returning default values, or undefined for tag components.
10
+ */
48
11
  function defineComponent(name, defaults) {
49
- const id = nextComponentId++;
50
- if (id >= 32) {
51
- throw new Error(`Maximum 32 component types exceeded (defining "${name}")`);
52
- }
53
- return {
54
- id,
55
- bit: 1 << id,
56
- name,
57
- create: defaults ?? (() => void 0)
58
- };
12
+ const id = nextComponentId++;
13
+ if (id >= 32) throw new Error(`Maximum 32 component types exceeded (defining "${name}")`);
14
+ return {
15
+ id,
16
+ bit: 1 << id,
17
+ name,
18
+ create: defaults ?? (() => void 0)
19
+ };
59
20
  }
21
+ /**
22
+ * Reset the component ID counter. Only for testing.
23
+ * @internal
24
+ */
60
25
  function _resetComponentIds() {
61
- nextComponentId = 0;
26
+ nextComponentId = 0;
62
27
  }
63
-
64
- // src/query.ts
65
- var import_events = require("@flare-engine/events");
28
+ //#endregion
29
+ //#region src/components.ts
30
+ /**
31
+ * Built-in ECS components using @flare-engine/math types.
32
+ */
33
+ /** 2D position component. */
34
+ const Position = defineComponent("Position", () => ({
35
+ x: 0,
36
+ y: 0
37
+ }));
38
+ /** 2D velocity component. */
39
+ const Velocity = defineComponent("Velocity", () => ({
40
+ x: 0,
41
+ y: 0
42
+ }));
43
+ /** Rotation in radians. */
44
+ const Rotation = defineComponent("Rotation", () => ({ angle: 0 }));
45
+ /** 2D scale component. */
46
+ const Scale = defineComponent("Scale", () => ({
47
+ x: 1,
48
+ y: 1
49
+ }));
50
+ /** Parent entity reference. */
51
+ const Parent = defineComponent("Parent", () => ({ entity: 0 }));
52
+ /** Countdown timer in seconds; entity expires when remaining reaches 0. */
53
+ const Lifetime = defineComponent("Lifetime", () => ({ remaining: 0 }));
54
+ /** Pins an entity's position to a target entity plus a fixed offset. */
55
+ const Follower = defineComponent("Follower", () => ({
56
+ target: 0,
57
+ offsetX: 0,
58
+ offsetY: 0
59
+ }));
60
+ //#endregion
61
+ //#region src/fsm.ts
62
+ /**
63
+ * Lightweight finite state machine. ~100 LOC.
64
+ *
65
+ * Manages named states with onEnter/onExit/onUpdate hooks
66
+ * and string-keyed transitions.
67
+ */
68
+ var FSM = class {
69
+ _current;
70
+ _states = /* @__PURE__ */ new Map();
71
+ _transitions = /* @__PURE__ */ new Map();
72
+ _context;
73
+ constructor(...args) {
74
+ this._context = args[0];
75
+ }
76
+ /** The currently active state, or undefined if none. */
77
+ get current() {
78
+ return this._current;
79
+ }
80
+ /** Register a state. */
81
+ addState(state) {
82
+ this._states.set(state.name, state);
83
+ return this;
84
+ }
85
+ /**
86
+ * Register a transition.
87
+ * When `trigger` fires in `fromState`, transition to `toState`.
88
+ */
89
+ addTransition(fromState, trigger, toState) {
90
+ let map = this._transitions.get(fromState);
91
+ if (!map) {
92
+ map = /* @__PURE__ */ new Map();
93
+ this._transitions.set(fromState, map);
94
+ }
95
+ map.set(trigger, toState);
96
+ return this;
97
+ }
98
+ /** Set the initial state (calls onEnter). */
99
+ start(stateName) {
100
+ const state = this._states.get(stateName);
101
+ if (!state) return;
102
+ this._current = state;
103
+ state.onEnter?.(this._context);
104
+ }
105
+ /** Fire a trigger. If a matching transition exists, switch states. */
106
+ trigger(name) {
107
+ if (!this._current) return;
108
+ const transitions = this._transitions.get(this._current.name);
109
+ if (!transitions) return;
110
+ const target = transitions.get(name);
111
+ if (target === void 0) return;
112
+ const next = this._states.get(target);
113
+ if (!next) return;
114
+ this._current.onExit?.(this._context);
115
+ this._current = next;
116
+ next.onEnter?.(this._context);
117
+ }
118
+ /** Update the current state. */
119
+ update(dt) {
120
+ this._current?.onUpdate?.(dt, this._context);
121
+ }
122
+ };
123
+ //#endregion
124
+ //#region src/prefab.ts
125
+ /**
126
+ * Define a prefab — a template for spawning entities with a fixed set of components.
127
+ *
128
+ * @param name Debug name.
129
+ * @param entries Array of [componentDef, data?] tuples.
130
+ */
131
+ function definePrefab(name, ...entries) {
132
+ const components = entries.map(([def, data]) => ({
133
+ def,
134
+ data
135
+ }));
136
+ return {
137
+ name,
138
+ spawn(world) {
139
+ const entity = world.spawn();
140
+ for (const entry of components) {
141
+ const data = typeof entry.data === "function" ? entry.data() : entry.data;
142
+ world.add(entity, entry.def, data);
143
+ }
144
+ return entity;
145
+ }
146
+ };
147
+ }
148
+ //#endregion
149
+ //#region src/query.ts
150
+ /**
151
+ * Query matches entities based on component archetypes.
152
+ *
153
+ * Uses bitmask matching: entity archetype & requiredMask === requiredMask
154
+ * and entity archetype & excludedMask === 0.
155
+ */
66
156
  var Query = class {
67
- /** Bitmask of required components. */
68
- requiredMask;
69
- /** Bitmask of excluded components. */
70
- excludedMask;
71
- /** Fires when an entity is added to this query's results. */
72
- onEntityAdded = new import_events.Signal();
73
- /** Fires when an entity is removed from this query's results. */
74
- onEntityRemoved = new import_events.Signal();
75
- /** Sorted array of matching entity IDs. */
76
- entities = [];
77
- /** Set for O(1) membership check. */
78
- entitySet = /* @__PURE__ */ new Set();
79
- constructor(requiredMask, excludedMask) {
80
- this.requiredMask = requiredMask;
81
- this.excludedMask = excludedMask;
82
- }
83
- /** Check if an archetype matches this query. */
84
- matches(archetype) {
85
- return (archetype & this.requiredMask) === this.requiredMask && (archetype & this.excludedMask) === 0;
86
- }
87
- /** @internal — called by World when an entity's archetype changes. */
88
- _check(entityId, archetype) {
89
- const isMatch = this.matches(archetype);
90
- const wasMatch = this.entitySet.has(entityId);
91
- if (isMatch && !wasMatch) {
92
- this.entitySet.add(entityId);
93
- this.entities.push(entityId);
94
- this.onEntityAdded.emit(entityId);
95
- } else if (!isMatch && wasMatch) {
96
- this.entitySet.delete(entityId);
97
- const idx = this.entities.indexOf(entityId);
98
- if (idx !== -1) this.entities.splice(idx, 1);
99
- this.onEntityRemoved.emit(entityId);
100
- }
101
- }
102
- /** @internal — called by World when an entity is removed entirely. */
103
- _remove(entityId) {
104
- if (this.entitySet.has(entityId)) {
105
- this.entitySet.delete(entityId);
106
- const idx = this.entities.indexOf(entityId);
107
- if (idx !== -1) this.entities.splice(idx, 1);
108
- this.onEntityRemoved.emit(entityId);
109
- }
110
- }
111
- /** Iterate matching entity IDs. */
112
- [Symbol.iterator]() {
113
- return this.entities[Symbol.iterator]();
114
- }
115
- /** Number of matching entities. */
116
- get count() {
117
- return this.entities.length;
118
- }
119
- /** Check if an entity matches this query. */
120
- has(entityId) {
121
- return this.entitySet.has(entityId);
122
- }
157
+ /** Bitmask of required components. */
158
+ requiredMask;
159
+ /** Bitmask of excluded components. */
160
+ excludedMask;
161
+ /** Fires when an entity is added to this query's results. */
162
+ onEntityAdded = new _flare_engine_events.Signal();
163
+ /** Fires when an entity is removed from this query's results. */
164
+ onEntityRemoved = new _flare_engine_events.Signal();
165
+ /** Sorted array of matching entity IDs. */
166
+ entities = [];
167
+ /** Set for O(1) membership check. */
168
+ entitySet = /* @__PURE__ */ new Set();
169
+ constructor(requiredMask, excludedMask) {
170
+ this.requiredMask = requiredMask;
171
+ this.excludedMask = excludedMask;
172
+ }
173
+ /** Check if an archetype matches this query. */
174
+ matches(archetype) {
175
+ return (archetype & this.requiredMask) === this.requiredMask && (archetype & this.excludedMask) === 0;
176
+ }
177
+ /** @internal — called by World when an entity's archetype changes. */
178
+ _check(entityId, archetype) {
179
+ const isMatch = this.matches(archetype);
180
+ const wasMatch = this.entitySet.has(entityId);
181
+ if (isMatch && !wasMatch) {
182
+ this.entitySet.add(entityId);
183
+ this.entities.push(entityId);
184
+ this.onEntityAdded.emit(entityId);
185
+ } else if (!isMatch && wasMatch) {
186
+ this.entitySet.delete(entityId);
187
+ const idx = this.entities.indexOf(entityId);
188
+ if (idx !== -1) this.entities.splice(idx, 1);
189
+ this.onEntityRemoved.emit(entityId);
190
+ }
191
+ }
192
+ /** @internal — called by World when an entity is removed entirely. */
193
+ _remove(entityId) {
194
+ if (this.entitySet.has(entityId)) {
195
+ this.entitySet.delete(entityId);
196
+ const idx = this.entities.indexOf(entityId);
197
+ if (idx !== -1) this.entities.splice(idx, 1);
198
+ this.onEntityRemoved.emit(entityId);
199
+ }
200
+ }
201
+ /** Iterate matching entity IDs. */
202
+ [Symbol.iterator]() {
203
+ return this.entities[Symbol.iterator]();
204
+ }
205
+ /** Number of matching entities. */
206
+ get count() {
207
+ return this.entities.length;
208
+ }
209
+ /** Check if an entity matches this query. */
210
+ has(entityId) {
211
+ return this.entitySet.has(entityId);
212
+ }
123
213
  };
214
+ /** Builder for creating queries with .with() / .without() chaining. */
124
215
  var QueryBuilder = class {
125
- required = 0;
126
- excluded = 0;
127
- with(...components) {
128
- for (const c of components) {
129
- this.required |= c.bit;
130
- }
131
- return this;
132
- }
133
- without(...components) {
134
- for (const c of components) {
135
- this.excluded |= c.bit;
136
- }
137
- return this;
138
- }
139
- /** Build the query (called internally by World). */
140
- build() {
141
- return new Query(this.required, this.excluded);
142
- }
216
+ required = 0;
217
+ excluded = 0;
218
+ with(...components) {
219
+ for (const c of components) this.required |= c.bit;
220
+ return this;
221
+ }
222
+ without(...components) {
223
+ for (const c of components) this.excluded |= c.bit;
224
+ return this;
225
+ }
226
+ /** Build the query (called internally by World). */
227
+ build() {
228
+ return new Query(this.required, this.excluded);
229
+ }
143
230
  };
144
-
145
- // src/world.ts
146
- var World = class {
147
- nextId = 1;
148
- archetypes = /* @__PURE__ */ new Map();
149
- // entityId → bitmask
150
- componentStores = /* @__PURE__ */ new Map();
151
- // componentId → (entityId → data)
152
- queries = [];
153
- systems = [];
154
- systemsSorted = false;
155
- /** Create a new entity. Returns the entity ID. */
156
- spawn() {
157
- const id = this.nextId++;
158
- this.archetypes.set(id, 0);
159
- return id;
160
- }
161
- /** Remove an entity and all its components. */
162
- destroy(entityId) {
163
- const arch = this.archetypes.get(entityId);
164
- if (arch === void 0) return;
165
- for (const [, store] of this.componentStores) {
166
- store.delete(entityId);
167
- }
168
- this.archetypes.delete(entityId);
169
- for (const query of this.queries) {
170
- query._remove(entityId);
171
- }
172
- }
173
- /** Add a component to an entity. */
174
- add(entityId, def, data) {
175
- const arch = this.archetypes.get(entityId);
176
- if (arch === void 0) return;
177
- let store = this.componentStores.get(def.id);
178
- if (!store) {
179
- store = /* @__PURE__ */ new Map();
180
- this.componentStores.set(def.id, store);
181
- }
182
- store.set(entityId, data !== void 0 ? data : def.create());
183
- const newArch = arch | def.bit;
184
- this.archetypes.set(entityId, newArch);
185
- for (const query of this.queries) {
186
- query._check(entityId, newArch);
187
- }
188
- }
189
- /** Remove a component from an entity. */
190
- remove(entityId, def) {
191
- const arch = this.archetypes.get(entityId);
192
- if (arch === void 0) return;
193
- const store = this.componentStores.get(def.id);
194
- if (store) store.delete(entityId);
195
- const newArch = arch & ~def.bit;
196
- this.archetypes.set(entityId, newArch);
197
- for (const query of this.queries) {
198
- query._check(entityId, newArch);
199
- }
200
- }
201
- /** Get component data for an entity. */
202
- get(entityId, def) {
203
- const store = this.componentStores.get(def.id);
204
- return store?.get(entityId);
205
- }
206
- /** Check if entity has a component. */
207
- has(entityId, def) {
208
- const arch = this.archetypes.get(entityId);
209
- return arch !== void 0 && (arch & def.bit) !== 0;
210
- }
211
- /** Check if entity exists. */
212
- exists(entityId) {
213
- return this.archetypes.has(entityId);
214
- }
215
- /**
216
- * Create a query. Queries auto-update as entities change.
217
- * Use the QueryBuilder-style chaining:
218
- * world.query(Position, Velocity)
219
- * Or use the builder:
220
- * world.queryBuilder().with(Position).without(Dead).build()
221
- */
222
- query(...components) {
223
- let mask = 0;
224
- for (const c of components) {
225
- mask |= c.bit;
226
- }
227
- const q = new Query(mask, 0);
228
- this.queries.push(q);
229
- for (const [entityId, arch] of this.archetypes) {
230
- q._check(entityId, arch);
231
- }
232
- return q;
233
- }
234
- /** Create a QueryBuilder for complex queries (with/without). */
235
- queryBuilder() {
236
- return new _WorldQueryBuilder(this);
237
- }
238
- /** Register a system function. Lower priority runs first. */
239
- addSystem(fn, priority = 0) {
240
- this.systems.push({ fn, priority });
241
- this.systemsSorted = false;
242
- }
243
- /** Remove a system. */
244
- removeSystem(fn) {
245
- const idx = this.systems.findIndex((s) => s.fn === fn);
246
- if (idx !== -1) this.systems.splice(idx, 1);
247
- }
248
- /** Run all systems in priority order. */
249
- step(dt) {
250
- if (!this.systemsSorted) {
251
- this.systems.sort((a, b) => a.priority - b.priority);
252
- this.systemsSorted = true;
253
- }
254
- for (const sys of this.systems) {
255
- sys.fn(this, dt);
256
- }
257
- }
258
- /** @internal Register a query for auto-update. */
259
- _registerQuery(q) {
260
- this.queries.push(q);
261
- for (const [entityId, arch] of this.archetypes) {
262
- q._check(entityId, arch);
263
- }
264
- }
265
- };
266
- var _WorldQueryBuilder = class extends QueryBuilder {
267
- world;
268
- constructor(world) {
269
- super();
270
- this.world = world;
271
- }
272
- build() {
273
- const q = super.build();
274
- this.world._registerQuery(q);
275
- return q;
276
- }
277
- };
278
-
279
- // src/system.ts
231
+ //#endregion
232
+ //#region src/system.ts
233
+ /**
234
+ * Define a system that processes entities matching a query.
235
+ *
236
+ * Returns a SystemDef that can be added to a World via world.addSystem().
237
+ * The system function receives the query's matching entities, dt, and world.
238
+ *
239
+ * Usage:
240
+ * const q = world.query(Position, Velocity);
241
+ * const moveSys = defineSystem(q, (entities, dt, world) => {
242
+ * for (const id of entities) { ... }
243
+ * });
244
+ * world.addSystem(moveSys._worldFn);
245
+ */
280
246
  function defineSystem(query, fn) {
281
- const worldFn = (world, dt) => {
282
- fn(query, dt, world);
283
- };
284
- return { query, fn, _worldFn: worldFn };
247
+ const worldFn = (world, dt) => {
248
+ fn(query, dt, world);
249
+ };
250
+ return {
251
+ query,
252
+ fn,
253
+ _worldFn: worldFn
254
+ };
285
255
  }
286
-
287
- // src/prefab.ts
288
- function definePrefab(name, ...entries) {
289
- const components = entries.map(([def, data]) => ({
290
- def,
291
- data
292
- }));
293
- return {
294
- name,
295
- spawn(world) {
296
- const entity = world.spawn();
297
- for (const entry of components) {
298
- const data = typeof entry.data === "function" ? entry.data() : entry.data;
299
- world.add(entity, entry.def, data);
300
- }
301
- return entity;
302
- }
303
- };
304
- }
305
-
306
- // src/fsm.ts
307
- var FSM = class {
308
- _current;
309
- _states = /* @__PURE__ */ new Map();
310
- _transitions = /* @__PURE__ */ new Map();
311
- _context;
312
- constructor(...args) {
313
- this._context = args[0];
314
- }
315
- /** The currently active state, or undefined if none. */
316
- get current() {
317
- return this._current;
318
- }
319
- /** Register a state. */
320
- addState(state) {
321
- this._states.set(state.name, state);
322
- return this;
323
- }
324
- /**
325
- * Register a transition.
326
- * When `trigger` fires in `fromState`, transition to `toState`.
327
- */
328
- addTransition(fromState, trigger, toState) {
329
- let map = this._transitions.get(fromState);
330
- if (!map) {
331
- map = /* @__PURE__ */ new Map();
332
- this._transitions.set(fromState, map);
333
- }
334
- map.set(trigger, toState);
335
- return this;
336
- }
337
- /** Set the initial state (calls onEnter). */
338
- start(stateName) {
339
- const state = this._states.get(stateName);
340
- if (!state) return;
341
- this._current = state;
342
- state.onEnter?.(this._context);
343
- }
344
- /** Fire a trigger. If a matching transition exists, switch states. */
345
- trigger(name) {
346
- if (!this._current) return;
347
- const transitions = this._transitions.get(this._current.name);
348
- if (!transitions) return;
349
- const target = transitions.get(name);
350
- if (target === void 0) return;
351
- const next = this._states.get(target);
352
- if (!next) return;
353
- this._current.onExit?.(this._context);
354
- this._current = next;
355
- next.onEnter?.(this._context);
356
- }
357
- /** Update the current state. */
358
- update(dt) {
359
- this._current?.onUpdate?.(dt, this._context);
360
- }
361
- };
362
-
363
- // src/components.ts
364
- var Position = defineComponent("Position", () => ({
365
- x: 0,
366
- y: 0
367
- }));
368
- var Velocity = defineComponent("Velocity", () => ({
369
- x: 0,
370
- y: 0
371
- }));
372
- var Rotation = defineComponent("Rotation", () => ({
373
- angle: 0
374
- }));
375
- var Scale = defineComponent("Scale", () => ({ x: 1, y: 1 }));
376
- var Parent = defineComponent("Parent", () => ({
377
- entity: 0
378
- }));
379
- var Lifetime = defineComponent("Lifetime", () => ({
380
- remaining: 0
381
- }));
382
- var Follower = defineComponent(
383
- "Follower",
384
- () => ({ target: 0, offsetX: 0, offsetY: 0 })
385
- );
386
-
387
- // src/systems.ts
256
+ //#endregion
257
+ //#region src/systems.ts
258
+ /**
259
+ * createMovementSystem — integrates Position by Velocity * dt each frame.
260
+ *
261
+ * Recommended priority: run BEFORE createFollowerSystem (0).
262
+ */
388
263
  function createMovementSystem(world) {
389
- const q = world.query(Position, Velocity);
390
- return defineSystem(q, (entities, dt, w) => {
391
- for (const id of entities) {
392
- const pos = w.get(id, Position);
393
- const vel = w.get(id, Velocity);
394
- pos.x += vel.x * dt;
395
- pos.y += vel.y * dt;
396
- }
397
- });
264
+ return defineSystem(world.query(Position, Velocity), (entities, dt, w) => {
265
+ for (const id of entities) {
266
+ const pos = w.get(id, Position);
267
+ const vel = w.get(id, Velocity);
268
+ pos.x += vel.x * dt;
269
+ pos.y += vel.y * dt;
270
+ }
271
+ });
398
272
  }
273
+ /**
274
+ * createLifetimeSystem — decrements Lifetime.remaining each frame.
275
+ * Entities whose remaining reaches <= 0 are collected, then onExpire is called
276
+ * for each AFTER the read loop.
277
+ *
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.
280
+ *
281
+ * The scratch array is closure-owned and grow-only — zero steady-state alloc.
282
+ *
283
+ * @param onExpire Destroy / pool policy — ecs never destroys on its own.
284
+ */
399
285
  function createLifetimeSystem(world, onExpire) {
400
- const q = world.query(Lifetime);
401
- const scratch = [];
402
- return defineSystem(q, (entities, dt, w) => {
403
- scratch.length = 0;
404
- for (const id of entities) {
405
- const life = w.get(id, Lifetime);
406
- life.remaining -= dt;
407
- if (life.remaining <= 0) {
408
- scratch.push(id);
409
- }
410
- }
411
- for (let i = 0; i < scratch.length; i++) {
412
- onExpire(scratch[i], w);
413
- }
414
- });
286
+ const q = world.query(Lifetime);
287
+ const scratch = [];
288
+ return defineSystem(q, (entities, dt, w) => {
289
+ scratch.length = 0;
290
+ for (const id of entities) {
291
+ const life = w.get(id, Lifetime);
292
+ life.remaining -= dt;
293
+ if (life.remaining <= 0) scratch.push(id);
294
+ }
295
+ for (let i = 0; i < scratch.length; i++) onExpire(scratch[i], w);
296
+ });
415
297
  }
298
+ /**
299
+ * createBoundsCullSystem — culls entities whose Position falls outside bounds.
300
+ * Reads bounds LIVE each frame so callers can mutate it to follow a camera.
301
+ * Entities outside are collected, then onCull is called for each after the read loop.
302
+ *
303
+ * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.
304
+ *
305
+ * Recommended priority: run AFTER createMovementSystem and createFollowerSystem.
306
+ *
307
+ * @param bounds Mutable bounding box read each frame.
308
+ * @param onCull Destroy / pool policy — ecs never destroys on its own.
309
+ */
416
310
  function createBoundsCullSystem(world, bounds, onCull) {
417
- const q = world.query(Position);
418
- const scratch = [];
419
- return defineSystem(q, (entities, _dt, w) => {
420
- scratch.length = 0;
421
- for (const id of entities) {
422
- const pos = w.get(id, Position);
423
- if (pos.x < bounds.minX || pos.x > bounds.maxX || pos.y < bounds.minY || pos.y > bounds.maxY) {
424
- scratch.push(id);
425
- }
426
- }
427
- for (let i = 0; i < scratch.length; i++) {
428
- onCull(scratch[i], w);
429
- }
430
- });
311
+ const q = world.query(Position);
312
+ const scratch = [];
313
+ return defineSystem(q, (entities, _dt, w) => {
314
+ scratch.length = 0;
315
+ for (const id of entities) {
316
+ const pos = w.get(id, Position);
317
+ if (pos.x < bounds.minX || pos.x > bounds.maxX || pos.y < bounds.minY || pos.y > bounds.maxY) scratch.push(id);
318
+ }
319
+ for (let i = 0; i < scratch.length; i++) onCull(scratch[i], w);
320
+ });
431
321
  }
322
+ /**
323
+ * createFollowerSystem — pins each Follower entity's Position to
324
+ * target.Position + (offsetX, offsetY).
325
+ * If the target is gone or has no Position, the entity is silently skipped.
326
+ *
327
+ * Recommended priority: run AFTER createMovementSystem (1) so the target's
328
+ * position is already integrated before the follower snaps to it.
329
+ */
432
330
  function createFollowerSystem(world) {
433
- const q = world.query(Position, Follower);
434
- return defineSystem(q, (entities, _dt, w) => {
435
- for (const id of entities) {
436
- const follower = w.get(id, Follower);
437
- const t = w.get(follower.target, Position);
438
- if (t === void 0) continue;
439
- const pos = w.get(id, Position);
440
- pos.x = t.x + follower.offsetX;
441
- pos.y = t.y + follower.offsetY;
442
- }
443
- });
331
+ return defineSystem(world.query(Position, Follower), (entities, _dt, w) => {
332
+ for (const id of entities) {
333
+ const follower = w.get(id, Follower);
334
+ const t = w.get(follower.target, Position);
335
+ if (t === void 0) continue;
336
+ const pos = w.get(id, Position);
337
+ pos.x = t.x + follower.offsetX;
338
+ pos.y = t.y + follower.offsetY;
339
+ }
340
+ });
444
341
  }
342
+ /**
343
+ * createOrphanCullSystem — fires onOrphan for each Follower whose target entity
344
+ * no longer exists. Does NOT move or destroy anything itself.
345
+ *
346
+ * Split from createFollowerSystem so games that want to orphan-cull can opt in
347
+ * without coupling destruction to the follower pin logic.
348
+ *
349
+ * Recommended priority: run AFTER createFollowerSystem (2) so the follower is
350
+ * pinned before orphans are detected.
351
+ *
352
+ * Deferred removal: same splice-during-iteration reason as createLifetimeSystem.
353
+ *
354
+ * @param onOrphan Called once per orphaned entity after the read loop.
355
+ */
445
356
  function createOrphanCullSystem(world, onOrphan) {
446
- const q = world.query(Follower);
447
- const scratch = [];
448
- return defineSystem(q, (entities, _dt, w) => {
449
- scratch.length = 0;
450
- for (const id of entities) {
451
- const follower = w.get(id, Follower);
452
- if (!w.exists(follower.target)) {
453
- scratch.push(id);
454
- }
455
- }
456
- for (let i = 0; i < scratch.length; i++) {
457
- onOrphan(scratch[i], w);
458
- }
459
- });
357
+ const q = world.query(Follower);
358
+ const scratch = [];
359
+ return defineSystem(q, (entities, _dt, w) => {
360
+ scratch.length = 0;
361
+ for (const id of entities) {
362
+ const follower = w.get(id, Follower);
363
+ if (!w.exists(follower.target)) scratch.push(id);
364
+ }
365
+ for (let i = 0; i < scratch.length; i++) onOrphan(scratch[i], w);
366
+ });
460
367
  }
461
- // Annotate the CommonJS export names for ESM import in node:
462
- 0 && (module.exports = {
463
- FSM,
464
- Follower,
465
- Lifetime,
466
- Parent,
467
- Position,
468
- Query,
469
- QueryBuilder,
470
- Rotation,
471
- Scale,
472
- Velocity,
473
- World,
474
- _resetComponentIds,
475
- createBoundsCullSystem,
476
- createFollowerSystem,
477
- createLifetimeSystem,
478
- createMovementSystem,
479
- createOrphanCullSystem,
480
- defineComponent,
481
- definePrefab,
482
- defineSystem
483
- });
368
+ //#endregion
369
+ //#region src/world.ts
370
+ /**
371
+ * World is the central ECS container.
372
+ *
373
+ * Entities are integer IDs. Components are stored in per-component Maps.
374
+ * Archetype bitmasks enable fast query matching.
375
+ */
376
+ var World = class {
377
+ nextId = 1;
378
+ archetypes = /* @__PURE__ */ new Map();
379
+ componentStores = /* @__PURE__ */ new Map();
380
+ queries = [];
381
+ queryIterDepth = 0;
382
+ pendingQueryRemove = null;
383
+ systems = [];
384
+ systemsSorted = false;
385
+ /** Create a new entity. Returns the entity ID. */
386
+ spawn() {
387
+ const id = this.nextId++;
388
+ this.archetypes.set(id, 0);
389
+ return id;
390
+ }
391
+ /** Remove an entity and all its components. */
392
+ destroy(entityId) {
393
+ if (this.archetypes.get(entityId) === void 0) return;
394
+ for (const [, store] of this.componentStores) store.delete(entityId);
395
+ this.archetypes.delete(entityId);
396
+ this.queryIterDepth++;
397
+ try {
398
+ for (const query of this.queries) query._remove(entityId);
399
+ } finally {
400
+ this.endQueryIteration();
401
+ }
402
+ }
403
+ /** Add a component to an entity. */
404
+ add(entityId, def, data) {
405
+ const arch = this.archetypes.get(entityId);
406
+ if (arch === void 0) return;
407
+ let store = this.componentStores.get(def.id);
408
+ if (!store) {
409
+ store = /* @__PURE__ */ new Map();
410
+ this.componentStores.set(def.id, store);
411
+ }
412
+ store.set(entityId, data !== void 0 ? data : def.create());
413
+ const newArch = arch | def.bit;
414
+ this.archetypes.set(entityId, newArch);
415
+ this.queryIterDepth++;
416
+ try {
417
+ for (const query of this.queries) query._check(entityId, newArch);
418
+ } finally {
419
+ this.endQueryIteration();
420
+ }
421
+ }
422
+ /** Remove a component from an entity. */
423
+ remove(entityId, def) {
424
+ const arch = this.archetypes.get(entityId);
425
+ if (arch === void 0) return;
426
+ const store = this.componentStores.get(def.id);
427
+ if (store) store.delete(entityId);
428
+ const newArch = arch & ~def.bit;
429
+ this.archetypes.set(entityId, newArch);
430
+ this.queryIterDepth++;
431
+ try {
432
+ for (const query of this.queries) query._check(entityId, newArch);
433
+ } finally {
434
+ this.endQueryIteration();
435
+ }
436
+ }
437
+ /** Get component data for an entity. */
438
+ get(entityId, def) {
439
+ return this.componentStores.get(def.id)?.get(entityId);
440
+ }
441
+ /** Check if entity has a component. */
442
+ has(entityId, def) {
443
+ const arch = this.archetypes.get(entityId);
444
+ return arch !== void 0 && (arch & def.bit) !== 0;
445
+ }
446
+ /** Check if entity exists. */
447
+ exists(entityId) {
448
+ return this.archetypes.has(entityId);
449
+ }
450
+ /** Number of live entities. */
451
+ get entityCount() {
452
+ return this.archetypes.size;
453
+ }
454
+ /**
455
+ * Walk every live entity ID. Iterates the live archetype map directly, with no
456
+ * array snapshot. Archetype changes (add/remove component) keep the same entity
457
+ * keys, so iteration is stable across them. Destroying entities inside the
458
+ * callback is safe, but entities spawned inside it are visited in the same pass
459
+ * (live Map iteration) — don't spawn from within.
460
+ */
461
+ forEachEntity(cb) {
462
+ for (const entityId of this.archetypes.keys()) cb(entityId);
463
+ }
464
+ /**
465
+ * Create a query. Queries auto-update as entities change.
466
+ * Use the QueryBuilder-style chaining:
467
+ * world.query(Position, Velocity)
468
+ * Or use the builder:
469
+ * world.queryBuilder().with(Position).without(Dead).build()
470
+ */
471
+ query(...components) {
472
+ let mask = 0;
473
+ for (const c of components) mask |= c.bit;
474
+ const q = new Query(mask, 0);
475
+ this.queries.push(q);
476
+ for (const [entityId, arch] of this.archetypes) q._check(entityId, arch);
477
+ return q;
478
+ }
479
+ /** Create a QueryBuilder for complex queries (with/without). */
480
+ queryBuilder() {
481
+ return new _WorldQueryBuilder(this);
482
+ }
483
+ /**
484
+ * Dispose a query created by `query()` or `queryBuilder().build()`. Afterwards
485
+ * the world stops updating it, so it no longer costs spawn/add/remove iteration
486
+ * time. The query is left inert — drop the reference to let it be collected.
487
+ *
488
+ * Safe to call from within a Query signal handler (e.g. a one-shot
489
+ * `onEntityAdded` that disposes its own query): the removal is deferred until
490
+ * the in-progress mutation finishes iterating, so no other query is skipped.
491
+ */
492
+ removeQuery(q) {
493
+ if (this.queryIterDepth > 0) {
494
+ if (this.pendingQueryRemove === null) this.pendingQueryRemove = [];
495
+ this.pendingQueryRemove.push(q);
496
+ return;
497
+ }
498
+ const idx = this.queries.indexOf(q);
499
+ if (idx !== -1) this.queries.splice(idx, 1);
500
+ }
501
+ /** @internal End a query-notify loop; flush any removeQuery deferred during it. */
502
+ endQueryIteration() {
503
+ this.queryIterDepth--;
504
+ if (this.queryIterDepth === 0 && this.pendingQueryRemove !== null) {
505
+ for (const q of this.pendingQueryRemove) {
506
+ const idx = this.queries.indexOf(q);
507
+ if (idx !== -1) this.queries.splice(idx, 1);
508
+ }
509
+ this.pendingQueryRemove.length = 0;
510
+ }
511
+ }
512
+ /** Register a system function. Lower priority runs first. */
513
+ addSystem(fn, priority = 0) {
514
+ this.systems.push({
515
+ fn,
516
+ priority
517
+ });
518
+ this.systemsSorted = false;
519
+ }
520
+ /** Remove a system. */
521
+ removeSystem(fn) {
522
+ const idx = this.systems.findIndex((s) => s.fn === fn);
523
+ if (idx !== -1) this.systems.splice(idx, 1);
524
+ }
525
+ /** Run all systems in priority order. */
526
+ step(dt) {
527
+ if (!this.systemsSorted) {
528
+ this.systems.sort((a, b) => a.priority - b.priority);
529
+ this.systemsSorted = true;
530
+ }
531
+ for (const sys of this.systems) sys.fn(this, dt);
532
+ }
533
+ /** @internal Register a query for auto-update. */
534
+ _registerQuery(q) {
535
+ this.queries.push(q);
536
+ for (const [entityId, arch] of this.archetypes) q._check(entityId, arch);
537
+ }
538
+ };
539
+ /**
540
+ * Internal query builder that auto-registers with a World.
541
+ */
542
+ var _WorldQueryBuilder = class extends QueryBuilder {
543
+ world;
544
+ constructor(world) {
545
+ super();
546
+ this.world = world;
547
+ }
548
+ build() {
549
+ const q = super.build();
550
+ this.world._registerQuery(q);
551
+ return q;
552
+ }
553
+ };
554
+ //#endregion
555
+ exports.FSM = FSM;
556
+ exports.Follower = Follower;
557
+ exports.Lifetime = Lifetime;
558
+ exports.Parent = Parent;
559
+ exports.Position = Position;
560
+ exports.Query = Query;
561
+ exports.QueryBuilder = QueryBuilder;
562
+ exports.Rotation = Rotation;
563
+ exports.Scale = Scale;
564
+ exports.Velocity = Velocity;
565
+ exports.World = World;
566
+ exports._resetComponentIds = _resetComponentIds;
567
+ exports.createBoundsCullSystem = createBoundsCullSystem;
568
+ exports.createFollowerSystem = createFollowerSystem;
569
+ exports.createLifetimeSystem = createLifetimeSystem;
570
+ exports.createMovementSystem = createMovementSystem;
571
+ exports.createOrphanCullSystem = createOrphanCullSystem;
572
+ exports.defineComponent = defineComponent;
573
+ exports.definePrefab = definePrefab;
574
+ exports.defineSystem = defineSystem;
575
+
484
576
  //# sourceMappingURL=index.js.map