fast-mesh-wasm 0.5.1 → 0.5.3

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 (39) hide show
  1. package/README.md +45 -3
  2. package/dist/{client-tP6R9foI.d.ts → client-D7yfPOyU.d.ts} +14 -5
  3. package/dist/{client-C61Kku4i.js → client-f895H_yB.js} +52 -7
  4. package/dist/{engine-X1Awlc5y.js → engine-BcJ5W6kS.js} +29 -4
  5. package/dist/io.d.ts +21 -9
  6. package/dist/io.js +102 -18
  7. package/dist/{mesh-D3fv56nF.d.ts → mesh-B3QP93wx.d.ts} +15 -4
  8. package/dist/{mesh-CWvrjO8S.js → mesh-hPWBQPaN.js} +28 -4
  9. package/dist/node.d.ts +2 -2
  10. package/dist/node.js +1 -1
  11. package/dist/{protocol-BGQAB0op.d.ts → protocol-Dt0zgang.d.ts} +20 -5
  12. package/dist/r3f.d.ts +3 -3
  13. package/dist/r3f.js +2 -2
  14. package/dist/react.d.ts +2 -2
  15. package/dist/{scene-BnkCS0sv.js → scene-CXtM_bxV.js} +150 -6
  16. package/dist/{scene-like-BzkDNHCy.d.ts → scene-like-Dq9_SaUL.d.ts} +225 -6
  17. package/dist/{store-CEd2y2KS.js → store-C9h7GFFl.js} +4 -5
  18. package/dist/{store-BKFzSykN.d.ts → store-CIW19oCh.d.ts} +4 -3
  19. package/dist/store.d.ts +2 -2
  20. package/dist/store.js +1 -1
  21. package/dist/three.d.ts +2 -2
  22. package/dist/three.js +1 -1
  23. package/dist/{views-CUBMOK0U.js → views-mp7Mf8CQ.js} +24 -1
  24. package/dist/wasm/fast_mesh_wasm.d.ts +39 -2
  25. package/dist/wasm/fast_mesh_wasm.js +104 -2
  26. package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
  27. package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +5 -0
  28. package/dist/wasm-threads/fast_mesh_wasm.d.ts +39 -2
  29. package/dist/wasm-threads/fast_mesh_wasm.js +105 -3
  30. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm +0 -0
  31. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm.d.ts +5 -0
  32. package/dist/web.d.ts +2 -2
  33. package/dist/web.js +1 -1
  34. package/dist/worker-engine.d.ts +1 -1
  35. package/dist/worker-engine.js +1 -1
  36. package/dist/worker-entry.js +1 -1
  37. package/dist/worker.d.ts +1 -1
  38. package/dist/worker.js +1 -1
  39. package/package.json +1 -1
package/README.md CHANGED
@@ -112,6 +112,17 @@ requestAnimationFrame(frame);
112
112
  - 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.
113
113
  - 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.
114
114
 
115
+ #### Textures
116
+
117
+ Add a mesh with `{ uvs }` (2 floats per vertex, read back zero-copy with `scene.views(mesh).uvs()`) and pass the texture to `bindMesh`:
118
+
119
+ ```ts
120
+ const mesh = scene.addMesh(positions, indices, { uvs });
121
+ const bound = bindMesh(scene, mesh, { map: texture });
122
+ ```
123
+
124
+ `importGLTF` returns `uvs` from `TEXCOORD_0` and `exportGLTF` writes them. Every mesh operation keeps UVs aligned or drops them, undoably: `weld` keeps seams apart, `simplify`, `subdivide`, `remesh`, `fillHoles` and `cutByPlane` interpolate, and `boolean` drops them. See [docs/uv-channel.md](docs/uv-channel.md) for the table.
125
+
115
126
  #### Fragment shading
116
127
 
117
128
  Vertex colours interpolate across each triangle, so the edge between coloured and base-coloured vertices blurs over a triangle's width. `bindMesh(scene, mesh, { shading: "fragment", edgeSoftness })` colours every pixel from the interpolated field value through the colouring's rule instead (a lookup texture and a shader chunk added with `onBeforeCompile`): range edges and colour steps, such as a contact heatmap's tolerance band, are crisp iso-lines, and at a vertex the colour equals its vertex colour. Far (`Infinity`) and NaN values never tint their neighbours.
@@ -204,7 +215,7 @@ const closest = scene.meshDistance(upper, lower); // { distance, a, b, ... }
204
215
  scene.free(); // or `using scene = new Scene()`
205
216
  ```
206
217
 
207
- Errors are `FastMeshError`s with a `code` (`UNKNOWN_MESH`, `INVALID_ARGUMENT`, `STALE_BVH`, ...). After a trap inside the WebAssembly module every later call throws `INSTANCE_POISONED`. A view is only valid until the next scene call that may allocate or move buffers: a kept view may read other data or be empty, so re-acquire views after any scene call. `new Scene({ debug: true })` makes views warn when they are read after such a call. Mesh edits (`scene.edit`), `analyze`, `measure`, `repair`, sections (`addSection`, `section`, `sectionGap`) and `findContacts` are documented in the types.
218
+ Errors are `FastMeshError`s with a `code` (`UNKNOWN_MESH`, `INVALID_ARGUMENT`, `STALE_BVH`, ...). After a trap inside the WebAssembly module every later call throws `INSTANCE_POISONED`. A view is only valid until the next scene call that may allocate or move buffers: a kept view may read other data or be empty, so re-acquire views after any scene call. `new Scene({ debug: true })` makes views warn when they are read after such a call. Mesh edits (`scene.edit`), `analyze`, `measure`, `repair`, `register` (rigid ICP alignment of two meshes), sections (`addSection`, `section`, `sectionGap`) and `findContacts` are documented in the types.
208
219
 
209
220
  ### Contact groups: fields to several meshes
210
221
 
@@ -295,7 +306,7 @@ const values = await scene.fetchFieldValues(gap); // `fieldValues` on Scene
295
306
  - **Requests run in order.** A newer colouring, section plane/meshes/fill or drag move drops the older one if it has not started yet, so fast toggling settles on the last state without doing the steps in between. Edits, repairs, `setPlacement`, adds, removals and undo/redo are never dropped. Each `setPlacement` is an undo step: for pointer-rate updates use a drag. Long work runs in steps: the Worker yields every few milliseconds during a field build, a field update or a large add, so newer batches are received (and coalesced) meanwhile.
296
307
  - **Drags are optimistic.** `scene.drag(mesh).move(pose)` moves the placement mirror at once, so the object follows the pointer; colours and sections catch up when the Worker's result arrives. In 9a a key's status covers only requests made under that key: a drag, `setPlacement` or edit puts its own key (`placement:<id>`, `edit:<id>`) into `"computing"`, not the `display:<id>` or `section:<id>:*` keys of the state that catches up after it. `end()` and `cancel()` return at once; `cancel()` restores the start pose and records nothing.
297
308
  - **Wide-range colouring during a drag.** After each batch the Worker recomputes the fields the batch made due in small steps, and drops the recompute when a newer move, `setPlacement`, edit, repair, compact, undo/redo or removal of either mesh is already queued; other requests wait for it. A pose's colours are applied all at once, never partly. So while the pointer keeps moving and one recompute takes longer than a frame, newer moves drop the recompute, until 200 ms have passed since the last colours were applied: then the recompute under way finishes and is shown, and the newest pose follows. During a sustained drag the colours therefore update about every 200 ms plus one recompute, each update exactly one pose, and when the drag ends (`end()`) the last pose's colours arrive within about one recompute (measured: one at 1M, but about 1.5 at 10M when most of the mesh is in range): the end drops a recompute kept for an older pose. A pointer that only pauses, without ending the drag, may wait up to two recomputes. Edits, undo/redo, removals and cancels always drop a stale recompute. `fetchFieldValues()` and `fieldStatus()` first bring every due field up to date in one go, which cannot be dropped, so do not poll them during a drag. On two touching 1M-triangle meshes with `maxDistance` 8, a recompute takes from about 0.07 s to 0.7 s depending on how much of the mesh is in range, and about ten times that at 10M; the Worker is never blocked for long, since a recompute runs in steps: about 12 ms at a time at 1M, and 14 to 18 ms for field builds and edits at 10M (see [docs/benchmarks.md](docs/benchmarks.md)). These are single-threaded figures; on a cross-origin isolated page the threaded engine makes a recompute 1.4 to 4.5 times faster (see [Multithreading (COOP/COEP)](#multithreading-coopcoep)). A contact range (a small `maxDistance`) keeps up with the pointer.
298
- - **Queries and anything that returns data** (`raycast`, `closestPoint`, `meshDistance`, `intersects`, `findContacts`, `analyze`, `measure`, `edit`, `repair`, `fetchFieldValues`, `fieldStatus`, `sectionGap`) return promises. Once a frame loop runs they go out with the next `commitFrame()` (or after 100 ms if no frame comes); before the first `commitFrame()` they are sent on a microtask. For latency-critical picking, keep a light picking copy in a main-thread `Scene`.
309
+ - **Queries and anything that returns data** (`raycast`, `closestPoint`, `meshDistance`, `intersects`, `findContacts`, `analyze`, `measure`, `register`, `edit`, `repair`, `fetchFieldValues`, `fieldStatus`, `sectionGap`) return promises. Once a frame loop runs they go out with the next `commitFrame()` (or after 100 ms if no frame comes); before the first `commitFrame()` they are sent on a microtask. For latency-critical picking, keep a light picking copy in a main-thread `Scene`.
299
310
  - **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.
300
311
  - **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.
301
312
  - **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.
@@ -319,7 +330,7 @@ import { Scene } from "fast-mesh-wasm"; // Node entry: the .wasm loads from disk
319
330
  const scene = new Scene(); // no init() needed, as in browsers
320
331
  const upper = scene.addMesh(upperPositions, upperIndices);
321
332
  const lower = scene.addMesh(lowerPositions, lowerIndices);
322
- scene.repair(upper, [{ op: "removeDegenerate" }]);
333
+ scene.repair(upper, { kind: "auto" }); // weld, remove degenerate, orient, remove small pieces, fill holes
323
334
  const gap = scene.addDistanceField({ name: "gap", on: upper, to: lower, maxDistance: 2 });
324
335
  scene.setColoring(upper, { field: gap, map: "turbo", range: [-0.5, 1] });
325
336
  const distance = scene.meshDistance(upper, lower)?.distance ?? Infinity;
@@ -602,6 +613,37 @@ Meshes must be added through the store (`store.addMesh`). A mesh added straight
602
613
 
603
614
  All functions throw an `Error` with a readable message when a buffer length is not a multiple of 3 or an index is out of range, and when called before `init()` has finished in the browser.
604
615
 
616
+ ## Command line
617
+
618
+ `fast-mesh` is a native binary for batch jobs and CI steps. It calls the Rust engine crates directly, with no WebAssembly or Node.js, and is not part of the npm package:
619
+
620
+ ```sh
621
+ cargo install --path crates/fast-mesh-cli # add --features parallel for multithreading
622
+
623
+ fast-mesh repair in.stl -o out.stl --auto # weld, remove degenerate, orient, remove small components, fill holes
624
+ fast-mesh measure in.stl --format json # counts, area, volume when watertight, defects
625
+ fast-mesh boolean a.stl b.stl --op union -o out.stl # union, intersection or difference (a minus b)
626
+ fast-mesh convert in.ply -o out.glb
627
+ ```
628
+
629
+ Files are `.stl` (binary or ASCII), `.obj`, `.ply` (ASCII or binary little-endian) and `.glb`, chosen by extension. `--ascii` writes the text form of `.stl` and `.ply`. `repair` takes `--weld-tolerance <d>`, `--min-triangles <n>`, `--max-edges <n|any>` and `--no-fair`, with the defaults of `AutoRepairOptions`. `fast-mesh <command> --help` lists a command's options.
630
+
631
+ | Exit code | Meaning |
632
+ | --- | --- |
633
+ | `0` | Success. |
634
+ | `1` | The operation or a file failed: malformed or truncated input, I/O, inputs a boolean refuses, an empty result, an invalid boolean result. |
635
+ | `2` | Usage error: bad arguments, an unsupported extension, or an output that names an input without `--force`. |
636
+
637
+ Reports go to stdout and diagnostics to stderr. With `--format json`, stdout holds one JSON object on success and nothing on failure, so a script can check the exit code and then parse. A hole `repair` leaves open is not a failure: it exits `0`, counts the hole in the report (`skipped`, `failed`) and warns on stderr.
638
+
639
+ The output appears whole or not at all: it is written beside the target and renamed over it when complete, so a failed run leaves any existing file untouched.
640
+
641
+ `boolean` refuses what the engine cannot resolve with `invalid input: boolean intersection too complex` (exit `1`); at present that includes many overlaps of curved surfaces, so check it on your data.
642
+
643
+ `boolean` also checks its result before writing. One that is open, non-manifold or has orientation conflicts fails with `the engine produced an invalid result` and its defect counts (exit `1`), leaving any existing output untouched, even with `--force`. Today's engine produces such results for some inputs, including overlapping cubes depending on how their faces are triangulated ([#165](https://github.com/YoonDongGeun/fast-mesh-wasm/issues/165)). The check is structural: it does not compare the result against the shape it should have.
644
+
645
+ Limits: a `.glb` becomes one mesh, with its node placements baked and its primitives merged. Draco and meshopt compression, GPU instancing, sparse accessors and buffers outside the GLB body are refused with an error, as is a file whose nodes reuse their meshes for more than 1,048,576 node-primitive pairs (or file size / 16, if larger). JSON `.gltf`, big-endian PLY and UVs are not supported. Other attributes (normals, colors, materials) are not carried across a conversion.
646
+
605
647
  ## Supported environments
606
648
 
607
649
  | Environment | Entry | Notes |
@@ -1,6 +1,6 @@
1
- import { $ as SectionPlane, A as JoinReport, B as RaycastOptions, C as FieldStatus, Ct as Placement, E as FindContactsOptions, Et as Positions64, F as MeshDistance, K as RepairReportOf, M as MeasureResult, N as MeshChange, Q as SectionGap, S as EditResult, W as RepairOp, Z as SectionDesc, _ as DistanceFieldDesc, _t as MeshHandle, b as EditOp, bt as Indices, c as ClosestHit, et as SectionResult, f as Contact, gt as FieldHandle, ht as MeshViews, i as AnalyzeOptions, k as JoinOptions, kt as Vec3, l as ClosestPointOptions, n as AddMeshOptions, r as Analysis, t as SceneLike, u as ColorRule, vt as SectionHandle, wt as PlacementInput, y as DragSession, z as RayHit } from "./scene-like-BzkDNHCy.js";
1
+ import { $ as RepairReportOf, Ct as SceneMeshViews, Et as SectionHandle, F as MeshChange, G as RegisterOptions, H as RaycastOptions, K as RegisterResult, L as MeshDistance, Lt as Vec3, M as JoinReport, Mt as PlacementInput, O as FindContactsOptions, Ot as Indices, P as MeasureResult, Pt as Positions64, S as EditOp, T as FieldStatus, Tt as MeshHandle, V as RayHit, Z as RepairOp, a as AutoRepairReport, at as SectionGap, d as ClosestPointOptions, f as ColorRule, i as AnalyzeOptions, it as SectionDesc, j as JoinOptions, jt as Placement, m as Contact, n as AddMeshOptions, o as AutoRepairRequest, ot as SectionPlane, r as Analysis, st as SectionResult, t as SceneLike, u as ClosestHit, w as EditResult, wt as FieldHandle, x as DragSession, y as DistanceFieldDesc } from "./scene-like-Dq9_SaUL.js";
2
2
  import { t as FastMeshError } from "./core-CJ9D6U5A.js";
3
- import "./protocol-BGQAB0op.js";
3
+ import "./protocol-Dt0zgang.js";
4
4
  /** What {@link WorkerScene} needs of a Worker; a browser `Worker` fits. */
5
5
  interface WorkerLike {
6
6
  postMessage(msg: unknown, transfer?: Transferable[]): void;
@@ -114,7 +114,7 @@ declare class WorkerScene implements SceneLike {
114
114
  * `"computing"` and its views are empty; its buffers arrive with that
115
115
  * status turning `"ready"`.
116
116
  */
117
- addMesh(positions: Positions64, indices: Indices, options?: Pick<AddMeshOptions, "origin" | "normals">): MeshHandle;
117
+ addMesh(positions: Positions64, indices: Indices, options?: Pick<AddMeshOptions, "origin" | "normals" | "uvs">): MeshHandle;
118
118
  /**
119
119
  * Removes a mesh, ending an active drag of it first. Later calls on it give
120
120
  * `UNKNOWN_MESH`; its mirrors stay readable until the removal is delivered
@@ -127,6 +127,14 @@ declare class WorkerScene implements SceneLike {
127
127
  * changes nothing, engine-side or here).
128
128
  */
129
129
  join(target: MeshHandle, source: MeshHandle, options: JoinOptions): Promise<JoinReport>;
130
+ /**
131
+ * Rigidly aligns `moving` to `fixed` by ICP from their placements as the
132
+ * Worker has them when the request runs; see `Scene.register`. An applied
133
+ * result reaches `placement()` with its batch, like a `setPlacement`.
134
+ * Not replayed by a restart: an unanswered one rejects with
135
+ * `INSTANCE_POISONED`, like an edit.
136
+ */
137
+ register(moving: MeshHandle, fixed: MeshHandle, options?: RegisterOptions): Promise<RegisterResult>;
130
138
  /**
131
139
  * Sets a mesh's placement (one undo step), scale included (`[1, 1, 1]`
132
140
  * when omitted); `placement()` follows when the result arrives.
@@ -141,7 +149,7 @@ declare class WorkerScene implements SceneLike {
141
149
  * getter returns the current mirror; a mirror is replaced when the slot
142
150
  * count changes or a buffer turns on or off, so get views right before use.
143
151
  */
144
- views(mesh: MeshHandle): MeshViews;
152
+ views(mesh: MeshHandle): SceneMeshViews;
145
153
  /**
146
154
  * The rule the mirrored colours and values are made by (a frozen copy of
147
155
  * the one given to `setColoring`, the same object until another rule is
@@ -164,7 +172,8 @@ declare class WorkerScene implements SceneLike {
164
172
  analyze(mesh: MeshHandle, options?: AnalyzeOptions): Promise<Analysis>;
165
173
  /** Scalar measurements of a mesh; see `Scene.measure`. */
166
174
  measure(mesh: MeshHandle): Promise<MeasureResult>;
167
- /** Runs one repair operation, or a list as one transaction; see `Scene.repair`. */
175
+ /** Runs one repair operation, a list as one transaction, or the auto pipeline; see `Scene.repair`. */
176
+ repair(mesh: MeshHandle, request: AutoRepairRequest): Promise<AutoRepairReport>;
168
177
  repair<const O extends RepairOp>(mesh: MeshHandle, op: O): Promise<RepairReportOf<O>>;
169
178
  repair<const O extends readonly RepairOp[]>(mesh: MeshHandle, ops: O): Promise<{ -readonly [K in keyof O]: RepairReportOf<O[K]>; }>;
170
179
  /** Undoes the latest step; an active drag is ended first. */
@@ -1,5 +1,5 @@
1
+ import { a as FieldHandle, c as rotationMatrix, l as targetsOf, o as MeshHandle, r as copyRule, s as SectionHandle, t as ViewGuard, u as checkRegisterOptions } from "./views-mp7Mf8CQ.js";
1
2
  import { o as reportListenerError, t as FastMeshError } from "./core-4OcWKu3r.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-CUBMOK0U.js";
3
3
  import { a as supersedes, n as isLastWins, r as keyOf } from "./protocol-Ci9LLiwO.js";
4
4
  // src/worker/client.ts
5
5
  /**
@@ -46,6 +46,7 @@ const STRIDE = {
46
46
  normals: 3,
47
47
  colors: 4,
48
48
  values: 1,
49
+ uvs: 2,
49
50
  indices: 3
50
51
  };
51
52
  const BUFFERS = Object.keys(STRIDE);
@@ -54,6 +55,7 @@ const MAKE = {
54
55
  normals: (b) => new Float32Array(b),
55
56
  colors: (b) => new Uint8Array(b),
56
57
  values: (b) => new Float32Array(b),
58
+ uvs: (b) => new Float32Array(b),
57
59
  indices: (b) => new Uint32Array(b)
58
60
  };
59
61
  const IDENTITY = [
@@ -70,7 +72,10 @@ const IDENTITY = [
70
72
  /** The buffers a batch transfers: those of its mesh adds. */
71
73
  function transferOf(batch) {
72
74
  const transfer = [];
73
- for (const req of batch) if (req.kind === "addMesh") transfer.push(req.positions, req.indices);
75
+ for (const req of batch) if (req.kind === "addMesh") {
76
+ transfer.push(req.positions, req.indices);
77
+ if (req.uvs !== void 0) transfer.push(req.uvs);
78
+ }
74
79
  return transfer;
75
80
  }
76
81
  /** The most failed requests kept for `restart()`. */
@@ -850,6 +855,7 @@ var WorkerScene = class WorkerScene {
850
855
  normals: c.normals,
851
856
  colors: c.colors,
852
857
  indices: c.indices,
858
+ ...c.uvs === void 0 ? {} : { uvs: c.uvs },
853
859
  fieldsChanged: c.fields.flatMap((id) => this.#fields.get(id)?.handle ?? []),
854
860
  sectionsChanged: c.sections.flatMap((id) => this.#sections.get(id)?.handle ?? [])
855
861
  };
@@ -862,14 +868,15 @@ var WorkerScene = class WorkerScene {
862
868
  st.normals = null;
863
869
  st.colors = null;
864
870
  st.values = null;
871
+ st.uvs = null;
865
872
  st.shown = null;
866
873
  this.#guard?.bump();
867
874
  }
868
875
  #applyBuffer(st, name, c) {
869
- const bytes = c.bytes[name];
870
- const ranges = c[name === "values" ? "colors" : name];
876
+ const bytes = c.bytes[name] ?? null;
877
+ const ranges = c[name === "values" ? "colors" : name] ?? [];
871
878
  if (bytes === null) {
872
- if ((name === "normals" || name === "colors" || name === "values") && st[name] !== null) {
879
+ if ((name === "normals" || name === "colors" || name === "values" || name === "uvs") && st[name] !== null) {
873
880
  st[name] = null;
874
881
  this.#guard?.bump();
875
882
  }
@@ -994,6 +1001,7 @@ var WorkerScene = class WorkerScene {
994
1001
  this.#alive();
995
1002
  const p = copyArray(positions, "positions", (x) => x instanceof Float32Array ? x.slice() : Float64Array.from(x));
996
1003
  const i = copyArray(indices, "indices", (x) => Uint32Array.from(x));
1004
+ const uvs = options.uvs === void 0 ? void 0 : copyArray(options.uvs, "uvs", (x) => Float32Array.from(x));
997
1005
  const origin = options.origin === void 0 ? boxCentre(p) : [
998
1006
  options.origin[0],
999
1007
  options.origin[1],
@@ -1014,6 +1022,7 @@ var WorkerScene = class WorkerScene {
1014
1022
  normals: null,
1015
1023
  colors: null,
1016
1024
  values: null,
1025
+ uvs: null,
1017
1026
  shown: null,
1018
1027
  pendingRules: /* @__PURE__ */ new Map(),
1019
1028
  indices: /* @__PURE__ */ new Uint32Array(0),
@@ -1047,6 +1056,7 @@ var WorkerScene = class WorkerScene {
1047
1056
  positions: p.buffer,
1048
1057
  f64: !(p instanceof Float32Array),
1049
1058
  indices: i.buffer,
1059
+ ...uvs === void 0 ? {} : { uvs: uvs.buffer },
1050
1060
  options: {
1051
1061
  origin,
1052
1062
  normals: st.normalsOn
@@ -1115,6 +1125,32 @@ var WorkerScene = class WorkerScene {
1115
1125
  for (const s of this.#sections.values()) if (!s.removed) s.meshes = s.meshes.filter((m) => m !== st);
1116
1126
  }
1117
1127
  /**
1128
+ * Rigidly aligns `moving` to `fixed` by ICP from their placements as the
1129
+ * Worker has them when the request runs; see `Scene.register`. An applied
1130
+ * result reaches `placement()` with its batch, like a `setPlacement`.
1131
+ * Not replayed by a restart: an unanswered one rejects with
1132
+ * `INSTANCE_POISONED`, like an edit.
1133
+ */
1134
+ register(moving, fixed, options = {}) {
1135
+ const m = this.#live(moving);
1136
+ const f = this.#live(fixed);
1137
+ try {
1138
+ checkRegisterOptions(m === f, options);
1139
+ } catch (e) {
1140
+ return Promise.reject(e);
1141
+ }
1142
+ if (this.#drag?.mesh === m || this.#drag?.mesh === f) this.#drag.end();
1143
+ const payload = copyInput(options, "options");
1144
+ return this.#ask((rev, qid) => ({
1145
+ kind: "register",
1146
+ rev,
1147
+ moving: m.id,
1148
+ fixed: f.id,
1149
+ payload,
1150
+ qid
1151
+ }), (v) => v);
1152
+ }
1153
+ /**
1118
1154
  * Sets a mesh's placement (one undo step), scale included (`[1, 1, 1]`
1119
1155
  * when omitted); `placement()` follows when the result arrives.
1120
1156
  */
@@ -1170,6 +1206,7 @@ var WorkerScene = class WorkerScene {
1170
1206
  this.#wantValues();
1171
1207
  return st.values === null ? null : wrap(st.values);
1172
1208
  },
1209
+ uvs: () => st.uvs === null ? null : wrap(st.uvs),
1173
1210
  indices: () => wrap(st.indices)
1174
1211
  };
1175
1212
  }
@@ -1996,7 +2033,7 @@ var WorkerScene = class WorkerScene {
1996
2033
  continue;
1997
2034
  }
1998
2035
  if (st.live) {
1999
- const { positions, indices } = liveGeometry(st);
2036
+ const { positions, indices, uvs } = liveGeometry(st);
2000
2037
  this.#push({
2001
2038
  kind: "addMesh",
2002
2039
  rev: ++this.#rev,
@@ -2004,6 +2041,7 @@ var WorkerScene = class WorkerScene {
2004
2041
  positions: positions.buffer,
2005
2042
  f64: true,
2006
2043
  indices: indices.buffer,
2044
+ ...uvs === null ? {} : { uvs: uvs.buffer },
2007
2045
  options: {
2008
2046
  origin: st.origin,
2009
2047
  normals: st.normalsOn
@@ -2256,6 +2294,7 @@ function liveGeometry(st) {
2256
2294
  let vertices = 0;
2257
2295
  for (let v = 0; v < slots; v++) if (index[v] === 0) index[v] = vertices++;
2258
2296
  const positions = new Float64Array(3 * vertices);
2297
+ const uvs = st.uvs === null ? null : new Float32Array(2 * vertices);
2259
2298
  const [ox, oy, oz] = st.origin;
2260
2299
  for (let v = 0; v < slots; v++) {
2261
2300
  const k = index[v];
@@ -2263,6 +2302,10 @@ function liveGeometry(st) {
2263
2302
  positions[3 * k] = p[3 * v] + ox;
2264
2303
  positions[3 * k + 1] = p[3 * v + 1] + oy;
2265
2304
  positions[3 * k + 2] = p[3 * v + 2] + oz;
2305
+ if (uvs !== null && st.uvs !== null) {
2306
+ uvs[2 * k] = st.uvs[2 * v];
2307
+ uvs[2 * k + 1] = st.uvs[2 * v + 1];
2308
+ }
2266
2309
  }
2267
2310
  }
2268
2311
  const indices = new Uint32Array(3 * triangles);
@@ -2278,7 +2321,8 @@ function liveGeometry(st) {
2278
2321
  }
2279
2322
  return {
2280
2323
  positions,
2281
- indices
2324
+ indices,
2325
+ uvs
2282
2326
  };
2283
2327
  }
2284
2328
  /** Merges a later record into an earlier one of the same mesh. */
@@ -2303,6 +2347,7 @@ function merge(a, b) {
2303
2347
  normals: mergeRanges(a.normals, b.normals),
2304
2348
  colors: mergeRanges(a.colors, b.colors),
2305
2349
  indices: mergeRanges(a.indices, b.indices),
2350
+ ...a.uvs === void 0 && b.uvs === void 0 ? {} : { uvs: mergeRanges(a.uvs ?? [], b.uvs ?? []) },
2306
2351
  fieldsChanged: union(a.fieldsChanged, b.fieldsChanged),
2307
2352
  sectionsChanged: union(a.sectionsChanged, b.sectionsChanged)
2308
2353
  };
@@ -1,5 +1,5 @@
1
1
  import { s as setMemory, t as FastMeshError } from "./core-4OcWKu3r.js";
2
- import { i as useWasmScene, n as fieldSteps, r as meshAdds, t as Scene } from "./scene-BnkCS0sv.js";
2
+ import { i as useWasmScene, n as fieldSteps, r as meshAdds, t as Scene } from "./scene-CXtM_bxV.js";
3
3
  import { a as supersedes, n as isLastWins, r as keyOf, t as isInit } from "./protocol-Ci9LLiwO.js";
4
4
  /**
5
5
  * A module importing a shared memory `e.m` (1 page, at most 2), exporting
@@ -479,10 +479,11 @@ const STRIDE = {
479
479
  normals: 3,
480
480
  colors: 4,
481
481
  values: 1,
482
+ uvs: 2,
482
483
  indices: 3
483
484
  };
484
485
  /** A buffer's dirty ranges: the values change with the colours. */
485
- const rangesOf = (c, name) => c[name === "values" ? "colors" : name];
486
+ const rangesOf = (c, name) => c[name === "values" ? "colors" : name] ?? [];
486
487
  /** Copies the dirty elements of `view` into a fresh buffer: the whole view for `"all"`. */
487
488
  function copyRanges(view, ranges, stride) {
488
489
  if (ranges === "all") return view.slice().buffer;
@@ -814,6 +815,8 @@ var Engine = class {
814
815
  const indices = new Uint32Array(req.indices);
815
816
  if (positions.length % 3 !== 0) throw invalid("positions length must be a multiple of 3");
816
817
  if (indices.length % 3 !== 0) throw invalid("indices length must be a multiple of 3");
818
+ const uvs = req.uvs === void 0 ? void 0 : new Float32Array(req.uvs);
819
+ if (uvs !== void 0 && uvs.length !== 2 * positions.length / 3) throw invalid("uvs need 2 values per vertex");
817
820
  const token = this.#meshAdds.beginUpload(positions.length / 3, indices.length / 3, {
818
821
  ...req.options,
819
822
  mode: "eager"
@@ -831,6 +834,13 @@ var Engine = class {
831
834
  this.#meshAdds.pushIndices(token, indices.subarray(at, at + n));
832
835
  await this.#maybeYield();
833
836
  }
837
+ if (uvs !== void 0) {
838
+ const u = Math.max(1, Math.floor(bytes / uvs.BYTES_PER_ELEMENT));
839
+ for (let at = 0; at < uvs.length; at += u) {
840
+ this.#meshAdds.pushUvs(token, uvs.subarray(at, at + u));
841
+ await this.#maybeYield();
842
+ }
843
+ }
834
844
  } catch (e) {
835
845
  try {
836
846
  this.#meshAdds.drop(token);
@@ -874,6 +884,7 @@ var Engine = class {
874
884
  case "edit":
875
885
  case "repair": return this.#pending(req.id);
876
886
  case "join": return this.#pending(req.target, req.source);
887
+ case "register": return this.#pending(req.moving, req.fixed);
877
888
  case "coloring": return this.#pending(req.id) || req.rule !== null && this.#fieldPending(req.rule?.field);
878
889
  case "fetchFieldValues": return this.#fieldPending(req.field);
879
890
  case "field": return req.desc !== void 0 ? this.#pending(req.desc.on, ...req.desc.to) : this.#fieldPending(req.field);
@@ -1185,7 +1196,8 @@ var Engine = class {
1185
1196
  * Whether the queued `req` makes a field step unit over `meshes` (the
1186
1197
  * meshes its fields are on and measured to) stale (§6.1): a drag move
1187
1198
  * (only with `moves`: within the starvation guard), a drag cancel or a
1188
- * placement, an edit, repair, compaction, join or removal of one of them,
1199
+ * placement, a registration of one of them, an edit, repair, compaction,
1200
+ * join or removal of one of them,
1189
1201
  * an undo or redo, or the removal of a field between two of them.
1190
1202
  */
1191
1203
  #makesStale(req, meshes, moves) {
@@ -1197,6 +1209,7 @@ var Engine = class {
1197
1209
  case "compact":
1198
1210
  case "removeMesh": return meshes.has(req.id);
1199
1211
  case "join": return meshes.has(req.target) || meshes.has(req.source);
1212
+ case "register": return meshes.has(req.moving);
1200
1213
  case "undo":
1201
1214
  case "redo": return true;
1202
1215
  case "field": {
@@ -1538,7 +1551,8 @@ var Engine = class {
1538
1551
  const positions = req.f64 ? new Float64Array(req.positions) : new Float32Array(req.positions);
1539
1552
  const h = s.addMesh(positions, new Uint32Array(req.indices), {
1540
1553
  ...req.options,
1541
- mode: "eager"
1554
+ mode: "eager",
1555
+ ...req.uvs === void 0 ? {} : { uvs: new Float32Array(req.uvs) }
1542
1556
  });
1543
1557
  this.#meshes.set(req.id, h);
1544
1558
  this.#meshIds.set(h, req.id);
@@ -1568,6 +1582,15 @@ var Engine = class {
1568
1582
  });
1569
1583
  return;
1570
1584
  }
1585
+ case "register": {
1586
+ const value = s.register(this.#mesh(req.moving), this.#mesh(req.fixed), req.payload);
1587
+ b.replies.push({
1588
+ qid: req.qid,
1589
+ ok: true,
1590
+ value
1591
+ });
1592
+ return;
1593
+ }
1571
1594
  case "compact":
1572
1595
  s.compact(this.#mesh(req.id));
1573
1596
  return;
@@ -1829,6 +1852,7 @@ var Engine = class {
1829
1852
  normals: v.normals()?.slice() ?? null,
1830
1853
  colors: v.colors()?.slice() ?? null,
1831
1854
  values: v.values?.()?.slice() ?? null,
1855
+ uvs: v.uvs()?.slice() ?? null,
1832
1856
  indices: v.indices().slice(),
1833
1857
  placement: s.placement(h),
1834
1858
  matrix4: Array.from(s.matrix4(h))
@@ -1949,6 +1973,7 @@ var Engine = class {
1949
1973
  normals: c.normals,
1950
1974
  colors: c.colors,
1951
1975
  indices: c.indices,
1976
+ ...c.uvs === void 0 ? {} : { uvs: c.uvs },
1952
1977
  fields: c.fieldsChanged.map((f) => this.#fieldIds.get(f)),
1953
1978
  sections: c.sectionsChanged.map((x) => this.#sectionIds.get(x)),
1954
1979
  vertexSlots: 0,
package/dist/io.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { _t as MeshHandle, t as SceneLike } from "./scene-like-BzkDNHCy.js";
1
+ import { Tt as MeshHandle, t as SceneLike } from "./scene-like-Dq9_SaUL.js";
2
2
  /** Shared by every exporter: whether local render coordinates are mapped to the world. */
3
3
  export interface ExportOptions {
4
4
  /**
@@ -77,7 +77,7 @@ export declare function exportOBJ(scene: SceneLike, mesh: MeshHandle, options?:
77
77
  export declare function exportPLY(scene: SceneLike, mesh: MeshHandle, options?: PlyExportOptions): Uint8Array;
78
78
  /**
79
79
  * glTF 2.0: one node, one mesh, one `TRIANGLES` primitive with `POSITION`
80
- * (plus `NORMAL` where present and `COLOR_0` as normalized RGBA bytes where
80
+ * (plus `TEXCOORD_0` as float pairs where the mesh has UVs, `NORMAL` where present and `COLOR_0` as normalized RGBA bytes where
81
81
  * the mesh is colored). Binary (default) returns a `.glb`; `binary: false`
82
82
  * a `.gltf` JSON with the buffer embedded as a base64 data URI.
83
83
  *
@@ -90,7 +90,7 @@ export declare function exportGLTF(scene: SceneLike, mesh: MeshHandle, options?:
90
90
  }): Uint8Array;
91
91
  /**
92
92
  * glTF 2.0 with `draco: true`: the same node, mesh and `TRIANGLES`
93
- * primitive, but the positions (plus normals and colors where present) ride
93
+ * primitive, but the positions (plus normals, colors and UVs where present) ride
94
94
  * a Draco bitstream in one buffer view instead of raw buffer views. The
95
95
  * primitive's accessors describe the decoded shape (POSITION keeps its
96
96
  * min/max); `extensionsUsed`/`extensionsRequired` name the extension.
@@ -113,6 +113,8 @@ export interface DracoQuantizationBits {
113
113
  normal?: number;
114
114
  /** COLOR bits. Defaults to `8` (lossless for byte colors). */
115
115
  color?: number;
116
+ /** TEX_COORD bits, over the UVs' range. Defaults to `16`. */
117
+ uv?: number;
116
118
  /**
117
119
  * TEX_COORD bits. Defaults to `12`. Validated but currently unused: UVs
118
120
  * ride issue #137 (there is no UV channel to encode yet).
@@ -163,18 +165,20 @@ export interface DracoEncodeOptions extends DracoCompressionOptions {
163
165
  * COLOR attribute. Each value must be an integer 0..255.
164
166
  */
165
167
  colors?: ArrayLike<number>;
168
+ /** Texture coordinates: 2 finite numbers per vertex. */
169
+ uvs?: ArrayLike<number>;
166
170
  }
167
171
  /**
168
172
  * Encodes a triangle mesh into standalone Draco bytes (a `.drc` file):
169
- * positions always, plus the `normals`/`colors` options when given.
173
+ * positions always, plus the `normals`/`colors`/`uvs` options when given.
170
174
  * Positions encode as 32-bit floats (wider inputs narrow).
171
175
  *
172
176
  * The draco3d encoder (WASM) initializes on first use; its module is shared
173
177
  * across calls. Needs the `draco3d` package installed unless `options`
174
178
  * supplies the module or its `.wasm`.
175
179
  *
176
- * Decodes through {@link decodeDraco} (positions and faces only: it maps
177
- * POSITION alone, so normals and colors need draco3d's own decoder).
180
+ * Decodes through {@link decodeDraco} (positions, faces and UVs: normals and
181
+ * colors need draco3d's own decoder).
178
182
  */
179
183
  export declare function encodeDraco(positions: ArrayLike<number>, indices: ArrayLike<number>, options?: DracoEncodeOptions): Promise<Uint8Array>;
180
184
  /**
@@ -186,8 +190,9 @@ export declare function encodeDraco(positions: ArrayLike<number>, indices: Array
186
190
  * Only uncompressed buffers are read. `KHR_draco_mesh_compression`
187
191
  * primitives throw (decode them with {@link importGLTFAsync}), as do sparse
188
192
  * accessors. External (non-embedded) `.bin` buffers load through
189
- * {@link importGLTFAsync}'s `resolveBuffer`. Animations, skins and materials
190
- * beyond per-vertex colors are skipped: the documented subset.
193
+ * {@link importGLTFAsync}'s `resolveBuffer`. Animations, skins, materials
194
+ * beyond per-vertex colors and `TEXCOORD_1` and up are skipped: the documented
195
+ * subset.
191
196
  */
192
197
  export interface ImportedMesh {
193
198
  /** The node name, else the mesh name, else `"mesh"` (deduplicated). */
@@ -200,6 +205,11 @@ export interface ImportedMesh {
200
205
  placement: Float64Array;
201
206
  /** RGBA bytes per vertex from `COLOR_0`, or `null` without colors. */
202
207
  colors: Uint8Array | null;
208
+ /**
209
+ * 2 floats per vertex from `TEXCOORD_0` (`scene.addMesh`'s `uvs`), or `null`
210
+ * without UVs. In glTF's convention: `v` points down from the image's top.
211
+ */
212
+ uvs: Float32Array | null;
203
213
  }
204
214
  /**
205
215
  * Reads a glTF 2.0 asset: a binary `.glb`, or a `.gltf` JSON whose buffers
@@ -223,6 +233,8 @@ export interface DecodedDracoMesh {
223
233
  positions: Float64Array;
224
234
  /** 3 vertex ids per triangle. */
225
235
  indices: Uint32Array;
236
+ /** 2 floats per vertex from the texture-coordinate attribute, or `null` without one. */
237
+ uvs: Float32Array | null;
226
238
  }
227
239
  /**
228
240
  * Supplies an external glTF buffer's bytes, by its `uri` as declared
@@ -280,7 +292,7 @@ export declare function decodeDraco(bytes: Uint8Array | ArrayBuffer, options?: D
280
292
  * (non-embedded) `.bin` buffers load through `options.resolveBuffer`. A Draco
281
293
  * primitive's positions and faces come from its compressed buffer view
282
294
  * (attribute ids from the extension); its node placement still bakes into
283
- * world positions, while colors read as `null` (compressed attributes beyond
295
+ * world positions and its `TEXCOORD_0` UVs, while colors read as `null` (compressed attributes beyond
284
296
  * POSITION are not mapped).
285
297
  *
286
298
  * Primitives without the extension decode synchronously in place, so assets