@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/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +486 -2
- package/dist/changes.d.ts +39 -0
- package/dist/changes.js +63 -0
- package/dist/coroutines.d.ts +82 -0
- package/dist/coroutines.js +97 -0
- package/dist/engine.d.ts +80 -0
- package/dist/engine.js +164 -0
- package/dist/growable.d.ts +23 -0
- package/dist/growable.js +28 -0
- package/dist/index.d.ts +145 -0
- package/dist/index.js +166 -0
- package/dist/objects.d.ts +43 -0
- package/dist/objects.js +78 -0
- package/dist/parallel-runtime.d.ts +43 -0
- package/dist/parallel.d.ts +102 -0
- package/dist/parallel.js +280 -0
- package/dist/parallel.worker.d.ts +1 -0
- package/dist/query.d.ts +42 -0
- package/dist/query.js +61 -0
- package/dist/reactive.d.ts +59 -0
- package/dist/reactive.js +106 -0
- package/dist/relation-query.d.ts +77 -0
- package/dist/relation-query.js +123 -0
- package/dist/relations.d.ts +72 -0
- package/dist/relations.js +99 -0
- package/dist/schedule.d.ts +82 -0
- package/dist/schedule.js +109 -0
- package/dist/scripts.d.ts +182 -0
- package/dist/scripts.js +278 -0
- package/dist/serialize-codec.d.ts +34 -0
- package/dist/serialize.d.ts +34 -0
- package/dist/serialize.js +355 -0
- package/dist/workers/parallel.js +1 -0
- package/package.json +105 -4
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { worldRelations as e } from "./relations.js";
|
|
2
|
+
import { MargoError as t } from "@margoengine/math/errors";
|
|
3
|
+
//#region src/relation-query.ts
|
|
4
|
+
var n = 4294967295, r = class {
|
|
5
|
+
constructor(e, t) {
|
|
6
|
+
this.world = e, this.visiting = !1, this.scratch = /* @__PURE__ */ new Uint32Array();
|
|
7
|
+
let n = (e) => ({
|
|
8
|
+
relation: e.relation,
|
|
9
|
+
target: e.target ?? "*",
|
|
10
|
+
with: [...e.with ?? []]
|
|
11
|
+
}), r = (t.relations ?? []).map(n), i = (t.optionalRelations ?? []).map(n), a = (t.withoutRelations ?? []).map(n), o = [
|
|
12
|
+
...r,
|
|
13
|
+
...i,
|
|
14
|
+
...a
|
|
15
|
+
];
|
|
16
|
+
if (this.with = [...t.with ?? []], this.without = [...t.without ?? []], this.optional = [...t.optional ?? []], !r.length && !this.with.length || o.some((t) => t.relation !== "*" && (typeof t.relation != "object" || t.relation === null || t.relation.world !== e) || t.target !== "*" && (!Number.isInteger(t.target) || t.target < 0 || t.target > 4294967295)) || [
|
|
17
|
+
...this.with,
|
|
18
|
+
...this.without,
|
|
19
|
+
...this.optional,
|
|
20
|
+
...o.flatMap((e) => e.with)
|
|
21
|
+
].some((t) => t.world !== e)) throw TypeError("Invalid relation query; use a pair term or a with component, relations of this world or *, and Uint32 targets or *");
|
|
22
|
+
this.required = r, this.optionalTerms = i, this.excludedTerms = a;
|
|
23
|
+
}
|
|
24
|
+
get termCount() {
|
|
25
|
+
return this.required.length + this.optionalTerms.length;
|
|
26
|
+
}
|
|
27
|
+
buffer() {
|
|
28
|
+
return this.scratch.length < this.world.capacity && (this.scratch = new Uint32Array(this.world.capacity)), this.scratch;
|
|
29
|
+
}
|
|
30
|
+
relationsOf(t) {
|
|
31
|
+
return t.relation === "*" ? e(this.world) : [t.relation];
|
|
32
|
+
}
|
|
33
|
+
targetOk(e, t) {
|
|
34
|
+
return (e.target === "*" || e.target === t) && e.with.every((e) => e.has(t));
|
|
35
|
+
}
|
|
36
|
+
pairs(e) {
|
|
37
|
+
let t = /* @__PURE__ */ new Map();
|
|
38
|
+
for (let n of this.relationsOf(e)) n.forEach((r, i) => {
|
|
39
|
+
if (!this.targetOk(e, i)) return;
|
|
40
|
+
let a = t.get(r);
|
|
41
|
+
a ? a.push({
|
|
42
|
+
relation: n,
|
|
43
|
+
target: i
|
|
44
|
+
}) : t.set(r, [{
|
|
45
|
+
relation: n,
|
|
46
|
+
target: i
|
|
47
|
+
}]);
|
|
48
|
+
});
|
|
49
|
+
return t;
|
|
50
|
+
}
|
|
51
|
+
excluded(e) {
|
|
52
|
+
for (let t of this.excludedTerms) for (let n of this.relationsOf(t)) {
|
|
53
|
+
if (t.target !== "*") {
|
|
54
|
+
if (n.has(e, t.target) && this.targetOk(t, t.target)) return !0;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
let r = this.buffer(), i = n.targets(e, r);
|
|
58
|
+
for (let e = 0; e < i; e++) if (this.targetOk(t, r[e])) return !0;
|
|
59
|
+
}
|
|
60
|
+
return !1;
|
|
61
|
+
}
|
|
62
|
+
allowed(e, t) {
|
|
63
|
+
return !this.world.alive(e) || !this.with.every((t) => t.has(e)) || this.without.some((t) => t.has(e)) || this.excluded(e) ? !1 : !t || [...this.required, ...this.optionalTerms].every((n, r) => {
|
|
64
|
+
let i = t.relations[r], a = t.targets[r];
|
|
65
|
+
return !i || this.world.alive(a) && i.has(e, a) && n.with.every((e) => e.has(a));
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
collect() {
|
|
69
|
+
if (this.visiting) throw new t("state", "Relation query is visiting; use a second query for a nested call");
|
|
70
|
+
let e = this.required.map((e) => this.pairs(e)), r = this.optionalTerms.map((e) => this.pairs(e)), i;
|
|
71
|
+
if (e.length) i = e[0].keys();
|
|
72
|
+
else {
|
|
73
|
+
let e = new Uint32Array(this.world.capacity);
|
|
74
|
+
i = e.subarray(0, this.world.query(this.with, e));
|
|
75
|
+
}
|
|
76
|
+
let a = [{
|
|
77
|
+
relation: void 0,
|
|
78
|
+
target: n
|
|
79
|
+
}], o = [];
|
|
80
|
+
for (let t of i) {
|
|
81
|
+
if (e.some((e) => !e.has(t)) || !this.allowed(t)) continue;
|
|
82
|
+
let n = [...e.map((e) => e.get(t)), ...r.map((e) => e.get(t) ?? a)], i = [[]];
|
|
83
|
+
for (let e of n) i = i.flatMap((t) => e.map((e) => [...t, e]));
|
|
84
|
+
for (let e of i) o.push({
|
|
85
|
+
source: t,
|
|
86
|
+
targets: e.map((e) => e.target),
|
|
87
|
+
relations: e.map((e) => e.relation)
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return o;
|
|
91
|
+
}
|
|
92
|
+
run(e, t) {
|
|
93
|
+
let n = this.collect();
|
|
94
|
+
if (e.length < n.length || t && (t.length !== this.termCount || t.some((e) => e.length < n.length))) throw RangeError("Relation query output is too small; allocate one row per pair combination and one target column per term");
|
|
95
|
+
return n.forEach((n, r) => {
|
|
96
|
+
e[r] = n.source, t?.forEach((e, t) => {
|
|
97
|
+
e[r] = n.targets[t];
|
|
98
|
+
});
|
|
99
|
+
}), n.length;
|
|
100
|
+
}
|
|
101
|
+
forEach(e) {
|
|
102
|
+
let t = this.collect(), n = [...this.with, ...this.optional], r = [...this.required, ...this.optionalTerms], i = new Int32Array(n.length), a = new Uint32Array(r.length), o = Array(r.length), s = new Int32Array(r.reduce((e, t) => e + t.with.length, 0)), c = 0;
|
|
103
|
+
this.visiting = !0;
|
|
104
|
+
try {
|
|
105
|
+
for (let l of t) {
|
|
106
|
+
if (!this.allowed(l.source, l)) continue;
|
|
107
|
+
n.forEach((e, t) => {
|
|
108
|
+
i[t] = e.index(l.source);
|
|
109
|
+
}), a.set(l.targets);
|
|
110
|
+
let t = 0;
|
|
111
|
+
r.forEach((e, n) => {
|
|
112
|
+
o[n] = l.relations[n];
|
|
113
|
+
for (let r of e.with) s[t++] = l.relations[n] ? r.index(a[n]) : -1;
|
|
114
|
+
}), e(l.source, i, a, s, o), c++;
|
|
115
|
+
}
|
|
116
|
+
} finally {
|
|
117
|
+
this.visiting = !1;
|
|
118
|
+
}
|
|
119
|
+
return c;
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
//#endregion
|
|
123
|
+
export { n as NO_TARGET, r as RelationQuery };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { Entity, World } from './index.js';
|
|
2
|
+
/** Rules of a {@link Relation}. For parent and child use all three: `{exclusive: true, cascade: true, acyclic: true}`. */
|
|
3
|
+
export interface RelationOptions {
|
|
4
|
+
/** A source has at most one target: a new pair replaces the old one. Default false. */
|
|
5
|
+
exclusive?: boolean;
|
|
6
|
+
/** Destroying a target destroys its sources, and theirs, all the way down. Default false: only the pairs end. */
|
|
7
|
+
cascade?: boolean;
|
|
8
|
+
/** Refuse a pair that would close a loop. Default false. */
|
|
9
|
+
acyclic?: boolean;
|
|
10
|
+
}
|
|
11
|
+
/** The relations of `world` that are not stopped, oldest first; a relation wildcard in `RelationQuery` reads these. */
|
|
12
|
+
export declare function worldRelations(world: World): readonly Relation[];
|
|
13
|
+
/**
|
|
14
|
+
* Pairs of entities with a meaning you name: `childOf`, `owns`, `targets`. A pair goes from a source to a target, and
|
|
15
|
+
* both directions can be read directly. Pairs of a destroyed entity end with it.
|
|
16
|
+
*/
|
|
17
|
+
export declare class Relation {
|
|
18
|
+
readonly world: World;
|
|
19
|
+
/** Pairs held now. */
|
|
20
|
+
size: number;
|
|
21
|
+
/** True when a source has at most one target. */
|
|
22
|
+
readonly exclusive: boolean;
|
|
23
|
+
/** True when destroying a target destroys its sources. */
|
|
24
|
+
readonly cascade: boolean;
|
|
25
|
+
/** True when pairs that close a loop are refused. */
|
|
26
|
+
readonly acyclic: boolean;
|
|
27
|
+
private readonly forward;
|
|
28
|
+
private readonly backward;
|
|
29
|
+
private readonly pending;
|
|
30
|
+
private draining;
|
|
31
|
+
private readonly store;
|
|
32
|
+
constructor(world: World, { exclusive, cascade, acyclic }?: RelationOptions);
|
|
33
|
+
/**
|
|
34
|
+
* Add the pair; false when it already exists. On an exclusive relation it replaces the source's old pair.
|
|
35
|
+
* @throws MargoError `'state'` when either entity is stale or destroyed.
|
|
36
|
+
* @throws TypeError on an acyclic relation when the pair would close a loop; nothing changes.
|
|
37
|
+
*/
|
|
38
|
+
add(source: Entity, target: Entity): boolean;
|
|
39
|
+
/** End the pair; false when there is none. Neither entity is destroyed. */
|
|
40
|
+
remove(source: Entity, target: Entity): boolean;
|
|
41
|
+
/** True when the pair exists. */
|
|
42
|
+
has(source: Entity, target: Entity): boolean;
|
|
43
|
+
/** The first target of `source`, the only one on an exclusive relation (a child's parent); undefined when it has none. */
|
|
44
|
+
target(source: Entity): Entity | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Write what `source` points at into `output`, oldest pair first; returns how many.
|
|
47
|
+
* @throws RangeError when `output` is too small (`world.capacity` entries always fit).
|
|
48
|
+
*/
|
|
49
|
+
targets(source: Entity, output: Uint32Array): number;
|
|
50
|
+
/**
|
|
51
|
+
* Write what points at `target` into `output`, oldest pair first (a parent's children); returns how many.
|
|
52
|
+
* @throws RangeError when `output` is too small (`world.capacity` entries always fit).
|
|
53
|
+
*/
|
|
54
|
+
sources(target: Entity, output: Uint32Array): number;
|
|
55
|
+
/**
|
|
56
|
+
* Write everything below `target`, breadth first (nearest first): its sources, their sources and so on, without
|
|
57
|
+
* `target` itself and each entity once, even in a loop; returns how many.
|
|
58
|
+
* @throws RangeError when `output` is too small (`world.capacity` entries always fit).
|
|
59
|
+
*/
|
|
60
|
+
descendants(target: Entity, output: Uint32Array): number;
|
|
61
|
+
/** Call `visit` for every pair. Pairs added during the loop may or may not be visited. */
|
|
62
|
+
forEach(visit: (source: Entity, target: Entity) => void): void;
|
|
63
|
+
/** End every pair and stop following the world. Safe to call twice. */
|
|
64
|
+
stop(): void;
|
|
65
|
+
[Symbol.dispose]: () => void;
|
|
66
|
+
private link;
|
|
67
|
+
private unlink;
|
|
68
|
+
/** True when walking targets from `from` arrives at `goal`, `from` itself included. */
|
|
69
|
+
private reaches;
|
|
70
|
+
/** The world is destroying `entity`. Cascades run from a list, so a deep hierarchy cannot overflow the call stack. */
|
|
71
|
+
private forget;
|
|
72
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
//#region src/relations.ts
|
|
2
|
+
var e = (e, t) => {
|
|
3
|
+
if (!e) return 0;
|
|
4
|
+
if (t.length < e.size) throw RangeError("Relation output is too small; pass a Uint32Array at least as long as the entity count (world.capacity always fits)");
|
|
5
|
+
let n = 0;
|
|
6
|
+
for (let r of e) t[n++] = r;
|
|
7
|
+
return n;
|
|
8
|
+
}, t = /* @__PURE__ */ new WeakMap();
|
|
9
|
+
function n(e) {
|
|
10
|
+
return [...t.get(e) ?? []];
|
|
11
|
+
}
|
|
12
|
+
var r = class {
|
|
13
|
+
constructor(e, { exclusive: n = !1, cascade: r = !1, acyclic: i = !1 } = {}) {
|
|
14
|
+
this.world = e, this.size = 0, this.forward = /* @__PURE__ */ new Map(), this.backward = /* @__PURE__ */ new Map(), this.pending = [], this.draining = !1, this.store = { remove: (e) => this.forget(e) }, this.exclusive = n, this.cascade = r, this.acyclic = i, e.attach(this.store);
|
|
15
|
+
let a = t.get(e);
|
|
16
|
+
a || t.set(e, a = /* @__PURE__ */ new Set()), a.add(this);
|
|
17
|
+
}
|
|
18
|
+
add(e, t) {
|
|
19
|
+
if (this.world.check(e), this.world.check(t), this.has(e, t)) return !1;
|
|
20
|
+
if (this.acyclic && this.reaches(t, e)) throw TypeError("Relation pair would close a loop; remove a pair first, or drop the acyclic option");
|
|
21
|
+
if (this.exclusive) {
|
|
22
|
+
let t = this.forward.get(e);
|
|
23
|
+
if (t) for (let n of t) this.remove(e, n);
|
|
24
|
+
}
|
|
25
|
+
return this.link(this.forward, e, t), this.link(this.backward, t, e), this.size++, !0;
|
|
26
|
+
}
|
|
27
|
+
remove(e, t) {
|
|
28
|
+
return this.has(e, t) ? (this.unlink(this.forward, e, t), this.unlink(this.backward, t, e), this.size--, !0) : !1;
|
|
29
|
+
}
|
|
30
|
+
has(e, t) {
|
|
31
|
+
return this.forward.get(e)?.has(t) ?? !1;
|
|
32
|
+
}
|
|
33
|
+
target(e) {
|
|
34
|
+
let t = this.forward.get(e);
|
|
35
|
+
if (t) for (let e of t) return e;
|
|
36
|
+
}
|
|
37
|
+
targets(t, n) {
|
|
38
|
+
return e(this.forward.get(t), n);
|
|
39
|
+
}
|
|
40
|
+
sources(t, n) {
|
|
41
|
+
return e(this.backward.get(t), n);
|
|
42
|
+
}
|
|
43
|
+
descendants(e, t) {
|
|
44
|
+
let n = /* @__PURE__ */ new Set([e]), r = 0;
|
|
45
|
+
for (let i = -1; i < r; i++) {
|
|
46
|
+
let a = this.backward.get(i < 0 ? e : t[i]);
|
|
47
|
+
if (a) {
|
|
48
|
+
for (let e of a) if (!n.has(e)) {
|
|
49
|
+
if (n.add(e), r === t.length) throw RangeError("Relation output is too small; pass a Uint32Array at least as long as the entity count (world.capacity always fits)");
|
|
50
|
+
t[r++] = e;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return r;
|
|
55
|
+
}
|
|
56
|
+
forEach(e) {
|
|
57
|
+
for (let [t, n] of this.forward) for (let r of n) e(t, r);
|
|
58
|
+
}
|
|
59
|
+
stop() {
|
|
60
|
+
this.world.detach(this.store), t.get(this.world)?.delete(this), this.forward.clear(), this.backward.clear(), this.size = 0;
|
|
61
|
+
}
|
|
62
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
63
|
+
this.stop();
|
|
64
|
+
}
|
|
65
|
+
link(e, t, n) {
|
|
66
|
+
let r = e.get(t);
|
|
67
|
+
r ? r.add(n) : e.set(t, /* @__PURE__ */ new Set([n]));
|
|
68
|
+
}
|
|
69
|
+
unlink(e, t, n) {
|
|
70
|
+
let r = e.get(t);
|
|
71
|
+
r.delete(n), r.size || e.delete(t);
|
|
72
|
+
}
|
|
73
|
+
reaches(e, t) {
|
|
74
|
+
let n = /* @__PURE__ */ new Set([e]), r = [e];
|
|
75
|
+
for (; r.length;) {
|
|
76
|
+
let e = r.pop();
|
|
77
|
+
if (e === t) return !0;
|
|
78
|
+
for (let t of this.forward.get(e) ?? []) n.has(t) || (n.add(t), r.push(t));
|
|
79
|
+
}
|
|
80
|
+
return !1;
|
|
81
|
+
}
|
|
82
|
+
forget(e) {
|
|
83
|
+
for (let t of [...this.forward.get(e) ?? []]) this.remove(e, t);
|
|
84
|
+
for (let t of [...this.backward.get(e) ?? []]) this.remove(t, e), this.cascade && this.pending.push(t);
|
|
85
|
+
if (!this.draining) {
|
|
86
|
+
this.draining = !0;
|
|
87
|
+
try {
|
|
88
|
+
for (; this.pending.length;) {
|
|
89
|
+
let e = this.pending.pop();
|
|
90
|
+
this.world.alive(e) && this.world.destroy(e);
|
|
91
|
+
}
|
|
92
|
+
} finally {
|
|
93
|
+
this.draining = !1, this.pending.length = 0;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
//#endregion
|
|
99
|
+
export { r as Relation, n as worldRelations };
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** What a system sees when it runs. One object is reused, so read it during the call and do not keep it. */
|
|
2
|
+
export interface ScheduleTime {
|
|
3
|
+
/** Seconds this run covers: the fixed step in a fixed system, the frame's time otherwise. */
|
|
4
|
+
delta: number;
|
|
5
|
+
/** Seconds on this phase's clock: steps times the step for fixed systems, the sum of frame times otherwise. */
|
|
6
|
+
elapsed: number;
|
|
7
|
+
/** Runs of this phase so far, starting at 1: the step number in a fixed system, the frame number otherwise. */
|
|
8
|
+
tick: number;
|
|
9
|
+
/** Share of a step still waiting in the accumulator, in [0, 1): blend two fixed states with it. 0 in fixed systems. */
|
|
10
|
+
alpha: number;
|
|
11
|
+
/** True in a fixed system. */
|
|
12
|
+
fixed: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** A system: plain code that reads and writes components, usually through a closure over them. */
|
|
15
|
+
export type SystemRun = (time: Readonly<ScheduleTime>) => void;
|
|
16
|
+
/** Where and when a system runs. */
|
|
17
|
+
export interface SystemOptions {
|
|
18
|
+
/** Names of systems this one runs before. Default none. */
|
|
19
|
+
before?: readonly string[];
|
|
20
|
+
/** Names of systems this one runs after. Default none. */
|
|
21
|
+
after?: readonly string[];
|
|
22
|
+
/** Run condition, asked before every run; the system is passed over when it returns false. Default: always run. */
|
|
23
|
+
when?: (time: Readonly<ScheduleTime>) => boolean;
|
|
24
|
+
/** Run in the fixed phase, zero or more times a frame at the schedule's step. Default false. */
|
|
25
|
+
fixed?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/** Settings of a {@link Schedule}. */
|
|
28
|
+
export interface ScheduleOptions {
|
|
29
|
+
/** Seconds per fixed step, above 0. Default 1/60. */
|
|
30
|
+
step?: number;
|
|
31
|
+
/** Most fixed steps in one update; time past that is dropped, so a long stall cannot snowball. Default 8. */
|
|
32
|
+
maxSteps?: number;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Named systems in a dependable order. Each {@link Schedule.update} runs the fixed phase (every `fixed` system, once per
|
|
36
|
+
* step the elapsed time pays for), then the frame phase (every other system, once). Order inside a phase comes from
|
|
37
|
+
* `before` and `after`, then from the order of `add`.
|
|
38
|
+
*/
|
|
39
|
+
export declare class Schedule {
|
|
40
|
+
/** Seconds per fixed step. */
|
|
41
|
+
readonly step: number;
|
|
42
|
+
/** Most fixed steps in one update. */
|
|
43
|
+
readonly maxSteps: number;
|
|
44
|
+
/** Seconds of frame time thrown away by the last update because of `maxSteps`. */
|
|
45
|
+
dropped: number;
|
|
46
|
+
private readonly entries;
|
|
47
|
+
private fixedPhase;
|
|
48
|
+
private framePhase;
|
|
49
|
+
private accumulator;
|
|
50
|
+
private steps;
|
|
51
|
+
private frames;
|
|
52
|
+
private clock;
|
|
53
|
+
private running;
|
|
54
|
+
private readonly time;
|
|
55
|
+
/** @throws RangeError for a step that is not a finite number above 0, or a maxSteps that is not a positive integer. */
|
|
56
|
+
constructor({ step, maxSteps }?: ScheduleOptions);
|
|
57
|
+
/**
|
|
58
|
+
* Add a system. Added during an update, it first runs in the next one. Names in `before` and `after` are resolved by
|
|
59
|
+
* the next update, so systems can be added in any order.
|
|
60
|
+
* @throws TypeError for an empty or repeated name, or a `run`, `when`, `before` or `after` of the wrong type.
|
|
61
|
+
*/
|
|
62
|
+
add(name: string, run: SystemRun, options?: SystemOptions): this;
|
|
63
|
+
/** Remove a system; false when there is none. Removed during an update, it does not run again, in that update either. */
|
|
64
|
+
remove(name: string): boolean;
|
|
65
|
+
/** True when a system has this name. */
|
|
66
|
+
has(name: string): boolean;
|
|
67
|
+
/**
|
|
68
|
+
* System names in run order, fixed phase first.
|
|
69
|
+
* @throws MargoError `'state'` when `before` or `after` name a missing system, form a cycle, or ask a frame system to
|
|
70
|
+
* run before a fixed one (the fixed phase always comes first).
|
|
71
|
+
*/
|
|
72
|
+
order(): string[];
|
|
73
|
+
/**
|
|
74
|
+
* Advance by `delta` seconds and run the systems; returns the number of fixed steps run. An error from a system
|
|
75
|
+
* reaches the caller and ends the update; time not yet stepped stays in the accumulator.
|
|
76
|
+
* @throws RangeError for a `delta` that is negative or not finite.
|
|
77
|
+
* @throws MargoError `'state'` when called from inside a system, and for the order errors of {@link Schedule.order}.
|
|
78
|
+
*/
|
|
79
|
+
update(delta: number): number;
|
|
80
|
+
private pass;
|
|
81
|
+
private resolve;
|
|
82
|
+
}
|
package/dist/schedule.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { MargoError as e } from "@margoengine/math/errors";
|
|
2
|
+
//#region src/schedule.ts
|
|
3
|
+
var t = (e, t) => {
|
|
4
|
+
if (e === void 0) return [];
|
|
5
|
+
if (!Array.isArray(e) || e.some((e) => typeof e != "string")) throw TypeError(`System ${t} is not a list of names; pass an array of system names`);
|
|
6
|
+
return [...e];
|
|
7
|
+
};
|
|
8
|
+
function n(t, n) {
|
|
9
|
+
let r = new Map(t.map((e) => [e, 0]));
|
|
10
|
+
for (let e of t) for (let t of n.get(e) ?? []) r.set(t, r.get(t) + 1);
|
|
11
|
+
let i = [];
|
|
12
|
+
for (; i.length < t.length;) {
|
|
13
|
+
let a = t.find((e) => r.get(e) === 0);
|
|
14
|
+
if (!a) {
|
|
15
|
+
let n = t.filter((e) => r.get(e) > 0).map((e) => e.name);
|
|
16
|
+
throw new e("state", `System order has a cycle among ${n.join(", ")}; remove a before or after`);
|
|
17
|
+
}
|
|
18
|
+
r.set(a, -1), i.push(a);
|
|
19
|
+
for (let e of n.get(a) ?? []) r.set(e, r.get(e) - 1);
|
|
20
|
+
}
|
|
21
|
+
return i;
|
|
22
|
+
}
|
|
23
|
+
var r = class {
|
|
24
|
+
constructor({ step: e = 1 / 60, maxSteps: t = 8 } = {}) {
|
|
25
|
+
if (this.dropped = 0, this.entries = /* @__PURE__ */ new Map(), this.framePhase = [], this.accumulator = 0, this.steps = 0, this.frames = 0, this.clock = 0, this.running = !1, this.time = {
|
|
26
|
+
delta: 0,
|
|
27
|
+
elapsed: 0,
|
|
28
|
+
tick: 0,
|
|
29
|
+
alpha: 0,
|
|
30
|
+
fixed: !1
|
|
31
|
+
}, !Number.isFinite(e) || e <= 0) throw RangeError("Invalid schedule step; use a finite number of seconds above 0, e.g. 1 / 60");
|
|
32
|
+
if (!Number.isSafeInteger(t) || t < 1) throw RangeError("Invalid schedule maxSteps; use a positive integer, e.g. 8");
|
|
33
|
+
this.step = e, this.maxSteps = t;
|
|
34
|
+
}
|
|
35
|
+
add(e, n, r = {}) {
|
|
36
|
+
if (typeof e != "string" || !e) throw TypeError("Invalid system name; pass a non-empty string");
|
|
37
|
+
if (this.entries.has(e)) throw TypeError(`System ${e} already exists; remove it or use another name`);
|
|
38
|
+
if (typeof n != "function") throw TypeError("Invalid system; pass a function");
|
|
39
|
+
let { when: i, fixed: a = !1 } = r;
|
|
40
|
+
if (i !== void 0 && typeof i != "function") throw TypeError("Invalid system condition; pass a function that returns a boolean");
|
|
41
|
+
let o = t(r.before, "before"), s = t(r.after, "after");
|
|
42
|
+
return this.entries.set(e, {
|
|
43
|
+
name: e,
|
|
44
|
+
run: n,
|
|
45
|
+
before: o,
|
|
46
|
+
after: s,
|
|
47
|
+
when: i,
|
|
48
|
+
fixed: !!a,
|
|
49
|
+
removed: !1
|
|
50
|
+
}), this.fixedPhase = void 0, this;
|
|
51
|
+
}
|
|
52
|
+
remove(e) {
|
|
53
|
+
let t = this.entries.get(e);
|
|
54
|
+
return t ? (t.removed = !0, this.entries.delete(e), this.fixedPhase = void 0, !0) : !1;
|
|
55
|
+
}
|
|
56
|
+
has(e) {
|
|
57
|
+
return this.entries.has(e);
|
|
58
|
+
}
|
|
59
|
+
order() {
|
|
60
|
+
return this.resolve(), [...this.fixedPhase, ...this.framePhase].map((e) => e.name);
|
|
61
|
+
}
|
|
62
|
+
update(t) {
|
|
63
|
+
if (this.running) throw new e("state", "Schedule is already updating; do not call update from a system");
|
|
64
|
+
if (!Number.isFinite(t) || t < 0) throw RangeError("Invalid schedule delta; pass a finite number of seconds, 0 or more");
|
|
65
|
+
this.resolve();
|
|
66
|
+
let n = this.step, r = this.time, i = this.fixedPhase, a = this.framePhase;
|
|
67
|
+
this.running = !0;
|
|
68
|
+
try {
|
|
69
|
+
this.accumulator += t;
|
|
70
|
+
let e = 0;
|
|
71
|
+
for (r.delta = n, r.alpha = 0, r.fixed = !0; this.accumulator >= n && e < this.maxSteps;) this.accumulator -= n, e++, r.tick = ++this.steps, r.elapsed = this.steps * n, this.pass(i);
|
|
72
|
+
if (this.dropped = 0, this.accumulator >= n) {
|
|
73
|
+
let e = this.accumulator % n;
|
|
74
|
+
this.dropped = this.accumulator - e, this.accumulator = e;
|
|
75
|
+
}
|
|
76
|
+
return this.clock += t, r.delta = t, r.elapsed = this.clock, r.tick = ++this.frames, r.alpha = this.accumulator / n, r.fixed = !1, this.pass(a), e;
|
|
77
|
+
} finally {
|
|
78
|
+
this.running = !1;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
pass(e) {
|
|
82
|
+
let t = this.time;
|
|
83
|
+
for (let n = 0; n < e.length; n++) {
|
|
84
|
+
let r = e[n];
|
|
85
|
+
!r.removed && (!r.when || r.when(t)) && r.run(t);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
resolve() {
|
|
89
|
+
if (this.fixedPhase) return;
|
|
90
|
+
let t = /* @__PURE__ */ new Map(), r = (n, r) => {
|
|
91
|
+
if (n.fixed && !r.fixed) return;
|
|
92
|
+
if (!n.fixed && r.fixed) throw new e("state", `Frame system ${n.name} cannot run before fixed system ${r.name}; the fixed phase runs first, so drop the order or make both fixed`);
|
|
93
|
+
let i = t.get(n);
|
|
94
|
+
i ? i.push(r) : t.set(n, [r]);
|
|
95
|
+
}, i = (t, n) => {
|
|
96
|
+
let r = this.entries.get(t);
|
|
97
|
+
if (!r) throw new e("state", `System ${n.name} is ordered against ${t}, which is missing; add it`);
|
|
98
|
+
return r;
|
|
99
|
+
}, a = [...this.entries.values()];
|
|
100
|
+
for (let e of a) {
|
|
101
|
+
for (let t of e.before) r(e, i(t, e));
|
|
102
|
+
for (let t of e.after) r(i(t, e), e);
|
|
103
|
+
}
|
|
104
|
+
let o = n(a.filter((e) => !e.fixed), t);
|
|
105
|
+
this.fixedPhase = n(a.filter((e) => e.fixed), t), this.framePhase = o;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
//#endregion
|
|
109
|
+
export { r as Schedule };
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import type { Entity, World } from './index.js';
|
|
2
|
+
import type { Schedule } from './schedule.js';
|
|
3
|
+
/** Value kinds of a script attribute. `vec2`, `vec3` and `vec4` hold number arrays; `color` is `[r, g, b, a]` in 0..1; `asset` is an id string. */
|
|
4
|
+
export type AttributeType = 'number' | 'boolean' | 'string' | 'enum' | 'vec2' | 'vec3' | 'vec4' | 'color' | 'entity' | 'asset';
|
|
5
|
+
/** One declared attribute. `default` is validated when the script is defined. */
|
|
6
|
+
export interface AttributeSpec {
|
|
7
|
+
type: AttributeType;
|
|
8
|
+
/** Default value. Default: 0, false, '', the first option, zeros, [1, 1, 1, 1] for color, or null for entity and asset. */
|
|
9
|
+
default?: unknown;
|
|
10
|
+
/** Smallest number, or smallest vector/color element. Default none. */
|
|
11
|
+
min?: number;
|
|
12
|
+
/** Largest number, or largest vector/color element. Default none. */
|
|
13
|
+
max?: number;
|
|
14
|
+
/** Allowed values of an `enum` (strings or numbers). Required for `enum`. */
|
|
15
|
+
options?: readonly (string | number)[];
|
|
16
|
+
/** Label for an inspector. Default: the attribute name. */
|
|
17
|
+
title?: string;
|
|
18
|
+
/** Asset kind hint for an inspector ('texture', 'model'...). Default none. */
|
|
19
|
+
assetKind?: string;
|
|
20
|
+
}
|
|
21
|
+
/** Attribute declarations by name. */
|
|
22
|
+
export type AttributeSpecs = Record<string, AttributeSpec>;
|
|
23
|
+
/** A live attribute value set (getters and setters that validate). */
|
|
24
|
+
export type AttributeValues = Record<string, any>;
|
|
25
|
+
/** A running script. Hooks are called with it as `this`. */
|
|
26
|
+
export interface ScriptInstance {
|
|
27
|
+
readonly entity: Entity;
|
|
28
|
+
readonly world: World;
|
|
29
|
+
readonly type: ScriptType;
|
|
30
|
+
/** Validated attributes; assigning one runs `onAttributeChange`. */
|
|
31
|
+
readonly attributes: AttributeValues;
|
|
32
|
+
/** Free-form state the script owns; it survives a hot reload. */
|
|
33
|
+
state: Record<string, any>;
|
|
34
|
+
/** True while the instance receives updates. Assign to enable or disable it. */
|
|
35
|
+
enabled: boolean;
|
|
36
|
+
/** True after `initialize` ran, until `destroy`. */
|
|
37
|
+
readonly initialized: boolean;
|
|
38
|
+
}
|
|
39
|
+
/** Lifecycle hooks of a script. All optional. */
|
|
40
|
+
export interface ScriptHooks {
|
|
41
|
+
/** Once, on the first update after the instance is added and enabled. `onEnable` runs just before it. */
|
|
42
|
+
initialize?(this: ScriptInstance): void;
|
|
43
|
+
/** Once, after every `initialize` of that batch has run. */
|
|
44
|
+
postInitialize?(this: ScriptInstance): void;
|
|
45
|
+
/** Every `Scripts.update`, with the frame time. */
|
|
46
|
+
update?(this: ScriptInstance, dt: number): void;
|
|
47
|
+
/** Every `Scripts.update`, after all `update` hooks. */
|
|
48
|
+
postUpdate?(this: ScriptInstance, dt: number): void;
|
|
49
|
+
/** Every `Scripts.fixedUpdate`, with the fixed step. */
|
|
50
|
+
fixedUpdate?(this: ScriptInstance, step: number): void;
|
|
51
|
+
onEnable?(this: ScriptInstance): void;
|
|
52
|
+
onDisable?(this: ScriptInstance): void;
|
|
53
|
+
/** An attribute was assigned a different value. */
|
|
54
|
+
onAttributeChange?(this: ScriptInstance, name: string, value: any, previous: any): void;
|
|
55
|
+
/** Instance removed, entity destroyed, or registry disposed; `onDisable` ran first when it was enabled. */
|
|
56
|
+
destroy?(this: ScriptInstance): void;
|
|
57
|
+
/** Hot reload: called on the instance of the NEW type with the type it replaces, to migrate `state`. */
|
|
58
|
+
swap?(this: ScriptInstance, previous: ScriptType): void;
|
|
59
|
+
}
|
|
60
|
+
/** Definition passed to {@link defineScript}. */
|
|
61
|
+
export interface ScriptDefinition extends ScriptHooks {
|
|
62
|
+
/** Unique name within a registry; hot reload matches by it. */
|
|
63
|
+
name: string;
|
|
64
|
+
attributes?: AttributeSpecs;
|
|
65
|
+
/** Run order across instances, lowest first, ties by order of `add`. Default 0. */
|
|
66
|
+
priority?: number;
|
|
67
|
+
}
|
|
68
|
+
/** A defined script type. */
|
|
69
|
+
export interface ScriptType extends ScriptHooks {
|
|
70
|
+
readonly name: string;
|
|
71
|
+
readonly priority: number;
|
|
72
|
+
readonly attributes: Readonly<Record<string, Readonly<AttributeSpec & {
|
|
73
|
+
title: string;
|
|
74
|
+
}>>>;
|
|
75
|
+
}
|
|
76
|
+
/** The hook that failed, for {@link ScriptsOptions.onError}. */
|
|
77
|
+
export type ScriptHook = keyof ScriptHooks;
|
|
78
|
+
/** Settings of {@link Scripts}. */
|
|
79
|
+
export interface ScriptsOptions {
|
|
80
|
+
/**
|
|
81
|
+
* Called for every error a script throws, so one failing script never stops the others. Default: errors are
|
|
82
|
+
* collected and rethrown after the pass as one MargoError `'failed'` whose `cause` is the first.
|
|
83
|
+
*/
|
|
84
|
+
onError?: (error: unknown, info: {
|
|
85
|
+
script: ScriptInstance;
|
|
86
|
+
hook: ScriptHook;
|
|
87
|
+
}) => void;
|
|
88
|
+
}
|
|
89
|
+
/** Options of {@link Scripts.add}. */
|
|
90
|
+
export interface AddScriptOptions {
|
|
91
|
+
/** Attribute values; others use defaults. */
|
|
92
|
+
values?: Record<string, unknown>;
|
|
93
|
+
/** Start enabled. Default true. */
|
|
94
|
+
enabled?: boolean;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Declare a script type: typed attributes plus lifecycle hooks. Register it with {@link Scripts.register}.
|
|
98
|
+
* @throws TypeError for a missing name, an unknown attribute type or a hook that is not a function.
|
|
99
|
+
* @throws RangeError for a default outside its own min/max or options.
|
|
100
|
+
*/
|
|
101
|
+
export declare function defineScript(def: ScriptDefinition): ScriptType;
|
|
102
|
+
/**
|
|
103
|
+
* Script components for a {@link World}: add scripts to entities, run their hooks, hot reload them. One registry per
|
|
104
|
+
* world; nothing is global. `using scripts = new Scripts(world)` destroys every instance at scope end.
|
|
105
|
+
*/
|
|
106
|
+
export declare class Scripts {
|
|
107
|
+
readonly world: World;
|
|
108
|
+
private readonly options;
|
|
109
|
+
private readonly types;
|
|
110
|
+
private all;
|
|
111
|
+
private readonly byEntity;
|
|
112
|
+
private pending;
|
|
113
|
+
private seq;
|
|
114
|
+
private errors;
|
|
115
|
+
private busy;
|
|
116
|
+
private disposed;
|
|
117
|
+
private readonly store;
|
|
118
|
+
constructor(world: World, options?: ScriptsOptions);
|
|
119
|
+
/** Register a script type; it must be registered before `add`. @throws TypeError when the name is taken (use {@link Scripts.reload}). */
|
|
120
|
+
register(type: ScriptType): this;
|
|
121
|
+
/** The registered type of that name, or undefined. */
|
|
122
|
+
get(name: string): ScriptType | undefined;
|
|
123
|
+
/** Inspector schema of every registered type, as plain JSON-safe data. */
|
|
124
|
+
schema(): {
|
|
125
|
+
name: string;
|
|
126
|
+
priority: number;
|
|
127
|
+
attributes: {
|
|
128
|
+
name: string;
|
|
129
|
+
type: AttributeType;
|
|
130
|
+
default: unknown;
|
|
131
|
+
title: string;
|
|
132
|
+
}[];
|
|
133
|
+
}[];
|
|
134
|
+
/**
|
|
135
|
+
* Attach a script to an entity, after the scripts it already has. Its hooks start on the next update or fixedUpdate.
|
|
136
|
+
* @throws MargoError `'state'` for a stale entity, an unregistered type or a disposed registry.
|
|
137
|
+
* @throws RangeError for an unknown or invalid attribute value.
|
|
138
|
+
*/
|
|
139
|
+
add(entity: Entity, type: ScriptType | string, { values, enabled }?: AddScriptOptions): ScriptInstance;
|
|
140
|
+
/** Instances on an entity, in the order they were added. */
|
|
141
|
+
on(entity: Entity): readonly ScriptInstance[];
|
|
142
|
+
/**
|
|
143
|
+
* Remove one instance, or every script of an entity (only those of `type` when given). Each runs `onDisable` (when
|
|
144
|
+
* enabled) then `destroy` if it had been initialised. Returns the number removed.
|
|
145
|
+
*/
|
|
146
|
+
remove(target: ScriptInstance | Entity, type?: ScriptType | string): number;
|
|
147
|
+
/** Run pending `onEnable`, `initialize` and `postInitialize` hooks now; `update` and `fixedUpdate` call this first. */
|
|
148
|
+
flush(): void;
|
|
149
|
+
/** One frame: flush, then `update` of every enabled instance, then `postUpdate`. @throws RangeError for a negative or non-finite `dt`. */
|
|
150
|
+
update(dt: number): void;
|
|
151
|
+
/** One fixed step: flush, then `fixedUpdate` of every enabled instance. */
|
|
152
|
+
fixedUpdate(step: number): void;
|
|
153
|
+
/** Add a frame system `scripts` (update, postUpdate) and a fixed system `scripts.fixed` (fixedUpdate) to a {@link Schedule}. */
|
|
154
|
+
install(schedule: Schedule, options?: {
|
|
155
|
+
before?: readonly string[];
|
|
156
|
+
after?: readonly string[];
|
|
157
|
+
}): this;
|
|
158
|
+
/**
|
|
159
|
+
* Hot reload: replace the registered type of the same name with a new implementation. Instances stay, with their
|
|
160
|
+
* attribute values (kept where the attribute still exists and is valid, otherwise reset to the new default), `state`,
|
|
161
|
+
* enabled flag and order. The new type's `swap(previous)` runs on each to migrate state. `initialize` runs again
|
|
162
|
+
* only with `reinitialize: true` (after `onDisable` and `destroy` of the old version, with `state` cleared).
|
|
163
|
+
* A type that is not registered yet is just registered. Returns the number of instances swapped.
|
|
164
|
+
*/
|
|
165
|
+
reload(next: ScriptType, { reinitialize }?: {
|
|
166
|
+
reinitialize?: boolean;
|
|
167
|
+
}): number;
|
|
168
|
+
/** Destroy every instance and detach from the world. Safe to call twice. */
|
|
169
|
+
[Symbol.dispose](): void;
|
|
170
|
+
/** Same as `[Symbol.dispose]()`. */
|
|
171
|
+
dispose(): void;
|
|
172
|
+
private live;
|
|
173
|
+
private sortAll;
|
|
174
|
+
private shape;
|
|
175
|
+
private setEnabled;
|
|
176
|
+
private kill;
|
|
177
|
+
private removeAll;
|
|
178
|
+
private call;
|
|
179
|
+
private step;
|
|
180
|
+
/** Run `body`; errors collected without an onError handler are rethrown once, at the end of the outermost pass. */
|
|
181
|
+
private pass;
|
|
182
|
+
}
|