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
@@ -1,5 +1,5 @@
1
+ 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, u as checkRegisterOptions } from "./views-mp7Mf8CQ.js";
1
2
  import { a as release, c as wasmMemory, i as finalizer, n as call, r as ensureInitialized, t as FastMeshError } from "./core-4OcWKu3r.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-CUBMOK0U.js";
3
3
  import { WasmScene } from "./wasm/fast_mesh_wasm.js";
4
4
  // src/changes.ts
5
5
  const ADDED = 1;
@@ -10,6 +10,8 @@ const POSITIONS_ALL = 16;
10
10
  const NORMALS_ALL = 32;
11
11
  const COLORS_ALL = 64;
12
12
  const INDICES_ALL = 128;
13
+ const UVS = 256;
14
+ const UVS_ALL = 512;
13
15
  /** Decodes `[record_count, record...]`. */
14
16
  function decodeChanges(msg) {
15
17
  let at = 0;
@@ -49,6 +51,7 @@ function decodeChanges(msg) {
49
51
  normals: ranges((flags & NORMALS_ALL) !== 0),
50
52
  colors: ranges((flags & COLORS_ALL) !== 0),
51
53
  indices: ranges((flags & INDICES_ALL) !== 0),
54
+ ...(flags & UVS) !== 0 ? { uvs: ranges((flags & UVS_ALL) !== 0) } : {},
52
55
  fields: ids(),
53
56
  sections: ids()
54
57
  });
@@ -368,7 +371,8 @@ const EDIT_CODES = {
368
371
  addVertices: 1,
369
372
  addTriangles: 2,
370
373
  removeTriangles: 3,
371
- removeVertices: 4
374
+ removeVertices: 4,
375
+ setUvs: 5
372
376
  };
373
377
  /** An id list as the binding's `n, r, ids..., (slot, op, i)...`; see `crate::edit`. */
374
378
  function encodeIds(list, what, words) {
@@ -426,7 +430,16 @@ function encodeEdit(ops) {
426
430
  case "removeTriangles":
427
431
  encodeIds(o.triangles, `${what}: triangles`, words);
428
432
  break;
429
- case "removeVertices": encodeIds(o.vertices, `${what}: vertices`, words);
433
+ case "removeVertices":
434
+ encodeIds(o.vertices, `${what}: vertices`, words);
435
+ break;
436
+ case "setUvs": {
437
+ encodeIds(o.vertices, `${what}: vertices`, words);
438
+ const uvs = Float64Array.from(o.uvs ?? []);
439
+ if (uvs.length !== 2 * o.vertices.length) throw invalid(`${what}: uvs need 2 values per vertex`);
440
+ values.push(uvs);
441
+ break;
442
+ }
430
443
  }
431
444
  });
432
445
  const out = new Uint32Array(words.reduce((n, w) => n + w.length, 0));
@@ -463,12 +476,30 @@ const REPAIR_CODES = {
463
476
  simplify: 13,
464
477
  subdivide: 14
465
478
  };
479
+ /** The op code of an {@link AutoRepairRequest}; see `crate::edit` in the Rust crate. */
480
+ const AUTO_REPAIR_CODE = 15;
466
481
  const FALLOFF_CODES = {
467
482
  linear: 0,
468
483
  smooth: 1
469
484
  };
470
485
  const SUBDIVIDE_METHOD_CODES = { loop: 0 };
471
486
  /** An optional number for the binding: NaN when unset; an explicit NaN is rejected. */
487
+ /** The `status` codes of `WasmScene.register`, in order. */
488
+ const REGISTER_STATUSES = [
489
+ "converged",
490
+ "maxIterations",
491
+ "underconstrained",
492
+ "tooFewCorrespondences",
493
+ "diverged"
494
+ ];
495
+ /** The `not applied` codes of `WasmScene.register`, in order. */
496
+ const REGISTER_NOT_APPLIED = [
497
+ null,
498
+ "notRequested",
499
+ "notConverged",
500
+ "rmseAboveLimit",
501
+ "tooFewInliers"
502
+ ];
472
503
  function optional(v, what) {
473
504
  if (v === void 0) return NaN;
474
505
  if (typeof v !== "number" || Number.isNaN(v)) throw invalid(`${what} must be a number`);
@@ -494,6 +525,9 @@ function encodeLoopId(id, out) {
494
525
  for (const v of [minVertex, len]) if (!Number.isInteger(v) || v < 0 || v >= U32_LIMIT) throw invalid("a loop id's minVertex and len must be u32 integers");
495
526
  out.push(minVertex, len, Number(hash & 4294967295n), Number(hash >> 32n));
496
527
  }
528
+ function isAutoRepair(op) {
529
+ return op?.kind === "auto";
530
+ }
497
531
  /** A repair op list as the binding's `(ops, loops)`; see `crate::edit` in the Rust crate. */
498
532
  function encodeRepair(ops) {
499
533
  const values = [];
@@ -606,7 +640,11 @@ var Reader = class {
606
640
  return out;
607
641
  }
608
642
  };
609
- const SKIP_REASONS = ["bounds", "unclean"];
643
+ const SKIP_REASONS = [
644
+ "bounds",
645
+ "unclean",
646
+ "uvSeam"
647
+ ];
610
648
  const FAIL_REASONS = [
611
649
  "projectionFolds",
612
650
  "noValidTriangulation",
@@ -701,6 +739,16 @@ function decodeReport(op, r) {
701
739
  };
702
740
  }
703
741
  }
742
+ /** An auto repair's result, stage by stage in the order they ran; see `crate::edit` in the Rust crate. */
743
+ function decodeAutoReport(r) {
744
+ const ops = Object.keys(REPAIR_CODES);
745
+ const stages = {};
746
+ while (r.at < r.data.length) {
747
+ const op = ops[r.next()];
748
+ stages[op] = decodeReport(op, r);
749
+ }
750
+ return stages;
751
+ }
704
752
  /** An analysis result; see `encode_analysis` in the Rust crate. */
705
753
  function decodeAnalysis(r) {
706
754
  const loops = r.many(() => ({
@@ -896,7 +944,8 @@ var Scene = class {
896
944
  * identity, so {@link Scene.matrix4} maps the local coordinates back to
897
945
  * where they were given.
898
946
  *
899
- * @throws `INVALID_ARGUMENT` for bad lengths or options, `INVALID_INDEX` for an index out of range.
947
+ * @throws `INVALID_ARGUMENT` for bad lengths or options (`uvs` not 2 finite
948
+ * values per vertex included), `INVALID_INDEX` for an index out of range.
900
949
  */
901
950
  addMesh(positions, indices, options = {}) {
902
951
  const s = this.#scene();
@@ -904,7 +953,13 @@ var Scene = class {
904
953
  const origin = options.origin === void 0 ? void 0 : Float64Array.from(options.origin);
905
954
  const p = toFloat64(positions);
906
955
  const i = toUint32(indices);
907
- const id = call(() => s.add_mesh(p, i, origin, mode, options.normals ?? true));
956
+ const normals = options.normals ?? true;
957
+ if (options.uvs === void 0) {
958
+ const id = call(() => s.add_mesh(p, i, origin, mode, normals));
959
+ return this.#meshHandle(id[0], id[1]);
960
+ }
961
+ const uvs = options.uvs instanceof Float32Array ? options.uvs : Float32Array.from(options.uvs);
962
+ const id = call(() => s.add_mesh_with_uvs(p, i, uvs, origin, mode, normals));
908
963
  return this.#meshHandle(id[0], id[1]);
909
964
  }
910
965
  /**
@@ -1000,6 +1055,88 @@ var Scene = class {
1000
1055
  return this.#meshHandle(r[0], r[1]);
1001
1056
  }
1002
1057
  /**
1058
+ * Rigidly aligns the mesh `moving` to the mesh `fixed` by point-to-plane ICP,
1059
+ * with the closest points found through `fixed`'s BVH and trimmed by
1060
+ * `options.overlap`. A drag of either mesh ends first, recording its moves
1061
+ * as one step, once the arguments have been checked.
1062
+ *
1063
+ * **The initial guess is the current placements.** ICP finds the nearest
1064
+ * fit, so put the meshes roughly in place first with `setPlacement`.
1065
+ *
1066
+ * **Applying.** By default a good result becomes `moving`'s placement as one
1067
+ * undo step (`applied` in the result): converged, with `rmse` within `maxRmse`
1068
+ * and enough points in range. Otherwise nothing moves, and `notApplied` says
1069
+ * why; `placement` still holds the estimate, for `setPlacement` if it will do.
1070
+ * `apply: false` only returns it.
1071
+ *
1072
+ * **Undetermined poses.** A plane's slide and a sphere's or a cylinder's spin
1073
+ * are not fixed by the data, though facets or noise can let the iteration
1074
+ * settle with a tiny `rmse`. These report `"underconstrained"` and list the
1075
+ * motions in `undetermined`. So do coarse regular meshes with exact fits close
1076
+ * by: a 16-sided sphere fits every 22.5 degrees. The check is local, so a
1077
+ * cube's 90-degree symmetry does not count. It adds a bounded cost: up to 12
1078
+ * restarts of up to 12 steps on at most 10,000 points.
1079
+ *
1080
+ * **Scales.** Only rotation and translation are solved. `moving`'s scale is
1081
+ * applied to its points and kept. `fixed`'s scale, uniform or not, is
1082
+ * followed exactly on a copy baked through it, so each such call costs a BVH
1083
+ * build. All distances are in world units.
1084
+ *
1085
+ * @throws `UNKNOWN_MESH` for a removed handle; `INVALID_ARGUMENT` for one
1086
+ * mesh twice, a mesh without triangles or an invalid option; `STALE_BVH` for
1087
+ * a stale Manual `fixed`. Bad options and one mesh twice change nothing,
1088
+ * and a drag keeps running. The other errors come after a drag has ended, and
1089
+ * change nothing else.
1090
+ */
1091
+ register(moving, fixed, options = {}) {
1092
+ const m = this.#id(moving);
1093
+ const f = this.#id(fixed);
1094
+ checkRegisterOptions(moving === fixed, options);
1095
+ const maxIterations = optional(options.maxIterations, "maxIterations");
1096
+ const tolerance = optional(options.tolerance, "tolerance");
1097
+ const overlap = optional(options.overlap, "overlap");
1098
+ const maxDistance = optional(options.maxDistance, "maxDistance");
1099
+ const maxSamples = optional(options.maxSamples, "maxSamples");
1100
+ const maxRmse = optional(options.maxRmse, "maxRmse");
1101
+ const apply = options.apply ?? true;
1102
+ if (this.#drag?.mesh === moving || this.#drag?.mesh === fixed) this.#drag.end();
1103
+ const r = call(() => this.#scene().register(m.index, m.generation, f.index, f.generation, maxIterations, tolerance, overlap, maxDistance, maxSamples, apply, maxRmse));
1104
+ const status = REGISTER_STATUSES[r[17]];
1105
+ const undetermined = [];
1106
+ for (let at = 24; at < r.length; at += 10) undetermined.push({
1107
+ translation: vec3At(r, at),
1108
+ rotation: vec3At(r, at + 3),
1109
+ about: vec3At(r, at + 6),
1110
+ alternativeRmse: r[at + 9]
1111
+ });
1112
+ return {
1113
+ placement: {
1114
+ rotation: Array.from(r.subarray(0, 9)),
1115
+ translation: [
1116
+ r[9],
1117
+ r[10],
1118
+ r[11]
1119
+ ],
1120
+ scale: [
1121
+ r[12],
1122
+ r[13],
1123
+ r[14]
1124
+ ]
1125
+ },
1126
+ rmse: r[15],
1127
+ iterations: r[16],
1128
+ converged: status === "converged",
1129
+ status,
1130
+ applied: r[18] === 1,
1131
+ samples: r[19],
1132
+ inliers: r[20],
1133
+ conditioning: r[21],
1134
+ notApplied: REGISTER_NOT_APPLIED[r[22]],
1135
+ maxRmse: r[23],
1136
+ undetermined
1137
+ };
1138
+ }
1139
+ /**
1003
1140
  * Sets a mesh's placement: world = rotation · (scale · local) + translation,
1004
1141
  * where local is relative to the mesh origin. A quaternion is normalised
1005
1142
  * and converted in double precision. The scale defaults to `[1, 1, 1]`
@@ -1149,6 +1286,7 @@ var Scene = class {
1149
1286
  normals: c.normals,
1150
1287
  colors: c.colors,
1151
1288
  indices: c.indices,
1289
+ ...c.uvs === void 0 ? {} : { uvs: c.uvs },
1152
1290
  fieldsChanged: c.fields.map((f) => this.#rawHandle(this.#fields, () => new FieldHandle(), f)),
1153
1291
  sectionsChanged: c.sections.map((x) => this.#rawHandle(this.#sections, () => new SectionHandle(), x))
1154
1292
  }));
@@ -1424,6 +1562,11 @@ var Scene = class {
1424
1562
  }
1425
1563
  repair(mesh, op) {
1426
1564
  const { index, generation } = this.#id(mesh);
1565
+ if (isAutoRepair(op)) {
1566
+ const values = Float64Array.of(AUTO_REPAIR_CODE, optional(op.weldTolerance, "weldTolerance"), optional(op.minTriangles, "minTriangles"), optional(op.maxEdges, "maxEdges"), op.fair === void 0 ? NaN : flagOf(op.fair, true));
1567
+ const noLoops = /* @__PURE__ */ new Uint32Array();
1568
+ return decodeAutoReport(new Reader(call(() => this.#scene().repair(index, generation, values, noLoops))));
1569
+ }
1427
1570
  const ops = Array.isArray(op) ? op : [op];
1428
1571
  const { values, loops } = encodeRepair(ops);
1429
1572
  const r = new Reader(call(() => this.#scene().repair(index, generation, values, loops)));
@@ -1837,6 +1980,7 @@ var Scene = class {
1837
1980
  },
1838
1981
  pushPositions: (token, chunk) => call(() => scene.#scene().add_mesh_push_positions(token, chunk)),
1839
1982
  pushIndices: (token, chunk) => call(() => scene.#scene().add_mesh_push_indices(token, chunk)),
1983
+ pushUvs: (token, chunk) => call(() => scene.#scene().add_mesh_push_uvs(token, chunk)),
1840
1984
  step: (token, budget) => call(() => scene.#scene().add_mesh_step(token, budget)),
1841
1985
  buffers: (token) => {
1842
1986
  const [pp, pl, np, nl, ip, il] = call(() => scene.#peek().add_mesh_buffers(token));
@@ -128,9 +128,20 @@ interface MeshViews {
128
128
  * provide it.
129
129
  */
130
130
  values?(): Float32Array | null;
131
+ /**
132
+ * Texture coordinates, 2 floats per vertex slot, or `null` for a mesh
133
+ * without them (never given, or dropped by an operation: see
134
+ * `docs/uv-channel.md`). Optional for other {@link SceneLike} hosts; `Scene`
135
+ * and `WorkerScene` provide it ({@link SceneMeshViews}).
136
+ */
137
+ uvs?(): Float32Array | null;
131
138
  /** 3 vertex indices per triangle slot; a removed triangle reads `0, 0, 0`. */
132
139
  indices(): Uint32Array;
133
140
  }
141
+ /** {@link MeshViews} of `Scene` and `WorkerScene`, which always provide `uvs`. */
142
+ interface SceneMeshViews extends MeshViews {
143
+ uvs(): Float32Array | null;
144
+ }
134
145
  /** `[start, count]` in elements: vertex slots, or triangle slots for indices. */
135
146
  type Range = readonly [start: number, count: number];
136
147
  /** A snapshot of selected vertices of one mesh; see the module docs. */
@@ -208,6 +219,12 @@ interface MeshChange {
208
219
  colors: Range[] | "all";
209
220
  /** Triangle slots. */
210
221
  indices: Range[] | "all";
222
+ /**
223
+ * Vertex slots. Only on a record of a mesh that has UVs or just lost them:
224
+ * `"all"` with `views(mesh).uvs()` reading `null` means an operation dropped
225
+ * them, and `"all"` after `undo` that they came back.
226
+ */
227
+ uvs?: Range[] | "all";
211
228
  fieldsChanged: FieldHandle[];
212
229
  sectionsChanged: SectionHandle[];
213
230
  }
@@ -276,6 +293,13 @@ interface AddMeshOptions {
276
293
  mode?: UpdateMode;
277
294
  /** Keep vertex normals up to date. Defaults to `true`. */
278
295
  normals?: boolean;
296
+ /**
297
+ * Texture coordinates: 2 finite values per vertex, stored as `f32` and read
298
+ * back with `views(mesh).uvs()`. Without them the mesh has no UV channel and
299
+ * pays nothing. Every operation keeps them aligned or drops them, undoably;
300
+ * see `docs/uv-channel.md`. Weld keeps seams apart.
301
+ */
302
+ uvs?: Float32Array | readonly number[];
279
303
  }
280
304
  /** Options of the {@link Scene} constructor. */
281
305
  interface SceneOptions {
@@ -540,6 +564,18 @@ type EditOp = {
540
564
  } | {
541
565
  op: "removeVertices";
542
566
  vertices: Uint32Array | readonly number[] | readonly EditRef[];
567
+ } |
568
+ /**
569
+ * Sets the UVs of vertices (2 values each; undoable like the rest of the
570
+ * edit), `addVertices` ones included. `addVertices` alone gives a mesh with
571
+ * UVs the UV `(0, 0)`, and `setPositions` leaves them as they were.
572
+ *
573
+ * @throws `INVALID_ARGUMENT` on a mesh without UVs.
574
+ */
575
+ {
576
+ op: "setUvs";
577
+ vertices: Uint32Array | readonly (number | EditRef)[];
578
+ uvs: Float32Array | readonly number[];
543
579
  };
544
580
  /** What {@link Scene.edit} added. */
545
581
  interface EditResult {
@@ -824,7 +860,7 @@ interface FillReport {
824
860
  /** Loops left out: beyond a bound, or unclean (or open). */
825
861
  skipped: {
826
862
  id: LoopId;
827
- reason: "bounds" | "unclean";
863
+ reason: "bounds" | "unclean" | "uvSeam";
828
864
  }[];
829
865
  /** Selected loops that could not be filled; they stay open. */
830
866
  failed: {
@@ -919,6 +955,123 @@ interface JoinReport {
919
955
  /** Bridge triangles between the two loops. */
920
956
  bridgeTrianglesAdded: number;
921
957
  }
958
+ /** Options of {@link Scene.register}. */
959
+ interface RegisterOptions {
960
+ /** The most solver steps. 0 only measures the current placement. Default 50. */
961
+ maxIterations?: number;
962
+ /**
963
+ * Stops when one step moves every point by at most this fraction of the
964
+ * moving mesh's extent (the largest distance of its points from their
965
+ * centroid). Default `1e-6`.
966
+ */
967
+ tolerance?: number;
968
+ /**
969
+ * The fraction of the moving mesh expected to lie over the fixed one, in
970
+ * `(0, 1]`: each iteration uses that many of its points, closest first, so
971
+ * the rest (the part beyond the overlap, and outliers) do not pull the
972
+ * result. Set it a little below the true overlap for partial scans.
973
+ * Default 1: every point counts, and nothing is rejected.
974
+ */
975
+ overlap?: number;
976
+ /** Points farther than this from the fixed mesh (world units) are not used. Default: no limit. */
977
+ maxDistance?: number;
978
+ /**
979
+ * The most points of the moving mesh to use, evenly spaced over its
980
+ * triangles' centroids and its vertices. `rmse` is measured on these.
981
+ * Default 100,000.
982
+ */
983
+ maxSamples?: number;
984
+ /**
985
+ * Whether a good result becomes the moving mesh's placement, as one undo
986
+ * step: it must converge, with `rmse` within `maxRmse` and at least half of
987
+ * the points `overlap` expects in range. Anything else is not applied,
988
+ * whatever this says; {@link RegisterResult.notApplied} says why. Default
989
+ * `true`.
990
+ */
991
+ apply?: boolean;
992
+ /**
993
+ * The largest `rmse` (world units) that may be applied, to keep a wrong local
994
+ * minimum from moving the mesh. Default: 1% of the moving points' extent,
995
+ * reported as {@link RegisterResult.maxRmse}. Scans noisier than that need
996
+ * their own limit; `Infinity` turns the guard off.
997
+ */
998
+ maxRmse?: number;
999
+ }
1000
+ /** Why {@link Scene.register} did not apply its result. */
1001
+ type RegisterNotApplied = "notRequested" | "notConverged" | "rmseAboveLimit" | "tooFewInliers";
1002
+ /**
1003
+ * A rigid motion the data do not determine, in world coordinates: a point `p`
1004
+ * moves along `translation + rotation x (p - about)`, scaled so that the moving
1005
+ * mesh's points move by 1 (root mean square).
1006
+ */
1007
+ interface RegisterMotion {
1008
+ translation: Vec3;
1009
+ /** The rotation part, as an axis scaled by its rate. */
1010
+ rotation: Vec3;
1011
+ /** The point the rotation turns about: the moved points' centroid. */
1012
+ about: Vec3;
1013
+ /** The rmse of the other pose found along this motion, which fits as well. */
1014
+ alternativeRmse: number;
1015
+ }
1016
+ /**
1017
+ * Why {@link Scene.register} stopped:
1018
+ * - `"converged"`: a step fell below the tolerance, and restarting from displaced
1019
+ * poses came back to the result, or only found worse fits: the data determine
1020
+ * every rigid motion locally.
1021
+ * - `"maxIterations"`: the steps ran out first, with no motion found undetermined.
1022
+ * - `"underconstrained"`: the data do not determine the pose. A restart stayed
1023
+ * displaced with a fit as good, as for a plane's slide, or a sphere's or a
1024
+ * cylinder's spin, even when facets or noise let the iteration settle with a
1025
+ * tiny `rmse`. {@link RegisterResult.undetermined} names the motions, and the
1026
+ * pose along them is arbitrary.
1027
+ * - `"tooFewCorrespondences"`: fewer than six points have a usable closest
1028
+ * point.
1029
+ * - `"diverged"`: a step took points out of the range the query can represent.
1030
+ */
1031
+ type RegisterStatus = "converged" | "maxIterations" | "underconstrained" | "tooFewCorrespondences" | "diverged";
1032
+ /** What {@link Scene.register} found. */
1033
+ interface RegisterResult {
1034
+ /**
1035
+ * The moving mesh's aligned placement, with its scale unchanged: the
1036
+ * converged result, or the best estimate when it did not converge.
1037
+ */
1038
+ placement: Placement;
1039
+ /**
1040
+ * The root mean square distance (world units) from the used points to the
1041
+ * fixed mesh at `placement`; `Infinity` when no point has a closest point.
1042
+ */
1043
+ rmse: number;
1044
+ /** Solver steps taken. */
1045
+ iterations: number;
1046
+ /**
1047
+ * `status === "converged"`. ICP is local, so this says the iteration settled
1048
+ * and the data determine the result locally, not that it found the right
1049
+ * alignment: a far guess can settle in a wrong minimum. `maxRmse` guards
1050
+ * applying against that.
1051
+ */
1052
+ converged: boolean;
1053
+ /** Why iteration stopped. */
1054
+ status: RegisterStatus;
1055
+ /** Whether `placement` was set on the moving mesh. */
1056
+ applied: boolean;
1057
+ /** Why it was not; `null` exactly when `applied`. */
1058
+ notApplied: RegisterNotApplied | null;
1059
+ /** The `rmse` limit that applied (world units). */
1060
+ maxRmse: number;
1061
+ /** Points of the moving mesh sampled. */
1062
+ samples: number;
1063
+ /** Sampled points used at `placement`: the rest were trimmed or out of range. */
1064
+ inliers: number;
1065
+ /**
1066
+ * The smallest eigenvalue of the solver's normal equations over the largest
1067
+ * at the last step, in `[0, 1]`; 0 when no step ran. Geometry only, with no
1068
+ * reference to noise: a low value warns of a weak motion, but a high one does
1069
+ * not show that it is determined. That is `undetermined`.
1070
+ */
1071
+ conditioning: number;
1072
+ /** The motions the data do not determine; non-empty only when `"underconstrained"`. */
1073
+ undetermined: RegisterMotion[];
1074
+ }
922
1075
  /** Options of {@link Scene.cutByPlane}. */
923
1076
  interface CutOptions {
924
1077
  /**
@@ -942,6 +1095,33 @@ interface CutReport {
942
1095
  }
943
1096
  /** Which boolean for {@link Scene.boolean} to compute. */
944
1097
  type BooleanOp = "union" | "subtract" | "intersect";
1098
+ /**
1099
+ * The standard cleanup pipeline for {@link Scene.repair}: weld, remove
1100
+ * degenerate, orient, remove small components, fill holes, as one transaction.
1101
+ * The library owns the order; an option left out takes the library's default.
1102
+ */
1103
+ interface AutoRepairRequest {
1104
+ kind: "auto";
1105
+ /** Vertices at most this far apart are welded, in mesh units. Default `1e-5`. */
1106
+ weldTolerance?: number;
1107
+ /** Components with fewer triangles are removed; the largest always stays. Default `500`. */
1108
+ minTriangles?: number;
1109
+ /** Fill only holes with at most this many edges; `Infinity` fills any size. Default `64`. */
1110
+ maxEdges?: number;
1111
+ /** Refine and fair each fill so it follows the surrounding curvature. Default `true`. */
1112
+ fair?: boolean;
1113
+ }
1114
+ /**
1115
+ * What an {@link AutoRepairRequest} did, one report per stage, keyed by the
1116
+ * stage's {@link RepairOp} name. The keys iterate in the order the stages ran.
1117
+ */
1118
+ interface AutoRepairReport {
1119
+ weld: WeldReport;
1120
+ removeDegenerate: DegenerateReport;
1121
+ orient: OrientReport;
1122
+ removeSmallComponents: RemoveReport;
1123
+ fillHoles: FillReport;
1124
+ }
945
1125
  /** The report of a {@link RepairOp}. */
946
1126
  type RepairReport = WeldReport | DegenerateReport | RemoveReport | OrientReport | FillReport | InflateReport | SmoothReport | RemeshReport | BridgeReport | GrabReport | RelaxReport | OffsetReport | ShellReport | SimplifyReport | SubdivideReport;
947
1127
  /** The report type of a repair op. */
@@ -999,7 +1179,8 @@ declare class Scene implements SceneLike {
999
1179
  * identity, so {@link Scene.matrix4} maps the local coordinates back to
1000
1180
  * where they were given.
1001
1181
  *
1002
- * @throws `INVALID_ARGUMENT` for bad lengths or options, `INVALID_INDEX` for an index out of range.
1182
+ * @throws `INVALID_ARGUMENT` for bad lengths or options (`uvs` not 2 finite
1183
+ * values per vertex included), `INVALID_INDEX` for an index out of range.
1003
1184
  */
1004
1185
  addMesh(positions: Positions64, indices: Indices, options?: AddMeshOptions): MeshHandle;
1005
1186
  /**
@@ -1049,6 +1230,41 @@ declare class Scene implements SceneLike {
1049
1230
  * boolean changes nothing.
1050
1231
  */
1051
1232
  boolean(target: MeshHandle, source: MeshHandle, op: BooleanOp): MeshHandle;
1233
+ /**
1234
+ * Rigidly aligns the mesh `moving` to the mesh `fixed` by point-to-plane ICP,
1235
+ * with the closest points found through `fixed`'s BVH and trimmed by
1236
+ * `options.overlap`. A drag of either mesh ends first, recording its moves
1237
+ * as one step, once the arguments have been checked.
1238
+ *
1239
+ * **The initial guess is the current placements.** ICP finds the nearest
1240
+ * fit, so put the meshes roughly in place first with `setPlacement`.
1241
+ *
1242
+ * **Applying.** By default a good result becomes `moving`'s placement as one
1243
+ * undo step (`applied` in the result): converged, with `rmse` within `maxRmse`
1244
+ * and enough points in range. Otherwise nothing moves, and `notApplied` says
1245
+ * why; `placement` still holds the estimate, for `setPlacement` if it will do.
1246
+ * `apply: false` only returns it.
1247
+ *
1248
+ * **Undetermined poses.** A plane's slide and a sphere's or a cylinder's spin
1249
+ * are not fixed by the data, though facets or noise can let the iteration
1250
+ * settle with a tiny `rmse`. These report `"underconstrained"` and list the
1251
+ * motions in `undetermined`. So do coarse regular meshes with exact fits close
1252
+ * by: a 16-sided sphere fits every 22.5 degrees. The check is local, so a
1253
+ * cube's 90-degree symmetry does not count. It adds a bounded cost: up to 12
1254
+ * restarts of up to 12 steps on at most 10,000 points.
1255
+ *
1256
+ * **Scales.** Only rotation and translation are solved. `moving`'s scale is
1257
+ * applied to its points and kept. `fixed`'s scale, uniform or not, is
1258
+ * followed exactly on a copy baked through it, so each such call costs a BVH
1259
+ * build. All distances are in world units.
1260
+ *
1261
+ * @throws `UNKNOWN_MESH` for a removed handle; `INVALID_ARGUMENT` for one
1262
+ * mesh twice, a mesh without triangles or an invalid option; `STALE_BVH` for
1263
+ * a stale Manual `fixed`. Bad options and one mesh twice change nothing,
1264
+ * and a drag keeps running. The other errors come after a drag has ended, and
1265
+ * change nothing else.
1266
+ */
1267
+ register(moving: MeshHandle, fixed: MeshHandle, options?: RegisterOptions): RegisterResult;
1052
1268
  /**
1053
1269
  * Sets a mesh's placement: world = rotation · (scale · local) + translation,
1054
1270
  * where local is relative to the mesh origin. A quaternion is normalised
@@ -1096,7 +1312,7 @@ declare class Scene implements SceneLike {
1096
1312
  * view; re-acquire views after every scene call that may allocate, since a
1097
1313
  * kept one may read other data or be empty (see {@link MeshViews}).
1098
1314
  */
1099
- views(mesh: MeshHandle): MeshViews;
1315
+ views(mesh: MeshHandle): SceneMeshViews;
1100
1316
  /**
1101
1317
  * Everything that changed since the previous call, one record per mesh.
1102
1318
  * There is a single consumer: apps that use {@link Scene.onChanges} call
@@ -1189,9 +1405,12 @@ declare class Scene implements SceneLike {
1189
1405
  * Runs one repair operation and returns its report, or a list of them in
1190
1406
  * order and returns their reports. A list is one transaction: one undo step,
1191
1407
  * and when any operation fails nothing changes and nothing is recorded.
1408
+ * `{ kind: "auto" }` runs the standard cleanup pipeline the same way and
1409
+ * returns a report per stage; see {@link AutoRepairRequest}.
1192
1410
  *
1193
1411
  * @throws `INVALID_ARGUMENT` for invalid options (`fillHoles` needs a bound or `loops`); `STALE_LOOPS` when a loop id of `fillHoles` no longer matches a loop of the mesh.
1194
1412
  */
1413
+ repair(mesh: MeshHandle, request: AutoRepairRequest): AutoRepairReport;
1195
1414
  repair<const O extends RepairOp>(mesh: MeshHandle, op: O): RepairReportOf<O>;
1196
1415
  repair<const O extends readonly RepairOp[]>(mesh: MeshHandle, ops: O): { -readonly [K in keyof O]: RepairReportOf<O[K]>; };
1197
1416
  /**
@@ -1394,8 +1613,8 @@ interface SceneLike {
1394
1613
  /**
1395
1614
  * Views of the mesh's render buffers. Slot counts follow from them, so
1396
1615
  * `positions()` must be exactly 3 × vertex slots long and `indices()`
1397
- * exactly 3 × triangle slots long (normals 3 and colours 4 per vertex slot,
1398
- * when present): `positions().length / 3` vertex slots and
1616
+ * exactly 3 × triangle slots long (normals 3, colours 4 and UVs 2 per vertex
1617
+ * slot, when present): `positions().length / 3` vertex slots and
1399
1618
  * `indices().length / 3` triangle slots.
1400
1619
  */
1401
1620
  views(mesh: MeshHandle): MeshViews;
@@ -1423,4 +1642,4 @@ interface SceneLike {
1423
1642
  */
1424
1643
  bounds?(mesh: MeshHandle): Bounds | null;
1425
1644
  }
1426
- export { SectionPlane as $, JoinReport as A, computeBounds as At, RaycastOptions as B, FieldStatus as C, Placement as Ct, GrabReport as D, Quat as Dt, FindContactsOptions as E, Positions64 as Et, MeshDistance as F, RepairReport as G, RemeshReport as H, OffsetReport as I, Scene as J, RepairReportOf as K, OrientReport as L, MeasureResult as M, MeshChange as N, InflateReport as O, UpdateMode as Ot, MeshComponent as P, SectionGap as Q, OutOfRange as R, EditResult as S, Mat3 as St, FilledLoop as T, Positions as Tt, RemoveReport as U, RelaxReport as V, RepairOp as W, SectionContour as X, SceneOptions as Y, SectionDesc as Z, DistanceFieldDesc as _, MeshHandle as _t, BooleanOp as a, SubdivideReport as at, EditOp as b, Indices as bt, ClosestHit as c, BrushSelect as ct, Colormap as d, LassoSelect as dt, SectionResult as et, Contact as f, SelectSpec as ft, DegenerateReport as g, FieldHandle as gt, CutReport as h, MeshViews as ht, AnalyzeOptions as i, SmoothReport as it, LoopId as j, computeVertexNormals as jt, JoinOptions as k, Vec3 as kt, ClosestPointOptions as l, ComponentSelect as lt, CutOptions as m, Range as mt, AddMeshOptions as n, SignMode as nt, BoundaryLoop as o, ThicknessFieldDesc as ot, CurvatureFieldDesc as p, VertexSelection as pt, Rgba as q, Analysis as r, SimplifyReport as rt, BridgeReport as s, WeldReport as st, SceneLike as t, ShellReport as tt, ColorRule as u, IsolateReport as ut, DragOptions as v, SectionHandle as vt, FillReport as w, PlacementInput as wt, EditRef as x, InitInput as xt, DragSession as y, Bounds as yt, RayHit as z };
1645
+ export { RepairReportOf as $, InflateReport as A, Mat3 as At, OutOfRange as B, EditRef as C, SceneMeshViews as Ct, FilledLoop as D, Bounds as Dt, FillReport as E, SectionHandle as Et, MeshChange as F, Quat as Ft, RegisterOptions as G, RaycastOptions as H, MeshComponent as I, UpdateMode as It, RelaxReport as J, RegisterResult as K, MeshDistance as L, Vec3 as Lt, JoinReport as M, PlacementInput as Mt, LoopId as N, Positions as Nt, FindContactsOptions as O, Indices as Ot, MeasureResult as P, Positions64 as Pt, RepairReport as Q, OffsetReport as R, computeBounds as Rt, EditOp as S, MeshViews as St, FieldStatus as T, MeshHandle as Tt, RegisterMotion as U, RayHit as V, RegisterNotApplied as W, RemoveReport as X, RemeshReport as Y, RepairOp as Z, CutReport as _, IsolateReport as _t, AutoRepairReport as a, SectionGap as at, DragOptions as b, VertexSelection as bt, BoundaryLoop as c, ShellReport as ct, ClosestPointOptions as d, SmoothReport as dt, Rgba as et, ColorRule as f, SubdivideReport as ft, CutOptions as g, ComponentSelect as gt, CurvatureFieldDesc as h, BrushSelect as ht, AnalyzeOptions as i, SectionDesc as it, JoinOptions as j, Placement as jt, GrabReport as k, InitInput as kt, BridgeReport as l, SignMode as lt, Contact as m, WeldReport as mt, AddMeshOptions as n, SceneOptions as nt, AutoRepairRequest as o, SectionPlane as ot, Colormap as p, ThicknessFieldDesc as pt, RegisterStatus as q, Analysis as r, SectionContour as rt, BooleanOp as s, SectionResult as st, SceneLike as t, Scene as tt, ClosestHit as u, SimplifyReport as ut, DegenerateReport as v, LassoSelect as vt, EditResult as w, FieldHandle as wt, DragSession as x, Range as xt, DistanceFieldDesc as y, SelectSpec as yt, OrientReport as z, computeVertexNormals as zt };
@@ -1,7 +1,7 @@
1
1
  import { o as reportListenerError, t as FastMeshError } from "./core-4OcWKu3r.js";
2
- import { l as targetsOf } from "./views-CUBMOK0U.js";
2
+ import { l as targetsOf } from "./views-mp7Mf8CQ.js";
3
3
  import { i as sectionAspects } from "./protocol-Ci9LLiwO.js";
4
- import { a as watchStatusKeys, r as addFieldKeyed } from "./client-C61Kku4i.js";
4
+ import { a as watchStatusKeys, r as addFieldKeyed } from "./client-f895H_yB.js";
5
5
  import { a as combine, c as sameData, n as EMPTY_SNAPSHOT, o as frozenCopy, t as DEFAULT_DISPLAY } from "./snapshot-BkbGPspK.js";
6
6
  // src/store/host.ts
7
7
  /** Whether `scene` is a Worker scene (structurally: it reports key statuses). */
@@ -61,7 +61,7 @@ function localHost(scene) {
61
61
  removeMesh: (mesh) => scene.removeMesh(mesh),
62
62
  setPlacement: (mesh, placement) => scene.setPlacement(mesh, placement),
63
63
  edit: (mesh, ops) => promised(() => scene.edit(mesh, ops)),
64
- repair: (mesh, op) => promised(() => scene.repair(mesh, op)),
64
+ repair: ((mesh, op) => promised(() => scene.repair(mesh, op))),
65
65
  undo: () => {
66
66
  scene.undo();
67
67
  },
@@ -124,7 +124,7 @@ function workerHost(scene) {
124
124
  removeMesh: (mesh) => scene.removeMesh(mesh),
125
125
  setPlacement: (mesh, placement) => scene.setPlacement(mesh, placement),
126
126
  edit: (mesh, ops) => scene.edit(mesh, ops),
127
- repair: (mesh, op) => scene.repair(mesh, op),
127
+ repair: ((mesh, op) => scene.repair(mesh, op)),
128
128
  undo: () => scene.undo(),
129
129
  redo: () => scene.redo(),
130
130
  canUndo: () => scene.canUndo,
@@ -560,7 +560,6 @@ var SceneStore = class {
560
560
  this.#alive();
561
561
  return this.#settled(this.#host.edit(mesh, ops));
562
562
  }
563
- /** Repairs a mesh (one undo step). */
564
563
  repair(mesh, op) {
565
564
  this.#alive();
566
565
  return this.#settled(this.#host.repair(mesh, op));
@@ -1,8 +1,8 @@
1
- import { $ as SectionPlane, Et as Positions64, G as RepairReport, J as Scene, N as MeshChange, R as OutOfRange, S as EditResult, W as RepairOp, Z as SectionDesc, _t as MeshHandle, b as EditOp, bt as Indices, d as Colormap, n as AddMeshOptions, nt as SignMode, q as Rgba, t as SceneLike, vt as SectionHandle, wt as PlacementInput, y as DragSession } from "./scene-like-BzkDNHCy.js";
2
- import { i as WorkerScene } from "./client-tP6R9foI.js";
1
+ import { B as OutOfRange, Et as SectionHandle, F as MeshChange, Mt as PlacementInput, Ot as Indices, Pt as Positions64, Q as RepairReport, S as EditOp, Tt as MeshHandle, Z as RepairOp, a as AutoRepairReport, et as Rgba, it as SectionDesc, lt as SignMode, n as AddMeshOptions, o as AutoRepairRequest, ot as SectionPlane, p as Colormap, t as SceneLike, tt as Scene, w as EditResult, x as DragSession } from "./scene-like-Dq9_SaUL.js";
2
+ import { i as WorkerScene } from "./client-D7yfPOyU.js";
3
3
  import { t as FastMeshError } from "./core-CJ9D6U5A.js";
4
4
  /** Options of `SceneStore.addMesh`: those both scenes take (a store mesh is always eager). */
5
- type StoreAddMeshOptions = Pick<AddMeshOptions, "origin" | "normals">;
5
+ type StoreAddMeshOptions = Pick<AddMeshOptions, "origin" | "normals" | "uvs">;
6
6
  /**
7
7
  * The state of a mesh's or section's work: `"computing"` while it, or a
8
8
  * result it depends on, is pending; `"ready"` once applied; `"error"` when
@@ -170,6 +170,7 @@ declare class SceneStore {
170
170
  edit(mesh: MeshHandle, ops: readonly EditOp[]): Promise<EditResult>;
171
171
  /** Repairs a mesh (one undo step). */
172
172
  repair(mesh: MeshHandle, op: RepairOp | readonly RepairOp[]): Promise<RepairReport | RepairReport[]>;
173
+ repair(mesh: MeshHandle, request: AutoRepairRequest): Promise<AutoRepairReport>;
173
174
  /** Undoes the latest step. */
174
175
  undo(): void;
175
176
  /** Redoes the latest undone step. */
package/dist/store.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { nt as SignMode, q as Rgba } from "./scene-like-BzkDNHCy.js";
2
- import { _ as StoreAddMeshOptions, a as DisplayState, c as MeshState, d as SceneSnapshot, f as SectionParts, g as sectionState, h as meshState, i as ContactGroup, l as REMOVED_MESH_STATE, m as Status, n as SectionPatch, o as DistanceColoring, p as SectionState, r as createSceneStore, s as EMPTY_SNAPSHOT, t as SceneStore, u as REMOVED_SECTION_STATE } from "./store-BKFzSykN.js";
1
+ import { et as Rgba, lt as SignMode } from "./scene-like-Dq9_SaUL.js";
2
+ import { _ as StoreAddMeshOptions, a as DisplayState, c as MeshState, d as SceneSnapshot, f as SectionParts, g as sectionState, h as meshState, i as ContactGroup, l as REMOVED_MESH_STATE, m as Status, n as SectionPatch, o as DistanceColoring, p as SectionState, r as createSceneStore, s as EMPTY_SNAPSHOT, t as SceneStore, u as REMOVED_SECTION_STATE } from "./store-CIW19oCh.js";
3
3
  /** Options of {@link contactHeatmap}. Distances are in the meshes' units. */
4
4
  interface ContactHeatmapOptions {
5
5
  /** The penetration depth shown darkest (`deep`); deeper clamps to it. `> 0`. */
package/dist/store.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as FastMeshError } from "./core-4OcWKu3r.js";
2
2
  import { i as REMOVED_SECTION_STATE, l as sectionState, n as EMPTY_SNAPSHOT, r as REMOVED_MESH_STATE, s as meshState } from "./snapshot-BkbGPspK.js";
3
- import { n as createSceneStore, t as SceneStore } from "./store-CEd2y2KS.js";
3
+ import { n as createSceneStore, t as SceneStore } from "./store-C9h7GFFl.js";
4
4
  // src/store/heatmap.ts
5
5
  /** The default colours: `#7f0000`, `#ff6b6b`, `#ffffff`, `#4caf50`, `#1e3a8a`. */
6
6
  const DEFAULT_COLORS = {