fast-mesh-wasm 0.3.1 → 0.4.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 (38) hide show
  1. package/README.md +5 -2
  2. package/dist/{client-Bp9FRd70.js → client-Bpjy-eFY.js} +1 -1
  3. package/dist/{client-m2zSdFlu.d.ts → client-D-O5-tAg.d.ts} +2 -2
  4. package/dist/{colormap-D_xH5hI5.js → colormap-DxGMYVfs.js} +1 -1
  5. package/dist/{engine-BpnthBYQ.js → engine-D6MpGb9i.js} +36 -10
  6. package/dist/{mesh-B16gV3oX.d.ts → mesh-BUVxv3jo.d.ts} +8 -1
  7. package/dist/{mesh-B8pae8WA.js → mesh-zj7-wJBw.js} +52 -5
  8. package/dist/node.d.ts +2 -2
  9. package/dist/node.js +1 -1
  10. package/dist/{protocol-W9R-iGl5.d.ts → protocol-CK6_3aqo.d.ts} +1 -1
  11. package/dist/r3f.d.ts +3 -3
  12. package/dist/r3f.js +2 -2
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{scene-BFd6nYRe.js → scene-D6m9XM3O.js} +98 -12
  15. package/dist/{scene-like-B_3qm0u6.d.ts → scene-like-DJKQP5uf.d.ts} +46 -5
  16. package/dist/{store-D3ErV6o-.js → store-Ml3TQGsR.js} +2 -2
  17. package/dist/{store-DNnHN33A.d.ts → store-QWRDXlAn.d.ts} +2 -2
  18. package/dist/store.d.ts +2 -2
  19. package/dist/store.js +1 -1
  20. package/dist/three.d.ts +7 -6
  21. package/dist/three.js +7 -2
  22. package/dist/{views-BaZqBxlX.js → views-Dh3aWc2q.js} +1 -1
  23. package/dist/wasm/fast_mesh_wasm.d.ts +44 -12
  24. package/dist/wasm/fast_mesh_wasm.js +82 -20
  25. package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
  26. package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +5 -1
  27. package/dist/wasm-threads/fast_mesh_wasm.d.ts +44 -12
  28. package/dist/wasm-threads/fast_mesh_wasm.js +82 -20
  29. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm +0 -0
  30. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm.d.ts +5 -1
  31. package/dist/web.d.ts +2 -2
  32. package/dist/web.js +1 -1
  33. package/dist/worker-engine.d.ts +7 -5
  34. package/dist/worker-engine.js +1 -1
  35. package/dist/worker-entry.js +1 -1
  36. package/dist/worker.d.ts +1 -1
  37. package/dist/worker.js +1 -1
  38. package/package.json +1 -1
package/README.md CHANGED
@@ -106,6 +106,9 @@ requestAnimationFrame(frame);
106
106
  - The engine's colour maps are sRGB-encoded bytes. The adapter converts them to three's linear working space as it copies them (a normalized `Uint16` colour attribute), so they look the same as in a renderer that passes the bytes through to a non-sRGB canvas.
107
107
  - A material you pass to `bindMesh` is used as given and must not be shared between bound meshes (the adapter controls its `color`, `vertexColors`, `opacity`, `transparent` and `depthWrite`). With `shading: "fragment"` it also patches the material's shaders and disposes its compiled program on bind and on restore (see [Fragment shading](#fragment-shading)).
108
108
  - The adapter only reads `scene.onChanges`; it never calls `takeChanges`.
109
+ - Bound meshes take their bounding box and sphere from the scene's live-vertex bounds (see `Scene.bounds`), recomputed only when positions or indices change; on a host without them the adapter walks the mirrors instead.
110
+ - Bound objects (and section groups) must sit under an untransformed parent: their matrices are driven as world matrices, so a transformed ancestor offsets them and is warned about once.
111
+ - With `new Scene({ debug: true })`, the views the adapter copies from are checked `Proxy` objects (see the Scene API section for their cost); the mirrors it uploads are always plain typed arrays.
109
112
 
110
113
  #### Fragment shading
111
114
 
@@ -149,7 +152,7 @@ colour(gap);
149
152
 
150
153
  // Drag the lower mesh. The whole drag is one undo step. Each `move`
151
154
  // recomputes the eager fields, so coalesce pointer events to one `move` per
152
- // animation frame.
155
+ // animation frame (`scene.drag(mesh, { coalesce: true })` does that for you).
153
156
  const drag = scene.drag(lower);
154
157
  let pending: { rotation: Quat; translation: Vec3 } | undefined;
155
158
  function onPointerMove(rotation: Quat, translation: Vec3) {
@@ -294,7 +297,7 @@ const values = await scene.fetchFieldValues(gap); // `fieldValues` on Scene
294
297
  - **Errors.** A failed state change shows on its key (`status(key).error`, a `FastMeshError` with the same `code` as on `Scene`); a failed promise rejects with it. After a trap inside the Worker every call fails with `INSTANCE_POISONED`, also when it happens on one of the multithreaded engine's pool threads (a panic or a trap in work split across threads); a few kinds of pool-thread failure still cannot be detected (see [Multithreading (COOP/COEP)](#multithreading-coopcoep)). `await scene.restart()` starts a new Worker and replays the scene from the main thread's mirrors: meshes (compacted: slot ids change, handles do not), placements, fields, colourings and sections. History is cleared, and edits or queries that had not finished fail and must be re-issued.
295
298
  - **Not in the Worker scene:** user-opened steps (`beginStep`/`endStep`/`cancelStep`), Lazy and Manual modes (it is always eager) and `takeChanges` (use `onChanges` or the return value of `commitFrame()`). `terminate()` stops the Worker.
296
299
  - **Large meshes.** `addMesh` copies its inputs on the main thread (they are then transferred to the Worker) and, without an `origin` option, scans the positions for the bounding-box centre. That takes about 9 ms for 1M triangles and about 63 ms for 10M (see [docs/benchmarks.md](docs/benchmarks.md)); passing `origin` skips the scan.
297
- - **Large meshes are added in the background.** A mesh of 65,536 triangles or more is built in steps inside the Worker, its normals and the copy of its buffers for the main thread included (about 1.1 s at 1M and 12 s at 10M, single-threaded) while the requests sent after it that do not need it run: toggles, edits, drags and queries of other meshes are answered within milliseconds instead of waiting. A request that names the new mesh (or a field not built yet that is measured on or to it), adds or removes a mesh, or queries every mesh (`raycast`, `closestPoint` without a mesh, `findContacts` without pairs) waits for it and finishes it first (in one call on a threaded engine, in steps that still yield on a single-threaded one), so the engine's state is the same as running the requests in order. Replies can come in another order, though: until the mesh lands, `status("mesh:<id>")` reads `"computing"` and its views are empty; its buffers arrive with that status turning `"ready"`, so a reply to an unrelated request sent after the add can arrive first. `createWorkerScene({ backgroundAddTriangles })` sets the threshold; `Infinity` turns background adds off (every add then comes back with its own batch's result).
300
+ - **Large meshes are added in the background.** A mesh of 65,536 triangles or more is built in steps inside the Worker, its upload, store build, normals and the copy of its buffers for the main thread included (about 1.1 s at 1M and 12 s at 10M, single-threaded) while the requests sent after it that do not need it run: toggles, edits, drags and queries of other meshes are answered within milliseconds instead of waiting. A request that names the new mesh (or a field not built yet that is measured on or to it), adds or removes a mesh, or queries every mesh (`raycast`, `closestPoint` without a mesh, `findContacts` without pairs) waits for it and finishes it first (in one call on a threaded engine, in steps that still yield on a single-threaded one), so the engine's state is the same as running the requests in order. Replies can come in another order, though: until the mesh lands, `status("mesh:<id>")` reads `"computing"` and its views are empty; its buffers arrive with that status turning `"ready"`, so a reply to an unrelated request sent after the add can arrive first. `createWorkerScene({ backgroundAddTriangles })` sets the threshold; `Infinity` turns background adds off (every add then comes back with its own batch's result).
298
301
 
299
302
  **Bundlers.** The Worker script is a separate file, `worker-entry.js`, loaded with `new Worker(new URL("./worker-entry.js", import.meta.url), { type: "module" })`. Vite and other bundlers that understand this pattern pick it up and emit it with the `.wasm` it loads: [`examples/webgpu`](examples/webgpu) uses the default with Vite, in both `vite build` and `vite dev` (open it with `?worker`). If your setup does not handle the pattern, serve the package's `dist/` folder (the Worker script loads the files next to it) and pass the script's URL, or create the Worker yourself:
300
303
 
@@ -1,5 +1,5 @@
1
1
  import { o as reportListenerError, t as FastMeshError } from "./core-Cke_kZ2e.js";
2
- import { a as FieldHandle, c as rotationMatrix, l as targetsOf, o as MeshHandle, r as copyRule, s as SectionHandle, t as ViewGuard } from "./views-BaZqBxlX.js";
2
+ import { a as FieldHandle, c as rotationMatrix, l as targetsOf, o as MeshHandle, r as copyRule, s as SectionHandle, t as ViewGuard } from "./views-Dh3aWc2q.js";
3
3
  import { a as supersedes, n as isLastWins, r as keyOf } from "./protocol-CAUYm1gd.js";
4
4
  //#region src/worker/client.ts
5
5
  /**
@@ -1,6 +1,6 @@
1
- import { $ as PlacementInput, A as RepairOp, B as SectionResult, D as RayHit, G as SectionHandle, L as SectionDesc, M as RepairReportOf, O as RaycastOptions, Q as Placement, R as SectionGap, S as MeshChange, U as FieldHandle, W as MeshHandle, Y as Indices, _ as FieldStatus, b as FindContactsOptions, c as ColorRule, f as DistanceFieldDesc, g as EditResult, i as AnalyzeOptions, it as Vec3, m as EditOp, n as AddMeshOptions, o as ClosestHit, p as DragSession, q as MeshViews, r as Analysis, s as ClosestPointOptions, t as SceneLike, tt as Positions64, u as Contact, w as MeshDistance, z as SectionPlane } from "./scene-like-B_3qm0u6.js";
1
+ import { $ as Placement, B as SectionPlane, C as MeshChange, G as MeshHandle, J as MeshViews, K as SectionHandle, N as RepairReportOf, O as RayHit, R as SectionDesc, T as MeshDistance, V as SectionResult, W as FieldHandle, X as Indices, _ as EditResult, at as Vec3, c as ColorRule, et as PlacementInput, f as DistanceFieldDesc, h as EditOp, i as AnalyzeOptions, j as RepairOp, k as RaycastOptions, m as DragSession, n as AddMeshOptions, nt as Positions64, o as ClosestHit, r as Analysis, s as ClosestPointOptions, t as SceneLike, u as Contact, v as FieldStatus, x as FindContactsOptions, z as SectionGap } from "./scene-like-DJKQP5uf.js";
2
2
  import { t as FastMeshError } from "./core-D2X9GPfK.js";
3
- import "./protocol-W9R-iGl5.js";
3
+ import "./protocol-CK6_3aqo.js";
4
4
  //#region src/worker/client.d.ts
5
5
  /** What {@link WorkerScene} needs of a Worker; a browser `Worker` fits. */
6
6
  interface WorkerLike {
@@ -36,7 +36,7 @@ const SRGB_TO_LINEAR16 = (() => {
36
36
  * engine). Grayscale is `(i, i, i)`.
37
37
  */
38
38
  const TABLES = {
39
- turbo: "IxcbJxooKxw0Lx4/MyBKNiNVOSVfOyhpPipyQCx7Qi+ERDGMRTSURzebSDmiSTypST6vSkG1SkS7S0bBS0nGS0zLS0/PSlHTSlTXSlfbSVnfSVziSF/lR2LoRmXqRWftRGrvQ23wQnDyQXL0QHX1P3j2Pnv3PX34O4D4OoP5OYb5OIj5N4v5NY75NJD4M5P4Mpb3MZj2MJv2L571LqD0LaPyLKXxK6jwKqruKq3tKa/rKLLqKLToJ7bmJ7nkJrviJr3gJcDeJcLc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+psT+qMX+qcb+qsf9rMj9rcn9rsn8sMr8scv8ssz7s837tc76ts76t8/5udD5utH4u9H4vNL3vtP2v9P2wNT1wdT0w9X0xNbzxdbyxtfxyNfxydjwytjvy9juzNntzdnsztrr0Nrq0drp0tvo09vn1Nvm1dvl1tzk19zj2Nzi2dzh2tzg293e3N3d3dzc3tzb39zZ4dvY4trW49rV5NnT5dnS5djR5tjP59fO6NbM6dbL6tXJ69TI69PG7NPF7dLD7tHC7tDA78+/78698M688c268cy48su38sq188m088iy9Mex9Mav9MWu9cSs9cOq9cGp9sCn9r+m9r6k9r2i97yh97qf97me97ic97eb97WZ97SX97OW97KU97CT96+R962Q96yO96uM96mL96iJ96aI9qWG9qOF9qKD9qCB9Z+A9Z1+9Zx99Jp79Jl69Jd485V385R18pJ08pBy8Y9x8Y1v8Itu8Ips74hr74Zp7oVo7YNm7YFl7H9j631i6nxg6npf6Xhd6HZc53Ra5nJZ5XBY5W9W5G1V42tT4mlS4WdR4GVP32NO3mFN3V9L3F1K21tJ2llH2FZG11RF1lJD1VBC1E5B00xA0Uk+0Ec9z0U8zkM7zEA5yz44yjs3yDk2xzY0xjQzxDEywy4xwSswwCgvvyUuvSIsvB4ruhoquRYptxEotgsntAQm"
42
42
  };
@@ -1,5 +1,5 @@
1
1
  import { s as setMemory, t as FastMeshError } from "./core-Cke_kZ2e.js";
2
- import { i as useWasmScene, n as fieldSteps, r as meshAdds, t as Scene } from "./scene-BFd6nYRe.js";
2
+ import { i as useWasmScene, n as fieldSteps, r as meshAdds, t as Scene } from "./scene-D6m9XM3O.js";
3
3
  import { a as supersedes, n as isLastWins, r as keyOf, t as isInit } from "./protocol-CAUYm1gd.js";
4
4
  /**
5
5
  * A module importing a shared memory `e.m` (1 page, at most 2), exporting
@@ -342,6 +342,8 @@ const ADD_STEP_WORK = 1e5;
342
342
  const ALL_POINTS = 4294967295;
343
343
  /** Bytes of a background add's render buffers copied per unit of {@link EngineOptions.addStepWork}. */
344
344
  const PACK_BYTES_PER_UNIT = 64;
345
+ /** Bytes of a background add's positions and indices uploaded per unit of {@link EngineOptions.addStepWork}. */
346
+ const UPLOAD_BYTES_PER_UNIT = 64;
345
347
  const now = typeof performance !== "undefined" && typeof performance.now === "function" ? () => performance.now() : () => Date.now();
346
348
  /**
347
349
  * Runs the engine on `port` until the instance traps. The WebAssembly module
@@ -758,7 +760,7 @@ var Engine = class {
758
760
  this.#unpack(req);
759
761
  try {
760
762
  if (req.kind === "addMesh" && this.#inBackground(req)) {
761
- this.#beginAdd(req);
763
+ await this.#beginAdd(req);
762
764
  this.#onChunk?.({
763
765
  kind: "addMeshBegin",
764
766
  id: req.id
@@ -798,20 +800,44 @@ var Engine = class {
798
800
  return this.#port.postUpdate !== void 0 && req.inline !== true && req.indices.byteLength / 12 >= this.#backgroundAdd;
799
801
  }
800
802
  /**
801
- * Starts adding a mesh in the background: the mesh and its BVH are built
802
- * outside the scene, a step at a time between other chunks and while the
803
- * Worker is idle, and it lands in the scene when built, in arrival order
804
- * with the other background adds. Until then its status is held, and a
805
- * request that depends on it ({@link Engine.#dependsOnAdds}) first
806
- * finishes every background add; other requests run meanwhile.
803
+ * Starts adding a mesh in the background: its inputs upload into wasm
804
+ * memory in chunks, yielding between them, then the mesh, its BVH and
805
+ * its normals are built outside the scene, a step at a time between
806
+ * other chunks and while the Worker is idle, and it lands in the scene
807
+ * when built, in arrival order with the other background adds. Until
808
+ * then its status is held, and a request that depends on it
809
+ * ({@link Engine.#dependsOnAdds}) first finishes every background add;
810
+ * other requests run meanwhile.
807
811
  */
808
- #beginAdd(req) {
812
+ async #beginAdd(req) {
809
813
  if (this.#meshes.has(req.id) || this.#adds.some((a) => a.id === req.id)) throw invalid(`mesh client id ${req.id} is already in use`);
810
814
  const positions = req.f64 ? new Float64Array(req.positions) : new Float32Array(req.positions);
811
- const token = this.#meshAdds.begin(positions, new Uint32Array(req.indices), {
815
+ const indices = new Uint32Array(req.indices);
816
+ if (positions.length % 3 !== 0) throw invalid("positions length must be a multiple of 3");
817
+ if (indices.length % 3 !== 0) throw invalid("indices length must be a multiple of 3");
818
+ const token = this.#meshAdds.beginUpload(positions.length / 3, indices.length / 3, {
812
819
  ...req.options,
813
820
  mode: "eager"
814
821
  });
822
+ try {
823
+ const bytes = this.#addStepWork * UPLOAD_BYTES_PER_UNIT;
824
+ const p = Math.max(1, Math.floor(bytes / positions.BYTES_PER_ELEMENT));
825
+ const n = Math.max(1, Math.floor(bytes / indices.BYTES_PER_ELEMENT));
826
+ for (let at = 0; at < positions.length; at += p) {
827
+ const chunk = positions.subarray(at, at + p);
828
+ this.#meshAdds.pushPositions(token, chunk instanceof Float64Array ? chunk : Float64Array.from(chunk));
829
+ await this.#maybeYield();
830
+ }
831
+ for (let at = 0; at < indices.length; at += n) {
832
+ this.#meshAdds.pushIndices(token, indices.subarray(at, at + n));
833
+ await this.#maybeYield();
834
+ }
835
+ } catch (e) {
836
+ try {
837
+ this.#meshAdds.drop(token);
838
+ } catch {}
839
+ throw e;
840
+ }
815
841
  this.#adds.push({
816
842
  id: req.id,
817
843
  token,
@@ -1,4 +1,4 @@
1
- import { W as MeshHandle, t as SceneLike } from "./scene-like-B_3qm0u6.js";
1
+ import { G as MeshHandle, t as SceneLike } from "./scene-like-DJKQP5uf.js";
2
2
  import * as THREE from "three";
3
3
  //#region src/three/mesh.d.ts
4
4
  /** Options of {@link bindMesh}. */
@@ -122,6 +122,13 @@ type MeshBinding = Pick<BoundMesh, "mesh" | "object">;
122
122
  * the scene and leaves the object as it was (remove it from your THREE.Scene
123
123
  * and call {@link BoundMesh.dispose}).
124
124
  *
125
+ * The object must sit under an untransformed parent (its `matrix` is a world
126
+ * matrix); a transformed ancestor is detected and warned about once.
127
+ *
128
+ * With a debug scene (`new Scene({ debug: true })`), the views the binding
129
+ * copies from are checked `Proxy` objects (see `SceneOptions.debug` for
130
+ * their cost); the mirrors it uploads are always plain typed arrays.
131
+ *
125
132
  * The adapter only listens through {@link SceneLike.onChanges}: call
126
133
  * `scene.commitFrame()` once per animation frame, before rendering.
127
134
  */
@@ -1,5 +1,5 @@
1
1
  import { t as FastMeshError } from "./core-Cke_kZ2e.js";
2
- import { a as SRGB_TO_LINEAR16, i as SHADING_VERTEX, o as encodeValues, r as SHADING_FRAGMENT, s as shadingOf } from "./colormap-D_xH5hI5.js";
2
+ import { a as SRGB_TO_LINEAR16, i as SHADING_VERTEX, o as encodeValues, r as SHADING_FRAGMENT, s as shadingOf } from "./colormap-DxGMYVfs.js";
3
3
  import * as THREE from "three";
4
4
  //#region src/three/mesh.ts
5
5
  const DEFAULT_COLOR = 13421772;
@@ -74,6 +74,13 @@ const BUFFERS = {
74
74
  * the scene and leaves the object as it was (remove it from your THREE.Scene
75
75
  * and call {@link BoundMesh.dispose}).
76
76
  *
77
+ * The object must sit under an untransformed parent (its `matrix` is a world
78
+ * matrix); a transformed ancestor is detected and warned about once.
79
+ *
80
+ * With a debug scene (`new Scene({ debug: true })`), the views the binding
81
+ * copies from are checked `Proxy` objects (see `SceneOptions.debug` for
82
+ * their cost); the mirrors it uploads are always plain typed arrays.
83
+ *
77
84
  * The adapter only listens through {@link SceneLike.onChanges}: call
78
85
  * `scene.commitFrame()` once per animation frame, before rendering.
79
86
  */
@@ -179,19 +186,36 @@ function bindMesh(scene, mesh, options = {}) {
179
186
  if (shading !== void 0) setShadingUniforms(uniforms, shading);
180
187
  return true;
181
188
  };
182
- /** Live triangles' vertices only: dead slots keep stale positions. */
189
+ /**
190
+ * Live triangles' vertices only: dead slots keep stale positions. From the
191
+ * scene's bounds when the host has them (one engine pass instead of two
192
+ * walks over every slot), else walked from the mirrors.
193
+ */
183
194
  const computeBounds = () => {
184
195
  const position = attributeOf("positions");
185
196
  const index = attributeOf("indices");
186
197
  if (position === void 0 || index === void 0) return;
198
+ const box = geometry.boundingBox ??= new THREE.Box3();
199
+ const sphere = geometry.boundingSphere ??= new THREE.Sphere();
200
+ const fromScene = typeof scene.bounds === "function" ? scene.bounds(mesh) : void 0;
201
+ if (fromScene !== void 0) {
202
+ if (fromScene === null) {
203
+ box.makeEmpty();
204
+ sphere.set(new THREE.Vector3(), -1);
205
+ return;
206
+ }
207
+ box.min.fromArray(fromScene.min);
208
+ box.max.fromArray(fromScene.max);
209
+ box.getCenter(sphere.center);
210
+ sphere.radius = box.min.distanceTo(box.max) / 2;
211
+ return;
212
+ }
187
213
  const p = position.array;
188
214
  const t = index.array;
189
- const box = geometry.boundingBox ??= new THREE.Box3();
190
215
  box.makeEmpty();
191
216
  const point = new THREE.Vector3();
192
217
  const live = (k) => t[k] !== 0 || t[k + 1] !== 0 || t[k + 2] !== 0;
193
218
  for (let k = 0; k < t.length; k += 3) if (live(k)) for (let c = 0; c < 3; c++) box.expandByPoint(point.fromArray(p, 3 * t[k + c]));
194
- const sphere = geometry.boundingSphere ??= new THREE.Sphere();
195
219
  if (box.isEmpty()) {
196
220
  sphere.set(new THREE.Vector3(), -1);
197
221
  return;
@@ -264,12 +288,14 @@ function bindMesh(scene, mesh, options = {}) {
264
288
  apply(void 0);
265
289
  computeBounds();
266
290
  updateMatrix();
291
+ checkUntransformedParent(object);
267
292
  let unsubscribe;
268
293
  const detach = () => {
269
294
  unsubscribe?.();
270
295
  unsubscribe = void 0;
271
296
  };
272
297
  unsubscribe = scene.onChanges((changes) => {
298
+ checkUntransformedParent(object);
273
299
  for (const c of changes) {
274
300
  if (c.mesh !== mesh) continue;
275
301
  if (c.removed) {
@@ -310,6 +336,27 @@ function bindMesh(scene, mesh, options = {}) {
310
336
  if (options.opacity !== void 0) bound.setOpacity(options.opacity);
311
337
  return bound;
312
338
  }
339
+ /** Objects already warned about a transformed ancestor. */
340
+ const warnedParents = /* @__PURE__ */ new WeakSet();
341
+ /** Whether the object's own transform is the identity. */
342
+ function isIdentityTransform(o) {
343
+ if (!o.matrixAutoUpdate) return o.matrix.elements.every((v, i) => v === (i % 5 === 0 ? 1 : 0));
344
+ const { position: p, quaternion: q, scale: s } = o;
345
+ return p.x === 0 && p.y === 0 && p.z === 0 && q.x === 0 && q.y === 0 && q.z === 0 && q.w === 1 && s.x === 1 && s.y === 1 && s.z === 1;
346
+ }
347
+ /**
348
+ * Warns once per object when it sits under a transformed ancestor: the
349
+ * adapter drives its matrix as a world matrix, so a transformed parent
350
+ * offsets it. Internal: shared with the controls and section bindings.
351
+ */
352
+ function checkUntransformedParent(object) {
353
+ if (warnedParents.has(object)) return;
354
+ for (let p = object.parent; p !== null; p = p.parent) if (!isIdentityTransform(p)) {
355
+ warnedParents.add(object);
356
+ console.warn("fast-mesh-wasm/three: the bound object has a transformed ancestor; its matrix is driven as a world matrix, so add it under the scene or an untransformed group.");
357
+ return;
358
+ }
359
+ }
313
360
  /** `INVALID_ARGUMENT` unless `width` is a finite number `>= 0`. */
314
361
  function checkSoftness(width) {
315
362
  if (typeof width !== "number" || !Number.isFinite(width) || width < 0) throw new FastMeshError("INVALID_ARGUMENT", "edgeSoftness must be a finite number >= 0");
@@ -425,4 +472,4 @@ function patchMaterial(material, uniforms) {
425
472
  };
426
473
  }
427
474
  //#endregion
428
- export { bindMesh as t };
475
+ export { checkUntransformedParent as n, bindMesh as t };
package/dist/node.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as PlacementInput, A as RepairOp, B as SectionResult, C as MeshComponent, D as RayHit, E as OutOfRange, F as SceneOptions, G as SectionHandle, H as WeldReport, I as SectionContour, J as Bounds, K as Range, L as SectionDesc, M as RepairReportOf, N as Rgba, O as RaycastOptions, P as Scene, Q as Placement, R as SectionGap, S as MeshChange, T as OrientReport, U as FieldHandle, V as SignMode, W as MeshHandle, X as InitInput, Y as Indices, Z as Mat3, _ as FieldStatus, a as BoundaryLoop, at as computeBounds, b as FindContactsOptions, c as ColorRule, d as DegenerateReport, et as Positions, f as DistanceFieldDesc, g as EditResult, h as EditRef, i as AnalyzeOptions, it as Vec3, j as RepairReport, k as RemoveReport, l as Colormap, m as EditOp, n as AddMeshOptions, nt as Quat, o as ClosestHit, ot as computeVertexNormals, p as DragSession, q as MeshViews, r as Analysis, rt as UpdateMode, s as ClosestPointOptions, t as SceneLike, tt as Positions64, u as Contact, v as FillReport, w as MeshDistance, x as LoopId, y as FilledLoop, z as SectionPlane } from "./scene-like-B_3qm0u6.js";
1
+ import { $ as Placement, A as RemoveReport, B as SectionPlane, C as MeshChange, D as OutOfRange, E as OrientReport, F as Scene, G as MeshHandle, H as SignMode, I as SceneOptions, J as MeshViews, K as SectionHandle, L as SectionContour, M as RepairReport, N as RepairReportOf, O as RayHit, P as Rgba, Q as Mat3, R as SectionDesc, S as LoopId, T as MeshDistance, U as WeldReport, V as SectionResult, W as FieldHandle, X as Indices, Y as Bounds, Z as InitInput, _ as EditResult, a as BoundaryLoop, at as Vec3, b as FilledLoop, c as ColorRule, d as DegenerateReport, et as PlacementInput, f as DistanceFieldDesc, g as EditRef, h as EditOp, i as AnalyzeOptions, it as UpdateMode, j as RepairOp, k as RaycastOptions, l as Colormap, m as DragSession, n as AddMeshOptions, nt as Positions64, o as ClosestHit, ot as computeBounds, p as DragOptions, q as Range, r as Analysis, rt as Quat, s as ClosestPointOptions, st as computeVertexNormals, t as SceneLike, tt as Positions, u as Contact, v as FieldStatus, w as MeshComponent, x as FindContactsOptions, y as FillReport, z as SectionGap } from "./scene-like-DJKQP5uf.js";
2
2
  import { n as FastMeshErrorCode, t as FastMeshError } from "./core-D2X9GPfK.js";
3
3
  //#region src/node.d.ts
4
4
  /**
@@ -8,4 +8,4 @@ import { n as FastMeshErrorCode, t as FastMeshError } from "./core-D2X9GPfK.js";
8
8
  */
9
9
  export declare function init(_input?: InitInput | Promise<InitInput>): Promise<void>;
10
10
  //#endregion
11
- export { type AddMeshOptions, type Analysis, type AnalyzeOptions, type BoundaryLoop, type Bounds, type ClosestHit, type ClosestPointOptions, type ColorRule, type Colormap, type Contact, type DegenerateReport, type DistanceFieldDesc, type DragSession, type EditOp, type EditRef, type EditResult, FastMeshError, type FastMeshErrorCode, type FieldHandle, type FieldStatus, type FillReport, type FilledLoop, type FindContactsOptions, type Indices, type InitInput, type LoopId, type Mat3, type MeshChange, type MeshComponent, type MeshDistance, type MeshHandle, type MeshViews, type OrientReport, type OutOfRange, type Placement, type PlacementInput, type Positions, type Positions64, type Quat, type Range, type RayHit, type RaycastOptions, type RemoveReport, type RepairOp, type RepairReport, type RepairReportOf, type Rgba, Scene, type SceneLike, type SceneOptions, type SectionContour, type SectionDesc, type SectionGap, type SectionHandle, type SectionPlane, type SectionResult, type SignMode, type UpdateMode, type Vec3, type WeldReport, computeBounds, computeVertexNormals };
11
+ export { type AddMeshOptions, type Analysis, type AnalyzeOptions, type BoundaryLoop, type Bounds, type ClosestHit, type ClosestPointOptions, type ColorRule, type Colormap, type Contact, type DegenerateReport, type DistanceFieldDesc, type DragOptions, type DragSession, type EditOp, type EditRef, type EditResult, FastMeshError, type FastMeshErrorCode, type FieldHandle, type FieldStatus, type FillReport, type FilledLoop, type FindContactsOptions, type Indices, type InitInput, type LoopId, type Mat3, type MeshChange, type MeshComponent, type MeshDistance, type MeshHandle, type MeshViews, type OrientReport, type OutOfRange, type Placement, type PlacementInput, type Positions, type Positions64, type Quat, type Range, type RayHit, type RaycastOptions, type RemoveReport, type RepairOp, type RepairReport, type RepairReportOf, type Rgba, Scene, type SceneLike, type SceneOptions, type SectionContour, type SectionDesc, type SectionGap, type SectionHandle, type SectionPlane, type SectionResult, type SignMode, type UpdateMode, type Vec3, type WeldReport, computeBounds, computeVertexNormals };
package/dist/node.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as FastMeshError } from "./core-Cke_kZ2e.js";
2
2
  import { n as computeVertexNormals, r as markInitialized, t as computeBounds } from "./api-BUy7FRx7.js";
3
- import { t as Scene } from "./scene-BFd6nYRe.js";
3
+ import { t as Scene } from "./scene-D6m9XM3O.js";
4
4
  import { initSync } from "./wasm/fast_mesh_wasm.js";
5
5
  import { readFileSync } from "node:fs";
6
6
  //#region src/node.ts
@@ -1,4 +1,4 @@
1
- import { B as SectionResult, K as Range, c as ColorRule, f as DistanceFieldDesc, n as AddMeshOptions, z as SectionPlane } from "./scene-like-B_3qm0u6.js";
1
+ import { B as SectionPlane, V as SectionResult, c as ColorRule, f as DistanceFieldDesc, n as AddMeshOptions, q as Range } from "./scene-like-DJKQP5uf.js";
2
2
  //#region src/worker/protocol.d.ts
3
3
  /** A mesh, field or section id allocated on the main side. Unique per kind. */
4
4
  type ClientId = number;
package/dist/r3f.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { W as MeshHandle } from "./scene-like-B_3qm0u6.js";
2
- import { t as SceneStore } from "./store-DNnHN33A.js";
3
- import { n as BoundMesh, t as BindMeshOptions } from "./mesh-B16gV3oX.js";
1
+ import { G as MeshHandle } from "./scene-like-DJKQP5uf.js";
2
+ import { t as SceneStore } from "./store-QWRDXlAn.js";
3
+ import { n as BoundMesh, t as BindMeshOptions } from "./mesh-BUVxv3jo.js";
4
4
  import * as THREE from "three";
5
5
  import { JSX } from "react";
6
6
  import { EventHandlers } from "@react-three/fiber";
package/dist/r3f.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as FastMeshError } from "./core-Cke_kZ2e.js";
2
- import { t as bindMesh } from "./mesh-B8pae8WA.js";
2
+ import { t as bindMesh } from "./mesh-zj7-wJBw.js";
3
3
  import { s as meshState } from "./snapshot-Cf6NgDl7.js";
4
- import { r as setFrameLoop } from "./store-D3ErV6o-.js";
4
+ import { r as setFrameLoop } from "./store-Ml3TQGsR.js";
5
5
  import { c as useStoreSelector, i as useScene, l as StoreContext, t as SceneProvider } from "./react-CTADh3NN.js";
6
6
  import * as THREE from "three";
7
7
  import { createElement, useCallback, useContext, useLayoutEffect, useRef, useState } from "react";
package/dist/react.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { G as SectionHandle, W as MeshHandle } from "./scene-like-B_3qm0u6.js";
1
+ import { G as MeshHandle, K as SectionHandle } from "./scene-like-DJKQP5uf.js";
2
2
  import { t as FastMeshError } from "./core-D2X9GPfK.js";
3
- import { a as DisplayState, c as MeshState, d as SceneSnapshot, n as SectionPatch, p as SectionState, t as SceneStore } from "./store-DNnHN33A.js";
3
+ import { a as DisplayState, c as MeshState, d as SceneSnapshot, n as SectionPatch, p as SectionState, t as SceneStore } from "./store-QWRDXlAn.js";
4
4
  import { ReactElement, ReactNode } from "react";
5
5
  //#region src/react/index.d.ts
6
6
  /** Provides `store` to the hooks below it. */
@@ -1,5 +1,5 @@
1
1
  import { a as release, c as wasmMemory, i as finalizer, n as call, r as ensureInitialized, t as FastMeshError } from "./core-Cke_kZ2e.js";
2
- import { a as FieldHandle, c as rotationMatrix, i as encodeRule, l as targetsOf, n as meshViews, o as MeshHandle, r as copyRule, s as SectionHandle, t as ViewGuard } from "./views-BaZqBxlX.js";
2
+ import { a as FieldHandle, c as rotationMatrix, i as encodeRule, l as targetsOf, n as meshViews, o as MeshHandle, r as copyRule, s as SectionHandle, t as ViewGuard } from "./views-Dh3aWc2q.js";
3
3
  import { WasmScene } from "./wasm/fast_mesh_wasm.js";
4
4
  //#region src/changes.ts
5
5
  const ADDED = 1;
@@ -78,6 +78,11 @@ const MODES = {
78
78
  lazy: 1,
79
79
  manual: 2
80
80
  };
81
+ const MODE_NAMES = [
82
+ "eager",
83
+ "lazy",
84
+ "manual"
85
+ ];
81
86
  function modeCode(mode) {
82
87
  if (!Object.hasOwn(MODES, mode)) throw invalid("mode must be \"eager\", \"lazy\" or \"manual\"");
83
88
  return MODES[mode];
@@ -239,7 +244,7 @@ function encodeRepair(ops) {
239
244
  count = o.loops.length;
240
245
  for (const id of o.loops) encodeLoopId(id, loops);
241
246
  }
242
- values.push(optional(o.maxEdges, "maxEdges"), optional(o.maxPerimeter, "maxPerimeter"), optional(o.maxArea, "maxArea"), count, flagOf(o.allowUnclean, false), flagOf(o.fair, true), optional(o.dpLimit, "dpLimit"));
247
+ values.push(optional(o.maxEdges, "maxEdges"), optional(o.maxPerimeter, "maxPerimeter"), optional(o.maxArea, "maxArea"), count, flagOf(o.allowUnclean, false), flagOf(o.fair, true), optional(o.dpLimit, "dpLimit"), optional(o.maxDihedral, "maxDihedral"), optional(o.maxRefineVertices, "maxRefineVertices"));
243
248
  break;
244
249
  }
245
250
  }
@@ -326,7 +331,8 @@ function decodeReport(op, r) {
326
331
  trianglesAdded: r.next(),
327
332
  verticesAdded: r.next(),
328
333
  converged: r.flag(),
329
- weights: WEIGHTS[r.next()]
334
+ weights: WEIGHTS[r.next()],
335
+ refineCapped: r.flag()
330
336
  })),
331
337
  skipped: r.many(() => ({
332
338
  id: r.loopId(),
@@ -599,6 +605,47 @@ var Scene = class {
599
605
  const m = modeCode(mode);
600
606
  call(() => this.#scene().set_mode(index, generation, m));
601
607
  }
608
+ /** When the mesh's derived data follows its edits; see {@link UpdateMode}. */
609
+ mode(mesh) {
610
+ const { index, generation } = this.#id(mesh);
611
+ const code = call(() => this.#peek().mode(index, generation));
612
+ return MODE_NAMES[code] ?? "eager";
613
+ }
614
+ /**
615
+ * The box around the vertices the live triangles use, in the mesh's local
616
+ * render coordinates ({@link Scene.matrix4} maps them to the world). Dead
617
+ * slots keep stale positions, so they are excluded. `null` without live
618
+ * triangles.
619
+ */
620
+ bounds(mesh) {
621
+ const { index, generation } = this.#id(mesh);
622
+ const b = call(() => this.#peek().bounds(index, generation));
623
+ if (b.length === 0) return null;
624
+ const min = [
625
+ b[0],
626
+ b[1],
627
+ b[2]
628
+ ];
629
+ const max = [
630
+ b[3],
631
+ b[4],
632
+ b[5]
633
+ ];
634
+ return {
635
+ min,
636
+ max,
637
+ center: [
638
+ (min[0] + max[0]) / 2,
639
+ (min[1] + max[1]) / 2,
640
+ (min[2] + max[2]) / 2
641
+ ],
642
+ size: [
643
+ max[0] - min[0],
644
+ max[1] - min[1],
645
+ max[2] - min[2]
646
+ ]
647
+ };
648
+ }
602
649
  /** Brings the mesh's derived data up to date now, whatever its mode. */
603
650
  update(mesh) {
604
651
  const { index, generation } = this.#id(mesh);
@@ -645,6 +692,7 @@ var Scene = class {
645
692
  * {@link Scene.commitFrame} instead.
646
693
  */
647
694
  takeChanges() {
695
+ this.#drag?.applyPending();
648
696
  const s = this.#scene();
649
697
  const raw = decodeChanges(call(() => s.take_changes()));
650
698
  const out = raw.map((c) => ({
@@ -742,6 +790,8 @@ var Scene = class {
742
790
  /** Ends one nesting level of the open step. Throws `STEP_NOT_OPEN` when none is open. */
743
791
  endStep() {
744
792
  const s = this.#scene();
793
+ const drag = this.#drag;
794
+ if (drag !== void 0 && this.#stepDepth > 0 && this.#stepDepth <= drag.depth) drag.applyPending();
745
795
  call(() => s.end_step());
746
796
  this.#stepDepth--;
747
797
  if (this.#drag !== void 0 && this.#stepDepth < this.#drag.depth) this.#drag.abandon();
@@ -757,16 +807,20 @@ var Scene = class {
757
807
  * Starts dragging a mesh: the moves until {@link DragSession.end} form one
758
808
  * undo step (nested in the open step, if there is one). One drag at a time.
759
809
  * Every {@link DragSession.move} recomputes the eager fields, so make at most
760
- * one move per animation frame, with the latest pointer pose.
810
+ * one move per animation frame, with the latest pointer pose, or pass
811
+ * `{ coalesce: true }` to have the drag do that for you.
761
812
  */
762
- drag(mesh) {
813
+ drag(mesh, options = {}) {
763
814
  this.#id(mesh);
764
815
  if (this.#drag !== void 0) throw invalid("a drag is already active; end or cancel it first");
816
+ const coalesce = options.coalesce ?? false;
765
817
  const start = this.placement(mesh);
766
818
  const outermost = this.#stepDepth === 0;
767
819
  this.beginStep();
768
820
  const depth = this.#stepDepth;
769
821
  let active = true;
822
+ /** The latest coalesced pose, not yet applied. */
823
+ let pending;
770
824
  const finish = () => {
771
825
  if (!active) return false;
772
826
  active = false;
@@ -776,6 +830,13 @@ var Scene = class {
776
830
  const close = () => {
777
831
  while (this.#stepDepth >= depth) this.endStep();
778
832
  };
833
+ const applyPending = () => {
834
+ if (pending !== void 0) {
835
+ const pose = pending;
836
+ pending = void 0;
837
+ this.setPlacement(mesh, pose);
838
+ }
839
+ };
779
840
  const session = {
780
841
  depth,
781
842
  mesh,
@@ -784,13 +845,37 @@ var Scene = class {
784
845
  },
785
846
  move: (placement) => {
786
847
  if (!active) throw invalid("the drag is over");
787
- this.setPlacement(mesh, placement);
848
+ if (!coalesce) {
849
+ this.setPlacement(mesh, placement);
850
+ return;
851
+ }
852
+ const rotation = rotationMatrix(placement.rotation);
853
+ if (!rotation.every(Number.isFinite)) throw invalid("rotation must be finite numbers");
854
+ const t = placement.translation;
855
+ if (t?.length !== 3 || ![
856
+ t[0],
857
+ t[1],
858
+ t[2]
859
+ ].every(Number.isFinite)) throw invalid("translation must be 3 finite numbers");
860
+ pending = {
861
+ rotation,
862
+ translation: [
863
+ t[0],
864
+ t[1],
865
+ t[2]
866
+ ]
867
+ };
788
868
  },
789
869
  end: () => {
790
- if (finish()) close();
870
+ if (finish()) try {
871
+ applyPending();
872
+ } finally {
873
+ close();
874
+ }
791
875
  },
792
876
  cancel: () => {
793
877
  if (!finish()) return;
878
+ pending = void 0;
794
879
  if (outermost) {
795
880
  this.cancelStep();
796
881
  return;
@@ -803,7 +888,8 @@ var Scene = class {
803
888
  },
804
889
  abandon: () => {
805
890
  finish();
806
- }
891
+ },
892
+ applyPending
807
893
  };
808
894
  this.#drag = session;
809
895
  return session;
@@ -1088,14 +1174,14 @@ var Scene = class {
1088
1174
  }
1089
1175
  static {
1090
1176
  meshAddsOf = (scene) => ({
1091
- begin: (positions, indices, options = {}) => {
1177
+ beginUpload: (vertices, triangles, options = {}) => {
1092
1178
  const s = scene.#scene();
1093
1179
  const mode = modeCode(options.mode ?? "eager");
1094
1180
  const origin = options.origin === void 0 ? void 0 : Float64Array.from(options.origin);
1095
- const p = toFloat64(positions);
1096
- const i = toUint32(indices);
1097
- return call(() => s.begin_add_mesh(p, i, origin, mode, options.normals ?? true));
1181
+ return call(() => s.begin_add_mesh_upload(vertices, triangles, origin, mode, options.normals ?? true));
1098
1182
  },
1183
+ pushPositions: (token, chunk) => call(() => scene.#scene().add_mesh_push_positions(token, chunk)),
1184
+ pushIndices: (token, chunk) => call(() => scene.#scene().add_mesh_push_indices(token, chunk)),
1099
1185
  step: (token, budget) => call(() => scene.#scene().add_mesh_step(token, budget)),
1100
1186
  buffers: (token) => {
1101
1187
  const [pp, pl, np, nl, ip, il] = call(() => scene.#peek().add_mesh_buffers(token));