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/dist/io.js CHANGED
@@ -10,10 +10,12 @@ function snapshot(scene, mesh, options) {
10
10
  const indices = views.indices().slice();
11
11
  const rawNormals = views.normals();
12
12
  const rawColors = views.colors();
13
+ const rawUvs = views.uvs?.() ?? null;
13
14
  const vertexSlots = positions.length / 3;
14
15
  const triangleSlots = indices.length / 3;
15
16
  const normals = rawNormals !== null && rawNormals !== void 0 && rawNormals.length >= positions.length ? rawNormals.slice() : null;
16
17
  const colors = rawColors !== null && rawColors !== void 0 && rawColors.length >= 4 / 3 * positions.length ? rawColors.slice() : null;
18
+ const uvs = rawUvs !== null && rawUvs.length >= 2 / 3 * positions.length ? rawUvs.slice() : null;
17
19
  const remap = new Int32Array(vertexSlots).fill(-1);
18
20
  const kept = new Uint32Array(indices.length);
19
21
  let triangles = 0;
@@ -39,6 +41,7 @@ function snapshot(scene, mesh, options) {
39
41
  const outPositions = new Float32Array(3 * vertices);
40
42
  const outNormals = normals !== null ? new Float32Array(3 * vertices) : null;
41
43
  const outColors = colors !== null ? new Uint8Array(4 * vertices) : null;
44
+ const outUvs = uvs !== null ? new Float32Array(2 * vertices) : null;
42
45
  for (let v = 0; v < vertexSlots; v++) {
43
46
  const to = remap[v];
44
47
  if (to === -1) continue;
@@ -56,12 +59,17 @@ function snapshot(scene, mesh, options) {
56
59
  outColors[4 * to + 2] = colors[4 * v + 2];
57
60
  outColors[4 * to + 3] = colors[4 * v + 3];
58
61
  }
62
+ if (outUvs !== null && uvs !== null) {
63
+ outUvs[2 * to] = uvs[2 * v];
64
+ outUvs[2 * to + 1] = uvs[2 * v + 1];
65
+ }
59
66
  }
60
67
  if (options?.applyPlacement !== false) applyMatrix(scene.matrix4(mesh), outPositions, outNormals);
61
68
  return {
62
69
  positions: outPositions,
63
70
  normals: outNormals,
64
71
  colors: outColors,
72
+ uvs: outUvs,
65
73
  indices: kept.subarray(0, 3 * triangles),
66
74
  triangles
67
75
  };
@@ -307,6 +315,7 @@ function exportGLTF(scene, mesh, options) {
307
315
  const vertices = snap.positions.length / 3;
308
316
  const useNormals = snap.normals !== null;
309
317
  const useColors = snap.colors !== null;
318
+ const useUvs = snap.uvs !== null;
310
319
  const positionBytes = new Uint8Array(snap.positions.buffer, snap.positions.byteOffset, snap.positions.byteLength);
311
320
  const normalBytes = snap.normals !== null ? new Uint8Array(snap.normals.buffer, snap.normals.byteOffset, snap.normals.byteLength) : null;
312
321
  const chunks = [positionBytes];
@@ -316,6 +325,7 @@ function exportGLTF(scene, mesh, options) {
316
325
  colorBytes = new Uint8Array(snap.colors.buffer, snap.colors.byteOffset, snap.colors.byteLength);
317
326
  chunks.push(colorBytes);
318
327
  }
328
+ if (snap.uvs !== null) chunks.push(new Uint8Array(snap.uvs.buffer, snap.uvs.byteOffset, snap.uvs.byteLength));
319
329
  const indicesCopy = new Uint32Array(snap.indices);
320
330
  const indicesChunk = new Uint8Array(indicesCopy.buffer, indicesCopy.byteOffset, indicesCopy.byteLength);
321
331
  chunks.push(indicesChunk);
@@ -336,10 +346,12 @@ function exportGLTF(scene, mesh, options) {
336
346
  const positionView = 0;
337
347
  const normalView = useNormals ? nextView++ : -1;
338
348
  const colorView = useColors ? nextView++ : -1;
349
+ const uvView = useUvs ? nextView++ : -1;
339
350
  const attributes = { POSITION: 0 };
340
351
  let accessorIndex = 1;
341
352
  if (useNormals) attributes["NORMAL"] = accessorIndex++;
342
353
  if (useColors) attributes["COLOR_0"] = accessorIndex++;
354
+ if (useUvs) attributes["TEXCOORD_0"] = accessorIndex++;
343
355
  const accessors = [{
344
356
  bufferView: positionView,
345
357
  componentType: 5126,
@@ -361,6 +373,12 @@ function exportGLTF(scene, mesh, options) {
361
373
  type: "VEC4",
362
374
  normalized: true
363
375
  });
376
+ if (useUvs) accessors.push({
377
+ bufferView: uvView,
378
+ componentType: 5126,
379
+ count: vertices,
380
+ type: "VEC2"
381
+ });
364
382
  accessors.push({
365
383
  bufferView: bufferViews.length - 1,
366
384
  componentType: 5125,
@@ -479,15 +497,15 @@ function toBase64(bytes) {
479
497
  }
480
498
  /**
481
499
  * Encodes a triangle mesh into standalone Draco bytes (a `.drc` file):
482
- * positions always, plus the `normals`/`colors` options when given.
500
+ * positions always, plus the `normals`/`colors`/`uvs` options when given.
483
501
  * Positions encode as 32-bit floats (wider inputs narrow).
484
502
  *
485
503
  * The draco3d encoder (WASM) initializes on first use; its module is shared
486
504
  * across calls. Needs the `draco3d` package installed unless `options`
487
505
  * supplies the module or its `.wasm`.
488
506
  *
489
- * Decodes through {@link decodeDraco} (positions and faces only: it maps
490
- * POSITION alone, so normals and colors need draco3d's own decoder).
507
+ * Decodes through {@link decodeDraco} (positions, faces and UVs: normals and
508
+ * colors need draco3d's own decoder).
491
509
  */
492
510
  async function encodeDraco(positions, indices, options) {
493
511
  const checkedPositions = checkedEncodePositions(positions);
@@ -495,7 +513,7 @@ async function encodeDraco(positions, indices, options) {
495
513
  const checkedNormals = checkedEncodeNormals(options?.normals, checkedPositions.length);
496
514
  const checkedColors = checkedEncodeColors(options?.colors, checkedPositions.length / 3);
497
515
  const settings = encodeSettings(options);
498
- return encodeMeshDraco(await encoderOf(options), checkedPositions, checkedIndices, checkedNormals, checkedColors, settings).bytes;
516
+ return encodeMeshDraco(await encoderOf(options), checkedPositions, checkedIndices, checkedNormals, checkedColors, checkedEncodeUvs(options?.uvs, checkedPositions.length / 3), settings).bytes;
499
517
  }
500
518
  /**
501
519
  * glTF 2.0 with `draco: true`: one node, one mesh, one `TRIANGLES`
@@ -513,7 +531,8 @@ async function exportGLTFDraco(scene, mesh, options) {
513
531
  const indices = checkedEncodeIndices(snap.indices, vertices);
514
532
  const normals = checkedEncodeNormals(snap.normals, positions.length);
515
533
  const colors = checkedEncodeColors(snap.colors, vertices);
516
- const { bytes, positionId, normalId, colorId } = encodeMeshDraco(await encoderOf(options?.dracoOptions), positions, indices, normals, colors, settings);
534
+ const uvs = checkedEncodeUvs(snap.uvs, vertices);
535
+ const { bytes, positionId, normalId, colorId, uvId } = encodeMeshDraco(await encoderOf(options?.dracoOptions), positions, indices, normals, colors, uvs, settings);
517
536
  const { min, max } = positionBounds(snap.positions);
518
537
  const attributes = { POSITION: 0 };
519
538
  const accessors = [{
@@ -544,6 +563,15 @@ async function exportGLTFDraco(scene, mesh, options) {
544
563
  });
545
564
  dracoAttributes["COLOR_0"] = colorId;
546
565
  }
566
+ if (uvs !== null) {
567
+ attributes["TEXCOORD_0"] = accessorIndex++;
568
+ accessors.push({
569
+ componentType: 5126,
570
+ count: vertices,
571
+ type: "VEC2"
572
+ });
573
+ dracoAttributes["TEXCOORD_0"] = uvId;
574
+ }
547
575
  accessors.push({
548
576
  componentType: 5125,
549
577
  count: indices.length,
@@ -592,6 +620,7 @@ function encodeSettings(options) {
592
620
  positionBits: checkedQuantizationBits(bits?.position, "position", 14),
593
621
  normalBits: checkedQuantizationBits(bits?.normal, "normal", 10),
594
622
  colorBits: checkedQuantizationBits(bits?.color, "color", 8),
623
+ uvBits: checkedQuantizationBits(bits?.uv, "uv", 16),
595
624
  level,
596
625
  preserveFaceOrder: options?.preserveFaceOrder === true
597
626
  };
@@ -645,12 +674,20 @@ function checkedEncodeColors(colors, vertices) {
645
674
  }
646
675
  return out;
647
676
  }
677
+ /** Copies UVs to floats (`null` without), checking length and finiteness. */
678
+ function checkedEncodeUvs(uvs, vertices) {
679
+ if (uvs === null || uvs === void 0) return null;
680
+ if (uvs.length !== 2 * vertices) throw new Error(`Draco: uvs need 2 numbers per vertex (got length ${uvs.length} for ${vertices} vertices)`);
681
+ const out = Float32Array.from(uvs);
682
+ for (let i = 0; i < out.length; i++) if (!Number.isFinite(out[i])) throw new Error(`Draco: uv ${Math.floor(i / 2)} is not finite`);
683
+ return out;
684
+ }
648
685
  /**
649
- * Builds the mesh (faces, POSITION, NORMAL/COLOR when present) and encodes
686
+ * Builds the mesh (faces, POSITION, NORMAL/COLOR/TEX_COORD when present) and encodes
650
687
  * it with the resolved settings. Colors ride a normalized uint8 attribute,
651
688
  * like glTF's `COLOR_0`. Throws when the encoder reports failure.
652
689
  */
653
- function encodeMeshDraco(module, positions, indices, normals, colors, settings) {
690
+ function encodeMeshDraco(module, positions, indices, normals, colors, uvs, settings) {
654
691
  const mesh = new module.Mesh();
655
692
  const builder = new module.MeshBuilder();
656
693
  try {
@@ -658,17 +695,20 @@ function encodeMeshDraco(module, positions, indices, normals, colors, settings)
658
695
  const positionId = builder.AddFloatAttributeToMesh(mesh, module.POSITION, positions.length / 3, 3, positions);
659
696
  let normalId = null;
660
697
  let colorId = null;
698
+ let uvId = null;
661
699
  if (normals !== null) normalId = builder.AddFloatAttributeToMesh(mesh, module.NORMAL, normals.length / 3, 3, normals);
662
700
  if (colors !== null) {
663
701
  colorId = builder.AddUInt8Attribute(mesh, module.COLOR, colors.length / 4, 4, colors);
664
702
  builder.SetNormalizedFlagForAttribute(mesh, colorId, true);
665
703
  }
704
+ if (uvs !== null) uvId = builder.AddFloatAttributeToMesh(mesh, module.TEX_COORD, uvs.length / 2, 2, uvs);
666
705
  const encoder = new module.Encoder();
667
706
  try {
668
707
  encoder.SetSpeedOptions(10 - settings.level, 10 - settings.level);
669
708
  encoder.SetAttributeQuantization(module.POSITION, settings.positionBits);
670
709
  if (normals !== null) encoder.SetAttributeQuantization(module.NORMAL, settings.normalBits);
671
710
  if (colors !== null) encoder.SetAttributeQuantization(module.COLOR, settings.colorBits);
711
+ if (uvs !== null) encoder.SetAttributeQuantization(module.TEX_COORD, settings.uvBits);
672
712
  encoder.SetEncodingMethod(settings.preserveFaceOrder ? module.MESH_SEQUENTIAL_ENCODING : module.MESH_EDGEBREAKER_ENCODING);
673
713
  const out = new module.DracoInt8Array();
674
714
  try {
@@ -680,7 +720,8 @@ function encodeMeshDraco(module, positions, indices, normals, colors, settings)
680
720
  bytes,
681
721
  positionId,
682
722
  normalId,
683
- colorId
723
+ colorId,
724
+ uvId
684
725
  };
685
726
  } finally {
686
727
  module.destroy(out);
@@ -820,7 +861,7 @@ async function decodeDraco(bytes, options) {
820
861
  * (non-embedded) `.bin` buffers load through `options.resolveBuffer`. A Draco
821
862
  * primitive's positions and faces come from its compressed buffer view
822
863
  * (attribute ids from the extension); its node placement still bakes into
823
- * world positions, while colors read as `null` (compressed attributes beyond
864
+ * world positions and its `TEXCOORD_0` UVs, while colors read as `null` (compressed attributes beyond
824
865
  * POSITION are not mapped).
825
866
  *
826
867
  * Primitives without the extension decode synchronously in place, so assets
@@ -882,9 +923,11 @@ async function createDecoderModule(wasmBinary) {
882
923
  * Decodes Draco-compressed bytes into positions and faces. `what` prefixes
883
924
  * every error (`"Draco"` for files, `glTF: "name"` for primitives). Reads
884
925
  * POSITION by type, or the extension's attribute id when one is given (the
885
- * ids the encoder wrote need not match the decoder's lookup).
926
+ * ids the encoder wrote need not match the decoder's lookup), and likewise the
927
+ * UVs: by type when `uvId` is undefined (a file), by id for a primitive that
928
+ * maps them, not at all for `null`.
886
929
  */
887
- function decodeDracoMesh(module, bytes, what, positionId) {
930
+ function decodeDracoMesh(module, bytes, what, positionId, uvId) {
888
931
  const decoder = new module.Decoder();
889
932
  const buffer = new module.DecoderBuffer();
890
933
  const view = new Int8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
@@ -915,6 +958,24 @@ function decodeDracoMesh(module, bytes, what, positionId) {
915
958
  } finally {
916
959
  module.destroy(floats);
917
960
  }
961
+ let uvAttribute;
962
+ if (typeof uvId === "number") uvAttribute = checkedUniqueAttribute(decoder, mesh, uvId, what, "TEXCOORD_0");
963
+ else if (uvId === void 0) {
964
+ const id = decoder.GetAttributeId(mesh, module.TEX_COORD);
965
+ uvAttribute = id < 0 ? void 0 : decoder.GetAttribute(mesh, id);
966
+ }
967
+ let uvs = null;
968
+ if (uvAttribute !== void 0) {
969
+ if (uvAttribute.num_components() !== 2) throw new Error(`${what}: the Draco UV attribute has ${uvAttribute.num_components()} components (2 expected)`);
970
+ uvs = new Float32Array(2 * vertices);
971
+ const values = new module.DracoFloat32Array();
972
+ try {
973
+ decoder.GetAttributeFloatForAllPoints(mesh, uvAttribute, values);
974
+ for (let i = 0; i < uvs.length; i++) uvs[i] = values.GetValue(i);
975
+ } finally {
976
+ module.destroy(values);
977
+ }
978
+ }
918
979
  const faces = mesh.num_faces();
919
980
  const indices = new Uint32Array(3 * faces);
920
981
  const face = new module.DracoInt32Array();
@@ -930,7 +991,8 @@ function decodeDracoMesh(module, bytes, what, positionId) {
930
991
  }
931
992
  return {
932
993
  positions,
933
- indices
994
+ indices,
995
+ uvs
934
996
  };
935
997
  } finally {
936
998
  module.destroy(mesh);
@@ -947,9 +1009,9 @@ function checkedPositionId(decoder, mesh, module, what) {
947
1009
  return id;
948
1010
  }
949
1011
  /** POSITION by the KHR extension's attribute id: throws on a dangling one. */
950
- function checkedUniqueAttribute(decoder, mesh, positionId, what) {
951
- const attribute = decoder.GetAttributeByUniqueId(mesh, positionId);
952
- if (attribute === void 0 || attribute === null) throw new Error(`${what} points at missing Draco POSITION attribute ${positionId}`);
1012
+ function checkedUniqueAttribute(decoder, mesh, id, what, name = "POSITION") {
1013
+ const attribute = decoder.GetAttributeByUniqueId(mesh, id);
1014
+ if (attribute === void 0 || attribute === null) throw new Error(`${what} points at missing Draco ${name} attribute ${id}`);
953
1015
  return attribute;
954
1016
  }
955
1017
  /** Reads one Draco-compressed primitive: the extension's buffer view decoded, placement baked. */
@@ -975,7 +1037,12 @@ async function readPrimitiveDraco(doc, buffers, spec, usedNames, decoderOfOption
975
1037
  if (!Number.isInteger(positionAttr) || positionAttr < 0) throw new Error(`${what} has a bad KHR_draco_mesh_compression POSITION attribute id`);
976
1038
  positionId = positionAttr;
977
1039
  }
978
- const { positions, indices } = decodeDracoMesh(module, buffer.subarray(base, end), what, positionId);
1040
+ const uvAttr = attributes["TEXCOORD_0"];
1041
+ if (uvAttr !== void 0 && (!Number.isInteger(uvAttr) || uvAttr < 0)) throw new Error(`${what} has a bad KHR_draco_mesh_compression TEXCOORD_0 attribute id`);
1042
+ const decoded = decodeDracoMesh(module, buffer.subarray(base, end), what, positionId, uvAttr === void 0 ? null : uvAttr);
1043
+ const { positions, indices } = decoded;
1044
+ const plainUvs = spec.primitive.attributes["TEXCOORD_0"];
1045
+ const uvs = decoded.uvs ?? (typeof plainUvs === "number" && doc.accessors?.[plainUvs]?.bufferView !== void 0 ? readUvs(doc, buffers, plainUvs, positions.length / 3, name) : null);
979
1046
  const world = spec.world;
980
1047
  for (let i = 0; i < positions.length; i += 3) {
981
1048
  const x = positions[i];
@@ -990,7 +1057,8 @@ async function readPrimitiveDraco(doc, buffers, spec, usedNames, decoderOfOption
990
1057
  positions,
991
1058
  indices,
992
1059
  placement: world.slice(),
993
- colors: null
1060
+ colors: null,
1061
+ uvs
994
1062
  };
995
1063
  }
996
1064
  /** The asset JSON, checked to be an object before the importers read it. */
@@ -1288,12 +1356,14 @@ function readPrimitive(doc, buffers, node, mesh, primitive, world, usedNames) {
1288
1356
  positions[i + 2] = world[2] * x + world[6] * y + world[10] * z + world[14];
1289
1357
  }
1290
1358
  const colors = typeof primitive.attributes["COLOR_0"] === "number" ? readColors(doc, buffers, primitive.attributes["COLOR_0"], positions.length / 3, name) : null;
1359
+ const uvs = typeof primitive.attributes["TEXCOORD_0"] === "number" ? readUvs(doc, buffers, primitive.attributes["TEXCOORD_0"], positions.length / 3, name) : null;
1291
1360
  return {
1292
1361
  name,
1293
1362
  positions,
1294
1363
  indices,
1295
1364
  placement: world.slice(),
1296
- colors
1365
+ colors,
1366
+ uvs
1297
1367
  };
1298
1368
  }
1299
1369
  /** The deduplicated mesh name: the node name, else the mesh name, else `"mesh"`. */
@@ -1366,6 +1436,20 @@ function accessorCount(doc, primitive, name) {
1366
1436
  if (accessor === void 0) throw new Error(`glTF: "${name}" has a primitive without POSITION`);
1367
1437
  return accessor.count;
1368
1438
  }
1439
+ function readUvs(doc, buffers, index, vertices, name) {
1440
+ const data = accessorData(doc, buffers, index, "TEXCOORD_0");
1441
+ if (data.components !== 2 || data.componentType !== 5126 && data.componentType !== 5121 && data.componentType !== 5123) throw new Error(`glTF: "${name}" has TEXCOORD_0 with ${data.components} ${data.size}-byte components (float, u8 or u16 VEC2)`);
1442
+ if (data.count !== vertices) throw new Error(`glTF: "${name}" has ${data.count} UVs for ${vertices} vertices`);
1443
+ const out = new Float32Array(2 * vertices);
1444
+ if (data.buffer.length === 0) return out;
1445
+ for (let i = 0; i < vertices; i++) for (let c = 0; c < 2; c++) {
1446
+ const at = data.base + i * data.stride + c * data.size;
1447
+ const v = data.componentType === 5126 ? data.view.getFloat32(at, true) : data.componentType === 5121 ? data.view.getUint8(at) / 255 : data.view.getUint16(at, true) / 65535;
1448
+ if (!Number.isFinite(v)) throw new Error(`glTF: "${name}" has a non-finite UV at vertex ${i}`);
1449
+ out[2 * i + c] = v;
1450
+ }
1451
+ return out;
1452
+ }
1369
1453
  function readColors(doc, buffers, index, vertices, name) {
1370
1454
  const data = accessorData(doc, buffers, index, "COLOR_0");
1371
1455
  if (data.components !== 3 && data.components !== 4 || data.componentType !== 5121 && data.componentType !== 5126) throw new Error(`glTF: "${name}" has COLOR_0 with ${data.components} ${data.size}-byte components (u8 or float VEC3/VEC4)`);
@@ -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
  import * as THREE from "three";
3
3
  /** Options of {@link bindMesh}. */
4
4
  interface BindMeshOptions {
@@ -16,6 +16,16 @@ interface BindMeshOptions {
16
16
  * it is rebuilt with, then without, the shading); the material stays usable.
17
17
  */
18
18
  material?: THREE.MeshStandardMaterial | THREE.MeshPhongMaterial | THREE.MeshLambertMaterial | THREE.MeshBasicMaterial;
19
+ /**
20
+ * The texture to draw the mesh's UVs with: sets the material's `map`, and
21
+ * makes the default material's colour white. A `material` that already has
22
+ * a `map` needs no more. Either way the map is on while the mesh has UVs: an
23
+ * operation that drops them (see `docs/uv-channel.md`) takes it off rather
24
+ * than stretch one texel over the surface, and undo puts it back. The
25
+ * texture stays the caller's to dispose. glTF UVs want `texture.flipY = false`,
26
+ * as three's `GLTFLoader` sets.
27
+ */
28
+ map?: THREE.Texture;
19
29
  /**
20
30
  * The colour shown while the mesh has no colouring. Defaults to the given
21
31
  * material's colour (left untouched), or light grey for the default material.
@@ -67,8 +77,8 @@ interface BindMeshOptions {
67
77
  interface BoundMesh {
68
78
  /**
69
79
  * The mesh to add to a THREE.Scene. Its geometry has `position`, `normal`
70
- * (when the scene mesh keeps normals), `color` (while colouring is on) and
71
- * an index; its `matrix` is the scene mesh's world matrix
80
+ * (when the scene mesh keeps normals), `uv` (while it has UVs), `color`
81
+ * (while colouring is on) and an index; its `matrix` is the scene mesh's world matrix
72
82
  * (`matrixAutoUpdate` is off). The colour attribute is normalized `Uint16`
73
83
  * RGBA: the engine's sRGB colours converted to three's linear working space.
74
84
  */
@@ -106,7 +116,8 @@ type MeshBinding = Pick<BoundMesh, "mesh" | "object">;
106
116
  * {@link SceneLike.commitFrame}: dirty ranges are copied into the attributes'
107
117
  * mirrors and marked with `addUpdateRange`, attributes are recreated when the
108
118
  * mesh's slot counts change, the colour attribute comes and goes with the
109
- * mesh's colouring, and `object.matrix` follows its placement.
119
+ * mesh's colouring, the `uv` attribute with its UVs, and `object.matrix`
120
+ * follows its placement.
110
121
  *
111
122
  * Dead vertex slots keep stale positions, so the geometry's bounding box and
112
123
  * sphere are computed from the vertices of live triangles only (a removed
@@ -41,6 +41,12 @@ const BUFFERS = {
41
41
  normalized: true,
42
42
  make: (n) => new Uint16Array(n)
43
43
  },
44
+ uvs: {
45
+ name: "uv",
46
+ itemSize: 2,
47
+ normalized: false,
48
+ make: (n) => new Float32Array(n)
49
+ },
44
50
  values: {
45
51
  name: "fmValue",
46
52
  itemSize: 4,
@@ -59,7 +65,8 @@ const BUFFERS = {
59
65
  * {@link SceneLike.commitFrame}: dirty ranges are copied into the attributes'
60
66
  * mirrors and marked with `addUpdateRange`, attributes are recreated when the
61
67
  * mesh's slot counts change, the colour attribute comes and goes with the
62
- * mesh's colouring, and `object.matrix` follows its placement.
68
+ * mesh's colouring, the `uv` attribute with its UVs, and `object.matrix`
69
+ * follows its placement.
63
70
  *
64
71
  * Dead vertex slots keep stale positions, so the geometry's bounding box and
65
72
  * sphere are computed from the vertices of live triangles only (a removed
@@ -88,18 +95,23 @@ function bindMesh(scene, mesh, options = {}) {
88
95
  if (options.shading !== void 0 && options.shading !== "vertex" && options.shading !== "fragment") throw new FastMeshError("INVALID_ARGUMENT", "shading must be \"vertex\" or \"fragment\"");
89
96
  checkSoftness(options.edgeSoftness ?? 0);
90
97
  const ownsMaterial = options.material === void 0;
91
- const material = options.material ?? new THREE.MeshStandardMaterial({ color: DEFAULT_COLOR });
98
+ const material = options.material ?? new THREE.MeshStandardMaterial({ color: options.map === void 0 ? DEFAULT_COLOR : WHITE });
99
+ const givenMap = material.map;
100
+ const map = options.map ?? givenMap;
101
+ material.map = map;
92
102
  const fragment = options.shading === "fragment" && typeof scene.coloring === "function" && typeof scene.views(mesh).values === "function" && patchable(material);
93
103
  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())");
94
104
  const keys = fragment ? [
95
105
  "positions",
96
106
  "normals",
97
107
  "values",
108
+ "uvs",
98
109
  "indices"
99
110
  ] : [
100
111
  "positions",
101
112
  "normals",
102
113
  "colors",
114
+ "uvs",
103
115
  "indices"
104
116
  ];
105
117
  if (options.color !== void 0) material.color.set(options.color);
@@ -124,6 +136,7 @@ function bindMesh(scene, mesh, options = {}) {
124
136
  case "normals": return v.normals();
125
137
  case "colors": return v.colors();
126
138
  case "values": return shading === void 0 ? null : v.values?.() ?? null;
139
+ case "uvs": return v.uvs?.() ?? null;
127
140
  case "indices": return v.indices();
128
141
  }
129
142
  };
@@ -245,7 +258,7 @@ function bindMesh(scene, mesh, options = {}) {
245
258
  const pending = [];
246
259
  const ruleChanged = followRule();
247
260
  for (const key of keys) {
248
- const dirty = change === void 0 || key === "values" && ruleChanged ? "all" : change[key === "values" ? "colors" : key];
261
+ const dirty = change === void 0 || key === "values" && ruleChanged ? "all" : change[key === "values" ? "colors" : key] ?? [];
249
262
  if (dirty !== "all" && dirty.length === 0 && !resized) continue;
250
263
  const view = viewOf(key);
251
264
  const attribute = attributeOf(key);
@@ -283,6 +296,11 @@ function bindMesh(scene, mesh, options = {}) {
283
296
  for (const key of keys) attributeOf(key)?.clearUpdateRanges();
284
297
  }
285
298
  setColored(attributeOf(fragment ? "values" : "colors") !== void 0);
299
+ const shown = attributeOf("uvs") === void 0 ? null : map;
300
+ if (material.map !== shown) {
301
+ material.map = shown;
302
+ material.needsUpdate = true;
303
+ }
286
304
  return geometryChanged;
287
305
  };
288
306
  apply(void 0);
@@ -330,7 +348,13 @@ function bindMesh(scene, mesh, options = {}) {
330
348
  geometry.dispose();
331
349
  uniforms?.fmLut.value?.dispose();
332
350
  if (ownsMaterial) material.dispose();
333
- else restoreMaterial?.();
351
+ else {
352
+ if (material.map !== givenMap) {
353
+ material.map = givenMap;
354
+ material.needsUpdate = true;
355
+ }
356
+ restoreMaterial?.();
357
+ }
334
358
  }
335
359
  };
336
360
  if (options.opacity !== void 0) bound.setOpacity(options.opacity);
package/dist/node.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as SectionPlane, A as JoinReport, At as computeBounds, B as RaycastOptions, C as FieldStatus, Ct as Placement, D as GrabReport, Dt as Quat, E as FindContactsOptions, Et as Positions64, F as MeshDistance, G as RepairReport, H as RemeshReport, I as OffsetReport, J as Scene, K as RepairReportOf, L as OrientReport, M as MeasureResult, N as MeshChange, O as InflateReport, Ot as UpdateMode, P as MeshComponent, Q as SectionGap, R as OutOfRange, S as EditResult, St as Mat3, T as FilledLoop, Tt as Positions, U as RemoveReport, V as RelaxReport, W as RepairOp, X as SectionContour, Y as SceneOptions, Z as SectionDesc, _ as DistanceFieldDesc, _t as MeshHandle, a as BooleanOp, at as SubdivideReport, b as EditOp, bt as Indices, c as ClosestHit, ct as BrushSelect, d as Colormap, dt as LassoSelect, et as SectionResult, f as Contact, ft as SelectSpec, g as DegenerateReport, gt as FieldHandle, h as CutReport, ht as MeshViews, i as AnalyzeOptions, it as SmoothReport, j as LoopId, jt as computeVertexNormals, k as JoinOptions, kt as Vec3, l as ClosestPointOptions, lt as ComponentSelect, m as CutOptions, mt as Range, n as AddMeshOptions, nt as SignMode, o as BoundaryLoop, ot as ThicknessFieldDesc, p as CurvatureFieldDesc, pt as VertexSelection, q as Rgba, r as Analysis, rt as SimplifyReport, s as BridgeReport, st as WeldReport, t as SceneLike, tt as ShellReport, u as ColorRule, ut as IsolateReport, v as DragOptions, vt as SectionHandle, w as FillReport, wt as PlacementInput, x as EditRef, xt as InitInput, y as DragSession, yt as Bounds, z as RayHit } from "./scene-like-BzkDNHCy.js";
1
+ import { $ as RepairReportOf, A as InflateReport, At as Mat3, B as OutOfRange, C as EditRef, Ct as SceneMeshViews, D as FilledLoop, Dt as Bounds, E as FillReport, Et as SectionHandle, F as MeshChange, Ft as Quat, G as RegisterOptions, H as RaycastOptions, I as MeshComponent, It as UpdateMode, J as RelaxReport, K as RegisterResult, L as MeshDistance, Lt as Vec3, M as JoinReport, Mt as PlacementInput, N as LoopId, Nt as Positions, O as FindContactsOptions, Ot as Indices, P as MeasureResult, Pt as Positions64, Q as RepairReport, R as OffsetReport, Rt as computeBounds, S as EditOp, St as MeshViews, T as FieldStatus, Tt as MeshHandle, U as RegisterMotion, V as RayHit, W as RegisterNotApplied, X as RemoveReport, Y as RemeshReport, Z as RepairOp, _ as CutReport, _t as IsolateReport, a as AutoRepairReport, at as SectionGap, b as DragOptions, bt as VertexSelection, c as BoundaryLoop, ct as ShellReport, d as ClosestPointOptions, dt as SmoothReport, et as Rgba, f as ColorRule, ft as SubdivideReport, g as CutOptions, gt as ComponentSelect, h as CurvatureFieldDesc, ht as BrushSelect, i as AnalyzeOptions, it as SectionDesc, j as JoinOptions, jt as Placement, k as GrabReport, kt as InitInput, l as BridgeReport, lt as SignMode, m as Contact, mt as WeldReport, n as AddMeshOptions, nt as SceneOptions, o as AutoRepairRequest, ot as SectionPlane, p as Colormap, pt as ThicknessFieldDesc, q as RegisterStatus, r as Analysis, rt as SectionContour, s as BooleanOp, st as SectionResult, t as SceneLike, tt as Scene, u as ClosestHit, ut as SimplifyReport, v as DegenerateReport, vt as LassoSelect, w as EditResult, wt as FieldHandle, x as DragSession, xt as Range, y as DistanceFieldDesc, yt as SelectSpec, z as OrientReport, zt as computeVertexNormals } from "./scene-like-Dq9_SaUL.js";
2
2
  import { n as FastMeshErrorCode, t as FastMeshError } from "./core-CJ9D6U5A.js";
3
3
  /**
4
4
  * Resolves immediately: in Node.js and Bun the module is ready as soon as it is imported.
@@ -6,4 +6,4 @@ import { n as FastMeshErrorCode, t as FastMeshError } from "./core-CJ9D6U5A.js";
6
6
  * the argument is ignored.
7
7
  */
8
8
  export declare function init(_input?: InitInput | Promise<InitInput>): Promise<void>;
9
- export { type AddMeshOptions, type Analysis, type AnalyzeOptions, type BooleanOp, type BoundaryLoop, type Bounds, type BridgeReport, type BrushSelect, type ClosestHit, type ClosestPointOptions, type ColorRule, type Colormap, type ComponentSelect, type Contact, type CurvatureFieldDesc, type CutOptions, type CutReport, type DegenerateReport, type DistanceFieldDesc, type DragOptions, type DragSession, type EditOp, type EditRef, type EditResult, FastMeshError, type FastMeshErrorCode, type FieldHandle, type FieldStatus, type FillReport, type FilledLoop, type FindContactsOptions, type GrabReport, type Indices, type InflateReport, type InitInput, type IsolateReport, type JoinOptions, type JoinReport, type LassoSelect, type LoopId, type Mat3, type MeasureResult, type MeshChange, type MeshComponent, type MeshDistance, type MeshHandle, type MeshViews, type OffsetReport, type OrientReport, type OutOfRange, type Placement, type PlacementInput, type Positions, type Positions64, type Quat, type Range, type RayHit, type RaycastOptions, type RelaxReport, type RemeshReport, 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 SelectSpec, type ShellReport, type SignMode, type SimplifyReport, type SmoothReport, type SubdivideReport, type ThicknessFieldDesc, type UpdateMode, type Vec3, type VertexSelection, type WeldReport, computeBounds, computeVertexNormals };
9
+ export { type AddMeshOptions, type Analysis, type AnalyzeOptions, type AutoRepairReport, type AutoRepairRequest, type BooleanOp, type BoundaryLoop, type Bounds, type BridgeReport, type BrushSelect, type ClosestHit, type ClosestPointOptions, type ColorRule, type Colormap, type ComponentSelect, type Contact, type CurvatureFieldDesc, type CutOptions, type CutReport, type DegenerateReport, type DistanceFieldDesc, type DragOptions, type DragSession, type EditOp, type EditRef, type EditResult, FastMeshError, type FastMeshErrorCode, type FieldHandle, type FieldStatus, type FillReport, type FilledLoop, type FindContactsOptions, type GrabReport, type Indices, type InflateReport, type InitInput, type IsolateReport, type JoinOptions, type JoinReport, type LassoSelect, type LoopId, type Mat3, type MeasureResult, type MeshChange, type MeshComponent, type MeshDistance, type MeshHandle, type MeshViews, type OffsetReport, type OrientReport, type OutOfRange, type Placement, type PlacementInput, type Positions, type Positions64, type Quat, type Range, type RayHit, type RaycastOptions, type RegisterMotion, type RegisterNotApplied, type RegisterOptions, type RegisterResult, type RegisterStatus, type RelaxReport, type RemeshReport, type RemoveReport, type RepairOp, type RepairReport, type RepairReportOf, type Rgba, Scene, type SceneLike, type SceneMeshViews, type SceneOptions, type SectionContour, type SectionDesc, type SectionGap, type SectionHandle, type SectionPlane, type SectionResult, type SelectSpec, type ShellReport, type SignMode, type SimplifyReport, type SmoothReport, type SubdivideReport, type ThicknessFieldDesc, type UpdateMode, type Vec3, type VertexSelection, type WeldReport, computeBounds, computeVertexNormals };
package/dist/node.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { n as computeVertexNormals, r as markInitialized, t as computeBounds } from "./api-4kz45-Mq.js";
2
2
  import { t as FastMeshError } from "./core-4OcWKu3r.js";
3
- import { t as Scene } from "./scene-BnkCS0sv.js";
3
+ import { t as Scene } from "./scene-CXtM_bxV.js";
4
4
  import { initSync } from "./wasm/fast_mesh_wasm.js";
5
5
  import { readFileSync } from "node:fs";
6
6
  // src/node.ts
@@ -1,4 +1,4 @@
1
- import { $ as SectionPlane, _ as DistanceFieldDesc, et as SectionResult, mt as Range, n as AddMeshOptions, u as ColorRule } from "./scene-like-BzkDNHCy.js";
1
+ import { f as ColorRule, n as AddMeshOptions, ot as SectionPlane, st as SectionResult, xt as Range, y as DistanceFieldDesc } from "./scene-like-Dq9_SaUL.js";
2
2
  /** A mesh, field or section id allocated on the main side. Unique per kind. */
3
3
  type ClientId = number;
4
4
  /** A {@link ColorRule} naming its field by client id. */
@@ -37,7 +37,9 @@ type Request = {
37
37
  f64: boolean;
38
38
  /** `Uint32Array` bytes. */
39
39
  indices: ArrayBuffer;
40
- /** `mode` is ignored: the Worker scene is always `"eager"`. */
40
+ /** `Float32Array` bytes of the UVs, for a mesh with them. */
41
+ uvs?: ArrayBuffer;
42
+ /** `mode` and `uvs` are ignored: the Worker scene is always `"eager"`, and `uvs` above is what crosses. */
41
43
  options: AddMeshOptions;
42
44
  /**
43
45
  * Add in place, in the batch's own result (a restart's replay), never
@@ -75,7 +77,7 @@ type Request = {
75
77
  kind: "edit" | "repair";
76
78
  rev: number;
77
79
  id: ClientId;
78
- /** `EditOp[]` for `edit`; `RepairOp` or `RepairOp[]` for `repair`. */
80
+ /** `EditOp[]` for `edit`; `RepairOp`, `RepairOp[]` or `AutoRepairRequest` for `repair`. */
79
81
  payload: unknown;
80
82
  /** When set, the result (an `EditResult` or the repair report(s)) is replied under it. */
81
83
  qid?: number;
@@ -90,6 +92,16 @@ type Request = {
90
92
  /** When set, the `JoinReport` is replied under it. */
91
93
  qid?: number;
92
94
  key?: string;
95
+ } | {
96
+ kind: "register";
97
+ rev: number;
98
+ moving: ClientId;
99
+ fixed: ClientId;
100
+ /** `RegisterOptions`. */
101
+ payload: unknown;
102
+ /** The `RegisterResult` is replied under it. */
103
+ qid: number;
104
+ key?: string;
93
105
  } | {
94
106
  kind: "undo" | "redo";
95
107
  rev: number;
@@ -156,9 +168,10 @@ type Request = {
156
168
  * `bytes` holds, per buffer, every dirty range's elements concatenated in
157
169
  * range order (positions and normals: 3 `f32` per vertex slot; colours: 4
158
170
  * bytes per vertex slot; values: 1 `f32` per vertex slot, over the colours'
159
- * ranges, once a `values` request turned them on; indices: 3 `u32` per triangle slot), or the whole buffer when the
171
+ * ranges, once a `values` request turned them on; UVs: 2 `f32` per vertex slot; indices: 3 `u32` per triangle slot), or the whole buffer when the
160
172
  * ranges are `"all"`. `null` for a buffer that is off (normals, colours and
161
- * values), and for every buffer of a removed mesh.
173
+ * values), and for every buffer of a removed mesh; UVs are absent when off.
174
+ * `uvs` is present only for a mesh that has UVs or just lost them.
162
175
  */
163
176
  interface MeshChangeWire {
164
177
  id: ClientId;
@@ -170,6 +183,7 @@ interface MeshChangeWire {
170
183
  normals: Range[] | "all";
171
184
  colors: Range[] | "all";
172
185
  indices: Range[] | "all";
186
+ uvs?: Range[] | "all";
173
187
  fields: ClientId[];
174
188
  sections: ClientId[];
175
189
  /** Slot counts after the change; 0 for a removed mesh. */
@@ -181,6 +195,7 @@ interface MeshChangeWire {
181
195
  colors: ArrayBuffer | null;
182
196
  values: ArrayBuffer | null;
183
197
  indices: ArrayBuffer | null;
198
+ uvs?: ArrayBuffer;
184
199
  };
185
200
  }
186
201
  /** An error crossing the boundary: a `FastMeshError` code and message. */
package/dist/r3f.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { _t as MeshHandle } from "./scene-like-BzkDNHCy.js";
2
- import { t as SceneStore } from "./store-BKFzSykN.js";
3
- import { n as BoundMesh, t as BindMeshOptions } from "./mesh-D3fv56nF.js";
1
+ import { Tt as MeshHandle } from "./scene-like-Dq9_SaUL.js";
2
+ import { t as SceneStore } from "./store-CIW19oCh.js";
3
+ import { n as BoundMesh, t as BindMeshOptions } from "./mesh-B3QP93wx.js";
4
4
  import * as THREE from "three";
5
5
  import { JSX } from "react";
6
6
  import { EventHandlers } from "@react-three/fiber";
package/dist/r3f.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { t as FastMeshError } from "./core-4OcWKu3r.js";
2
2
  import { c as useStoreSelector, i as useScene, l as StoreContext, t as SceneProvider } from "./react-DzrtrzZy.js";
3
3
  import { s as meshState } from "./snapshot-BkbGPspK.js";
4
- import { r as setFrameLoop } from "./store-CEd2y2KS.js";
5
- import { t as bindMesh } from "./mesh-CWvrjO8S.js";
4
+ import { r as setFrameLoop } from "./store-C9h7GFFl.js";
5
+ import { t as bindMesh } from "./mesh-hPWBQPaN.js";
6
6
  import * as THREE from "three";
7
7
  import { createElement, useCallback, useContext, useLayoutEffect, useRef, useState } from "react";
8
8
  import { useFrame, useThree } from "@react-three/fiber";
package/dist/react.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as FastMeshError } from "./core-CJ9D6U5A.js";
2
- import { _t as MeshHandle, vt as SectionHandle } from "./scene-like-BzkDNHCy.js";
3
- import { a as DisplayState, c as MeshState, d as SceneSnapshot, n as SectionPatch, p as SectionState, t as SceneStore } from "./store-BKFzSykN.js";
2
+ import { Et as SectionHandle, Tt as MeshHandle } from "./scene-like-Dq9_SaUL.js";
3
+ import { a as DisplayState, c as MeshState, d as SceneSnapshot, n as SectionPatch, p as SectionState, t as SceneStore } from "./store-CIW19oCh.js";
4
4
  import { ReactElement, ReactNode } from "react";
5
5
  /** Provides `store` to the hooks below it. */
6
6
  export declare function SceneProvider(props: {