@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,497 @@
1
+ // 3MF materials extension on top of parse3MF: texture2d, texture2dgroup, compositematerials, multiproperties and the
2
+ // display properties (metallic, specular and translucent).
3
+ import { LoaderError } from './types.js';
4
+ import { floats } from './util.js';
5
+ import { SRGBToLinear, LinearToSRGB, hexColor } from '@margoengine/math/color';
6
+ import { THREEMF_UNITS, cornerProperty, read3MF, } from './threemf.js';
7
+ const F = '3MF';
8
+ /** A display property number: `fallback` when absent, refused below 0 or above `max`. */
9
+ function amount(value, fallback, max, what) {
10
+ if (value === undefined)
11
+ return fallback;
12
+ const number = value.trim() ? Number(value) : Number.NaN;
13
+ if (!(Number.isFinite(number) && number >= 0 && number <= max))
14
+ throw new LoaderError(F, 'range', `invalid ${what} "${value.slice(0, 32)}"`);
15
+ return number;
16
+ }
17
+ /** An sRGB colour attribute, `fallback` when absent. */
18
+ function colorOf(value, fallback) {
19
+ if (value === undefined)
20
+ return fallback;
21
+ const color = hexColor(value.trim());
22
+ if (!color)
23
+ throw new LoaderError(F, 'syntax', `invalid color "${value.slice(0, 16)}"`);
24
+ return color;
25
+ }
26
+ /** Three numbers of 0 or more, above 0 with `positive`. */
27
+ function triplet(value, what, positive) {
28
+ const out = list(value, what);
29
+ if (out.length !== 3)
30
+ throw new LoaderError(F, 'syntax', `${what} needs three numbers, not "${value.slice(0, 64)}"`);
31
+ if (out.some((v) => v < 0 || (positive && v === 0)))
32
+ throw new LoaderError(F, 'range', `invalid ${what} "${value.slice(0, 64)}"`);
33
+ return out;
34
+ }
35
+ function list(value, what) {
36
+ const parts = (value ?? '').trim().split(/\s+/).map(Number);
37
+ if (!value?.trim() || !parts.every(Number.isFinite))
38
+ throw new LoaderError(F, 'syntax', `invalid ${what} "${String(value).slice(0, 64)}"`);
39
+ return parts;
40
+ }
41
+ function required(value, element, attribute) {
42
+ if (!value)
43
+ throw new LoaderError(F, 'syntax', `<${element}> without ${attribute}`);
44
+ return value;
45
+ }
46
+ /**
47
+ * Reads a 3MF package like `parse3MF` and adds the materials extension: `texture2d` images, `texture2dgroup`
48
+ * coordinates, `compositematerials` as mixed colours, `multiproperties` layers, and the display properties as each
49
+ * group's `metallic` (`pbmetallic` and `pbmetallictexturedisplayproperties`), `specular` (`pbspecular` and
50
+ * `pbspeculartexturedisplayproperties`) or `translucent`. Every triangle corner gets its own
51
+ * vertex, so `uvs` and `colors` can differ across a seam; `uvs` use Margo's convention, v = 1 - the file's v. `colors` is
52
+ * present when corners of a triangle differ or a layer sets them. A group's `texture` indexes `textures`. In
53
+ * `multiproperties` colour layers mix by their alpha, and the first texture layer sets the group's texture: draw
54
+ * `colors` as a tint over it.
55
+ *
56
+ * @param input The package's bytes.
57
+ * @param options The same options as `parse3MF`.
58
+ * @returns The merged mesh with its coordinates, colours and images.
59
+ * @throws LoaderError with the codes of `parse3MF`, with `range` for a property index outside its group or its display
60
+ * properties, for a metalness, roughness or glossiness outside 0 to 1 (a texture's factor: below 0), a negative
61
+ * attenuation or a refractive index of 0 or less, and `syntax` for display properties that are not defined or are of a
62
+ * kind their group cannot take, and for a colour or a number triplet that is not one.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * import { parse3MFMaterials } from '@margoengine/loaders/threemf-materials';
67
+ *
68
+ * const bytes = await (await fetch('/prints/lithophane.3mf')).arrayBuffer();
69
+ * const { groups, textures, uvs } = await parse3MFMaterials(bytes);
70
+ * const image = await createImageBitmap(new Blob([textures[groups[0].texture ?? 0].data]));
71
+ * console.log(image.width, uvs?.length);
72
+ * ```
73
+ */
74
+ export function parse3MFMaterials(input, options = {}) {
75
+ return read3MFMaterials(input, options);
76
+ }
77
+ /** Shared materials reader with optional additional format hooks, used by the lattice/slice entry. */
78
+ export async function read3MFMaterials(input, options, extra) {
79
+ const stores = new Map(), textures = [], uvs = floats(), colors = floats(), opacity = floats(),
80
+ /** Each layer attribute's values by vertex, written at each corner. */
81
+ layerData = new Map();
82
+ let group, multi, composite,
83
+ /** The open container of display properties, and the open `basematerials` with the `<base>` elements seen in it. */
84
+ entries, materialGroup, textured = false, varied = false, translucent = false;
85
+ const store = (model) => {
86
+ let found = stores.get(model);
87
+ if (!found) {
88
+ found = {
89
+ textures: new Map(),
90
+ groups: new Map(),
91
+ multis: new Map(),
92
+ materials: new Set(),
93
+ displays: new Map(),
94
+ shown: new Map(),
95
+ bases: new Map(),
96
+ };
97
+ stores.set(model, found);
98
+ }
99
+ return found;
100
+ };
101
+ /** The display properties of entry `index` of a property group. Read after parsing, so a later resource counts. */
102
+ const finish = (model, id, index) => {
103
+ const { displays, shown, bases, groups, multis, textures: known } = store(model), layers = multis.get(id);
104
+ if (layers) {
105
+ for (let layer = 0; layer < layers.pids.length; layer++) {
106
+ const found = finish(model, layers.pids[layer], layers.rows[index]?.[layer] ?? 0);
107
+ if (found)
108
+ return [found[0], { ...found[1], layer }];
109
+ }
110
+ return undefined;
111
+ }
112
+ const reference = shown.get(id) ?? bases.get(id)?.get(index);
113
+ if (reference === undefined)
114
+ return undefined;
115
+ const display = displays.get(reference), refuse = (code, what) => {
116
+ throw new LoaderError(F, code, what);
117
+ }, short = reference.slice(0, 32);
118
+ if (!display)
119
+ return refuse('syntax', `display properties ${short} are not defined`);
120
+ if ('maps' in display !== groups.has(id))
121
+ return refuse('syntax', `property group ${id.slice(0, 32)} cannot take the kind of display properties ${short}`);
122
+ if (!('maps' in display))
123
+ return [
124
+ display.kind,
125
+ display.entries[index] ?? refuse('range', `property index ${index} is outside display properties ${short}`),
126
+ ];
127
+ const [first, second] = display.maps.map((texture) => known.get(texture) ?? refuse('syntax', `texture ${texture.slice(0, 32)} is not defined`)), named = display.kind === 'metallic'
128
+ ? { metalnessTexture: first, roughnessTexture: second }
129
+ : { specularTexture: first, glossinessTexture: second };
130
+ return [display.kind, { ...display.entry, ...named }];
131
+ };
132
+ /** A triangle's display properties: its first corner's. */
133
+ const finishAt = (...[model, object, mesh, t]) => {
134
+ const property = cornerProperty(model, object, mesh, t, 0);
135
+ return property && finish(model, property.id, property.index);
136
+ };
137
+ /** What one corner samples: a texture and uv, a colour, or both through layers. */
138
+ const sample = (model, id, index, layered) => {
139
+ const { groups, multis, textures: known } = store(model), coords = groups.get(id);
140
+ if (coords) {
141
+ if ((index + 1) * 2 > coords.coords.length)
142
+ throw new LoaderError(F, 'range', `property index ${index} is outside texture group ${id.slice(0, 32)}`);
143
+ const texture = known.get(coords.texture);
144
+ if (texture === undefined)
145
+ throw new LoaderError(F, 'syntax', `texture ${coords.texture.slice(0, 32)} is not defined`);
146
+ return { texture, u: coords.coords[index * 2], v: 1 - coords.coords[index * 2 + 1] };
147
+ }
148
+ const layers = layered ? undefined : multis.get(id);
149
+ if (layers) {
150
+ const row = layers.rows[index];
151
+ if (!row)
152
+ throw new LoaderError(F, 'range', `property index ${index} is outside multiproperties ${id.slice(0, 32)}`);
153
+ const out = {};
154
+ layers.pids.forEach((pid, layer) => {
155
+ const { color, ...image } = sample(model, pid, row[layer] ?? 0, true);
156
+ if (image.texture !== undefined && out.texture === undefined)
157
+ Object.assign(out, image);
158
+ if (color) {
159
+ const under = out.color, a = color[3];
160
+ if (under) {
161
+ const multiply = layers.blends[layer - 1] === 'multiply';
162
+ out.color = [0, 1, 2].map((c) => LinearToSRGB(multiply
163
+ ? SRGBToLinear(color[c]) * SRGBToLinear(under[c])
164
+ : SRGBToLinear(color[c]) * a + SRGBToLinear(under[c]) * (1 - a)));
165
+ out.color[3] = multiply ? a * under[3] : a + under[3] * (1 - a);
166
+ }
167
+ else
168
+ out.color = [...color];
169
+ }
170
+ });
171
+ return out;
172
+ }
173
+ const colorsOf = model.properties.get(id);
174
+ if (!colorsOf)
175
+ return {};
176
+ if (index >= colorsOf.length)
177
+ throw new LoaderError(F, 'range', `property index ${index} is outside property group ${id.slice(0, 32)}`);
178
+ return { color: colorsOf[index] };
179
+ };
180
+ const at = (model, ...where) => {
181
+ const property = cornerProperty(...where);
182
+ return property ? sample(model, property.id, property.index, false) : {};
183
+ };
184
+ const extension = {
185
+ element(model, name, a) {
186
+ if (name === 'basematerials' || name === 'colorgroup') {
187
+ if (a.id && a.displaypropertiesid)
188
+ store(model).shown.set(a.id, a.displaypropertiesid);
189
+ if (name === 'basematerials' && a.id) {
190
+ store(model).materials.add(a.id);
191
+ materialGroup = { id: a.id, count: 0 };
192
+ }
193
+ }
194
+ else if (name === 'base' && materialGroup) {
195
+ const index = materialGroup.count++;
196
+ if (a.displaypropertiesid) {
197
+ const { bases } = store(model);
198
+ let own = bases.get(materialGroup.id);
199
+ if (!own)
200
+ bases.set(materialGroup.id, (own = new Map()));
201
+ own.set(index, a.displaypropertiesid);
202
+ }
203
+ }
204
+ },
205
+ open(model, name, a) {
206
+ switch (name) {
207
+ case 'texture2d': {
208
+ const id = required(a.id, name, 'id');
209
+ store(model).textures.set(id, textures.length);
210
+ textures.push({
211
+ path: required(a.path, name, 'path'),
212
+ contentType: a.contenttype ?? '',
213
+ data: new Uint8Array(0),
214
+ tileStyleU: a.tilestyleu ?? 'wrap',
215
+ tileStyleV: a.tilestylev ?? 'wrap',
216
+ filter: a.filter ?? 'auto',
217
+ });
218
+ break;
219
+ }
220
+ case 'texture2dgroup': {
221
+ const id = required(a.id, name, 'id');
222
+ group = { texture: required(a.texid, name, 'texid'), coords: [] };
223
+ store(model).groups.set(id, group);
224
+ if (a.displaypropertiesid)
225
+ store(model).shown.set(id, a.displaypropertiesid);
226
+ model.propertyIds.push(id);
227
+ break;
228
+ }
229
+ case 'pbmetallicdisplayproperties':
230
+ case 'pbspeculardisplayproperties':
231
+ case 'translucentdisplayproperties': {
232
+ const kind = name === 'translucentdisplayproperties'
233
+ ? 'translucent'
234
+ : name === 'pbspeculardisplayproperties'
235
+ ? 'specular'
236
+ : 'metallic';
237
+ entries = [];
238
+ store(model).displays.set(required(a.id, name, 'id'), { kind, entries });
239
+ break;
240
+ }
241
+ case 'pbmetallic':
242
+ entries?.push({
243
+ name: a.name ?? '',
244
+ metalness: amount(a.metallicness, 0, 1, 'metallicness'),
245
+ roughness: amount(a.roughness, 1, 1, 'roughness'),
246
+ });
247
+ break;
248
+ case 'pbspecular': {
249
+ const [r, g, b] = colorOf(a.specularcolor, [56 / 255, 56 / 255, 56 / 255, 1]);
250
+ entries?.push({
251
+ name: a.name ?? '',
252
+ specularColor: [r, g, b],
253
+ glossiness: amount(a.glossiness, 0, 1, 'glossiness'),
254
+ });
255
+ break;
256
+ }
257
+ case 'translucent':
258
+ entries?.push({
259
+ name: a.name ?? '',
260
+ attenuation: triplet(required(a.attenuation, name, 'attenuation'), 'attenuation', false),
261
+ refractiveIndex: triplet(a.refractiveindex ?? '1 1 1', 'refractiveindex', true),
262
+ roughness: amount(a.roughness, 0, 1, 'roughness'),
263
+ });
264
+ break;
265
+ case 'pbmetallictexturedisplayproperties': {
266
+ const factor = colorOf(a.basecolorfactor, [1, 1, 1, 1]);
267
+ store(model).displays.set(required(a.id, name, 'id'), {
268
+ kind: 'metallic',
269
+ maps: [
270
+ required(a.metallictextureid, name, 'metallictextureid'),
271
+ required(a.roughnesstextureid, name, 'roughnesstextureid'),
272
+ ],
273
+ entry: {
274
+ name: a.name ?? '',
275
+ // A factor above 1 brightens the sampled value, which stays at most 1.
276
+ metalness: amount(a.metallicfactor, 1, Number.MAX_VALUE, 'metallicfactor'),
277
+ roughness: amount(a.roughnessfactor, 1, Number.MAX_VALUE, 'roughnessfactor'),
278
+ ...(factor.some((value) => value !== 1) ? { baseColorFactor: factor } : {}),
279
+ },
280
+ });
281
+ break;
282
+ }
283
+ case 'pbspeculartexturedisplayproperties': {
284
+ const [r, g, b] = colorOf(a.specularfactor, [1, 1, 1, 1]), diffuse = colorOf(a.diffusefactor, [1, 1, 1, 1]);
285
+ store(model).displays.set(required(a.id, name, 'id'), {
286
+ kind: 'specular',
287
+ maps: [
288
+ required(a.speculartextureid, name, 'speculartextureid'),
289
+ required(a.glossinesstextureid, name, 'glossinesstextureid'),
290
+ ],
291
+ entry: {
292
+ name: a.name ?? '',
293
+ specularColor: [r, g, b],
294
+ glossiness: amount(a.glossinessfactor, 1, Number.MAX_VALUE, 'glossinessfactor'),
295
+ ...(diffuse.some((value) => value !== 1) ? { diffuseFactor: diffuse } : {}),
296
+ },
297
+ });
298
+ break;
299
+ }
300
+ case 'tex2coord': {
301
+ const u = Number(a.u), v = Number(a.v);
302
+ if (!Number.isFinite(u) || !Number.isFinite(v))
303
+ throw new LoaderError(F, 'syntax', `invalid texture coordinate "${a.u}, ${a.v}"`);
304
+ group?.coords.push(u, v);
305
+ break;
306
+ }
307
+ case 'multiproperties': {
308
+ const id = required(a.id, name, 'id');
309
+ const pids = required(a.pids, name, 'pids').trim().split(/\s+/), blends = a.blendmethods?.trim().split(/\s+/) ?? [];
310
+ if (blends.length >= pids.length || blends.some((b) => b !== 'mix' && b !== 'multiply'))
311
+ throw new LoaderError(F, 'range', 'blendmethods must contain mix/multiply for at most layers minus one');
312
+ const { groups, multis, materials } = store(model), kinds = pids.map((pid, k) => {
313
+ if (groups.has(pid))
314
+ return 'texture';
315
+ if (multis.has(pid))
316
+ throw new LoaderError(F, 'syntax', 'a multiproperties must not name a multiproperties');
317
+ if (!model.properties.has(pid))
318
+ throw new LoaderError(F, 'syntax', `property group ${pid.slice(0, 32)} is not defined`);
319
+ if (materials.has(pid) && k)
320
+ throw new LoaderError(F, 'syntax', 'a multiproperties names one material group at most, first');
321
+ return 'color';
322
+ });
323
+ if (kinds.filter((kind, k) => kind === 'color' && !materials.has(pids[k])).length > 1)
324
+ throw new LoaderError(F, 'syntax', 'a multiproperties names one colour group at most');
325
+ multi = { pids, rows: [], blends, kinds };
326
+ store(model).multis.set(id, multi);
327
+ model.propertyIds.push(id);
328
+ break;
329
+ }
330
+ case 'multi':
331
+ multi?.rows.push(list(a.pindices, 'pindices'));
332
+ break;
333
+ case 'compositematerials': {
334
+ const id = required(a.id, name, 'id'), base = model.properties.get(required(a.matid, name, 'matid'));
335
+ if (!base)
336
+ throw new LoaderError(F, 'syntax', `material group ${a.matid.slice(0, 32)} is not defined`);
337
+ composite = { base, indices: list(a.matindices, 'matindices'), colors: [] };
338
+ store(model).materials.add(id);
339
+ if (a.displaypropertiesid)
340
+ store(model).shown.set(id, a.displaypropertiesid);
341
+ model.properties.set(id, composite.colors);
342
+ model.propertyIds.push(id);
343
+ break;
344
+ }
345
+ case 'composite': {
346
+ if (!composite)
347
+ break;
348
+ const { base, indices } = composite, values = list(a.values, 'values'), mixed = [0, 0, 0, 0];
349
+ let total = 0;
350
+ indices.forEach((index, i) => {
351
+ const weight = values[i] ?? 0, color = base[index];
352
+ if (weight < 0)
353
+ throw new LoaderError(F, 'range', 'composite weights must be nonnegative');
354
+ if (!color)
355
+ throw new LoaderError(F, 'range', `matindices entry ${index} is outside its material group`);
356
+ total += weight;
357
+ for (let c = 0; c < 4; c++)
358
+ mixed[c] += (c < 3 ? SRGBToLinear(color[c]) : color[c]) * weight;
359
+ });
360
+ if (total === 0) {
361
+ for (const index of indices)
362
+ for (let c = 0; c < 4; c++)
363
+ mixed[c] += c < 3 ? SRGBToLinear(base[index][c]) : base[index][c];
364
+ total = indices.length;
365
+ }
366
+ composite.colors.push(mixed.map((value, c) => (c < 3 ? LinearToSRGB(value / total) : value / total)));
367
+ break;
368
+ }
369
+ }
370
+ },
371
+ close(_, name) {
372
+ if (name === 'texture2dgroup')
373
+ group = undefined;
374
+ else if (name === 'multiproperties')
375
+ multi = undefined;
376
+ else if (name === 'compositematerials')
377
+ composite = undefined;
378
+ else if (name.endsWith('displayproperties'))
379
+ entries = undefined;
380
+ else if (name === 'basematerials')
381
+ materialGroup = undefined;
382
+ },
383
+ async ready(read) {
384
+ for (const texture of textures)
385
+ texture.data = await read(texture.path);
386
+ },
387
+ bucket(model, object, mesh, t) {
388
+ const property = cornerProperty(model, object, mesh, t, 0), layered = property && store(model).multis.has(property.id) ? `|m${property.id}` : '';
389
+ const found = finishAt(model, object, mesh, t),
390
+ // The name does not change how a triangle looks, so it does not split a group.
391
+ shown = found ? `|${found[0]}${JSON.stringify({ ...found[1], name: undefined })}` : '';
392
+ return String(at(model, model, object, mesh, t, 0).texture ?? '') + layered + shown;
393
+ },
394
+ corner(model, object, mesh, t, k) {
395
+ const property = cornerProperty(model, object, mesh, t, k), layers = property && store(model).multis.get(property.id);
396
+ if (layers) {
397
+ const vertex = uvs.length / 2, row = layers.rows[property.index];
398
+ if (!row)
399
+ throw new LoaderError(F, 'range', `property index ${property.index} is outside multiproperties ${property.id.slice(0, 32)}`);
400
+ layers.pids.forEach((pid, layer) => {
401
+ // A pindex the row leaves out is 0 (spec 5.1).
402
+ const { color, u, v } = sample(model, pid, row[layer] ?? 0, true), name = `layer${color ? 'Color' : 'UV'}${layer}`;
403
+ let data = layerData.get(name);
404
+ if (!data)
405
+ layerData.set(name, (data = { size: color ? 4 : 2, values: new Map() }));
406
+ data.values.set(vertex, color ? [...color] : [u ?? 0, v ?? 0]);
407
+ });
408
+ }
409
+ const { texture, u, v, color } = at(model, model, object, mesh, t, k);
410
+ if (texture !== undefined)
411
+ textured = true;
412
+ uvs.push(u ?? 0);
413
+ uvs.push(v ?? 0);
414
+ const [r, g, b] = color ?? [1, 1, 1];
415
+ colors.push3(r, g, b);
416
+ const alpha = color?.[3] ?? 1;
417
+ opacity.push(alpha);
418
+ if (alpha !== 1)
419
+ translucent = true;
420
+ if (!varied) {
421
+ const first = at(model, model, object, mesh, t, 0).color;
422
+ varied = color !== first || (store(model).multis.size > 0 && color !== undefined);
423
+ }
424
+ },
425
+ group(target, model, object, mesh, t) {
426
+ const { texture } = at(model, model, object, mesh, t, 0);
427
+ if (texture !== undefined)
428
+ target.texture = texture;
429
+ const found = finishAt(model, object, mesh, t);
430
+ if (found)
431
+ Object.assign(target, { [found[0]]: found[1] });
432
+ const property = cornerProperty(model, object, mesh, t, 0), { multis, groups, textures: known } = store(model), layers = property && multis.get(property.id);
433
+ if (layers)
434
+ target.layers = layers.pids.map((pid, k) => {
435
+ const kind = layers.kinds[k];
436
+ return {
437
+ kind,
438
+ ...(kind === 'texture' ? { texture: known.get(groups.get(pid).texture) } : {}),
439
+ attribute: `layer${kind === 'texture' ? 'UV' : 'Color'}${k}`,
440
+ blend: k && layers.blends[k - 1] === 'multiply' ? 'multiply' : 'mix',
441
+ };
442
+ });
443
+ },
444
+ };
445
+ const hooks = extra
446
+ ? {
447
+ element(model, name, a) {
448
+ extension.element?.(model, name, a);
449
+ return extra.element?.(model, name, a);
450
+ },
451
+ instance: extra.instance,
452
+ hasGeometry: extra.hasGeometry,
453
+ open(model, name, a) {
454
+ extension.open?.(model, name, a);
455
+ extra.open?.(model, name, a);
456
+ },
457
+ close(model, name) {
458
+ extension.close?.(model, name);
459
+ extra.close?.(model, name);
460
+ },
461
+ async ready(read, context) {
462
+ await extra.ready?.(read, context);
463
+ await extension.ready?.(read, context);
464
+ },
465
+ bucket(model, object, mesh, t) {
466
+ return extension.bucket(model, object, mesh, t) + '|' + extra.bucket(model, object, mesh, t);
467
+ },
468
+ corner(model, object, mesh, t, k) {
469
+ extension.corner(model, object, mesh, t, k);
470
+ extra.corner(model, object, mesh, t, k);
471
+ },
472
+ group(group, model, object, mesh, t) {
473
+ extension.group(group, model, object, mesh, t);
474
+ extra.group(group, model, object, mesh, t);
475
+ },
476
+ }
477
+ : extension;
478
+ const result = (await read3MF(input, options, hooks));
479
+ result.textures = textures;
480
+ result.metresPerUnit = options.units === 'file' ? THREEMF_UNITS[result.unit] : 1;
481
+ if (textured)
482
+ result.uvs = uvs.result();
483
+ if (varied)
484
+ result.colors = colors.result();
485
+ else
486
+ delete result.colors;
487
+ if (translucent)
488
+ result.attributes = { ...result.attributes, opacity: opacity.result() };
489
+ const vertices = result.positions.length / 3;
490
+ for (const [name, { size, values }] of layerData) {
491
+ const out = new Float32Array(vertices * size);
492
+ for (const [vertex, value] of values)
493
+ out.set(value, vertex * size);
494
+ result.attributes = { ...result.attributes, [name]: out };
495
+ }
496
+ return result;
497
+ }
@@ -0,0 +1,75 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ // @ts-ignore optional peer: its types apply when it is installed
3
+ import { Material, Texture, type MaterialMesh } from '@margoengine/materials';
4
+ import type { ThreeMFMaterials } from './threemf-materials.js';
5
+ /** Options of {@link create3MFMesh}. */
6
+ export interface ThreeMFMeshOptions {
7
+ /**
8
+ * `'smooth'` (default) shares one angle-weighted normal where corners meet at the same position and their faces are
9
+ * within `creaseAngle` of each other, so edges sharper than that stay sharp; `'flat'` gives every triangle its face
10
+ * normal.
11
+ */
12
+ normals?: 'smooth' | 'flat';
13
+ /** The largest angle between faces that `'smooth'` normals blend across, in degrees, 0 to 180. Default 40. */
14
+ creaseAngle?: number;
15
+ /**
16
+ * Every material's roughness, 0 to 1, in place of the file's value and map. Default: that of the group's `metallic` or
17
+ * `translucent`, 1 - the glossiness of its `specular`, else 0.6.
18
+ */
19
+ roughness?: number;
20
+ /** Every material's metalness, 0 to 1, in place of the file's value and map. Default: the group's `metallic`, else 0. */
21
+ metalness?: number;
22
+ /** Draw both faces. Default true: printed parts are often open or inside out. */
23
+ doubleSided?: boolean;
24
+ /** Draw the colours as they are, without light (`shading: 'basic'`). Default false. */
25
+ unlit?: boolean;
26
+ /** Draw order of the mesh. Default 0. */
27
+ renderOrder?: number;
28
+ /** Stops the image decoding; the promise then rejects with a `LoaderError` code `aborted`. */
29
+ signal?: AbortSignal;
30
+ }
31
+ /** What {@link create3MFMesh} made. The textures and materials are its own: `dispose()` releases them with the mesh. */
32
+ export interface ThreeMFMesh {
33
+ mesh: MaterialMesh<Material[]>;
34
+ /**
35
+ * One per group, in `groups` order, empty groups left out. Groups that look alike (a scan has one per vertex colour)
36
+ * share one `Material`, so changing it changes them all.
37
+ */
38
+ materials: Material[];
39
+ /** The decoded textures, by their index in `textures`. */
40
+ textures: Map<number, Texture>;
41
+ dispose(): void;
42
+ [Symbol.dispose](): void;
43
+ }
44
+ /**
45
+ * Draws a `parse3MFMaterials` result as one materials mesh with a material per group: colour groups, composites and
46
+ * per-corner colours as vertex colours, a texture group's image as the colour map, and a `multiproperties` stack as its
47
+ * layers (`layered()`), blended as the 3MF Materials and Properties Extension 1.2.1 specifies (mix and multiply, in
48
+ * linear light). A group's `metallic` sets its material's metalness and roughness, with their maps. Its `specular` is
49
+ * drawn as an index of refraction of 0 with that specular colour (`KHR_materials_ior`), and roughness 1 - glossiness.
50
+ * Its `translucent` is drawn as transmission through a volume: the thickness is the object's mean chord, 4 V / S, and the
51
+ * attenuation is converted with `metresPerUnit`; draw it with `@margoengine/materials/transmission` to refract the scene
52
+ * behind it, without which the background shows through tinted. `unlit` draws neither. Colour images decode with
53
+ * `createImageBitmap`; roughness, metalness and glossiness maps need the optional `@margoengine/decoders` peer, which
54
+ * reads their texels exactly.
55
+ *
56
+ * @param engine The engine to draw in.
57
+ * @param loaded What `parse3MFMaterials` returned.
58
+ * @param options Normals, surface numbers, draw order and an abort signal.
59
+ * @returns The mesh, its materials and textures, and `dispose()`.
60
+ * @throws LoaderError `unsupported` for a stack needing more than two UV sets or a varying colour above a texture
61
+ * layer, `range` for a group naming a missing texture or layer attribute, `aborted` when the signal fires.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * import { Engine } from '@margoengine/core';
66
+ * import { parse3MFMaterials } from '@margoengine/loaders/threemf-materials';
67
+ * import { create3MFMesh } from '@margoengine/loaders/threemf-mesh';
68
+ *
69
+ * const engine = await Engine.create(document.querySelector('canvas')!);
70
+ * const bytes = await (await fetch('/prints/multiprop-opaque.3mf')).arrayBuffer();
71
+ * using model = await create3MFMesh(engine, await parse3MFMaterials(bytes));
72
+ * console.log(model.materials.length, model.textures.size);
73
+ * ```
74
+ */
75
+ export declare function create3MFMesh(engine: EngineKernel, loaded: ThreeMFMaterials, options?: ThreeMFMeshOptions): Promise<ThreeMFMesh>;