@margoengine/loaders 0.0.0-stage → 1.0.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 (226) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1665 -2
  4. package/dist/3dm.d.ts +161 -0
  5. package/dist/3dm.js +289 -0
  6. package/dist/3ds.d.ts +124 -0
  7. package/dist/3ds.js +392 -0
  8. package/dist/acclaim.d.ts +90 -0
  9. package/dist/acclaim.js +312 -0
  10. package/dist/amf.d.ts +45 -0
  11. package/dist/amf.js +256 -0
  12. package/dist/babylon.d.ts +197 -0
  13. package/dist/babylon.js +701 -0
  14. package/dist/common.d.ts +7 -0
  15. package/dist/common.js +6 -0
  16. package/dist/crease.d.ts +7 -0
  17. package/dist/crease.js +67 -0
  18. package/dist/dae-animation.d.ts +66 -0
  19. package/dist/dae-animation.js +266 -0
  20. package/dist/dae-common.d.ts +95 -0
  21. package/dist/dae-common.js +226 -0
  22. package/dist/dae-controllers.d.ts +57 -0
  23. package/dist/dae-controllers.js +164 -0
  24. package/dist/dae-kinematics.d.ts +65 -0
  25. package/dist/dae-kinematics.js +461 -0
  26. package/dist/dae-pose.d.ts +131 -0
  27. package/dist/dae-pose.js +381 -0
  28. package/dist/dae-scene.d.ts +203 -0
  29. package/dist/dae-scene.js +279 -0
  30. package/dist/dae.d.ts +166 -0
  31. package/dist/dae.js +644 -0
  32. package/dist/detect.d.ts +20 -0
  33. package/dist/detect.js +72 -0
  34. package/dist/dxf-hatch.d.ts +8 -0
  35. package/dist/dxf-hatch.js +346 -0
  36. package/dist/dxf-leaders.d.ts +59 -0
  37. package/dist/dxf-leaders.js +258 -0
  38. package/dist/dxf.d.ts +122 -0
  39. package/dist/dxf.js +985 -0
  40. package/dist/engine.d.ts +41 -0
  41. package/dist/engine.js +120 -0
  42. package/dist/font-opentype.d.ts +14 -0
  43. package/dist/font-opentype.js +33 -0
  44. package/dist/font-woff.d.ts +23 -0
  45. package/dist/font-woff.js +293 -0
  46. package/dist/font.d.ts +41 -0
  47. package/dist/font.js +26 -0
  48. package/dist/gcode.d.ts +92 -0
  49. package/dist/gcode.js +369 -0
  50. package/dist/geo-model.d.ts +84 -0
  51. package/dist/geo-model.js +220 -0
  52. package/dist/geo-mvt.d.ts +15 -0
  53. package/dist/geo-mvt.js +302 -0
  54. package/dist/geo-shp.d.ts +15 -0
  55. package/dist/geo-shp.js +234 -0
  56. package/dist/geo-xml.d.ts +6 -0
  57. package/dist/geo-xml.js +165 -0
  58. package/dist/geo.d.ts +8 -0
  59. package/dist/geo.js +59 -0
  60. package/dist/geometry.d.ts +60 -0
  61. package/dist/geometry.js +273 -0
  62. package/dist/index.d.ts +54 -0
  63. package/dist/index.js +28 -0
  64. package/dist/kmz.d.ts +78 -0
  65. package/dist/kmz.js +173 -0
  66. package/dist/las.d.ts +92 -0
  67. package/dist/las.js +110 -0
  68. package/dist/ldraw.d.ts +118 -0
  69. package/dist/ldraw.js +474 -0
  70. package/dist/load.d.ts +72 -0
  71. package/dist/load.js +205 -0
  72. package/dist/lottie.d.ts +154 -0
  73. package/dist/lottie.js +893 -0
  74. package/dist/lwo.d.ts +81 -0
  75. package/dist/lwo.js +454 -0
  76. package/dist/lzf.d.ts +13 -0
  77. package/dist/lzf.js +56 -0
  78. package/dist/materialx.d.ts +120 -0
  79. package/dist/materialx.js +563 -0
  80. package/dist/md2.d.ts +52 -0
  81. package/dist/md2.js +112 -0
  82. package/dist/mmcif.d.ts +14 -0
  83. package/dist/mmcif.js +246 -0
  84. package/dist/mmd.d.ts +244 -0
  85. package/dist/mmd.js +958 -0
  86. package/dist/mocap.d.ts +71 -0
  87. package/dist/mocap.js +178 -0
  88. package/dist/molecule-common.d.ts +4 -0
  89. package/dist/molecule-common.js +54 -0
  90. package/dist/mtl.d.ts +125 -0
  91. package/dist/mtl.js +550 -0
  92. package/dist/normals.d.ts +7 -0
  93. package/dist/normals.js +31 -0
  94. package/dist/nrrd.d.ts +70 -0
  95. package/dist/nrrd.js +785 -0
  96. package/dist/nurbs.d.ts +118 -0
  97. package/dist/nurbs.js +265 -0
  98. package/dist/obj.d.ts +145 -0
  99. package/dist/obj.js +462 -0
  100. package/dist/off.d.ts +10 -0
  101. package/dist/off.js +155 -0
  102. package/dist/outline-font.d.ts +87 -0
  103. package/dist/outline-font.js +110 -0
  104. package/dist/outline.d.ts +20 -0
  105. package/dist/outline.js +215 -0
  106. package/dist/pcd.d.ts +34 -0
  107. package/dist/pcd.js +258 -0
  108. package/dist/pdb.d.ts +67 -0
  109. package/dist/pdb.js +126 -0
  110. package/dist/ply.d.ts +35 -0
  111. package/dist/ply.js +392 -0
  112. package/dist/polygon.d.ts +9 -0
  113. package/dist/polygon.js +49 -0
  114. package/dist/prwm.d.ts +24 -0
  115. package/dist/prwm.js +114 -0
  116. package/dist/render.d.ts +32 -0
  117. package/dist/render.js +181 -0
  118. package/dist/sfnt-cff.d.ts +37 -0
  119. package/dist/sfnt-cff.js +749 -0
  120. package/dist/sfnt-layout.d.ts +24 -0
  121. package/dist/sfnt-layout.js +266 -0
  122. package/dist/sfnt-reader.d.ts +28 -0
  123. package/dist/sfnt-reader.js +87 -0
  124. package/dist/sfnt-variation.d.ts +40 -0
  125. package/dist/sfnt-variation.js +318 -0
  126. package/dist/shared/asset-url.js +82 -0
  127. package/dist/shared/crc32.d.ts +2 -0
  128. package/dist/shared/crc32.js +47 -0
  129. package/dist/shared/errors.js +36 -0
  130. package/dist/shared/inflate.js +284 -0
  131. package/dist/shared/normals.js +26 -0
  132. package/dist/shared/scene-scope.js +56 -0
  133. package/dist/shared/trailing-data.js +45 -0
  134. package/dist/stl.d.ts +64 -0
  135. package/dist/stl.js +309 -0
  136. package/dist/svg.d.ts +90 -0
  137. package/dist/svg.js +1007 -0
  138. package/dist/tds.d.ts +2 -0
  139. package/dist/tds.js +2 -0
  140. package/dist/textures.d.ts +42 -0
  141. package/dist/textures.js +53 -0
  142. package/dist/threemf-beam-reader.d.ts +19 -0
  143. package/dist/threemf-beam-reader.js +165 -0
  144. package/dist/threemf-beams.d.ts +52 -0
  145. package/dist/threemf-beams.js +268 -0
  146. package/dist/threemf-boolean-read.d.ts +10 -0
  147. package/dist/threemf-boolean-read.js +113 -0
  148. package/dist/threemf-boolean.d.ts +59 -0
  149. package/dist/threemf-boolean.js +20 -0
  150. package/dist/threemf-csg.d.ts +14 -0
  151. package/dist/threemf-csg.js +193 -0
  152. package/dist/threemf-displacement-read.d.ts +8 -0
  153. package/dist/threemf-displacement-read.js +213 -0
  154. package/dist/threemf-displacement.d.ts +71 -0
  155. package/dist/threemf-displacement.js +18 -0
  156. package/dist/threemf-evaluate.d.ts +36 -0
  157. package/dist/threemf-evaluate.js +86 -0
  158. package/dist/threemf-functions.d.ts +33 -0
  159. package/dist/threemf-functions.js +359 -0
  160. package/dist/threemf-lattice-mesh.d.ts +9 -0
  161. package/dist/threemf-lattice-mesh.js +115 -0
  162. package/dist/threemf-lattice.d.ts +139 -0
  163. package/dist/threemf-lattice.js +379 -0
  164. package/dist/threemf-levelset.d.ts +23 -0
  165. package/dist/threemf-levelset.js +105 -0
  166. package/dist/threemf-materials.d.ts +162 -0
  167. package/dist/threemf-materials.js +497 -0
  168. package/dist/threemf-mesh.d.ts +75 -0
  169. package/dist/threemf-mesh.js +422 -0
  170. package/dist/threemf-secure.d.ts +50 -0
  171. package/dist/threemf-secure.js +153 -0
  172. package/dist/threemf-tessellate.d.ts +37 -0
  173. package/dist/threemf-tessellate.js +277 -0
  174. package/dist/threemf-volume-colour.d.ts +25 -0
  175. package/dist/threemf-volume-colour.js +233 -0
  176. package/dist/threemf-volume-sample.d.ts +8 -0
  177. package/dist/threemf-volume-sample.js +65 -0
  178. package/dist/threemf-volumetric-read.d.ts +15 -0
  179. package/dist/threemf-volumetric-read.js +539 -0
  180. package/dist/threemf-volumetric.d.ts +177 -0
  181. package/dist/threemf-volumetric.js +28 -0
  182. package/dist/threemf.d.ts +170 -0
  183. package/dist/threemf.js +609 -0
  184. package/dist/tilt.d.ts +62 -0
  185. package/dist/tilt.js +186 -0
  186. package/dist/tmx.d.ts +151 -0
  187. package/dist/tmx.js +394 -0
  188. package/dist/ttf.d.ts +78 -0
  189. package/dist/ttf.js +568 -0
  190. package/dist/types.d.ts +108 -0
  191. package/dist/types.js +35 -0
  192. package/dist/usd.d.ts +2 -0
  193. package/dist/usd.js +2 -0
  194. package/dist/usd.worker.d.ts +1 -0
  195. package/dist/usdz.d.ts +50 -0
  196. package/dist/usdz.js +646 -0
  197. package/dist/util.d.ts +75 -0
  198. package/dist/util.js +241 -0
  199. package/dist/vdb.d.ts +111 -0
  200. package/dist/vdb.js +663 -0
  201. package/dist/vrml.d.ts +53 -0
  202. package/dist/vrml.js +532 -0
  203. package/dist/vtk-cells.d.ts +29 -0
  204. package/dist/vtk-cells.js +211 -0
  205. package/dist/vtk-legacy.d.ts +57 -0
  206. package/dist/vtk-legacy.js +439 -0
  207. package/dist/vtk-reader.d.ts +19 -0
  208. package/dist/vtk-reader.js +134 -0
  209. package/dist/vtk-xml.d.ts +96 -0
  210. package/dist/vtk-xml.js +578 -0
  211. package/dist/vtk.d.ts +13 -0
  212. package/dist/vtk.js +234 -0
  213. package/dist/woff-glyf.d.ts +17 -0
  214. package/dist/woff-glyf.js +215 -0
  215. package/dist/worker.d.ts +10 -0
  216. package/dist/worker.js +93 -0
  217. package/dist/workers/usd.js +3 -0
  218. package/dist/xfile.d.ts +99 -0
  219. package/dist/xfile.js +706 -0
  220. package/dist/xml.d.ts +107 -0
  221. package/dist/xml.js +843 -0
  222. package/dist/xyz.d.ts +16 -0
  223. package/dist/xyz.js +110 -0
  224. package/dist/zip.d.ts +38 -0
  225. package/dist/zip.js +150 -0
  226. package/package.json +289 -4
@@ -0,0 +1,113 @@
1
+ import { booleanMesh } from './threemf-csg.js';
2
+ import { LoaderError } from './types.js';
3
+ import { limits, throwIfAborted } from './util.js';
4
+ const F = '3MF';
5
+ const OPERATIONS = ['union', 'difference', 'intersection'];
6
+ const bad = (message) => {
7
+ throw new LoaderError(F, 'syntax', message);
8
+ };
9
+ /**
10
+ * The boolean reader's hooks. `others` says that hooks before these turn displacement meshes, level sets and lattices
11
+ * into triangles, so such an object may be a base.
12
+ */
13
+ export function booleanStage(options, others = false) {
14
+ const evaluate = options.evaluate !== false;
15
+ const shapes = [], listed = new Map(),
16
+ /** Objects with a shape of another extension, which no operand may have. */
17
+ extended = new Map(), current = new Map();
18
+ let built = 0;
19
+ const hooks = {
20
+ booleans: true,
21
+ welded: true,
22
+ // A base may be another extension's shape.
23
+ levelSets: true,
24
+ element(model, name, a) {
25
+ if (name === 'object')
26
+ current.set(model, a.id);
27
+ else if (name === 'displacementmesh' || name === 'beamlattice' || name === 'levelset') {
28
+ let ids = extended.get(model);
29
+ if (!ids)
30
+ extended.set(model, (ids = new Set()));
31
+ ids.add(current.get(model));
32
+ }
33
+ },
34
+ instance(model, object, m, scale) {
35
+ if (evaluate && object.levelSet && !others)
36
+ throw new LoaderError(F, 'unsupported', `object ${object.id.slice(0, 32)} is a volumetric level set; parse3MFBoolean meshes none (parse3MFEvaluated from @margoengine/loaders/threemf-evaluate does; evaluate: false reads the shapes)`);
37
+ const found = listed.get(model)?.get(object.id);
38
+ if (!found)
39
+ return;
40
+ found.instances.push(m.map((v) => v * scale));
41
+ built++;
42
+ },
43
+ hasGeometry: () => built > 0,
44
+ async ready(_read, { models, partPath }) {
45
+ const root = models.values().next().value;
46
+ // A part that another names is finished before the part that names it.
47
+ for (const model of [...models.values()].reverse()) {
48
+ const own = new Map(), order = [...model.objects.keys()], modelPath = partPath(model);
49
+ listed.set(model, own);
50
+ for (const object of model.objects.values()) {
51
+ const { id, boolean: data } = object;
52
+ if (!data)
53
+ continue;
54
+ const label = `boolean shape ${id.slice(0, 32)}`;
55
+ if (!OPERATIONS.includes(data.operation))
56
+ bad(`${label} has the unknown operation ${data.operation.slice(0, 32)}`);
57
+ if (object.mesh || object.components.length)
58
+ bad(`${label} also has a mesh or components`);
59
+ if (object.pid !== undefined || object.pindex !== undefined)
60
+ bad(`${label} takes no pid or pindex`);
61
+ if (!data.operands.length)
62
+ bad(`${label} needs a boolean element`);
63
+ const operand = (reference, isBase) => {
64
+ const { objectId, path, transform } = reference;
65
+ if (path !== undefined && model !== root)
66
+ bad(`${label}: only the root model part may name another part`);
67
+ const owner = path ? models.get(path.replace(/\\/g, '/').replace(/^\/+/, '').toLowerCase()) : model, target = owner.objects.get(objectId), what = `${label}: object ${objectId.slice(0, 32)}`;
68
+ // Defined before it is named, so no shape reads itself.
69
+ if (!target || (owner === model && order.indexOf(objectId) >= order.indexOf(id)))
70
+ bad(`${what} is not defined before it`);
71
+ if (target.type !== 'model' || target.components.length || target.alternatives.length)
72
+ bad(`${what} must be a model shape without components or alternatives`);
73
+ if (!isBase && (!target.mesh || target.boolean || extended.get(owner)?.has(objectId)))
74
+ bad(`${what} must be a plain triangle mesh`);
75
+ const mesh = target.boolean ? undefined : target.mesh, ownerPath = partPath(owner);
76
+ return {
77
+ objectId,
78
+ ...(ownerPath === undefined ? {} : { modelPath: ownerPath }),
79
+ transform,
80
+ ...(mesh ? { mesh: { positions: mesh.vertices.result(), indices: mesh.triangles.result() } } : {}),
81
+ };
82
+ };
83
+ const shape = {
84
+ objectId: id,
85
+ ...(modelPath === undefined ? {} : { modelPath }),
86
+ ...(object.name === undefined ? {} : { name: object.name }),
87
+ operation: data.operation,
88
+ base: operand(data.base, true),
89
+ operands: data.operands.map((o) => operand(o, false)),
90
+ instances: [],
91
+ };
92
+ own.set(id, shape);
93
+ shapes.push(shape);
94
+ if (!evaluate)
95
+ continue;
96
+ throwIfAborted(options.signal, F);
97
+ const inputs = [data.base, ...data.operands].map(({ objectId, path, transform }) => {
98
+ const owner = path ? models.get(path.replace(/\\/g, '/').replace(/^\/+/, '').toLowerCase()) : model, target = owner.objects.get(objectId);
99
+ if ((!others && extended.get(owner)?.has(objectId)) || !target.mesh)
100
+ throw new LoaderError(F, 'unsupported', `${label}: its base ${objectId.slice(0, 32)} is a displacement mesh, a level set or another extension's shape, which parse3MFBoolean does not evaluate (parse3MFEvaluated from @margoengine/loaders/threemf-evaluate does; evaluate: false reads the shapes)`);
101
+ return { model: owner, object: target, transform };
102
+ });
103
+ // Later shapes read this one as a mesh.
104
+ object.mesh = await booleanMesh(model, id, shape.operation, inputs, limits(options, F).maxTriangles);
105
+ }
106
+ }
107
+ },
108
+ bucket: () => '',
109
+ corner() { },
110
+ group() { },
111
+ };
112
+ return { hooks, shapes };
113
+ }
@@ -0,0 +1,59 @@
1
+ import { type ThreeMFOptions, type ThreeMFResult } from './threemf.js';
2
+ import type { ThreeMFVolumeSamples } from './threemf-volumetric.js';
3
+ import type { BinaryInput } from './util.js';
4
+ declare const OPERATIONS: readonly ['union', 'difference', 'intersection'];
5
+ /** An object a boolean shape reads. */
6
+ export interface ThreeMFBooleanOperand {
7
+ objectId: string;
8
+ /** Its model part, when not the root. */
9
+ modelPath?: string;
10
+ /** Twelve numbers as a 3MF transform writes them, applied before the operation. */
11
+ transform: Float64Array;
12
+ /** Its triangles in its own coordinates and the model's unit; absent for a shape without them. */
13
+ mesh?: {
14
+ positions: Float32Array;
15
+ indices: Uint32Array;
16
+ };
17
+ /**
18
+ * With `parse3MFEvaluated`, when the object has volume data: reads it at points in the object's own coordinates,
19
+ * which `transform` takes to the shape's.
20
+ */
21
+ sample?(positions: ArrayLike<number>): Promise<ThreeMFVolumeSamples>;
22
+ }
23
+ /** A boolean shape: `operands` applied to `base` in order. */
24
+ export interface ThreeMFBooleanShape {
25
+ objectId: string;
26
+ modelPath?: string;
27
+ name?: string;
28
+ operation: (typeof OPERATIONS)[number];
29
+ base: ThreeMFBooleanOperand;
30
+ operands: ThreeMFBooleanOperand[];
31
+ /**
32
+ * Each place the build puts the shape: twelve numbers as a 3MF transform writes them, from the shape's coordinates to
33
+ * the result's units. None for a shape that only another shape reads.
34
+ */
35
+ instances: Float64Array[];
36
+ }
37
+ /** Options of {@link parse3MFBoolean}. */
38
+ export interface ThreeMFBooleanOptions extends ThreeMFOptions {
39
+ /** Evaluate each boolean shape and add its surface to the result. Default true. */
40
+ evaluate?: boolean;
41
+ }
42
+ /** The result of {@link parse3MFBoolean}. */
43
+ export interface ThreeMFBooleanResult extends ThreeMFResult {
44
+ /** Every boolean shape, each after the shapes it reads. */
45
+ shapes: ThreeMFBooleanShape[];
46
+ }
47
+ /**
48
+ * Parses a 3MF package with the boolean operations extension. Each boolean shape is evaluated exactly by
49
+ * `@margoengine/mesh-edit` and its surface joins the result's triangles where the build places it, with the colours of
50
+ * the surfaces it came from; the shapes are returned beside them with their operands' triangles and placements. A base
51
+ * that is a displacement mesh or a level set is not evaluated here (`parse3MFEvaluated` evaluates one).
52
+ *
53
+ * @throws LoaderError for what the extension rules out (an unknown operation, a property on a shape, a base that is not
54
+ * a `model` shape or has alternatives, an operand that is not a plain `model` mesh, a shape that reads itself or a later
55
+ * object), an input that is not a closed solid, a base this entry does not evaluate, a built level set, and what
56
+ * `parse3MF` throws.
57
+ */
58
+ export declare function parse3MFBoolean(input: BinaryInput, options?: ThreeMFBooleanOptions): Promise<ThreeMFBooleanResult>;
59
+ export {};
@@ -0,0 +1,20 @@
1
+ // Reads the 3MF Consortium's Boolean Operations Extension (https://github.com/3MFConsortium/spec_booleans): the shapes
2
+ // made by union, difference and intersection, and the meshes they name.
3
+ import { read3MF } from './threemf.js';
4
+ import { booleanStage } from './threemf-boolean-read.js';
5
+ const OPERATIONS = ['union', 'difference', 'intersection'];
6
+ /**
7
+ * Parses a 3MF package with the boolean operations extension. Each boolean shape is evaluated exactly by
8
+ * `@margoengine/mesh-edit` and its surface joins the result's triangles where the build places it, with the colours of
9
+ * the surfaces it came from; the shapes are returned beside them with their operands' triangles and placements. A base
10
+ * that is a displacement mesh or a level set is not evaluated here (`parse3MFEvaluated` evaluates one).
11
+ *
12
+ * @throws LoaderError for what the extension rules out (an unknown operation, a property on a shape, a base that is not
13
+ * a `model` shape or has alternatives, an operand that is not a plain `model` mesh, a shape that reads itself or a later
14
+ * object), an input that is not a closed solid, a base this entry does not evaluate, a built level set, and what
15
+ * `parse3MF` throws.
16
+ */
17
+ export async function parse3MFBoolean(input, options = {}) {
18
+ const stage = booleanStage(options), read = await read3MF(input, options, stage.hooks);
19
+ return { ...read, shapes: stage.shapes };
20
+ }
@@ -0,0 +1,14 @@
1
+ import { type ThreeMFMesh, type ThreeMFModel, type ThreeMFObject } from './threemf.js';
2
+ /** One input of a boolean shape: an object with triangles, and the transform applied to it first. */
3
+ export interface BooleanInput {
4
+ model: ThreeMFModel;
5
+ object: ThreeMFObject;
6
+ transform: ArrayLike<number>;
7
+ }
8
+ /**
9
+ * The triangles of `inputs[0] operation inputs[1..]` in the shape's coordinates and the model's unit, with its colours
10
+ * added to `model`.
11
+ *
12
+ * @throws LoaderError for an input that is not a closed, outward solid, and for more than `maxTriangles`.
13
+ */
14
+ export declare function booleanMesh(model: ThreeMFModel, id: string, operation: 'union' | 'difference' | 'intersection', inputs: readonly BooleanInput[], maxTriangles: number): Promise<ThreeMFMesh>;
@@ -0,0 +1,193 @@
1
+ // Evaluates a 3MF boolean shape (https://github.com/3MFConsortium/spec_booleans, chapter 2) with the exact n-ary
2
+ // boolean of `@margoengine/mesh-edit`: the base, then each operand in order, where a difference takes the union of the
3
+ // operands away. A face keeps the colour of the surface it came from, as the extension asks for all three operations.
4
+ import { cornerProperty } from './threemf.js';
5
+ import { LoaderError } from './types.js';
6
+ import { floats, uints } from './util.js';
7
+ const F = '3MF';
8
+ const NONE = 0xffffffff;
9
+ /** Each evaluated shape as its polygons, which a later shape reads without the rounding and splitting of triangles. */
10
+ const evaluated = new WeakMap();
11
+ const face = (id, vertices) => ({
12
+ id: String(id),
13
+ vertices,
14
+ uv: vertices.map(() => [0, 0]),
15
+ });
16
+ function triangleSolid(model, object, mesh) {
17
+ const source = mesh.vertices.array, count = mesh.vertices.length / 3, solid = {
18
+ vertices: Array.from({ length: count }, (_, v) => [...source.subarray(v * 3, v * 3 + 3)]),
19
+ faces: [],
20
+ colours: [],
21
+ fills: [],
22
+ fill: mesh.fill,
23
+ };
24
+ for (let t = 0; t < mesh.triangles.length / 3; t++) {
25
+ const corners = [...mesh.triangles.array.subarray(t * 3, t * 3 + 3)];
26
+ if (corners.some((v) => v >= count))
27
+ throw new LoaderError(F, 'range', `a triangle index of object ${object.id} is outside 0..${count - 1}`);
28
+ solid.faces.push(face(t, corners));
29
+ solid.fills.push(mesh.fills ? mesh.fills[t] : mesh.fill);
30
+ solid.colours.push([0, 1, 2].map((k) => {
31
+ const property = cornerProperty(model, object, mesh, t, k);
32
+ return property && model.properties.get(property.id)?.[property.index];
33
+ }));
34
+ }
35
+ return solid;
36
+ }
37
+ /** The solid under a 3MF transform; a mirrored one turns its faces back outward. */
38
+ function placed({ vertices, faces, colours, fills, fill }, m) {
39
+ const moved = new Map(), move = (from) => {
40
+ if (!from)
41
+ return from;
42
+ let to = moved.get(from);
43
+ if (!to)
44
+ moved.set(from, (to = movedFill(from, m)));
45
+ return to;
46
+ };
47
+ const mirrored = m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]) < 0;
48
+ const turn = (list) => (mirrored ? [...list].reverse() : list);
49
+ return {
50
+ vertices: vertices.map(([x, y, z]) => [0, 1, 2].map((k) => x * m[k] + y * m[3 + k] + z * m[6 + k] + m[9 + k])),
51
+ faces: faces.map((f, i) => face(i, turn(f.vertices))),
52
+ colours: colours.map(turn),
53
+ fills: fills.map(move),
54
+ fill: move(fill),
55
+ };
56
+ }
57
+ /** The fill of a solid after the 3MF transform `m`: a point goes back through `m` before the colour's own transform. */
58
+ function movedFill({ fields, ...fill }, m) {
59
+ const [a, b, c, d, e, f, g, h, i, x, y, z] = Array.from(m), determinant = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g), inverse = [
60
+ e * i - f * h,
61
+ c * h - b * i,
62
+ b * f - c * e,
63
+ f * g - d * i,
64
+ a * i - c * g,
65
+ c * d - a * f,
66
+ d * h - e * g,
67
+ b * g - a * h,
68
+ a * e - b * d,
69
+ ].map((v) => v / determinant), back = [0, 1, 2].map((k) => -(x * inverse[k] + y * inverse[3 + k] + z * inverse[6 + k])), rows = [...inverse, ...back],
70
+ // Row vectors: first `rows`, then the field's own.
71
+ after = (own = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]) => Array.from({ length: 12 }, (_, at) => {
72
+ const r = Math.floor(at / 3), k = at % 3;
73
+ return (rows[r * 3] * own[k] +
74
+ rows[r * 3 + 1] * own[3 + k] +
75
+ rows[r * 3 + 2] * own[6 + k] +
76
+ (r === 3 ? own[9 + k] : 0));
77
+ });
78
+ return { ...fill, fields: fields.map((field) => ({ ...field, transform: after(field.transform) })) };
79
+ }
80
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
81
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
82
+ const distance = (a, b) => Math.hypot(...sub(a, b));
83
+ const doubleArea = (a, b, c) => {
84
+ const u = sub(b, a), v = sub(c, a);
85
+ return Math.hypot(u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]);
86
+ };
87
+ /** Whether a triangle's least height is within a few Float32 steps at its corners, as `FLOAT32_GRAIN` of mesh-edit. */
88
+ function thin(a, b, c) {
89
+ const longest = Math.max(distance(a, b), distance(b, c), distance(c, a)), size = [a, b, c].flat().reduce((most, x) => Math.max(most, Math.abs(x)), 0);
90
+ return !(doubleArea(a, b, c) > longest * size * 2 ** -20);
91
+ }
92
+ /** The colour of a flat or linearly shaded source face at a point of its plane. */
93
+ function shade({ vertices, faces, colours }, at) {
94
+ const own = colours[at];
95
+ if (!own.every(Boolean))
96
+ return undefined;
97
+ const painted = own;
98
+ if (painted.every((c) => String(c) === String(painted[0])))
99
+ return () => painted[0];
100
+ const points = faces[at].vertices.map((v) => vertices[v]);
101
+ // The widest fan triangle carries the face's linear colour.
102
+ let best = 1;
103
+ for (let i = 2; i + 1 < points.length; i++)
104
+ if (doubleArea(points[0], points[i], points[i + 1]) > doubleArea(points[0], points[best], points[best + 1]))
105
+ best = i;
106
+ const [a, b, c] = [points[0], points[best], points[best + 1]], u = sub(b, a), v = sub(c, a), uu = dot(u, u), uv = dot(u, v), vv = dot(v, v), d = uu * vv - uv * uv || 1;
107
+ return (p) => {
108
+ const w = sub(p, a), s = (vv * dot(w, u) - uv * dot(w, v)) / d, t = (uu * dot(w, v) - uv * dot(w, u)) / d;
109
+ // Rounding puts a point of an edge a hair outside the triangle; a colour stays a colour.
110
+ return [0, 1, 2, 3].map((i) => Math.min(1, Math.max(0, (1 - s - t) * painted[0][i] + s * painted[best][i] + t * painted[best + 1][i])));
111
+ };
112
+ }
113
+ /**
114
+ * The triangles of `inputs[0] operation inputs[1..]` in the shape's coordinates and the model's unit, with its colours
115
+ * added to `model`.
116
+ *
117
+ * @throws LoaderError for an input that is not a closed, outward solid, and for more than `maxTriangles`.
118
+ */
119
+ export async function booleanMesh(model, id, operation, inputs, maxTriangles) {
120
+ const { batchBooleanMeshes } = await import('@margoengine/mesh-edit/boolean-batch'), label = `boolean shape ${id.slice(0, 32)}`;
121
+ const solids = inputs.map(({ model: owner, object, transform }) => placed(evaluated.get(object.mesh) ?? triangleSolid(owner, object, object.mesh), transform));
122
+ let next = 0, result;
123
+ try {
124
+ result = batchBooleanMeshes(solids, operation, { createId: () => `f${next++}`, precision: 'float32' });
125
+ }
126
+ catch (error) {
127
+ throw new LoaderError(F, error instanceof RangeError ? 'limit' : 'syntax', `${label}: ${error.message}`);
128
+ }
129
+ const points = result.mesh.vertices,
130
+ // The extension's overlapping order: a difference keeps the base's volume, the others take the last object's.
131
+ filling = (operation === 'difference' ? solids[0] : solids[solids.length - 1])?.fill, shape = { vertices: points, faces: [], colours: [], fills: [], fill: filling }, fills = [], vertices = floats(), triangles = uints(), pids = uints(), properties = uints(), welded = new Map(), colors = [], known = new Map();
132
+ let group = -1;
133
+ const colour = (value) => {
134
+ const key = value.join(',');
135
+ let at = known.get(key);
136
+ if (at === undefined) {
137
+ known.set(key, (at = colors.length));
138
+ colors.push(value);
139
+ }
140
+ return at;
141
+ };
142
+ const vertex = ([x, y, z]) => {
143
+ const stored = [Math.fround(x), Math.fround(y), Math.fround(z)], key = stored.join(',');
144
+ let at = welded.get(key);
145
+ if (at === undefined) {
146
+ welded.set(key, (at = vertices.length / 3));
147
+ vertices.push3(...stored);
148
+ }
149
+ return at;
150
+ };
151
+ for (const piece of result.mesh.faces) {
152
+ const { input, face: from } = result.sources[piece.id], paint = shade(solids[input], Number(from)), corners = piece.vertices.map((v) => points[v]), own = corners.map((p) => paint?.(p));
153
+ shape.faces.push(face(shape.faces.length, [...piece.vertices]));
154
+ shape.colours.push(own);
155
+ // A union's face is its own solid's surface; the faces of the others bound the filling volume.
156
+ const fill = operation === 'union' ? solids[input].fills[Number(from)] : filling;
157
+ shape.fills.push(fill);
158
+ if (paint && group < 0) {
159
+ group = model.propertyIds.length;
160
+ const key = `\0boolean ${id}`;
161
+ model.propertyIds.push(key);
162
+ model.properties.set(key, colors);
163
+ }
164
+ // A fan from the first corner; a face with corners about in a line fans from its centre, so no triangle is flat or
165
+ // too thin for Float32 to give it a normal.
166
+ let ring = corners, shades = own;
167
+ const flat = corners.some((p, i) => i > 1 && thin(corners[0], corners[i - 1], p));
168
+ if (flat) {
169
+ const centre = [0, 1, 2].map((k) => corners.reduce((sum, p) => sum + p[k], 0) / corners.length), shade = paint?.(centre);
170
+ ring = [centre, ...corners, corners[0]];
171
+ shades = [shade, ...own, own[0]];
172
+ }
173
+ const ids = ring.map(vertex), painting = shades.map((c) => (c ? colour(c) : NONE));
174
+ for (let i = 1; i + 1 < ids.length; i++) {
175
+ if (ids[0] === ids[i] || ids[i] === ids[i + 1] || ids[i + 1] === ids[0])
176
+ continue;
177
+ if (triangles.length / 3 >= maxTriangles)
178
+ throw new LoaderError(F, 'limit', `${label} exceeds ${maxTriangles} triangles; raise maxTriangles`);
179
+ triangles.push3(ids[0], ids[i], ids[i + 1]);
180
+ // A face whose source has no property has none either.
181
+ pids.push(paint ? group : NONE);
182
+ properties.push3(painting[0], painting[i], painting[i + 1]);
183
+ fills.push(fill);
184
+ }
185
+ }
186
+ const mesh = { vertices, triangles, pid: pids, p: properties };
187
+ if (filling)
188
+ mesh.fill = filling;
189
+ if (fills.some(Boolean))
190
+ mesh.fills = fills;
191
+ evaluated.set(mesh, shape);
192
+ return mesh;
193
+ }
@@ -0,0 +1,8 @@
1
+ import type { ThreeMFDisplacementOptions, ThreeMFDisplacementResult } from './threemf-displacement.js';
2
+ import type { ThreeMFExtension } from './threemf.js';
3
+ /** The displacement reader's hooks. */
4
+ export declare function displacementStage(options: ThreeMFDisplacementOptions): {
5
+ hooks: ThreeMFExtension;
6
+ /** What the reader adds to the core result, once the build has been walked. */
7
+ result(): Pick<ThreeMFDisplacementResult, 'maps' | 'displacementGroups' | 'meshes'>;
8
+ };
@@ -0,0 +1,213 @@
1
+ import { tessellate } from './threemf-tessellate.js';
2
+ import { LoaderError } from './types.js';
3
+ import { floats, limits, throwIfAborted } from './util.js';
4
+ const F = '3MF';
5
+ const bad = (message) => {
6
+ throw new LoaderError(F, 'syntax', message);
7
+ };
8
+ const required = (a, key, element) => a[key] ?? bad(`<${element}> without ${key}`);
9
+ const number = (value, what, fallback) => {
10
+ if (value === undefined)
11
+ return fallback ?? bad(`missing ${what}`);
12
+ const n = Number(value);
13
+ return value.trim() && Number.isFinite(n) ? n : bad(`invalid ${what}`);
14
+ };
15
+ const index = (value, count, what) => {
16
+ const n = number(value, what);
17
+ if (!Number.isInteger(n) || n < 0 || n >= count)
18
+ throw new LoaderError(F, 'range', `${what} ${String(value).slice(0, 16)} is outside 0..${count - 1}`);
19
+ return n;
20
+ };
21
+ /** The groups of one model part with their maps decoded by `@margoengine/decoders`, loaded only for a displaced mesh. */
22
+ async function heightGroups(groups, maps) {
23
+ const { decodePNG } = await import('@margoengine/decoders/png'), pictures = new Map();
24
+ return groups.map(({ mapId, modelPath, height, offset, coordinates, vectors }) => {
25
+ const map = maps.find((m) => m.id === mapId && m.modelPath === modelPath);
26
+ let picture = pictures.get(map.data);
27
+ if (!picture) {
28
+ try {
29
+ pictures.set(map.data, (picture = decodePNG(map.data, { bitDepth: 16 })));
30
+ }
31
+ catch (error) {
32
+ bad(`${map.path.slice(0, 128)}: ${error.message}`);
33
+ }
34
+ }
35
+ const heights = {
36
+ ...picture,
37
+ channel: 'RGBA'.indexOf(map.channel),
38
+ tileU: map.tileU,
39
+ tileV: map.tileV,
40
+ nearest: map.filter === 'nearest',
41
+ };
42
+ return { height, offset, coordinates, vectors, map: heights };
43
+ });
44
+ }
45
+ /** The displacement reader's hooks. */
46
+ export function displacementStage(options) {
47
+ const { samplesPerTexel = 1, maxSegments = 256 } = options;
48
+ if (!(Number.isFinite(samplesPerTexel) && samplesPerTexel > 0))
49
+ throw new LoaderError(F, 'range', 'samplesPerTexel must be a positive number');
50
+ if (!(Number.isInteger(maxSegments) && maxSegments >= 1 && maxSegments <= 65_536))
51
+ throw new LoaderError(F, 'range', 'maxSegments must be an integer from 1 to 65536');
52
+ const parts = new Map(), listed = new Map(), maps = [], groups = [], meshes = [];
53
+ const part = (model) => {
54
+ let found = parts.get(model);
55
+ if (!found)
56
+ parts.set(model, (found = { maps: new Map(), vectors: new Map(), groups: new Map(), meshes: new Map() }));
57
+ return found;
58
+ };
59
+ const resource = (p, a, element) => {
60
+ const id = required(a, 'id', element);
61
+ if (p.maps.has(id) || p.vectors.has(id) || p.groups.has(id))
62
+ bad(`duplicate resource id ${id.slice(0, 32)}`);
63
+ return id;
64
+ };
65
+ const hooks = {
66
+ welded: true,
67
+ field: {
68
+ open(model, name, a) {
69
+ const p = part(model);
70
+ if (name === 'displacement2d') {
71
+ const id = resource(p, a, name), channel = a.channel ?? 'G';
72
+ if (!['R', 'G', 'B', 'A'].includes(channel))
73
+ bad(`invalid displacement channel ${channel.slice(0, 8)}`);
74
+ p.maps.set(id, {
75
+ id,
76
+ path: required(a, 'path', name),
77
+ channel: channel,
78
+ tileU: a.tilestyleu ?? 'wrap',
79
+ tileV: a.tilestylev ?? 'wrap',
80
+ filter: a.filter ?? 'auto',
81
+ });
82
+ }
83
+ else if (name === 'normvectorgroup') {
84
+ const id = resource(p, a, name);
85
+ p.vectors.set(id, (p.list = []));
86
+ }
87
+ else if (name === 'normvector' && p.list) {
88
+ const v = [number(a.x, 'normvector x'), number(a.y, 'normvector y'), number(a.z, 'normvector z')], length = Math.hypot(...v);
89
+ if (!(length > 0))
90
+ bad('a displacement vector has no length');
91
+ // Consumers normalize vectors that are not (displacement extension 3.2.1).
92
+ p.list.push(v[0] / length, v[1] / length, v[2] / length);
93
+ }
94
+ else if (name === 'disp2dgroup') {
95
+ const id = resource(p, a, name), group = {
96
+ id,
97
+ mapId: required(a, 'dispid', name),
98
+ vectorsId: required(a, 'nid', name),
99
+ height: number(a.height, 'height'),
100
+ offset: number(a.offset, 'offset', 0),
101
+ coords: floats(),
102
+ normals: [],
103
+ };
104
+ if (!p.maps.has(group.mapId) || !p.vectors.has(group.vectorsId))
105
+ bad(`disp2dgroup ${id.slice(0, 32)} names a map or vector group not defined before it`);
106
+ p.groups.set(id, (p.group = group));
107
+ }
108
+ else if (name === 'disp2dcoord' && p.group) {
109
+ const vectors = p.vectors.get(p.group.vectorsId), factor = number(a.f, 'f', 1);
110
+ if (factor < 0)
111
+ bad('a displacement factor is negative');
112
+ p.group.coords.push3(number(a.u, 'u'), number(a.v, 'v'), factor);
113
+ p.group.normals.push(index(a.n, vectors.length / 3, 'vector index'));
114
+ }
115
+ },
116
+ close(model, name) {
117
+ const p = part(model);
118
+ if (name === 'normvectorgroup')
119
+ p.list = undefined;
120
+ else if (name === 'disp2dgroup')
121
+ p.group = undefined;
122
+ },
123
+ },
124
+ element(model, name, a) {
125
+ const p = part(model);
126
+ if (name === 'object')
127
+ p.object = a.id;
128
+ else if (name === 'displacementmesh' && p.object !== undefined) {
129
+ p.mesh = { groups: [], corners: [] };
130
+ p.meshes.set(p.object, p.mesh);
131
+ }
132
+ else if (name === 'triangles' && p.mesh)
133
+ p.mesh.did = a.did;
134
+ else if (name === 'triangle' && p.mesh) {
135
+ const { d1, d2 = d1, d3 = d1, did = p.mesh.did } = a;
136
+ if (d1 === undefined) {
137
+ p.mesh.groups.push(-1);
138
+ p.mesh.corners.push(-1, -1, -1);
139
+ return;
140
+ }
141
+ const group = did === undefined ? undefined : p.groups.get(did);
142
+ if (!group)
143
+ bad(`a displaced triangle of object ${String(p.object).slice(0, 32)} names no disp2dgroup`);
144
+ const count = group.coords.length / 3;
145
+ // The group's place in its part for now; `ready` turns it into its place in the result.
146
+ p.mesh.groups.push([...p.groups.keys()].indexOf(did));
147
+ p.mesh.corners.push(index(d1, count, 'd1'), index(d2, count, 'd2'), index(d3, count, 'd3'));
148
+ }
149
+ },
150
+ close(model, name) {
151
+ if (name === 'displacementmesh')
152
+ part(model).mesh = undefined;
153
+ },
154
+ instance(model, object, m, scale) {
155
+ listed
156
+ .get(model)
157
+ ?.get(object.id)
158
+ ?.instances.push(m.map((v) => v * scale));
159
+ },
160
+ async ready(bytes, { models, partPath }) {
161
+ const files = new Map();
162
+ for (const model of models.values()) {
163
+ const p = parts.get(model);
164
+ if (!p)
165
+ continue;
166
+ const modelPath = partPath(model), where = modelPath === undefined ? {} : { modelPath }, first = groups.length, own = new Map();
167
+ listed.set(model, own);
168
+ for (const map of p.maps.values()) {
169
+ let data = files.get(map.path);
170
+ if (!data)
171
+ files.set(map.path, (data = await bytes(map.path)));
172
+ maps.push({ ...map, ...where, data });
173
+ }
174
+ for (const { id, mapId, vectorsId, height, offset, coords, normals } of p.groups.values()) {
175
+ const list = p.vectors.get(vectorsId), vectors = new Float32Array(normals.length * 3);
176
+ normals.forEach((n, i) => vectors.set(list.slice(n * 3, n * 3 + 3), i * 3));
177
+ groups.push({ id, ...where, mapId, height, offset, coordinates: coords.result(), vectors });
178
+ }
179
+ for (const [objectId, found] of p.meshes) {
180
+ const data = model.objects.get(objectId).mesh, mesh = {
181
+ objectId,
182
+ ...where,
183
+ positions: data.vertices.result(),
184
+ indices: data.triangles.result(),
185
+ triangleGroups: Int32Array.from(found.groups, (g) => (g < 0 ? -1 : g + first)),
186
+ triangleCoordinates: Int32Array.from(found.corners),
187
+ instances: [],
188
+ };
189
+ own.set(objectId, mesh);
190
+ meshes.push(mesh);
191
+ }
192
+ if (options.tessellate === false || !p.meshes.size)
193
+ continue;
194
+ const heights = await heightGroups(groups.slice(first), maps);
195
+ for (const [objectId, found] of p.meshes) {
196
+ throwIfAborted(options.signal, F);
197
+ const object = model.objects.get(objectId);
198
+ object.mesh = tessellate(model, object, object.mesh, found.groups.map((g) => heights[g]), found.corners, { samplesPerTexel, maxSegments, maxTriangles: limits(options, F).maxTriangles });
199
+ }
200
+ }
201
+ },
202
+ bucket: () => '',
203
+ corner() { },
204
+ group() { },
205
+ };
206
+ return {
207
+ hooks,
208
+ /** What the reader adds to the core result, once the build has been walked. */
209
+ result() {
210
+ return { maps, displacementGroups: groups, meshes: meshes.filter((m) => m.instances.length) };
211
+ },
212
+ };
213
+ }