@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
package/dist/dae.js ADDED
@@ -0,0 +1,644 @@
1
+ import { LoaderError } from './types.js';
2
+ import { CornerWelder, DEFAULT_MAX_TRIANGLES, DEFAULT_MAX_VERTICES, floats, limits, resolvePath, toBytes, uints, } from './util.js';
3
+ import { decodeXML, readXMLTree } from './xml.js';
4
+ import { AXES, converter, F, IDENTITY, integer, kid, kids, lookatMatrix, multiply, numbers, readSource, ref, skewMatrix, stackMatrix, TRANSFORM_SIZES, } from './dae-common.js';
5
+ import { readControllers } from './dae-controllers.js';
6
+ import { readAnimations } from './dae-animation.js';
7
+ import { deformInstance, restPose } from './dae-pose.js';
8
+ import { placeScene } from './dae-scene.js';
9
+ const NONE = 0xffffffff;
10
+ // The per-file part cap shared by every loader that makes one mesh per part (docs/limits.md).
11
+ const MAX_NODES = 100_000;
12
+ const MAX_DEPTH = 64;
13
+ function readMesh(geometry, mesh, ids, limit, totals, warn) {
14
+ const id = geometry.attributes.id ?? '', what = `geometry "${id}"`;
15
+ const sources = new Map();
16
+ for (const e of kids(mesh, 'source'))
17
+ if (e.attributes.id)
18
+ sources.set(e.attributes.id, readSource(e, ids));
19
+ const source = (url, semantic) => {
20
+ const found = sources.get(ref(url));
21
+ if (!found)
22
+ throw new LoaderError(F, 'syntax', `${what} ${semantic} input names no source "${ref(url)}"`);
23
+ return found;
24
+ };
25
+ const vertices = kid(mesh, 'vertices');
26
+ if (!vertices)
27
+ throw new LoaderError(F, 'syntax', `${what} has no <vertices>`);
28
+ const vertexInputs = new Map(kids(vertices, 'input').map((i) => [i.attributes.semantic, i.attributes.source]));
29
+ if (!vertexInputs.has('POSITION'))
30
+ throw new LoaderError(F, 'syntax', `${what} <vertices> has no POSITION input`);
31
+ const positionSource = source(vertexInputs.get('POSITION'), 'POSITION'), vertexCount = positionSource.count;
32
+ if (positionSource.params.length < 3)
33
+ throw new LoaderError(F, 'syntax', `${what} POSITION source "${positionSource.id}" has fewer than 3 components`);
34
+ const positions = floats(), normals = floats(), uvs = floats(), colors = floats(), positionIndices = uints(), indices = uints(), faceSizes = uints(), lineIndices = uints(), linePositions = floats(), lineColors = floats(), linePositionIndices = uints(), groups = [], lineGroups = [];
35
+ let hasNormal = false, hasUV = false, hasColor = false, hasLineColor = false;
36
+ for (const primitive of mesh.children) {
37
+ const type = primitive.name;
38
+ const isLines = type === 'lines' || type === 'linestrips';
39
+ if (!isLines &&
40
+ type !== 'triangles' &&
41
+ type !== 'polylist' &&
42
+ type !== 'polygons' &&
43
+ type !== 'trifans' &&
44
+ type !== 'tristrips')
45
+ continue;
46
+ const inputs = kids(primitive, 'input'), stride = Math.max(0, ...inputs.map((i) => integer(i.attributes.offset, 0, `${what} input offset`) + 1));
47
+ const find = (semantic) => {
48
+ const matches = inputs.filter((i) => i.attributes.semantic === semantic);
49
+ matches.sort((a, b) => integer(a.attributes.set, 0, 'set') - integer(b.attributes.set, 0, 'set'));
50
+ const input = matches[0];
51
+ return (input && {
52
+ source: source(input.attributes.source, semantic),
53
+ offset: integer(input.attributes.offset, 0, `${what} input offset`),
54
+ });
55
+ };
56
+ const vertexInput = inputs.find((i) => i.attributes.semantic === 'VERTEX');
57
+ if (!vertexInput)
58
+ throw new LoaderError(F, 'syntax', `${what} <${type}> has no VERTEX input`);
59
+ const vertexOffset = integer(vertexInput.attributes.offset, 0, `${what} input offset`);
60
+ // An attribute the primitive lacks may come from <vertices>, indexed like the vertex.
61
+ const shared = (semantic) => find(semantic) ??
62
+ (vertexInputs.has(semantic)
63
+ ? { source: source(vertexInputs.get(semantic), semantic), offset: vertexOffset }
64
+ : undefined);
65
+ const normal = shared('NORMAL'), texcoord = shared('TEXCOORD'), color = shared('COLOR');
66
+ // Line primitives keep vertices of their own, so their inputs say nothing of the triangles'.
67
+ hasNormal ||= !isLines && !!normal;
68
+ hasUV ||= !isLines && !!texcoord;
69
+ hasColor ||= !isLines && !!color;
70
+ const welder = new CornerWelder(vertexCount), base = positions.length / 3, start = indices.length;
71
+ let p = [];
72
+ const at = (input, corner, what2) => {
73
+ if (!input)
74
+ return NONE;
75
+ const index = p[corner * stride + input.offset], count = input.source.count;
76
+ if (!(Number.isInteger(index) && index >= 0 && index < count))
77
+ throw new LoaderError(F, 'range', `${what} ${what2} index ${index} is outside 0..${count - 1}`);
78
+ return index;
79
+ };
80
+ const read = (input, index, component) => {
81
+ const s = input.source;
82
+ return component < s.params.length ? s.data[s.offset + index * s.stride + s.params[component]] : 1;
83
+ };
84
+ const position = { source: positionSource, offset: vertexOffset };
85
+ const corner = (c) => {
86
+ const v = at(position, c, 'vertex'), n = at(normal, c, 'normal'), t = at(texcoord, c, 'texcoord'), k = at(color, c, 'color'), before = welder.count, out = welder.weld(v, n, t, k);
87
+ if (out === before) {
88
+ if (++totals.vertices > limit.maxVertices)
89
+ throw new LoaderError(F, 'limit', `vertex count exceeds the limit of ${limit.maxVertices}`);
90
+ positions.push3(read(position, v, 0), read(position, v, 1), read(position, v, 2));
91
+ if (normal)
92
+ normals.push3(read(normal, n, 0), read(normal, n, 1), read(normal, n, 2));
93
+ else
94
+ normals.push3(0, 0, 0);
95
+ uvs.push(texcoord ? read(texcoord, t, 0) : 0);
96
+ uvs.push(texcoord && texcoord.source.params.length > 1 ? 1 - read(texcoord, t, 1) : 0);
97
+ if (color)
98
+ colors.push3(read(color, k, 0), read(color, k, 1), read(color, k, 2));
99
+ else
100
+ colors.push3(1, 1, 1);
101
+ positionIndices.push(v);
102
+ }
103
+ return base + out;
104
+ };
105
+ // Corners of one polygon in order, triangulated as a fan.
106
+ const polygon = (first, size) => {
107
+ if (size < 3)
108
+ throw new LoaderError(F, 'syntax', `${what} <${type}> has a polygon with ${size} corners`);
109
+ if ((totals.triangles += size - 2) > limit.maxTriangles)
110
+ throw new LoaderError(F, 'limit', `triangle count exceeds the limit of ${limit.maxTriangles}`);
111
+ const c0 = corner(first);
112
+ let previous = corner(first + 1);
113
+ for (let k = 2; k < size; k++) {
114
+ const current = corner(first + k);
115
+ indices.push3(c0, previous, current);
116
+ previous = current;
117
+ }
118
+ faceSizes.push(size);
119
+ };
120
+ const values = (e, label) => e ? numbers(e.text, `${what} <${label}>`) : [];
121
+ const corners = (list, label) => {
122
+ if (!stride || list.length % stride)
123
+ throw new LoaderError(F, 'syntax', `${what} <${label}> holds ${list.length} indices, not a multiple of ${stride}`);
124
+ return list.length / stride;
125
+ };
126
+ if (isLines) {
127
+ // COLLADA 1.4.1 `<lines>`: one <p> of corner pairs; `<linestrips>`: one <p> per strip of two or more corners.
128
+ const lineStart = lineIndices.length, lineWelder = new CornerWelder(vertexCount), lineBase = linePositions.length / 3;
129
+ const lineCorner = (c) => {
130
+ const v = at(position, c, 'vertex'), k = at(color, c, 'color'), before = lineWelder.count, out = lineWelder.weld(v, k, NONE, NONE);
131
+ if (out === before) {
132
+ if (++totals.vertices > limit.maxVertices)
133
+ throw new LoaderError(F, 'limit', `vertex count exceeds the limit of ${limit.maxVertices}`);
134
+ linePositions.push3(read(position, v, 0), read(position, v, 1), read(position, v, 2));
135
+ if (color)
136
+ lineColors.push3(read(color, k, 0), read(color, k, 1), read(color, k, 2));
137
+ else
138
+ lineColors.push3(1, 1, 1);
139
+ linePositionIndices.push(v);
140
+ }
141
+ return lineBase + out;
142
+ };
143
+ hasLineColor ||= !!color;
144
+ for (const e of type === 'lines' ? [kid(primitive, 'p')] : kids(primitive, 'p')) {
145
+ if (!e)
146
+ continue;
147
+ p = values(e, 'p');
148
+ const total = corners(p, 'p');
149
+ if (type === 'lines' ? total % 2 : total < 2)
150
+ throw new LoaderError(F, 'syntax', `${what} <${type}> has ${total} corners in a <p>`);
151
+ for (let k = 0; k + 1 < total; k += type === 'lines' ? 2 : 1) {
152
+ lineIndices.push(lineCorner(k));
153
+ lineIndices.push(lineCorner(k + 1));
154
+ }
155
+ }
156
+ const group = { start: lineStart, count: lineIndices.length - lineStart };
157
+ if (primitive.attributes.material !== undefined)
158
+ group.symbol = primitive.attributes.material;
159
+ if (group.count)
160
+ lineGroups.push(group);
161
+ continue;
162
+ }
163
+ if (type === 'triangles' || type === 'polylist') {
164
+ p = values(kid(primitive, 'p'), 'p');
165
+ const total = corners(p, 'p');
166
+ if (type === 'triangles' && total % 3)
167
+ throw new LoaderError(F, 'syntax', `${what} <triangles> has ${total} corners, not a multiple of 3`);
168
+ const sizes = type === 'triangles' ? new Array(total / 3).fill(3) : values(kid(primitive, 'vcount'), 'vcount');
169
+ let first = 0;
170
+ for (const size of sizes) {
171
+ if (!Number.isSafeInteger(size) || first + size > total)
172
+ throw new LoaderError(F, 'syntax', `${what} <${type}> vcount does not match its <p> indices`);
173
+ polygon(first, size);
174
+ first += size;
175
+ }
176
+ if (first !== total)
177
+ throw new LoaderError(F, 'syntax', `${what} <${type}> vcount does not match its <p> indices`);
178
+ }
179
+ else
180
+ for (const e of primitive.children) {
181
+ if (e.name !== 'p' && e.name !== 'ph')
182
+ continue;
183
+ if (e.name === 'ph')
184
+ warn(`${what}: polygon holes (<ph><h>) are not imported; the outer polygon is kept`);
185
+ p = values(e.name === 'p' ? e : kid(e, 'p'), 'p');
186
+ const total = corners(p, 'p');
187
+ if (type !== 'tristrips')
188
+ polygon(0, total);
189
+ else
190
+ for (let k = 0; k + 2 < total; k++) {
191
+ if ((totals.triangles += 1) > limit.maxTriangles)
192
+ throw new LoaderError(F, 'limit', `triangle count exceeds the limit of ${limit.maxTriangles}`);
193
+ const a = corner(k), b = corner(k + 1), c = corner(k + 2);
194
+ if (k % 2)
195
+ indices.push3(b, a, c);
196
+ else
197
+ indices.push3(a, b, c);
198
+ faceSizes.push(3);
199
+ }
200
+ }
201
+ const group = { start, count: indices.length - start };
202
+ if (primitive.attributes.material !== undefined)
203
+ group.symbol = primitive.attributes.material;
204
+ if (group.count)
205
+ groups.push(group);
206
+ }
207
+ const result = {
208
+ kind: 'mesh',
209
+ id,
210
+ positions: positions.result(),
211
+ indices: indices.result(),
212
+ groups,
213
+ faceSizes: faceSizes.result(),
214
+ positionIndices: positionIndices.result(),
215
+ };
216
+ if (lineIndices.length) {
217
+ result.lines = {
218
+ positions: linePositions.result(),
219
+ positionIndices: linePositionIndices.result(),
220
+ indices: lineIndices.result(),
221
+ groups: lineGroups,
222
+ };
223
+ if (hasLineColor)
224
+ result.lines.colors = lineColors.result();
225
+ }
226
+ if (geometry.attributes.name !== undefined)
227
+ result.name = geometry.attributes.name;
228
+ if (hasNormal)
229
+ result.normals = normals.result();
230
+ if (hasUV)
231
+ result.uvs = uvs.result();
232
+ if (hasColor)
233
+ result.colors = colors.result();
234
+ return result;
235
+ }
236
+ /** An `<init_from>` URI as a path relative to the .dae folder (`file:///C:/a%20b.png` becomes `C:/a b.png`). */
237
+ function imagePath(uri) {
238
+ let path = uri.trim();
239
+ if (/^data:/i.test(path))
240
+ return path;
241
+ path = path.replace(/^file:(\/\/)?/i, '').replace(/^\/([a-z]:)/i, '$1');
242
+ try {
243
+ path = decodeURIComponent(path);
244
+ }
245
+ catch {
246
+ // Not percent-encoded: keep as written.
247
+ }
248
+ return resolvePath('', path);
249
+ }
250
+ const SHADINGS = ['constant', 'lambert', 'phong', 'blinn'];
251
+ const CHANNELS = ['emission', 'ambient', 'diffuse', 'specular', 'reflective', 'transparent'];
252
+ const SCALARS = [
253
+ ['shininess', 'shininess'],
254
+ ['reflectivity', 'reflectivity'],
255
+ ['transparency', 'transparency'],
256
+ ['index_of_refraction', 'indexOfRefraction'],
257
+ ];
258
+ function readMaterial(material, ids, images, warn) {
259
+ const id = material.attributes.id ?? '', effect = ids.get(ref(kid(material, 'instance_effect')?.attributes.url)), profile = kid(effect, 'profile_COMMON'), technique = kid(profile, 'technique'), shader = technique?.children.find((c) => SHADINGS.includes(c.name));
260
+ const result = { id, shading: shader?.name ?? 'lambert' };
261
+ if (material.attributes.name !== undefined)
262
+ result.name = material.attributes.name;
263
+ if (!effect)
264
+ warn(`material "${id}" names no effect`);
265
+ else if (!shader)
266
+ warn(`material "${id}": effect "${effect.attributes.id}" has no profile_COMMON shader`);
267
+ if (!shader)
268
+ return result;
269
+ const params = new Map();
270
+ for (const scope of [effect, profile, technique])
271
+ for (const p of kids(scope, 'newparam'))
272
+ if (p.attributes.sid)
273
+ params.set(p.attributes.sid, p);
274
+ const texturePath = (sid) => {
275
+ const sampler = kid(params.get(sid), 'sampler2D');
276
+ if (sampler) {
277
+ // 1.5: the sampler names the image; 1.4.1: sampler -> surface -> image id.
278
+ const instance = kid(sampler, 'instance_image');
279
+ if (instance)
280
+ return images.get(ref(instance.attributes.url));
281
+ const surface = kid(params.get(kid(sampler, 'source')?.text.trim() ?? ''), 'surface');
282
+ return images.get(kid(surface, 'init_from')?.text.trim() ?? '');
283
+ }
284
+ return images.get(sid); // some exporters name the image directly
285
+ };
286
+ for (const name of CHANNELS) {
287
+ const e = kid(shader, name);
288
+ if (!e)
289
+ continue;
290
+ const channel = {}, color = kid(e, 'color'), texture = kid(e, 'texture');
291
+ if (color) {
292
+ const v = numbers(color.text, `material "${id}" ${name} color`);
293
+ if (v.length !== 3 && v.length !== 4)
294
+ throw new LoaderError(F, 'syntax', `material "${id}" ${name} color has ${v.length} values; expected 3 or 4`);
295
+ channel.color = [v[0], v[1], v[2], v[3] ?? 1];
296
+ }
297
+ if (texture) {
298
+ const path = texturePath(texture.attributes.texture ?? '');
299
+ if (path === undefined)
300
+ warn(`material "${id}" ${name} texture "${texture.attributes.texture}" names no <image>`);
301
+ else {
302
+ channel.texture = { path };
303
+ if (texture.attributes.texcoord !== undefined)
304
+ channel.texture.texcoord = texture.attributes.texcoord;
305
+ }
306
+ }
307
+ if (channel.color || channel.texture)
308
+ result[name] = channel;
309
+ if (name === 'transparent' && e.attributes.opaque)
310
+ result.opaque = e.attributes.opaque;
311
+ }
312
+ for (const [name, key] of SCALARS) {
313
+ const value = kid(kid(shader, name), 'float');
314
+ if (value)
315
+ result[key] = numbers(value.text, `material "${id}" ${name}`)[0];
316
+ }
317
+ return result;
318
+ }
319
+ /** The node's transform stack as written, in document order (each element post-multiplies). */
320
+ function readTransforms(node, warn) {
321
+ const out = [];
322
+ for (const e of node.children) {
323
+ if (!Object.hasOwn(TRANSFORM_SIZES, e.name))
324
+ continue;
325
+ const type = e.name, count = TRANSFORM_SIZES[type], what = `node "${node.attributes.id ?? node.attributes.name ?? ''}" <${e.name}>`, values = numbers(e.text, what);
326
+ if (values.length !== count || !values.every(Number.isFinite))
327
+ throw new LoaderError(F, 'syntax', `${what} needs ${count} finite numbers, got ${values.length}`);
328
+ if (type === 'lookat' && !lookatMatrix(values))
329
+ warn(`${what} has its eye on the interest point or up along the view; only the eye is used: fix eye, interest or up`);
330
+ if (type === 'skew' && !skewMatrix(values))
331
+ warn(`${what} is skipped: give a nonzero translation axis, a rotation axis not parallel to it, and an angle that does not turn the rotation axis onto or past it`);
332
+ const transform = { type, values };
333
+ if (e.attributes.sid !== undefined)
334
+ transform.sid = e.attributes.sid;
335
+ out.push(transform);
336
+ }
337
+ return out;
338
+ }
339
+ function bindMaterials(instance, materialIndex, warn) {
340
+ const bound = Object.create(null);
341
+ for (const m of kids(kid(kid(instance, 'bind_material'), 'technique_common'), 'instance_material')) {
342
+ const material = materialIndex.get(ref(m.attributes.target));
343
+ if (material === undefined)
344
+ warn(`instance_material "${m.attributes.target}" names no <material>`);
345
+ else if (m.attributes.symbol !== undefined)
346
+ bound[m.attributes.symbol] = material;
347
+ }
348
+ return bound;
349
+ }
350
+ /** Depth-first search of node trees. */
351
+ function findNode(roots, match) {
352
+ for (const root of roots) {
353
+ if (match(root))
354
+ return root;
355
+ const found = findNode(root.children, match);
356
+ if (found)
357
+ return found;
358
+ }
359
+ return undefined;
360
+ }
361
+ /**
362
+ * Parses a COLLADA 1.4.1 or 1.5 document (`.dae`): mesh geometries (`<triangles>`, `<polylist>`, `<polygons>`,
363
+ * `<trifans>`, `<tristrips>` with VERTEX, POSITION, NORMAL, TEXCOORD and COLOR inputs), `profile_COMMON` materials
364
+ * (constant, lambert, phong, blinn; colors and textures through sampler and surface params), images, and the
365
+ * instanced visual scene with matrix/translate/rotate/scale stacks, `bind_material` symbols and `instance_node`.
366
+ * Controllers (`<skin>` with up to four influences per vertex, `<morph>` NORMALIZED or RELATIVE) and
367
+ * `<instance_controller>` with `<skeleton>` roots, animations (nested, LINEAR, STEP, BEZIER and HERMITE samplers on
368
+ * node transform elements and morph weights) and animation clips are read too. `up_axis` and `unit` are converted to
369
+ * Y-up meters, alike for geometry, node, bind shape and inverse bind matrices. `lookat` and `skew` join the transform
370
+ * stack; `<instance_camera>` and `<instance_light>` give `cameras` and `lights` (technique_common optics and lights)
371
+ * with their frames. `<lines>` and `<linestrips>` come back as each geometry's `lines`. Polygon holes, and cameras,
372
+ * lights, channels or controllers that do not fit, are not imported; each is reported in `warnings`. Image paths are
373
+ * relative to the .dae folder, for the caller's resolver. Joints are read by `parseDAEKinematics` of
374
+ * `@margoengine/loaders/dae-kinematics`.
375
+ */
376
+ export function parseDAE(input, options = {}) {
377
+ return readDAE(daeRoot(input, options), options);
378
+ }
379
+ /** The document's `<COLLADA>` element. */
380
+ export function daeRoot(input, options) {
381
+ // The limits are checked before the XML is read.
382
+ limits(options, F);
383
+ const root = readXMLTree(typeof input === 'string' ? input : decodeXML(toBytes(input, F)), F, {
384
+ external: options.external,
385
+ }).children[0];
386
+ if (root?.name !== 'COLLADA')
387
+ throw new LoaderError(F, 'header', `root element is <${root?.name ?? ''}>, not <COLLADA>`);
388
+ return root;
389
+ }
390
+ /** {@link parseDAE} of a document already read, for entries that also read other libraries of it. */
391
+ export function readDAE(root, options) {
392
+ const limit = limits(options, F), warnings = new Set(), warn = (message) => void warnings.add(message);
393
+ const ids = new Map(), images = new Map();
394
+ const index = (e) => {
395
+ if (e.attributes.id)
396
+ ids.set(e.attributes.id, e);
397
+ if (e.name === 'image' && e.attributes.id) {
398
+ const from = kid(e, 'init_from'), uri = (kid(from, 'ref') ?? from)?.text.trim();
399
+ if (uri)
400
+ images.set(e.attributes.id, imagePath(uri));
401
+ else
402
+ warn(`image "${e.attributes.id}" has no file (embedded data is not imported)`);
403
+ }
404
+ for (const child of e.children)
405
+ index(child);
406
+ };
407
+ index(root);
408
+ const asset = kid(root, 'asset'), upAxis = (kid(asset, 'up_axis')?.text.trim() || 'Y_UP'), unit = kid(asset, 'unit')?.attributes.meter, meter = unit === undefined ? 1 : Number(unit);
409
+ if (!Object.hasOwn(AXES, upAxis))
410
+ throw new LoaderError(F, 'syntax', `unknown up_axis "${upAxis.slice(0, 16)}"`);
411
+ if (!(meter > 0 && Number.isFinite(meter)))
412
+ throw new LoaderError(F, 'syntax', `unit meter must be a positive number, got "${String(unit).slice(0, 16)}"`);
413
+ const axis = AXES[upAxis];
414
+ const geometries = [], geometryIndex = new Map(), totals = { vertices: 0, triangles: 0 };
415
+ for (const geometry of kids(kid(root, 'library_geometries'), 'geometry')) {
416
+ const mesh = kid(geometry, 'mesh');
417
+ if (!mesh) {
418
+ warn(`geometry "${geometry.attributes.id}" is not a <mesh> and is not imported`);
419
+ continue;
420
+ }
421
+ const loaded = readMesh(geometry, mesh, ids, limit, totals, warn);
422
+ // Y-up meters: p' = meter * R p, n' = R n.
423
+ const p = loaded.positions, n = loaded.normals;
424
+ for (let i = 0; i < p.length; i += 3) {
425
+ const x = p[i], y = p[i + 1], z = p[i + 2];
426
+ for (let r = 0; r < 3; r++)
427
+ p[i + r] = meter * (axis[r * 3] * x + axis[r * 3 + 1] * y + axis[r * 3 + 2] * z);
428
+ if (!n)
429
+ continue;
430
+ const nx = n[i], ny = n[i + 1], nz = n[i + 2];
431
+ for (let r = 0; r < 3; r++)
432
+ n[i + r] = axis[r * 3] * nx + axis[r * 3 + 1] * ny + axis[r * 3 + 2] * nz;
433
+ }
434
+ geometryIndex.set(loaded.id, geometries.length);
435
+ geometries.push(loaded);
436
+ }
437
+ const materials = [], materialIndex = new Map();
438
+ for (const material of kids(kid(root, 'library_materials'), 'material')) {
439
+ materialIndex.set(material.attributes.id ?? '', materials.length);
440
+ materials.push(readMaterial(material, ids, images, warn));
441
+ }
442
+ // M' = C M C^-1 with C = meter * R: rotations keep their axes in Y-up, translations scale to meters.
443
+ const convert = converter(upAxis, meter);
444
+ const { skins, morphs, controllers } = readControllers(root, ids, geometryIndex, (g) => geometries[g].positionIndices, convert, warn);
445
+ // Controller instances whose skin joints resolve once the whole scene exists.
446
+ const pending = [], placements = [], copies = new Map();
447
+ let nodeCount = 0;
448
+ const readNode = (e, depth) => {
449
+ if (depth > MAX_DEPTH)
450
+ throw new LoaderError(F, 'limit', `nodes nest deeper than ${MAX_DEPTH} (an instance_node cycle?)`);
451
+ if (++nodeCount > MAX_NODES)
452
+ throw new LoaderError(F, 'limit', `the scene expands to more than ${MAX_NODES} nodes`);
453
+ const transforms = readTransforms(e, warn), node = { matrix: convert(stackMatrix(transforms)), transforms, instances: [], children: [] };
454
+ if (e.attributes.id !== undefined)
455
+ node.id = e.attributes.id;
456
+ if (e.attributes.name !== undefined)
457
+ node.name = e.attributes.name;
458
+ if (e.attributes.sid !== undefined)
459
+ node.sid = e.attributes.sid;
460
+ const list = copies.get(e);
461
+ if (list)
462
+ list.push(node);
463
+ else
464
+ copies.set(e, [node]);
465
+ for (const child of e.children)
466
+ switch (child.name) {
467
+ case 'node':
468
+ node.children.push(readNode(child, depth + 1));
469
+ break;
470
+ case 'instance_node': {
471
+ const target = ids.get(ref(child.attributes.url));
472
+ if (target?.name === 'node')
473
+ node.children.push(readNode(target, depth + 1));
474
+ else
475
+ warn(`instance_node "${child.attributes.url}" names no <node>`);
476
+ break;
477
+ }
478
+ case 'instance_camera':
479
+ case 'instance_light':
480
+ placements.push({
481
+ node,
482
+ kind: child.name === 'instance_camera' ? 'camera' : 'light',
483
+ url: child.attributes.url ?? '',
484
+ });
485
+ break;
486
+ case 'instance_geometry': {
487
+ const geometry = geometryIndex.get(ref(child.attributes.url));
488
+ if (geometry === undefined) {
489
+ warn(`instance_geometry "${child.attributes.url}" names no imported mesh`);
490
+ break;
491
+ }
492
+ node.instances.push({ geometry, materials: bindMaterials(child, materialIndex, warn) });
493
+ break;
494
+ }
495
+ case 'instance_controller': {
496
+ const url = ref(child.attributes.url), controller = controllers.get(url);
497
+ if (!controller) {
498
+ warn(`instance_controller "${child.attributes.url}" names no imported <controller>, so its node has no mesh`);
499
+ break;
500
+ }
501
+ const instance = {
502
+ geometry: controller.geometry,
503
+ materials: bindMaterials(child, materialIndex, warn),
504
+ };
505
+ if (controller.morph !== undefined)
506
+ instance.morph = controller.morph;
507
+ if (controller.skin !== undefined) {
508
+ instance.skin = controller.skin;
509
+ pending.push({
510
+ instance,
511
+ roots: kids(child, 'skeleton').map((s) => ref(s.text.trim())),
512
+ idref: !!controller.idref,
513
+ url,
514
+ });
515
+ }
516
+ node.instances.push(instance);
517
+ }
518
+ }
519
+ return node;
520
+ };
521
+ const sceneUrl = kid(kid(root, 'scene'), 'instance_visual_scene')?.attributes.url, scene = sceneUrl ? ids.get(ref(sceneUrl)) : kid(kid(root, 'library_visual_scenes'), 'visual_scene');
522
+ if (sceneUrl && scene?.name !== 'visual_scene')
523
+ throw new LoaderError(F, 'syntax', `instance_visual_scene "${sceneUrl.slice(0, 64)}" names no <visual_scene>`);
524
+ const nodes = kids(scene, 'node').map((e) => readNode(e, 0));
525
+ // Name_array joints are sids under the <skeleton> roots; IDREF_array joints are node ids. Ids and names are also
526
+ // tried, since exporters disagree.
527
+ for (const { instance, roots, idref, url } of pending) {
528
+ const skin = skins[instance.skin], starts = roots.flatMap((id) => {
529
+ const element = ids.get(id);
530
+ return (element && copies.get(element)?.slice(0, 1)) ?? [];
531
+ }), scope = starts.length ? starts : nodes, joints = [];
532
+ for (const name of skin.joints) {
533
+ const joint = idref
534
+ ? findNode(nodes, (n) => n.id === name)
535
+ : (findNode(scope, (n) => n.sid === name) ??
536
+ findNode(scope, (n) => n.id === name) ??
537
+ findNode(scope, (n) => n.name === name) ??
538
+ findNode(nodes, (n) => n.sid === name));
539
+ if (!joint) {
540
+ warn(`skin "${url}": joint "${name}" names no node, so the mesh is not skinned`);
541
+ break;
542
+ }
543
+ joints.push(joint);
544
+ }
545
+ if (joints.length === skin.joints.length)
546
+ instance.joints = joints;
547
+ else
548
+ delete instance.skin;
549
+ }
550
+ const { animations, clips } = readAnimations(root, ids, morphs, warn), { cameras, lights } = placeScene({ nodes, upAxis, meter }, ids, placements, warn);
551
+ const used = new Set();
552
+ for (const material of materials)
553
+ for (const name of CHANNELS) {
554
+ const path = material[name]?.texture?.path;
555
+ if (path !== undefined)
556
+ used.add(path);
557
+ }
558
+ return {
559
+ upAxis,
560
+ meter,
561
+ geometries,
562
+ materials,
563
+ images: [...used],
564
+ nodes,
565
+ skins,
566
+ morphs,
567
+ animations,
568
+ clips,
569
+ cameras,
570
+ lights,
571
+ warnings: [...warnings],
572
+ };
573
+ }
574
+ /**
575
+ * Bakes a parsed COLLADA scene into one `LoadedGeometry` for `createMeshes` and `toGeometry`: every node instance's
576
+ * geometry transformed by its world matrix (mirroring transforms keep outward winding), one group per instance and
577
+ * primitive, named after the node and colored with the bound material's diffuse color. Morphed instances use the
578
+ * pose's weights and skinned ones are skinned by their joints' world matrices, so `flattenDAE(dae, poseDAE(dae, t))`
579
+ * bakes the animated scene at time t; without a pose the scene is at rest.
580
+ */
581
+ export function flattenDAE(dae, pose = restPose(dae)) {
582
+ const parts = [];
583
+ const walk = (node, parent) => {
584
+ const world = multiply(parent, pose.local.get(node) ?? node.matrix);
585
+ for (const instance of node.instances) {
586
+ const geometry = dae.geometries[instance.geometry];
587
+ if (!geometry)
588
+ throw new LoaderError(F, 'range', `instance names geometry ${instance.geometry}, which does not exist`);
589
+ parts.push({ node, geometry, materials: instance.materials, ...deformInstance(dae, instance, world, pose) });
590
+ }
591
+ for (const child of node.children)
592
+ walk(child, world);
593
+ };
594
+ for (const node of dae.nodes)
595
+ walk(node, IDENTITY);
596
+ let vertexCount = 0, indexCount = 0, faceCount = 0;
597
+ for (const { geometry } of parts) {
598
+ vertexCount += geometry.positions.length / 3;
599
+ indexCount += geometry.indices.length;
600
+ faceCount += geometry.faceSizes.length;
601
+ }
602
+ if (vertexCount > DEFAULT_MAX_VERTICES || indexCount / 3 > DEFAULT_MAX_TRIANGLES)
603
+ throw new LoaderError(F, 'limit', `the flattened scene has ${vertexCount} vertices and ${indexCount / 3} triangles`);
604
+ const has = (key) => parts.some((p) => p.geometry[key]), positions = new Float32Array(vertexCount * 3), normals = has('normals') ? new Float32Array(vertexCount * 3) : undefined, uvs = has('uvs') ? new Float32Array(vertexCount * 2) : undefined, colors = has('colors') ? new Float32Array(vertexCount * 3).fill(1) : undefined, indices = new Uint32Array(indexCount), faceSizes = new Uint32Array(faceCount), groups = [];
605
+ let v = 0, o = 0, f = 0;
606
+ for (const part of parts) {
607
+ const { node, geometry, materials } = part, count = geometry.positions.length / 3;
608
+ positions.set(part.positions, v * 3);
609
+ if (normals && part.normals)
610
+ normals.set(part.normals, v * 3);
611
+ if (uvs && geometry.uvs)
612
+ uvs.set(geometry.uvs, v * 2);
613
+ if (colors && geometry.colors)
614
+ colors.set(geometry.colors, v * 3);
615
+ const flip = part.flip, source = geometry.indices;
616
+ for (let i = 0; i < source.length; i += 3) {
617
+ indices[o + i] = v + source[i];
618
+ indices[o + i + 1] = v + source[flip ? i + 2 : i + 1];
619
+ indices[o + i + 2] = v + source[flip ? i + 1 : i + 2];
620
+ }
621
+ for (const g of geometry.groups) {
622
+ const group = { start: o + g.start, count: g.count };
623
+ const name = node.name ?? node.id;
624
+ if (name !== undefined)
625
+ group.name = name;
626
+ const material = g.symbol === undefined ? undefined : dae.materials[materials[g.symbol]];
627
+ if (material?.diffuse?.color)
628
+ group.color = [...material.diffuse.color];
629
+ groups.push(group);
630
+ }
631
+ faceSizes.set(geometry.faceSizes, f);
632
+ v += count;
633
+ o += source.length;
634
+ f += geometry.faceSizes.length;
635
+ }
636
+ const result = { kind: 'mesh', positions, indices, groups, faceSizes };
637
+ if (normals)
638
+ result.normals = normals;
639
+ if (uvs)
640
+ result.uvs = uvs;
641
+ if (colors)
642
+ result.colors = colors;
643
+ return result;
644
+ }
@@ -0,0 +1,20 @@
1
+ import { type LoadedGeometry } from './types.js';
2
+ import { type BinaryInput } from './util.js';
3
+ import { type PLYOptions } from './ply.js';
4
+ import { type ThreeMFOptions } from './threemf.js';
5
+ import { type PCDOptions } from './pcd.js';
6
+ import { type OFFOptions } from './off.js';
7
+ import { type XYZOptions } from './xyz.js';
8
+ import { type VTKOptions } from './vtk.js';
9
+ import { type USDOptions } from './usdz.js';
10
+ /** A format detectFormat and parseAny can detect: ply, 3mf, pcd, off, xyz, vtk, usda or usdz. */
11
+ export type LoaderFormat = 'ply' | '3mf' | 'pcd' | 'off' | 'xyz' | 'vtk' | 'usda' | 'usdz';
12
+ /** Guesses the format from the file's first bytes, then from `name`'s extension. Returns null when unknown. */
13
+ export declare function detectFormat(input: BinaryInput, name?: string): LoaderFormat | null;
14
+ /** The union of every loader's options, plus a file name hint and a forced format, for parseAny. */
15
+ export type AnyOptions = PLYOptions & ThreeMFOptions & PCDOptions & OFFOptions & XYZOptions & VTKOptions & USDOptions & {
16
+ name?: string;
17
+ format?: LoaderFormat;
18
+ };
19
+ /** Detects the format (or uses `options.format`) and parses with the matching loader. Imports every parser. */
20
+ export declare function parseAny(input: BinaryInput, options?: AnyOptions): Promise<LoadedGeometry>;