fast-mesh-wasm 0.6.0 → 0.8.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 (51) hide show
  1. package/README.md +43 -3
  2. package/dist/client-CJWOKQMM.d.ts +664 -0
  3. package/dist/{client-BrTp2eMp.js → client-DQADH6KL.js} +1893 -109
  4. package/dist/{engine-DjdY3GxK.js → engine-D2124Vml.js} +995 -52
  5. package/dist/io.d.ts +205 -2
  6. package/dist/io.js +3063 -9
  7. package/dist/{mesh-DIWD2F5-.js → mesh-BtWBMRMO.js} +2 -1
  8. package/dist/{mesh-BsqIofgT.d.ts → mesh-DTm2Fnqa.d.ts} +3 -2
  9. package/dist/node.d.ts +4 -2
  10. package/dist/node.js +4 -3
  11. package/dist/primitives-6T0eQiSm.d.ts +157 -0
  12. package/dist/primitives-wasm-C30Bk4ut.js +3827 -0
  13. package/dist/primitives-wasm-d9m2vikb.d.ts +43 -0
  14. package/dist/{protocol-Ci9LLiwO.js → protocol-Bvjmvlb3.js} +38 -3
  15. package/dist/protocol-Da0kmXuF.d.ts +743 -0
  16. package/dist/r3f.d.ts +3 -3
  17. package/dist/r3f.js +3 -3
  18. package/dist/{react-DzrtrzZy.js → react-DIuy5dyR.js} +12 -3
  19. package/dist/react.d.ts +6 -3
  20. package/dist/react.js +1 -1
  21. package/dist/scene-like-Bx7lZKif.d.ts +4808 -0
  22. package/dist/{store-DIQmxF_s.js → store-BxzcXy9y.js} +431 -65
  23. package/dist/{store-BfC6kkf5.d.ts → store-LM3iU8E4.d.ts} +110 -11
  24. package/dist/store.d.ts +3 -3
  25. package/dist/store.js +1 -1
  26. package/dist/three.d.ts +13 -11
  27. package/dist/three.js +63 -18
  28. package/dist/views-DPMbo0Sl.js +3147 -0
  29. package/dist/wasm/fast_mesh_wasm.d.ts +548 -8
  30. package/dist/wasm/fast_mesh_wasm.js +2100 -89
  31. package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
  32. package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +95 -0
  33. package/dist/wasm-threads/fast_mesh_wasm.d.ts +548 -8
  34. package/dist/wasm-threads/fast_mesh_wasm.js +2101 -90
  35. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm +0 -0
  36. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm.d.ts +95 -0
  37. package/dist/wave6-wasm-Bt4vTlKz.js +146 -0
  38. package/dist/web.d.ts +4 -2
  39. package/dist/web.js +4 -3
  40. package/dist/worker-engine.d.ts +20 -2
  41. package/dist/worker-engine.js +1 -1
  42. package/dist/worker-entry.js +1 -1
  43. package/dist/worker.d.ts +1 -1
  44. package/dist/worker.js +1 -1
  45. package/package.json +1 -1
  46. package/dist/api-4kz45-Mq.js +0 -63
  47. package/dist/client-Ds09vLkN.d.ts +0 -336
  48. package/dist/protocol-Cb23HelE.d.ts +0 -327
  49. package/dist/scene-D0HNTwoo.js +0 -2216
  50. package/dist/scene-like-CADk1vfb.d.ts +0 -1755
  51. package/dist/views-B00kdV0R.js +0 -214
@@ -1,6 +1,6 @@
1
- import { c as SectionHandle, d as checkRegisterOptions, i as copyRule, l as rotationMatrix, o as FieldHandle, r as checkInteractionPoints, s as MeshHandle, t as ViewGuard, u as targetsOf } from "./views-B00kdV0R.js";
1
+ import { $ as checkU32Arg, $t as normalizeBooleanArgs, A as checkLatticeOptions, At as normalizeSelectSmallIslandsArgs, Cn as checkHeightfieldPlacement, Ct as normalizeHollowArgs, D as checkRegisterOptions, Dn as encodeHeightMapOptions, Dt as normalizeReconstructArgs, E as wrapMeshList, En as encodeHeightMapFrame, Et as normalizePlacementInputArgs, Fn as rotationMatrix, Ft as normalizeXpbdArgs, H as extrudeFacesArgs, I as hullMeshList, In as targetsOf, J as DEFAULT_COLLISION_RULE, Jt as checkSurfacePathOptions, L as hullNormals, Mn as FieldHandle, Mt as normalizeSliceContoursArgs, Nn as MeshHandle, Nt as normalizeU32Selection, O as DEFAULT_LATTICE_MAX_VOXELS, Ot as normalizeScreenSelectArgs, Pn as SectionHandle, Pt as normalizeVertexMaskSelectArgs, Qt as isBrushSculptOp, R as hullPointsBuffer, S as checkWrapOptions, Sn as checkHeightfield, St as normalizeGrowShrinkArgs, Tt as normalizePlaceMeshArgs, U as checkDelaunayFlipOptions, V as extrudeBaseArgs, W as checkDenoiseOptions, X as checkBooleanArg, Yt as checkU32Int, _ as createDeformDomain, _t as normalizeBuildFfdLatticeArgs, an as normalizeGeodesicOptions, bt as normalizeFfdArgs, c as EntryBook, cn as normalizePartialBridgeOptions, dn as normalizeSourceVertices, en as normalizeCsgBatchArgs, et as cloudBuffer, f as tellPermanent, fn as normalizeSurfacePathTarget, g as createInspectDomain, gn as throwIfAborted, gt as normalizeArapArgs, h as createRemeshDomain, hn as normalizeVec3, ht as normalizeAlignToPrimitiveArgs, i as copyRule, in as normalizeFillHolesContinuityOptions, jn as isHeightMapFrame, jt as normalizeSliceContourStackArgs, k as DEFAULT_LATTICE_PREVIEW_VOXELS, kn as heightMapMeshList, kt as normalizeSelectInSphereArgs, l as checkHistoryBudget, ln as normalizeQualityArgs, m as createRepairDomain, mn as normalizeU32List, nn as normalizeDyntopoCenterRadius, on as normalizeLandmarkPairs, p as createSculptDomain, pn as normalizeTrimCurveArgs, r as checkInteractionPoints, rn as normalizeDyntopoOptions, sn as normalizeOverhangOptions, t as ViewGuard, tn as normalizeDeviationOptions, tt as cloudOrigin, u as checkHistoryEntry, un as normalizeRegistrationOptions, v as createBooleanDomain, vt as normalizeCollisionRule, wt as normalizeKelvinletArgs, xt as normalizeFitPrimitiveArgs, y as createAlignDomain, yn as encodePrimitive, yt as normalizeDrainHoleArgs } from "./views-DPMbo0Sl.js";
2
2
  import { o as reportListenerError, t as FastMeshError } from "./core-4OcWKu3r.js";
3
- import { a as supersedes, n as isLastWins, r as keyOf } from "./protocol-Ci9LLiwO.js";
3
+ import { a as supersedes, n as isLastWins, r as keyOf } from "./protocol-Bvjmvlb3.js";
4
4
  // src/worker/client.ts
5
5
  /**
6
6
  * Starts a Worker running the scene engine and resolves once it is ready.
@@ -11,6 +11,7 @@ async function createWorkerScene(options = {}) {
11
11
  const threads = options.threads === void 0 ? void 0 : Math.min(Math.max(options.threads, 1), 64);
12
12
  const background = options.backgroundAddTriangles;
13
13
  if (background !== void 0 && (typeof background !== "number" || Number.isNaN(background) || background < 0)) throw invalid(`backgroundAddTriangles must be a number, 0 or more (got ${String(background)})`);
14
+ const budget = options.historyBudget === void 0 ? void 0 : checkHistoryBudget(options.historyBudget);
14
15
  const make = () => options.createWorker?.() ?? (options.workerUrl === void 0 ? new Worker(new URL("./worker-entry.js", import.meta.url), { type: "module" }) : new Worker(options.workerUrl, { type: "module" }));
15
16
  const dev = import.meta.env?.DEV === true;
16
17
  const debug = (options.debug ?? false) || dev;
@@ -21,7 +22,8 @@ async function createWorkerScene(options = {}) {
21
22
  kind: "init",
22
23
  threads: skipped ? 1 : threads,
23
24
  debug,
24
- ...background === void 0 ? {} : { backgroundAddTriangles: background }
25
+ ...background === void 0 ? {} : { backgroundAddTriangles: background },
26
+ ...budget === void 0 ? {} : { historyBudget: budget }
25
27
  }
26
28
  });
27
29
  try {
@@ -75,7 +77,7 @@ function transferOf(batch) {
75
77
  for (const req of batch) if (req.kind === "addMesh") {
76
78
  transfer.push(req.positions, req.indices);
77
79
  if (req.uvs !== void 0) transfer.push(req.uvs);
78
- }
80
+ } else if (req.kind === "addHeightfield") transfer.push(req.field.heights.buffer);
79
81
  return transfer;
80
82
  }
81
83
  /** The most failed requests kept for `restart()`. */
@@ -203,7 +205,7 @@ function sortOf(req) {
203
205
  ...base,
204
206
  kind: "removal"
205
207
  };
206
- if (req.kind === "setPlacement" || req.kind === "drag" || req.kind === "coloring" || req.kind === "field" || req.kind === "section") return {
208
+ if (req.kind === "setPlacement" || req.kind === "drag" || req.kind === "coloring" || req.kind === "field" || req.kind === "section" || req.kind === "historyBudget") return {
207
209
  ...base,
208
210
  kind: "declarative",
209
211
  covers: coversOf(req)
@@ -247,6 +249,12 @@ const THREADS_UNAVAILABLE = "fast-mesh-wasm: the multithreaded engine cannot run
247
249
  let addFieldKeyedOf;
248
250
  /** Set by `WorkerScene`'s static block: the internal {@link watchStatusKeys}. */
249
251
  let watchStatusKeysOf;
252
+ /** Set by `WorkerScene`'s static block: the internal {@link fieldTargets}. */
253
+ let fieldTargetsOf;
254
+ /** Set by `WorkerScene`'s static block: the internal {@link sectionMeshes}. */
255
+ let sectionMeshesOf;
256
+ /** Set by `WorkerScene`'s static block: the internal {@link presenceVersion}. */
257
+ let presenceVersionOf;
250
258
  /**
251
259
  * A scene whose engine runs in a Worker, from {@link createWorkerScene}. It
252
260
  * mirrors `Scene` (always `"eager"`) with these differences:
@@ -337,6 +345,7 @@ var WorkerScene = class WorkerScene {
337
345
  #optimistic = /* @__PURE__ */ new Set();
338
346
  #listeners = /* @__PURE__ */ new Set();
339
347
  #statusListeners = /* @__PURE__ */ new Set();
348
+ #permanentListeners = /* @__PURE__ */ new Set();
340
349
  #status = /* @__PURE__ */ new Map();
341
350
  /** Called with each key whose status is set or forgotten, at once (see {@link watchStatusKeys}). */
342
351
  #statusSinks = /* @__PURE__ */ new Set();
@@ -347,9 +356,15 @@ var WorkerScene = class WorkerScene {
347
356
  canUndo: false,
348
357
  canRedo: false
349
358
  };
359
+ #historyBytes = 0;
360
+ /** The application's entries in the history, or on their way to it. */
361
+ #entries = new EntryBook();
362
+ /** See {@link presenceVersion}. */
363
+ #presenceVersion = 0;
350
364
  /** The values mirror is on (a `values()` read asked for it). */
351
365
  #values = false;
352
366
  #drag;
367
+ #stepDepth = 0;
353
368
  #poison;
354
369
  #terminated = false;
355
370
  /** The current Worker's start. */
@@ -377,6 +392,119 @@ var WorkerScene = class WorkerScene {
377
392
  #warned = false;
378
393
  /** The current Worker's crash channel (see `#watch`), while it may run threaded. */
379
394
  #crashWatch;
395
+ /** Default collision response rule persisted across Worker restarts. */
396
+ #defaultCollisionRule = { ...DEFAULT_COLLISION_RULE };
397
+ /**
398
+ * Explicit per-pair collision rules keyed canonically by sorted ClientId
399
+ * pair; those of a parked mesh wait here for its way back.
400
+ */
401
+ #collisionRules = /* @__PURE__ */ new Map();
402
+ /**
403
+ * Callable async repair domain (`worker.repair(mesh, op)` and `worker.repair.<method>(...)`).
404
+ */
405
+ repair = createRepairDomain({
406
+ repair: ((mesh, op) => this.#runRepair(mesh, op)),
407
+ analyze: (mesh, options) => this.analyze(mesh, options),
408
+ join: (target, source, options) => this.join(target, source, options),
409
+ fillHoleContinuity: (mesh, loopIndex, options) => this.fillHoleContinuity(mesh, loopIndex, options),
410
+ fillAllHolesContinuity: (mesh, options) => this.fillAllHolesContinuity(mesh, options),
411
+ bridgePartialArcs: (mesh, loopA, loopB, options) => this.bridgePartialArcs(mesh, loopA, loopB, options),
412
+ selectFacesScreen: (mesh, shape, options) => this.selectFacesScreen(mesh, shape, options),
413
+ selectFacesInSphere: (mesh, center, radius, normalCone) => this.selectFacesInSphere(mesh, center, radius, normalCone),
414
+ selectByCreaseAngle: (mesh, seedTri, maxDihedralRad) => this.selectByCreaseAngle(mesh, seedTri, maxDihedralRad),
415
+ selectConnectedShell: (mesh, seedTri) => this.selectConnectedShell(mesh, seedTri),
416
+ selectSmallFaceIslands: (mesh, maxFaceCount, maxArea) => this.selectSmallFaceIslands(mesh, maxFaceCount, maxArea),
417
+ growFaceSelection: (mesh, selectedTris, rings, adjacency) => this.growFaceSelection(mesh, selectedTris, rings, adjacency),
418
+ shrinkFaceSelection: (mesh, selectedTris, rings, adjacency) => this.shrinkFaceSelection(mesh, selectedTris, rings, adjacency),
419
+ fillSelectionHoles: (mesh, selectedTris, maxHoleTris) => this.fillSelectionHoles(mesh, selectedTris, maxHoleTris),
420
+ smoothSelectionBoundary: (mesh, selectedTris, iterations) => this.smoothSelectionBoundary(mesh, selectedTris, iterations),
421
+ faceSelectionToVertexMask: (mesh, selectedTris) => this.faceSelectionToVertexMask(mesh, selectedTris),
422
+ vertexMaskToFaceSelection: (mesh, mask, threshold, requireAllVertices) => this.vertexMaskToFaceSelection(mesh, mask, threshold, requireAllVertices),
423
+ deleteSelectedFaces: (mesh, selectedTris) => this.deleteSelectedFaces(mesh, selectedTris),
424
+ extractSelectedFaces: (mesh, selectedTris, options) => this.extractSelectedFaces(mesh, selectedTris, options),
425
+ splitSelectedFaces: (mesh, selectedTris, options) => this.splitSelectedFaces(mesh, selectedTris, options)
426
+ });
427
+ /**
428
+ * Callable async sculpt domain (`worker.sculpt(mesh, op)` and `worker.sculpt.<method>(...)`).
429
+ */
430
+ sculpt = createSculptDomain({
431
+ sculpt: ((mesh, op) => this.#runRepair(mesh, op)),
432
+ verticesInSphere: (mesh, center, radius) => this.verticesInSphere(mesh, center, radius),
433
+ beginStep: () => this.beginStep(),
434
+ endStep: () => this.endStep(),
435
+ cancelStep: () => this.cancelStep(),
436
+ applyDyntopo: (mesh, center, radius, options, pinned) => this.applyDyntopo(mesh, center, radius, options, pinned),
437
+ dyntopoDab: (mesh, dab, options, protection) => this.dyntopoDab(mesh, dab, options, protection)
438
+ });
439
+ /** Async remesh, simplification, subdivision, and volumetric reconstruction domain. */
440
+ remesh = createRemeshDomain({ repair: ((mesh, op) => this.#runRepair(mesh, op)) });
441
+ /** Callable async boolean, CSG batch, cut, curve-trim, offset, and shell domain. */
442
+ boolean = createBooleanDomain({
443
+ isAsync: true,
444
+ repair: ((mesh, op) => this.#runRepair(mesh, op)),
445
+ boolean: (target, source, op, options) => this.#runBoolean(target, source, op, options),
446
+ booleanBatch: (meshesOrTree, treeOrOptions, maybeOptions) => Array.isArray(meshesOrTree) ? this.booleanBatch(meshesOrTree, treeOrOptions, maybeOptions) : this.booleanBatch(meshesOrTree, treeOrOptions),
447
+ cutByPlane: (mesh, plane, options) => this.cutByPlane(mesh, plane, options),
448
+ trimByCurve: (mesh, optionsOrCurve, maybeOptions) => Array.isArray(optionsOrCurve) ? this.trimByCurve(mesh, optionsOrCurve, maybeOptions) : this.trimByCurve(mesh, optionsOrCurve),
449
+ hollowMesh: (mesh, options) => this.hollowMesh(mesh, options),
450
+ punchDrainHole: (mesh, options) => this.punchDrainHole(mesh, options),
451
+ placeMesh: (target, stamp, options) => this.placeMesh(target, stamp, options)
452
+ });
453
+ /** Async surface deformation and vertex-protection domain. */
454
+ deform = createDeformDomain({
455
+ sculpt: ((mesh, op) => this.#runRepair(mesh, op)),
456
+ buildFfdLattice: (mesh, dims, basis, padding) => this.buildFfdLattice(mesh, dims, basis, padding),
457
+ applyFfd: (mesh, options) => this.applyFfd(mesh, options),
458
+ applyArap: (mesh, options) => this.applyArap(mesh, options),
459
+ applyKelvinlet: (mesh, options) => this.applyKelvinlet(mesh, options),
460
+ applyXpbd: (mesh, options) => this.applyXpbd(mesh, options)
461
+ });
462
+ /** Async defect analysis, printability/quality inspection, metrology, geodesics, queries, fields, and section domain. */
463
+ inspect = createInspectDomain({
464
+ analyze: (mesh, options) => this.analyze(mesh, options),
465
+ measure: (mesh) => this.measure(mesh),
466
+ bounds: (mesh) => this.bounds(mesh),
467
+ raycast: (origin, direction, options) => this.raycast(origin, direction, options),
468
+ closestPoint: (point, options) => this.closestPoint(point, options),
469
+ meshDistance: (a, b, options) => this.meshDistance(a, b, options),
470
+ intersects: (a, b) => this.intersects(a, b),
471
+ selfIntersectingTriangles: (mesh) => this.selfIntersectingTriangles(mesh),
472
+ findContacts: (options) => this.findContacts(options),
473
+ overhangs: (mesh, options) => this.overhangs(mesh, options),
474
+ triangleQuality: (mesh, metricOrOptions, sliverThreshold) => this.triangleQuality(mesh, metricOrOptions, sliverThreshold),
475
+ meshDeviation: (source, target, options) => this.meshDeviation(source, target, options),
476
+ geodesicDistances: (mesh, sources, options) => this.geodesicDistances(mesh, sources, options),
477
+ releaseGeodesics: () => this.releaseGeodesics(),
478
+ shortestSurfacePath: (mesh, sources, targetVertex, options) => this.shortestSurfacePath(mesh, sources, targetVertex, options),
479
+ addDistanceField: (desc) => this.addDistanceField(desc),
480
+ removeField: (field) => this.removeField(field),
481
+ fieldValues: (field) => this.fetchFieldValues(field),
482
+ fieldNearest: (field) => this.fetchFieldNearest(field),
483
+ fieldStatus: (field) => this.fieldStatus(field),
484
+ fieldTargetStatus: (field) => this.fieldTargetStatus(field),
485
+ setColoring: (mesh, rule) => this.setColoring(mesh, rule),
486
+ coloring: (mesh) => this.coloring(mesh),
487
+ addSection: (desc) => this.addSection(desc),
488
+ setSectionPlane: (section, plane) => this.setSectionPlane(section, plane),
489
+ sectionPlane: (section) => this.sectionPlane(section),
490
+ setSectionMeshes: (section, meshes) => this.setSectionMeshes(section, meshes),
491
+ setSectionFill: (section, fill) => this.setSectionFill(section, fill),
492
+ removeSection: (section) => this.removeSection(section),
493
+ section: (section, mesh) => this.section(section, mesh),
494
+ sectionGap: (section, a, b) => this.sectionGap(section, a, b),
495
+ fitPrimitive: (mesh, options) => this.fitPrimitive(mesh, options),
496
+ alignToFittedPrimitive: (mesh, primitive, targetAxis, targetOrigin) => this.alignToFittedPrimitive(mesh, primitive, targetAxis, targetOrigin),
497
+ sliceContours: (mesh, origin, normal) => this.sliceContours(mesh, origin, normal),
498
+ sliceContourStack: (mesh, origin, normal, spacing, count) => this.sliceContourStack(mesh, origin, normal, spacing, count),
499
+ reconstructPointCloud: (cloud, options) => this.reconstructPointCloud(cloud, options)
500
+ });
501
+ /** Async rigid registration, multi-stage alignment, landmark SVD, and symmetry domain. */
502
+ align = createAlignDomain({
503
+ register: (moving, fixed, options) => this.register(moving, fixed, options),
504
+ alignByLandmarks: (moving, fixed, pairs, allowScaling) => this.alignByLandmarks(moving, fixed, pairs, allowScaling),
505
+ registerMultistage: (moving, fixed, options) => this.registerMultistage(moving, fixed, options),
506
+ detectSymmetryPlane: (mesh) => this.detectSymmetryPlane(mesh)
507
+ });
380
508
  /** Use {@link createWorkerScene}. */
381
509
  constructor(make, options) {
382
510
  this.#make = make;
@@ -565,27 +693,58 @@ var WorkerScene = class WorkerScene {
565
693
  }
566
694
  return req.rev;
567
695
  }
568
- /** Queues a request with a reply and sends soon; resolves with `map(value)`. */
569
- #ask(make, map) {
696
+ /**
697
+ * Queues a request with a reply and sends soon; resolves with `map(value)`.
698
+ * With a `signal`, an abort rejects at once with its reason and cancels
699
+ * the query (see {@link WorkerScene.#cancel}).
700
+ */
701
+ #ask(make, map, signal) {
570
702
  return new Promise((resolve, reject) => {
571
703
  this.#alive();
572
704
  const qid = ++this.#qid;
573
705
  const req = make(++this.#rev, qid);
706
+ throwIfAborted(signal);
707
+ const abort = () => this.#cancel(qid, signal?.reason);
708
+ signal?.addEventListener("abort", abort, { once: true });
574
709
  this.#replies.set(qid, {
575
710
  resolve: (v) => {
711
+ signal?.removeEventListener("abort", abort);
576
712
  try {
577
713
  resolve(map(v));
578
714
  } catch (e) {
579
715
  reject(e);
580
716
  }
581
717
  },
582
- reject
718
+ reject: (e) => {
719
+ signal?.removeEventListener("abort", abort);
720
+ reject(e);
721
+ }
583
722
  });
584
723
  this.#push(req);
585
724
  this.#scheduleFlush();
586
725
  });
587
726
  }
588
727
  /**
728
+ * Cancels a query: rejects its promise with `reason`, and takes it out of
729
+ * the requests not sent yet, or else tells the Worker to drop it.
730
+ */
731
+ #cancel(qid, reason) {
732
+ const pending = this.#replies.get(qid);
733
+ if (pending === void 0) return;
734
+ this.#replies.delete(qid);
735
+ const at = this.#queue.findIndex((req) => req.qid === qid);
736
+ if (at >= 0) this.#queue.splice(at, 1);
737
+ else if (!this.#terminated && this.#poison === void 0) {
738
+ this.#push({
739
+ kind: "cancel",
740
+ rev: ++this.#rev,
741
+ qid
742
+ });
743
+ this.#scheduleFlush();
744
+ }
745
+ pending.reject(reason);
746
+ }
747
+ /**
589
748
  * Makes sure a queued promise call gets sent: with a frame loop, by the
590
749
  * next `commitFrame()` or else the fallback timer, so pointer-rate queries
591
750
  * never send the frame's moves early; without one, on a microtask.
@@ -607,14 +766,14 @@ var WorkerScene = class WorkerScene {
607
766
  }
608
767
  }
609
768
  /** A query by name, with its reply mapped. */
610
- #query(name, args, map) {
769
+ #query(name, args, map, signal) {
611
770
  return this.#ask((rev, qid) => ({
612
771
  kind: "query",
613
772
  rev,
614
773
  qid,
615
774
  name,
616
775
  args: args()
617
- }), (v) => map(v));
776
+ }), (v) => map(v), signal);
618
777
  }
619
778
  /**
620
779
  * Sends the queued requests as one batch, coalesced; returns it when it
@@ -633,6 +792,7 @@ var WorkerScene = class WorkerScene {
633
792
  }
634
793
  const transfer = [];
635
794
  for (const req of batch) if (req.kind === "addMesh") transfer.push(req.positions, req.indices);
795
+ else if (req.kind === "addHeightfield") transfer.push(req.field.heights.buffer);
636
796
  try {
637
797
  if (this.#handoff !== void 0) {
638
798
  const held = structuredClone(batch, { transfer });
@@ -658,6 +818,7 @@ var WorkerScene = class WorkerScene {
658
818
  #fail(batch, error, log = true) {
659
819
  for (const req of batch) {
660
820
  if (log) this.#logFailed(req);
821
+ if (req.kind === "entry") this.#entries.tell(req.id, "drop");
661
822
  const key = keyOf(req);
662
823
  if (key !== void 0 && this.#latest.get(key) === req.rev) this.#setStatus(key, {
663
824
  status: "error",
@@ -691,6 +852,7 @@ var WorkerScene = class WorkerScene {
691
852
  this.#drag.active = false;
692
853
  this.#drag = void 0;
693
854
  }
855
+ this.#stepDepth = 0;
694
856
  for (const st of this.#meshes.values()) {
695
857
  if (st.local !== void 0 && !samePose(st.local, st.pose)) this.#optimistic.add(st);
696
858
  st.local = void 0;
@@ -712,6 +874,7 @@ var WorkerScene = class WorkerScene {
712
874
  this.#batchDone.delete(batch);
713
875
  }
714
876
  this.#releaseHolds();
877
+ this.#entries.dropAll();
715
878
  this.#statusChanged();
716
879
  }
717
880
  #receive(msg) {
@@ -757,6 +920,7 @@ var WorkerScene = class WorkerScene {
757
920
  });
758
921
  for (const req of batch) this.#logFailed(req);
759
922
  this.#releaseHolds();
923
+ this.#entries.dropAll();
760
924
  this.#applyStatus(r);
761
925
  this.#applyReplies(r);
762
926
  for (const req of batch) {
@@ -776,15 +940,23 @@ var WorkerScene = class WorkerScene {
776
940
  for (const k of st.pendingRules.keys()) if (k <= rev) st.pendingRules.delete(k);
777
941
  }
778
942
  for (const c of r.changes) this.#applyChange(c);
943
+ const permanent = this.#permanentSteps(r);
944
+ this.#applyPresence(r);
779
945
  for (const st of this.#meshes.values()) if (st.colors === null) st.shown = null;
780
946
  for (const p of r.placements) {
781
947
  const st = this.#meshes.get(p.id);
782
- if (st !== void 0) st.pose = {
783
- rotation: p.rotation,
784
- translation: p.translation,
785
- scale: p.scale,
786
- matrix4: Float64Array.from(p.matrix4)
787
- };
948
+ if (st !== void 0) {
949
+ st.pose = {
950
+ rotation: p.rotation,
951
+ translation: p.translation,
952
+ scale: p.scale,
953
+ matrix4: Float64Array.from(p.matrix4)
954
+ };
955
+ if (p.authoritative && st.local !== void 0 && st.localUntil === Number.POSITIVE_INFINITY && r.rev >= (this.#latest.get(`placement:${st.id}`) ?? 0) && !samePose(st.local, st.pose)) {
956
+ st.local = st.pose;
957
+ this.#optimistic.add(st);
958
+ }
959
+ }
788
960
  }
789
961
  for (const s of r.sections) {
790
962
  const st = this.#sections.get(s.section);
@@ -804,9 +976,42 @@ var WorkerScene = class WorkerScene {
804
976
  this.#history = { ...r.history };
805
977
  this.#statusChanged();
806
978
  }
979
+ this.#historyBytes = r.historyBytes ?? 0;
807
980
  this.#applyStatus(r);
981
+ this.#applyEntries(r);
982
+ tellPermanent(this.#permanentListeners, permanent);
808
983
  this.#applyReplies(r);
809
984
  }
985
+ /**
986
+ * Calls the application's entries the result undid, redid or dropped. An
987
+ * entry recorded here since the request that undid (or redid) them was made
988
+ * comes after it in the history, but its change is made already: it steps
989
+ * back first and forward again after, so that the callbacks run in the
990
+ * history's order.
991
+ */
992
+ #applyEntries(r) {
993
+ const events = r.entries ?? [];
994
+ for (let k = 0; k < events.length;) {
995
+ const { id, what, rev } = events[k];
996
+ if (what === "drop") {
997
+ this.#entries.tell(id, what);
998
+ k++;
999
+ continue;
1000
+ }
1001
+ const later = this.#entries.after(rev);
1002
+ for (const l of [...later].reverse()) this.#entries.tell(l, "undo");
1003
+ for (; k < events.length && events[k].rev === rev && events[k].what !== "drop"; k++) this.#entries.tell(events[k].id, events[k].what);
1004
+ for (const l of later) this.#entries.tell(l, "redo");
1005
+ }
1006
+ }
1007
+ #permanentSteps(r) {
1008
+ const handles = (ids) => ids.flatMap((id) => this.#meshes.get(id)?.handle ?? []);
1009
+ return (r.permanent ?? []).map((p) => ({
1010
+ ...p,
1011
+ meshes: handles(p.meshes),
1012
+ gone: handles(p.gone)
1013
+ }));
1014
+ }
810
1015
  #applyStatus(r) {
811
1016
  for (const s of r.status) {
812
1017
  const latest = this.#latest.get(s.key) ?? 0;
@@ -837,18 +1042,27 @@ var WorkerScene = class WorkerScene {
837
1042
  if (st === void 0) return;
838
1043
  if (c.removed) {
839
1044
  st.live = false;
1045
+ if (c.restorable === true) st.parkedRule = st.shown;
840
1046
  this.#clearMirrors(st);
841
1047
  } else {
842
1048
  if (c.added) {
843
1049
  st.live = true;
844
1050
  st.add = void 0;
1051
+ st.shown ??= st.parkedRule;
1052
+ st.parkedRule = null;
1053
+ if (c.origin !== void 0) {
1054
+ st.origin = [...c.origin];
1055
+ st.pose = poseOf(st.pose.rotation, st.pose.translation, st.origin, st.pose.scale);
1056
+ }
845
1057
  }
846
1058
  for (const name of BUFFERS) this.#applyBuffer(st, name, c);
1059
+ if (c.bounds !== void 0) st.bounds = cloneBounds(c.bounds);
847
1060
  }
848
1061
  const record = {
849
1062
  mesh: st.handle,
850
1063
  added: c.added,
851
1064
  removed: c.removed,
1065
+ ...c.restorable === true ? { restorable: true } : {},
852
1066
  placementChanged: c.placementChanged,
853
1067
  capacityChanged: c.capacityChanged,
854
1068
  positions: c.positions,
@@ -862,6 +1076,79 @@ var WorkerScene = class WorkerScene {
862
1076
  const prev = this.#changes.get(st);
863
1077
  this.#changes.set(st, prev === void 0 ? record : merge(prev, record));
864
1078
  }
1079
+ /**
1080
+ * Follows the meshes that undoable adds and removals, and their undo and
1081
+ * redo, moved out of the engine's scene or back into it. A removal
1082
+ * requested after the result's batch decides instead.
1083
+ */
1084
+ #applyPresence(r) {
1085
+ if (r.presence === void 0 && r.fieldTargets === void 0 && r.sectionMeshes === void 0) return;
1086
+ this.#presenceVersion++;
1087
+ this.#statusChanged();
1088
+ const moved = (r.presence ?? []).flatMap(({ id, state }) => {
1089
+ const st = this.#meshes.get(id);
1090
+ return st === void 0 || r.rev < st.removedRev ? [] : [{
1091
+ st,
1092
+ state
1093
+ }];
1094
+ });
1095
+ const left = [];
1096
+ for (const { st, state } of moved) {
1097
+ if (state === "live") {
1098
+ st.removed = false;
1099
+ st.parked = false;
1100
+ st.gone = false;
1101
+ st.removedRev = 0;
1102
+ continue;
1103
+ }
1104
+ if (!st.removed) left.push(st);
1105
+ st.removed = true;
1106
+ st.parked = state === "parked";
1107
+ st.live = false;
1108
+ st.add = void 0;
1109
+ st.local = void 0;
1110
+ st.localUntil = 0;
1111
+ st.requested = void 0;
1112
+ st.requestedUntil = 0;
1113
+ if (!st.gone && this.#changes.get(st)?.removed !== true) {
1114
+ this.#clearMirrors(st);
1115
+ this.#removedHere(st);
1116
+ }
1117
+ }
1118
+ for (const st of left) {
1119
+ this.#dropLinks(st);
1120
+ this.#dropCollisionRules(st, r.rev);
1121
+ }
1122
+ for (const { section, meshes } of r.sectionMeshes ?? []) {
1123
+ const s = this.#sections.get(section);
1124
+ if (s !== void 0 && !s.removed && (this.#latest.get(`section:${section}:meshes`) ?? 0) <= r.rev) s.meshes = meshes.flatMap((id) => this.#meshes.get(id) ?? []);
1125
+ }
1126
+ for (const { field, to } of r.fieldTargets ?? []) {
1127
+ const f = this.#fields.get(field);
1128
+ if (f === void 0 || f.removed) continue;
1129
+ if (to === null) this.#fieldRemoved(f, r.rev);
1130
+ else f.desc = {
1131
+ ...f.desc,
1132
+ to
1133
+ };
1134
+ }
1135
+ for (const { st, state } of moved) if (state === "gone" && st.gone) this.#forgetMesh(st);
1136
+ }
1137
+ /** Keeps only a tombstone of a mesh removed for good, once its removal is delivered. */
1138
+ #forgetMesh(st) {
1139
+ this.#dropCollisionRules(st);
1140
+ this.#meshes.delete(st.id);
1141
+ this.#byMesh.delete(st.handle);
1142
+ this.#tombstones.add(st.handle);
1143
+ const id = st.id;
1144
+ this.#forgetKeys([
1145
+ `mesh:${id}`,
1146
+ `placement:${id}`,
1147
+ `edit:${id}`,
1148
+ `display:${id}`
1149
+ ], []);
1150
+ this.#statusChanged();
1151
+ }
865
1152
  #clearMirrors(st) {
866
1153
  st.positions = /* @__PURE__ */ new Float32Array(0);
867
1154
  st.indices = /* @__PURE__ */ new Uint32Array(0);
@@ -869,6 +1156,7 @@ var WorkerScene = class WorkerScene {
869
1156
  st.colors = null;
870
1157
  st.values = null;
871
1158
  st.uvs = null;
1159
+ st.bounds = null;
872
1160
  st.shown = null;
873
1161
  this.#guard?.bump();
874
1162
  }
@@ -995,7 +1283,8 @@ var WorkerScene = class WorkerScene {
995
1283
  * it that do not need it run meanwhile, so a reply to one of them can
996
1284
  * arrive before the mesh. Until it lands, `status("mesh:<id>")` reads
997
1285
  * `"computing"` and its views are empty; its buffers arrive with that
998
- * status turning `"ready"`.
1286
+ * status turning `"ready"`. An `undoable` add is never in the background:
1287
+ * it lands in the step it was made in, and undo removes the mesh again.
999
1288
  */
1000
1289
  addMesh(positions, indices, options = {}) {
1001
1290
  this.#alive();
@@ -1007,17 +1296,36 @@ var WorkerScene = class WorkerScene {
1007
1296
  options.origin[1],
1008
1297
  options.origin[2]
1009
1298
  ];
1010
- const id = ++this.#nextMesh;
1011
- const handle = new MeshHandle();
1012
- const known = origin ?? [
1299
+ const st = this.#allocMeshState(origin ?? [
1013
1300
  0,
1014
1301
  0,
1015
1302
  0
1016
- ];
1303
+ ], options.normals ?? true);
1304
+ const undoable = options.undoable === true;
1305
+ st.add = {
1306
+ kind: "addMesh",
1307
+ rev: ++this.#rev,
1308
+ id: st.id,
1309
+ positions: p.buffer,
1310
+ f64: !(p instanceof Float32Array),
1311
+ indices: i.buffer,
1312
+ ...uvs === void 0 ? {} : { uvs: uvs.buffer },
1313
+ options: {
1314
+ origin,
1315
+ normals: st.normalsOn,
1316
+ ...undoable ? { undoable } : {}
1317
+ }
1318
+ };
1319
+ this.#push(st.add);
1320
+ return st.handle;
1321
+ }
1322
+ #allocMeshState(knownOrigin, normalsOn) {
1323
+ const id = ++this.#nextMesh;
1324
+ const handle = new MeshHandle();
1017
1325
  const st = {
1018
1326
  id,
1019
1327
  handle,
1020
- origin: known,
1328
+ origin: knownOrigin,
1021
1329
  positions: /* @__PURE__ */ new Float32Array(0),
1022
1330
  normals: null,
1023
1331
  colors: null,
@@ -1026,11 +1334,12 @@ var WorkerScene = class WorkerScene {
1026
1334
  shown: null,
1027
1335
  pendingRules: /* @__PURE__ */ new Map(),
1028
1336
  indices: /* @__PURE__ */ new Uint32Array(0),
1337
+ bounds: void 0,
1029
1338
  pose: poseOf(IDENTITY, [
1030
1339
  0,
1031
1340
  0,
1032
1341
  0
1033
- ], known, [
1342
+ ], knownOrigin, [
1034
1343
  1,
1035
1344
  1,
1036
1345
  1
@@ -1040,80 +1349,116 @@ var WorkerScene = class WorkerScene {
1040
1349
  requested: void 0,
1041
1350
  requestedUntil: 0,
1042
1351
  removed: false,
1352
+ removedRev: 0,
1353
+ parked: false,
1043
1354
  gone: false,
1355
+ parkedRule: null,
1044
1356
  coloring: null,
1045
1357
  live: false,
1046
- normalsOn: options.normals ?? true,
1358
+ normalsOn,
1047
1359
  add: void 0,
1048
1360
  sent: false
1049
1361
  };
1050
1362
  this.#meshes.set(id, st);
1051
1363
  this.#byMesh.set(handle, st);
1052
- st.add = {
1053
- kind: "addMesh",
1054
- rev: ++this.#rev,
1055
- id,
1056
- positions: p.buffer,
1057
- f64: !(p instanceof Float32Array),
1058
- indices: i.buffer,
1059
- ...uvs === void 0 ? {} : { uvs: uvs.buffer },
1060
- options: {
1061
- origin,
1062
- normals: st.normalsOn
1063
- }
1064
- };
1065
- this.#push(st.add);
1066
- return handle;
1364
+ return st;
1365
+ }
1366
+ #discardPlaceholder(st) {
1367
+ if (st !== void 0 && !st.live) {
1368
+ st.removed = true;
1369
+ st.gone = true;
1370
+ this.#meshes.delete(st.id);
1371
+ this.#byMesh.delete(st.handle);
1372
+ }
1373
+ }
1374
+ #endDragOn(...meshes) {
1375
+ if (this.#drag !== void 0 && meshes.includes(this.#drag.mesh)) this.#drag.end();
1067
1376
  }
1068
1377
  /**
1069
1378
  * Removes a mesh, ending an active drag of it first. Later calls on it give
1070
1379
  * `UNKNOWN_MESH`; its mirrors stay readable until the removal is delivered
1071
1380
  * by `commitFrame()`.
1381
+ *
1382
+ * With `undoable` the removal is an undo step (or part of the open one):
1383
+ * {@link WorkerScene.undo} brings the mesh back with the same handle, as
1384
+ * `Scene.removeMesh` does. A {@link WorkerScene.restart} clears the history,
1385
+ * so it makes the removal permanent, and so does one larger than the
1386
+ * history budget: {@link WorkerScene.onPermanent} tells once the result is
1387
+ * in, and {@link WorkerScene.removalBytes} before.
1072
1388
  */
1073
- removeMesh(mesh) {
1389
+ removeMesh(mesh, options = {}) {
1074
1390
  const st = this.#live(mesh);
1075
1391
  if (this.#drag?.mesh === st) this.#drag.end();
1392
+ const undoable = options.undoable === true;
1076
1393
  const rev = ++this.#rev;
1394
+ st.parked = undoable;
1077
1395
  this.#noteRemoved(st, rev);
1078
1396
  this.#push({
1079
1397
  kind: "removeMesh",
1080
1398
  rev,
1081
- id: st.id
1399
+ id: st.id,
1400
+ ...undoable ? { undoable } : {}
1082
1401
  });
1083
1402
  }
1084
1403
  /**
1404
+ * Whether the scene has `mesh`: `false` once its removal is requested, or
1405
+ * a result says that the undo of its add (or the redo of its removal) took
1406
+ * it out.
1407
+ */
1408
+ has(mesh) {
1409
+ return !(mesh instanceof MeshHandle && this.#tombstones.has(mesh)) && !this.#state(mesh).removed;
1410
+ }
1411
+ /**
1412
+ * Whether undo or redo can still bring back a removed `mesh`, as of the
1413
+ * latest result (see `Scene.isRestorable`).
1414
+ */
1415
+ isRestorable(mesh) {
1416
+ if (mesh instanceof MeshHandle && this.#tombstones.has(mesh)) return false;
1417
+ const st = this.#state(mesh);
1418
+ return st.removed && st.parked;
1419
+ }
1420
+ /** About the bytes of history an undoable removal of `mesh` takes; see `Scene.removalBytes`. */
1421
+ removalBytes(mesh) {
1422
+ return this.#query("removalBytes", () => ({ mesh: this.#live(mesh).id }), (v) => v);
1423
+ }
1424
+ /**
1085
1425
  * Joins `source` into `target`; see `Scene.join`. The source stays usable
1086
1426
  * until the join lands: only a successful result removes it (a failed join
1087
- * changes nothing, engine-side or here).
1427
+ * changes nothing, engine-side or here), as part of the join's undo step.
1428
+ * {@link WorkerScene.undo} brings it back.
1429
+ *
1430
+ * @deprecated Use `workerScene.repair.join()` instead.
1088
1431
  */
1089
1432
  join(target, source, options) {
1090
1433
  const ta = this.#live(target);
1091
1434
  const st = this.#live(source);
1092
1435
  if (this.#drag?.mesh === st) this.#drag.end();
1093
1436
  const payload = copyInput(options, "options");
1094
- let rev = 0;
1095
- return this.#ask((r, qid) => {
1096
- rev = r;
1097
- return {
1098
- kind: "join",
1099
- rev: r,
1100
- target: ta.id,
1101
- source: st.id,
1102
- payload,
1103
- qid
1104
- };
1105
- }, (v) => v).then((report) => {
1106
- this.#noteRemoved(st, rev);
1107
- return report;
1108
- });
1437
+ return this.#ask((rev, qid) => ({
1438
+ kind: "join",
1439
+ rev,
1440
+ target: ta.id,
1441
+ source: st.id,
1442
+ payload,
1443
+ qid
1444
+ }), (v) => v);
1109
1445
  }
1110
1446
  /**
1111
1447
  * Notes a mesh as removed at `rev`: later calls on it give `UNKNOWN_MESH`,
1112
- * fields on it (or only to it) are dropped and its section entries go. The
1113
- * engine does the same when the removal lands.
1448
+ * and its links go ({@link WorkerScene.#dropLinks}).
1114
1449
  */
1115
1450
  #noteRemoved(st, rev) {
1116
1451
  st.removed = true;
1452
+ st.removedRev = rev;
1453
+ if (!st.parked) this.#dropFieldsOf(st, rev);
1454
+ this.#dropLinks(st);
1455
+ }
1456
+ /**
1457
+ * Drops the fields on a mesh removed for good (or only to it). The engine
1458
+ * does the same when the removal lands; for a parked mesh it says what is
1459
+ * left of the fields ({@link WorkerScene.#applyPresence}).
1460
+ */
1461
+ #dropFieldsOf(st, rev) {
1117
1462
  for (const f of this.#fields.values()) {
1118
1463
  if (f.removed) continue;
1119
1464
  if (f.desc.on === st.id || f.desc.to.length === 1 && f.desc.to[0] === st.id) this.#fieldRemoved(f, rev);
@@ -1122,7 +1467,18 @@ var WorkerScene = class WorkerScene {
1122
1467
  to: f.desc.to.filter((m) => m !== st.id)
1123
1468
  };
1124
1469
  }
1470
+ }
1471
+ /**
1472
+ * A removed mesh's section entries go, as they do in the engine, and its
1473
+ * collision rules, unless it is parked: they come back with it.
1474
+ */
1475
+ #dropLinks(st) {
1125
1476
  for (const s of this.#sections.values()) if (!s.removed) s.meshes = s.meshes.filter((m) => m !== st);
1477
+ if (!st.parked) this.#dropCollisionRules(st);
1478
+ }
1479
+ /** Drops the collision rules of a mesh's pairs: those requested after `rev` only, if given. */
1480
+ #dropCollisionRules(st, rev = 0) {
1481
+ for (const [key, entry] of [...this.#collisionRules.entries()]) if ((entry.a === st || entry.b === st) && entry.rev > rev) this.#collisionRules.delete(key);
1126
1482
  }
1127
1483
  /**
1128
1484
  * Rigidly aligns `moving` to `fixed` by ICP from their placements as the
@@ -1130,6 +1486,8 @@ var WorkerScene = class WorkerScene {
1130
1486
  * result reaches `placement()` with its batch, like a `setPlacement`.
1131
1487
  * Not replayed by a restart: an unanswered one rejects with
1132
1488
  * `INSTANCE_POISONED`, like an edit.
1489
+ *
1490
+ * @deprecated Use `workerScene.align.register()` instead.
1133
1491
  */
1134
1492
  register(moving, fixed, options = {}) {
1135
1493
  const m = this.#live(moving);
@@ -1151,6 +1509,249 @@ var WorkerScene = class WorkerScene {
1151
1509
  }), (v) => v);
1152
1510
  }
1153
1511
  /**
1512
+ * Aligns `moving` to `fixed` using corresponding world-space landmark pairs
1513
+ * via Umeyama N-point SVD (see `Scene.alignByLandmarks`).
1514
+ */
1515
+ alignByLandmarks(moving, fixed, pairs, allowScaling = false) {
1516
+ return this.#ask((rev, qid) => {
1517
+ const m = this.#live(moving);
1518
+ const f = this.#live(fixed);
1519
+ normalizeLandmarkPairs(m === f, pairs, allowScaling);
1520
+ this.#endDragOn(m, f);
1521
+ return {
1522
+ kind: "alignByLandmarks",
1523
+ rev,
1524
+ moving: m.id,
1525
+ fixed: f.id,
1526
+ pairs: pairs.map((p) => ({
1527
+ source: normalizeVec3(p.source, "pair.source"),
1528
+ target: normalizeVec3(p.target, "pair.target")
1529
+ })),
1530
+ allowScaling,
1531
+ qid
1532
+ };
1533
+ }, (v) => v);
1534
+ }
1535
+ /**
1536
+ * Runs multi-stage coarse + fine ICP registration from `moving` to `fixed`
1537
+ * (see `Scene.registerMultistage`).
1538
+ */
1539
+ registerMultistage(moving, fixed, options = {}) {
1540
+ return this.#ask((rev, qid) => {
1541
+ const m = this.#live(moving);
1542
+ const f = this.#live(fixed);
1543
+ const payload = normalizeRegistrationOptions(m === f, options);
1544
+ this.#endDragOn(m, f);
1545
+ return {
1546
+ kind: "registerMultistage",
1547
+ rev,
1548
+ moving: m.id,
1549
+ fixed: f.id,
1550
+ payload,
1551
+ qid
1552
+ };
1553
+ }, (v) => v);
1554
+ }
1555
+ /** Detects the dominant world-space reflection symmetry plane of `mesh`. */
1556
+ detectSymmetryPlane(mesh) {
1557
+ return this.#query("detectSymmetryPlane", () => ({ mesh: this.#live(mesh).id }), (v) => v);
1558
+ }
1559
+ /** Async boolean CSG operation backing {@link WorkerScene.boolean}. */
1560
+ #runBoolean(target, source, op, options) {
1561
+ return this.#ask((rev, qid) => {
1562
+ const ta = this.#live(target);
1563
+ const sb = this.#live(source);
1564
+ const payload = normalizeBooleanArgs(op, options);
1565
+ this.#endDragOn(ta, sb);
1566
+ return {
1567
+ kind: "boolean",
1568
+ rev,
1569
+ target: ta.id,
1570
+ source: sb.id,
1571
+ payload,
1572
+ qid
1573
+ };
1574
+ }, () => target);
1575
+ }
1576
+ booleanBatch(meshesOrTree, treeOrOptions, maybeOptions) {
1577
+ let added;
1578
+ return this.#ask((rev, qid) => {
1579
+ const { meshes, tree, options } = normalizeCsgBatchArgs(meshesOrTree, treeOrOptions, maybeOptions);
1580
+ const states = meshes.map((m) => this.#live(m));
1581
+ added = this.#allocMeshState([
1582
+ 0,
1583
+ 0,
1584
+ 0
1585
+ ], states[0]?.normalsOn ?? true);
1586
+ return {
1587
+ kind: "booleanBatch",
1588
+ rev,
1589
+ meshes: states.map((s) => s.id),
1590
+ tree,
1591
+ options,
1592
+ addedId: added.id,
1593
+ qid
1594
+ };
1595
+ }, () => added.handle).catch((e) => {
1596
+ this.#discardPlaceholder(added);
1597
+ throw e;
1598
+ });
1599
+ }
1600
+ /** Cuts `mesh` by `plane` in the Worker (see `Scene.cutByPlane`). */
1601
+ cutByPlane(mesh, plane, options) {
1602
+ let added;
1603
+ return this.#ask((rev, qid) => {
1604
+ const st = this.#live(mesh);
1605
+ if (plane == null || typeof plane !== "object") throw invalid("plane must be an object");
1606
+ const origin = normalizeVec3(plane.origin, "plane.origin");
1607
+ const normal = normalizeVec3(plane.normal, "plane.normal");
1608
+ const cap = options?.cap ?? true;
1609
+ if (typeof cap !== "boolean") throw invalid("cap must be a boolean");
1610
+ this.#endDragOn(st);
1611
+ added = this.#allocMeshState(st.origin, st.normalsOn);
1612
+ return {
1613
+ kind: "cutByPlane",
1614
+ rev,
1615
+ id: st.id,
1616
+ addedId: added.id,
1617
+ plane: {
1618
+ origin,
1619
+ normal
1620
+ },
1621
+ cap,
1622
+ qid
1623
+ };
1624
+ }, (v) => {
1625
+ const r = v;
1626
+ return {
1627
+ kept: mesh,
1628
+ removed: added.handle,
1629
+ keptTriangles: r.keptTriangles,
1630
+ removedTriangles: r.removedTriangles,
1631
+ capTriangles: r.capTriangles
1632
+ };
1633
+ }).catch((e) => {
1634
+ this.#discardPlaceholder(added);
1635
+ throw e;
1636
+ });
1637
+ }
1638
+ trimByCurve(mesh, optionsOrCurve, maybeOptions) {
1639
+ return this.#ask((rev, qid) => {
1640
+ const st = this.#live(mesh);
1641
+ const payload = normalizeTrimCurveArgs(optionsOrCurve, maybeOptions);
1642
+ this.#endDragOn(st);
1643
+ return {
1644
+ kind: "trimByCurve",
1645
+ rev,
1646
+ id: st.id,
1647
+ payload,
1648
+ qid
1649
+ };
1650
+ }, (v) => {
1651
+ return {
1652
+ kept: mesh,
1653
+ ...v
1654
+ };
1655
+ });
1656
+ }
1657
+ /** Fills a single boundary loop with selectable G0/G1/G2 continuity. */
1658
+ fillHoleContinuity(mesh, loopIndex, options = {}) {
1659
+ return this.#ask((rev, qid) => {
1660
+ const st = this.#live(mesh);
1661
+ const norm = normalizeFillHolesContinuityOptions(options);
1662
+ const loopIdx = checkU32Int(loopIndex, "loopIndex");
1663
+ this.#endDragOn(st);
1664
+ return {
1665
+ kind: "fillHoleContinuity",
1666
+ rev,
1667
+ id: st.id,
1668
+ loopIndex: loopIdx,
1669
+ options: norm,
1670
+ qid
1671
+ };
1672
+ }, (v) => v);
1673
+ }
1674
+ /** Fills all eligible holes with selectable G0/G1/G2 continuity. */
1675
+ fillAllHolesContinuity(mesh, options = {}) {
1676
+ return this.#ask((rev, qid) => {
1677
+ const st = this.#live(mesh);
1678
+ const norm = normalizeFillHolesContinuityOptions(options);
1679
+ this.#endDragOn(st);
1680
+ return {
1681
+ kind: "fillAllHolesContinuity",
1682
+ rev,
1683
+ id: st.id,
1684
+ options: norm,
1685
+ qid
1686
+ };
1687
+ }, (v) => v);
1688
+ }
1689
+ /** Bridges two boundary vertex arcs or index ranges. */
1690
+ bridgePartialArcs(mesh, loopA = [], loopB = [], options = {}) {
1691
+ return this.#ask((rev, qid) => {
1692
+ const st = this.#live(mesh);
1693
+ const vertsA = normalizeU32List(loopA, "loopA");
1694
+ const vertsB = normalizeU32List(loopB, "loopB");
1695
+ const norm = normalizePartialBridgeOptions(options);
1696
+ this.#endDragOn(st);
1697
+ return {
1698
+ kind: "bridgePartialArcs",
1699
+ rev,
1700
+ id: st.id,
1701
+ loopA: vertsA,
1702
+ loopB: vertsB,
1703
+ options: norm,
1704
+ qid
1705
+ };
1706
+ }, (v) => v);
1707
+ }
1708
+ /** Runs localized dynamic topology remeshing inside sphere `(center, radius)`. */
1709
+ applyDyntopo(mesh, center, radius, options = {}, pinned = []) {
1710
+ return this.#ask((rev, qid) => {
1711
+ const st = this.#live(mesh);
1712
+ const cr = normalizeDyntopoCenterRadius(center, radius);
1713
+ const norm = normalizeDyntopoOptions(options);
1714
+ const pinnedList = normalizeU32List(pinned, "pinned");
1715
+ this.#endDragOn(st);
1716
+ return {
1717
+ kind: "applyDyntopo",
1718
+ rev,
1719
+ id: st.id,
1720
+ center: cr.center,
1721
+ radius: cr.radius,
1722
+ options: norm,
1723
+ pinned: pinnedList,
1724
+ qid
1725
+ };
1726
+ }, (v) => v);
1727
+ }
1728
+ /** Applies localized dynamic topology remeshing followed by a brush dab. */
1729
+ dyntopoDab(mesh, dab, options = {}, protection) {
1730
+ return this.#ask((rev, qid) => {
1731
+ const st = this.#live(mesh);
1732
+ if (!isBrushSculptOp(dab)) throw invalid("dyntopoDab requires a brush sculpt operation");
1733
+ const norm = normalizeDyntopoOptions(options);
1734
+ const effective = protection !== void 0 ? {
1735
+ ...dab,
1736
+ protect: protection
1737
+ } : { ...dab };
1738
+ if (effective.protect !== void 0) effective.protect = {
1739
+ vertices: normalizeU32List(effective.protect.vertices, "protect.vertices"),
1740
+ ...effective.protect.weights !== void 0 ? { weights: Array.from(effective.protect.weights) } : {},
1741
+ ...effective.protect.band !== void 0 ? { band: effective.protect.band } : {}
1742
+ };
1743
+ this.#endDragOn(st);
1744
+ return {
1745
+ kind: "dyntopoDab",
1746
+ rev,
1747
+ id: st.id,
1748
+ dab: effective,
1749
+ options: norm,
1750
+ qid
1751
+ };
1752
+ }, (v) => v);
1753
+ }
1754
+ /**
1154
1755
  * Sets a mesh's placement (one undo step), scale included (`[1, 1, 1]`
1155
1756
  * when omitted); `placement()` follows when the result arrives.
1156
1757
  */
@@ -1190,6 +1791,15 @@ var WorkerScene = class WorkerScene {
1190
1791
  return this.#shown(this.#mirrored(mesh)).matrix4.slice();
1191
1792
  }
1192
1793
  /**
1794
+ * The box around the vertices the live triangles use, in the mesh's local
1795
+ * render coordinates, mirrored from the Worker. `null` without live triangles.
1796
+ */
1797
+ bounds(mesh) {
1798
+ const st = this.#mirrored(mesh);
1799
+ if (st.bounds === void 0) return;
1800
+ return cloneBounds(st.bounds);
1801
+ }
1802
+ /**
1193
1803
  * The mirrors of the mesh's render buffers, at full slot length. Each
1194
1804
  * getter returns the current mirror; a mirror is replaced when the slot
1195
1805
  * count changes or a buffer turns on or off, so get views right before use.
@@ -1249,6 +1859,8 @@ var WorkerScene = class WorkerScene {
1249
1859
  drag(mesh) {
1250
1860
  const st = this.#live(mesh);
1251
1861
  if (this.#drag?.active) throw invalid("a drag is already active; end or cancel it first");
1862
+ this.#stepDepth++;
1863
+ const dragDepth = this.#stepDepth;
1252
1864
  const start = st.requested !== void 0 && (st.local === void 0 || st.requestedUntil > st.localUntil) ? st.requested : st.local ?? st.pose;
1253
1865
  const key = `placement:${st.id}`;
1254
1866
  this.#push({
@@ -1264,6 +1876,7 @@ var WorkerScene = class WorkerScene {
1264
1876
  if (!d.active) return false;
1265
1877
  d.active = false;
1266
1878
  this.#drag = void 0;
1879
+ this.#stepDepth = Math.min(this.#stepDepth, dragDepth - 1);
1267
1880
  if (this.#terminated) return true;
1268
1881
  st.localUntil = this.#push({
1269
1882
  kind: "drag",
@@ -1277,8 +1890,19 @@ var WorkerScene = class WorkerScene {
1277
1890
  const d = {
1278
1891
  mesh: st,
1279
1892
  active: true,
1893
+ stepDepth: dragDepth,
1280
1894
  end: () => {
1281
1895
  finish("end");
1896
+ },
1897
+ abandon: (rev, restore = false) => {
1898
+ if (!d.active) return;
1899
+ d.active = false;
1900
+ this.#drag = void 0;
1901
+ st.localUntil = rev;
1902
+ if (restore) {
1903
+ st.local = start;
1904
+ this.#optimistic.add(st);
1905
+ }
1282
1906
  }
1283
1907
  };
1284
1908
  this.#drag = d;
@@ -1339,18 +1963,27 @@ var WorkerScene = class WorkerScene {
1339
1963
  id: st.id
1340
1964
  });
1341
1965
  }
1342
- /** A report of the mesh's defects; see `Scene.analyze`. */
1966
+ /**
1967
+ * A report of the mesh's defects; see `Scene.analyze`.
1968
+ *
1969
+ * @deprecated Use `workerScene.inspect.analyze()` or `workerScene.repair.analyze()` instead.
1970
+ */
1343
1971
  analyze(mesh, options) {
1344
1972
  return this.#query("analyze", () => ({
1345
1973
  mesh: this.#live(mesh).id,
1346
1974
  options
1347
1975
  }), (v) => v);
1348
1976
  }
1349
- /** Scalar measurements of a mesh; see `Scene.measure`. */
1977
+ /**
1978
+ * Scalar measurements of a mesh; see `Scene.measure`.
1979
+ *
1980
+ * @deprecated Use `workerScene.inspect.measure()` instead.
1981
+ */
1350
1982
  measure(mesh) {
1351
1983
  return this.#query("measure", () => ({ mesh: this.#live(mesh).id }), (v) => v);
1352
1984
  }
1353
- repair(mesh, op) {
1985
+ /** Runs one repair operation, a list as one transaction, or the auto pipeline; see `Scene.repair`. */
1986
+ #runRepair(mesh, op) {
1354
1987
  return this.#ask((rev, qid) => ({
1355
1988
  kind: "repair",
1356
1989
  rev,
@@ -1359,36 +1992,1062 @@ var WorkerScene = class WorkerScene {
1359
1992
  qid
1360
1993
  }), (v) => v);
1361
1994
  }
1362
- /** Undoes the latest step; an active drag is ended first. */
1363
- undo() {
1364
- this.#alive();
1365
- this.#drag?.end();
1366
- this.#forgetRequested();
1367
- this.#push({
1368
- kind: "undo",
1369
- rev: ++this.#rev
1370
- });
1995
+ /**
1996
+ * Live triangle-used vertex ids of `mesh` inside the closed local-space
1997
+ * sphere `(center, radius)`, in ascending order; see `Scene.verticesInSphere`.
1998
+ *
1999
+ * @deprecated Use `workerScene.sculpt.verticesInSphere()` instead.
2000
+ */
2001
+ verticesInSphere(mesh, center, radius) {
2002
+ return this.#query("verticesInSphere", () => {
2003
+ const id = this.#live(mesh).id;
2004
+ const c = center;
2005
+ if (c?.length !== 3 || ![
2006
+ c[0],
2007
+ c[1],
2008
+ c[2]
2009
+ ].every((x) => typeof x === "number" && Number.isFinite(x))) throw invalid("center must be 3 finite numbers");
2010
+ if (typeof radius !== "number" || !Number.isFinite(radius) || radius < 0) throw invalid("radius must be a finite non-negative number");
2011
+ return {
2012
+ mesh: id,
2013
+ center: [
2014
+ c[0],
2015
+ c[1],
2016
+ c[2]
2017
+ ],
2018
+ radius
2019
+ };
2020
+ }, (v) => v);
1371
2021
  }
1372
- /** Redoes the latest undone step; an active drag is ended first. */
1373
- redo() {
1374
- this.#alive();
1375
- this.#drag?.end();
1376
- this.#forgetRequested();
1377
- this.#push({
1378
- kind: "redo",
1379
- rev: ++this.#rev
1380
- });
2022
+ /** Evaluates world-space printability overhangs against `buildDirection` (see `Scene.overhangs`). */
2023
+ overhangs(mesh, options = {}) {
2024
+ return this.#query("overhangs", () => ({
2025
+ mesh: this.#live(mesh).id,
2026
+ options: normalizeOverhangOptions(options)
2027
+ }), (v) => v);
2028
+ }
2029
+ /** Computes per-triangle geometric quality and worst-incident vertex quality (see `Scene.triangleQuality`). */
2030
+ triangleQuality(mesh, metricOrOptions = "radiusRatio", sliverThreshold) {
2031
+ return this.#query("triangleQuality", () => {
2032
+ const id = this.#live(mesh).id;
2033
+ const norm = normalizeQualityArgs(metricOrOptions, sliverThreshold);
2034
+ return {
2035
+ mesh: id,
2036
+ metric: norm.metric,
2037
+ sliverThreshold: norm.sliverThreshold
2038
+ };
2039
+ }, (v) => v);
2040
+ }
2041
+ /** Computes vertex-wise Hausdorff or signed distance deviation from `source` to `target`. */
2042
+ meshDeviation(source, target, options = {}) {
2043
+ return this.#query("meshDeviation", () => ({
2044
+ source: this.#live(source).id,
2045
+ target: this.#live(target).id,
2046
+ options: normalizeDeviationOptions(options)
2047
+ }), (v) => v);
1381
2048
  }
1382
2049
  /**
1383
- * An undo or redo is queued: requested placements and the poses held for
1384
- * ended drags no longer say where the meshes will be. The engine's pose is
1385
- * shown (and a new drag starts from it) until the results arrive.
2050
+ * Computes geodesic surface distances from `sources` on `mesh` (`"dijkstra"`
2051
+ * or `"heatMethod"`), in steps on the Worker: `options.signal` cancels the
2052
+ * query. Other requests wait for it.
1386
2053
  */
1387
- #forgetRequested() {
1388
- for (const st of this.#meshes.values()) {
1389
- st.requested = void 0;
1390
- if (st.local !== void 0 && st.localUntil !== Number.POSITIVE_INFINITY) {
1391
- if (!samePose(st.local, st.pose)) this.#optimistic.add(st);
2054
+ geodesicDistances(mesh, sources, options = {}) {
2055
+ return this.#query("geodesicDistances", () => ({
2056
+ mesh: this.#live(mesh).id,
2057
+ sources: Array.from(normalizeSourceVertices(sources)),
2058
+ options: normalizeGeodesicOptions(options)
2059
+ }), (v) => v, options.signal);
2060
+ }
2061
+ /** Frees what `"heatMethod"` queries keep in the Worker for the next one of the same mesh. */
2062
+ releaseGeodesics() {
2063
+ return this.#query("releaseGeodesics", () => ({}), () => void 0);
2064
+ }
2065
+ /**
2066
+ * Traces an intrinsic shortest path along the surface of `mesh` to
2067
+ * `targetVertex`. Without `options.distances` it computes them first, like
2068
+ * {@link WorkerScene.geodesicDistances}: `options.signal` cancels that.
2069
+ */
2070
+ shortestSurfacePath(mesh, sources, targetVertex, options = {}) {
2071
+ return this.#query("shortestSurfacePath", () => {
2072
+ const id = this.#live(mesh).id;
2073
+ const src = Array.from(normalizeSourceVertices(sources));
2074
+ const target = normalizeSurfacePathTarget(targetVertex);
2075
+ const checked = checkSurfacePathOptions(options);
2076
+ return {
2077
+ mesh: id,
2078
+ sources: src,
2079
+ targetVertex: target,
2080
+ options: {
2081
+ ...checked.geodesic,
2082
+ ...checked.distances === void 0 ? {} : { distances: checked.distances.slice() }
2083
+ }
2084
+ };
2085
+ }, (v) => v, options.signal);
2086
+ }
2087
+ selectFacesScreen(mesh, shape, options) {
2088
+ return this.#query("selectFacesScreen", () => {
2089
+ const id = this.#live(mesh).id;
2090
+ normalizeScreenSelectArgs(shape, options);
2091
+ return {
2092
+ mesh: id,
2093
+ shape: copyInput(shape, "shape"),
2094
+ options: copyInput(options, "options")
2095
+ };
2096
+ }, (v) => v);
2097
+ }
2098
+ selectFacesInSphere(mesh, center, radius, normalCone) {
2099
+ return this.#query("selectFacesInSphere", () => {
2100
+ const id = this.#live(mesh).id;
2101
+ normalizeSelectInSphereArgs(center, radius, normalCone);
2102
+ return {
2103
+ mesh: id,
2104
+ center: [
2105
+ center[0],
2106
+ center[1],
2107
+ center[2]
2108
+ ],
2109
+ radius,
2110
+ ...normalCone === void 0 ? {} : { normalCone: {
2111
+ normal: [
2112
+ normalCone.normal[0],
2113
+ normalCone.normal[1],
2114
+ normalCone.normal[2]
2115
+ ],
2116
+ angleRad: normalCone.angleRad
2117
+ } }
2118
+ };
2119
+ }, (v) => v);
2120
+ }
2121
+ selectByCreaseAngle(mesh, seedTri, maxDihedralRad) {
2122
+ return this.#query("selectByCreaseAngle", () => ({
2123
+ mesh: this.#live(mesh).id,
2124
+ seedTri: checkU32Arg(seedTri, "seedTri"),
2125
+ maxDihedralRad
2126
+ }), (v) => v);
2127
+ }
2128
+ selectConnectedShell(mesh, seedTri) {
2129
+ return this.#query("selectConnectedShell", () => ({
2130
+ mesh: this.#live(mesh).id,
2131
+ seedTri: checkU32Arg(seedTri, "seedTri")
2132
+ }), (v) => v);
2133
+ }
2134
+ selectSmallFaceIslands(mesh, maxFaceCount, maxArea) {
2135
+ return this.#query("selectSmallFaceIslands", () => {
2136
+ const id = this.#live(mesh).id;
2137
+ const n = normalizeSelectSmallIslandsArgs(maxFaceCount, maxArea);
2138
+ return {
2139
+ mesh: id,
2140
+ maxFaceCount: n.maxFaceCount,
2141
+ ...maxArea === void 0 ? {} : { maxArea: n.maxArea }
2142
+ };
2143
+ }, (v) => v);
2144
+ }
2145
+ growFaceSelection(mesh, selectedTris, rings = 1, adjacency = "edge") {
2146
+ return this.#query("growFaceSelection", () => {
2147
+ const id = this.#live(mesh).id;
2148
+ const n = normalizeGrowShrinkArgs(selectedTris, rings, adjacency);
2149
+ return {
2150
+ mesh: id,
2151
+ selectedTris: n.selectedTris,
2152
+ rings: n.rings,
2153
+ adjacency
2154
+ };
2155
+ }, (v) => v);
2156
+ }
2157
+ shrinkFaceSelection(mesh, selectedTris, rings = 1, adjacency = "edge") {
2158
+ return this.#query("shrinkFaceSelection", () => {
2159
+ const id = this.#live(mesh).id;
2160
+ const n = normalizeGrowShrinkArgs(selectedTris, rings, adjacency);
2161
+ return {
2162
+ mesh: id,
2163
+ selectedTris: n.selectedTris,
2164
+ rings: n.rings,
2165
+ adjacency
2166
+ };
2167
+ }, (v) => v);
2168
+ }
2169
+ fillSelectionHoles(mesh, selectedTris, maxHoleTris) {
2170
+ return this.#query("fillSelectionHoles", () => ({
2171
+ mesh: this.#live(mesh).id,
2172
+ selectedTris: normalizeU32Selection(selectedTris),
2173
+ maxHoleTris: checkU32Arg(maxHoleTris, "maxHoleTris")
2174
+ }), (v) => v);
2175
+ }
2176
+ smoothSelectionBoundary(mesh, selectedTris, iterations = 1) {
2177
+ return this.#query("smoothSelectionBoundary", () => ({
2178
+ mesh: this.#live(mesh).id,
2179
+ selectedTris: normalizeU32Selection(selectedTris),
2180
+ iterations: checkU32Arg(iterations, "iterations")
2181
+ }), (v) => v);
2182
+ }
2183
+ faceSelectionToVertexMask(mesh, selectedTris) {
2184
+ return this.#query("faceSelectionToVertexMask", () => ({
2185
+ mesh: this.#live(mesh).id,
2186
+ selectedTris: normalizeU32Selection(selectedTris)
2187
+ }), (v) => v);
2188
+ }
2189
+ vertexMaskToFaceSelection(mesh, mask, threshold = .5, requireAllVertices = false) {
2190
+ return this.#query("vertexMaskToFaceSelection", () => {
2191
+ const id = this.#live(mesh).id;
2192
+ const n = normalizeVertexMaskSelectArgs(mask, threshold, requireAllVertices);
2193
+ return {
2194
+ mesh: id,
2195
+ mask: n.mask,
2196
+ threshold: n.threshold,
2197
+ requireAllVertices: n.requireAllVertices
2198
+ };
2199
+ }, (v) => v);
2200
+ }
2201
+ deleteSelectedFaces(mesh, selectedTris) {
2202
+ return this.#ask((rev, qid) => {
2203
+ const st = this.#live(mesh);
2204
+ const tris = normalizeU32Selection(selectedTris);
2205
+ this.#endDragOn(st);
2206
+ return {
2207
+ kind: "deleteSelectedFaces",
2208
+ rev,
2209
+ id: st.id,
2210
+ selectedTris: tris,
2211
+ qid
2212
+ };
2213
+ }, (v) => v);
2214
+ }
2215
+ /** Extrudes a face selection in the Worker, one undo step (see `Scene.extrudeFaces`). */
2216
+ extrudeFaces(mesh, triangles, options) {
2217
+ return this.#ask((rev, qid) => {
2218
+ const st = this.#live(mesh);
2219
+ const tris = normalizeU32Selection(triangles, "triangles");
2220
+ extrudeFacesArgs(options);
2221
+ const cloned = copyInput(options, "options");
2222
+ this.#endDragOn(st);
2223
+ return {
2224
+ kind: "extrudeFaces",
2225
+ rev,
2226
+ id: st.id,
2227
+ triangles: tris,
2228
+ options: cloned,
2229
+ qid
2230
+ };
2231
+ }, (v) => v);
2232
+ }
2233
+ /** Extrudes a mesh's boundary to a flat base in the Worker, one undo step (see `Scene.extrudeBase`). */
2234
+ extrudeBase(mesh, options) {
2235
+ return this.#ask((rev, qid) => {
2236
+ const st = this.#live(mesh);
2237
+ extrudeBaseArgs(options);
2238
+ const cloned = copyInput(options, "options");
2239
+ this.#endDragOn(st);
2240
+ return {
2241
+ kind: "extrudeBase",
2242
+ rev,
2243
+ id: st.id,
2244
+ options: cloned,
2245
+ qid
2246
+ };
2247
+ }, (v) => v);
2248
+ }
2249
+ extractSelectedFaces(mesh, selectedTris, options = {}) {
2250
+ let added;
2251
+ return this.#ask((rev, qid) => {
2252
+ const st = this.#live(mesh);
2253
+ const tris = normalizeU32Selection(selectedTris);
2254
+ const normals = checkBooleanArg(options?.normals, st.normalsOn, "options.normals");
2255
+ this.#endDragOn(st);
2256
+ added = this.#allocMeshState(st.origin, normals);
2257
+ return {
2258
+ kind: "extractSelectedFaces",
2259
+ rev,
2260
+ id: st.id,
2261
+ addedId: added.id,
2262
+ selectedTris: tris,
2263
+ normals,
2264
+ qid
2265
+ };
2266
+ }, () => added.handle).catch((e) => {
2267
+ this.#discardPlaceholder(added);
2268
+ throw e;
2269
+ });
2270
+ }
2271
+ splitSelectedFaces(mesh, selectedTris, options = {}) {
2272
+ let added;
2273
+ return this.#ask((rev, qid) => {
2274
+ const st = this.#live(mesh);
2275
+ const tris = normalizeU32Selection(selectedTris);
2276
+ const normals = checkBooleanArg(options?.normals, st.normalsOn, "options.normals");
2277
+ this.#endDragOn(st);
2278
+ added = this.#allocMeshState(st.origin, normals);
2279
+ return {
2280
+ kind: "splitSelectedFaces",
2281
+ rev,
2282
+ id: st.id,
2283
+ addedId: added.id,
2284
+ selectedTris: tris,
2285
+ normals,
2286
+ qid
2287
+ };
2288
+ }, (v) => {
2289
+ const r = v;
2290
+ return {
2291
+ detached: this.#handleOf(r.detached),
2292
+ removedTriangles: r.removedTriangles,
2293
+ removedVertices: r.removedVertices
2294
+ };
2295
+ }).catch((e) => {
2296
+ this.#discardPlaceholder(added);
2297
+ throw e;
2298
+ });
2299
+ }
2300
+ buildFfdLattice(mesh, dims, basis = "bernstein", padding = 0) {
2301
+ return this.#query("buildFfdLattice", () => {
2302
+ const id = this.#live(mesh).id;
2303
+ normalizeBuildFfdLatticeArgs(dims, basis, padding);
2304
+ return {
2305
+ mesh: id,
2306
+ dims: [
2307
+ dims[0],
2308
+ dims[1],
2309
+ dims[2]
2310
+ ],
2311
+ basis,
2312
+ padding
2313
+ };
2314
+ }, (v) => v);
2315
+ }
2316
+ applyFfd(mesh, options) {
2317
+ return this.#ask((rev, qid) => {
2318
+ const st = this.#live(mesh);
2319
+ normalizeFfdArgs(options);
2320
+ const cloned = copyInput(options, "options");
2321
+ this.#endDragOn(st);
2322
+ return {
2323
+ kind: "applyFfd",
2324
+ rev,
2325
+ id: st.id,
2326
+ options: cloned,
2327
+ qid
2328
+ };
2329
+ }, (v) => v);
2330
+ }
2331
+ applyArap(mesh, options) {
2332
+ return this.#ask((rev, qid) => {
2333
+ const st = this.#live(mesh);
2334
+ normalizeArapArgs(options);
2335
+ const cloned = copyInput(options, "options");
2336
+ this.#endDragOn(st);
2337
+ return {
2338
+ kind: "applyArap",
2339
+ rev,
2340
+ id: st.id,
2341
+ options: cloned,
2342
+ qid
2343
+ };
2344
+ }, (v) => v);
2345
+ }
2346
+ applyKelvinlet(mesh, options) {
2347
+ return this.#ask((rev, qid) => {
2348
+ const st = this.#live(mesh);
2349
+ normalizeKelvinletArgs(options);
2350
+ const cloned = copyInput(options, "options");
2351
+ this.#endDragOn(st);
2352
+ return {
2353
+ kind: "applyKelvinlet",
2354
+ rev,
2355
+ id: st.id,
2356
+ options: cloned,
2357
+ qid
2358
+ };
2359
+ }, (v) => v);
2360
+ }
2361
+ applyXpbd(mesh, options) {
2362
+ return this.#ask((rev, qid) => {
2363
+ const st = this.#live(mesh);
2364
+ normalizeXpbdArgs(options);
2365
+ const cloned = copyInput(options, "options");
2366
+ this.#endDragOn(st);
2367
+ return {
2368
+ kind: "applyXpbd",
2369
+ rev,
2370
+ id: st.id,
2371
+ options: cloned,
2372
+ qid
2373
+ };
2374
+ }, (v) => v);
2375
+ }
2376
+ setDefaultCollisionRule(rule) {
2377
+ this.#alive();
2378
+ const normalized = normalizeCollisionRule(rule);
2379
+ this.#defaultCollisionRule = normalized;
2380
+ this.#push({
2381
+ kind: "setDefaultCollisionRule",
2382
+ rev: ++this.#rev,
2383
+ rule: { ...normalized }
2384
+ });
2385
+ }
2386
+ defaultCollisionRule() {
2387
+ this.#alive();
2388
+ return { ...this.#defaultCollisionRule };
2389
+ }
2390
+ setCollisionRule(a, b, rule) {
2391
+ const sa = this.#live(a);
2392
+ const sb = this.#live(b);
2393
+ if (sa === sb) throw invalid("collision rule requires two distinct meshes");
2394
+ const normalized = normalizeCollisionRule(rule);
2395
+ const rev = ++this.#rev;
2396
+ this.#collisionRules.set(collisionPairKey(sa.id, sb.id), {
2397
+ a: sa,
2398
+ b: sb,
2399
+ rule: normalized,
2400
+ rev
2401
+ });
2402
+ this.#push({
2403
+ kind: "setCollisionRule",
2404
+ rev,
2405
+ a: sa.id,
2406
+ b: sb.id,
2407
+ rule: { ...normalized }
2408
+ });
2409
+ }
2410
+ clearCollisionRule(a, b) {
2411
+ const sa = this.#live(a);
2412
+ const sb = this.#live(b);
2413
+ if (sa === sb) throw invalid("collision rule requires two distinct meshes");
2414
+ const existed = this.#collisionRules.delete(collisionPairKey(sa.id, sb.id));
2415
+ this.#push({
2416
+ kind: "clearCollisionRule",
2417
+ rev: ++this.#rev,
2418
+ a: sa.id,
2419
+ b: sb.id
2420
+ });
2421
+ return existed;
2422
+ }
2423
+ collisionRule(a, b) {
2424
+ const sa = this.#live(a);
2425
+ const sb = this.#live(b);
2426
+ if (sa === sb) throw invalid("collision rule requires two distinct meshes");
2427
+ const entry = this.#collisionRules.get(collisionPairKey(sa.id, sb.id));
2428
+ return entry !== void 0 ? { ...entry.rule } : { ...this.#defaultCollisionRule };
2429
+ }
2430
+ hasActiveCollisionResponse(mesh) {
2431
+ const st = this.#live(mesh);
2432
+ if (this.#defaultCollisionRule.mode !== "passThrough") return true;
2433
+ for (const entry of this.#collisionRules.values()) if ((entry.a === st || entry.b === st) && !entry.a.removed && !entry.b.removed && entry.rule.mode !== "passThrough") return true;
2434
+ return false;
2435
+ }
2436
+ moveWithCollision(mesh, placement, isRelease = false) {
2437
+ return this.#ask((rev, qid) => {
2438
+ const st = this.#live(mesh);
2439
+ const norm = normalizePlacementInputArgs(placement);
2440
+ const release = checkBooleanArg(isRelease, false, "isRelease");
2441
+ this.#endDragOn(st);
2442
+ const wirePlacement = {
2443
+ rotation: Array.from(norm.rotation),
2444
+ translation: [
2445
+ norm.translation[0],
2446
+ norm.translation[1],
2447
+ norm.translation[2]
2448
+ ],
2449
+ ...norm.scale === void 0 ? {} : { scale: [
2450
+ norm.scale[0],
2451
+ norm.scale[1],
2452
+ norm.scale[2]
2453
+ ] }
2454
+ };
2455
+ return {
2456
+ kind: "moveWithCollision",
2457
+ rev,
2458
+ id: st.id,
2459
+ placement: wirePlacement,
2460
+ isRelease: release,
2461
+ qid
2462
+ };
2463
+ }, (v) => this.#mapCollisionReport(v));
2464
+ }
2465
+ commitCollisionInteraction(mesh) {
2466
+ return this.#ask((rev, qid) => {
2467
+ const st = this.#live(mesh);
2468
+ this.#endDragOn(st);
2469
+ return {
2470
+ kind: "commitCollisionInteraction",
2471
+ rev,
2472
+ id: st.id,
2473
+ qid
2474
+ };
2475
+ }, (v) => this.#mapCollisionReport(v));
2476
+ }
2477
+ fitPrimitive(mesh, options = {}) {
2478
+ return this.#query("fitPrimitive", () => {
2479
+ const id = this.#live(mesh).id;
2480
+ normalizeFitPrimitiveArgs(options);
2481
+ return {
2482
+ mesh: id,
2483
+ options: copyInput(options, "options")
2484
+ };
2485
+ }, (v) => v);
2486
+ }
2487
+ alignToFittedPrimitive(mesh, primitive, targetAxis, targetOrigin) {
2488
+ return this.#ask((rev, qid) => {
2489
+ const st = this.#live(mesh);
2490
+ const n = normalizeAlignToPrimitiveArgs(primitive, targetAxis, targetOrigin);
2491
+ this.#endDragOn(st);
2492
+ return {
2493
+ kind: "alignToFittedPrimitive",
2494
+ rev,
2495
+ id: st.id,
2496
+ primitive: copyInput(primitive, "primitive"),
2497
+ targetAxis: [
2498
+ n.targetAxis[0],
2499
+ n.targetAxis[1],
2500
+ n.targetAxis[2]
2501
+ ],
2502
+ targetOrigin: [
2503
+ n.targetOrigin[0],
2504
+ n.targetOrigin[1],
2505
+ n.targetOrigin[2]
2506
+ ],
2507
+ qid
2508
+ };
2509
+ }, (v) => v);
2510
+ }
2511
+ sliceContours(mesh, origin, normal) {
2512
+ return this.#query("sliceContours", () => {
2513
+ const id = this.#live(mesh).id;
2514
+ const n = normalizeSliceContoursArgs(origin, normal);
2515
+ return {
2516
+ mesh: id,
2517
+ origin: [
2518
+ n.origin[0],
2519
+ n.origin[1],
2520
+ n.origin[2]
2521
+ ],
2522
+ normal: [
2523
+ n.normal[0],
2524
+ n.normal[1],
2525
+ n.normal[2]
2526
+ ]
2527
+ };
2528
+ }, (v) => v);
2529
+ }
2530
+ sliceContourStack(mesh, origin, normal, spacing, count) {
2531
+ return this.#query("sliceContourStack", () => {
2532
+ const id = this.#live(mesh).id;
2533
+ const n = normalizeSliceContourStackArgs(origin, normal, spacing, count);
2534
+ return {
2535
+ mesh: id,
2536
+ origin: [
2537
+ n.origin[0],
2538
+ n.origin[1],
2539
+ n.origin[2]
2540
+ ],
2541
+ normal: [
2542
+ n.normal[0],
2543
+ n.normal[1],
2544
+ n.normal[2]
2545
+ ],
2546
+ spacing: n.spacing,
2547
+ count: n.count
2548
+ };
2549
+ }, (v) => v);
2550
+ }
2551
+ /**
2552
+ * Adds the convex hull of `meshes` (one mesh or several) in the Worker as a
2553
+ * new mesh, one undo step (see `Scene.convexHull`).
2554
+ */
2555
+ convexHull(meshes, options) {
2556
+ let added;
2557
+ return this.#ask((rev, qid) => {
2558
+ const states = hullMeshList(meshes).map((m) => this.#live(m));
2559
+ const normals = hullNormals(options);
2560
+ added = this.#allocMeshState([
2561
+ 0,
2562
+ 0,
2563
+ 0
2564
+ ], normals);
2565
+ return {
2566
+ kind: "convexHull",
2567
+ rev,
2568
+ addedId: added.id,
2569
+ meshes: states.map((st) => st.id),
2570
+ normals,
2571
+ qid
2572
+ };
2573
+ }, (v) => ({
2574
+ mesh: added.handle,
2575
+ ...v
2576
+ })).catch((e) => {
2577
+ this.#discardPlaceholder(added);
2578
+ throw e;
2579
+ });
2580
+ }
2581
+ /**
2582
+ * Adds the convex hull of world `points` in the Worker as a new mesh, one
2583
+ * undo step (see `Scene.convexHullOfPoints`). The points are copied.
2584
+ */
2585
+ convexHullOfPoints(points, options) {
2586
+ let added;
2587
+ return this.#ask((rev, qid) => {
2588
+ this.#alive();
2589
+ const buf = hullPointsBuffer(points);
2590
+ const normals = hullNormals(options);
2591
+ added = this.#allocMeshState([
2592
+ 0,
2593
+ 0,
2594
+ 0
2595
+ ], normals);
2596
+ return {
2597
+ kind: "convexHullPoints",
2598
+ rev,
2599
+ addedId: added.id,
2600
+ points: buf,
2601
+ normals,
2602
+ qid
2603
+ };
2604
+ }, (v) => ({
2605
+ mesh: added.handle,
2606
+ ...v
2607
+ })).catch((e) => {
2608
+ this.#discardPlaceholder(added);
2609
+ throw e;
2610
+ });
2611
+ }
2612
+ /** Fits a height map's frame to `meshes` (one mesh or several) in the Worker (see `Scene.heightMapFrame`). */
2613
+ heightMapFrame(meshes, options) {
2614
+ return this.#query("heightMapFrame", () => ({
2615
+ meshes: heightMapMeshList(meshes).map((m) => this.#live(m).id),
2616
+ options: encodeHeightMapOptions(options)
2617
+ }), (v) => v);
2618
+ }
2619
+ /**
2620
+ * An orthographic depth image of `meshes` (one mesh or several), sampled in
2621
+ * the Worker and transferred (see `Scene.heightMap`). Asking for bands of
2622
+ * `rows` lets other requests run in between them.
2623
+ */
2624
+ heightMap(meshes, frame, rows) {
2625
+ return this.#query("heightMap", () => ({
2626
+ meshes: heightMapMeshList(meshes).map((m) => this.#live(m).id),
2627
+ ...isHeightMapFrame(frame) ? { frame: encodeHeightMapFrame(frame) } : { options: encodeHeightMapOptions(frame) },
2628
+ ...rows === void 0 ? {} : { rows: [rows[0], rows[1]] }
2629
+ }), (v) => v);
2630
+ }
2631
+ /**
2632
+ * Adds the relief of a grid of heights in the Worker as a new mesh, one undo
2633
+ * step (see `Scene.addHeightfield`). The heights are copied here and
2634
+ * transferred; the mesh itself comes back only as the mirror's buffers.
2635
+ */
2636
+ addHeightfield(field, options) {
2637
+ let added;
2638
+ return this.#ask((rev, qid) => {
2639
+ this.#alive();
2640
+ const checked = checkHeightfield(field);
2641
+ const placement = checkHeightfieldPlacement(options);
2642
+ added = this.#allocMeshState([
2643
+ 0,
2644
+ 0,
2645
+ 0
2646
+ ], placement.normals);
2647
+ const copy = {
2648
+ ...checked,
2649
+ heights: checked.heights.slice()
2650
+ };
2651
+ return {
2652
+ kind: "addHeightfield",
2653
+ rev,
2654
+ addedId: added.id,
2655
+ field: copy,
2656
+ placement,
2657
+ qid
2658
+ };
2659
+ }, (v) => ({
2660
+ mesh: added.handle,
2661
+ ...v
2662
+ })).catch((e) => {
2663
+ this.#discardPlaceholder(added);
2664
+ throw e;
2665
+ });
2666
+ }
2667
+ /** Smooths noise out of `mesh` in the Worker, one undo step (see `Scene.denoise`). */
2668
+ denoise(mesh, options) {
2669
+ return this.#ask((rev, qid) => {
2670
+ const st = this.#live(mesh);
2671
+ const checked = checkDenoiseOptions(options);
2672
+ this.#endDragOn(st);
2673
+ return {
2674
+ kind: "denoise",
2675
+ rev,
2676
+ id: st.id,
2677
+ options: checked,
2678
+ qid
2679
+ };
2680
+ }, (v) => v);
2681
+ }
2682
+ /** Flips `mesh`'s edges towards Delaunay in the Worker, one undo step (see `Scene.delaunayFlips`). */
2683
+ delaunayFlips(mesh, options) {
2684
+ return this.#ask((rev, qid) => {
2685
+ const st = this.#live(mesh);
2686
+ const checked = checkDelaunayFlipOptions(options);
2687
+ this.#endDragOn(st);
2688
+ return {
2689
+ kind: "delaunayFlips",
2690
+ rev,
2691
+ id: st.id,
2692
+ options: checked,
2693
+ qid
2694
+ };
2695
+ }, (v) => v);
2696
+ }
2697
+ /**
2698
+ * Plans the voxel grid of {@link WorkerScene.wrap} for the same meshes and
2699
+ * options without running it (see `Scene.wrapPlan`).
2700
+ */
2701
+ wrapPlan(meshes, options) {
2702
+ return this.#query("wrapPlan", () => ({
2703
+ meshes: wrapMeshList(meshes).map((m) => this.#live(m).id),
2704
+ options: checkWrapOptions(options)
2705
+ }), (v) => v);
2706
+ }
2707
+ /**
2708
+ * Wraps `meshes` (one mesh or several) in one closed, manifold envelope in
2709
+ * the Worker, added as a new mesh, one undo step (see `Scene.wrap`). The
2710
+ * page stays live while it runs.
2711
+ */
2712
+ wrap(meshes, options) {
2713
+ let added;
2714
+ return this.#ask((rev, qid) => {
2715
+ const states = wrapMeshList(meshes).map((m) => this.#live(m));
2716
+ const checked = checkWrapOptions(options);
2717
+ added = this.#allocMeshState([
2718
+ 0,
2719
+ 0,
2720
+ 0
2721
+ ], checked.normals);
2722
+ return {
2723
+ kind: "wrap",
2724
+ rev,
2725
+ addedId: added.id,
2726
+ meshes: states.map((st) => st.id),
2727
+ options: checked,
2728
+ qid
2729
+ };
2730
+ }, (v) => ({
2731
+ mesh: added.handle,
2732
+ ...v
2733
+ })).catch((e) => {
2734
+ this.#discardPlaceholder(added);
2735
+ throw e;
2736
+ });
2737
+ }
2738
+ reconstructPointCloud(cloud, options = {}) {
2739
+ let added;
2740
+ return this.#ask((rev, qid) => {
2741
+ this.#alive();
2742
+ const buf = cloudBuffer(cloud).slice();
2743
+ const origin = cloudOrigin(cloud);
2744
+ normalizeReconstructArgs(options);
2745
+ const normals = checkBooleanArg(options?.normals, true, "options.normals");
2746
+ added = this.#allocMeshState(origin ?? [
2747
+ 0,
2748
+ 0,
2749
+ 0
2750
+ ], normals);
2751
+ return {
2752
+ kind: "reconstructPointCloud",
2753
+ rev,
2754
+ addedId: added.id,
2755
+ cloud: buf,
2756
+ ...origin === void 0 ? {} : { origin },
2757
+ options: copyInput(options, "options"),
2758
+ qid
2759
+ };
2760
+ }, () => added.handle).catch((e) => {
2761
+ this.#discardPlaceholder(added);
2762
+ throw e;
2763
+ });
2764
+ }
2765
+ hollowMesh(mesh, options) {
2766
+ return this.#ask((rev, qid) => {
2767
+ const st = this.#live(mesh);
2768
+ normalizeHollowArgs(options);
2769
+ const cloned = copyInput(options, "options");
2770
+ this.#endDragOn(st);
2771
+ return {
2772
+ kind: "hollowMesh",
2773
+ rev,
2774
+ id: st.id,
2775
+ options: cloned,
2776
+ qid
2777
+ };
2778
+ }, (v) => v);
2779
+ }
2780
+ /**
2781
+ * Plans the voxel grid of {@link WorkerScene.latticeFill} for the same mesh
2782
+ * and options without running it (see `Scene.latticePlan`).
2783
+ */
2784
+ latticePlan(mesh, options) {
2785
+ return this.#query("latticePlan", () => ({
2786
+ mesh: this.#live(mesh).id,
2787
+ options: checkLatticeOptions(options, DEFAULT_LATTICE_MAX_VOXELS)
2788
+ }), (v) => v);
2789
+ }
2790
+ /**
2791
+ * Fills the inside of a closed mesh, or the cavity of a hollowed one, with a
2792
+ * lattice in the Worker, one undo step (see `Scene.latticeFill`). The page
2793
+ * stays live while it runs.
2794
+ */
2795
+ latticeFill(mesh, options) {
2796
+ return this.#ask((rev, qid) => {
2797
+ const st = this.#live(mesh);
2798
+ const checked = checkLatticeOptions(options, DEFAULT_LATTICE_MAX_VOXELS);
2799
+ this.#endDragOn(st);
2800
+ return {
2801
+ kind: "latticeFill",
2802
+ rev,
2803
+ id: st.id,
2804
+ options: checked,
2805
+ qid
2806
+ };
2807
+ }, (v) => v);
2808
+ }
2809
+ /**
2810
+ * The walls of a lattice on a small grid, built in the Worker without
2811
+ * changing the mesh (see `Scene.latticePreview`).
2812
+ */
2813
+ latticePreview(mesh, options) {
2814
+ return this.#query("latticePreview", () => ({
2815
+ mesh: this.#live(mesh).id,
2816
+ options: checkLatticeOptions(options, DEFAULT_LATTICE_PREVIEW_VOXELS)
2817
+ }), (v) => v);
2818
+ }
2819
+ punchDrainHole(mesh, options) {
2820
+ let plug;
2821
+ return this.#ask((rev, qid) => {
2822
+ const st = this.#live(mesh);
2823
+ const n = normalizeDrainHoleArgs(options);
2824
+ const plugNormals = checkBooleanArg(n.plugNormals, st.normalsOn, "options.plugNormals");
2825
+ const cloned = copyInput(options, "options");
2826
+ this.#endDragOn(st);
2827
+ plug = n.generatePlug ? this.#allocMeshState(st.origin, plugNormals) : void 0;
2828
+ return {
2829
+ kind: "punchDrainHole",
2830
+ rev,
2831
+ id: st.id,
2832
+ ...plug === void 0 ? {} : { plugId: plug.id },
2833
+ options: cloned,
2834
+ qid
2835
+ };
2836
+ }, (v) => {
2837
+ const r = v;
2838
+ if (plug !== void 0 && !r.plugs.includes(plug.id)) this.#discardPlaceholder(plug);
2839
+ return {
2840
+ ...r,
2841
+ plugs: r.plugs.map((pid) => this.#handleOf(pid))
2842
+ };
2843
+ }).catch((e) => {
2844
+ this.#discardPlaceholder(plug);
2845
+ throw e;
2846
+ });
2847
+ }
2848
+ placeMesh(target, stamp, options) {
2849
+ let added;
2850
+ return this.#ask((rev, qid) => {
2851
+ const stTarget = this.#live(target);
2852
+ const stStamp = this.#live(stamp);
2853
+ const n = normalizePlaceMeshArgs(options);
2854
+ const normals = checkBooleanArg(n.normals, stStamp.normalsOn, "options.normals");
2855
+ const cloned = copyInput(options, "options");
2856
+ this.#endDragOn(stTarget, stStamp);
2857
+ added = (options.mode ?? "keepSeparate") === "keepSeparate" ? this.#allocMeshState(stTarget.origin, normals) : void 0;
2858
+ return {
2859
+ kind: "placeMesh",
2860
+ rev,
2861
+ target: stTarget.id,
2862
+ stamp: stStamp.id,
2863
+ ...added === void 0 ? {} : { addedId: added.id },
2864
+ options: cloned,
2865
+ qid
2866
+ };
2867
+ }, (v) => {
2868
+ const r = v;
2869
+ if (added !== void 0 && r.added !== added.id) this.#discardPlaceholder(added);
2870
+ return {
2871
+ ...r,
2872
+ added: r.added === null ? null : this.#handleOf(r.added)
2873
+ };
2874
+ }).catch((e) => {
2875
+ this.#discardPlaceholder(added);
2876
+ throw e;
2877
+ });
2878
+ }
2879
+ #mapCollisionReport(r) {
2880
+ return {
2881
+ ...r,
2882
+ activePairs: r.activePairs.map((p) => ({
2883
+ ...p,
2884
+ other: this.#handleOf(p.other)
2885
+ })),
2886
+ modifiedMeshes: r.modifiedMeshes.map((id) => this.#handleOf(id))
2887
+ };
2888
+ }
2889
+ /** Undoes the latest step; an active drag is ended first. */
2890
+ undo() {
2891
+ this.#alive();
2892
+ this.#drag?.end();
2893
+ this.#stepDepth = 0;
2894
+ this.#forgetRequested();
2895
+ this.#push({
2896
+ kind: "undo",
2897
+ rev: ++this.#rev
2898
+ });
2899
+ this.#scheduleFlush();
2900
+ }
2901
+ /** Redoes the latest undone step; an active drag is ended first. */
2902
+ redo() {
2903
+ this.#alive();
2904
+ this.#drag?.end();
2905
+ this.#stepDepth = 0;
2906
+ this.#forgetRequested();
2907
+ this.#push({
2908
+ kind: "redo",
2909
+ rev: ++this.#rev
2910
+ });
2911
+ this.#scheduleFlush();
2912
+ }
2913
+ /** Closes an open step and drops every undo and redo step. */
2914
+ clearHistory() {
2915
+ this.#alive();
2916
+ this.#drag?.end();
2917
+ this.#stepDepth = 0;
2918
+ this.#forgetRequested();
2919
+ this.#push({
2920
+ kind: "clearHistory",
2921
+ rev: ++this.#rev
2922
+ });
2923
+ this.#scheduleFlush();
2924
+ }
2925
+ /**
2926
+ * Records an entry of the application's own in the history, after the
2927
+ * requests before it; see `Scene.recordEntry`. Its functions run here, on
2928
+ * this thread, as the result that undid, redid or dropped it is applied:
2929
+ * after the mirrors and before the promises the result settles and the
2930
+ * change records of the next {@link WorkerScene.commitFrame}.
2931
+ *
2932
+ * The history's order is that of the calls, whatever is in flight: an
2933
+ * `undo()` undoes what was recorded last when it was called, and the engine
2934
+ * says what that was. An entry recorded while an `undo()` or `redo()` is in
2935
+ * flight comes after it, and the undone entries' functions then run around
2936
+ * it (its `undo` before them, its `redo` after), so that every function
2937
+ * finds the application as the history has it. An entry that could not be
2938
+ * recorded is dropped, and so is every entry by a
2939
+ * {@link WorkerScene.restart}, which clears the history.
2940
+ *
2941
+ * @throws `INVALID_ARGUMENT` for an entry without `undo` and `redo`, or with
2942
+ * bytes below 0.
2943
+ */
2944
+ recordEntry(entry) {
2945
+ this.#alive();
2946
+ const { bytes, coalesce } = checkHistoryEntry(entry);
2947
+ const rev = ++this.#rev;
2948
+ const id = this.#entries.add(entry, rev);
2949
+ this.#push({
2950
+ kind: "entry",
2951
+ rev,
2952
+ id,
2953
+ bytes,
2954
+ ...coalesce === void 0 ? {} : { coalesce }
2955
+ });
2956
+ this.#scheduleFlush();
2957
+ }
2958
+ /** The most bytes the history may hold, as last set here. */
2959
+ get historyBudget() {
2960
+ return this.#init.historyBudget ?? 268435456;
2961
+ }
2962
+ /**
2963
+ * Changes the most bytes the history may hold, after the requests before
2964
+ * it; see `Scene.setHistoryBudget`. A {@link WorkerScene.restart} keeps it.
2965
+ *
2966
+ * @throws `INVALID_ARGUMENT` for anything but a number, 0 or more.
2967
+ */
2968
+ setHistoryBudget(bytes) {
2969
+ this.#alive();
2970
+ const budget = checkHistoryBudget(bytes);
2971
+ this.#init = {
2972
+ ...this.#init,
2973
+ historyBudget: budget
2974
+ };
2975
+ this.#push({
2976
+ kind: "historyBudget",
2977
+ rev: ++this.#rev,
2978
+ bytes: budget
2979
+ });
2980
+ this.#scheduleFlush();
2981
+ }
2982
+ /** The bytes the history holds, as of the latest result. */
2983
+ get historyBytes() {
2984
+ return this.#historyBytes;
2985
+ }
2986
+ /**
2987
+ * Registers a listener called with each step the history could not keep
2988
+ * (an action that is permanent, or one that cannot be redone), as its
2989
+ * result is applied, before the promises it settles; see
2990
+ * `Scene.onPermanent`. Returns the function that removes it.
2991
+ */
2992
+ onPermanent(listener) {
2993
+ this.#permanentListeners.add(listener);
2994
+ return () => {
2995
+ this.#permanentListeners.delete(listener);
2996
+ };
2997
+ }
2998
+ /**
2999
+ * Opens a history step, or one more nesting level of the open one. Edits,
3000
+ * repairs, and placement changes until the matching {@link WorkerScene.endStep}
3001
+ * are coalesced into a single undo entry.
3002
+ */
3003
+ beginStep() {
3004
+ this.#alive();
3005
+ this.#stepDepth++;
3006
+ this.#push({
3007
+ kind: "step",
3008
+ rev: ++this.#rev,
3009
+ phase: "begin"
3010
+ });
3011
+ this.#scheduleFlush();
3012
+ }
3013
+ /** Ends one nesting level of the open step. Throws `STEP_NOT_OPEN` when none is open. */
3014
+ endStep() {
3015
+ this.#alive();
3016
+ if (this.#stepDepth === 0) throw new FastMeshError("STEP_NOT_OPEN", "no history step is open");
3017
+ const closingDrag = this.#drag !== void 0 && this.#stepDepth <= this.#drag.stepDepth;
3018
+ const rev = this.#push({
3019
+ kind: "step",
3020
+ rev: ++this.#rev,
3021
+ phase: "end"
3022
+ });
3023
+ this.#stepDepth--;
3024
+ if (closingDrag && this.#drag !== void 0) this.#drag.abandon(rev, false);
3025
+ this.#scheduleFlush();
3026
+ }
3027
+ /** Reverts and discards the open step, however deeply nested. Throws `STEP_NOT_OPEN` when none is open. */
3028
+ cancelStep() {
3029
+ this.#alive();
3030
+ if (this.#stepDepth === 0) throw new FastMeshError("STEP_NOT_OPEN", "no history step is open");
3031
+ const rev = this.#push({
3032
+ kind: "step",
3033
+ rev: ++this.#rev,
3034
+ phase: "cancel"
3035
+ });
3036
+ this.#stepDepth = 0;
3037
+ this.#drag?.abandon(rev, true);
3038
+ this.#forgetRequested();
3039
+ this.#scheduleFlush();
3040
+ }
3041
+ /**
3042
+ * An undo or redo is queued: requested placements and the poses held for
3043
+ * ended drags no longer say where the meshes will be. The engine's pose is
3044
+ * shown (and a new drag starts from it) until the results arrive.
3045
+ */
3046
+ #forgetRequested() {
3047
+ for (const st of this.#meshes.values()) {
3048
+ st.requested = void 0;
3049
+ if (st.local !== void 0 && st.localUntil !== Number.POSITIVE_INFINITY) {
3050
+ if (!samePose(st.local, st.pose)) this.#optimistic.add(st);
1392
3051
  st.local = void 0;
1393
3052
  st.localUntil = 0;
1394
3053
  }
@@ -1410,7 +3069,34 @@ var WorkerScene = class WorkerScene {
1410
3069
  get canRedo() {
1411
3070
  return this.#history.canRedo;
1412
3071
  }
1413
- /** Adds a signed distance field; see `Scene.addDistanceField`. */
3072
+ /**
3073
+ * Generates a primitive shape in the Worker, as the standalone
3074
+ * `generatePrimitive` does on a thread with the module initialised; the
3075
+ * buffers are transferred back, and the scene is not touched. The shape is
3076
+ * checked by type here, its ranges in the Worker.
3077
+ *
3078
+ * @throws (rejects) `INVALID_ARGUMENT` for an unknown kind or a parameter
3079
+ * out of range; `OUT_OF_MEMORY` when the buffers cannot be allocated.
3080
+ */
3081
+ generatePrimitive(shape) {
3082
+ return this.#query("generatePrimitive", () => encodePrimitive(shape), (v) => v);
3083
+ }
3084
+ /**
3085
+ * Generates the relief of a grid of heights in the Worker, as the standalone
3086
+ * `generateHeightfield` does on a thread with the module initialised; the
3087
+ * buffers are transferred back, and the scene is not touched.
3088
+ *
3089
+ * @throws (rejects) `INVALID_ARGUMENT` for a grid out of range;
3090
+ * `OUT_OF_MEMORY` when the buffers cannot be allocated.
3091
+ */
3092
+ generateHeightfield(field) {
3093
+ return this.#query("generateHeightfield", () => checkHeightfield(field), (v) => v);
3094
+ }
3095
+ /**
3096
+ * Adds a signed distance field; see `Scene.addDistanceField`.
3097
+ *
3098
+ * @deprecated Use `workerScene.inspect.addDistanceField()` instead.
3099
+ */
1414
3100
  addDistanceField(desc) {
1415
3101
  return this.#addField(desc, void 0);
1416
3102
  }
@@ -1686,7 +3372,11 @@ var WorkerScene = class WorkerScene {
1686
3372
  b: this.#live(b).id
1687
3373
  }), (v) => v);
1688
3374
  }
1689
- /** The nearest hit of a world ray over every mesh, or `null`; see `Scene.raycast`. */
3375
+ /**
3376
+ * The nearest hit of a world ray over every mesh, or `null`; see `Scene.raycast`.
3377
+ *
3378
+ * @deprecated Use `workerScene.inspect.raycast()` instead.
3379
+ */
1690
3380
  raycast(origin, direction, options) {
1691
3381
  return this.#query("raycast", () => ({
1692
3382
  origin: [...origin],
@@ -1697,7 +3387,11 @@ var WorkerScene = class WorkerScene {
1697
3387
  mesh: this.#handleOf(v.mesh)
1698
3388
  });
1699
3389
  }
1700
- /** The surface point nearest to a world point, or `null`; see `Scene.closestPoint`. */
3390
+ /**
3391
+ * The surface point nearest to a world point, or `null`; see `Scene.closestPoint`.
3392
+ *
3393
+ * @deprecated Use `workerScene.inspect.closestPoint()` instead.
3394
+ */
1701
3395
  closestPoint(point, options = {}) {
1702
3396
  return this.#query("closestPoint", () => ({
1703
3397
  point: [...point],
@@ -1710,7 +3404,11 @@ var WorkerScene = class WorkerScene {
1710
3404
  mesh: this.#handleOf(v.mesh)
1711
3405
  });
1712
3406
  }
1713
- /** The distance between two meshes' surfaces, or `null`; see `Scene.meshDistance`. */
3407
+ /**
3408
+ * The distance between two meshes' surfaces, or `null`; see `Scene.meshDistance`.
3409
+ *
3410
+ * @deprecated Use `workerScene.inspect.meshDistance()` instead.
3411
+ */
1714
3412
  meshDistance(a, b, options) {
1715
3413
  return this.#query("meshDistance", () => ({
1716
3414
  a: this.#live(a).id,
@@ -1718,14 +3416,29 @@ var WorkerScene = class WorkerScene {
1718
3416
  options
1719
3417
  }), (v) => v);
1720
3418
  }
1721
- /** Whether two meshes intersect or touch as placed. */
3419
+ /**
3420
+ * Whether two meshes intersect or touch as placed.
3421
+ *
3422
+ * @deprecated Use `workerScene.inspect.intersects()` instead.
3423
+ */
1722
3424
  intersects(a, b) {
1723
3425
  return this.#query("intersects", () => ({
1724
3426
  a: this.#live(a).id,
1725
3427
  b: this.#live(b).id
1726
3428
  }), (v) => v);
1727
3429
  }
1728
- /** Every mesh pair (or every pair of `pairs`) within `margin`; see `Scene.findContacts`. */
3430
+ /**
3431
+ * The live triangle slots of `mesh` that intersect or touch another of its
3432
+ * own triangles, ascending; see `Scene.selfIntersectingTriangles`.
3433
+ */
3434
+ selfIntersectingTriangles(mesh) {
3435
+ return this.#query("selfIntersectingTriangles", () => ({ mesh: this.#live(mesh).id }), (v) => v);
3436
+ }
3437
+ /**
3438
+ * Every mesh pair (or every pair of `pairs`) within `margin`; see `Scene.findContacts`.
3439
+ *
3440
+ * @deprecated Use `workerScene.inspect.findContacts()` instead.
3441
+ */
1729
3442
  findContacts(options = {}) {
1730
3443
  return this.#query("findContacts", () => ({
1731
3444
  margin: options.margin,
@@ -1789,19 +3502,7 @@ var WorkerScene = class WorkerScene {
1789
3502
  const st = this.#byMesh.get(c.mesh);
1790
3503
  if (st === void 0) continue;
1791
3504
  st.gone = true;
1792
- if (st.removed) {
1793
- this.#meshes.delete(st.id);
1794
- this.#byMesh.delete(st.handle);
1795
- this.#tombstones.add(st.handle);
1796
- const id = st.id;
1797
- this.#forgetKeys([
1798
- `mesh:${id}`,
1799
- `placement:${id}`,
1800
- `edit:${id}`,
1801
- `display:${id}`
1802
- ], []);
1803
- this.#statusChanged();
1804
- }
3505
+ if (st.removed && !st.parked) this.#forgetMesh(st);
1805
3506
  }
1806
3507
  let failure;
1807
3508
  for (const listener of [...this.#listeners]) try {
@@ -1864,7 +3565,8 @@ var WorkerScene = class WorkerScene {
1864
3565
  * - fields, colourings and sections as last requested (removed ones are
1865
3566
  * not re-created).
1866
3567
  *
1867
- * History is cleared (`canUndo`/`canRedo` are false). The replay is sent
3568
+ * History is cleared (`canUndo`/`canRedo` are false), and the meshes it
3569
+ * could have brought back are gone for good. The replay is sent
1868
3570
  * at once, not with the next frame. Every replayed key is `"computing"`
1869
3571
  * until the replay's results arrive, and so is the key of every pending
1870
3572
  * declarative request (placement, drag, colouring, field, section), also
@@ -1994,6 +3696,7 @@ var WorkerScene = class WorkerScene {
1994
3696
  this.#drag.active = false;
1995
3697
  this.#drag = void 0;
1996
3698
  }
3699
+ this.#stepDepth = 0;
1997
3700
  for (const st of this.#meshes.values()) {
1998
3701
  if (!samePose(this.#shown(st), poses.get(st))) this.#optimistic.add(st);
1999
3702
  st.local = void 0;
@@ -2034,6 +3737,8 @@ var WorkerScene = class WorkerScene {
2034
3737
  canUndo: false,
2035
3738
  canRedo: false
2036
3739
  };
3740
+ this.#historyBytes = 0;
3741
+ this.#entries.dropAll();
2037
3742
  this.#statusChanged();
2038
3743
  const first = this.#rev + 1;
2039
3744
  if (this.#values) this.#push({
@@ -2041,6 +3746,11 @@ var WorkerScene = class WorkerScene {
2041
3746
  rev: ++this.#rev
2042
3747
  });
2043
3748
  const replayed = /* @__PURE__ */ new Set();
3749
+ for (const st of [...this.#meshes.values()].filter((m) => m.parked)) {
3750
+ st.parked = false;
3751
+ this.#dropFieldsOf(st, this.#rev);
3752
+ if (st.gone) this.#forgetMesh(st);
3753
+ }
2044
3754
  for (const st of this.#meshes.values()) {
2045
3755
  if (st.removed) {
2046
3756
  if (!st.gone) {
@@ -2163,6 +3873,19 @@ var WorkerScene = class WorkerScene {
2163
3873
  desc
2164
3874
  });
2165
3875
  }
3876
+ this.#push({
3877
+ kind: "setDefaultCollisionRule",
3878
+ rev: ++this.#rev,
3879
+ rule: { ...this.#defaultCollisionRule }
3880
+ });
3881
+ for (const [key, entry] of [...this.#collisionRules.entries()]) if (!entry.a.removed && !entry.b.removed && replayed.has(entry.a.id) && replayed.has(entry.b.id)) this.#push({
3882
+ kind: "setCollisionRule",
3883
+ rev: ++this.#rev,
3884
+ a: entry.a.id,
3885
+ b: entry.b.id,
3886
+ rule: { ...entry.rule }
3887
+ });
3888
+ else if (!replayed.has(entry.a.id) || !replayed.has(entry.b.id)) this.#collisionRules.delete(key);
2166
3889
  const rev = this.#push({
2167
3890
  kind: "clearHistory",
2168
3891
  rev: ++this.#rev
@@ -2196,6 +3919,7 @@ var WorkerScene = class WorkerScene {
2196
3919
  mesh: st.handle,
2197
3920
  added: false,
2198
3921
  removed: true,
3922
+ ...st.parked ? { restorable: true } : {},
2199
3923
  placementChanged: false,
2200
3924
  capacityChanged: false,
2201
3925
  positions: [],
@@ -2223,6 +3947,7 @@ var WorkerScene = class WorkerScene {
2223
3947
  this.#drag.active = false;
2224
3948
  this.#drag = void 0;
2225
3949
  }
3950
+ this.#stepDepth = 0;
2226
3951
  this.#worker.terminate();
2227
3952
  this.#unwatch();
2228
3953
  this.#dropHandoff();
@@ -2236,6 +3961,7 @@ var WorkerScene = class WorkerScene {
2236
3961
  this.#batchDone.clear();
2237
3962
  this.#queue = [];
2238
3963
  this.#inflight.length = 0;
3964
+ this.#entries.dropAll();
2239
3965
  }
2240
3966
  static {
2241
3967
  createScene = (make, options) => {
@@ -2249,6 +3975,13 @@ var WorkerScene = class WorkerScene {
2249
3975
  scene.#statusSinks.delete(sink);
2250
3976
  };
2251
3977
  };
3978
+ fieldTargetsOf = (scene, field) => {
3979
+ const st = scene.#byField.get(field);
3980
+ if (st === void 0 || st.removed) return null;
3981
+ return st.desc.to.flatMap((id) => scene.#meshes.get(id)?.handle ?? []);
3982
+ };
3983
+ sectionMeshesOf = (scene, section) => scene.#bySection.get(section)?.meshes.map((m) => m.handle) ?? [];
3984
+ presenceVersionOf = (scene) => scene.#presenceVersion;
2252
3985
  }
2253
3986
  };
2254
3987
  /**
@@ -2271,6 +4004,25 @@ function watchStatusKeys(scene, sink) {
2271
4004
  return watchStatusKeysOf(scene, sink);
2272
4005
  }
2273
4006
  /**
4007
+ * Internal, not exported from `fast-mesh-wasm/worker`: the targets a field is
4008
+ * left with as of the latest result, or `null` for one that is gone.
4009
+ */
4010
+ function fieldTargets(scene, field) {
4011
+ return fieldTargetsOf(scene, field);
4012
+ }
4013
+ /** Internal, not exported from `fast-mesh-wasm/worker`: the meshes a section cuts, as of the latest result. */
4014
+ function sectionMeshes(scene, section) {
4015
+ return sectionMeshesOf(scene, section);
4016
+ }
4017
+ /**
4018
+ * Internal, not exported from `fast-mesh-wasm/worker`: goes up with every
4019
+ * result that says where undoable adds and removals moved meshes. `onStatus`
4020
+ * listeners are called for it.
4021
+ */
4022
+ function presenceVersion(scene) {
4023
+ return presenceVersionOf(scene);
4024
+ }
4025
+ /**
2274
4026
  * A deep copy of a caller's request input (edit ops, repair ops), taken at
2275
4027
  * call time so later changes to it do not leak into the request.
2276
4028
  */
@@ -2296,6 +4048,31 @@ function copyArray(value, what, copy) {
2296
4048
  * slot order, as world positions before placement (local plus origin, in
2297
4049
  * `f64`, so the engine gets the same `f32` local positions back).
2298
4050
  */
4051
+ function cloneBounds(b) {
4052
+ if (b === null) return null;
4053
+ return {
4054
+ min: [
4055
+ b.min[0],
4056
+ b.min[1],
4057
+ b.min[2]
4058
+ ],
4059
+ max: [
4060
+ b.max[0],
4061
+ b.max[1],
4062
+ b.max[2]
4063
+ ],
4064
+ center: [
4065
+ b.center[0],
4066
+ b.center[1],
4067
+ b.center[2]
4068
+ ],
4069
+ size: [
4070
+ b.size[0],
4071
+ b.size[1],
4072
+ b.size[2]
4073
+ ]
4074
+ };
4075
+ }
2299
4076
  function liveGeometry(st) {
2300
4077
  const idx = st.indices;
2301
4078
  const p = st.positions;
@@ -2352,6 +4129,10 @@ function merge(a, b) {
2352
4129
  };
2353
4130
  if (b.added) return {
2354
4131
  ...b,
4132
+ ...a.removed ? {
4133
+ placementChanged: true,
4134
+ capacityChanged: true
4135
+ } : {},
2355
4136
  fieldsChanged: union(a.fieldsChanged, b.fieldsChanged),
2356
4137
  sectionsChanged: union(a.sectionsChanged, b.sectionsChanged)
2357
4138
  };
@@ -2395,6 +4176,9 @@ function checkPlane(plane) {
2395
4176
  normal
2396
4177
  };
2397
4178
  }
4179
+ function collisionPairKey(a, b) {
4180
+ return a < b ? `${a}:${b}` : `${b}:${a}`;
4181
+ }
2398
4182
  /**
2399
4183
  * A checked plane with its normal normalised. Scaled by its largest
2400
4184
  * component first, so a huge finite normal (whose length overflows) or a
@@ -2417,4 +4201,4 @@ function normalised(plane) {
2417
4201
  ]
2418
4202
  };
2419
4203
  }
2420
- export { watchStatusKeys as a, createWorkerScene as i, WorkerScene as n, addFieldKeyed as r, MAX_THREADS as t };
4204
+ export { fieldTargets as a, watchStatusKeys as c, createWorkerScene as i, WorkerScene as n, presenceVersion as o, addFieldKeyed as r, sectionMeshes as s, MAX_THREADS as t };