fast-mesh-wasm 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +488 -1
  2. package/dist/{api-D0o2HjaU.js → api-BUy7FRx7.js} +11 -11
  3. package/dist/client-Bp9FRd70.js +2278 -0
  4. package/dist/client-m2zSdFlu.d.ts +305 -0
  5. package/dist/colormap-D_xH5hI5.js +303 -0
  6. package/dist/core-Cke_kZ2e.js +113 -0
  7. package/dist/core-D2X9GPfK.d.ts +15 -0
  8. package/dist/engine-B-ZEzR1c.js +1818 -0
  9. package/dist/mesh-B16gV3oX.d.ts +130 -0
  10. package/dist/mesh-B8pae8WA.js +428 -0
  11. package/dist/node.d.ts +3 -2
  12. package/dist/node.js +5 -4
  13. package/dist/protocol-CAUYm1gd.js +68 -0
  14. package/dist/protocol-W9R-iGl5.d.ts +293 -0
  15. package/dist/r3f.d.ts +59 -0
  16. package/dist/r3f.js +165 -0
  17. package/dist/react-CTADh3NN.js +124 -0
  18. package/dist/react.d.ts +65 -0
  19. package/dist/react.js +1 -0
  20. package/dist/scene-BG3EEyfw.js +1243 -0
  21. package/dist/scene-like-B_3qm0u6.d.ts +925 -0
  22. package/dist/snapshot-Cf6NgDl7.js +104 -0
  23. package/dist/store-D3ErV6o-.js +1379 -0
  24. package/dist/store-DNnHN33A.d.ts +285 -0
  25. package/dist/store.d.ts +61 -0
  26. package/dist/store.js +105 -0
  27. package/dist/three.d.ts +118 -0
  28. package/dist/three.js +390 -0
  29. package/dist/views-BaZqBxlX.js +189 -0
  30. package/dist/wasm/fast_mesh_wasm.d.ts +458 -0
  31. package/dist/wasm/fast_mesh_wasm.js +1150 -0
  32. package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
  33. package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +74 -0
  34. package/dist/wasm-threads/fast_mesh_wasm.d.ts +540 -0
  35. package/dist/wasm-threads/fast_mesh_wasm.js +1513 -0
  36. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm +0 -0
  37. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm.d.ts +93 -0
  38. package/dist/wasm-threads/package.json +7 -0
  39. package/dist/wasm-threads/snippets/fast-mesh-wasm-ae14781a92c2789e/inline0.js +16 -0
  40. package/dist/wasm-threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +107 -0
  41. package/dist/web.d.ts +3 -2
  42. package/dist/web.js +4 -2
  43. package/dist/worker-engine.d.ts +248 -0
  44. package/dist/worker-engine.js +1 -0
  45. package/dist/worker-entry.d.ts +1 -0
  46. package/dist/worker-entry.js +11 -0
  47. package/dist/worker.d.ts +2 -0
  48. package/dist/worker.js +1 -0
  49. package/package.json +53 -4
  50. package/dist/api-HcskOwd7.d.ts +0 -43
@@ -0,0 +1,130 @@
1
+ import { W as MeshHandle, t as SceneLike } from "./scene-like-B_3qm0u6.js";
2
+ import * as THREE from "three";
3
+ //#region src/three/mesh.d.ts
4
+ /** Options of {@link bindMesh}. */
5
+ interface BindMeshOptions {
6
+ /**
7
+ * The material to draw with. Defaults to a new `MeshStandardMaterial`, which
8
+ * {@link BoundMesh.dispose} then disposes; a material passed here is used as
9
+ * given and left to the caller to dispose.
10
+ *
11
+ * The binding controls the material's `color`, `vertexColors`, `opacity`,
12
+ * `transparent` and `depthWrite` (colouring and {@link BoundMesh.setOpacity}
13
+ * change them), so do not share one material between bound meshes: give
14
+ * each its own (`material.clone()`). With `shading: "fragment"` the
15
+ * binding calls the material's `dispose()` when it binds and again when it
16
+ * is disposed and puts the material back (dropping its compiled program so
17
+ * it is rebuilt with, then without, the shading); the material stays usable.
18
+ */
19
+ material?: THREE.MeshStandardMaterial | THREE.MeshPhongMaterial | THREE.MeshLambertMaterial | THREE.MeshBasicMaterial;
20
+ /**
21
+ * The colour shown while the mesh has no colouring. Defaults to the given
22
+ * material's colour (left untouched), or light grey for the default material.
23
+ */
24
+ color?: THREE.ColorRepresentation;
25
+ /**
26
+ * Initial opacity in [0, 1], applied with {@link BoundMesh.setOpacity}.
27
+ * Without it, the default material is opaque and a given material keeps
28
+ * its `opacity`, `transparent` and `depthWrite`.
29
+ */
30
+ opacity?: number;
31
+ /**
32
+ * How a colouring is drawn.
33
+ *
34
+ * - `"vertex"` (the default): the engine's colours as a vertex attribute,
35
+ * interpolated across each triangle, so the edge between coloured and
36
+ * base-coloured vertices blurs over a triangle's width.
37
+ * - `"fragment"`: every fragment is coloured from the interpolated field
38
+ * value through the colouring's rule (a lookup texture and a shader chunk
39
+ * added to the material with `onBeforeCompile`, so `WebGLRenderer` only).
40
+ * Range edges and colour steps (a contact heatmap's tolerance band) are
41
+ * crisp iso-lines of the value, softened with `edgeSoftness`, and
42
+ * gradients are smooth per pixel. At a vertex the colour equals its
43
+ * vertex colour. Far (`Infinity`) and NaN values never tint their
44
+ * neighbours. Needs a scene with `coloring(mesh)` and
45
+ * `views(mesh).values` (`Scene` and `WorkerScene` have both); on another
46
+ * host the binding falls back to `"vertex"` ({@link BoundMesh.shading}),
47
+ * and so does a material three's `WebGLRenderer` does not build from its
48
+ * own shader chunks (a node material for `WebGPURenderer`, say), with a
49
+ * warning.
50
+ *
51
+ * The binding patches the material it draws with, so each fragment-shaded
52
+ * binding needs its own material (`material.clone()`): binding a material
53
+ * another live fragment-shaded binding uses throws `INVALID_ARGUMENT`.
54
+ * Disposing the binding puts the material back as it was (and disposes
55
+ * its compiled program, so a later binding recompiles with its own
56
+ * uniforms).
57
+ */
58
+ shading?: "vertex" | "fragment";
59
+ /**
60
+ * Fragment shading: the width, in the field's distance units, of the blend
61
+ * at each colour step (a range edge to the base colour, the edges of a
62
+ * contact band). 0 (the default) is a hard edge. Ignored by vertex shading.
63
+ * See {@link BoundMesh.setEdgeSoftness}.
64
+ */
65
+ edgeSoftness?: number;
66
+ }
67
+ /** A scene mesh bound to a THREE.Mesh by {@link bindMesh}. */
68
+ interface BoundMesh {
69
+ /**
70
+ * The mesh to add to a THREE.Scene. Its geometry has `position`, `normal`
71
+ * (when the scene mesh keeps normals), `color` (while colouring is on) and
72
+ * an index; its `matrix` is the scene mesh's world matrix
73
+ * (`matrixAutoUpdate` is off). The colour attribute is normalized `Uint16`
74
+ * RGBA: the engine's sRGB colours converted to three's linear working space.
75
+ */
76
+ readonly object: THREE.Mesh;
77
+ readonly mesh: MeshHandle;
78
+ /** The shading in use: `"fragment"` only when asked for and the scene supports it. */
79
+ readonly shading: "vertex" | "fragment";
80
+ /**
81
+ * Sets the fragment shading's edge softness (see
82
+ * {@link BindMeshOptions.edgeSoftness}): a finite number `>= 0`. Takes
83
+ * effect on the next render, with no recompile. A display setting: never
84
+ * recorded in history.
85
+ */
86
+ setEdgeSoftness(width: number): void;
87
+ /**
88
+ * Sets the opacity in [0, 1]. Below 1 the material is transparent and does
89
+ * not write depth. A display setting: never recorded in history.
90
+ */
91
+ setOpacity(alpha: number): void;
92
+ /**
93
+ * Stops following the scene and disposes the geometry (and the material when
94
+ * `bindMesh` created it). The object stays wherever it was added. Safe to
95
+ * call more than once, before or after the scene mesh is removed.
96
+ */
97
+ dispose(): void;
98
+ }
99
+ /**
100
+ * The part of a {@link BoundMesh} that `attachTransformControls` and
101
+ * `bindSection` use: the scene mesh and its THREE.Mesh. A full `BoundMesh`
102
+ * is one, and so is the binding `<FastMesh onBind>` delivers.
103
+ */
104
+ type MeshBinding = Pick<BoundMesh, "mesh" | "object">;
105
+ /**
106
+ * Binds a scene mesh to a new THREE.Mesh and keeps it in sync on every
107
+ * {@link SceneLike.commitFrame}: dirty ranges are copied into the attributes'
108
+ * mirrors and marked with `addUpdateRange`, attributes are recreated when the
109
+ * mesh's slot counts change, the colour attribute comes and goes with the
110
+ * mesh's colouring, and `object.matrix` follows its placement.
111
+ *
112
+ * Dead vertex slots keep stale positions, so the geometry's bounding box and
113
+ * sphere are computed from the vertices of live triangles only (a removed
114
+ * triangle reads `0, 0, 0` in the index). They are recomputed when positions
115
+ * or indices change, never on placement-only frames.
116
+ *
117
+ * With `shading: "fragment"` the colour attribute is replaced by the
118
+ * colouring's values (`fmValue`), coloured per fragment by a shader chunk the
119
+ * binding adds to the material (see {@link BindMeshOptions.shading}).
120
+ *
121
+ * When the scene mesh is removed, the binding detaches: it stops following
122
+ * the scene and leaves the object as it was (remove it from your THREE.Scene
123
+ * and call {@link BoundMesh.dispose}).
124
+ *
125
+ * The adapter only listens through {@link SceneLike.onChanges}: call
126
+ * `scene.commitFrame()` once per animation frame, before rendering.
127
+ */
128
+ declare function bindMesh(scene: SceneLike, mesh: MeshHandle, options?: BindMeshOptions): BoundMesh;
129
+ //#endregion
130
+ export { bindMesh as i, BoundMesh as n, MeshBinding as r, BindMeshOptions as t };
@@ -0,0 +1,428 @@
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";
3
+ import * as THREE from "three";
4
+ //#region src/three/mesh.ts
5
+ const DEFAULT_COLOR = 13421772;
6
+ const WHITE = new THREE.Color(16777215);
7
+ /**
8
+ * Update ranges listed on one attribute before they are folded into a single
9
+ * full range. Ranges pile up while a bound mesh is not rendered (culled,
10
+ * hidden, on-demand rendering), and three uploads each one separately.
11
+ */
12
+ const MAX_UPDATE_RANGES = 64;
13
+ /**
14
+ * Copies RGBA8 sRGB colours into the `Uint16` mirror at `at`: colour channels
15
+ * through {@link SRGB_TO_LINEAR16}, alpha (already linear) scaled from 255 to
16
+ * 65535. `at` is a multiple of 4.
17
+ */
18
+ const copyColors = (mirror, src, at) => {
19
+ for (let i = 0; i < src.length; i++) {
20
+ const j = at + i;
21
+ mirror[j] = (j & 3) === 3 ? src[i] * 257 : SRGB_TO_LINEAR16[src[i]];
22
+ }
23
+ };
24
+ /** How each buffer maps to an attribute: components per element and the mirror type. */
25
+ const BUFFERS = {
26
+ positions: {
27
+ name: "position",
28
+ itemSize: 3,
29
+ normalized: false,
30
+ make: (n) => new Float32Array(n)
31
+ },
32
+ normals: {
33
+ name: "normal",
34
+ itemSize: 3,
35
+ normalized: false,
36
+ make: (n) => new Float32Array(n)
37
+ },
38
+ colors: {
39
+ name: "color",
40
+ itemSize: 4,
41
+ normalized: true,
42
+ make: (n) => new Uint16Array(n)
43
+ },
44
+ values: {
45
+ name: "fmValue",
46
+ itemSize: 4,
47
+ normalized: false,
48
+ make: (n) => new Float32Array(n)
49
+ },
50
+ indices: {
51
+ name: "index",
52
+ itemSize: 3,
53
+ normalized: false,
54
+ make: (n) => new Uint32Array(n)
55
+ }
56
+ };
57
+ /**
58
+ * Binds a scene mesh to a new THREE.Mesh and keeps it in sync on every
59
+ * {@link SceneLike.commitFrame}: dirty ranges are copied into the attributes'
60
+ * mirrors and marked with `addUpdateRange`, attributes are recreated when the
61
+ * mesh's slot counts change, the colour attribute comes and goes with the
62
+ * mesh's colouring, and `object.matrix` follows its placement.
63
+ *
64
+ * Dead vertex slots keep stale positions, so the geometry's bounding box and
65
+ * sphere are computed from the vertices of live triangles only (a removed
66
+ * triangle reads `0, 0, 0` in the index). They are recomputed when positions
67
+ * or indices change, never on placement-only frames.
68
+ *
69
+ * With `shading: "fragment"` the colour attribute is replaced by the
70
+ * colouring's values (`fmValue`), coloured per fragment by a shader chunk the
71
+ * binding adds to the material (see {@link BindMeshOptions.shading}).
72
+ *
73
+ * When the scene mesh is removed, the binding detaches: it stops following
74
+ * the scene and leaves the object as it was (remove it from your THREE.Scene
75
+ * and call {@link BoundMesh.dispose}).
76
+ *
77
+ * The adapter only listens through {@link SceneLike.onChanges}: call
78
+ * `scene.commitFrame()` once per animation frame, before rendering.
79
+ */
80
+ function bindMesh(scene, mesh, options = {}) {
81
+ if (options.shading !== void 0 && options.shading !== "vertex" && options.shading !== "fragment") throw new FastMeshError("INVALID_ARGUMENT", "shading must be \"vertex\" or \"fragment\"");
82
+ checkSoftness(options.edgeSoftness ?? 0);
83
+ const ownsMaterial = options.material === void 0;
84
+ const material = options.material ?? new THREE.MeshStandardMaterial({ color: DEFAULT_COLOR });
85
+ const fragment = options.shading === "fragment" && typeof scene.coloring === "function" && typeof scene.views(mesh).values === "function" && patchable(material);
86
+ if (fragment && patched.has(material)) throw new FastMeshError("INVALID_ARGUMENT", "the material is already drawn by another fragment-shaded binding: give each binding its own (material.clone())");
87
+ const keys = fragment ? [
88
+ "positions",
89
+ "normals",
90
+ "values",
91
+ "indices"
92
+ ] : [
93
+ "positions",
94
+ "normals",
95
+ "colors",
96
+ "indices"
97
+ ];
98
+ if (options.color !== void 0) material.color.set(options.color);
99
+ const baseColor = material.color.clone();
100
+ const geometry = new THREE.BufferGeometry();
101
+ const object = new THREE.Mesh(geometry, material);
102
+ object.matrixAutoUpdate = false;
103
+ let vertexSlots = -1;
104
+ let triangleSlots = -1;
105
+ let colored = false;
106
+ let rule = null;
107
+ let shading;
108
+ const uniforms = fragment ? shadingUniforms(options.edgeSoftness ?? 0) : void 0;
109
+ const restoreMaterial = uniforms === void 0 ? void 0 : patchMaterial(material, uniforms);
110
+ /** The attribute of a buffer, or undefined when it is off. */
111
+ const attributeOf = (key) => key === "indices" ? geometry.getIndex() ?? void 0 : geometry.getAttribute(BUFFERS[key].name);
112
+ /** A fresh view of a buffer, or null when it is off. */
113
+ const viewOf = (key) => {
114
+ const v = scene.views(mesh);
115
+ switch (key) {
116
+ case "positions": return v.positions();
117
+ case "normals": return v.normals();
118
+ case "colors": return v.colors();
119
+ case "values": return shading === void 0 ? null : v.values?.() ?? null;
120
+ case "indices": return v.indices();
121
+ }
122
+ };
123
+ /** Mirror length of a buffer at the current slot counts. */
124
+ const lengthOf = (key) => key === "indices" ? 3 * triangleSlots : BUFFERS[key].itemSize * vertexSlots;
125
+ /**
126
+ * Copies `view[from, to)` into `mirror`, clamped to both. A lazy mesh's
127
+ * normals can be shorter than its slots until it is updated; the rest of the
128
+ * mirror then keeps its data. `subarray` gives a plain typed array even for
129
+ * a debug-mode Proxy view. Colours are converted from sRGB to linear, and
130
+ * values (one per slot, four mirror elements each) encoded.
131
+ */
132
+ const copy = (key, mirror, view, from, to) => {
133
+ if (key === "values") {
134
+ const end = Math.min(to / 4, view.length, mirror.length / 4);
135
+ if (end > from / 4) encodeValues(view, mirror, from / 4, end);
136
+ return;
137
+ }
138
+ const end = Math.min(to, view.length, mirror.length);
139
+ if (end <= from) return;
140
+ if (key === "colors") {
141
+ copyColors(mirror, view.subarray(from, end), from);
142
+ return;
143
+ }
144
+ mirror.set(view.subarray(from, end), from);
145
+ };
146
+ /** A new attribute for `key` holding the whole view, installed in the geometry. */
147
+ const create = (key, view) => {
148
+ const spec = BUFFERS[key];
149
+ const mirror = spec.make(lengthOf(key));
150
+ copy(key, mirror, view, 0, mirror.length);
151
+ if (key === "indices") geometry.setIndex(new THREE.BufferAttribute(mirror, 1));
152
+ else geometry.setAttribute(spec.name, new THREE.BufferAttribute(mirror, spec.itemSize, spec.normalized));
153
+ };
154
+ const remove = (key) => {
155
+ if (key === "indices") geometry.setIndex(null);
156
+ else geometry.deleteAttribute(BUFFERS[key].name);
157
+ };
158
+ const setColored = (on) => {
159
+ if (on === colored) return;
160
+ colored = on;
161
+ material.color.copy(on ? WHITE : baseColor);
162
+ if (uniforms !== void 0) {
163
+ uniforms.fmOn.value = on;
164
+ return;
165
+ }
166
+ material.vertexColors = on;
167
+ material.needsUpdate = true;
168
+ };
169
+ /**
170
+ * Fragment shading: follows the scene's rule for the mesh. Returns whether
171
+ * it changed, in which case every value is encoded again.
172
+ */
173
+ const followRule = () => {
174
+ if (uniforms === void 0) return false;
175
+ const now = scene.coloring?.(mesh) ?? null;
176
+ if (now === rule) return false;
177
+ rule = now;
178
+ shading = now === null ? void 0 : shadingOf(now);
179
+ if (shading !== void 0) setShadingUniforms(uniforms, shading);
180
+ return true;
181
+ };
182
+ /** Live triangles' vertices only: dead slots keep stale positions. */
183
+ const computeBounds = () => {
184
+ const position = attributeOf("positions");
185
+ const index = attributeOf("indices");
186
+ if (position === void 0 || index === void 0) return;
187
+ const p = position.array;
188
+ const t = index.array;
189
+ const box = geometry.boundingBox ??= new THREE.Box3();
190
+ box.makeEmpty();
191
+ const point = new THREE.Vector3();
192
+ const live = (k) => t[k] !== 0 || t[k + 1] !== 0 || t[k + 2] !== 0;
193
+ 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
+ if (box.isEmpty()) {
196
+ sphere.set(new THREE.Vector3(), -1);
197
+ return;
198
+ }
199
+ box.getCenter(sphere.center);
200
+ let r2 = 0;
201
+ for (let k = 0; k < t.length; k += 3) if (live(k)) for (let c = 0; c < 3; c++) r2 = Math.max(r2, sphere.center.distanceToSquared(point.fromArray(p, 3 * t[k + c])));
202
+ sphere.radius = Math.sqrt(r2);
203
+ };
204
+ const updateMatrix = () => {
205
+ object.matrix.fromArray(scene.matrix4(mesh));
206
+ object.matrixWorldNeedsUpdate = true;
207
+ };
208
+ /**
209
+ * Brings every buffer of `change` (all of them when it is undefined) into
210
+ * the geometry. Returns whether positions or indices changed.
211
+ */
212
+ const apply = (change) => {
213
+ const v = scene.views(mesh);
214
+ const vs = v.positions().length / 3;
215
+ const ts = v.indices().length / 3;
216
+ const resized = vs !== vertexSlots || ts !== triangleSlots;
217
+ vertexSlots = vs;
218
+ triangleSlots = ts;
219
+ let structural = false;
220
+ let geometryChanged = false;
221
+ const pending = [];
222
+ const ruleChanged = followRule();
223
+ for (const key of keys) {
224
+ const dirty = change === void 0 || key === "values" && ruleChanged ? "all" : change[key === "values" ? "colors" : key];
225
+ if (dirty !== "all" && dirty.length === 0 && !resized) continue;
226
+ const view = viewOf(key);
227
+ const attribute = attributeOf(key);
228
+ if (view === null) {
229
+ if (attribute !== void 0) {
230
+ structural = true;
231
+ pending.push(() => remove(key));
232
+ }
233
+ continue;
234
+ }
235
+ if (key === "positions" || key === "indices") geometryChanged = true;
236
+ if (attribute === void 0 || attribute.array.length !== lengthOf(key)) {
237
+ structural = true;
238
+ pending.push(() => create(key, view));
239
+ continue;
240
+ }
241
+ const mirror = attribute.array;
242
+ const itemSize = BUFFERS[key].itemSize;
243
+ if (dirty === "all") {
244
+ copy(key, mirror, view, 0, mirror.length);
245
+ attribute.addUpdateRange(0, mirror.length);
246
+ } else for (const [start, count] of dirty) {
247
+ copy(key, mirror, view, start * itemSize, (start + count) * itemSize);
248
+ attribute.addUpdateRange(start * itemSize, count * itemSize);
249
+ }
250
+ if (attribute.updateRanges.length > MAX_UPDATE_RANGES) {
251
+ attribute.clearUpdateRanges();
252
+ attribute.addUpdateRange(0, mirror.length);
253
+ }
254
+ attribute.needsUpdate = true;
255
+ }
256
+ if (structural) {
257
+ geometry.dispose();
258
+ for (const run of pending) run();
259
+ for (const key of keys) attributeOf(key)?.clearUpdateRanges();
260
+ }
261
+ setColored(attributeOf(fragment ? "values" : "colors") !== void 0);
262
+ return geometryChanged;
263
+ };
264
+ apply(void 0);
265
+ computeBounds();
266
+ updateMatrix();
267
+ let unsubscribe;
268
+ const detach = () => {
269
+ unsubscribe?.();
270
+ unsubscribe = void 0;
271
+ };
272
+ unsubscribe = scene.onChanges((changes) => {
273
+ for (const c of changes) {
274
+ if (c.mesh !== mesh) continue;
275
+ if (c.removed) {
276
+ detach();
277
+ return;
278
+ }
279
+ if (apply(c)) computeBounds();
280
+ if (c.placementChanged) updateMatrix();
281
+ }
282
+ });
283
+ let disposed = false;
284
+ const bound = {
285
+ object,
286
+ mesh,
287
+ shading: fragment ? "fragment" : "vertex",
288
+ setEdgeSoftness(width) {
289
+ checkSoftness(width);
290
+ if (uniforms !== void 0) uniforms.fmSoftness.value = width;
291
+ },
292
+ setOpacity(alpha) {
293
+ if (typeof alpha !== "number" || !(alpha >= 0 && alpha <= 1)) throw new FastMeshError("INVALID_ARGUMENT", "opacity must be a number in [0, 1]");
294
+ const transparent = alpha < 1;
295
+ if (material.transparent !== transparent) material.needsUpdate = true;
296
+ material.opacity = alpha;
297
+ material.transparent = transparent;
298
+ material.depthWrite = !transparent;
299
+ },
300
+ dispose() {
301
+ detach();
302
+ if (disposed) return;
303
+ disposed = true;
304
+ geometry.dispose();
305
+ uniforms?.fmLut.value?.dispose();
306
+ if (ownsMaterial) material.dispose();
307
+ else restoreMaterial?.();
308
+ }
309
+ };
310
+ if (options.opacity !== void 0) bound.setOpacity(options.opacity);
311
+ return bound;
312
+ }
313
+ /** `INVALID_ARGUMENT` unless `width` is a finite number `>= 0`. */
314
+ function checkSoftness(width) {
315
+ if (typeof width !== "number" || !Number.isFinite(width) || width < 0) throw new FastMeshError("INVALID_ARGUMENT", "edgeSoftness must be a finite number >= 0");
316
+ }
317
+ /** The fragment shading's uniforms (see `SHADING_FRAGMENT`), shared with the material's shader. */
318
+ function shadingUniforms(softness) {
319
+ return {
320
+ fmLut: { value: null },
321
+ fmCount: { value: 0 },
322
+ fmBuiltin: { value: true },
323
+ fmRange: { value: new THREE.Vector2() },
324
+ fmCenter: { value: 0 },
325
+ fmHasCenter: { value: false },
326
+ fmBelowBase: { value: false },
327
+ fmAboveBase: { value: true },
328
+ fmBase: { value: new THREE.Vector4() },
329
+ fmNan: { value: new THREE.Vector4() },
330
+ fmSoftness: { value: softness },
331
+ fmOn: { value: false }
332
+ };
333
+ }
334
+ /** Loads a rule's shading data into the uniforms; the texture is reused while its size holds. */
335
+ function setShadingUniforms(u, s) {
336
+ let lut = u.fmLut.value;
337
+ if (lut === null || lut.image.width !== s.width) {
338
+ lut?.dispose();
339
+ lut = new THREE.DataTexture(s.lut, s.width, 4, THREE.RGBAFormat, THREE.FloatType);
340
+ lut.minFilter = THREE.NearestFilter;
341
+ lut.magFilter = THREE.NearestFilter;
342
+ lut.generateMipmaps = false;
343
+ u.fmLut.value = lut;
344
+ } else lut.image.data.set(s.lut);
345
+ lut.needsUpdate = true;
346
+ u.fmCount.value = s.count;
347
+ u.fmBuiltin.value = s.builtin;
348
+ u.fmRange.value.set(s.range[0], s.range[1]);
349
+ u.fmHasCenter.value = !Number.isNaN(s.center);
350
+ u.fmCenter.value = Number.isNaN(s.center) ? 0 : s.center;
351
+ u.fmBelowBase.value = s.belowBase;
352
+ u.fmAboveBase.value = s.aboveBase;
353
+ u.fmBase.value.fromArray(s.base);
354
+ u.fmNan.value.fromArray(s.nan);
355
+ }
356
+ /** Materials a live fragment-shaded binding has patched. */
357
+ const patched = /* @__PURE__ */ new WeakSet();
358
+ /** The shader chunks fragment shading hooks into, in each stage. */
359
+ const HOOKS = {
360
+ vertex: ["#include <common>", "#include <begin_vertex>"],
361
+ fragment: ["#include <common>", "#include <color_fragment>"]
362
+ };
363
+ /** `ShaderLib` entries of the materials fragment shading supports, by `material.type`. */
364
+ const SHADER_LIB = {
365
+ MeshStandardMaterial: "standard",
366
+ MeshPhysicalMaterial: "physical",
367
+ MeshPhongMaterial: "phong",
368
+ MeshLambertMaterial: "lambert",
369
+ MeshBasicMaterial: "basic"
370
+ };
371
+ /**
372
+ * Whether `WebGLRenderer` builds the material from three's chunks with the
373
+ * hooks fragment shading needs; else warns that the binding uses vertex
374
+ * colours.
375
+ */
376
+ function patchable(material) {
377
+ const lib = THREE.ShaderLib[SHADER_LIB[material.type] ?? ""];
378
+ const ok = material.isNodeMaterial !== true && lib !== void 0 && HOOKS.vertex.every((h) => lib.vertexShader.includes(h)) && HOOKS.fragment.every((h) => lib.fragmentShader.includes(h));
379
+ if (!ok) console.warn(`fast-mesh-wasm: shading "fragment" needs a WebGLRenderer material built from three's shader chunks (MeshStandardMaterial, MeshPhongMaterial, MeshLambertMaterial or MeshBasicMaterial); ${material.type} is drawn with vertex colours.`);
380
+ return ok;
381
+ }
382
+ /**
383
+ * Adds the fragment shading to a material's shaders (`onBeforeCompile`, after
384
+ * any handler it had) under its own program cache key, and disposes the
385
+ * material's compiled program so the next render compiles it with these
386
+ * uniforms; turns its `vertexColors` off meanwhile. Returns the function
387
+ * that puts the material's handler, key and `vertexColors` back (disposing
388
+ * the program again).
389
+ */
390
+ function patchMaterial(material, uniforms) {
391
+ const before = material.onBeforeCompile;
392
+ const key = material.customProgramCacheKey;
393
+ const vertexColors = material.vertexColors;
394
+ material.vertexColors = false;
395
+ let warned = false;
396
+ const hook = (source, chunk, add) => {
397
+ if (!source.includes(chunk)) {
398
+ if (!warned) {
399
+ warned = true;
400
+ console.warn(`fast-mesh-wasm: fragment shading could not find ${chunk} in the material's shader; colours are not shown.`);
401
+ }
402
+ return source;
403
+ }
404
+ return source.replace(chunk, `${chunk}\n${add}`);
405
+ };
406
+ material.onBeforeCompile = function(shader, renderer) {
407
+ before.call(this, shader, renderer);
408
+ Object.assign(shader.uniforms, uniforms);
409
+ shader.vertexShader = hook(hook(shader.vertexShader, HOOKS.vertex[0], SHADING_VERTEX), HOOKS.vertex[1], " vFmValue = fmValue;");
410
+ shader.fragmentShader = hook(hook(shader.fragmentShader, HOOKS.fragment[0], SHADING_FRAGMENT), HOOKS.fragment[1], " if (fmOn) diffuseColor *= fmShade(vFmValue);");
411
+ };
412
+ material.customProgramCacheKey = function() {
413
+ return `${key.call(this)}|fast-mesh-fragment-shading`;
414
+ };
415
+ patched.add(material);
416
+ material.dispose();
417
+ material.needsUpdate = true;
418
+ return () => {
419
+ material.onBeforeCompile = before;
420
+ material.customProgramCacheKey = key;
421
+ material.vertexColors = vertexColors;
422
+ patched.delete(material);
423
+ material.dispose();
424
+ material.needsUpdate = true;
425
+ };
426
+ }
427
+ //#endregion
428
+ export { bindMesh as t };
package/dist/node.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { a as Vec3, i as Positions, n as Indices, o as computeBounds, r as InitInput, s as computeVertexNormals, t as Bounds } from "./api-HcskOwd7.js";
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";
2
+ import { n as FastMeshErrorCode, t as FastMeshError } from "./core-D2X9GPfK.js";
2
3
  //#region src/node.d.ts
3
4
  /**
4
5
  * Resolves immediately: in Node.js and Bun the module is ready as soon as it is imported.
@@ -7,4 +8,4 @@ import { a as Vec3, i as Positions, n as Indices, o as computeBounds, r as InitI
7
8
  */
8
9
  export declare function init(_input?: InitInput | Promise<InitInput>): Promise<void>;
9
10
  //#endregion
10
- export { type Bounds, type Indices, type InitInput, type Positions, type Vec3, 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 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,9 +1,10 @@
1
- import { n as computeVertexNormals, r as markInitialized, t as computeBounds } from "./api-D0o2HjaU.js";
1
+ import { t as FastMeshError } from "./core-Cke_kZ2e.js";
2
+ import { n as computeVertexNormals, r as markInitialized, t as computeBounds } from "./api-BUy7FRx7.js";
3
+ import { t as Scene } from "./scene-BG3EEyfw.js";
2
4
  import { initSync } from "./wasm/fast_mesh_wasm.js";
3
5
  import { readFileSync } from "node:fs";
4
6
  //#region src/node.ts
5
- initSync({ module: readFileSync(new URL("./wasm/fast_mesh_wasm_bg.wasm", import.meta.url)) });
6
- markInitialized();
7
+ markInitialized(initSync({ module: readFileSync(new URL("./wasm/fast_mesh_wasm_bg.wasm", import.meta.url)) }));
7
8
  /**
8
9
  * Resolves immediately: in Node.js and Bun the module is ready as soon as it is imported.
9
10
  * Accepts the same argument as the browser `init()` so the same code runs everywhere;
@@ -13,4 +14,4 @@ function init(_input) {
13
14
  return Promise.resolve();
14
15
  }
15
16
  //#endregion
16
- export { computeBounds, computeVertexNormals, init };
17
+ export { FastMeshError, Scene, computeBounds, computeVertexNormals, init };
@@ -0,0 +1,68 @@
1
+ //#region src/worker/protocol.ts
2
+ /** Whether a message to a Worker is its {@link InitMessage} (else a batch). */
3
+ function isInit(data) {
4
+ return !Array.isArray(data) && data?.kind === "init";
5
+ }
6
+ /**
7
+ * The key of a request: its own `key`, or a default naming what it targets
8
+ * (`mesh:<id>` for add and remove, `edit:<id>` for edits, repairs and
9
+ * compaction, `field:<id>`, `section:<id>` for section add and remove,
10
+ * `section:<id>:<aspects>` for a section `set`, such as `section:3:plane` or
11
+ * `section:3:plane+fill`, `history`). Queries have none.
12
+ */
13
+ function keyOf(req) {
14
+ if ("key" in req && req.key !== void 0) return req.key;
15
+ switch (req.kind) {
16
+ case "addMesh":
17
+ case "removeMesh": return `mesh:${req.id}`;
18
+ case "compact":
19
+ case "edit":
20
+ case "repair": return `edit:${req.id}`;
21
+ case "undo":
22
+ case "redo":
23
+ case "clearHistory": return "history";
24
+ case "field": return `field:${req.field}`;
25
+ case "section": return req.op === "set" ? `section:${req.section}:${sectionAspects(req.desc).join("+") || "none"}` : `section:${req.section}`;
26
+ default: return;
27
+ }
28
+ }
29
+ /** The aspects a section `set` changes, in application order. */
30
+ function sectionAspects(desc) {
31
+ return [
32
+ "plane",
33
+ "meshes",
34
+ "fill"
35
+ ].filter((a) => desc?.[a] !== void 0);
36
+ }
37
+ /**
38
+ * Whether only the latest of consecutive same-key requests of this kind
39
+ * matters: colouring, section plane/meshes/fill changes and drag moves. The
40
+ * engine drops such a request only when the next queued request with the
41
+ * same key is of the same kind, for the same target, and (for a section
42
+ * `set`) changes every aspect the earlier one changed; so a reused key never
43
+ * drops another target's or another aspect's change.
44
+ */
45
+ function isLastWins(req) {
46
+ return req.kind === "coloring" || req.kind === "section" && req.op === "set" || req.kind === "drag" && req.phase === "move";
47
+ }
48
+ /**
49
+ * Whether `later` makes the last-wins request `earlier` redundant: same kind,
50
+ * same target (mesh or section) and, for a section `set`, every aspect of
51
+ * `earlier` changed again. Keys are not compared here.
52
+ */
53
+ function supersedes(later, earlier) {
54
+ if (!isLastWins(earlier) || !isLastWins(later) || later.kind !== earlier.kind) return false;
55
+ switch (earlier.kind) {
56
+ case "coloring":
57
+ case "drag": return later.id === earlier.id;
58
+ case "section": {
59
+ const l = later;
60
+ if (l.section !== earlier.section) return false;
61
+ const changed = sectionAspects(l.desc);
62
+ return sectionAspects(earlier.desc).every((a) => changed.includes(a));
63
+ }
64
+ default: return false;
65
+ }
66
+ }
67
+ //#endregion
68
+ export { supersedes as a, sectionAspects as i, isLastWins as n, keyOf as r, isInit as t };