@margoengine/ecs 0.0.0-stage → 1.0.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,487 @@
1
- # Temporary Holding Version
1
+ # @margoengine/ecs
2
+
3
+ Import `margoengine/ecs` from the `margoengine` package, or `@margoengine/ecs` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ A sparse-set ECS with packed Float32, Float64, Int32, Uint32 and Uint8 component fields.
6
+
7
+ ```ts
8
+ import {World} from 'margoengine/ecs';
9
+ const world = new World(1024);
10
+ const position = world.component({x: Float32Array, y: Float32Array});
11
+ const entity = world.create();
12
+ position.add(entity, {x: 10});
13
+ const results = new Uint32Array(world.capacity);
14
+ const count = world.query([position], results);
15
+ ```
16
+
17
+ Numeric entity IDs include a generation, so destroyed/reused slots reject stale handles. Removal swaps the last dense row into the removed row: call component.index(entity) before using a row index. Queries write into caller-owned storage and reject undersized output. Integer writes reject truncation and overflow. A `World` has a fixed capacity; a `GrowableWorld` grows. This is a sparse-set implementation, not a second archetype storage engine.
18
+
19
+ ## Growable worlds
20
+
21
+ `GrowableWorld` (from `margoengine/ecs/growable`) doubles its slots when `create` runs out, so you do not have to guess a capacity. Everything else works as in a `World`.
22
+
23
+ ```ts
24
+ import {GrowableWorld} from 'margoengine/ecs/growable';
25
+ const world = new GrowableWorld({capacity: 1024});
26
+ const position = world.component({x: Float32Array});
27
+ const {x} = position.fields;
28
+ const results = world.allocate(Uint32Array); // keeps up with the capacity
29
+ for (let i = 0; i < 5000; i++) position.add(world.create(), {x: i});
30
+ console.log(world.capacity, x.length); // 8192 8192
31
+ console.log(world.query([position], results)); // 5000
32
+ ```
33
+
34
+ | `new GrowableWorld` option | Default | Meaning |
35
+ | --- | --- | --- |
36
+ | `capacity` | `1024` | Slots at the start |
37
+ | `limit` | `1000000` | Most slots it may grow to, at most 1,000,000; past it `create` throws `RangeError` |
38
+
39
+ Growing moves nothing: arrays sit on resizable buffers, so `component.fields`, arrays taken from them and ids all stay valid, and arrays only get longer. A `Uint32Array` you made yourself stays its size, so make query outputs with `world.allocate(Uint32Array)`. Ids are spaced by `limit`, and an id must fit 32 bits, so a slot retires after about 4,294,967,295 / `limit` reuses (4,294 at the default) and the world grows past it; lower `limit` for a world that churns entities hard. Resizable arrays cost speed: a loop over 100,000 rows took about twice as long as on a plain `World` (0.25 to 0.31 ms against 0.12 to 0.15, Node 26, busy machine, [ecs-growable.mjs](../../examples/package-benchmarks/ecs-growable.mjs)). When a bound is known, use a `World`.
40
+
41
+ ## Query filters and tags
42
+
43
+ `world.query` intersects components. `Query` (from `margoengine/ecs`, or `margoengine/ecs/query` alone) adds `without` and `optional` terms, and `world.tag()` makes a component with no fields.
44
+
45
+ ```ts
46
+ import {Query, World} from 'margoengine/ecs';
47
+ const world = new World(1024);
48
+ const position = world.component({x: Float32Array});
49
+ const health = world.component({value: Float32Array});
50
+ const frozen = world.tag();
51
+ const entity = world.create();
52
+ position.add(entity, {x: 1});
53
+ const stuck = world.create();
54
+ position.add(stuck, {x: 2});
55
+ frozen.add(stuck);
56
+ const moving = new Query(world, {with: [position], without: [frozen], optional: [health]});
57
+ moving.forEach((id, rows) => {
58
+ position.fields.x[rows[0]] += 1;
59
+ if (rows[1] >= 0) health.fields.value[rows[1]] -= 1; // -1: this entity has no health
60
+ });
61
+ const results = new Uint32Array(world.capacity);
62
+ console.log(moving.run(results), frozen.has(stuck)); // 1 true
63
+ ```
64
+
65
+ | `new Query` term | Default | Meaning |
66
+ | --- | --- | --- |
67
+ | `with` | required | An entity must have all of these; at least one |
68
+ | `without` | none | An entity must have none of these |
69
+ | `optional` | none | Never changes the match; `forEach` gives its row, or -1 |
70
+
71
+ `run(output)` writes the ids into your array. `forEach(visit)` passes the `with` rows, then the `optional` rows, in one reused `Int32Array`. It takes the match list first and looks rows up just before each call, so `visit` can add, remove and destroy; entities that stop matching are passed over, and new matches wait for the next call. A `Query` cannot run inside its own `forEach`; use a second one to nest. Tags store no field data, only the 8 bytes per world slot every component uses for its entity index.
72
+
73
+ ## Systems and scheduler
74
+
75
+ `Schedule` (from `margoengine/ecs`, or `margoengine/ecs/schedule` alone) runs named systems in a dependable order. Each `update(delta)` runs the fixed phase, then the frame phase. A `fixed: true` system runs once per step the elapsed time pays for, so physics stays deterministic at any frame rate. Everything else runs once per update.
76
+
77
+ ```ts
78
+ import {Schedule, World} from 'margoengine/ecs';
79
+ const world = new World(1024);
80
+ const position = world.component({x: Float32Array});
81
+ const velocity = world.component({x: Float32Array});
82
+ const entity = world.create();
83
+ position.add(entity, {x: 0});
84
+ velocity.add(entity, {x: 2});
85
+ const moving = new Uint32Array(world.capacity);
86
+ let paused = false;
87
+ const schedule = new Schedule({step: 1 / 60});
88
+ schedule.add('move', (time) => {
89
+ const count = world.query([position, velocity], moving);
90
+ for (let i = 0; i < count; i++) {
91
+ const id = moving[i];
92
+ position.fields.x[position.index(id)] += velocity.fields.x[velocity.index(id)] * time.delta;
93
+ }
94
+ }, {fixed: true, when: () => !paused});
95
+ schedule.add('report', () => console.log(position.fields.x[position.index(entity)]), {after: ['move']});
96
+ schedule.update(1 / 30); // two fixed steps of move, then report once
97
+ ```
98
+
99
+ | `new Schedule` option | Default | Meaning |
100
+ | --- | --- | --- |
101
+ | `step` | `1 / 60` | Seconds per fixed step |
102
+ | `maxSteps` | `8` | Most fixed steps in one update; the rest of a long stall is dropped and reported in `schedule.dropped` |
103
+
104
+ | `schedule.add` option | Default | Meaning |
105
+ | --- | --- | --- |
106
+ | `before`, `after` | none | Names of systems this one runs before or after, in the same phase; a frame system may also run `after` a fixed one |
107
+ | `when` | always | Run condition, asked before every run |
108
+ | `fixed` | `false` | Run in the fixed phase |
109
+
110
+ Systems receive `{delta, elapsed, tick, alpha, fixed}`: `delta` is the step in a fixed system and the frame time otherwise, `alpha` is the share of a step left in the accumulator, for blending the last two fixed states when drawing. The object is reused, so read it during the call. Order is `before` and `after`, then the order of `add`. `schedule.order()` lists the result. A missing name, a cycle, or a frame system ordered before a fixed one throws MargoError `'state'` from `order` or the next `update`. Systems are synchronous and run on the calling thread; a `Schedule` holds one step size, so use a second `Schedule` for a second rate.
111
+
112
+ ## Script components
113
+
114
+ `Scripts` (from `margoengine/ecs/scripts`) puts behaviour on entities the way the script components of PlayCanvas and Needle do: a script type declares typed attributes and lifecycle hooks, and any number of instances attach to an entity. One registry belongs to one `World`; there are no globals. Hooks run with the instance as `this`, which carries `entity`, `world`, `attributes`, `state` (yours, kept across hot reload) and `enabled`.
115
+
116
+ ```ts
117
+ import {Schedule, World} from 'margoengine/ecs';
118
+ import {Scripts, defineScript} from 'margoengine/ecs/scripts';
119
+ const world = new World(64);
120
+ const errors: unknown[] = [];
121
+ const scripts = new Scripts(world, {onError: (error) => errors.push(error)});
122
+ const spin = defineScript({
123
+ name: 'spin',
124
+ attributes: {
125
+ speed: {type: 'number', default: 1, min: 0, max: 10},
126
+ axis: {type: 'vec3', default: [0, 1, 0]},
127
+ tint: {type: 'color', default: '#ff8800'},
128
+ },
129
+ initialize() { this.state.angle = 0; },
130
+ update(dt) { this.state.angle += this.attributes.speed * dt; },
131
+ onAttributeChange(name, value, previous) { console.log(name, previous, '->', value); },
132
+ });
133
+ scripts.register(spin);
134
+ const entity = world.create();
135
+ const instance = scripts.add(entity, spin, {values: {speed: 2}});
136
+ const schedule = new Schedule();
137
+ scripts.install(schedule); // frame system "scripts" and fixed system "scripts.fixed"
138
+ schedule.update(0.5);
139
+ instance.attributes.speed = 4; // validated; logs: speed 2 -> 4
140
+ console.log(instance.state.angle); // 1
141
+ // Hot reload: same instances, attribute values and state, no new initialize.
142
+ scripts.reload(defineScript({
143
+ name: 'spin',
144
+ attributes: {speed: {type: 'number', default: 1}, axis: {type: 'vec3'}},
145
+ update(dt) { this.state.angle += this.attributes.speed * dt * 2; },
146
+ swap(previous) { console.log('swapped from', previous.name); },
147
+ }));
148
+ schedule.update(0.5);
149
+ console.log(instance.state.angle, scripts.schema()[0].attributes.map((a) => a.name)); // 5 [ 'speed', 'axis' ]
150
+ scripts.dispose();
151
+ ```
152
+
153
+ | Attribute `type` | Value | Options |
154
+ | --- | --- | --- |
155
+ | `number` | finite number, default 0 | `min`, `max` |
156
+ | `boolean`, `string` | default `false`, `''` | none |
157
+ | `enum` | one of `options`, default the first | `options` (required) |
158
+ | `vec2`, `vec3`, `vec4` | array of that many finite numbers, default zeros | `min`, `max` per element |
159
+ | `color` | `[r, g, b, a]` in 0..1, or `'#rgb'` / `'#rrggbb'`, default white | `min`, `max` (inside 0..1) |
160
+ | `entity`, `asset` | entity id or asset id string, default `null` | `assetKind` hint |
161
+
162
+ Every attribute also takes `default` and `title` (an inspector label). A bad default throws when the script is defined; a bad value throws `RangeError` naming the attribute when it is added or assigned. `scripts.schema()` returns every registered type's attributes as JSON-safe data for an inspector.
163
+
164
+ | Hook | When |
165
+ | --- | --- |
166
+ | `onEnable`, `initialize`, `postInitialize` | First `update`, `fixedUpdate` or `flush` after `add` while enabled: every `initialize` of the batch, then every `postInitialize` |
167
+ | `update(dt)`, `postUpdate(dt)` | Each `scripts.update(dt)`, every `update` before any `postUpdate`, ordered by `priority` then by `add` |
168
+ | `fixedUpdate(step)` | Each `scripts.fixedUpdate(step)` |
169
+ | `onEnable`, `onDisable` | `instance.enabled` changes; a disabled instance gets no update hooks |
170
+ | `onAttributeChange(name, value, previous)` | An attribute is assigned a different value after `initialize` |
171
+ | `destroy` | `scripts.remove`, `world.destroy(entity)` or dispose, after `onDisable` |
172
+ | `swap(previous)` | Hot reload, on the new type |
173
+
174
+ `scripts.reload(newType, {reinitialize})` swaps the implementation registered under that name. Instances stay with their attribute values (kept when the attribute still exists and is valid, else reset to the new default), `state`, enabled flag and order. `initialize` runs again only with `reinitialize: true`, after the old `onDisable` and `destroy`, with `state` cleared. An error thrown by a hook goes to `onError(error, {script, hook})` and the other scripts still run; without `onError` the pass finishes and throws one MargoError `'failed'` whose `cause` is the first error. `scripts.dispose()` (or `using`) destroys every instance.
175
+
176
+ Sources: the feature set follows the public documentation of PlayCanvas script components (attributes, initialize/postInitialize/update/postUpdate, enable/disable, swap for hot reload) and Needle Engine components; the code is written clean room from those feature names.
177
+
178
+ ## Coroutines
179
+
180
+ `Coroutines` (from `@margoengine/ecs/coroutines`) runs multi-frame logic written as a generator, so a sequence reads top to bottom instead of as a state machine. `update(dt)` steps every running coroutine once; `install(schedule)` adds a frame system that does it. A bare `yield` waits one update, `yield 0.5` waits half a second, `yield promise` waits for a promise (a rejection is thrown into the generator at that `yield`), and `yield other` waits until another coroutine ends. `start(generator)` returns a `Coroutine` with `cancel()`, `active` and `done`; `run(generator)` is the async form and returns `done`, which resolves when the generator returns and rejects with an AbortError when it is cancelled. Cancelling runs the generator's `finally` blocks. Pass `{signal}` to cancel with an `AbortSignal`.
181
+
182
+ ```ts
183
+ import {Schedule} from '@margoengine/ecs/schedule';
184
+ import {Coroutines} from '@margoengine/ecs/coroutines';
185
+
186
+ const coroutines = new Coroutines();
187
+ const schedule = new Schedule();
188
+ coroutines.install(schedule);
189
+ const log: string[] = [];
190
+ function* door() {
191
+ log.push('open');
192
+ yield 0.2; // seconds
193
+ log.push('close');
194
+ }
195
+ const sequence = coroutines.run(door());
196
+ for (let i = 0; i < 30; i++) schedule.update(1 / 60);
197
+ await sequence;
198
+ console.log(log); // ['open', 'close']
199
+ const blink = coroutines.start((function* () { while (true) yield; })());
200
+ blink.cancel(); // blink.done rejects with an AbortError
201
+ coroutines.dispose();
202
+ ```
203
+
204
+ A coroutine that throws goes to `onError(error, coroutine)` when you pass it, otherwise `update` rethrows a MargoError `'failed'` with the first error as `cause` after stepping the others. `update` throws a RangeError for a negative or non-finite `dt`, and a coroutine that yields a negative number gets one thrown at its `yield`. A script can start coroutines from its hooks and cancel them in `destroy`. The pattern follows the coroutine runners of other engines' public docs; the stepping is plain generator protocol.
205
+
206
+ ## Change detection
207
+
208
+ `ChangeTracker` (from `margoengine/ecs`, or `margoengine/ecs/changes` alone) answers which entities gained, changed or lost one component since its last `clear()`.
209
+
210
+ ```ts
211
+ import {ChangeTracker, World} from 'margoengine/ecs';
212
+ const world = new World(1024);
213
+ const health = world.component({value: Float32Array});
214
+ const tracker = new ChangeTracker(health);
215
+ const entity = world.create();
216
+ health.add(entity, {value: 100});
217
+ const results = new Uint32Array(world.capacity);
218
+ console.log(tracker.added(results)); // 1, results[0] is the entity
219
+ tracker.clear();
220
+ health.add(entity, {value: 90}); // seen
221
+ health.fields.value[health.index(entity)] = 80; // not seen by itself...
222
+ health.touch(entity); // ...until reported
223
+ console.log(tracker.changed(results)); // 1
224
+ tracker.clear();
225
+ world.destroy(entity);
226
+ console.log(tracker.removed(results)); // 1, results[0] is now a stale id
227
+ tracker.stop();
228
+ ```
229
+
230
+ `fields` are plain typed arrays, so a direct write cannot be seen: call `component.touch(entity)` after one, or write through `component.add`. Results are net over the window: added then removed reports nothing, removed then added back is `changed`, added then written stays `added`. Each tracker keeps its own window, so systems can read at their own pace; call `clear()` when one is done, for example in a last system of a `Schedule`. `stop()`, or `using`, detaches a tracker. A tracker costs 24 bytes per world slot. To react at once instead of reading a window, push your own `{onAdd, onChange, onRemove}` onto `component.observers`; do not add or remove rows of that component from inside one.
231
+
232
+ ## Object fields
233
+
234
+ `ObjectComponent` (from `margoengine/ecs/objects`) holds any JavaScript value, such as a string, an array, a callback or a whole object, beside packed numeric fields. Declare a value field with `objectField(create)`: `create` runs for every new row, so each row gets its own array or object, and without one the field starts `undefined`.
235
+
236
+ ```ts
237
+ import {ChangeTracker, Query, World} from 'margoengine/ecs';
238
+ import {ObjectComponent, objectField} from 'margoengine/ecs/objects';
239
+ const world = new World(1024);
240
+ const unit = new ObjectComponent(world, {
241
+ name: objectField(() => 'unit'),
242
+ path: objectField((): number[][] => []), // a new array for every row
243
+ target: objectField(), // undefined until set
244
+ hp: Uint8Array,
245
+ });
246
+ const tracker = new ChangeTracker(unit);
247
+ const a = world.create();
248
+ const b = world.create();
249
+ unit.add(a, {name: 'scout', hp: 40});
250
+ unit.add(b, {target: a});
251
+ console.log(unit.fields.name[unit.index(b)], unit.fields.hp[unit.index(b)]); // unit 0
252
+ console.log(unit.fields.path[0] !== unit.fields.path[1]); // true
253
+ tracker.clear();
254
+ unit.fields.path[unit.index(a)].push([3, 4]); // not seen by itself...
255
+ unit.touch(a); // ...until reported
256
+ const results = new Uint32Array(world.capacity);
257
+ console.log(tracker.changed(results)); // 1
258
+ new Query(world, {with: [unit]}).forEach((id, rows) => {
259
+ console.log(unit.fields.name[rows[0]]); // scout, then unit
260
+ });
261
+ world.destroy(a); // b moves to row 0; row 1's references are dropped
262
+ console.log(unit.index(b), unit.fields.name.length); // 0 1
263
+ tracker.stop();
264
+ ```
265
+
266
+ An `ObjectComponent` is a component like any other: `Query`, `world.query`, `ChangeTracker`, `ReactiveQuery`, `RelationQuery`, `WorldSerializer` and `observers` take it, and `fields`, `index`, `has`, `add`, `touch` and `remove` work as on a numeric one. A value field is a plain array in `fields`, indexed with `component.index(entity)` like the typed arrays beside it, and the schema types each one from its factory, so `fields.name` reads as `string[]`.
267
+
268
+ - **Identity:** a stored value is the value you passed, never a copy: objects, functions and cycles keep their identity, and `add` does not check value fields at all. Numeric fields are checked as on any component, and an unknown field throws `RangeError`.
269
+ - **Atomic add:** every value is checked, and every factory of a new row run, before the row changes. A bad number, an unknown field or a factory that throws leaves the entity without a row (or its old row unchanged); a value you pass for a new row skips that field's factory.
270
+ - **Row lifetime:** removal moves the last row into the gap, value fields included, and shortens each value array, so a removed row's values are no longer held by the component and can be collected. Call `index(entity)` again after any removal.
271
+ - **Changes:** writing into a stored object (`path.push`) or into `fields` directly is invisible to trackers, as for numeric fields; call `touch(entity)` after, or write the field again through `add`, which reports a change.
272
+ - **References to entities:** a value field holding an entity id keeps that id after the entity is destroyed, and `world.alive(id)` tells you. For pairs that end with their entities, use `Relation`.
273
+
274
+ A value field holds a strong reference; `weakObjectField` below holds a weak one.
275
+
276
+ ### Weak reference fields
277
+
278
+ `weakObjectField()` declares a field that holds a `WeakRef` to each row's value, so the component never keeps the value alive: once nothing else holds it, the garbage collector may take it and the row reads `undefined`. Use it for caches, back-pointers to scene objects and anything owned elsewhere.
279
+
280
+ ```ts
281
+ import {World} from 'margoengine/ecs';
282
+ import {ObjectComponent, objectField, weakObjectField} from 'margoengine/ecs/objects';
283
+ const world = new World(64);
284
+ const view = new ObjectComponent(world, {
285
+ node: weakObjectField<{name: string}>(), // owned by the scene graph, not by the ECS
286
+ label: objectField(() => ''),
287
+ });
288
+ const scene = {name: 'crate'};
289
+ const e = world.create();
290
+ view.add(e, {node: scene, label: 'crate'});
291
+ console.log(view.fields.node[view.index(e)]?.name); // crate, while the scene still holds it
292
+ view.add(e, {node: undefined}); // clear it
293
+ console.log(view.fields.node[view.index(e)]); // undefined
294
+ ```
295
+
296
+ - **Values:** an object, a function, an unregistered symbol or `undefined`. Anything else (a number, a string, a `Symbol.for` symbol) throws `TypeError`, from `add` before the row changes, from a factory before the row is made, and from a direct write into `fields`.
297
+ - **Reading:** `fields.node[row]` reads the value through `deref()`, so test for `undefined` each time you read; a value stays readable at least until the current task ends (ECMAScript keeps a `WeakRef` target alive for the rest of the job that made or read it).
298
+ - **Same rules as strong fields:** atomic add, row moves on removal, `touch` and change reports work as above. A weak field serializes the value it holds at that moment.
299
+
300
+ Sources: ECMA-262, 2021 edition, section 26.1 *WeakRef Objects* (https://tc39.es/ecma262/#sec-weak-ref-objects), from the TC39 WeakRefs proposal by D. Tribble, M. Miller, T. Schneidereit, S. Gunasekaran and D. Ehrenberg (https://github.com/tc39/proposal-weakrefs); B. Hayes, *Ephemerons: a new finalization mechanism*, OOPSLA 1997 (https://doi.org/10.1145/263698.263733); the Becsy `Type.weakObject` field documentation (https://lastolivegames.github.io/becsy/guide/architecture/components) as the rival feature matched.
301
+
302
+ ## Relationships
303
+
304
+ `Relation` (from `margoengine/ecs`, or `margoengine/ecs/relations` alone) holds pairs of entities with a meaning you name. A pair goes from a source to a target and reads both ways.
305
+
306
+ ```ts
307
+ import {Relation, World} from 'margoengine/ecs';
308
+ const world = new World(1024);
309
+ const childOf = new Relation(world, {exclusive: true, cascade: true, acyclic: true});
310
+ const owns = new Relation(world);
311
+ const ship = world.create();
312
+ const turret = world.create();
313
+ const barrel = world.create();
314
+ childOf.add(turret, ship);
315
+ childOf.add(barrel, turret);
316
+ owns.add(ship, barrel);
317
+ owns.add(ship, turret);
318
+ const results = new Uint32Array(world.capacity);
319
+ console.log(childOf.target(barrel) === turret); // true
320
+ console.log(childOf.sources(ship, results)); // 1: the children of ship
321
+ console.log(childOf.descendants(ship, results)); // 2: turret, then barrel
322
+ console.log(owns.targets(ship, results)); // 2
323
+ world.destroy(ship); // turret and barrel go with it; every pair ends
324
+ console.log(world.alive(barrel), owns.size); // false 0
325
+ ```
326
+
327
+ | `new Relation` option | Default | Meaning |
328
+ | --- | --- | --- |
329
+ | `exclusive` | `false` | A source has at most one target; a new pair replaces the old one |
330
+ | `cascade` | `false` | Destroying a target destroys its sources, all the way down |
331
+ | `acyclic` | `false` | `add` throws `TypeError` for a pair that would close a loop |
332
+
333
+ `has`, `target`, `targets`, `sources`, `descendants` and `forEach` read pairs directly. Results go into your `Uint32Array`, oldest pair first, and `descendants` is breadth first, so parents come before children. Pairs of a destroyed entity always end. An `acyclic` add walks up from the target, so it costs the depth of the hierarchy. `stop()`, or `using`, ends all pairs and detaches from the world. Pairs live in Maps and Sets, not typed arrays: keep per-frame data in components.
334
+
335
+ ## Relation queries
336
+
337
+ `RelationQuery` (from `margoengine/ecs/relation-query`) joins entities through `Relation` pairs: it finds sources by their components and their pairs, and gives back each pair's target and the target's component rows.
338
+
339
+ ```ts
340
+ import {Relation, World} from 'margoengine/ecs';
341
+ import {RelationQuery} from 'margoengine/ecs/relation-query';
342
+ const world = new World(1024);
343
+ const position = world.component({x: Float32Array});
344
+ const fuel = world.component({litres: Float32Array});
345
+ const docked = world.tag();
346
+ const dockedAt = new Relation(world, {exclusive: true});
347
+ const likes = new Relation(world);
348
+ const station = world.create();
349
+ fuel.add(station, {litres: 500});
350
+ const moon = world.create();
351
+ const a = world.create();
352
+ const b = world.create();
353
+ position.add(a, {x: 1});
354
+ position.add(b, {x: 2});
355
+ dockedAt.add(a, station);
356
+ dockedAt.add(b, moon); // moon has no fuel
357
+ likes.add(a, station);
358
+ likes.add(a, moon);
359
+ // Ships with a position docked at something with fuel, and every target they like.
360
+ const refuel = new RelationQuery(world, {
361
+ with: [position],
362
+ without: [docked],
363
+ relations: [{relation: dockedAt, with: [fuel]}, {relation: likes}],
364
+ });
365
+ const sources = new Uint32Array(world.capacity);
366
+ const at = new Uint32Array(world.capacity);
367
+ const liked = new Uint32Array(world.capacity);
368
+ console.log(refuel.run(sources, [at, liked])); // 2: a at station likes station, a at station likes moon
369
+ console.log(sources[0] === a, at[0] === station, liked[1] === moon); // true true true
370
+ refuel.forEach((ship, rows, targets, targetRows) => {
371
+ fuel.fields.litres[targetRows[0]] -= 10; // targetRows: the with rows of each term, in order
372
+ position.fields.x[rows[0]] += 1;
373
+ });
374
+ console.log(fuel.fields.litres[fuel.index(station)]); // 480
375
+ const atStation = new RelationQuery(world, {relations: [{relation: dockedAt, target: station}]});
376
+ console.log(atStation.run(sources), sources[0] === a); // 1 true
377
+ ```
378
+
379
+ | Term | Default | Meaning |
380
+ | --- | --- | --- |
381
+ | `relations` | none | Required pair terms; a source must hold a pair of every term. A query needs one, or a `with` component |
382
+ | `optionalRelations` | none | Pair terms that never stop a match; an absent one gives `NO_TARGET` |
383
+ | `withoutRelations` | none | Pair terms a source must not match |
384
+ | `relations[i].relation` | required | A `Relation` of this world, or `'*'` for any of them |
385
+ | `relations[i].target` | `'*'` | One target id, or `'*'` for any target |
386
+ | `relations[i].with` | none | Components the target must have; their rows come back |
387
+ | `with` | none | Components the source must have |
388
+ | `without` | none | Components the source must not have |
389
+ | `optional` | none | Never changes the match; `forEach` gives its row, or -1 |
390
+
391
+ - **Products.** A source matches once for every combination of its pairs, one target per term, so a source with two
392
+ matching `likes` pairs and one `dockedAt` pair appears twice. Sources come in the order of their first pair under
393
+ the first term, and each term's targets oldest pair first. Two terms may name the same relation; each picks a target
394
+ on its own, so the same target can fill both. The product is built in memory, so a source with many pairs under
395
+ several wildcard terms costs their product.
396
+ - **`run(output, targets?)`** writes one source id per combination into `output`, and with `targets`, one
397
+ `Uint32Array` per term, the target that term picked. It returns the count and throws `RangeError`, writing
398
+ nothing, when an array is too short or `targets` does not hold one array per term.
399
+ - **`forEach(visit)`** calls `visit(source, rows, targets, targetRows, relations)` per combination: `rows` holds the source's
400
+ `with` rows then its `optional` rows (-1 when absent), `targets` the picked targets in term order, and `targetRows`
401
+ each term's `with` rows, the terms one after another. The arrays are reused between calls, so copy what you keep.
402
+ It takes the matches first and checks each one again just before its call, so `visit` may add or remove pairs,
403
+ components and entities: a combination that stopped matching (a pair gone, an entity destroyed, a component lost)
404
+ is passed over, and new matches wait for the next call. It returns the number of calls made.
405
+ - **Nesting.** A query cannot run, or visit, inside its own `forEach` (MargoError `'state'`); use a second query.
406
+ - **Errors.** No required pair term and no `with` component, a relation or component of another world, or a target that is neither `'*'` nor a
407
+ 32-bit entity id throws `TypeError` at construction. An exact target that is destroyed simply matches nothing.
408
+
409
+ ### Negated, optional and wildcard pair terms
410
+
411
+ `withoutRelations` leaves out a source with any matching pair, `optionalRelations` adds pair terms that never stop a match, and `relation: '*'` matches a pair of any relation of the world. A query needs at least one required pair term or one `with` component, which then supplies the sources.
412
+
413
+ ```ts
414
+ import {Relation, World} from 'margoengine/ecs';
415
+ import {NO_TARGET, RelationQuery} from 'margoengine/ecs/relation-query';
416
+ const world = new World(1024);
417
+ const position = world.component({x: Float32Array});
418
+ const dockedAt = new Relation(world, {exclusive: true});
419
+ const orbits = new Relation(world);
420
+ const station = world.create();
421
+ const [a, b, c] = [world.create(), world.create(), world.create()];
422
+ for (const ship of [a, b, c]) position.add(ship, {x: 0});
423
+ dockedAt.add(a, station);
424
+ orbits.add(c, station);
425
+ const ids = new Uint32Array(world.capacity);
426
+ // Ships with a position that are docked nowhere.
427
+ const undocked = new RelationQuery(world, {with: [position], withoutRelations: [{relation: dockedAt}]});
428
+ console.log(undocked.run(ids)); // 2: b and c
429
+ // Anything with a pair to the station, whatever the relation; relations[0] says which one matched.
430
+ const near = new RelationQuery(world, {relations: [{relation: '*', target: station}]});
431
+ near.forEach((ship, rows, targets, targetRows, relations) => {
432
+ console.log(ship === a ? 'a' : 'c', relations[0] === dockedAt ? 'docked' : 'orbiting');
433
+ }); // a docked, then c orbiting
434
+ // Every ship, with its dock when it has one.
435
+ const docks = new Uint32Array(world.capacity);
436
+ const all = new RelationQuery(world, {with: [position], optionalRelations: [{relation: dockedAt}]});
437
+ const n = all.run(ids, [docks]);
438
+ for (let i = 0; i < n; i++) console.log(docks[i] === NO_TARGET ? 'undocked' : 'docked'); // docked, undocked, undocked
439
+ ```
440
+
441
+ - **Columns.** `targets` columns and `targetRows` hold the required terms, then the optional ones; `termCount` is
442
+ their number. An optional term enumerates every matching pair like a required one; a source with none gets one
443
+ match with target `NO_TARGET` (0xffffffff), target rows -1 and `relations[i]` undefined.
444
+ - **Negated terms** take the same `relation`, `target` and `with` as any pair term: a source is left out when it holds
445
+ a pair of that relation to that target whose target has those components. In `forEach` a source that gains such a
446
+ pair before its call is passed over.
447
+ - **Relation wildcard.** `relation: '*'` reads every `Relation` made on this world and not stopped, oldest first
448
+ (`worldRelations(world)` from `margoengine/ecs/relations` lists them). A source with pairs of two relations to the
449
+ same target matches once per relation.
450
+
451
+ Sources: E. F. Codd, *A relational model of data for large shared data banks*, CACM 13(6), 1970
452
+ (https://doi.org/10.1145/362384.362685), for the join and the anti-join a negated term is; S. Abiteboul, R. Hull and
453
+ V. Vianu, *Foundations of Databases*, Addison-Wesley 1995, chapter 15 (negation in Datalog, stratified and
454
+ safe: a negated term only filters sources already bound by a positive one); S. Mertens, the Flecs query manual
455
+ (https://www.flecs.dev/flecs/md_docs_2Queries.html), `Not` and `Optional` operators and `(*, target)` pairs; bitECS
456
+ 0.4 `Not`, `Pair` and `Wildcard` (https://github.com/NateTheGreatt/bitECS/blob/main/docs/Intro.md), the rival matched.
457
+
458
+ ## Engine bridge
459
+
460
+ `MeshBridge` (from `margoengine/ecs/engine`) copies a transform component to core meshes in one bulk step a frame, so systems work on packed arrays and never touch a mesh. It writes through `TransformWriter` from `@margoengine/scene/bulk`, an optional peer of this entry: `margoengine` includes it, and with the `@margoengine/*` packages install `@margoengine/scene` beside `@margoengine/ecs`.
461
+
462
+ ```ts
463
+ import {createStage} from 'margoengine';
464
+ import {World} from 'margoengine/ecs';
465
+ import {MeshBridge, transformSchema} from 'margoengine/ecs/engine';
466
+ const stage = await createStage('#app');
467
+ const world = new World(1024);
468
+ const transform = world.component(transformSchema);
469
+ const bridge = new MeshBridge(transform, {disposeMeshes: true});
470
+ const entity = world.create();
471
+ bridge.link(entity, stage.box());
472
+ stage.onTick((delta) => {
473
+ transform.fields.x[transform.index(entity)] += delta;
474
+ bridge.sync();
475
+ });
476
+ ```
477
+
478
+ | `new MeshBridge` option | Default | Meaning |
479
+ | --- | --- | --- |
480
+ | `disposeMeshes` | `false` | Dispose a linked mesh when its entity loses the component or is destroyed |
481
+
482
+ `transformSchema` is position `x y z`, quaternion `qx qy qz qw` and scale `sx sy sz`. A component may hold any of those three groups, whole; a mesh keeps its own values for a group the component lacks. `link(entity, mesh)` fills a new row from the mesh, so nothing jumps; a row made by hand needs `qw: 1` and a scale, or `sync` throws the mesh's RangeError. `sync()` takes one pass over the links to find what moved, then makes one `TransformWriter` write per changed group for each run of rows that changed, so a world where everything moves costs three writes and a world where nothing moves costs that pass alone. The checks and the result are those of the mesh's setters, `mesh.rotation` included, and a group the mesh already holds is left alone. The first `sync` after a link or unlink builds the writer again, about one pass over the links. A link ends with `unlink(entity)`, when the entity loses the component or is destroyed, or with `stop()`. A mesh disposed behind the bridge makes `sync` throw MargoError `'disposed'` rather than write to whichever mesh reuses its slot. Transforms are local to the mesh's parent; set hierarchies on the meshes with `setParent`.
483
+
484
+ Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
485
+
486
+ Build and unit tests: npm test --workspace @margoengine/ecs
2
487
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
@@ -0,0 +1,39 @@
1
+ import type { ComponentStore as Component } from './index.js';
2
+ /**
3
+ * What happened to one component since the last {@link ChangeTracker.clear}, as a net result: an entity added and
4
+ * removed again in the window is not reported at all, one removed and added back is `changed`, and one added and then
5
+ * written stays `added`. Each tracker has its own window, so two systems can read the same component at their own pace.
6
+ *
7
+ * Writes through `component.add` are seen; writes straight into `component.fields` are not until `component.touch`
8
+ * reports them.
9
+ */
10
+ export declare class ChangeTracker {
11
+ readonly component: Component;
12
+ private readonly addedSet;
13
+ private readonly changedSet;
14
+ private readonly removedSet;
15
+ private readonly observer;
16
+ /** Start tracking `component`; changes before this call are not reported. */
17
+ constructor(component: Component);
18
+ /**
19
+ * Write the entities that gained the component into `output`, in no fixed order; returns how many.
20
+ * @throws RangeError when `output` is too small (`world.capacity` entries always fit).
21
+ */
22
+ added(output: Uint32Array): number;
23
+ /**
24
+ * Write the entities whose row was written and that had the component before the window; returns how many.
25
+ * @throws RangeError when `output` is too small (`world.capacity` entries always fit).
26
+ */
27
+ changed(output: Uint32Array): number;
28
+ /**
29
+ * Write the entities that lost the component, destroyed ones included (their ids are stale); returns how many.
30
+ * @throws RangeError when `output` is too small (`world.capacity` entries always fit).
31
+ */
32
+ removed(output: Uint32Array): number;
33
+ /** Start a new window: forget everything reported so far. Costs one step per change held, not per entity. */
34
+ clear(): void;
35
+ /** Stop tracking. What the tracker holds can still be read. Safe to call twice. */
36
+ stop(): void;
37
+ /** `stop()`, for `using` (on runtimes that have `Symbol.dispose`). */
38
+ [Symbol.dispose]: () => void;
39
+ }
@@ -0,0 +1,63 @@
1
+ //#region src/changes.ts
2
+ var e = class {
3
+ constructor(e) {
4
+ this.size = 0, this.dense = e.allocate(Uint32Array), this.sparse = e.allocate(Int32Array, -1), this.stride = e.stride;
5
+ }
6
+ has(e) {
7
+ let t = this.sparse[e % this.stride];
8
+ return t >= 0 && this.dense[t] === e;
9
+ }
10
+ add(e) {
11
+ this.has(e) || (this.sparse[e % this.stride] = this.size, this.dense[this.size++] = e);
12
+ }
13
+ delete(e) {
14
+ if (!this.has(e)) return;
15
+ let t = e % this.stride, n = this.sparse[t], r = this.dense[--this.size];
16
+ this.sparse[t] = -1, n !== this.size && (this.dense[n] = r, this.sparse[r % this.stride] = n);
17
+ }
18
+ clear() {
19
+ for (let e = 0; e < this.size; e++) this.sparse[this.dense[e] % this.stride] = -1;
20
+ this.size = 0;
21
+ }
22
+ copy(e) {
23
+ if (e.length < this.size) throw RangeError("Change output is too small; pass a Uint32Array at least as long as the entity count (world.capacity always fits)");
24
+ return e.set(this.dense.subarray(0, this.size)), this.size;
25
+ }
26
+ }, t = class {
27
+ constructor(t) {
28
+ this.component = t;
29
+ let { world: n } = t, r = this.addedSet = new e(n), i = this.changedSet = new e(n), a = this.removedSet = new e(n);
30
+ this.observer = {
31
+ onAdd(e) {
32
+ a.has(e) ? (a.delete(e), i.add(e)) : r.add(e);
33
+ },
34
+ onChange(e) {
35
+ r.has(e) || i.add(e);
36
+ },
37
+ onRemove(e) {
38
+ r.has(e) ? r.delete(e) : (i.delete(e), a.add(e));
39
+ }
40
+ }, t.observers.push(this.observer);
41
+ }
42
+ added(e) {
43
+ return this.addedSet.copy(e);
44
+ }
45
+ changed(e) {
46
+ return this.changedSet.copy(e);
47
+ }
48
+ removed(e) {
49
+ return this.removedSet.copy(e);
50
+ }
51
+ clear() {
52
+ this.addedSet.clear(), this.changedSet.clear(), this.removedSet.clear();
53
+ }
54
+ stop() {
55
+ let { observers: e } = this.component, t = e.indexOf(this.observer);
56
+ t >= 0 && e.splice(t, 1);
57
+ }
58
+ [Symbol.dispose ?? Symbol()]() {
59
+ this.stop();
60
+ }
61
+ };
62
+ //#endregion
63
+ export { t as ChangeTracker };