archetype-ecs-lib 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
+ ![Coverage](https://raw.githubusercontent.com/PirateJL/archetype-ecs-lib/refs/heads/gh-pages/assets/coverage.svg)
2
+
1
3
  # Archetype ECS Lib
2
4
 
3
5
  A tiny **archetype-based ECS** (Entity Component System) for TypeScript.
@@ -5,70 +7,23 @@ A tiny **archetype-based ECS** (Entity Component System) for TypeScript.
5
7
  - **Archetypes (tables)** store entities in a **SoA** layout (one column per component type).
6
8
  - **Queries** iterate matching archetypes efficiently.
7
9
  - **Commands** let you **defer structural changes** (spawn/despawn/add/remove) safely.
10
+ - **Resources (singletons)** store **global world state** (Input, Time, Config, Asset caches…) keyed by type, without using entities.
11
+ - **Events** transient messages (Hit happened, Click happened, Play sound).
8
12
  - A minimal **Schedule** runs systems by phases and flushes commands between phases.
9
13
 
10
14
  Exports are defined in `index.ts`:
11
15
  - `Types`, `TypeRegistry`, `Commands`, `World`, `Schedule`
12
16
 
17
+ > :exclamation: The full documentation is at [https://piratejl.github.io/archetype-ecs-lib/](https://piratejl.github.io/archetype-ecs-lib/)
18
+
13
19
  ---
14
20
 
15
21
  ## Install
16
22
 
17
23
  ```bash
18
24
  npm i archetype-ecs-lib
19
- # or
20
- pnpm add archetype-ecs-lib
21
- # or
22
- yarn add archetype-ecs-lib
23
- ````
24
-
25
- ---
26
-
27
- ## Core concepts
28
-
29
- ### Entity
30
-
31
- An entity is a lightweight handle:
32
-
33
- ```ts
34
- type Entity = { id: number; gen: number };
35
25
  ```
36
26
 
37
- The `gen` (generation) prevents using stale entity handles after despawn/reuse.
38
-
39
- ### Component
40
-
41
- A component is any class used as a type key:
42
-
43
- ```ts
44
- class Position { constructor(public x = 0, public y = 0) {} }
45
- class Velocity { constructor(public x = 0, public y = 0) {} }
46
- ```
47
-
48
- Internally, constructors are mapped to a stable numeric `TypeId` via `typeId()`.
49
-
50
- ### World
51
-
52
- `World` owns entities, archetypes, commands, and systems.
53
-
54
- Structural operations:
55
-
56
- * `spawn()`, `despawn(e)`
57
- * `add(e, Ctor, value)`, `remove(e, Ctor)`
58
- * `has(e, Ctor)`, `get(e, Ctor)`, `set(e, Ctor, value)`
59
- * `query(...ctors)` to iterate entities with required components
60
- * `cmd()` to enqueue deferred commands
61
- * `flush()` applies queued commands
62
- * `update(dt)` runs registered systems and flushes at the end
63
-
64
- ### Deferred structural changes (important)
65
-
66
- While iterating a query (or while systems are running), doing structural changes directly can throw:
67
-
68
- > “Cannot do structural change (…) while iterating. Use world.cmd() and flush …”
69
-
70
- Use `world.cmd()` inside systems / loops, and let `world.flush()` apply changes safely.
71
-
72
27
  ---
73
28
 
74
29
  ## Quick start
@@ -87,7 +42,7 @@ world.add(e, Position, new Position(0, 0));
87
42
  world.add(e, Velocity, new Velocity(1, 0));
88
43
 
89
44
  // A simple system
90
- world.addSystem((w: any, dt: number) => {
45
+ world.addSystem((w) => {
91
46
  for (const { e, c1: pos, c2: vel } of w.query(Position, Velocity)) {
92
47
  pos.x += vel.x * dt;
93
48
  pos.y += vel.y * dt;
@@ -100,107 +55,7 @@ world.addSystem((w: any, dt: number) => {
100
55
  world.update(1 / 60);
101
56
  ```
102
57
 
103
- > Note: `SystemFn` is typed as `(world: WorldI, dt) => void` where `WorldI` only requires `flush()`.
104
- > In practice, you’ll typically use the concrete `World` API in systems (cast `world` or type your function accordingly).
105
-
106
- ---
107
-
108
- ## Query API
109
-
110
- ```ts
111
- for (const row of world.query(Position, Velocity)) {
112
- // row.e -> Entity
113
- // row.c1 -> Position
114
- // row.c2 -> Velocity
115
- }
116
- ```
117
-
118
- `query(...ctors)` yields objects shaped like:
119
-
120
- * `e`: the entity
121
- * `c1`, `c2`, `c3`, …: component values **in the same order** as the ctor arguments
122
-
123
- So if you call `query(A, B, C)` you’ll get `{ e, c1: A, c2: B, c3: C }`.
124
-
125
- ---
126
-
127
- ## Commands API (deferred ops)
128
-
129
- ```ts
130
- const cmd = world.cmd();
131
-
132
- cmd.spawn((e) => {
133
- cmd.add(e, Position, new Position(0, 0));
134
- });
135
-
136
- cmd.add(entity, Velocity, new Velocity(1, 0));
137
- cmd.remove(entity, Velocity);
138
- cmd.despawn(entity);
139
-
140
- // Apply them (World.update() also flushes automatically at end)
141
- world.flush();
142
- ```
143
-
144
- Supported commands (`Commands.ts`):
145
-
146
- * `spawn(init?)`
147
- * `despawn(e)`
148
- * `add(e, ctor, value)`
149
- * `remove(e, ctor)`
150
-
151
- ---
152
-
153
- ## Schedule (phases)
154
-
155
- `Schedule` is a small phase runner:
156
-
157
- ```ts
158
- import { World, Schedule } from "archetype-ecs-lib";
159
-
160
- const world = new World();
161
- const sched = new Schedule();
162
-
163
- sched
164
- .add("input", (w: any) => { /* read input, enqueue commands */ })
165
- .add("sim", (w: any, dt) => { /* update movement */ })
166
- .add("render",(w: any) => { /* build render data */ });
167
-
168
- const phases = ["input", "sim", "render"];
169
-
170
- // Runs each phase in order and calls world.flush() after each phase.
171
- sched.run(world, 1/60, phases);
172
- ```
173
-
174
- This is handy when you want deterministic ordering and command application points.
175
-
176
- ---
177
-
178
- ## World API summary
179
-
180
- ### Entity lifecycle
181
-
182
- * `spawn(): Entity`
183
- * `despawn(e: Entity): void`
184
- * `isAlive(e: Entity): boolean`
185
-
186
- ### Components
187
-
188
- * `has(e, Ctor): boolean`
189
- * `get(e, Ctor): T | undefined`
190
- * `set(e, Ctor, value): void` *(requires the component to exist; otherwise throws)*
191
- * `add(e, Ctor, value): void` *(structural: may move entity between archetypes)*
192
- * `remove(e, Ctor): void` *(structural: may move entity between archetypes)*
193
-
194
- ### Systems / frame
195
-
196
- * `addSystem(fn): this`
197
- * `update(dt): void` *(runs systems in order, then flushes)*
198
- * `cmd(): Commands`
199
- * `flush(): void`
200
-
201
- ### Queries
202
-
203
- * `query(...ctors): Iterable<{ e: Entity; c1?: any; c2?: any; ... }>`
58
+ > Note: `SystemFn` is typed as `(world: WorldApi, dt) => void`..
204
59
 
205
60
  ---
206
61
 
@@ -214,26 +69,4 @@ This is handy when you want deterministic ordering and command application point
214
69
 
215
70
  ## License
216
71
 
217
- ```
218
- MIT License
219
-
220
- Copyright (c) 2025 Jean-Laurent Duzant
221
-
222
- Permission is hereby granted, free of charge, to any person obtaining a copy
223
- of this software and associated documentation files (the "Software"), to deal
224
- in the Software without restriction, including without limitation the rights
225
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
226
- copies of the Software, and to permit persons to whom the Software is
227
- furnished to do so, subject to the following conditions:
228
-
229
- The above copyright notice and this permission notice shall be included in all
230
- copies or substantial portions of the Software.
231
-
232
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
233
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
234
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
235
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
236
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
237
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
238
- SOFTWARE.
239
- ```
72
+ This code is distributed under the terms and conditions of the [MIT license](https://github.com/PirateJL/archetype-ecs-lib/blob/master/LICENSE).
@@ -1,4 +1,4 @@
1
- import { Column, Entity, Signature, TypeId } from "./Types";
1
+ import type { Column, Entity, Signature, TypeId } from "./Types";
2
2
  export declare class Archetype {
3
3
  readonly id: number;
4
4
  readonly sig: Signature;
@@ -1,4 +1,4 @@
1
- import type { ComponentCtor, Entity } from "./Types";
1
+ import type { CommandsApi, ComponentCtor, ComponentCtorBundleItem, Entity } from "./Types";
2
2
  export type Command = {
3
3
  k: "spawn";
4
4
  init?: (e: Entity) => void;
@@ -15,11 +15,16 @@ export type Command = {
15
15
  e: Entity;
16
16
  ctor: ComponentCtor<any>;
17
17
  };
18
- export declare class Commands {
19
- private readonly q;
18
+ export declare class Commands implements CommandsApi {
19
+ private q;
20
20
  spawn(init?: (e: Entity) => void): void;
21
+ spawnBundle(...items: ComponentCtorBundleItem[]): void;
21
22
  despawn(e: Entity): void;
23
+ despawnBundle(entities: Entity[]): void;
22
24
  add<T>(e: Entity, ctor: ComponentCtor<T>, value: T): void;
25
+ addBundle(e: Entity, ...items: ComponentCtorBundleItem[]): void;
23
26
  remove<T>(e: Entity, ctor: ComponentCtor<T>): void;
27
+ removeBundle(e: Entity, ...ctors: ComponentCtor<any>[]): void;
28
+ hasPending(): boolean;
24
29
  drain(): Command[];
25
30
  }
@@ -1,4 +1,31 @@
1
1
  "use strict";
2
+ var __values = (this && this.__values) || function(o) {
3
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
4
+ if (m) return m.call(o);
5
+ if (o && typeof o.length === "number") return {
6
+ next: function () {
7
+ if (o && i >= o.length) o = void 0;
8
+ return { value: o && o[i++], done: !o };
9
+ }
10
+ };
11
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
12
+ };
13
+ var __read = (this && this.__read) || function (o, n) {
14
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
15
+ if (!m) return o;
16
+ var i = m.call(o), r, ar = [], e;
17
+ try {
18
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
19
+ }
20
+ catch (error) { e = { error: error }; }
21
+ finally {
22
+ try {
23
+ if (r && !r.done && (m = i["return"])) m.call(i);
24
+ }
25
+ finally { if (e) throw e.error; }
26
+ }
27
+ return ar;
28
+ };
2
29
  Object.defineProperty(exports, "__esModule", { value: true });
3
30
  exports.Commands = void 0;
4
31
  var Commands = /** @class */ (function () {
@@ -8,18 +35,101 @@ var Commands = /** @class */ (function () {
8
35
  Commands.prototype.spawn = function (init) {
9
36
  this.q.push({ k: "spawn", init: init });
10
37
  };
38
+ Commands.prototype.spawnBundle = function () {
39
+ var _this = this;
40
+ var items = [];
41
+ for (var _i = 0; _i < arguments.length; _i++) {
42
+ items[_i] = arguments[_i];
43
+ }
44
+ this.spawn(function (e) {
45
+ var e_1, _a;
46
+ try {
47
+ // Applied during the same flush thanks to World.flush draining until empty.
48
+ for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
49
+ var _b = __read(items_1_1.value, 2), ctor = _b[0], value = _b[1];
50
+ _this.add(e, ctor, value);
51
+ }
52
+ }
53
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
54
+ finally {
55
+ try {
56
+ if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
57
+ }
58
+ finally { if (e_1) throw e_1.error; }
59
+ }
60
+ });
61
+ };
11
62
  Commands.prototype.despawn = function (e) {
12
63
  this.q.push({ k: "despawn", e: e });
13
64
  };
65
+ Commands.prototype.despawnBundle = function (entities) {
66
+ var e_2, _a;
67
+ try {
68
+ for (var entities_1 = __values(entities), entities_1_1 = entities_1.next(); !entities_1_1.done; entities_1_1 = entities_1.next()) {
69
+ var e = entities_1_1.value;
70
+ this.despawn(e);
71
+ }
72
+ }
73
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
74
+ finally {
75
+ try {
76
+ if (entities_1_1 && !entities_1_1.done && (_a = entities_1.return)) _a.call(entities_1);
77
+ }
78
+ finally { if (e_2) throw e_2.error; }
79
+ }
80
+ };
14
81
  Commands.prototype.add = function (e, ctor, value) {
15
82
  this.q.push({ k: "add", e: e, ctor: ctor, value: value });
16
83
  };
84
+ Commands.prototype.addBundle = function (e) {
85
+ var e_3, _a;
86
+ var items = [];
87
+ for (var _i = 1; _i < arguments.length; _i++) {
88
+ items[_i - 1] = arguments[_i];
89
+ }
90
+ try {
91
+ for (var items_2 = __values(items), items_2_1 = items_2.next(); !items_2_1.done; items_2_1 = items_2.next()) {
92
+ var _b = __read(items_2_1.value, 2), ctor = _b[0], value = _b[1];
93
+ this.add(e, ctor, value);
94
+ }
95
+ }
96
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
97
+ finally {
98
+ try {
99
+ if (items_2_1 && !items_2_1.done && (_a = items_2.return)) _a.call(items_2);
100
+ }
101
+ finally { if (e_3) throw e_3.error; }
102
+ }
103
+ };
17
104
  Commands.prototype.remove = function (e, ctor) {
18
105
  this.q.push({ k: "remove", e: e, ctor: ctor });
19
106
  };
107
+ Commands.prototype.removeBundle = function (e) {
108
+ var e_4, _a;
109
+ var ctors = [];
110
+ for (var _i = 1; _i < arguments.length; _i++) {
111
+ ctors[_i - 1] = arguments[_i];
112
+ }
113
+ try {
114
+ for (var ctors_1 = __values(ctors), ctors_1_1 = ctors_1.next(); !ctors_1_1.done; ctors_1_1 = ctors_1.next()) {
115
+ var ctor = ctors_1_1.value;
116
+ this.remove(e, ctor);
117
+ }
118
+ }
119
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
120
+ finally {
121
+ try {
122
+ if (ctors_1_1 && !ctors_1_1.done && (_a = ctors_1.return)) _a.call(ctors_1);
123
+ }
124
+ finally { if (e_4) throw e_4.error; }
125
+ }
126
+ };
127
+ Commands.prototype.hasPending = function () {
128
+ return this.q.length > 0;
129
+ };
20
130
  Commands.prototype.drain = function () {
21
- var out = this.q.slice();
22
- this.q.length = 0;
131
+ var out = this.q;
132
+ this.q = [];
23
133
  return out;
24
134
  };
25
135
  return Commands;
@@ -1,4 +1,4 @@
1
- import { Entity, EntityMeta } from "./Types";
1
+ import type { Entity, EntityMeta } from "./Types";
2
2
  export declare class EntityManager {
3
3
  private _nextId;
4
4
  private _free;
@@ -0,0 +1,23 @@
1
+ export declare class EventChannel<T> {
2
+ private _read;
3
+ private _write;
4
+ /** Emit an event into the current phase write buffer. */
5
+ emit(ev: T): void;
6
+ /**
7
+ * Drain readable events (emitted in the previous phase), then clears the read buffer.
8
+ * Zero allocations; fast for hot paths.
9
+ */
10
+ drain(fn: (ev: T) => void): void;
11
+ /**
12
+ * Read-only view of readable events (previous phase).
13
+ * Valid until the next schedule boundary (swapEvents).
14
+ * Do not store this reference long-term.
15
+ */
16
+ values(): readonly T[];
17
+ count(): number;
18
+ clear(): void;
19
+ /** Clears both buffers (rarely needed, but useful for resets). */
20
+ clearAll(): void;
21
+ /** @internal Called by World at phase boundaries. */
22
+ swapBuffers(): void;
23
+ }
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __values = (this && this.__values) || function(o) {
3
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
4
+ if (m) return m.call(o);
5
+ if (o && typeof o.length === "number") return {
6
+ next: function () {
7
+ if (o && i >= o.length) o = void 0;
8
+ return { value: o && o[i++], done: !o };
9
+ }
10
+ };
11
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.EventChannel = void 0;
15
+ var EventChannel = /** @class */ (function () {
16
+ function EventChannel() {
17
+ this._read = [];
18
+ this._write = [];
19
+ }
20
+ /** Emit an event into the current phase write buffer. */
21
+ EventChannel.prototype.emit = function (ev) {
22
+ this._write.push(ev);
23
+ };
24
+ /**
25
+ * Drain readable events (emitted in the previous phase), then clears the read buffer.
26
+ * Zero allocations; fast for hot paths.
27
+ */
28
+ EventChannel.prototype.drain = function (fn) {
29
+ var e_1, _a;
30
+ var read = this._read;
31
+ try {
32
+ for (var read_1 = __values(read), read_1_1 = read_1.next(); !read_1_1.done; read_1_1 = read_1.next()) {
33
+ var r = read_1_1.value;
34
+ fn(r);
35
+ }
36
+ }
37
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
38
+ finally {
39
+ try {
40
+ if (read_1_1 && !read_1_1.done && (_a = read_1.return)) _a.call(read_1);
41
+ }
42
+ finally { if (e_1) throw e_1.error; }
43
+ }
44
+ this.clear();
45
+ };
46
+ /**
47
+ * Read-only view of readable events (previous phase).
48
+ * Valid until the next schedule boundary (swapEvents).
49
+ * Do not store this reference long-term.
50
+ */
51
+ EventChannel.prototype.values = function () {
52
+ return this._read;
53
+ };
54
+ EventChannel.prototype.count = function () {
55
+ return this._read.length;
56
+ };
57
+ EventChannel.prototype.clear = function () {
58
+ this._read.length = 0;
59
+ };
60
+ /** Clears both buffers (rarely needed, but useful for resets). */
61
+ EventChannel.prototype.clearAll = function () {
62
+ this._read.length = 0;
63
+ this._write.length = 0;
64
+ };
65
+ /** @internal Called by World at phase boundaries. */
66
+ EventChannel.prototype.swapBuffers = function () {
67
+ if (this._write.length === 0 && this._read.length === 0)
68
+ return;
69
+ var tmp = this._read;
70
+ this._read = this._write;
71
+ this._write = tmp;
72
+ this._write.length = 0;
73
+ };
74
+ return EventChannel;
75
+ }());
76
+ exports.EventChannel = EventChannel;
@@ -1,4 +1,4 @@
1
- import type { SystemFn, WorldI } from "./Types";
1
+ import type { SystemFn, WorldApi } from "./Types";
2
2
  /**
3
3
  * Minimal scheduler that supports phases, without borrow-checking.
4
4
  * (Add conflict detection later if you want parallelism.)
@@ -6,5 +6,5 @@ import type { SystemFn, WorldI } from "./Types";
6
6
  export declare class Schedule {
7
7
  private readonly phases;
8
8
  add(phase: string, fn: SystemFn): this;
9
- run(world: WorldI, dt: number, phaseOrder: string[]): void;
9
+ run(world: WorldApi, dt: number, phaseOrder: string[]): void;
10
10
  }
@@ -38,7 +38,16 @@ var Schedule = /** @class */ (function () {
38
38
  try {
39
39
  for (var list_1 = (e_2 = void 0, __values(list)), list_1_1 = list_1.next(); !list_1_1.done; list_1_1 = list_1.next()) {
40
40
  var fn = list_1_1.value;
41
- fn(world, dt);
41
+ try {
42
+ fn(world, dt);
43
+ }
44
+ catch (error) {
45
+ var sysName = fn.name && fn.name.length > 0 ? fn.name : "<anonymous>";
46
+ var msg = error.message !== undefined && typeof 'string' ? error.message : JSON.stringify(error);
47
+ var e = new Error("[phase=".concat(phase, " system=").concat(sysName, "] ").concat(msg));
48
+ e.cause = error;
49
+ throw e;
50
+ }
42
51
  }
43
52
  }
44
53
  catch (e_2_1) { e_2 = { error: e_2_1 }; }
@@ -49,7 +58,11 @@ var Schedule = /** @class */ (function () {
49
58
  finally { if (e_2) throw e_2.error; }
50
59
  }
51
60
  // apply deferred commands between phases
52
- world.flush();
61
+ if (world.cmd().hasPending()) {
62
+ world.flush();
63
+ }
64
+ // deliver events emitted in this phase to the next phase
65
+ world.swapEvents();
53
66
  }
54
67
  }
55
68
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -1,4 +1,4 @@
1
- import { Signature, TypeId } from "./Types";
1
+ import type { Signature, TypeId } from "./Types";
2
2
  export declare function signatureKey(sig: Signature): string;
3
3
  export declare function mergeSignature(sig: Signature, add: TypeId): TypeId[];
4
4
  export declare function subtractSignature(sig: Signature, remove: TypeId): TypeId[];
@@ -1,4 +1,4 @@
1
- import { TypeId, ComponentCtor } from "./Types";
1
+ import type { TypeId, ComponentCtor } from "./Types";
2
2
  /**
3
3
  * Returns a stable numeric TypeId for a component constructor.
4
4
  */