@hackbuild/motion-net 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Moheeb Zara
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,153 @@
1
- # Temporary Holding Version
1
+ # @hackbuild/motion-net
2
2
 
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.
3
+ A runtime and a quadruped gait host for the published categorical codebook
4
+ matching network (Starke et al., "Categorical Codebook Matching for
5
+ Embodied Character Controllers", SIGGRAPH 2024).
6
+
7
+ Licences:
8
+
9
+ - This code is MIT. It was written from a functional specification of the
10
+ network (weight format, equations, input and output layout, test
11
+ vectors) and the published paper, by a team that did not read the
12
+ earlier implementation in this repository or the upstream code.
13
+ - The weights are CC BY-NC 4.0 (Paul Starke and Sebastian Starke, Meta,
14
+ AI4AnimationPy). They are loaded at run time from a URL, an ArrayBuffer
15
+ or a File, and are not included in this package, its builds or the
16
+ example site. The licence line is stated on the first load in a page.
17
+
18
+ ## What it does
19
+
20
+ - `loadWeights({ manifest, bin, sha256? })`: reads the JSON manifest and
21
+ the flat binary from a URL, bytes or a File, checks the SHA-256 when one
22
+ is given, and checks every tensor's dtype, shape, count, alignment and
23
+ range against the dimensions in the manifest before anything runs. A
24
+ failure throws a message that names the tensor. `UPSTREAM` holds one
25
+ public copy pinned to a commit and its SHA-256 (computed from a
26
+ download).
27
+ - The forward pass in Rust (`crates/motion-net`): binary16 weights decoded
28
+ exactly to f32, code estimate, three refinement passes, and the time
29
+ conditioned decoder for 16 frames. The first decoder layer is affine in
30
+ time, so it runs as two matrix products instead of sixteen; layers 2 and
31
+ 3 run batched over the frames. The dot product keeps 16 running sums in
32
+ a fixed order: four f32x4 registers on wasm32 SIMD128, an array natively,
33
+ so both builds give the same bits.
34
+ - `Predictor.create(weights, { worker })`: runs the network in a worker
35
+ made from a blob, which also starts from file://. The worker drives the
36
+ wasm through a plain C ABI, with no generated glue to import. When a
37
+ worker is refused or does not start in 10 s, the same code runs in the
38
+ page (`mode` and `fallbackReason` say which).
39
+ - `QuadrupedHost`: implements the `LocomotionBackend` contract of
40
+ `@hackbuild/gait` (structurally, without depending on it) and fills its
41
+ `MotorState` with source `neural`. Per frame it
42
+ - smooths the command (speed and turn rate, or a world velocity and
43
+ facing) and picks a style label by speed (Idle, Walk, Trot, Canter;
44
+ any of the nine labels can be held);
45
+ - builds the input from the dog's own current pose and velocities, a 16
46
+ sample trajectory, and the style pose, and asks for a new prediction
47
+ every 0.1 s with one in flight;
48
+ - plays each prediction from the time it was requested, so latency is
49
+ skipped rather than replayed, and hides the seam to the previous one
50
+ with a decaying offset;
51
+ - integrates the network's root motion, lets the root take over the
52
+ drift of the network's planted paws, and leans the trajectory with an
53
+ integral loop on speed and turn rate until the dog meets the command;
54
+ - pins each paw while its contact value says stance, bends the limb with
55
+ a two bone solve to reach the pin, and blends a released paw back;
56
+ - holds the last pose and brings the root to rest when a prediction is
57
+ late, and drops one that lands after a newer one.
58
+ It exposes the root transform and velocity, 27 bone positions and
59
+ rotations (right handed, +Z forward, +X to the dog's left, as in the
60
+ gait package), contact values, per paw phase, the style, wall clock
61
+ latency and evaluation time, and per frame foot slide. Every constant in
62
+ `DEFAULT_TUNING` carries the reason for its value beside it.
63
+
64
+ ## Install
65
+
66
+ ```sh
67
+ npm install @hackbuild/motion-net three
68
+ ```
69
+
70
+ ```ts
71
+ import { Predictor, QuadrupedHost, UPSTREAM, loadWeights } from "@hackbuild/motion-net";
72
+
73
+ const weights = await loadWeights({ manifest: UPSTREAM.manifest, bin: UPSTREAM.bin, sha256: UPSTREAM.binSha256 });
74
+ const predictor = await Predictor.create(weights);
75
+ const dog = new QuadrupedHost(predictor, weights.styles);
76
+ // each frame
77
+ const root = dog.update(dt, { speed: 1.2, turnRate: 0.3 });
78
+ dog.positions; // 27 x 3, world, meters
79
+ dog.rotations; // 27 x 4 quaternions
80
+ ```
81
+
82
+ ## What is verified, and what is not
83
+
84
+ ### Verified on this machine
85
+
86
+ - 2026-11-23: `cargo test -p hackbuild-motion-net` passed 8 of 8 tests
87
+ (counted), clippy clean natively and for wasm32 with SIMD128. A plain
88
+ double precision evaluation of the equations matches the crate's forward
89
+ pass within 1e-5 relative on a random network (measured).
90
+ - 2026-11-23: the golden trace (two evaluations of a seeded random network
91
+ loaded from binary16 and binary32 bytes, and binary16 decodes) is bit
92
+ identical between the native build and the wasm SIMD128 build (measured,
93
+ vitest).
94
+ - 2026-11-23: the three test vectors of the specification pass on the
95
+ published weights: worst listed value error 4.8e-7 relative, worst
96
+ checksum error 7.8e-8 relative, against a tolerance of 1e-4 and 1e-5
97
+ (measured). One evaluation takes 4 to 6 ms in Node on an Apple M1
98
+ (measured). These tests need the weights and run only when
99
+ `HB_MOTION_NET_BIN` and `HB_MOTION_NET_MANIFEST` point at local copies;
100
+ otherwise they are skipped and the test output says so. CI has no
101
+ weights, so CI does not run them.
102
+ - 2026-11-23: host on the published weights, 60 Hz, page engine in Node,
103
+ over the last 8 s of 16 s runs (measured): commanded 0.6, 1, 1.6, 2.4 and
104
+ 3.5 m/s gave 0.598, 0.999, 1.626, 2.395 and 3.515 m/s; stance paw slide
105
+ p95 per frame 0, 0, 5.7, 4.8 and 10.2 mm with pins, against 7.4, 9.6,
106
+ 11.8, 17.6 and 17.4 mm for the network's own paws; 1 rad/s at 1 m/s gave
107
+ 0.999 rad/s; idle travels under 5 cm in 3 s. Gated on the weights as
108
+ above.
109
+ - 2026-11-23: host on a kinematic stand in (no weights, runs in CI): speed
110
+ within 5 percent at 0.6, 1.2 and 2.5 m/s, turn rate within 10 percent,
111
+ idle, a world velocity with a facing, no NaN on zero, negative, NaN or
112
+ infinite dt or commands, a 1.5 s late prediction held and recovered with
113
+ the largest bone move 47 mm in one frame, a stale prediction dropped,
114
+ stride frequency and duty recovered from contacts (measured).
115
+ - 2026-11-23: the example page on the published weights in Chrome 150 on
116
+ an Apple M1 at real frame rate, through `tools/check-examples.mjs`: the
117
+ network ran in the blob worker, 4.5 ms per evaluation, 5 ms wall clock
118
+ latency, 59.9 fps p50, pinned stance slide p95 5.6 mm per frame against
119
+ 10.8 mm for the network's paws, while wandering through speeds
120
+ and turns (measured). The screenshot shows a standing four legged
121
+ skeleton; a person watching the gait at frame rate has not been
122
+ recorded.
123
+
124
+ - 2026-11-23: `Predictor.predict` rejects an input of the wrong length and
125
+ keeps working; a run asked for after `dispose`, a worker crash after
126
+ start, and an engine error with no run id each reject the pending runs
127
+ instead of leaving them open (tested on a small synthetic network in
128
+ the page engine; the worker crash path is untested).
129
+
130
+ ### Not verified by anything
131
+
132
+ - The worker and the in page fallback from file://, and the fallback on a
133
+ page whose policy refuses blob workers. Node has no worker, so tests run
134
+ the page path only.
135
+ - Retargeting the 27 bone skeleton onto another rig; the host gives the
136
+ network's own skeleton, and the bone axes follow the source rig's
137
+ conventions.
138
+ - Pace, Sit, Stand, Lie and Jump through the host: they can be held as a
139
+ style, and nothing measures how they look.
140
+ - At a gallop (above about 3 m/s) the limbs cannot always reach their pins
141
+ and the paw slides up to about 10 mm per frame p95 (measured above).
142
+
143
+ ## Size budget
144
+
145
+ | file | gzip (measured) | ceiling |
146
+ |---|---|---|
147
+ | `dist/index.js` (main entry, imports external) | 47,768 bytes | 50,156 bytes |
148
+ | `dist/wasm/motion_net_bg.wasm` | 23,690 bytes | 24,874 bytes |
149
+ | `dist/motion-net.iife.js` (single file build) | 47,978 bytes | 50,376 bytes |
150
+
151
+ Measured 2026-11-24 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
152
+ tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
153
+ 5 percent from its row.
@@ -0,0 +1,95 @@
1
+ import type { Dims, Dtype, Weights } from "./weights.js";
2
+ export type EngineMode = "worker" | "page";
3
+ export interface RawPrediction {
4
+ /** 16 rows of 412 denormalized values. */
5
+ frames: Float32Array;
6
+ /** Refined code, 1024 values. */
7
+ code: Float32Array;
8
+ /** Code estimate before refinement. */
9
+ code0: Float32Array;
10
+ /** Milliseconds the evaluation took where it ran (measured). */
11
+ ms: number;
12
+ }
13
+ interface TensorSlot {
14
+ key: string;
15
+ dtype: Dtype;
16
+ offset: number;
17
+ count: number;
18
+ }
19
+ type EngineIn = {
20
+ kind: "configure-network";
21
+ wasm: ArrayBuffer;
22
+ dims: Dims;
23
+ blob: ArrayBuffer;
24
+ tensors: TensorSlot[];
25
+ } | {
26
+ kind: "infer";
27
+ requestId: number;
28
+ input: Float32Array;
29
+ } | {
30
+ kind: "teardown";
31
+ };
32
+ type EngineOut = {
33
+ kind: "network-configured";
34
+ inputLength: number;
35
+ } | {
36
+ kind: "network-configure-failed";
37
+ message: string;
38
+ } | {
39
+ kind: "inference-done";
40
+ requestId: number;
41
+ frames: Float32Array;
42
+ code: Float32Array;
43
+ code0: Float32Array;
44
+ inferenceMs: number;
45
+ } | {
46
+ kind: "inference-failed";
47
+ requestId: number;
48
+ message: string;
49
+ } | {
50
+ kind: "network-crashed";
51
+ message: string;
52
+ };
53
+ interface Port {
54
+ onmessage: ((ev: {
55
+ data: EngineIn;
56
+ }) => void) | null;
57
+ postMessage(msg: EngineOut, transfer?: Transferable[]): void;
58
+ }
59
+ /**
60
+ * The engine loop. Self contained: the worker source is this function's
61
+ * text, so it must not touch anything outside its own body.
62
+ */
63
+ export declare function engineMain(port: Port): void;
64
+ export interface PredictorOptions {
65
+ /** "auto" tries a worker and falls back to the page; true insists on a worker; false runs in the page. */
66
+ worker?: boolean | "auto";
67
+ /** The wasm: a URL or bytes. Defaults to the base64 copy shipped in the package. */
68
+ wasm?: URL | string | ArrayBuffer | ArrayBufferView;
69
+ /** How long a worker may take to report ready before the page fallback takes over, ms. */
70
+ workerTimeoutMs?: number;
71
+ }
72
+ /** Evaluates the network, in a worker or in the page. */
73
+ export declare class Predictor {
74
+ readonly mode: EngineMode;
75
+ private readonly waiting;
76
+ private nextId;
77
+ private channel;
78
+ private dead;
79
+ /** Why the worker was not used, when it was not. */
80
+ fallbackReason: string | null;
81
+ /** Raw input length the network takes; set by `create`. */
82
+ inputLength: number;
83
+ private constructor();
84
+ /** Runs one evaluation on a raw input of 339 values. */
85
+ predict(input: Float32Array): Promise<RawPrediction>;
86
+ dispose(): void;
87
+ /** @internal Rejects every pending run and every later one. */
88
+ fail(message: string): void;
89
+ /** @internal */
90
+ receive(m: EngineOut): void;
91
+ private rejectAll;
92
+ private shutdown;
93
+ static create(weights: Weights, opts?: PredictorOptions): Promise<Predictor>;
94
+ }
95
+ export {};
package/dist/engine.js ADDED
@@ -0,0 +1,374 @@
1
+ /**
2
+ * The engine loop. Self contained: the worker source is this function's
3
+ * text, so it must not touch anything outside its own body.
4
+ */
5
+ export function engineMain(port) {
6
+ const now = () => (typeof performance === "object" && performance ? performance.now() : Date.now());
7
+ let abi = null;
8
+ let handle = 0;
9
+ let dims = null;
10
+ let broken = null;
11
+ const say = (msg, transfer) => {
12
+ if (transfer)
13
+ port.postMessage(msg, transfer);
14
+ else
15
+ port.postMessage(msg);
16
+ };
17
+ const reason = (e) => (e instanceof Error ? e.message : String(e));
18
+ const bindings = (mod, exportsOf) => {
19
+ // supply whatever the generated glue would; the C ABI needs none of it
20
+ const imports = {};
21
+ for (const imp of WebAssembly.Module.imports(mod)) {
22
+ if (imp.kind !== "function")
23
+ throw new Error(`the wasm asks for a ${imp.kind} import named ${imp.name}`);
24
+ const ns = (imports[imp.module] ??= {});
25
+ ns[imp.name] =
26
+ imp.name === "__wbindgen_init_externref_table"
27
+ ? () => {
28
+ const table = exportsOf()?.__wbindgen_externrefs;
29
+ if (!table)
30
+ return;
31
+ const at = table.grow(4);
32
+ table.set(0, undefined);
33
+ table.set(at, undefined);
34
+ table.set(at + 1, null);
35
+ table.set(at + 2, true);
36
+ table.set(at + 3, false);
37
+ }
38
+ : () => {
39
+ throw new Error(`the wasm called ${imp.module}.${imp.name}, which this engine does not provide`);
40
+ };
41
+ }
42
+ return imports;
43
+ };
44
+ const configure = async (m) => {
45
+ const mod = await WebAssembly.compile(m.wasm);
46
+ let live = null;
47
+ const inst = await WebAssembly.instantiate(mod, bindings(mod, () => live));
48
+ live = inst.exports;
49
+ live.__wbindgen_start?.();
50
+ const d = m.dims;
51
+ const e = live.mn_create(d.dIn, d.dOut, d.hidden, d.group, d.frames, d.passes);
52
+ if (!e)
53
+ throw new Error("the network rejected the dimensions");
54
+ const enc = new TextEncoder();
55
+ const src = new Uint8Array(m.blob);
56
+ for (const t of m.tensors) {
57
+ const name = enc.encode(t.key);
58
+ const bytes = t.count * (t.dtype === "f16" ? 2 : 4);
59
+ const kp = live.mn_alloc(name.length) >>> 0;
60
+ const dp = live.mn_alloc(bytes) >>> 0;
61
+ // views are taken after both allocations, which can grow memory
62
+ const heap = new Uint8Array(live.memory.buffer);
63
+ heap.set(name, kp);
64
+ heap.set(src.subarray(t.offset, t.offset + bytes), dp);
65
+ const code = live.mn_set(e, kp, name.length, t.dtype === "f16" ? 0 : 1, dp, t.count);
66
+ live.mn_free(kp, name.length);
67
+ live.mn_free(dp, bytes);
68
+ if (code > 1) {
69
+ live.mn_destroy(e);
70
+ const why = ["", "", "has the wrong element count", "is shorter than its count", "has a bad key or dtype"][code] ?? `failed with code ${code}`;
71
+ throw new Error(`tensor ${t.key} ${why}`);
72
+ }
73
+ }
74
+ const gap = live.mn_missing(e);
75
+ if (gap !== 0) {
76
+ live.mn_destroy(e);
77
+ throw new Error(`tensor number ${gap - 1} of the network was never filled`);
78
+ }
79
+ abi = live;
80
+ handle = e;
81
+ dims = d;
82
+ };
83
+ const infer = (requestId, input) => {
84
+ if (!abi || !dims)
85
+ return say({ kind: "inference-failed", requestId, message: "motion-net: the engine is not configured" });
86
+ if (input.length !== dims.dIn)
87
+ return say({ kind: "inference-failed", requestId, message: `motion-net: the input has ${input.length} values, the network takes ${dims.dIn} values` });
88
+ const a = abi;
89
+ let elapsed;
90
+ let frames;
91
+ let code;
92
+ let code0;
93
+ try {
94
+ new Float32Array(a.memory.buffer, a.mn_input(handle) >>> 0, dims.dIn).set(input);
95
+ const start = now();
96
+ const status = a.mn_forward(handle);
97
+ elapsed = now() - start;
98
+ if (status !== 0)
99
+ throw new Error("a tensor went missing before the forward pass");
100
+ const read = (which, n) => new Float32Array(a.memory.buffer, a.mn_output(handle, which) >>> 0, n).slice();
101
+ frames = read(0, dims.frames * dims.dOut);
102
+ code = read(1, dims.hidden);
103
+ code0 = read(2, dims.hidden);
104
+ }
105
+ catch (e) {
106
+ // a trap leaves linear memory in an unknown state; stop for good
107
+ broken = `motion-net: the network engine crashed: ${reason(e)}`;
108
+ abi = null;
109
+ return say({ kind: "network-crashed", message: broken });
110
+ }
111
+ say({ kind: "inference-done", requestId, frames, code, code0, inferenceMs: elapsed }, [frames.buffer, code.buffer, code0.buffer]);
112
+ };
113
+ let setup = Promise.resolve();
114
+ port.onmessage = (ev) => {
115
+ const m = ev.data;
116
+ if (broken) {
117
+ if (m.kind === "infer")
118
+ say({ kind: "inference-failed", requestId: m.requestId, message: broken });
119
+ return;
120
+ }
121
+ if (m.kind === "configure-network") {
122
+ setup = configure(m).then(() => say({ kind: "network-configured", inputLength: m.dims.dIn }), (e) => say({ kind: "network-configure-failed", message: `motion-net: the network did not set up: ${reason(e)}` }));
123
+ }
124
+ else if (m.kind === "infer") {
125
+ const { requestId, input } = m;
126
+ void setup.then(() => infer(requestId, input));
127
+ }
128
+ else if (m.kind === "teardown") {
129
+ void setup.then(() => {
130
+ if (abi && handle)
131
+ abi.mn_destroy(handle);
132
+ abi = null;
133
+ handle = 0;
134
+ broken = "motion-net: the engine was torn down";
135
+ });
136
+ }
137
+ };
138
+ }
139
+ /** Why a blob worker cannot be made here, or null when one can be tried. */
140
+ function workerBlocker() {
141
+ if (typeof Worker !== "function")
142
+ return "no worker support in this runtime";
143
+ if (typeof Blob !== "function" || typeof URL === "undefined" || typeof URL.createObjectURL !== "function")
144
+ return "no blob urls in this runtime";
145
+ return null;
146
+ }
147
+ async function wasmBytesFrom(src) {
148
+ if (src === undefined) {
149
+ const v = (await import("./wasm/inline.js")).wasmBytes();
150
+ return v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength);
151
+ }
152
+ if (src instanceof ArrayBuffer)
153
+ return src.slice(0);
154
+ if (ArrayBuffer.isView(src))
155
+ return src.buffer.slice(src.byteOffset, src.byteOffset + src.byteLength);
156
+ const res = await fetch(String(src));
157
+ if (!res.ok)
158
+ throw new Error(`motion-net: fetch ${String(src)} answered ${res.status}`);
159
+ return res.arrayBuffer();
160
+ }
161
+ function setupMessage(w, wasm) {
162
+ const blob = w.bin.slice(0);
163
+ const wasmCopy = wasm.slice(0);
164
+ return [{ kind: "configure-network", wasm: wasmCopy, dims: { ...w.dims }, blob, tensors: w.tensors.map((t) => ({ ...t })) }, [wasmCopy, blob]];
165
+ }
166
+ /** Starts the engine in a blob worker. Resolves with the channel, or rejects with the reason it could not. */
167
+ function startWorker(setup, timeoutMs, onMessage, onCrash) {
168
+ const blocked = workerBlocker();
169
+ if (blocked)
170
+ return Promise.reject(new Error(blocked));
171
+ const text = `"use strict";\n(${engineMain.toString()})(self);\n`;
172
+ const url = URL.createObjectURL(new Blob([text], { type: "text/javascript" }));
173
+ let worker;
174
+ try {
175
+ worker = new Worker(url);
176
+ }
177
+ catch (e) {
178
+ URL.revokeObjectURL(url);
179
+ return Promise.reject(new Error(`blob workers refused: ${e.message}`));
180
+ }
181
+ return new Promise((resolve, reject) => {
182
+ let settled = false;
183
+ const channel = {
184
+ post: (msg, transfer) => worker.postMessage(msg, transfer),
185
+ close: () => worker.terminate(),
186
+ };
187
+ const give = (why) => {
188
+ if (settled)
189
+ return;
190
+ settled = true;
191
+ clearTimeout(timer);
192
+ worker.terminate();
193
+ URL.revokeObjectURL(url);
194
+ reject(new Error(why));
195
+ };
196
+ const timer = setTimeout(() => give(`the worker did not set up within ${timeoutMs} ms`), timeoutMs);
197
+ worker.onmessage = (ev) => {
198
+ const m = ev.data;
199
+ if (!settled) {
200
+ if (m.kind === "network-configured") {
201
+ settled = true;
202
+ clearTimeout(timer);
203
+ URL.revokeObjectURL(url);
204
+ resolve(channel);
205
+ }
206
+ else if (m.kind === "network-configure-failed")
207
+ give(m.message);
208
+ return;
209
+ }
210
+ onMessage(m);
211
+ };
212
+ worker.onerror = (ev) => {
213
+ ev.preventDefault?.();
214
+ const msg = ev.message || "the worker script failed to start";
215
+ if (!settled)
216
+ give(`the worker failed: ${msg}`);
217
+ else
218
+ onCrash(`motion-net: the network worker crashed: ${msg}`);
219
+ };
220
+ worker.onmessageerror = () => {
221
+ if (settled)
222
+ onCrash("motion-net: the network worker sent a message the page could not read");
223
+ };
224
+ worker.postMessage(setup[0], setup[1]);
225
+ });
226
+ }
227
+ /** Starts the engine in this page behind a MessageChannel. */
228
+ function startPage(setup, onMessage) {
229
+ const mc = new MessageChannel();
230
+ const engineSide = mc.port1;
231
+ const pageSide = mc.port2;
232
+ engineMain(engineSide);
233
+ // in node a listening port holds the process open; the engine should not
234
+ for (const p of [engineSide, pageSide])
235
+ p.unref?.();
236
+ const channel = {
237
+ post: (msg, transfer) => pageSide.postMessage(msg, transfer),
238
+ close: () => {
239
+ pageSide.onmessage = null;
240
+ engineSide.onmessage = null;
241
+ pageSide.close();
242
+ engineSide.close();
243
+ },
244
+ };
245
+ return new Promise((resolve, reject) => {
246
+ let settled = false;
247
+ pageSide.onmessage = (ev) => {
248
+ const m = ev.data;
249
+ if (!settled) {
250
+ if (m.kind === "network-configured") {
251
+ settled = true;
252
+ resolve(channel);
253
+ }
254
+ else if (m.kind === "network-configure-failed") {
255
+ settled = true;
256
+ channel.close();
257
+ reject(new Error(m.message));
258
+ }
259
+ return;
260
+ }
261
+ onMessage(m);
262
+ };
263
+ pageSide.postMessage(setup[0], setup[1]);
264
+ });
265
+ }
266
+ /** Evaluates the network, in a worker or in the page. */
267
+ export class Predictor {
268
+ mode;
269
+ waiting = new Map();
270
+ nextId = 1;
271
+ channel = null;
272
+ dead = null;
273
+ /** Why the worker was not used, when it was not. */
274
+ fallbackReason = null;
275
+ /** Raw input length the network takes; set by `create`. */
276
+ inputLength = 0;
277
+ constructor(mode) {
278
+ this.mode = mode;
279
+ }
280
+ /** Runs one evaluation on a raw input of 339 values. */
281
+ predict(input) {
282
+ if (this.dead)
283
+ return Promise.reject(new Error(this.dead));
284
+ if (input.length !== this.inputLength)
285
+ return Promise.reject(new Error(`motion-net: the input has ${input.length} values, the network takes ${this.inputLength} values`));
286
+ const requestId = this.nextId++;
287
+ // a copy goes to the engine, so the caller may refill its buffer at once
288
+ const copy = input.slice();
289
+ return new Promise((resolve, reject) => {
290
+ this.waiting.set(requestId, { resolve, reject });
291
+ try {
292
+ this.channel.post({ kind: "infer", requestId, input: copy }, [copy.buffer]);
293
+ }
294
+ catch (e) {
295
+ this.fail(`motion-net: the engine could not take the request: ${e.message}`);
296
+ }
297
+ });
298
+ }
299
+ dispose() {
300
+ if (this.dead)
301
+ return;
302
+ this.dead = "motion-net: the predictor was disposed. the run was dropped.";
303
+ this.rejectAll(this.dead);
304
+ this.shutdown();
305
+ }
306
+ /** @internal Rejects every pending run and every later one. */
307
+ fail(message) {
308
+ if (this.dead)
309
+ return;
310
+ this.dead = message;
311
+ console.warn(message);
312
+ this.rejectAll(message);
313
+ this.shutdown();
314
+ }
315
+ /** @internal */
316
+ receive(m) {
317
+ if (this.dead)
318
+ return;
319
+ if (m.kind === "inference-done" || m.kind === "inference-failed") {
320
+ const w = this.waiting.get(m.requestId);
321
+ if (!w)
322
+ return;
323
+ this.waiting.delete(m.requestId);
324
+ if (m.kind === "inference-done")
325
+ w.resolve({ frames: m.frames, code: m.code, code0: m.code0, ms: m.inferenceMs });
326
+ else
327
+ w.reject(new Error(m.message));
328
+ }
329
+ else if (m.kind === "network-crashed")
330
+ this.fail(m.message);
331
+ }
332
+ rejectAll(message) {
333
+ const all = [...this.waiting.values()];
334
+ this.waiting.clear();
335
+ for (const w of all)
336
+ w.reject(new Error(message));
337
+ }
338
+ shutdown() {
339
+ const c = this.channel;
340
+ this.channel = null;
341
+ if (!c)
342
+ return;
343
+ try {
344
+ c.post({ kind: "teardown" }, []);
345
+ }
346
+ catch {
347
+ // the engine is already gone
348
+ }
349
+ c.close();
350
+ }
351
+ static async create(weights, opts = {}) {
352
+ const want = opts.worker ?? "auto";
353
+ const wasm = await wasmBytesFrom(opts.wasm);
354
+ let reason = want === false ? null : "";
355
+ if (want !== false) {
356
+ const p = new Predictor("worker");
357
+ try {
358
+ p.channel = await startWorker(setupMessage(weights, wasm), opts.workerTimeoutMs ?? 15000, (m) => p.receive(m), (why) => p.fail(why));
359
+ p.inputLength = weights.dims.dIn;
360
+ return p;
361
+ }
362
+ catch (e) {
363
+ reason = e.message;
364
+ if (want === true)
365
+ throw new Error(`motion-net: no network worker. ${reason}.`);
366
+ }
367
+ }
368
+ const p = new Predictor("page");
369
+ p.fallbackReason = reason;
370
+ p.channel = await startPage(setupMessage(weights, wasm), (m) => p.receive(m));
371
+ p.inputLength = weights.dims.dIn;
372
+ return p;
373
+ }
374
+ }