fast-mesh-wasm 0.2.0 → 0.3.1
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 +490 -1
- package/dist/{api-D0o2HjaU.js → api-BUy7FRx7.js} +11 -11
- package/dist/client-Bp9FRd70.js +2278 -0
- package/dist/client-m2zSdFlu.d.ts +305 -0
- package/dist/colormap-D_xH5hI5.js +303 -0
- package/dist/core-Cke_kZ2e.js +113 -0
- package/dist/core-D2X9GPfK.d.ts +15 -0
- package/dist/engine-BpnthBYQ.js +1927 -0
- package/dist/mesh-B16gV3oX.d.ts +130 -0
- package/dist/mesh-B8pae8WA.js +428 -0
- package/dist/node.d.ts +3 -2
- package/dist/node.js +5 -4
- package/dist/protocol-CAUYm1gd.js +68 -0
- package/dist/protocol-W9R-iGl5.d.ts +293 -0
- package/dist/r3f.d.ts +59 -0
- package/dist/r3f.js +165 -0
- package/dist/react-CTADh3NN.js +124 -0
- package/dist/react.d.ts +65 -0
- package/dist/react.js +1 -0
- package/dist/scene-BFd6nYRe.js +1256 -0
- package/dist/scene-like-B_3qm0u6.d.ts +925 -0
- package/dist/snapshot-Cf6NgDl7.js +104 -0
- package/dist/store-D3ErV6o-.js +1379 -0
- package/dist/store-DNnHN33A.d.ts +285 -0
- package/dist/store.d.ts +61 -0
- package/dist/store.js +105 -0
- package/dist/three.d.ts +118 -0
- package/dist/three.js +390 -0
- package/dist/views-BaZqBxlX.js +189 -0
- package/dist/wasm/fast_mesh_wasm.d.ts +475 -0
- package/dist/wasm/fast_mesh_wasm.js +1184 -0
- package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
- package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +76 -0
- package/dist/wasm-threads/fast_mesh_wasm.d.ts +557 -0
- package/dist/wasm-threads/fast_mesh_wasm.js +1547 -0
- package/dist/wasm-threads/fast_mesh_wasm_bg.wasm +0 -0
- package/dist/wasm-threads/fast_mesh_wasm_bg.wasm.d.ts +95 -0
- package/dist/wasm-threads/package.json +7 -0
- package/dist/wasm-threads/snippets/fast-mesh-wasm-ae14781a92c2789e/inline0.js +16 -0
- package/dist/wasm-threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +107 -0
- package/dist/web.d.ts +3 -2
- package/dist/web.js +4 -2
- package/dist/worker-engine.d.ts +255 -0
- package/dist/worker-engine.js +1 -0
- package/dist/worker-entry.d.ts +1 -0
- package/dist/worker-entry.js +11 -0
- package/dist/worker.d.ts +2 -0
- package/dist/worker.js +1 -0
- package/package.json +53 -4
- package/dist/api-HcskOwd7.d.ts +0 -43
|
@@ -0,0 +1,1927 @@
|
|
|
1
|
+
import { s as setMemory, t as FastMeshError } from "./core-Cke_kZ2e.js";
|
|
2
|
+
import { i as useWasmScene, n as fieldSteps, r as meshAdds, t as Scene } from "./scene-BFd6nYRe.js";
|
|
3
|
+
import { a as supersedes, n as isLastWins, r as keyOf, t as isInit } from "./protocol-CAUYm1gd.js";
|
|
4
|
+
/**
|
|
5
|
+
* A module importing a shared memory `e.m` (1 page, at most 2), exporting
|
|
6
|
+
* `grow(pages)` (`memory.grow`: the old size in pages, or -1),
|
|
7
|
+
* `fill(address)` (`memory.fill` of one byte there) and `copy(address)`
|
|
8
|
+
* (`memory.copy` of the byte at 0 there); both return 0.
|
|
9
|
+
*/
|
|
10
|
+
const MODULE = new Uint8Array([
|
|
11
|
+
0,
|
|
12
|
+
97,
|
|
13
|
+
115,
|
|
14
|
+
109,
|
|
15
|
+
1,
|
|
16
|
+
0,
|
|
17
|
+
0,
|
|
18
|
+
0,
|
|
19
|
+
1,
|
|
20
|
+
6,
|
|
21
|
+
1,
|
|
22
|
+
96,
|
|
23
|
+
1,
|
|
24
|
+
127,
|
|
25
|
+
1,
|
|
26
|
+
127,
|
|
27
|
+
2,
|
|
28
|
+
9,
|
|
29
|
+
1,
|
|
30
|
+
1,
|
|
31
|
+
101,
|
|
32
|
+
1,
|
|
33
|
+
109,
|
|
34
|
+
2,
|
|
35
|
+
3,
|
|
36
|
+
1,
|
|
37
|
+
2,
|
|
38
|
+
3,
|
|
39
|
+
4,
|
|
40
|
+
3,
|
|
41
|
+
0,
|
|
42
|
+
0,
|
|
43
|
+
0,
|
|
44
|
+
7,
|
|
45
|
+
22,
|
|
46
|
+
3,
|
|
47
|
+
4,
|
|
48
|
+
103,
|
|
49
|
+
114,
|
|
50
|
+
111,
|
|
51
|
+
119,
|
|
52
|
+
0,
|
|
53
|
+
0,
|
|
54
|
+
4,
|
|
55
|
+
102,
|
|
56
|
+
105,
|
|
57
|
+
108,
|
|
58
|
+
108,
|
|
59
|
+
0,
|
|
60
|
+
1,
|
|
61
|
+
4,
|
|
62
|
+
99,
|
|
63
|
+
111,
|
|
64
|
+
112,
|
|
65
|
+
121,
|
|
66
|
+
0,
|
|
67
|
+
2,
|
|
68
|
+
10,
|
|
69
|
+
37,
|
|
70
|
+
3,
|
|
71
|
+
6,
|
|
72
|
+
0,
|
|
73
|
+
32,
|
|
74
|
+
0,
|
|
75
|
+
64,
|
|
76
|
+
0,
|
|
77
|
+
11,
|
|
78
|
+
13,
|
|
79
|
+
0,
|
|
80
|
+
32,
|
|
81
|
+
0,
|
|
82
|
+
65,
|
|
83
|
+
0,
|
|
84
|
+
65,
|
|
85
|
+
1,
|
|
86
|
+
252,
|
|
87
|
+
11,
|
|
88
|
+
0,
|
|
89
|
+
65,
|
|
90
|
+
0,
|
|
91
|
+
11,
|
|
92
|
+
14,
|
|
93
|
+
0,
|
|
94
|
+
32,
|
|
95
|
+
0,
|
|
96
|
+
65,
|
|
97
|
+
0,
|
|
98
|
+
65,
|
|
99
|
+
1,
|
|
100
|
+
252,
|
|
101
|
+
10,
|
|
102
|
+
0,
|
|
103
|
+
0,
|
|
104
|
+
65,
|
|
105
|
+
0,
|
|
106
|
+
11
|
|
107
|
+
]);
|
|
108
|
+
const PAGE = 65536;
|
|
109
|
+
/**
|
|
110
|
+
* The nested Worker: instantiates the module on the memory it is sent, grows
|
|
111
|
+
* it a page, answers `grow`'s result (-1 when the message could not be read).
|
|
112
|
+
*/
|
|
113
|
+
const SCRIPT = `self.onmessageerror = () => self.postMessage(-1);
|
|
114
|
+
self.onmessage = (e) => {
|
|
115
|
+
let old = -1;
|
|
116
|
+
try {
|
|
117
|
+
old = new WebAssembly.Instance(e.data.module, { e: { m: e.data.memory } }).exports.grow(1);
|
|
118
|
+
} catch {}
|
|
119
|
+
self.postMessage(old);
|
|
120
|
+
};`;
|
|
121
|
+
/** Nested classic Workers from a Blob URL, when this scope has what that takes. */
|
|
122
|
+
function browserSpawn() {
|
|
123
|
+
const { Worker: NestedWorker, Blob: ScriptBlob, URL: Urls } = globalThis;
|
|
124
|
+
if (typeof NestedWorker !== "function" || typeof ScriptBlob !== "function" || Urls?.createObjectURL === void 0) return;
|
|
125
|
+
const createUrl = Urls.createObjectURL.bind(Urls);
|
|
126
|
+
return (source) => {
|
|
127
|
+
const url = createUrl(new ScriptBlob([source], { type: "text/javascript" }));
|
|
128
|
+
const revoke = () => Urls.revokeObjectURL?.(url);
|
|
129
|
+
let worker;
|
|
130
|
+
try {
|
|
131
|
+
worker = new NestedWorker(url);
|
|
132
|
+
} catch (e) {
|
|
133
|
+
revoke();
|
|
134
|
+
throw e;
|
|
135
|
+
}
|
|
136
|
+
const terminate = worker.terminate.bind(worker);
|
|
137
|
+
worker.terminate = () => {
|
|
138
|
+
terminate();
|
|
139
|
+
revoke();
|
|
140
|
+
};
|
|
141
|
+
return worker;
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Resolves with why the threaded engine must not run in this browser (a
|
|
146
|
+
* shared memory grown on a nested Worker cannot be filled or copied into
|
|
147
|
+
* here), or
|
|
148
|
+
* `undefined` when it may: the probe passed, or could not tell (no nested
|
|
149
|
+
* Workers, a Worker that failed, could not read or answer the message, or did
|
|
150
|
+
* not answer within `timeoutMs`). Never
|
|
151
|
+
* rejects. `spawn` defaults to Blob-URL Workers, and to no probe where there
|
|
152
|
+
* are none (Node).
|
|
153
|
+
*/
|
|
154
|
+
async function probeSharedGrowth(options = {}) {
|
|
155
|
+
const spawn = options.spawn ?? browserSpawn();
|
|
156
|
+
if (spawn === void 0) return;
|
|
157
|
+
let worker;
|
|
158
|
+
let timer;
|
|
159
|
+
try {
|
|
160
|
+
const module = new WebAssembly.Module(MODULE);
|
|
161
|
+
const memory = new WebAssembly.Memory({
|
|
162
|
+
initial: 1,
|
|
163
|
+
maximum: 2,
|
|
164
|
+
shared: true
|
|
165
|
+
});
|
|
166
|
+
const { exports } = new WebAssembly.Instance(module, { e: { m: memory } });
|
|
167
|
+
exports.fill(0);
|
|
168
|
+
exports.copy(0);
|
|
169
|
+
const w = spawn(SCRIPT);
|
|
170
|
+
worker = w;
|
|
171
|
+
if (await new Promise((resolve) => {
|
|
172
|
+
timer = setTimeout(() => resolve(void 0), options.timeoutMs ?? 1e3);
|
|
173
|
+
w.onmessage = (e) => resolve(e.data);
|
|
174
|
+
w.onerror = () => resolve(void 0);
|
|
175
|
+
w.onmessageerror = () => resolve(void 0);
|
|
176
|
+
w.postMessage({
|
|
177
|
+
module,
|
|
178
|
+
memory
|
|
179
|
+
});
|
|
180
|
+
}) !== 1) return;
|
|
181
|
+
for (const op of ["fill", "copy"]) try {
|
|
182
|
+
exports[op](PAGE);
|
|
183
|
+
} catch {
|
|
184
|
+
return `a shared WebAssembly memory grown on another thread traps memory.${op} on this one, as in WebKit 26`;
|
|
185
|
+
}
|
|
186
|
+
return;
|
|
187
|
+
} catch {
|
|
188
|
+
return;
|
|
189
|
+
} finally {
|
|
190
|
+
clearTimeout(timer);
|
|
191
|
+
worker?.terminate();
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const SEE = "See \"Multithreading (COOP/COEP)\" in the fast-mesh-wasm README.";
|
|
195
|
+
/**
|
|
196
|
+
* The threaded glue instantiated but its pool did not start (it rejected or
|
|
197
|
+
* timed out). The Worker holds leftovers (the instance, nested Workers), so
|
|
198
|
+
* it is replaced by a single-threaded one rather than falling back itself.
|
|
199
|
+
* The message is the warning text; `warning` is set (by {@link startEngine})
|
|
200
|
+
* in development only.
|
|
201
|
+
*/
|
|
202
|
+
var PoolStartError = class extends Error {
|
|
203
|
+
name = "PoolStartError";
|
|
204
|
+
warning;
|
|
205
|
+
};
|
|
206
|
+
/** The default pool size: the logical cores, at most 8 (4 when unknown). */
|
|
207
|
+
function defaultThreads(nav) {
|
|
208
|
+
return Math.min(nav?.hardwareConcurrency ?? 4, 8);
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Loads and initialises the glue to run: the threaded one with its pool
|
|
212
|
+
* started when `isolated` and `threads` is not 1, else (or when importing or
|
|
213
|
+
* instantiating it fails) the single-threaded one. Returns the glue, its
|
|
214
|
+
* memory and the threads the engine computes with (1 when single-threaded);
|
|
215
|
+
* `probeFailed` is set when the probe ruled the threaded engine out. The
|
|
216
|
+
* probe runs while the threaded glue is imported; only its instantiation
|
|
217
|
+
* waits for the probe's answer.
|
|
218
|
+
* Rejects with a {@link PoolStartError} when the pool fails or times out
|
|
219
|
+
* after the threaded glue instantiated (`warn` is then not called). A
|
|
220
|
+
* started pool is watched for crashes on `crashChannel`, when given.
|
|
221
|
+
*/
|
|
222
|
+
async function loadEngine(options) {
|
|
223
|
+
const { threads, warn } = options;
|
|
224
|
+
if (threads !== 1 && options.isolated) {
|
|
225
|
+
let started;
|
|
226
|
+
const probing = options.probe?.().catch(() => void 0);
|
|
227
|
+
const imported = new Promise((resolve) => resolve(options.importThreaded())).then((glue) => ({ glue }), (error) => ({ error }));
|
|
228
|
+
const broken = await probing;
|
|
229
|
+
if (broken !== void 0) {
|
|
230
|
+
warn?.(`fast-mesh-wasm: the multithreaded engine cannot run in this browser (${broken}); running single-threaded. ${SEE}`);
|
|
231
|
+
const glue = await options.importSingle();
|
|
232
|
+
return {
|
|
233
|
+
wasm: glue,
|
|
234
|
+
memory: (await glue.default()).memory,
|
|
235
|
+
threads: 1,
|
|
236
|
+
probeFailed: true
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
try {
|
|
240
|
+
const got = await imported;
|
|
241
|
+
if ("error" in got) throw got.error;
|
|
242
|
+
started = {
|
|
243
|
+
wasm: got.glue,
|
|
244
|
+
memory: (await got.glue.default()).memory
|
|
245
|
+
};
|
|
246
|
+
} catch (e) {
|
|
247
|
+
warn?.(failed(e));
|
|
248
|
+
}
|
|
249
|
+
if (started !== void 0) {
|
|
250
|
+
try {
|
|
251
|
+
await timeout(started.wasm.initThreadPool(threads), options.poolTimeoutMs ?? 1e4);
|
|
252
|
+
} catch (e) {
|
|
253
|
+
throw new PoolStartError(failed(e));
|
|
254
|
+
}
|
|
255
|
+
if (options.crashChannel !== void 0) try {
|
|
256
|
+
started.wasm.watchPoolCrashes(options.crashChannel);
|
|
257
|
+
} catch (e) {
|
|
258
|
+
const cause = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
|
|
259
|
+
warn?.(`fast-mesh-wasm: crash detection unavailable (${cause}): a crash on a thread of the pool will hang the Worker scene instead of failing its calls with INSTANCE_POISONED. ${SEE}`);
|
|
260
|
+
}
|
|
261
|
+
return {
|
|
262
|
+
...started,
|
|
263
|
+
threads
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
} else if (threads !== 1) warn?.(`fast-mesh-wasm: the page is not cross-origin isolated (no COOP/COEP headers), so the Worker scene runs single-threaded. ${SEE}`);
|
|
267
|
+
const glue = await options.importSingle();
|
|
268
|
+
const { memory } = await glue.default();
|
|
269
|
+
return {
|
|
270
|
+
wasm: glue,
|
|
271
|
+
memory,
|
|
272
|
+
threads: 1
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
/** The warning for a threaded start that failed with `e`. */
|
|
276
|
+
function failed(e) {
|
|
277
|
+
return `fast-mesh-wasm: the multithreaded engine could not start (${e instanceof Error ? `${e.name}: ${e.message}` : String(e)}); running single-threaded. ${SEE}`;
|
|
278
|
+
}
|
|
279
|
+
/** `promise`, or a rejection once `ms` have passed. */
|
|
280
|
+
function timeout(promise, ms) {
|
|
281
|
+
let timer;
|
|
282
|
+
const late = new Promise((_, reject) => {
|
|
283
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`the thread pool did not start within ${ms} ms`)), ms);
|
|
284
|
+
});
|
|
285
|
+
return Promise.race([promise, late]).finally(() => clearTimeout(timer));
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Starts the Worker's engine for its {@link InitMessage}: loads the glue
|
|
289
|
+
* ({@link loadEngine}, probing with {@link probeSharedGrowth} unless
|
|
290
|
+
* `loaders` names a probe) and makes scenes use it. `isolated` defaults to the
|
|
291
|
+
* global `crossOriginIsolated`; development warnings are collected only on a
|
|
292
|
+
* page (where it is a boolean; Node `worker_threads` has none) and when
|
|
293
|
+
* `debug` is set. Resolves with what the ready message reports (`probeFailed`
|
|
294
|
+
* in production too: the scene caches it); rejects
|
|
295
|
+
* with a {@link PoolStartError} (its `warning` set in development) when the
|
|
296
|
+
* Worker must be replaced by a single-threaded one.
|
|
297
|
+
*/
|
|
298
|
+
async function startEngine(init, loaders, isolated = globalThis.crossOriginIsolated) {
|
|
299
|
+
let warning;
|
|
300
|
+
const dev = init.debug && typeof isolated === "boolean";
|
|
301
|
+
let loaded;
|
|
302
|
+
try {
|
|
303
|
+
loaded = await loadEngine({
|
|
304
|
+
probe: () => probeSharedGrowth(),
|
|
305
|
+
...loaders,
|
|
306
|
+
threads: init.threads ?? defaultThreads(globalThis.navigator),
|
|
307
|
+
isolated: isolated === true,
|
|
308
|
+
crashChannel: init.crashChannel,
|
|
309
|
+
warn: dev ? (message) => {
|
|
310
|
+
warning ??= message;
|
|
311
|
+
} : void 0
|
|
312
|
+
});
|
|
313
|
+
} catch (e) {
|
|
314
|
+
if (e instanceof PoolStartError && dev) e.warning = e.message;
|
|
315
|
+
throw e;
|
|
316
|
+
}
|
|
317
|
+
const { wasm, memory, threads, probeFailed } = loaded;
|
|
318
|
+
useWasmScene(wasm.WasmScene);
|
|
319
|
+
setMemory(memory);
|
|
320
|
+
return {
|
|
321
|
+
threads,
|
|
322
|
+
...warning === void 0 ? {} : { warning },
|
|
323
|
+
...probeFailed === void 0 ? {} : { probeFailed }
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
//#endregion
|
|
327
|
+
//#region src/worker/engine.ts
|
|
328
|
+
/** The default {@link EngineOptions.yieldMs}. */
|
|
329
|
+
const YIELD_MS = 4;
|
|
330
|
+
/** The default {@link EngineOptions.staleGuardMs}. */
|
|
331
|
+
const STALE_GUARD_MS = 200;
|
|
332
|
+
/** The default {@link EngineOptions.stepPoints}. */
|
|
333
|
+
const STEP_POINTS = 4096;
|
|
334
|
+
/**
|
|
335
|
+
* The default {@link EngineOptions.backgroundAddTriangles}: smaller meshes
|
|
336
|
+
* add in well under a frame, in place.
|
|
337
|
+
*/
|
|
338
|
+
const BACKGROUND_ADD_TRIANGLES = 65536;
|
|
339
|
+
/** The default {@link EngineOptions.addStepWork}: a few milliseconds of BVH build. */
|
|
340
|
+
const ADD_STEP_WORK = 1e5;
|
|
341
|
+
/** A step budget that computes a whole unit at once. */
|
|
342
|
+
const ALL_POINTS = 4294967295;
|
|
343
|
+
/** Bytes of a background add's render buffers copied per unit of {@link EngineOptions.addStepWork}. */
|
|
344
|
+
const PACK_BYTES_PER_UNIT = 64;
|
|
345
|
+
const now = typeof performance !== "undefined" && typeof performance.now === "function" ? () => performance.now() : () => Date.now();
|
|
346
|
+
/**
|
|
347
|
+
* Runs the engine on `port` until the instance traps. The WebAssembly module
|
|
348
|
+
* must already be initialised.
|
|
349
|
+
*/
|
|
350
|
+
function runEngine(port, options = {}) {
|
|
351
|
+
const engine = new Engine(port, options);
|
|
352
|
+
port.onMessage((batch) => engine.receive(batch));
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Serves the engine on a Worker's endpoint once it starts. `ready` is the
|
|
356
|
+
* start itself (the WebAssembly module's initialisation), or a function
|
|
357
|
+
* starting it for the Worker's first {@link InitMessage} (as the browser
|
|
358
|
+
* Worker script does); with a promise, init messages are ignored. Batches
|
|
359
|
+
* arriving before are kept and run in order; then `{ kind: "ready" }` (with
|
|
360
|
+
* the {@link Started} report, 1 thread by default) is posted first. When the
|
|
361
|
+
* start fails, `{ kind: "fatal" }` is posted instead and nothing runs. When
|
|
362
|
+
* it fails with a {@link PoolStartError} (the threaded pool did not start),
|
|
363
|
+
* `{ kind: "fallback" }` is posted instead, giving back every batch received
|
|
364
|
+
* (and, one message each, every batch received later), their buffers
|
|
365
|
+
* transferred: the scene replaces this Worker with a single-threaded one and
|
|
366
|
+
* sends them there.
|
|
367
|
+
*/
|
|
368
|
+
function serveEngine(endpoint, ready, options = {}) {
|
|
369
|
+
let deliver;
|
|
370
|
+
let started = typeof ready !== "function";
|
|
371
|
+
/** The engine's options, with the scene's from its init message. */
|
|
372
|
+
let engineOptions = options;
|
|
373
|
+
const early = [];
|
|
374
|
+
/** Set once the start failed with a `PoolStartError`: batches go back. */
|
|
375
|
+
let giveBack = false;
|
|
376
|
+
const back = (batches, warning) => {
|
|
377
|
+
const transfer = [];
|
|
378
|
+
for (const batch of batches) for (const req of batch) if (req.kind === "addMesh") transfer.push(req.positions, req.indices);
|
|
379
|
+
endpoint.post(warning === void 0 ? {
|
|
380
|
+
kind: "fallback",
|
|
381
|
+
batches
|
|
382
|
+
} : {
|
|
383
|
+
kind: "fallback",
|
|
384
|
+
batches,
|
|
385
|
+
warning
|
|
386
|
+
}, transfer);
|
|
387
|
+
};
|
|
388
|
+
const serve = (start) => start.then((info) => {
|
|
389
|
+
const { threads = 1, warning, probeFailed } = info ?? {};
|
|
390
|
+
endpoint.post({
|
|
391
|
+
kind: "ready",
|
|
392
|
+
threads,
|
|
393
|
+
...warning === void 0 ? {} : { warning },
|
|
394
|
+
...probeFailed === true ? { probeFailed } : {}
|
|
395
|
+
}, []);
|
|
396
|
+
runEngine({
|
|
397
|
+
post: (msg, transfer) => endpoint.post(msg, transfer),
|
|
398
|
+
postUpdate: (result, transfer) => endpoint.post({
|
|
399
|
+
kind: "update",
|
|
400
|
+
result
|
|
401
|
+
}, transfer),
|
|
402
|
+
onMessage: (cb) => {
|
|
403
|
+
deliver = cb;
|
|
404
|
+
for (const batch of early.splice(0)) cb(batch);
|
|
405
|
+
}
|
|
406
|
+
}, {
|
|
407
|
+
threads,
|
|
408
|
+
...engineOptions
|
|
409
|
+
});
|
|
410
|
+
}, (e) => {
|
|
411
|
+
if (e instanceof PoolStartError) {
|
|
412
|
+
giveBack = true;
|
|
413
|
+
back(early.splice(0), e.warning);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
const cause = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
|
|
417
|
+
endpoint.post({
|
|
418
|
+
kind: "fatal",
|
|
419
|
+
error: {
|
|
420
|
+
code: "INSTANCE_POISONED",
|
|
421
|
+
message: `the Worker could not load fast-mesh (${cause})`
|
|
422
|
+
}
|
|
423
|
+
}, []);
|
|
424
|
+
});
|
|
425
|
+
endpoint.onMessage((data) => {
|
|
426
|
+
if (isInit(data)) {
|
|
427
|
+
if (!started && typeof ready === "function") {
|
|
428
|
+
started = true;
|
|
429
|
+
if (data.backgroundAddTriangles !== void 0) engineOptions = {
|
|
430
|
+
...options,
|
|
431
|
+
backgroundAddTriangles: data.backgroundAddTriangles
|
|
432
|
+
};
|
|
433
|
+
serve(new Promise((resolve) => resolve(ready(data))));
|
|
434
|
+
}
|
|
435
|
+
} else if (giveBack) back([data]);
|
|
436
|
+
else if (deliver === void 0) early.push(data);
|
|
437
|
+
else deliver(data);
|
|
438
|
+
});
|
|
439
|
+
if (typeof ready !== "function") serve(ready);
|
|
440
|
+
}
|
|
441
|
+
function unknown(code, id) {
|
|
442
|
+
return new FastMeshError(code, `no ${code.slice(8).toLowerCase()} with client id ${id}`);
|
|
443
|
+
}
|
|
444
|
+
function invalid(message) {
|
|
445
|
+
return new FastMeshError("INVALID_ARGUMENT", message);
|
|
446
|
+
}
|
|
447
|
+
function isPoison(e) {
|
|
448
|
+
return e instanceof FastMeshError && e.code === "INSTANCE_POISONED" || e instanceof WebAssembly.RuntimeError;
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* An error as it crosses the boundary. A `FastMeshError` keeps its code;
|
|
452
|
+
* anything else (a malformed request) is reported as `INVALID_ARGUMENT`.
|
|
453
|
+
*/
|
|
454
|
+
function toWire(e) {
|
|
455
|
+
if (e instanceof FastMeshError) return {
|
|
456
|
+
code: e.code,
|
|
457
|
+
message: e.message
|
|
458
|
+
};
|
|
459
|
+
return {
|
|
460
|
+
code: "INVALID_ARGUMENT",
|
|
461
|
+
message: e instanceof Error ? `${e.name}: ${e.message}` : String(e)
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
const POISONED = {
|
|
465
|
+
code: "INSTANCE_POISONED",
|
|
466
|
+
message: "an earlier fast-mesh call panicked; the WebAssembly instance can no longer be used"
|
|
467
|
+
};
|
|
468
|
+
/** The poisoned error after packing or sending a result failed with `e`. */
|
|
469
|
+
function packingFailed(e) {
|
|
470
|
+
return {
|
|
471
|
+
code: "INSTANCE_POISONED",
|
|
472
|
+
message: `packing or sending the Worker result failed (${e instanceof Error ? `${e.name}: ${e.message}` : String(e)}); the Worker scene can no longer be used`
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
/** Elements per slot of each buffer. */
|
|
476
|
+
const STRIDE = {
|
|
477
|
+
positions: 3,
|
|
478
|
+
normals: 3,
|
|
479
|
+
colors: 4,
|
|
480
|
+
values: 1,
|
|
481
|
+
indices: 3
|
|
482
|
+
};
|
|
483
|
+
/** A buffer's dirty ranges: the values change with the colours. */
|
|
484
|
+
const rangesOf = (c, name) => c[name === "values" ? "colors" : name];
|
|
485
|
+
/** Copies the dirty elements of `view` into a fresh buffer: the whole view for `"all"`. */
|
|
486
|
+
function copyRanges(view, ranges, stride) {
|
|
487
|
+
if (ranges === "all") return view.slice().buffer;
|
|
488
|
+
let total = 0;
|
|
489
|
+
for (const [, count] of ranges) total += count * stride;
|
|
490
|
+
const out = new view.constructor(total);
|
|
491
|
+
let at = 0;
|
|
492
|
+
for (const [start, count] of ranges) {
|
|
493
|
+
out.set(view.subarray(start * stride, (start + count) * stride), at);
|
|
494
|
+
at += count * stride;
|
|
495
|
+
}
|
|
496
|
+
return out.buffer;
|
|
497
|
+
}
|
|
498
|
+
/** What one batch collects for its `Result`. */
|
|
499
|
+
var Batch = class {
|
|
500
|
+
rev = 0;
|
|
501
|
+
status = [];
|
|
502
|
+
replies = [];
|
|
503
|
+
colorings = [];
|
|
504
|
+
transfer = [];
|
|
505
|
+
ready(key, rev) {
|
|
506
|
+
if (key !== void 0) this.status.push({
|
|
507
|
+
key,
|
|
508
|
+
rev,
|
|
509
|
+
status: "ready"
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
error(key, rev, error) {
|
|
513
|
+
if (key !== void 0) this.status.push({
|
|
514
|
+
key,
|
|
515
|
+
rev,
|
|
516
|
+
status: "error",
|
|
517
|
+
error
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
/** Marks the end of a received batch in the queue: its result is posted there. */
|
|
522
|
+
const END = Symbol("end of batch");
|
|
523
|
+
/** Whether every byte of a {@link Packed} copy is copied. */
|
|
524
|
+
const packedAll = (p) => p !== void 0 && p.done === p.positions.byteLength + (p.normals?.byteLength ?? 0) + p.indices.byteLength;
|
|
525
|
+
/**
|
|
526
|
+
* Yields to the message loop, so batches sent meanwhile are received:
|
|
527
|
+
* `setImmediate` where there is one (Node: a chain of `MessageChannel` ticks
|
|
528
|
+
* after chunks of a millisecond or more lets no `parentPort` message in,
|
|
529
|
+
* measured), else a `MessageChannel` tick (browsers interleave it with the
|
|
530
|
+
* Worker's messages, checked in headless Chrome; nested timers are clamped
|
|
531
|
+
* to 4 ms there), else `setTimeout(0)`.
|
|
532
|
+
*/
|
|
533
|
+
function messageTick() {
|
|
534
|
+
const immediate = globalThis.setImmediate;
|
|
535
|
+
if (typeof immediate === "function") return () => new Promise((resolve) => immediate(resolve));
|
|
536
|
+
if (typeof MessageChannel === "undefined") return () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
537
|
+
const channel = new MessageChannel();
|
|
538
|
+
const waiting = [];
|
|
539
|
+
channel.port1.onmessage = () => waiting.shift()?.();
|
|
540
|
+
channel.port1.unref?.();
|
|
541
|
+
return () => new Promise((resolve) => {
|
|
542
|
+
waiting.push(resolve);
|
|
543
|
+
channel.port2.postMessage(null);
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
var Engine = class {
|
|
547
|
+
#port;
|
|
548
|
+
#scene = new Scene();
|
|
549
|
+
/** The scene's stepped field updates (internal API). */
|
|
550
|
+
#steps = fieldSteps(this.#scene);
|
|
551
|
+
/** The scene's stepped mesh adds (internal API). */
|
|
552
|
+
#meshAdds = meshAdds(this.#scene);
|
|
553
|
+
/** Meshes being added in the background, in arrival order. */
|
|
554
|
+
#adds = [];
|
|
555
|
+
/**
|
|
556
|
+
* Landed background adds whose render buffers were copied out before:
|
|
557
|
+
* their record in the next frame sends these copies, unless a request
|
|
558
|
+
* changed the mesh since (see {@link Engine.#unpack}).
|
|
559
|
+
*/
|
|
560
|
+
#packed = /* @__PURE__ */ new Map();
|
|
561
|
+
#backgroundAdd;
|
|
562
|
+
#addStepWork;
|
|
563
|
+
/** More than one thread: a waiting request finishes adds in one call. */
|
|
564
|
+
#threaded;
|
|
565
|
+
#keepCopies;
|
|
566
|
+
/** The revision of the last result posted, for `update` messages. */
|
|
567
|
+
#lastRev = 0;
|
|
568
|
+
/** A received batch is being run: its first request started, its result is not posted yet. */
|
|
569
|
+
#batchOpen = false;
|
|
570
|
+
/**
|
|
571
|
+
* The open batch's end marker is consumed (its fields are being stepped
|
|
572
|
+
* or its result packed): a poisoning then must not take the next
|
|
573
|
+
* batch's requests for this one's.
|
|
574
|
+
*/
|
|
575
|
+
#endConsumed = false;
|
|
576
|
+
/** Requests received and not run yet, each batch followed by {@link END}. */
|
|
577
|
+
#queue = [];
|
|
578
|
+
/** A drain is under way (possibly waiting at a yield). */
|
|
579
|
+
#running = false;
|
|
580
|
+
/** What the batch being run collects for its result. */
|
|
581
|
+
#batch = new Batch();
|
|
582
|
+
#poisoned = false;
|
|
583
|
+
/** A `values` request turned the values mirror on. */
|
|
584
|
+
#mirrorValues = false;
|
|
585
|
+
/** The next result carries every coloured mesh's colours and values whole. */
|
|
586
|
+
#valuesFull = false;
|
|
587
|
+
#meshes = /* @__PURE__ */ new Map();
|
|
588
|
+
#fields = /* @__PURE__ */ new Map();
|
|
589
|
+
/** Fields whose build was abandoned: built when a request first needs them. */
|
|
590
|
+
#deferred = /* @__PURE__ */ new Map();
|
|
591
|
+
#sections = /* @__PURE__ */ new Map();
|
|
592
|
+
/** Engine handles back to client ids, for change records and query results. */
|
|
593
|
+
#meshIds = /* @__PURE__ */ new Map();
|
|
594
|
+
#fieldIds = /* @__PURE__ */ new Map();
|
|
595
|
+
#sectionIds = /* @__PURE__ */ new Map();
|
|
596
|
+
/**
|
|
597
|
+
* Handles removed this batch: their reverse ids are dropped once the frame
|
|
598
|
+
* (which may still report them) is packed.
|
|
599
|
+
*/
|
|
600
|
+
#removed = [];
|
|
601
|
+
#removedFields = [];
|
|
602
|
+
#removedSections = [];
|
|
603
|
+
/** Each field's meshes, `[on, to]`: removing either drops the field. */
|
|
604
|
+
/** Per field: `[on, ...to]`. */
|
|
605
|
+
#fieldMeshes = /* @__PURE__ */ new Map();
|
|
606
|
+
/** Each section's meshes, for the entries a mesh removal ends. */
|
|
607
|
+
#sectionMeshes = /* @__PURE__ */ new Map();
|
|
608
|
+
/** Section entries ended by mesh removals this batch, reported as `null`. */
|
|
609
|
+
#goneEntries = [];
|
|
610
|
+
/** The active drag, by the dragged mesh's client id. */
|
|
611
|
+
#drag;
|
|
612
|
+
#debug;
|
|
613
|
+
#onChunk;
|
|
614
|
+
#tick = messageTick();
|
|
615
|
+
#yieldMs;
|
|
616
|
+
/** When the engine last yielded (or started draining). */
|
|
617
|
+
#yielded = 0;
|
|
618
|
+
#stepPoints;
|
|
619
|
+
/**
|
|
620
|
+
* The `display:` statuses of batches whose field step unit was abandoned:
|
|
621
|
+
* they go with the result of the batch whose unit completes next, so the
|
|
622
|
+
* keys read "computing" until then.
|
|
623
|
+
*/
|
|
624
|
+
#held = [];
|
|
625
|
+
/**
|
|
626
|
+
* The meshes of the last abandoned unit, until a unit completes: its
|
|
627
|
+
* fields are still due, so a unit opened while a request queued makes it
|
|
628
|
+
* stale would be abandoned too.
|
|
629
|
+
*/
|
|
630
|
+
#lastAbandoned;
|
|
631
|
+
#staleGuardMs;
|
|
632
|
+
/**
|
|
633
|
+
* When the last field step unit completed (the engine's start before
|
|
634
|
+
* the first): drag moves abandon units only within the guard after it.
|
|
635
|
+
*/
|
|
636
|
+
#published = now();
|
|
637
|
+
constructor(port, options) {
|
|
638
|
+
this.#port = port;
|
|
639
|
+
this.#debug = options.debug ?? false;
|
|
640
|
+
this.#onChunk = options.onChunk;
|
|
641
|
+
this.#yieldMs = options.yieldMs ?? 4;
|
|
642
|
+
const points = Math.floor(options.stepPoints ?? 4096);
|
|
643
|
+
this.#stepPoints = points >= 1 ? Math.min(points, ALL_POINTS) : 1;
|
|
644
|
+
this.#staleGuardMs = options.staleGuardMs ?? 200;
|
|
645
|
+
const bg = options.backgroundAddTriangles;
|
|
646
|
+
this.#backgroundAdd = bg === void 0 || Number.isNaN(bg) ? BACKGROUND_ADD_TRIANGLES : Math.max(0, bg);
|
|
647
|
+
const work = Math.floor(options.addStepWork ?? 1e5);
|
|
648
|
+
this.#addStepWork = work >= 1 ? Math.min(work, ALL_POINTS) : ADD_STEP_WORK;
|
|
649
|
+
this.#threaded = (options.threads ?? 1) > 1;
|
|
650
|
+
this.#keepCopies = options.keepCopies ?? false;
|
|
651
|
+
this.#steps.setDefer(true);
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* {@link Engine.#maybeYield}, first advancing the oldest background add by
|
|
655
|
+
* one step when the time budget is spent, so that adds go on while the
|
|
656
|
+
* engine is busy (about half the time at most). `false` once poisoned.
|
|
657
|
+
*/
|
|
658
|
+
async #yieldWithAdds(land = true) {
|
|
659
|
+
if (this.#adds.length > 0 && now() - this.#yielded >= this.#yieldMs && !await this.#advanceAdd(land)) return false;
|
|
660
|
+
await this.#maybeYield();
|
|
661
|
+
return true;
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Yields to the message loop once the time budget since the last yield is
|
|
665
|
+
* spent; batches sent meanwhile are received there, and the next chunk's
|
|
666
|
+
* cancellation check sees them.
|
|
667
|
+
*/
|
|
668
|
+
async #maybeYield() {
|
|
669
|
+
if (now() - this.#yielded >= this.#yieldMs) {
|
|
670
|
+
await this.#tick();
|
|
671
|
+
this.#yielded = now();
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
receive(batch) {
|
|
675
|
+
if (this.#poisoned) {
|
|
676
|
+
this.#postPoisoned(batch, new Batch());
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
this.#queue.push(...batch, END);
|
|
680
|
+
if (!this.#running) this.#drain();
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Whether a later queued request (from index `from` on) with the same key
|
|
684
|
+
* supersedes the last-wins request `req`.
|
|
685
|
+
*/
|
|
686
|
+
#superseded(req, key, from = 0) {
|
|
687
|
+
if (key === void 0 || !isLastWins(req)) return false;
|
|
688
|
+
for (let k = from; k < this.#queue.length; k++) {
|
|
689
|
+
const later = this.#queue[k];
|
|
690
|
+
if (later !== END && keyOf(later) === key) return supersedes(later, req);
|
|
691
|
+
}
|
|
692
|
+
return false;
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Cooperative cancellation of a field build: a field `add` keyed like the
|
|
696
|
+
* display it is built for is abandoned when the request it feeds (the next
|
|
697
|
+
* queued last-wins request with that key) is already superseded. The field
|
|
698
|
+
* is then kept as deferred and built when first needed.
|
|
699
|
+
*/
|
|
700
|
+
#abandoned(req, key) {
|
|
701
|
+
if (req.kind !== "field" || req.op !== "add" || key === void 0 || req.desc === void 0) return false;
|
|
702
|
+
if (this.#fields.has(req.field) || this.#deferred.has(req.field)) return false;
|
|
703
|
+
if (!this.#feedsSuperseded(key)) return false;
|
|
704
|
+
this.#deferred.set(req.field, req.desc);
|
|
705
|
+
this.#fieldMeshes.set(req.field, [req.desc.on, ...req.desc.to]);
|
|
706
|
+
return true;
|
|
707
|
+
}
|
|
708
|
+
/** Whether the next queued last-wins request keyed `key` is already superseded. */
|
|
709
|
+
#feedsSuperseded(key) {
|
|
710
|
+
if (key === void 0) return false;
|
|
711
|
+
const at = this.#queue.findIndex((x) => x !== END && keyOf(x) === key && isLastWins(x));
|
|
712
|
+
return at >= 0 && this.#superseded(this.#queue[at], key, at + 1);
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Runs the queue in arrival order, one chunk (a request, or one operation
|
|
716
|
+
* of a repair list) at a time, yielding to the message loop between
|
|
717
|
+
* chunks once the time budget is spent, so that newer batches are
|
|
718
|
+
* received meanwhile: superseded "last
|
|
719
|
+
* wins" requests are then dropped before they start, and abandoned field
|
|
720
|
+
* builds are deferred. Each batch's result is posted when its last
|
|
721
|
+
* request is done, so results stay one per batch, in order.
|
|
722
|
+
*/
|
|
723
|
+
async #drain() {
|
|
724
|
+
this.#running = true;
|
|
725
|
+
this.#yielded = now();
|
|
726
|
+
try {
|
|
727
|
+
while (this.#queue.length > 0 || this.#adds.length > 0) {
|
|
728
|
+
if (this.#queue.length === 0) {
|
|
729
|
+
if (!await this.#advanceAdd()) return;
|
|
730
|
+
await this.#tick();
|
|
731
|
+
this.#yielded = now();
|
|
732
|
+
continue;
|
|
733
|
+
}
|
|
734
|
+
const item = this.#queue.shift();
|
|
735
|
+
if (item === END) {
|
|
736
|
+
this.#batchOpen = true;
|
|
737
|
+
this.#endConsumed = true;
|
|
738
|
+
if (!await this.#stepFields() || !this.#finish()) return;
|
|
739
|
+
this.#batchOpen = false;
|
|
740
|
+
this.#endConsumed = false;
|
|
741
|
+
} else {
|
|
742
|
+
this.#batchOpen = true;
|
|
743
|
+
if (!await this.#step(item)) return;
|
|
744
|
+
}
|
|
745
|
+
if (this.#queue.length > 0 && this.#queue[0] !== END && !await this.#yieldWithAdds()) return;
|
|
746
|
+
}
|
|
747
|
+
} finally {
|
|
748
|
+
this.#running = false;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
/** Runs one request; `false` once the engine is poisoned. */
|
|
752
|
+
async #step(req) {
|
|
753
|
+
const b = this.#batch;
|
|
754
|
+
b.rev = Math.max(b.rev, req.rev);
|
|
755
|
+
const key = keyOf(req);
|
|
756
|
+
if (this.#superseded(req, key) || this.#abandoned(req, key)) return true;
|
|
757
|
+
if (this.#adds.length > 0 && this.#dependsOnAdds(req) && !await this.#finishAdds(req)) return false;
|
|
758
|
+
this.#unpack(req);
|
|
759
|
+
try {
|
|
760
|
+
if (req.kind === "addMesh" && this.#inBackground(req)) {
|
|
761
|
+
this.#beginAdd(req);
|
|
762
|
+
this.#onChunk?.({
|
|
763
|
+
kind: "addMeshBegin",
|
|
764
|
+
id: req.id
|
|
765
|
+
});
|
|
766
|
+
return true;
|
|
767
|
+
}
|
|
768
|
+
if (req.kind === "repair" && this.#inSteps(req)) await this.#repairInSteps(req, b);
|
|
769
|
+
else if (req.kind === "field" && req.op === "add") {
|
|
770
|
+
if (!await this.#addFieldInSteps(req, key)) return true;
|
|
771
|
+
} else this.#run(req, b);
|
|
772
|
+
b.ready(key, req.rev);
|
|
773
|
+
this.#onChunk?.({
|
|
774
|
+
kind: req.kind,
|
|
775
|
+
id: req.id
|
|
776
|
+
});
|
|
777
|
+
} catch (e) {
|
|
778
|
+
if (isPoison(e)) {
|
|
779
|
+
this.#poison(b, POISONED, req);
|
|
780
|
+
return false;
|
|
781
|
+
}
|
|
782
|
+
const error = toWire(e);
|
|
783
|
+
b.error(key, req.rev, error);
|
|
784
|
+
const qid = req.qid;
|
|
785
|
+
if (qid !== void 0) b.replies.push({
|
|
786
|
+
qid,
|
|
787
|
+
ok: false,
|
|
788
|
+
error
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
return true;
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Whether an add runs in the background: the port can post updates, the
|
|
795
|
+
* mesh is large enough, and the add is not asked to run in place.
|
|
796
|
+
*/
|
|
797
|
+
#inBackground(req) {
|
|
798
|
+
return this.#port.postUpdate !== void 0 && req.inline !== true && req.indices.byteLength / 12 >= this.#backgroundAdd;
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Starts adding a mesh in the background: the mesh and its BVH are built
|
|
802
|
+
* outside the scene, a step at a time between other chunks and while the
|
|
803
|
+
* Worker is idle, and it lands in the scene when built, in arrival order
|
|
804
|
+
* with the other background adds. Until then its status is held, and a
|
|
805
|
+
* request that depends on it ({@link Engine.#dependsOnAdds}) first
|
|
806
|
+
* finishes every background add; other requests run meanwhile.
|
|
807
|
+
*/
|
|
808
|
+
#beginAdd(req) {
|
|
809
|
+
if (this.#meshes.has(req.id) || this.#adds.some((a) => a.id === req.id)) throw invalid(`mesh client id ${req.id} is already in use`);
|
|
810
|
+
const positions = req.f64 ? new Float64Array(req.positions) : new Float32Array(req.positions);
|
|
811
|
+
const token = this.#meshAdds.begin(positions, new Uint32Array(req.indices), {
|
|
812
|
+
...req.options,
|
|
813
|
+
mode: "eager"
|
|
814
|
+
});
|
|
815
|
+
this.#adds.push({
|
|
816
|
+
id: req.id,
|
|
817
|
+
token,
|
|
818
|
+
key: keyOf(req),
|
|
819
|
+
rev: req.rev,
|
|
820
|
+
built: false
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
/** Whether a mesh of `ids` is being added in the background. */
|
|
824
|
+
#pending(...ids) {
|
|
825
|
+
return this.#adds.some((a) => ids.includes(a.id));
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* Whether the field `id` is deferred (not built yet) and measured on or
|
|
829
|
+
* to a mesh being added in the background: building it needs that mesh.
|
|
830
|
+
*/
|
|
831
|
+
#fieldPending(id) {
|
|
832
|
+
const desc = this.#deferred.get(id);
|
|
833
|
+
return desc !== void 0 && this.#pending(desc.on, ...desc.to);
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Whether `req` must see the background adds landed first: it names one
|
|
837
|
+
* of their meshes, or a deferred field measured on or to one (building
|
|
838
|
+
* it needs the mesh), adds or removes a mesh (slots are allocated in
|
|
839
|
+
* arrival order), or queries every mesh (`raycast`, `closestPoint`
|
|
840
|
+
* without a mesh, `findContacts` without pairs).
|
|
841
|
+
*/
|
|
842
|
+
#dependsOnAdds(req) {
|
|
843
|
+
switch (req.kind) {
|
|
844
|
+
case "addMesh":
|
|
845
|
+
case "removeMesh": return true;
|
|
846
|
+
case "compact":
|
|
847
|
+
case "setPlacement":
|
|
848
|
+
case "drag":
|
|
849
|
+
case "edit":
|
|
850
|
+
case "repair": return this.#pending(req.id);
|
|
851
|
+
case "coloring": return this.#pending(req.id) || req.rule !== null && this.#fieldPending(req.rule?.field);
|
|
852
|
+
case "fetchFieldValues": return this.#fieldPending(req.field);
|
|
853
|
+
case "field": return req.desc !== void 0 ? this.#pending(req.desc.on, ...req.desc.to) : this.#fieldPending(req.field);
|
|
854
|
+
case "section": {
|
|
855
|
+
const meshes = req.desc?.meshes;
|
|
856
|
+
return Array.isArray(meshes) && this.#pending(...meshes);
|
|
857
|
+
}
|
|
858
|
+
case "query": {
|
|
859
|
+
const a = req.args ?? {};
|
|
860
|
+
switch (req.name) {
|
|
861
|
+
case "raycast": return true;
|
|
862
|
+
case "fieldStatus":
|
|
863
|
+
case "fieldNearest":
|
|
864
|
+
case "fieldTargetStatus": return this.#fieldPending(a.field);
|
|
865
|
+
case "closestPoint": return a.options?.mesh === void 0 || this.#pending(a.options.mesh);
|
|
866
|
+
case "findContacts": return a.pairs === void 0 || this.#pending(...a.pairs.flat());
|
|
867
|
+
default: return this.#pending(a.a, a.b, a.mesh);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
default: return false;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Advances the oldest background add by one step: of its build (BVH and
|
|
875
|
+
* normals), or once built, of the copy of its render buffers
|
|
876
|
+
* ({@link Engine.#pack}); with `land`, lands it once copied (landing
|
|
877
|
+
* changes the scene, which would drop an open field step unit: the
|
|
878
|
+
* unit's loop steps without landing; copying changes nothing). A build
|
|
879
|
+
* that fails is dropped, with an error status for its add. Without
|
|
880
|
+
* `copy`, a built add lands at once and the frame copies its buffers.
|
|
881
|
+
* `false` once poisoned.
|
|
882
|
+
*/
|
|
883
|
+
async #advanceAdd(land = true, failed, copy = true) {
|
|
884
|
+
const a = this.#adds[0];
|
|
885
|
+
if (a === void 0) return true;
|
|
886
|
+
if (a.built && (!copy || a.uncopied === true) && land) {
|
|
887
|
+
a.packed = void 0;
|
|
888
|
+
return this.#land(a, failed);
|
|
889
|
+
}
|
|
890
|
+
if (!a.built) {
|
|
891
|
+
try {
|
|
892
|
+
a.built = this.#meshAdds.step(a.token, this.#addStepWork);
|
|
893
|
+
} catch (e) {
|
|
894
|
+
return this.#addFailed(a, e, false, failed);
|
|
895
|
+
}
|
|
896
|
+
this.#onChunk?.({
|
|
897
|
+
kind: "addMeshStep",
|
|
898
|
+
id: a.id
|
|
899
|
+
});
|
|
900
|
+
} else if (!packedAll(a.packed) && a.uncopied !== true) {
|
|
901
|
+
try {
|
|
902
|
+
this.#pack(a);
|
|
903
|
+
} catch (e) {
|
|
904
|
+
if (isPoison(e)) return this.#addFailed(a, e, false, failed);
|
|
905
|
+
a.packed = void 0;
|
|
906
|
+
a.uncopied = true;
|
|
907
|
+
}
|
|
908
|
+
this.#onChunk?.({
|
|
909
|
+
kind: "addMeshPack",
|
|
910
|
+
id: a.id
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
return (packedAll(a.packed) || a.uncopied === true) && land ? this.#land(a, failed) : true;
|
|
914
|
+
}
|
|
915
|
+
/**
|
|
916
|
+
* Whether `req` may change the positions, normals or triangles of the
|
|
917
|
+
* mesh `id`: an edit, repair, compaction or removal of it, or any undo
|
|
918
|
+
* or redo.
|
|
919
|
+
*/
|
|
920
|
+
#changesMesh(req, id) {
|
|
921
|
+
switch (req.kind) {
|
|
922
|
+
case "edit":
|
|
923
|
+
case "repair":
|
|
924
|
+
case "compact":
|
|
925
|
+
case "removeMesh": return req.id === id;
|
|
926
|
+
case "undo":
|
|
927
|
+
case "redo": return true;
|
|
928
|
+
default: return false;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Copies about {@link EngineOptions.addStepWork} × 64 more bytes of a
|
|
933
|
+
* built add's render buffers (positions, normals, indices) out of wasm
|
|
934
|
+
* memory, so that the frame it lands in sends them instead of copying
|
|
935
|
+
* the whole mesh then. The build's buffers are the added mesh's, moved
|
|
936
|
+
* into the scene unchanged, so the copies are what the frame would copy,
|
|
937
|
+
* bit for bit, unless a request changes the mesh first
|
|
938
|
+
* ({@link Engine.#unpack}).
|
|
939
|
+
*/
|
|
940
|
+
#pack(a) {
|
|
941
|
+
const views = this.#meshAdds.buffers(a.token);
|
|
942
|
+
const p = a.packed ??= {
|
|
943
|
+
positions: new ArrayBuffer(views.positions.byteLength),
|
|
944
|
+
normals: views.normals === null ? null : new ArrayBuffer(views.normals.byteLength),
|
|
945
|
+
indices: new ArrayBuffer(views.indices.byteLength),
|
|
946
|
+
done: 0
|
|
947
|
+
};
|
|
948
|
+
const parts = [
|
|
949
|
+
[views.positions, p.positions],
|
|
950
|
+
[views.normals, p.normals],
|
|
951
|
+
[views.indices, p.indices]
|
|
952
|
+
];
|
|
953
|
+
let budget = this.#addStepWork * PACK_BYTES_PER_UNIT;
|
|
954
|
+
let start = 0;
|
|
955
|
+
for (const [view, out] of parts) {
|
|
956
|
+
if (view === null || out === null) continue;
|
|
957
|
+
const end = start + out.byteLength;
|
|
958
|
+
if (budget > 0 && p.done < end) {
|
|
959
|
+
const from = p.done - start;
|
|
960
|
+
const n = Math.min(out.byteLength - from, budget);
|
|
961
|
+
new Uint8Array(out, from, n).set(new Uint8Array(view.buffer, view.byteOffset + from, n));
|
|
962
|
+
p.done += n;
|
|
963
|
+
budget -= n;
|
|
964
|
+
}
|
|
965
|
+
start = end;
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Forgets the copied-out buffers of a landed mesh that `req` may change
|
|
970
|
+
* (an edit, repair or compaction of it, an undo or redo), to free them
|
|
971
|
+
* early. Correctness does not depend on it: the copies are sent only
|
|
972
|
+
* while the mesh's content stamp is the one it landed with.
|
|
973
|
+
*/
|
|
974
|
+
#unpack(req) {
|
|
975
|
+
if (this.#packed.size === 0 || this.#keepCopies) return;
|
|
976
|
+
for (const h of [...this.#packed.keys()]) if (this.#changesMesh(req, this.#meshId(h))) this.#packed.delete(h);
|
|
977
|
+
}
|
|
978
|
+
/**
|
|
979
|
+
* Finishes every background add, in arrival order, for `failed`, the
|
|
980
|
+
* request that waits on them (it is among the failed requests if they
|
|
981
|
+
* poison the engine). Threaded, each lands in one call, which builds
|
|
982
|
+
* what is left of its BVH at once with the parallel one-call build
|
|
983
|
+
* (several times faster than steps). Single-threaded the two cost the
|
|
984
|
+
* same, so it keeps stepping, yielding (to receive only) between steps,
|
|
985
|
+
* so that newer batches still arrive and coalesce; it skips the copy of
|
|
986
|
+
* an add's buffers when `failed` changes that mesh (the frame copies
|
|
987
|
+
* them anyway).
|
|
988
|
+
*/
|
|
989
|
+
async #finishAdds(failed) {
|
|
990
|
+
while (this.#adds.length > 0) {
|
|
991
|
+
if (this.#threaded) {
|
|
992
|
+
if (!this.#land(this.#adds[0], failed)) return false;
|
|
993
|
+
continue;
|
|
994
|
+
}
|
|
995
|
+
const copy = failed === void 0 || !this.#changesMesh(failed, this.#adds[0].id);
|
|
996
|
+
if (!await this.#advanceAdd(true, failed, copy)) return false;
|
|
997
|
+
if (this.#adds.length > 0) await this.#maybeYield();
|
|
998
|
+
}
|
|
999
|
+
return true;
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Adds a built mesh to the scene. Its status goes with the batch under
|
|
1003
|
+
* way, or, when the Worker is idle (no batch received and not finished),
|
|
1004
|
+
* in an `update` message with the frame it lands in.
|
|
1005
|
+
*/
|
|
1006
|
+
#land(a, failed) {
|
|
1007
|
+
this.#adds.shift();
|
|
1008
|
+
let h;
|
|
1009
|
+
try {
|
|
1010
|
+
h = this.#meshAdds.finish(a.token);
|
|
1011
|
+
} catch (e) {
|
|
1012
|
+
return this.#addFailed(a, e, true, failed);
|
|
1013
|
+
}
|
|
1014
|
+
this.#meshes.set(a.id, h);
|
|
1015
|
+
this.#meshIds.set(h, a.id);
|
|
1016
|
+
if (packedAll(a.packed)) try {
|
|
1017
|
+
a.packed.stamp = this.#meshAdds.stamp(h);
|
|
1018
|
+
this.#packed.set(h, a.packed);
|
|
1019
|
+
} catch (e) {
|
|
1020
|
+
if (isPoison(e)) return this.#addFailed(a, e, true, failed);
|
|
1021
|
+
}
|
|
1022
|
+
this.#onChunk?.({
|
|
1023
|
+
kind: "addMesh",
|
|
1024
|
+
id: a.id
|
|
1025
|
+
});
|
|
1026
|
+
this.#settle((b) => b.ready(a.key, a.rev));
|
|
1027
|
+
return true;
|
|
1028
|
+
}
|
|
1029
|
+
/**
|
|
1030
|
+
* Drops a failed background add; `false` (poisoned) on a trap, with
|
|
1031
|
+
* `failed` (the request waiting on it, if any) among the failed requests.
|
|
1032
|
+
*/
|
|
1033
|
+
#addFailed(a, e, taken = false, failed) {
|
|
1034
|
+
if (!taken) {
|
|
1035
|
+
this.#adds.shift();
|
|
1036
|
+
try {
|
|
1037
|
+
this.#meshAdds.drop(a.token);
|
|
1038
|
+
} catch {}
|
|
1039
|
+
}
|
|
1040
|
+
if (isPoison(e)) {
|
|
1041
|
+
if (this.#batchOpen) {
|
|
1042
|
+
this.#batch.error(a.key, a.rev, POISONED);
|
|
1043
|
+
this.#poison(this.#batch, POISONED, failed, this.#endConsumed);
|
|
1044
|
+
} else {
|
|
1045
|
+
const b = new Batch();
|
|
1046
|
+
b.error(a.key, a.rev, POISONED);
|
|
1047
|
+
this.#poisonIdle(b, POISONED);
|
|
1048
|
+
}
|
|
1049
|
+
return false;
|
|
1050
|
+
}
|
|
1051
|
+
const error = toWire(e);
|
|
1052
|
+
this.#settle((b) => b.error(a.key, a.rev, error));
|
|
1053
|
+
return true;
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Records a background add's outcome with `put`: in the batch under way,
|
|
1057
|
+
* or, when the Worker is idle, in an `update` message with the frame.
|
|
1058
|
+
*/
|
|
1059
|
+
#settle(put) {
|
|
1060
|
+
if (this.#batchOpen) {
|
|
1061
|
+
put(this.#batch);
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
const b = new Batch();
|
|
1065
|
+
b.rev = this.#lastRev;
|
|
1066
|
+
put(b);
|
|
1067
|
+
let result;
|
|
1068
|
+
try {
|
|
1069
|
+
result = this.#result(b);
|
|
1070
|
+
} catch (e) {
|
|
1071
|
+
this.#poisonIdle(b, isPoison(e) ? POISONED : packingFailed(e));
|
|
1072
|
+
return;
|
|
1073
|
+
}
|
|
1074
|
+
try {
|
|
1075
|
+
this.#port.postUpdate?.(result, b.transfer);
|
|
1076
|
+
} catch (e) {
|
|
1077
|
+
this.#poisonIdle(b, packingFailed(e));
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
/**
|
|
1081
|
+
* Brings the fields the batch left due up to date in steps of
|
|
1082
|
+
* {@link EngineOptions.stepPoints} vertices, yielding between them once
|
|
1083
|
+
* the time budget is spent. At each step boundary, when a queued request
|
|
1084
|
+
* makes the unit stale ({@link Engine.#makesStale}), the unit is
|
|
1085
|
+
* abandoned: the batch's result then carries none of its values or
|
|
1086
|
+
* colours, and the `display:` statuses of its meshes are held back until a
|
|
1087
|
+
* later unit completes. No unit is opened while a request queued makes
|
|
1088
|
+
* the last abandoned unit stale (its fields are still due, so the new unit
|
|
1089
|
+
* would be stale too). Past the starvation guard
|
|
1090
|
+
* ({@link EngineOptions.staleGuardMs}) drag moves no longer abandon, so a
|
|
1091
|
+
* sustained drag still publishes. Other requests wait for the unit. A field error
|
|
1092
|
+
* ends the unit like a failed eager update: swallowed, the failing fields
|
|
1093
|
+
* stay stale. `false` once the engine is poisoned.
|
|
1094
|
+
*/
|
|
1095
|
+
async #stepFields() {
|
|
1096
|
+
const steps = this.#steps;
|
|
1097
|
+
const b = this.#batch;
|
|
1098
|
+
if (this.#lastAbandoned !== void 0 && this.#staleQueued(this.#lastAbandoned)) {
|
|
1099
|
+
this.#hold(b, this.#lastAbandoned);
|
|
1100
|
+
return true;
|
|
1101
|
+
}
|
|
1102
|
+
let meshes;
|
|
1103
|
+
for (;;) {
|
|
1104
|
+
let state;
|
|
1105
|
+
try {
|
|
1106
|
+
state = steps.step(this.#stepPoints);
|
|
1107
|
+
if (state === "pending") meshes ??= new Set(steps.meshes().map((h) => this.#meshId(h)));
|
|
1108
|
+
} catch (e) {
|
|
1109
|
+
let error = e;
|
|
1110
|
+
if (!isPoison(error)) try {
|
|
1111
|
+
steps.abandon();
|
|
1112
|
+
} catch (e2) {
|
|
1113
|
+
error = e2;
|
|
1114
|
+
}
|
|
1115
|
+
if (isPoison(error)) {
|
|
1116
|
+
b.status.push(...this.#held.splice(0));
|
|
1117
|
+
this.#poison(b, POISONED, void 0, true);
|
|
1118
|
+
return false;
|
|
1119
|
+
}
|
|
1120
|
+
state = "done";
|
|
1121
|
+
}
|
|
1122
|
+
this.#onChunk?.({ kind: "fieldStep" });
|
|
1123
|
+
if (state !== "pending") {
|
|
1124
|
+
if (state !== "idle") this.#published = now();
|
|
1125
|
+
this.#lastAbandoned = void 0;
|
|
1126
|
+
b.status.push(...this.#held.splice(0));
|
|
1127
|
+
return true;
|
|
1128
|
+
}
|
|
1129
|
+
if (!await this.#yieldWithAdds(false)) return false;
|
|
1130
|
+
if (meshes !== void 0 && this.#staleQueued(meshes)) {
|
|
1131
|
+
steps.abandon();
|
|
1132
|
+
this.#onChunk?.({ kind: "fieldStepAbandon" });
|
|
1133
|
+
this.#lastAbandoned = meshes;
|
|
1134
|
+
this.#hold(b, meshes);
|
|
1135
|
+
return true;
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
/**
|
|
1140
|
+
* Whether a queued request makes a unit over `meshes` stale. Drag moves
|
|
1141
|
+
* count only within the starvation guard after the last completed unit,
|
|
1142
|
+
* or when the drag's `end` is queued too: on release the newest pose
|
|
1143
|
+
* follows within one recompute, never after a kept older one. (An `end`
|
|
1144
|
+
* with no move queued before it leaves the unit alone: the unit is then
|
|
1145
|
+
* at the final pose.)
|
|
1146
|
+
*/
|
|
1147
|
+
#staleQueued(meshes) {
|
|
1148
|
+
const moves = now() - this.#published <= this.#staleGuardMs || this.#queue.some((item) => item !== END && item.kind === "drag" && item.phase === "end" && meshes.has(item.id));
|
|
1149
|
+
return this.#queue.some((item) => item !== END && this.#makesStale(item, meshes, moves));
|
|
1150
|
+
}
|
|
1151
|
+
/** Moves the batch's `display:` statuses of `meshes` to the held ones. */
|
|
1152
|
+
#hold(b, meshes) {
|
|
1153
|
+
const kept = [];
|
|
1154
|
+
for (const st of b.status.splice(0)) (st.key.startsWith("display:") && meshes.has(Number(st.key.slice(8))) ? this.#held : kept).push(st);
|
|
1155
|
+
b.status.push(...kept);
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Whether the queued `req` makes a field step unit over `meshes` (the
|
|
1159
|
+
* meshes its fields are on and measured to) stale (§6.1): a drag move
|
|
1160
|
+
* (only with `moves`: within the starvation guard), a drag cancel or a
|
|
1161
|
+
* placement, an edit, repair, compaction or removal of one of them, an
|
|
1162
|
+
* undo or redo, or the removal of a field between two of them.
|
|
1163
|
+
*/
|
|
1164
|
+
#makesStale(req, meshes, moves) {
|
|
1165
|
+
switch (req.kind) {
|
|
1166
|
+
case "drag": return meshes.has(req.id) && (req.phase === "cancel" || moves && (req.phase === "move" || req.phase === "end" && req.rotation !== void 0));
|
|
1167
|
+
case "setPlacement":
|
|
1168
|
+
case "edit":
|
|
1169
|
+
case "repair":
|
|
1170
|
+
case "compact":
|
|
1171
|
+
case "removeMesh": return meshes.has(req.id);
|
|
1172
|
+
case "undo":
|
|
1173
|
+
case "redo": return true;
|
|
1174
|
+
case "field": {
|
|
1175
|
+
const on = this.#fieldMeshes.get(req.field);
|
|
1176
|
+
return req.op === "remove" && on !== void 0 && on.every((m) => meshes.has(m));
|
|
1177
|
+
}
|
|
1178
|
+
default: return false;
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* Brings every due field up to date at once, for a request that reads
|
|
1183
|
+
* fields (their values, status or colours). A field error is swallowed
|
|
1184
|
+
* like a failed eager update's; a trap is rethrown.
|
|
1185
|
+
*/
|
|
1186
|
+
#settleFields() {
|
|
1187
|
+
try {
|
|
1188
|
+
while (this.#steps.step(ALL_POINTS) === "pending");
|
|
1189
|
+
} catch (e) {
|
|
1190
|
+
if (isPoison(e)) throw e;
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
/** Posts the finished batch's result; `false` when packing failed (poisoned). */
|
|
1194
|
+
#finish() {
|
|
1195
|
+
const b = this.#batch;
|
|
1196
|
+
this.#batch = new Batch();
|
|
1197
|
+
let result;
|
|
1198
|
+
try {
|
|
1199
|
+
result = this.#result(b);
|
|
1200
|
+
} catch (e) {
|
|
1201
|
+
this.#poison(b, isPoison(e) ? POISONED : packingFailed(e), void 0, true);
|
|
1202
|
+
return false;
|
|
1203
|
+
}
|
|
1204
|
+
this.#lastRev = Math.max(this.#lastRev, result.rev);
|
|
1205
|
+
try {
|
|
1206
|
+
this.#port.post(result, b.transfer);
|
|
1207
|
+
} catch (e) {
|
|
1208
|
+
this.#poison(b, packingFailed(e), void 0, true);
|
|
1209
|
+
return false;
|
|
1210
|
+
}
|
|
1211
|
+
return true;
|
|
1212
|
+
}
|
|
1213
|
+
/**
|
|
1214
|
+
* Stops the engine and posts the batches as failed. In `b`'s result every
|
|
1215
|
+
* status and reply already collected, `failed` and the rest of its batch
|
|
1216
|
+
* (none when `ended`: its end was reached) get `error`; every later batch
|
|
1217
|
+
* already received gets a poisoned result of its own.
|
|
1218
|
+
*/
|
|
1219
|
+
#poison(b, error, failed, ended = false) {
|
|
1220
|
+
this.#poisoned = true;
|
|
1221
|
+
this.#failAdds(b, error);
|
|
1222
|
+
const rest = this.#queue.splice(0);
|
|
1223
|
+
for (const st of b.status) {
|
|
1224
|
+
st.status = "error";
|
|
1225
|
+
st.error = error;
|
|
1226
|
+
}
|
|
1227
|
+
for (const reply of b.replies) {
|
|
1228
|
+
reply.ok = false;
|
|
1229
|
+
reply.error = error;
|
|
1230
|
+
delete reply.value;
|
|
1231
|
+
}
|
|
1232
|
+
b.transfer.length = 0;
|
|
1233
|
+
let end = ended ? -1 : rest.indexOf(END);
|
|
1234
|
+
if (end < 0 && !ended) end = rest.length;
|
|
1235
|
+
const own = rest.slice(0, Math.max(end, 0));
|
|
1236
|
+
this.#postPoisoned(failed === void 0 ? own : [failed, ...own], b, error);
|
|
1237
|
+
for (let start = end + 1; start < rest.length;) {
|
|
1238
|
+
let next = rest.indexOf(END, start);
|
|
1239
|
+
if (next < 0) next = rest.length;
|
|
1240
|
+
this.#postPoisoned(rest.slice(start, next), new Batch(), error);
|
|
1241
|
+
start = next + 1;
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
/**
|
|
1245
|
+
* Stops the engine while no batch is open (a background add trapped or
|
|
1246
|
+
* could not be posted while the Worker was idle): `b`'s outcome, every
|
|
1247
|
+
* pending add's key failed with it, goes out as a poisoned `update`,
|
|
1248
|
+
* which belongs to no batch; batches received but not started (none,
|
|
1249
|
+
* normally) get poisoned results of their own, as later ones will.
|
|
1250
|
+
*/
|
|
1251
|
+
#poisonIdle(b, error) {
|
|
1252
|
+
this.#poisoned = true;
|
|
1253
|
+
this.#failAdds(b, error);
|
|
1254
|
+
for (const st of b.status) {
|
|
1255
|
+
st.status = "error";
|
|
1256
|
+
st.error = error;
|
|
1257
|
+
}
|
|
1258
|
+
const result = {
|
|
1259
|
+
rev: this.#lastRev,
|
|
1260
|
+
changes: [],
|
|
1261
|
+
placements: [],
|
|
1262
|
+
sections: [],
|
|
1263
|
+
history: {
|
|
1264
|
+
canUndo: false,
|
|
1265
|
+
canRedo: false
|
|
1266
|
+
},
|
|
1267
|
+
status: b.status,
|
|
1268
|
+
replies: [],
|
|
1269
|
+
colorings: [],
|
|
1270
|
+
poisoned: true
|
|
1271
|
+
};
|
|
1272
|
+
try {
|
|
1273
|
+
this.#port.postUpdate?.(result, []);
|
|
1274
|
+
} catch {}
|
|
1275
|
+
const rest = this.#queue.splice(0);
|
|
1276
|
+
for (let start = 0; start < rest.length;) {
|
|
1277
|
+
let next = rest.indexOf(END, start);
|
|
1278
|
+
if (next < 0) next = rest.length;
|
|
1279
|
+
this.#postPoisoned(rest.slice(start, next), new Batch(), error);
|
|
1280
|
+
start = next + 1;
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
/** Fails the status of every background add still pending into `b`, and forgets them. */
|
|
1284
|
+
#failAdds(b, error) {
|
|
1285
|
+
for (const a of this.#adds.splice(0)) b.error(a.key, a.rev, error);
|
|
1286
|
+
}
|
|
1287
|
+
#postPoisoned(failed, b, error = POISONED) {
|
|
1288
|
+
for (const req of failed) {
|
|
1289
|
+
b.rev = Math.max(b.rev, req.rev);
|
|
1290
|
+
b.error(keyOf(req), req.rev, error);
|
|
1291
|
+
const qid = req.qid;
|
|
1292
|
+
if (qid !== void 0) b.replies.push({
|
|
1293
|
+
qid,
|
|
1294
|
+
ok: false,
|
|
1295
|
+
error
|
|
1296
|
+
});
|
|
1297
|
+
}
|
|
1298
|
+
const result = {
|
|
1299
|
+
rev: b.rev,
|
|
1300
|
+
changes: [],
|
|
1301
|
+
placements: [],
|
|
1302
|
+
sections: [],
|
|
1303
|
+
history: {
|
|
1304
|
+
canUndo: false,
|
|
1305
|
+
canRedo: false
|
|
1306
|
+
},
|
|
1307
|
+
status: b.status,
|
|
1308
|
+
replies: b.replies,
|
|
1309
|
+
colorings: [],
|
|
1310
|
+
poisoned: true
|
|
1311
|
+
};
|
|
1312
|
+
try {
|
|
1313
|
+
this.#port.post(result, b.transfer);
|
|
1314
|
+
} catch {
|
|
1315
|
+
try {
|
|
1316
|
+
this.#port.post({
|
|
1317
|
+
...result,
|
|
1318
|
+
status: b.status.map((st) => ({
|
|
1319
|
+
key: st.key,
|
|
1320
|
+
rev: st.rev,
|
|
1321
|
+
status: "error",
|
|
1322
|
+
error
|
|
1323
|
+
})),
|
|
1324
|
+
replies: b.replies.map((r) => ({
|
|
1325
|
+
qid: r.qid,
|
|
1326
|
+
ok: false,
|
|
1327
|
+
error
|
|
1328
|
+
}))
|
|
1329
|
+
}, []);
|
|
1330
|
+
} catch {}
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* Whether a repair list runs one operation per chunk, inside a history
|
|
1335
|
+
* step: one undo step, reverted when an operation fails, like the list
|
|
1336
|
+
* call. Only where that is the same as the list call: more than one
|
|
1337
|
+
* operation, no drag holding a step open, and no redo steps (the first
|
|
1338
|
+
* recorded operation would drop them even if a later one fails).
|
|
1339
|
+
*/
|
|
1340
|
+
#inSteps(req) {
|
|
1341
|
+
return Array.isArray(req.payload) && req.payload.length > 1 && this.#drag === void 0 && !this.#scene.canRedo();
|
|
1342
|
+
}
|
|
1343
|
+
async #repairInSteps(req, b) {
|
|
1344
|
+
const s = this.#scene;
|
|
1345
|
+
const mesh = this.#mesh(req.id);
|
|
1346
|
+
const ops = req.payload;
|
|
1347
|
+
const reports = [];
|
|
1348
|
+
s.beginStep();
|
|
1349
|
+
try {
|
|
1350
|
+
for (let k = 0; k < ops.length; k++) {
|
|
1351
|
+
if (k > 0) await this.#maybeYield();
|
|
1352
|
+
reports.push(s.repair(mesh, ops[k]));
|
|
1353
|
+
this.#onChunk?.({
|
|
1354
|
+
kind: "repairOp",
|
|
1355
|
+
id: req.id
|
|
1356
|
+
});
|
|
1357
|
+
}
|
|
1358
|
+
} catch (e) {
|
|
1359
|
+
if (!isPoison(e)) s.cancelStep();
|
|
1360
|
+
throw e;
|
|
1361
|
+
}
|
|
1362
|
+
s.endStep();
|
|
1363
|
+
if (req.qid !== void 0) b.replies.push({
|
|
1364
|
+
qid: req.qid,
|
|
1365
|
+
ok: true,
|
|
1366
|
+
value: reports
|
|
1367
|
+
});
|
|
1368
|
+
}
|
|
1369
|
+
/**
|
|
1370
|
+
* Adds a field and builds it in steps of {@link EngineOptions.stepPoints}
|
|
1371
|
+
* (its sign data, near search and values), yielding between them once the
|
|
1372
|
+
* time budget is spent. At each step boundary the 9a rule applies: when
|
|
1373
|
+
* the display request the add feeds is superseded by a queued one, the
|
|
1374
|
+
* build is abandoned and the field, never computed, is withdrawn without a
|
|
1375
|
+
* report and kept as deferred (built when first needed), as if abandoned
|
|
1376
|
+
* before it started; `false` then. Other requests wait for the build. A
|
|
1377
|
+
* build that fails withdraws the field and throws, so the add fails and
|
|
1378
|
+
* the scene is as before.
|
|
1379
|
+
*/
|
|
1380
|
+
async #addFieldInSteps(req, key) {
|
|
1381
|
+
if (this.#fields.has(req.field) || this.#deferred.has(req.field)) throw invalid(`field client id ${req.field} is already in use`);
|
|
1382
|
+
const desc = req.desc;
|
|
1383
|
+
if (desc === void 0) throw invalid("adding a field needs a desc");
|
|
1384
|
+
const steps = this.#steps;
|
|
1385
|
+
const h = steps.addDeferred({
|
|
1386
|
+
...desc,
|
|
1387
|
+
on: this.#mesh(desc.on),
|
|
1388
|
+
to: desc.to.map((m) => this.#mesh(m))
|
|
1389
|
+
});
|
|
1390
|
+
const forget = () => {
|
|
1391
|
+
if (steps.withdraw(h)) this.#fieldIds.delete(h);
|
|
1392
|
+
else {
|
|
1393
|
+
this.#scene.removeField(h);
|
|
1394
|
+
this.#removedFields.push(h);
|
|
1395
|
+
}
|
|
1396
|
+
this.#fields.delete(req.field);
|
|
1397
|
+
this.#fieldMeshes.delete(req.field);
|
|
1398
|
+
};
|
|
1399
|
+
this.#fields.set(req.field, h);
|
|
1400
|
+
this.#fieldIds.set(h, req.field);
|
|
1401
|
+
this.#fieldMeshes.set(req.field, [desc.on, ...desc.to]);
|
|
1402
|
+
for (;;) {
|
|
1403
|
+
let state;
|
|
1404
|
+
try {
|
|
1405
|
+
state = steps.stepField(h, this.#stepPoints);
|
|
1406
|
+
} catch (e) {
|
|
1407
|
+
if (!isPoison(e)) forget();
|
|
1408
|
+
throw e;
|
|
1409
|
+
}
|
|
1410
|
+
this.#onChunk?.({
|
|
1411
|
+
kind: "fieldBuildStep",
|
|
1412
|
+
id: req.field
|
|
1413
|
+
});
|
|
1414
|
+
if (state !== "pending") break;
|
|
1415
|
+
await this.#maybeYield();
|
|
1416
|
+
if (this.#feedsSuperseded(key)) {
|
|
1417
|
+
steps.abandon();
|
|
1418
|
+
forget();
|
|
1419
|
+
this.#deferred.set(req.field, desc);
|
|
1420
|
+
this.#fieldMeshes.set(req.field, [desc.on, ...desc.to]);
|
|
1421
|
+
this.#onChunk?.({
|
|
1422
|
+
kind: "fieldBuildAbandon",
|
|
1423
|
+
id: req.field
|
|
1424
|
+
});
|
|
1425
|
+
return false;
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
this.#onChunk?.({
|
|
1429
|
+
kind: "fieldBuild",
|
|
1430
|
+
id: req.field
|
|
1431
|
+
});
|
|
1432
|
+
return true;
|
|
1433
|
+
}
|
|
1434
|
+
#mesh(id) {
|
|
1435
|
+
const h = this.#meshes.get(id);
|
|
1436
|
+
if (h === void 0) throw unknown("UNKNOWN_MESH", id);
|
|
1437
|
+
return h;
|
|
1438
|
+
}
|
|
1439
|
+
/** A field's handle; a deferred field is built first. */
|
|
1440
|
+
#field(id) {
|
|
1441
|
+
const h = this.#fields.get(id);
|
|
1442
|
+
if (h !== void 0) return h;
|
|
1443
|
+
const desc = this.#deferred.get(id);
|
|
1444
|
+
if (desc === void 0) throw unknown("UNKNOWN_FIELD", id);
|
|
1445
|
+
return this.#buildField(id, desc);
|
|
1446
|
+
}
|
|
1447
|
+
/**
|
|
1448
|
+
* Computes a field (one chunk). Built late, a field has the values it
|
|
1449
|
+
* would have had (eager fields follow every edit and placement); only its
|
|
1450
|
+
* errors (a taken name, say) surface late, on the request that needs it.
|
|
1451
|
+
* A failed build keeps the field deferred: the next request that needs it
|
|
1452
|
+
* tries again (and reports the error again), and removing it still works.
|
|
1453
|
+
*/
|
|
1454
|
+
#buildField(id, desc) {
|
|
1455
|
+
const h = this.#scene.addDistanceField({
|
|
1456
|
+
...desc,
|
|
1457
|
+
on: this.#mesh(desc.on),
|
|
1458
|
+
to: desc.to.map((m) => this.#mesh(m))
|
|
1459
|
+
});
|
|
1460
|
+
this.#deferred.delete(id);
|
|
1461
|
+
this.#fields.set(id, h);
|
|
1462
|
+
this.#fieldIds.set(h, id);
|
|
1463
|
+
this.#fieldMeshes.set(id, [desc.on, ...desc.to]);
|
|
1464
|
+
this.#onChunk?.({
|
|
1465
|
+
kind: "fieldBuild",
|
|
1466
|
+
id
|
|
1467
|
+
});
|
|
1468
|
+
return h;
|
|
1469
|
+
}
|
|
1470
|
+
#section(id) {
|
|
1471
|
+
const h = this.#sections.get(id);
|
|
1472
|
+
if (h === void 0) throw unknown("UNKNOWN_SECTION", id);
|
|
1473
|
+
return h;
|
|
1474
|
+
}
|
|
1475
|
+
#meshList(ids) {
|
|
1476
|
+
if (!Array.isArray(ids)) throw invalid("meshes must be an array of client ids");
|
|
1477
|
+
return ids.map((id) => this.#mesh(id));
|
|
1478
|
+
}
|
|
1479
|
+
/** The client id of an engine mesh handle (a mesh of this engine always has one). */
|
|
1480
|
+
#meshId(h) {
|
|
1481
|
+
return this.#meshIds.get(h);
|
|
1482
|
+
}
|
|
1483
|
+
#run(req, b) {
|
|
1484
|
+
const s = this.#scene;
|
|
1485
|
+
switch (req.kind) {
|
|
1486
|
+
case "addMesh": {
|
|
1487
|
+
if (this.#meshes.has(req.id) || this.#adds.some((a) => a.id === req.id)) throw invalid(`mesh client id ${req.id} is already in use`);
|
|
1488
|
+
const positions = req.f64 ? new Float64Array(req.positions) : new Float32Array(req.positions);
|
|
1489
|
+
const h = s.addMesh(positions, new Uint32Array(req.indices), {
|
|
1490
|
+
...req.options,
|
|
1491
|
+
mode: "eager"
|
|
1492
|
+
});
|
|
1493
|
+
this.#meshes.set(req.id, h);
|
|
1494
|
+
this.#meshIds.set(h, req.id);
|
|
1495
|
+
return;
|
|
1496
|
+
}
|
|
1497
|
+
case "removeMesh": {
|
|
1498
|
+
const h = this.#mesh(req.id);
|
|
1499
|
+
s.removeMesh(h);
|
|
1500
|
+
this.#meshes.delete(req.id);
|
|
1501
|
+
this.#removed.push(h);
|
|
1502
|
+
if (this.#drag?.id === req.id) this.#drag = void 0;
|
|
1503
|
+
for (const [field, [on, ...to]] of this.#fieldMeshes) if (on === req.id || to.length === 1 && to[0] === req.id) this.#dropField(field);
|
|
1504
|
+
else if (to.includes(req.id)) {
|
|
1505
|
+
this.#fieldMeshes.set(field, [on, ...to.filter((m) => m !== req.id)]);
|
|
1506
|
+
const desc = this.#deferred.get(field);
|
|
1507
|
+
if (desc !== void 0) this.#deferred.set(field, {
|
|
1508
|
+
...desc,
|
|
1509
|
+
to: desc.to.filter((m) => m !== req.id)
|
|
1510
|
+
});
|
|
1511
|
+
}
|
|
1512
|
+
for (const [section, meshes] of this.#sectionMeshes) if (meshes.includes(req.id)) {
|
|
1513
|
+
this.#sectionMeshes.set(section, meshes.filter((m) => m !== req.id));
|
|
1514
|
+
this.#goneEntries.push({
|
|
1515
|
+
section,
|
|
1516
|
+
mesh: req.id
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
return;
|
|
1520
|
+
}
|
|
1521
|
+
case "compact":
|
|
1522
|
+
s.compact(this.#mesh(req.id));
|
|
1523
|
+
return;
|
|
1524
|
+
case "setPlacement":
|
|
1525
|
+
s.setPlacement(this.#mesh(req.id), {
|
|
1526
|
+
rotation: req.rotation,
|
|
1527
|
+
translation: req.translation
|
|
1528
|
+
});
|
|
1529
|
+
return;
|
|
1530
|
+
case "drag":
|
|
1531
|
+
this.#runDrag(req);
|
|
1532
|
+
return;
|
|
1533
|
+
case "edit": {
|
|
1534
|
+
const value = s.edit(this.#mesh(req.id), req.payload);
|
|
1535
|
+
if (req.qid !== void 0) b.replies.push({
|
|
1536
|
+
qid: req.qid,
|
|
1537
|
+
ok: true,
|
|
1538
|
+
value
|
|
1539
|
+
});
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
case "repair": {
|
|
1543
|
+
const value = s.repair(this.#mesh(req.id), req.payload);
|
|
1544
|
+
if (req.qid !== void 0) b.replies.push({
|
|
1545
|
+
qid: req.qid,
|
|
1546
|
+
ok: true,
|
|
1547
|
+
value
|
|
1548
|
+
});
|
|
1549
|
+
return;
|
|
1550
|
+
}
|
|
1551
|
+
case "undo":
|
|
1552
|
+
s.undo();
|
|
1553
|
+
return;
|
|
1554
|
+
case "redo":
|
|
1555
|
+
s.redo();
|
|
1556
|
+
return;
|
|
1557
|
+
case "clearHistory":
|
|
1558
|
+
if (this.#drag !== void 0) {
|
|
1559
|
+
this.#drag.session.end();
|
|
1560
|
+
this.#drag = void 0;
|
|
1561
|
+
}
|
|
1562
|
+
s.clearHistory();
|
|
1563
|
+
return;
|
|
1564
|
+
case "coloring":
|
|
1565
|
+
s.setColoring(this.#mesh(req.id), req.rule === null ? null : this.#rule(req.rule));
|
|
1566
|
+
b.colorings.push({
|
|
1567
|
+
id: req.id,
|
|
1568
|
+
rev: req.rev
|
|
1569
|
+
});
|
|
1570
|
+
return;
|
|
1571
|
+
case "values":
|
|
1572
|
+
this.#valuesFull ||= !this.#mirrorValues;
|
|
1573
|
+
this.#mirrorValues = true;
|
|
1574
|
+
return;
|
|
1575
|
+
case "field":
|
|
1576
|
+
this.#runField(req);
|
|
1577
|
+
return;
|
|
1578
|
+
case "section":
|
|
1579
|
+
this.#runSection(req);
|
|
1580
|
+
return;
|
|
1581
|
+
case "query":
|
|
1582
|
+
if (req.name === "fieldStatus" || req.name === "fieldNearest" || req.name === "fieldTargetStatus" || req.name === "debugDump") this.#settleFields();
|
|
1583
|
+
b.replies.push({
|
|
1584
|
+
qid: req.qid,
|
|
1585
|
+
ok: true,
|
|
1586
|
+
value: this.#query(req.name, req.args)
|
|
1587
|
+
});
|
|
1588
|
+
return;
|
|
1589
|
+
case "fetchFieldValues": {
|
|
1590
|
+
this.#settleFields();
|
|
1591
|
+
const values = s.fieldValues(this.#field(req.field)).slice();
|
|
1592
|
+
b.replies.push({
|
|
1593
|
+
qid: req.qid,
|
|
1594
|
+
ok: true,
|
|
1595
|
+
value: values
|
|
1596
|
+
});
|
|
1597
|
+
b.transfer.push(values.buffer);
|
|
1598
|
+
return;
|
|
1599
|
+
}
|
|
1600
|
+
default: throw invalid(`unknown request kind ${req.kind}`);
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
#runDrag(req) {
|
|
1604
|
+
const pose = () => {
|
|
1605
|
+
if (req.rotation === void 0 || req.translation === void 0) throw invalid("a drag move needs a rotation and a translation");
|
|
1606
|
+
return {
|
|
1607
|
+
rotation: req.rotation,
|
|
1608
|
+
translation: req.translation
|
|
1609
|
+
};
|
|
1610
|
+
};
|
|
1611
|
+
if (req.phase === "begin") {
|
|
1612
|
+
const session = this.#scene.drag(this.#mesh(req.id));
|
|
1613
|
+
this.#drag = {
|
|
1614
|
+
id: req.id,
|
|
1615
|
+
session
|
|
1616
|
+
};
|
|
1617
|
+
return;
|
|
1618
|
+
}
|
|
1619
|
+
this.#mesh(req.id);
|
|
1620
|
+
const drag = this.#drag;
|
|
1621
|
+
if (drag === void 0 || drag.id !== req.id || !drag.session.active) throw invalid("no active drag of this mesh");
|
|
1622
|
+
switch (req.phase) {
|
|
1623
|
+
case "move":
|
|
1624
|
+
drag.session.move(pose());
|
|
1625
|
+
return;
|
|
1626
|
+
case "end":
|
|
1627
|
+
this.#drag = void 0;
|
|
1628
|
+
if (req.rotation !== void 0) {
|
|
1629
|
+
try {
|
|
1630
|
+
drag.session.move(pose());
|
|
1631
|
+
} finally {
|
|
1632
|
+
drag.session.end();
|
|
1633
|
+
}
|
|
1634
|
+
return;
|
|
1635
|
+
}
|
|
1636
|
+
drag.session.end();
|
|
1637
|
+
return;
|
|
1638
|
+
case "cancel":
|
|
1639
|
+
this.#drag = void 0;
|
|
1640
|
+
drag.session.cancel();
|
|
1641
|
+
return;
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
#rule(rule) {
|
|
1645
|
+
return {
|
|
1646
|
+
...rule,
|
|
1647
|
+
field: this.#field(rule.field)
|
|
1648
|
+
};
|
|
1649
|
+
}
|
|
1650
|
+
/** A field removal (adds run in steps: {@link Engine.#addFieldInSteps}). */
|
|
1651
|
+
#runField(req) {
|
|
1652
|
+
if (this.#deferred.has(req.field)) {
|
|
1653
|
+
this.#dropField(req.field);
|
|
1654
|
+
return;
|
|
1655
|
+
}
|
|
1656
|
+
this.#scene.removeField(this.#field(req.field));
|
|
1657
|
+
this.#dropField(req.field);
|
|
1658
|
+
}
|
|
1659
|
+
/** Forgets a field the scene no longer has; its reverse id goes after packing. */
|
|
1660
|
+
#dropField(field) {
|
|
1661
|
+
const h = this.#fields.get(field);
|
|
1662
|
+
if (h !== void 0) this.#removedFields.push(h);
|
|
1663
|
+
this.#fields.delete(field);
|
|
1664
|
+
this.#deferred.delete(field);
|
|
1665
|
+
this.#fieldMeshes.delete(field);
|
|
1666
|
+
}
|
|
1667
|
+
#runSection(req) {
|
|
1668
|
+
const s = this.#scene;
|
|
1669
|
+
const desc = req.desc ?? {};
|
|
1670
|
+
switch (req.op) {
|
|
1671
|
+
case "add": {
|
|
1672
|
+
if (this.#sections.has(req.section)) throw invalid(`section client id ${req.section} is already in use`);
|
|
1673
|
+
const h = s.addSection({
|
|
1674
|
+
plane: desc.plane,
|
|
1675
|
+
meshes: this.#meshList(desc.meshes),
|
|
1676
|
+
fill: desc.fill
|
|
1677
|
+
});
|
|
1678
|
+
this.#sections.set(req.section, h);
|
|
1679
|
+
this.#sectionIds.set(h, req.section);
|
|
1680
|
+
this.#sectionMeshes.set(req.section, [...desc.meshes]);
|
|
1681
|
+
return;
|
|
1682
|
+
}
|
|
1683
|
+
case "set": {
|
|
1684
|
+
const h = this.#section(req.section);
|
|
1685
|
+
if (desc.plane !== void 0) s.setSectionPlane(h, desc.plane);
|
|
1686
|
+
if (desc.meshes !== void 0) {
|
|
1687
|
+
s.setSectionMeshes(h, this.#meshList(desc.meshes));
|
|
1688
|
+
this.#sectionMeshes.set(req.section, [...desc.meshes]);
|
|
1689
|
+
}
|
|
1690
|
+
if (desc.fill !== void 0) s.setSectionFill(h, desc.fill);
|
|
1691
|
+
return;
|
|
1692
|
+
}
|
|
1693
|
+
case "remove": {
|
|
1694
|
+
const h = this.#section(req.section);
|
|
1695
|
+
s.removeSection(h);
|
|
1696
|
+
this.#sections.delete(req.section);
|
|
1697
|
+
this.#sectionMeshes.delete(req.section);
|
|
1698
|
+
this.#removedSections.push(h);
|
|
1699
|
+
return;
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
#query(name, args) {
|
|
1704
|
+
const s = this.#scene;
|
|
1705
|
+
if (typeof args !== "object" || args === null) throw invalid("query args must be an object");
|
|
1706
|
+
switch (name) {
|
|
1707
|
+
case "raycast": {
|
|
1708
|
+
const a = args;
|
|
1709
|
+
const hit = s.raycast(a.origin, a.direction, a.options);
|
|
1710
|
+
return hit === null ? null : {
|
|
1711
|
+
...hit,
|
|
1712
|
+
mesh: this.#meshId(hit.mesh)
|
|
1713
|
+
};
|
|
1714
|
+
}
|
|
1715
|
+
case "closestPoint": {
|
|
1716
|
+
const a = args;
|
|
1717
|
+
const mesh = a.options?.mesh === void 0 ? void 0 : this.#mesh(a.options.mesh);
|
|
1718
|
+
const hit = s.closestPoint(a.point, {
|
|
1719
|
+
maxDistance: a.options?.maxDistance,
|
|
1720
|
+
mesh
|
|
1721
|
+
});
|
|
1722
|
+
return hit === null ? null : {
|
|
1723
|
+
...hit,
|
|
1724
|
+
mesh: this.#meshId(hit.mesh)
|
|
1725
|
+
};
|
|
1726
|
+
}
|
|
1727
|
+
case "meshDistance": {
|
|
1728
|
+
const a = args;
|
|
1729
|
+
return s.meshDistance(this.#mesh(a.a), this.#mesh(a.b), a.options);
|
|
1730
|
+
}
|
|
1731
|
+
case "intersects": {
|
|
1732
|
+
const a = args;
|
|
1733
|
+
return s.intersects(this.#mesh(a.a), this.#mesh(a.b));
|
|
1734
|
+
}
|
|
1735
|
+
case "findContacts": {
|
|
1736
|
+
const a = args;
|
|
1737
|
+
const pairs = a.pairs?.map(([x, y]) => [this.#mesh(x), this.#mesh(y)]);
|
|
1738
|
+
return s.findContacts({
|
|
1739
|
+
margin: a.margin,
|
|
1740
|
+
pairs
|
|
1741
|
+
}).map((c) => ({
|
|
1742
|
+
...c,
|
|
1743
|
+
a: this.#meshId(c.a),
|
|
1744
|
+
b: this.#meshId(c.b)
|
|
1745
|
+
}));
|
|
1746
|
+
}
|
|
1747
|
+
case "analyze": {
|
|
1748
|
+
const a = args;
|
|
1749
|
+
return s.analyze(this.#mesh(a.mesh), a.options);
|
|
1750
|
+
}
|
|
1751
|
+
case "fieldTargetStatus": {
|
|
1752
|
+
const a = args;
|
|
1753
|
+
return s.fieldTargetStatus(this.#field(a.field));
|
|
1754
|
+
}
|
|
1755
|
+
case "fieldNearest": {
|
|
1756
|
+
const a = args;
|
|
1757
|
+
return s.fieldNearest(this.#field(a.field));
|
|
1758
|
+
}
|
|
1759
|
+
case "fieldStatus": {
|
|
1760
|
+
const a = args;
|
|
1761
|
+
return s.fieldStatus(this.#field(a.field));
|
|
1762
|
+
}
|
|
1763
|
+
case "sectionGap": {
|
|
1764
|
+
const a = args;
|
|
1765
|
+
return s.sectionGap(this.#section(a.section), this.#mesh(a.a), this.#mesh(a.b));
|
|
1766
|
+
}
|
|
1767
|
+
case "debugDump": {
|
|
1768
|
+
if (!this.#debug) throw invalid(`unknown query ${name}`);
|
|
1769
|
+
const h = this.#mesh(args.mesh);
|
|
1770
|
+
const v = s.views(h);
|
|
1771
|
+
return {
|
|
1772
|
+
positions: v.positions().slice(),
|
|
1773
|
+
normals: v.normals()?.slice() ?? null,
|
|
1774
|
+
colors: v.colors()?.slice() ?? null,
|
|
1775
|
+
values: v.values?.()?.slice() ?? null,
|
|
1776
|
+
indices: v.indices().slice(),
|
|
1777
|
+
placement: s.placement(h),
|
|
1778
|
+
matrix4: Array.from(s.matrix4(h))
|
|
1779
|
+
};
|
|
1780
|
+
}
|
|
1781
|
+
default: throw invalid(`unknown query ${name}`);
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
/** Commits the frame and packs everything that changed. */
|
|
1785
|
+
#result(b) {
|
|
1786
|
+
const s = this.#scene;
|
|
1787
|
+
let frame = s.commitFrame();
|
|
1788
|
+
if (this.#valuesFull) {
|
|
1789
|
+
this.#valuesFull = false;
|
|
1790
|
+
frame = this.#withValues(frame);
|
|
1791
|
+
}
|
|
1792
|
+
const changes = [];
|
|
1793
|
+
const placements = [];
|
|
1794
|
+
const sections = [];
|
|
1795
|
+
for (const c of frame) {
|
|
1796
|
+
const id = this.#meshId(c.mesh);
|
|
1797
|
+
changes.push(this.#change(c, id, b));
|
|
1798
|
+
if (c.removed) continue;
|
|
1799
|
+
if (c.added || c.placementChanged) {
|
|
1800
|
+
const p = s.placement(c.mesh);
|
|
1801
|
+
placements.push({
|
|
1802
|
+
id,
|
|
1803
|
+
rotation: p.rotation,
|
|
1804
|
+
translation: p.translation,
|
|
1805
|
+
matrix4: Array.from(s.matrix4(c.mesh))
|
|
1806
|
+
});
|
|
1807
|
+
}
|
|
1808
|
+
for (const sh of c.sectionsChanged) {
|
|
1809
|
+
const section = this.#sectionIds.get(sh);
|
|
1810
|
+
const result = this.#sectionResult(sh, c.mesh);
|
|
1811
|
+
if (result !== null) {
|
|
1812
|
+
for (const contour of result.contours) b.transfer.push(contour.points.buffer);
|
|
1813
|
+
if (result.fill !== void 0) b.transfer.push(result.fill.positions.buffer, result.fill.indices.buffer);
|
|
1814
|
+
}
|
|
1815
|
+
sections.push({
|
|
1816
|
+
section,
|
|
1817
|
+
mesh: id,
|
|
1818
|
+
result
|
|
1819
|
+
});
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
for (const { section, mesh } of this.#goneEntries.splice(0)) sections.push({
|
|
1823
|
+
section,
|
|
1824
|
+
mesh,
|
|
1825
|
+
result: null
|
|
1826
|
+
});
|
|
1827
|
+
const history = {
|
|
1828
|
+
canUndo: s.canUndo(),
|
|
1829
|
+
canRedo: s.canRedo()
|
|
1830
|
+
};
|
|
1831
|
+
this.#packed.clear();
|
|
1832
|
+
for (const h of this.#removed.splice(0)) this.#meshIds.delete(h);
|
|
1833
|
+
for (const h of this.#removedFields.splice(0)) this.#fieldIds.delete(h);
|
|
1834
|
+
for (const h of this.#removedSections.splice(0)) this.#sectionIds.delete(h);
|
|
1835
|
+
return {
|
|
1836
|
+
rev: b.rev,
|
|
1837
|
+
changes,
|
|
1838
|
+
placements,
|
|
1839
|
+
sections,
|
|
1840
|
+
history,
|
|
1841
|
+
status: b.status,
|
|
1842
|
+
replies: b.replies,
|
|
1843
|
+
colorings: b.colorings
|
|
1844
|
+
};
|
|
1845
|
+
}
|
|
1846
|
+
/**
|
|
1847
|
+
* `frame` with every coloured mesh's colours "all" (a record added where it
|
|
1848
|
+
* has none), so the values mirror just turned on starts whole.
|
|
1849
|
+
*/
|
|
1850
|
+
#withValues(frame) {
|
|
1851
|
+
const out = [...frame];
|
|
1852
|
+
for (const h of this.#meshes.values()) {
|
|
1853
|
+
if ((this.#scene.views(h).values?.() ?? null) === null) continue;
|
|
1854
|
+
const at = out.findIndex((c) => c.mesh === h);
|
|
1855
|
+
if (at === -1) out.push({
|
|
1856
|
+
mesh: h,
|
|
1857
|
+
added: false,
|
|
1858
|
+
removed: false,
|
|
1859
|
+
placementChanged: false,
|
|
1860
|
+
capacityChanged: false,
|
|
1861
|
+
positions: [],
|
|
1862
|
+
normals: [],
|
|
1863
|
+
colors: "all",
|
|
1864
|
+
indices: [],
|
|
1865
|
+
fieldsChanged: [],
|
|
1866
|
+
sectionsChanged: []
|
|
1867
|
+
});
|
|
1868
|
+
else if (!out[at].removed) out[at] = {
|
|
1869
|
+
...out[at],
|
|
1870
|
+
colors: "all"
|
|
1871
|
+
};
|
|
1872
|
+
}
|
|
1873
|
+
return out;
|
|
1874
|
+
}
|
|
1875
|
+
/** The section's result for a mesh, or `null` when the section or the entry is gone. */
|
|
1876
|
+
#sectionResult(section, mesh) {
|
|
1877
|
+
try {
|
|
1878
|
+
return this.#scene.section(section, mesh);
|
|
1879
|
+
} catch (e) {
|
|
1880
|
+
if (e instanceof FastMeshError && (e.code === "INVALID_ARGUMENT" || e.code === "UNKNOWN_MESH" || e.code === "UNKNOWN_SECTION")) return null;
|
|
1881
|
+
throw e;
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
#change(c, id, b) {
|
|
1885
|
+
const wire = {
|
|
1886
|
+
id,
|
|
1887
|
+
added: c.added,
|
|
1888
|
+
removed: c.removed,
|
|
1889
|
+
placementChanged: c.placementChanged,
|
|
1890
|
+
capacityChanged: c.capacityChanged,
|
|
1891
|
+
positions: c.positions,
|
|
1892
|
+
normals: c.normals,
|
|
1893
|
+
colors: c.colors,
|
|
1894
|
+
indices: c.indices,
|
|
1895
|
+
fields: c.fieldsChanged.map((f) => this.#fieldIds.get(f)),
|
|
1896
|
+
sections: c.sectionsChanged.map((x) => this.#sectionIds.get(x)),
|
|
1897
|
+
vertexSlots: 0,
|
|
1898
|
+
triangleSlots: 0,
|
|
1899
|
+
bytes: {
|
|
1900
|
+
positions: null,
|
|
1901
|
+
normals: null,
|
|
1902
|
+
colors: null,
|
|
1903
|
+
values: null,
|
|
1904
|
+
indices: null
|
|
1905
|
+
}
|
|
1906
|
+
};
|
|
1907
|
+
if (c.removed) return wire;
|
|
1908
|
+
wire.vertexSlots = this.#scene.vertexSlots(c.mesh);
|
|
1909
|
+
wire.triangleSlots = this.#scene.triangleSlots(c.mesh);
|
|
1910
|
+
let packed = c.added ? this.#packed.get(c.mesh) : void 0;
|
|
1911
|
+
if (packed !== void 0 && packed.stamp !== this.#meshAdds.stamp(c.mesh)) packed = void 0;
|
|
1912
|
+
const views = this.#scene.views(c.mesh);
|
|
1913
|
+
for (const name of Object.keys(STRIDE)) {
|
|
1914
|
+
const view = name === "values" && !this.#mirrorValues ? null : views[name]?.() ?? null;
|
|
1915
|
+
if (view !== null) {
|
|
1916
|
+
const ranges = rangesOf(c, name);
|
|
1917
|
+
const copy = name === "positions" || name === "normals" || name === "indices" ? packed?.[name] : void 0;
|
|
1918
|
+
const bytes = ranges === "all" && copy != null && copy.byteLength === view.byteLength ? copy : copyRanges(view, ranges, STRIDE[name]);
|
|
1919
|
+
wire.bytes[name] = bytes;
|
|
1920
|
+
b.transfer.push(bytes);
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
return wire;
|
|
1924
|
+
}
|
|
1925
|
+
};
|
|
1926
|
+
//#endregion
|
|
1927
|
+
export { YIELD_MS as a, loadEngine as c, STEP_POINTS as i, startEngine as l, BACKGROUND_ADD_TRIANGLES as n, runEngine as o, STALE_GUARD_MS as r, serveEngine as s, ADD_STEP_WORK as t, probeSharedGrowth as u };
|