@margoengine/loaders 0.0.0-stage → 0.1.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 (184) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1198 -3
  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/dae-animation.d.ts +66 -0
  17. package/dist/dae-animation.js +266 -0
  18. package/dist/dae-common.d.ts +95 -0
  19. package/dist/dae-common.js +226 -0
  20. package/dist/dae-controllers.d.ts +57 -0
  21. package/dist/dae-controllers.js +164 -0
  22. package/dist/dae-pose.d.ts +131 -0
  23. package/dist/dae-pose.js +381 -0
  24. package/dist/dae-scene.d.ts +203 -0
  25. package/dist/dae-scene.js +279 -0
  26. package/dist/dae.d.ts +161 -0
  27. package/dist/dae.js +633 -0
  28. package/dist/detect.d.ts +20 -0
  29. package/dist/detect.js +72 -0
  30. package/dist/dxf.d.ts +81 -0
  31. package/dist/dxf.js +774 -0
  32. package/dist/engine.d.ts +36 -0
  33. package/dist/engine.js +117 -0
  34. package/dist/font-opentype.d.ts +14 -0
  35. package/dist/font-opentype.js +33 -0
  36. package/dist/font-woff.d.ts +23 -0
  37. package/dist/font-woff.js +293 -0
  38. package/dist/font.d.ts +41 -0
  39. package/dist/font.js +26 -0
  40. package/dist/gcode.d.ts +55 -0
  41. package/dist/gcode.js +278 -0
  42. package/dist/geo-model.d.ts +84 -0
  43. package/dist/geo-model.js +220 -0
  44. package/dist/geo-mvt.d.ts +15 -0
  45. package/dist/geo-mvt.js +302 -0
  46. package/dist/geo-shp.d.ts +15 -0
  47. package/dist/geo-shp.js +234 -0
  48. package/dist/geo-xml.d.ts +6 -0
  49. package/dist/geo-xml.js +165 -0
  50. package/dist/geo.d.ts +8 -0
  51. package/dist/geo.js +59 -0
  52. package/dist/geometry.d.ts +60 -0
  53. package/dist/geometry.js +273 -0
  54. package/dist/index.d.ts +54 -0
  55. package/dist/index.js +28 -0
  56. package/dist/kmz.d.ts +78 -0
  57. package/dist/kmz.js +173 -0
  58. package/dist/las.d.ts +92 -0
  59. package/dist/las.js +110 -0
  60. package/dist/ldraw.d.ts +118 -0
  61. package/dist/ldraw.js +474 -0
  62. package/dist/load.d.ts +72 -0
  63. package/dist/load.js +205 -0
  64. package/dist/lottie.d.ts +154 -0
  65. package/dist/lottie.js +893 -0
  66. package/dist/lwo.d.ts +81 -0
  67. package/dist/lwo.js +454 -0
  68. package/dist/lzf.d.ts +13 -0
  69. package/dist/lzf.js +56 -0
  70. package/dist/materialx.d.ts +120 -0
  71. package/dist/materialx.js +563 -0
  72. package/dist/md2.d.ts +52 -0
  73. package/dist/md2.js +112 -0
  74. package/dist/mmcif.d.ts +14 -0
  75. package/dist/mmcif.js +246 -0
  76. package/dist/mmd.d.ts +244 -0
  77. package/dist/mmd.js +958 -0
  78. package/dist/mocap.d.ts +71 -0
  79. package/dist/mocap.js +178 -0
  80. package/dist/molecule-common.d.ts +4 -0
  81. package/dist/molecule-common.js +54 -0
  82. package/dist/mtl.d.ts +120 -0
  83. package/dist/mtl.js +469 -0
  84. package/dist/normals.d.ts +7 -0
  85. package/dist/normals.js +31 -0
  86. package/dist/nrrd.d.ts +63 -0
  87. package/dist/nrrd.js +743 -0
  88. package/dist/nurbs.d.ts +118 -0
  89. package/dist/nurbs.js +265 -0
  90. package/dist/obj.d.ts +143 -0
  91. package/dist/obj.js +456 -0
  92. package/dist/off.d.ts +10 -0
  93. package/dist/off.js +155 -0
  94. package/dist/outline-font.d.ts +87 -0
  95. package/dist/outline-font.js +110 -0
  96. package/dist/outline.d.ts +20 -0
  97. package/dist/outline.js +215 -0
  98. package/dist/pcd.d.ts +34 -0
  99. package/dist/pcd.js +258 -0
  100. package/dist/pdb.d.ts +67 -0
  101. package/dist/pdb.js +126 -0
  102. package/dist/ply.d.ts +35 -0
  103. package/dist/ply.js +392 -0
  104. package/dist/polygon.d.ts +9 -0
  105. package/dist/polygon.js +49 -0
  106. package/dist/prwm.d.ts +24 -0
  107. package/dist/prwm.js +114 -0
  108. package/dist/render.d.ts +27 -0
  109. package/dist/render.js +153 -0
  110. package/dist/sfnt-cff.d.ts +37 -0
  111. package/dist/sfnt-cff.js +749 -0
  112. package/dist/sfnt-layout.d.ts +24 -0
  113. package/dist/sfnt-layout.js +266 -0
  114. package/dist/sfnt-reader.d.ts +28 -0
  115. package/dist/sfnt-reader.js +87 -0
  116. package/dist/sfnt-variation.d.ts +40 -0
  117. package/dist/sfnt-variation.js +318 -0
  118. package/dist/shared/asset-url.js +82 -0
  119. package/dist/shared/crc32.d.ts +2 -0
  120. package/dist/shared/crc32.js +47 -0
  121. package/dist/shared/errors.js +36 -0
  122. package/dist/shared/inflate.js +284 -0
  123. package/dist/shared/normals.js +26 -0
  124. package/dist/shared/scene-scope.js +56 -0
  125. package/dist/shared/trailing-data.js +42 -0
  126. package/dist/stl.d.ts +64 -0
  127. package/dist/stl.js +309 -0
  128. package/dist/svg.d.ts +90 -0
  129. package/dist/svg.js +1007 -0
  130. package/dist/tds.d.ts +2 -0
  131. package/dist/tds.js +2 -0
  132. package/dist/textures.d.ts +42 -0
  133. package/dist/textures.js +53 -0
  134. package/dist/threemf-lattice.d.ts +139 -0
  135. package/dist/threemf-lattice.js +514 -0
  136. package/dist/threemf-materials.d.ts +75 -0
  137. package/dist/threemf-materials.js +314 -0
  138. package/dist/threemf-mesh.d.ts +60 -0
  139. package/dist/threemf-mesh.js +201 -0
  140. package/dist/threemf.d.ts +101 -0
  141. package/dist/threemf.js +415 -0
  142. package/dist/tilt.d.ts +62 -0
  143. package/dist/tilt.js +186 -0
  144. package/dist/tmx.d.ts +151 -0
  145. package/dist/tmx.js +394 -0
  146. package/dist/ttf.d.ts +78 -0
  147. package/dist/ttf.js +568 -0
  148. package/dist/types.d.ts +90 -0
  149. package/dist/types.js +35 -0
  150. package/dist/usd.d.ts +2 -0
  151. package/dist/usd.js +2 -0
  152. package/dist/usd.worker.d.ts +1 -0
  153. package/dist/usdz.d.ts +50 -0
  154. package/dist/usdz.js +646 -0
  155. package/dist/util.d.ts +75 -0
  156. package/dist/util.js +241 -0
  157. package/dist/vdb.d.ts +111 -0
  158. package/dist/vdb.js +663 -0
  159. package/dist/vrml.d.ts +53 -0
  160. package/dist/vrml.js +532 -0
  161. package/dist/vtk-cells.d.ts +29 -0
  162. package/dist/vtk-cells.js +211 -0
  163. package/dist/vtk-legacy.d.ts +57 -0
  164. package/dist/vtk-legacy.js +439 -0
  165. package/dist/vtk-reader.d.ts +19 -0
  166. package/dist/vtk-reader.js +134 -0
  167. package/dist/vtk-xml.d.ts +96 -0
  168. package/dist/vtk-xml.js +578 -0
  169. package/dist/vtk.d.ts +13 -0
  170. package/dist/vtk.js +234 -0
  171. package/dist/woff-glyf.d.ts +17 -0
  172. package/dist/woff-glyf.js +215 -0
  173. package/dist/worker.d.ts +10 -0
  174. package/dist/worker.js +93 -0
  175. package/dist/workers/usd.js +3 -0
  176. package/dist/xfile.d.ts +99 -0
  177. package/dist/xfile.js +706 -0
  178. package/dist/xml.d.ts +107 -0
  179. package/dist/xml.js +843 -0
  180. package/dist/xyz.d.ts +16 -0
  181. package/dist/xyz.js +110 -0
  182. package/dist/zip.d.ts +38 -0
  183. package/dist/zip.js +150 -0
  184. package/package.json +246 -6
@@ -0,0 +1,314 @@
1
+ // 3MF materials extension on top of parse3MF: texture2d, texture2dgroup, compositematerials and multiproperties.
2
+ import { LoaderError } from './types.js';
3
+ import { floats } from './util.js';
4
+ import { SRGBToLinear, LinearToSRGB } from '@margoengine/math/color';
5
+ import { cornerProperty, read3MF, } from './threemf.js';
6
+ const F = '3MF';
7
+ function list(value, what) {
8
+ const parts = (value ?? '').trim().split(/\s+/).map(Number);
9
+ if (!value?.trim() || !parts.every(Number.isFinite))
10
+ throw new LoaderError(F, 'syntax', `invalid ${what} "${String(value).slice(0, 64)}"`);
11
+ return parts;
12
+ }
13
+ function required(value, element, attribute) {
14
+ if (!value)
15
+ throw new LoaderError(F, 'syntax', `<${element}> without ${attribute}`);
16
+ return value;
17
+ }
18
+ /**
19
+ * Reads a 3MF package like `parse3MF` and adds the materials extension: `texture2d` images, `texture2dgroup`
20
+ * coordinates, `compositematerials` as mixed colours, and `multiproperties` layers. Every triangle corner gets its own
21
+ * vertex, so `uvs` and `colors` can differ across a seam; `uvs` use Margo's convention, v = 1 - the file's v. `colors` is
22
+ * present when corners of a triangle differ or a layer sets them. A group's `texture` indexes `textures`. In
23
+ * `multiproperties` colour layers mix by their alpha, and the first texture layer sets the group's texture: draw
24
+ * `colors` as a tint over it.
25
+ *
26
+ * @param input The package's bytes.
27
+ * @param options The same options as `parse3MF`.
28
+ * @returns The merged mesh with its coordinates, colours and images.
29
+ * @throws LoaderError with the codes of `parse3MF`, with `range` for a property index outside its group.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * import { parse3MFMaterials } from '@margoengine/loaders/threemf-materials';
34
+ *
35
+ * const bytes = await (await fetch('/prints/lithophane.3mf')).arrayBuffer();
36
+ * const { groups, textures, uvs } = await parse3MFMaterials(bytes);
37
+ * const image = await createImageBitmap(new Blob([textures[groups[0].texture ?? 0].data]));
38
+ * console.log(image.width, uvs?.length);
39
+ * ```
40
+ */
41
+ export function parse3MFMaterials(input, options = {}) {
42
+ return read3MFMaterials(input, options);
43
+ }
44
+ /** Shared materials reader with optional additional format hooks, used by the lattice/slice entry. */
45
+ export async function read3MFMaterials(input, options, extra) {
46
+ const stores = new Map(), textures = [], uvs = floats(), colors = floats(), opacity = floats(),
47
+ /** Each layer attribute's values by vertex, written at each corner. */
48
+ layerData = new Map();
49
+ let group, multi, composite, textured = false, varied = false, translucent = false;
50
+ const store = (model) => {
51
+ let found = stores.get(model);
52
+ if (!found)
53
+ stores.set(model, (found = { textures: new Map(), groups: new Map(), multis: new Map(), materials: new Set() }));
54
+ return found;
55
+ };
56
+ /** What one corner samples: a texture and uv, a colour, or both through layers. */
57
+ const sample = (model, id, index, layered) => {
58
+ const { groups, multis, textures: known } = store(model), coords = groups.get(id);
59
+ if (coords) {
60
+ if ((index + 1) * 2 > coords.coords.length)
61
+ throw new LoaderError(F, 'range', `property index ${index} is outside texture group ${id.slice(0, 32)}`);
62
+ const texture = known.get(coords.texture);
63
+ if (texture === undefined)
64
+ throw new LoaderError(F, 'syntax', `texture ${coords.texture.slice(0, 32)} is not defined`);
65
+ return { texture, u: coords.coords[index * 2], v: 1 - coords.coords[index * 2 + 1] };
66
+ }
67
+ const layers = layered ? undefined : multis.get(id);
68
+ if (layers) {
69
+ const row = layers.rows[index];
70
+ if (!row)
71
+ throw new LoaderError(F, 'range', `property index ${index} is outside multiproperties ${id.slice(0, 32)}`);
72
+ const out = {};
73
+ layers.pids.forEach((pid, layer) => {
74
+ const { color, ...image } = sample(model, pid, row[layer] ?? 0, true);
75
+ if (image.texture !== undefined && out.texture === undefined)
76
+ Object.assign(out, image);
77
+ if (color) {
78
+ const under = out.color, a = color[3];
79
+ if (under) {
80
+ const multiply = layers.blends[layer - 1] === 'multiply';
81
+ out.color = [0, 1, 2].map((c) => LinearToSRGB(multiply
82
+ ? SRGBToLinear(color[c]) * SRGBToLinear(under[c])
83
+ : SRGBToLinear(color[c]) * a + SRGBToLinear(under[c]) * (1 - a)));
84
+ out.color[3] = multiply ? a * under[3] : a + under[3] * (1 - a);
85
+ }
86
+ else
87
+ out.color = [...color];
88
+ }
89
+ });
90
+ return out;
91
+ }
92
+ const colorsOf = model.properties.get(id);
93
+ if (!colorsOf)
94
+ return {};
95
+ if (index >= colorsOf.length)
96
+ throw new LoaderError(F, 'range', `property index ${index} is outside property group ${id.slice(0, 32)}`);
97
+ return { color: colorsOf[index] };
98
+ };
99
+ const at = (model, ...where) => {
100
+ const property = cornerProperty(...where);
101
+ return property ? sample(model, property.id, property.index, false) : {};
102
+ };
103
+ const extension = {
104
+ element(model, name, a) {
105
+ if (name === 'basematerials' && a.id)
106
+ store(model).materials.add(a.id);
107
+ },
108
+ open(model, name, a) {
109
+ switch (name) {
110
+ case 'texture2d': {
111
+ const id = required(a.id, name, 'id');
112
+ store(model).textures.set(id, textures.length);
113
+ textures.push({
114
+ path: required(a.path, name, 'path'),
115
+ contentType: a.contenttype ?? '',
116
+ data: new Uint8Array(0),
117
+ tileStyleU: a.tilestyleu ?? 'wrap',
118
+ tileStyleV: a.tilestylev ?? 'wrap',
119
+ filter: a.filter ?? 'auto',
120
+ });
121
+ break;
122
+ }
123
+ case 'texture2dgroup': {
124
+ const id = required(a.id, name, 'id');
125
+ group = { texture: required(a.texid, name, 'texid'), coords: [] };
126
+ store(model).groups.set(id, group);
127
+ model.propertyIds.push(id);
128
+ break;
129
+ }
130
+ case 'tex2coord': {
131
+ const u = Number(a.u), v = Number(a.v);
132
+ if (!Number.isFinite(u) || !Number.isFinite(v))
133
+ throw new LoaderError(F, 'syntax', `invalid texture coordinate "${a.u}, ${a.v}"`);
134
+ group?.coords.push(u, v);
135
+ break;
136
+ }
137
+ case 'multiproperties': {
138
+ const id = required(a.id, name, 'id');
139
+ const pids = required(a.pids, name, 'pids').trim().split(/\s+/), blends = a.blendmethods?.trim().split(/\s+/) ?? [];
140
+ if (blends.length >= pids.length || blends.some((b) => b !== 'mix' && b !== 'multiply'))
141
+ throw new LoaderError(F, 'range', 'blendmethods must contain mix/multiply for at most layers minus one');
142
+ const { groups, multis, materials } = store(model), kinds = pids.map((pid, k) => {
143
+ if (groups.has(pid))
144
+ return 'texture';
145
+ if (multis.has(pid))
146
+ throw new LoaderError(F, 'syntax', 'a multiproperties must not name a multiproperties');
147
+ if (!model.properties.has(pid))
148
+ throw new LoaderError(F, 'syntax', `property group ${pid.slice(0, 32)} is not defined`);
149
+ if (materials.has(pid) && k)
150
+ throw new LoaderError(F, 'syntax', 'a multiproperties names one material group at most, first');
151
+ return 'color';
152
+ });
153
+ if (kinds.filter((kind, k) => kind === 'color' && !materials.has(pids[k])).length > 1)
154
+ throw new LoaderError(F, 'syntax', 'a multiproperties names one colour group at most');
155
+ multi = { pids, rows: [], blends, kinds };
156
+ store(model).multis.set(id, multi);
157
+ model.propertyIds.push(id);
158
+ break;
159
+ }
160
+ case 'multi':
161
+ multi?.rows.push(list(a.pindices, 'pindices'));
162
+ break;
163
+ case 'compositematerials': {
164
+ const id = required(a.id, name, 'id'), base = model.properties.get(required(a.matid, name, 'matid'));
165
+ if (!base)
166
+ throw new LoaderError(F, 'syntax', `material group ${a.matid.slice(0, 32)} is not defined`);
167
+ composite = { base, indices: list(a.matindices, 'matindices'), colors: [] };
168
+ store(model).materials.add(id);
169
+ model.properties.set(id, composite.colors);
170
+ model.propertyIds.push(id);
171
+ break;
172
+ }
173
+ case 'composite': {
174
+ if (!composite)
175
+ break;
176
+ const { base, indices } = composite, values = list(a.values, 'values'), mixed = [0, 0, 0, 0];
177
+ let total = 0;
178
+ indices.forEach((index, i) => {
179
+ const weight = values[i] ?? 0, color = base[index];
180
+ if (weight < 0)
181
+ throw new LoaderError(F, 'range', 'composite weights must be nonnegative');
182
+ if (!color)
183
+ throw new LoaderError(F, 'range', `matindices entry ${index} is outside its material group`);
184
+ total += weight;
185
+ for (let c = 0; c < 4; c++)
186
+ mixed[c] += (c < 3 ? SRGBToLinear(color[c]) : color[c]) * weight;
187
+ });
188
+ if (total === 0) {
189
+ for (const index of indices)
190
+ for (let c = 0; c < 4; c++)
191
+ mixed[c] += c < 3 ? SRGBToLinear(base[index][c]) : base[index][c];
192
+ total = indices.length;
193
+ }
194
+ composite.colors.push(mixed.map((value, c) => (c < 3 ? LinearToSRGB(value / total) : value / total)));
195
+ break;
196
+ }
197
+ }
198
+ },
199
+ close(_, name) {
200
+ if (name === 'texture2dgroup')
201
+ group = undefined;
202
+ else if (name === 'multiproperties')
203
+ multi = undefined;
204
+ else if (name === 'compositematerials')
205
+ composite = undefined;
206
+ },
207
+ async ready(read) {
208
+ for (const texture of textures)
209
+ texture.data = await read(texture.path);
210
+ },
211
+ bucket(model, object, mesh, t) {
212
+ const property = cornerProperty(model, object, mesh, t, 0), layered = property && store(model).multis.has(property.id) ? `|m${property.id}` : '';
213
+ return String(at(model, model, object, mesh, t, 0).texture ?? '') + layered;
214
+ },
215
+ corner(model, object, mesh, t, k) {
216
+ const property = cornerProperty(model, object, mesh, t, k), layers = property && store(model).multis.get(property.id);
217
+ if (layers) {
218
+ const vertex = uvs.length / 2, row = layers.rows[property.index];
219
+ if (!row)
220
+ throw new LoaderError(F, 'range', `property index ${property.index} is outside multiproperties ${property.id.slice(0, 32)}`);
221
+ layers.pids.forEach((pid, layer) => {
222
+ // A pindex the row leaves out is 0 (spec 5.1).
223
+ const { color, u, v } = sample(model, pid, row[layer] ?? 0, true), name = `layer${color ? 'Color' : 'UV'}${layer}`;
224
+ let data = layerData.get(name);
225
+ if (!data)
226
+ layerData.set(name, (data = { size: color ? 4 : 2, values: new Map() }));
227
+ data.values.set(vertex, color ? [...color] : [u ?? 0, v ?? 0]);
228
+ });
229
+ }
230
+ const { texture, u, v, color } = at(model, model, object, mesh, t, k);
231
+ if (texture !== undefined)
232
+ textured = true;
233
+ uvs.push(u ?? 0);
234
+ uvs.push(v ?? 0);
235
+ const [r, g, b] = color ?? [1, 1, 1];
236
+ colors.push3(r, g, b);
237
+ const alpha = color?.[3] ?? 1;
238
+ opacity.push(alpha);
239
+ if (alpha !== 1)
240
+ translucent = true;
241
+ if (!varied) {
242
+ const first = at(model, model, object, mesh, t, 0).color;
243
+ varied = color !== first || (store(model).multis.size > 0 && color !== undefined);
244
+ }
245
+ },
246
+ group(target, model, object, mesh, t) {
247
+ const { texture } = at(model, model, object, mesh, t, 0);
248
+ if (texture !== undefined)
249
+ target.texture = texture;
250
+ const property = cornerProperty(model, object, mesh, t, 0), { multis, groups, textures: known } = store(model), layers = property && multis.get(property.id);
251
+ if (layers)
252
+ target.layers = layers.pids.map((pid, k) => {
253
+ const kind = layers.kinds[k];
254
+ return {
255
+ kind,
256
+ ...(kind === 'texture' ? { texture: known.get(groups.get(pid).texture) } : {}),
257
+ attribute: `layer${kind === 'texture' ? 'UV' : 'Color'}${k}`,
258
+ blend: k && layers.blends[k - 1] === 'multiply' ? 'multiply' : 'mix',
259
+ };
260
+ });
261
+ },
262
+ };
263
+ const hooks = extra
264
+ ? {
265
+ element(model, name, a) {
266
+ extension.element?.(model, name, a);
267
+ return extra.element?.(model, name, a);
268
+ },
269
+ instance: extra.instance,
270
+ hasGeometry: extra.hasGeometry,
271
+ open(model, name, a) {
272
+ extension.open?.(model, name, a);
273
+ extra.open?.(model, name, a);
274
+ },
275
+ close(model, name) {
276
+ extension.close?.(model, name);
277
+ extra.close?.(model, name);
278
+ },
279
+ async ready(read, context) {
280
+ await extra.ready?.(read, context);
281
+ await extension.ready?.(read, context);
282
+ },
283
+ bucket(model, object, mesh, t) {
284
+ return extension.bucket(model, object, mesh, t) + '|' + extra.bucket(model, object, mesh, t);
285
+ },
286
+ corner(model, object, mesh, t, k) {
287
+ extension.corner(model, object, mesh, t, k);
288
+ extra.corner(model, object, mesh, t, k);
289
+ },
290
+ group(group, model, object, mesh, t) {
291
+ extension.group(group, model, object, mesh, t);
292
+ extra.group(group, model, object, mesh, t);
293
+ },
294
+ }
295
+ : extension;
296
+ const result = (await read3MF(input, options, hooks));
297
+ result.textures = textures;
298
+ if (textured)
299
+ result.uvs = uvs.result();
300
+ if (varied)
301
+ result.colors = colors.result();
302
+ else
303
+ delete result.colors;
304
+ if (translucent)
305
+ result.attributes = { ...result.attributes, opacity: opacity.result() };
306
+ const vertices = result.positions.length / 3;
307
+ for (const [name, { size, values }] of layerData) {
308
+ const out = new Float32Array(vertices * size);
309
+ for (const [vertex, value] of values)
310
+ out.set(value, vertex * size);
311
+ result.attributes = { ...result.attributes, [name]: out };
312
+ }
313
+ return result;
314
+ }
@@ -0,0 +1,60 @@
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 area-weighted normal where corners meet at the same position, as `parse3MF` and
9
+ * `createMeshes` shade; `'flat'` gives every triangle its face normal.
10
+ */
11
+ normals?: 'smooth' | 'flat';
12
+ /** Every material's roughness, 0 to 1. Default 0.6. */
13
+ roughness?: number;
14
+ /** Every material's metalness, 0 to 1. Default 0. */
15
+ metalness?: number;
16
+ /** Draw both faces. Default true: printed parts are often open or inside out. */
17
+ doubleSided?: boolean;
18
+ /** Draw the colours as they are, without light (`shading: 'basic'`). Default false. */
19
+ unlit?: boolean;
20
+ /** Draw order of the mesh. Default 0. */
21
+ renderOrder?: number;
22
+ /** Stops the image decoding; the promise then rejects with a `LoaderError` code `aborted`. */
23
+ signal?: AbortSignal;
24
+ }
25
+ /** What {@link create3MFMesh} made. The textures and materials are its own: `dispose()` releases them with the mesh. */
26
+ export interface ThreeMFMesh {
27
+ mesh: MaterialMesh<Material[]>;
28
+ /** One per group, in `groups` order, empty groups left out. */
29
+ materials: Material[];
30
+ /** The decoded textures, by their index in `textures`. */
31
+ textures: Map<number, Texture>;
32
+ dispose(): void;
33
+ [Symbol.dispose](): void;
34
+ }
35
+ /**
36
+ * Draws a `parse3MFMaterials` result as one materials mesh with a material per group: colour groups, composites and
37
+ * per-corner colours as vertex colours, a texture group's image as the colour map, and a `multiproperties` stack as its
38
+ * layers (`layered()`), blended as the 3MF Materials and Properties Extension 1.2.1 specifies (mix and multiply, in
39
+ * linear light). Images decode with `createImageBitmap`.
40
+ *
41
+ * @param engine The engine to draw in.
42
+ * @param loaded What `parse3MFMaterials` returned.
43
+ * @param options Normals, surface numbers, draw order and an abort signal.
44
+ * @returns The mesh, its materials and textures, and `dispose()`.
45
+ * @throws LoaderError `unsupported` for a stack needing more than two UV sets or a varying colour above a texture
46
+ * layer, `range` for a group naming a missing texture or layer attribute, `aborted` when the signal fires.
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * import { Engine } from '@margoengine/core';
51
+ * import { parse3MFMaterials } from '@margoengine/loaders/threemf-materials';
52
+ * import { create3MFMesh } from '@margoengine/loaders/threemf-mesh';
53
+ *
54
+ * const engine = await Engine.create(document.querySelector('canvas')!);
55
+ * const bytes = await (await fetch('/prints/multiprop-opaque.3mf')).arrayBuffer();
56
+ * using model = await create3MFMesh(engine, await parse3MFMaterials(bytes));
57
+ * console.log(model.materials.length, model.textures.size);
58
+ * ```
59
+ */
60
+ export declare function create3MFMesh(engine: EngineKernel, loaded: ThreeMFMaterials, options?: ThreeMFMeshOptions): Promise<ThreeMFMesh>;
@@ -0,0 +1,201 @@
1
+ import { Material, Texture, createMesh } from '@margoengine/materials';
2
+ import { layered } from '@margoengine/materials/layered';
3
+ import { SRGBToLinear } from '@margoengine/math/color';
4
+ import { computeVertexNormals } from './normals.js';
5
+ import { LoaderError } from './types.js';
6
+ import { throwIfAborted } from './util.js';
7
+ const F = '3MF';
8
+ const wrap = (style) => style === 'mirror' ? 'mirror' : style === 'clamp' || style === 'none' ? 'clamp' : 'repeat';
9
+ async function decode(texture, signal) {
10
+ // Pixels as stored: the spec reads colour as sRGB and alpha as linear, unpremultiplied.
11
+ const image = await createImageBitmap(new Blob([texture.data.slice()], { type: texture.contentType }), {
12
+ colorSpaceConversion: 'none',
13
+ premultiplyAlpha: 'none',
14
+ });
15
+ throwIfAborted(signal, F);
16
+ const nearest = texture.filter === 'nearest', filter = nearest ? 'nearest' : 'linear';
17
+ return new Texture(image, {
18
+ wrapS: wrap(texture.tileStyleU),
19
+ wrapT: wrap(texture.tileStyleV),
20
+ minFilter: filter,
21
+ magFilter: filter,
22
+ mipmaps: !nearest,
23
+ });
24
+ }
25
+ function smoothIndices(positions) {
26
+ const first = new Map(), out = new Uint32Array(positions.length / 3);
27
+ for (let v = 0; v < out.length; v++) {
28
+ const key = `${positions[v * 3]},${positions[v * 3 + 1]},${positions[v * 3 + 2]}`;
29
+ let at = first.get(key);
30
+ if (at === undefined)
31
+ first.set(key, (at = v));
32
+ out[v] = at;
33
+ }
34
+ return out;
35
+ }
36
+ /**
37
+ * Turns one group's stack into the colour each vertex starts with and the `layered()` layers over it. The colour
38
+ * layers below the first texture layer are blended per corner, in linear light as the spec says, into the vertex
39
+ * colour; the first layer is opaque. Every layer from the first texture up becomes a material layer: a texture mixes by
40
+ * its own alpha (the bottom one covers), a colour layer needs one colour across the group. Texture layers share UV0
41
+ * and UV1 by their coordinates.
42
+ */
43
+ function stack(loaded, group, layers, vertices, textures, colors, uvs) {
44
+ const data = (layer) => {
45
+ const values = loaded.attributes?.[layer.attribute];
46
+ if (!values)
47
+ throw new LoaderError(F, 'range', `layer attribute ${layer.attribute} is missing from attributes`);
48
+ return values;
49
+ };
50
+ const top = layers.findIndex((layer) => layer.kind === 'texture'), folded = top < 0 ? layers.length : top;
51
+ for (const v of vertices) {
52
+ const out = [1, 1, 1, 1];
53
+ for (let k = 0; k < folded; k++) {
54
+ const c = data(layers[k]).subarray(v * 4, v * 4 + 4), rgb = [0, 1, 2].map((i) => SRGBToLinear(c[i])), a = c[3];
55
+ if (!k)
56
+ out.splice(0, 4, ...rgb, 1);
57
+ else if (layers[k].blend === 'multiply')
58
+ out.splice(0, 4, ...rgb.map((x, i) => x * out[i]), a * out[3]);
59
+ else
60
+ out.splice(0, 4, ...rgb.map((x, i) => x * a + out[i] * (1 - a)), a + out[3] * (1 - a));
61
+ }
62
+ colors.set(out, v * 4);
63
+ }
64
+ const slots = [], same = (a, b) => [...vertices].every((v) => a[v * 2] === b[v * 2] && a[v * 2 + 1] === b[v * 2 + 1]);
65
+ const out = [];
66
+ for (let k = folded; k < layers.length; k++) {
67
+ const layer = layers[k], values = data(layer), multiply = layer.blend === 'multiply';
68
+ if (layer.kind === 'color') {
69
+ const c = values.subarray(vertices[0] * 4, vertices[0] * 4 + 4);
70
+ if (![...vertices].every((v) => [0, 1, 2, 3].every((i) => values[v * 4 + i] === c[i])))
71
+ throw new LoaderError(F, 'unsupported', `group ${group.name ?? group.objectId ?? ''}: a colour layer above a texture layer must hold one colour across the group`);
72
+ const color = [0, 1, 2].map((i) => SRGBToLinear(c[i]));
73
+ out.push(multiply ? { color, blend: 'multiply' } : { color, opacity: c[3] });
74
+ continue;
75
+ }
76
+ let slot = slots.findIndex((uv) => uv === values || same(uv, values));
77
+ if (slot < 0)
78
+ slot = slots.push(values) - 1;
79
+ if (slot > 1)
80
+ throw new LoaderError(F, 'unsupported', 'a layer stack uses more than two sets of texture coordinates (UV0, UV1)');
81
+ for (const v of vertices)
82
+ uvs[slot].set([values[v * 2], 1 - values[v * 2 + 1]], v * 2);
83
+ const map = textures.get(layer.texture), texCoord = slot;
84
+ // The bottom layer starts the stack opaque; a mix layer above covers by its alpha; multiply scales by it.
85
+ out.push(k === 0
86
+ ? { map, texCoord }
87
+ : multiply
88
+ ? { map, texCoord, blend: 'multiply' }
89
+ : { map, texCoord, mask: map, maskChannel: 'a' });
90
+ }
91
+ return out;
92
+ }
93
+ /**
94
+ * Draws a `parse3MFMaterials` result as one materials mesh with a material per group: colour groups, composites and
95
+ * per-corner colours as vertex colours, a texture group's image as the colour map, and a `multiproperties` stack as its
96
+ * layers (`layered()`), blended as the 3MF Materials and Properties Extension 1.2.1 specifies (mix and multiply, in
97
+ * linear light). Images decode with `createImageBitmap`.
98
+ *
99
+ * @param engine The engine to draw in.
100
+ * @param loaded What `parse3MFMaterials` returned.
101
+ * @param options Normals, surface numbers, draw order and an abort signal.
102
+ * @returns The mesh, its materials and textures, and `dispose()`.
103
+ * @throws LoaderError `unsupported` for a stack needing more than two UV sets or a varying colour above a texture
104
+ * layer, `range` for a group naming a missing texture or layer attribute, `aborted` when the signal fires.
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * import { Engine } from '@margoengine/core';
109
+ * import { parse3MFMaterials } from '@margoengine/loaders/threemf-materials';
110
+ * import { create3MFMesh } from '@margoengine/loaders/threemf-mesh';
111
+ *
112
+ * const engine = await Engine.create(document.querySelector('canvas')!);
113
+ * const bytes = await (await fetch('/prints/multiprop-opaque.3mf')).arrayBuffer();
114
+ * using model = await create3MFMesh(engine, await parse3MFMaterials(bytes));
115
+ * console.log(model.materials.length, model.textures.size);
116
+ * ```
117
+ */
118
+ export async function create3MFMesh(engine, loaded, options = {}) {
119
+ const { positions, indices, groups = [] } = loaded, { signal } = options;
120
+ if (loaded.kind !== 'mesh' || !indices?.length)
121
+ throw new LoaderError(F, 'unsupported', 'create3MFMesh needs triangles; pass parse3MFMaterials output');
122
+ const mode = options.normals ?? 'smooth';
123
+ if (mode !== 'smooth' && mode !== 'flat')
124
+ throw new LoaderError(F, 'range', 'normals must be smooth or flat');
125
+ const count = positions.length / 3, used = new Set();
126
+ for (const group of groups) {
127
+ if (group.texture !== undefined)
128
+ used.add(group.texture);
129
+ for (const layer of group.layers ?? [])
130
+ if (layer.texture !== undefined)
131
+ used.add(layer.texture);
132
+ }
133
+ const textures = new Map(), materials = [];
134
+ const release = () => {
135
+ for (const material of materials)
136
+ material.dispose();
137
+ for (const texture of textures.values())
138
+ texture.dispose();
139
+ };
140
+ try {
141
+ for (const k of used) {
142
+ throwIfAborted(signal, F);
143
+ const source = loaded.textures[k];
144
+ if (!source)
145
+ throw new LoaderError(F, 'range', `a group names texture ${k}, outside textures`);
146
+ textures.set(k, await decode(source, signal));
147
+ }
148
+ const colors = new Float32Array(count * 4).fill(1), uvs = [new Float32Array(count * 2), new Float32Array(count * 2)], geometryGroups = [];
149
+ for (const group of groups) {
150
+ if (!group.count)
151
+ continue;
152
+ const vertices = indices.subarray(group.start, group.start + group.count);
153
+ let features = [], map;
154
+ if (group.layers?.length)
155
+ features = stack(loaded, group, group.layers, vertices, textures, colors, uvs);
156
+ else {
157
+ const { colors: rgb, uvs: uv } = loaded, alpha = loaded.attributes?.opacity;
158
+ for (const v of vertices) {
159
+ for (let c = 0; c < 3; c++)
160
+ colors[v * 4 + c] = SRGBToLinear(rgb?.[v * 3 + c] ?? group.color?.[c] ?? 1);
161
+ colors[v * 4 + 3] = alpha?.[v] ?? group.color?.[3] ?? 1;
162
+ if (uv)
163
+ uvs[0].set([uv[v * 2], 1 - uv[v * 2 + 1]], v * 2);
164
+ }
165
+ if (group.texture !== undefined)
166
+ map = textures.get(group.texture);
167
+ }
168
+ const transparent = [...vertices].some((v) => colors[v * 4 + 3] < 1);
169
+ geometryGroups.push({ start: group.start, count: group.count, materialIndex: materials.length });
170
+ materials.push(new Material({
171
+ ...(map ? { map } : {}),
172
+ ...(options.unlit ? { shading: 'basic' } : {}),
173
+ roughness: options.roughness ?? 0.6,
174
+ metalness: options.metalness ?? 0,
175
+ doubleSided: options.doubleSided ?? true,
176
+ transparent,
177
+ features: features.length ? [layered({ layers: features })] : [],
178
+ }));
179
+ }
180
+ if (!materials.length)
181
+ throw new LoaderError(F, 'unsupported', 'the result has no nonempty groups to draw');
182
+ const normals = mode === 'flat'
183
+ ? computeVertexNormals(positions, indices)
184
+ : (() => {
185
+ const shared = smoothIndices(positions), welded = computeVertexNormals(positions, indices.map((v) => shared[v])), out = new Float32Array(count * 3);
186
+ for (let v = 0; v < count; v++)
187
+ out.set(welded.subarray(shared[v] * 3, shared[v] * 3 + 3), v * 3);
188
+ return out;
189
+ })();
190
+ const mesh = createMesh(engine, { positions, normals, indices, uvs: uvs[0], uvs1: uvs[1], colors, groups: geometryGroups }, materials, { renderOrder: options.renderOrder ?? 0 });
191
+ const dispose = () => {
192
+ mesh.destroy();
193
+ release();
194
+ };
195
+ return { mesh, materials, textures, dispose, [Symbol.dispose]: dispose };
196
+ }
197
+ catch (error) {
198
+ release();
199
+ throw error;
200
+ }
201
+ }