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