@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/xfile.js ADDED
@@ -0,0 +1,706 @@
1
+ // DirectX `.x` files, text and binary, read from Microsoft's public "DirectX File Format" reference (the `xof` header,
2
+ // the template data objects Frame, FrameTransformMatrix, Mesh, MeshNormals, MeshTextureCoords, MeshMaterialList, Material,
3
+ // TextureFilename, MeshVertexColors, XSkinMeshHeader, SkinWeights, AnimationSet, Animation, AnimationKey and
4
+ // AnimTicksPerSecond, and the binary token stream). The format is left-handed with row vectors; `rightHanded` (default
5
+ // true) mirrors Z into the engine's space.
6
+ import { LoaderError } from './types.js';
7
+ import { DEFAULT_MAX_TRIANGLES, DEFAULT_MAX_VERTICES, toBytes } from './util.js';
8
+ const F = 'X';
9
+ const bad = (code, m) => {
10
+ throw new LoaderError(F, code, m);
11
+ };
12
+ function textTokens(text, limit) {
13
+ const out = [];
14
+ let i = 0;
15
+ const n = text.length;
16
+ while (i < n) {
17
+ const c = text.charCodeAt(i);
18
+ if (c <= 32 || c === 59 /* ; */ || c === 44 /* , */) {
19
+ i++;
20
+ continue;
21
+ }
22
+ if (c === 35 /* # */ || (c === 47 && text.charCodeAt(i + 1) === 47)) {
23
+ while (i < n && text.charCodeAt(i) !== 10)
24
+ i++;
25
+ continue;
26
+ }
27
+ if (out.length >= limit)
28
+ bad('limit', `more than ${limit} tokens`);
29
+ if (c === 123) {
30
+ out.push({ k: '{' });
31
+ i++;
32
+ }
33
+ else if (c === 125) {
34
+ out.push({ k: '}' });
35
+ i++;
36
+ }
37
+ else if (c === 34) {
38
+ const end = text.indexOf('"', i + 1);
39
+ if (end < 0)
40
+ bad('syntax', 'a string is not closed');
41
+ out.push({ k: 'str', v: text.slice(i + 1, end) });
42
+ i = end + 1;
43
+ }
44
+ else if (c === 60) {
45
+ const end = text.indexOf('>', i);
46
+ if (end < 0)
47
+ bad('syntax', 'a GUID is not closed');
48
+ out.push({ k: 'guid' });
49
+ i = end + 1;
50
+ }
51
+ else {
52
+ let j = i;
53
+ while (j < n) {
54
+ const d = text.charCodeAt(j);
55
+ if (d <= 32 || d === 59 || d === 44 || d === 123 || d === 125 || d === 34)
56
+ break;
57
+ j++;
58
+ }
59
+ const word = text.slice(i, j);
60
+ i = j;
61
+ if (/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(word))
62
+ out.push({ k: 'num', v: Number(word) });
63
+ else if (word === 'template')
64
+ out.push({ k: 'template' });
65
+ else
66
+ out.push({ k: 'name', v: word });
67
+ }
68
+ }
69
+ return out;
70
+ }
71
+ const T = {
72
+ NAME: 1,
73
+ STRING: 2,
74
+ INTEGER: 3,
75
+ GUID: 5,
76
+ INTEGER_LIST: 6,
77
+ FLOAT_LIST: 7,
78
+ OBRACE: 10,
79
+ CBRACE: 11,
80
+ TEMPLATE: 31,
81
+ LAST_PUNCT: 20,
82
+ FIRST_TYPE: 40,
83
+ LAST_TYPE: 52,
84
+ };
85
+ function binaryTokens(bytes, start, floatSize, limit) {
86
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
87
+ const out = [];
88
+ let p = start;
89
+ const need = (n, what) => {
90
+ if (n < 0 || p + n > bytes.length)
91
+ bad('truncated', `${what} runs past the end of the file`);
92
+ };
93
+ while (p < bytes.length) {
94
+ need(2, 'a token');
95
+ const id = view.getUint16(p, true);
96
+ p += 2;
97
+ if (out.length >= limit)
98
+ bad('limit', `more than ${limit} tokens`);
99
+ if (id === T.NAME || id === T.STRING) {
100
+ need(4, 'a string length');
101
+ const len = view.getUint32(p, true);
102
+ p += 4;
103
+ need(len, 'a string');
104
+ let s = '';
105
+ for (let i = 0; i < len; i++)
106
+ s += String.fromCharCode(bytes[p + i]);
107
+ p += len;
108
+ out.push(id === T.NAME ? { k: 'name', v: s } : { k: 'str', v: s });
109
+ }
110
+ else if (id === T.INTEGER) {
111
+ need(4, 'an integer');
112
+ out.push({ k: 'num', v: view.getUint32(p, true) });
113
+ p += 4;
114
+ }
115
+ else if (id === T.GUID) {
116
+ need(16, 'a GUID');
117
+ p += 16;
118
+ out.push({ k: 'guid' });
119
+ }
120
+ else if (id === T.INTEGER_LIST || id === T.FLOAT_LIST) {
121
+ need(4, 'a list length');
122
+ const count = view.getUint32(p, true);
123
+ p += 4;
124
+ const size = id === T.INTEGER_LIST ? 4 : floatSize;
125
+ if (count > (bytes.length - p) / size)
126
+ bad('truncated', `a list of ${count} values runs past the end of the file`);
127
+ if (out.length + count > limit)
128
+ bad('limit', `more than ${limit} tokens`);
129
+ for (let i = 0; i < count; i++, p += size)
130
+ out.push({
131
+ k: 'num',
132
+ v: id === T.INTEGER_LIST
133
+ ? view.getUint32(p, true)
134
+ : size === 4
135
+ ? view.getFloat32(p, true)
136
+ : view.getFloat64(p, true),
137
+ });
138
+ }
139
+ else if (id === T.OBRACE)
140
+ out.push({ k: '{' });
141
+ else if (id === T.CBRACE)
142
+ out.push({ k: '}' });
143
+ else if (id === T.TEMPLATE)
144
+ out.push({ k: 'template' });
145
+ else if ((id >= 12 && id <= T.LAST_PUNCT) || (id >= T.FIRST_TYPE && id <= T.LAST_TYPE)) {
146
+ // separators and the template member types carry no data of their own
147
+ }
148
+ else
149
+ bad('syntax', `unknown token ${id}`);
150
+ }
151
+ return out;
152
+ }
153
+ function buildTree(tokens, maxDepth, maxNodes) {
154
+ let p = 0, count = 0;
155
+ const roots = [];
156
+ const skipBlock = () => {
157
+ // At the `{` of a template body: skip to its matching `}`.
158
+ let depth = 0;
159
+ for (; p < tokens.length; p++) {
160
+ const k = tokens[p].k;
161
+ if (k === '{')
162
+ depth++;
163
+ else if (k === '}' && --depth === 0) {
164
+ p++;
165
+ return;
166
+ }
167
+ }
168
+ bad('truncated', 'a template is not closed');
169
+ };
170
+ const object = (depth) => {
171
+ if (depth > maxDepth)
172
+ bad('limit', `objects nest deeper than ${maxDepth}`);
173
+ if (++count > maxNodes * 8)
174
+ bad('limit', 'too many data objects');
175
+ const head = tokens[p++];
176
+ const node = { type: head.v, name: '', values: [], children: [], refs: [], items: [] };
177
+ // An optional name, an optional GUID, then the body.
178
+ if (tokens[p]?.k === 'name')
179
+ node.name = tokens[p++].v;
180
+ if (tokens[p]?.k !== '{')
181
+ bad('syntax', `object "${node.type}" has no body`);
182
+ p++;
183
+ if (tokens[p]?.k === 'guid')
184
+ p++;
185
+ for (;;) {
186
+ const t = tokens[p];
187
+ if (!t)
188
+ return bad('truncated', `object "${node.type}" is not closed`);
189
+ if (t.k === '}') {
190
+ p++;
191
+ return node;
192
+ }
193
+ if (t.k === 'num' || t.k === 'str') {
194
+ node.values.push(t.v);
195
+ p++;
196
+ }
197
+ else if (t.k === '{') {
198
+ // A reference: { name } with an optional GUID.
199
+ p++;
200
+ if (tokens[p]?.k === 'name') {
201
+ const ref = tokens[p++].v;
202
+ node.refs.push(ref);
203
+ node.items.push(ref);
204
+ }
205
+ while (tokens[p] && tokens[p].k !== '}')
206
+ p++;
207
+ if (!tokens[p])
208
+ bad('truncated', 'a reference is not closed');
209
+ p++;
210
+ }
211
+ else if (t.k === 'name') {
212
+ const child = object(depth + 1);
213
+ node.children.push(child);
214
+ node.items.push(child);
215
+ }
216
+ else
217
+ bad('syntax', `unexpected token in "${node.type}"`);
218
+ }
219
+ };
220
+ while (p < tokens.length) {
221
+ const t = tokens[p];
222
+ if (t.k === 'template') {
223
+ p++;
224
+ if (tokens[p]?.k === 'name')
225
+ p++;
226
+ if (tokens[p]?.k !== '{')
227
+ bad('syntax', 'a template has no body');
228
+ skipBlock();
229
+ }
230
+ else if (t.k === 'name')
231
+ roots.push(object(0));
232
+ else
233
+ bad('syntax', 'unexpected token at the top level');
234
+ }
235
+ return roots;
236
+ }
237
+ // ---- interpretation -------------------------------------------------------------------------------------------------
238
+ /** Cursor over a node's numbers with bounds checks: a count that claims more than is left throws. */
239
+ class Reader {
240
+ constructor(values, what) {
241
+ this.values = values;
242
+ this.what = what;
243
+ this.at = 0;
244
+ }
245
+ get left() {
246
+ return this.values.length - this.at;
247
+ }
248
+ int() {
249
+ const v = this.values[this.at++];
250
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 0)
251
+ return bad('syntax', `${this.what}: expected a count or index`);
252
+ return v;
253
+ }
254
+ num() {
255
+ const v = this.values[this.at++];
256
+ if (typeof v !== 'number')
257
+ return bad('truncated', `${this.what}: a number is missing`);
258
+ return v;
259
+ }
260
+ str() {
261
+ const v = this.values[this.at++];
262
+ return typeof v === 'string' ? v : bad('syntax', `${this.what}: expected a string`);
263
+ }
264
+ /** `n` numbers; `n` is checked against what is left before anything is allocated. */
265
+ take(n) {
266
+ if (n > this.left)
267
+ bad('truncated', `${this.what}: ${n} values announced, ${this.left} present`);
268
+ const out = this.values.slice(this.at, this.at + n);
269
+ this.at += n;
270
+ for (const v of out)
271
+ if (typeof v !== 'number')
272
+ bad('syntax', `${this.what}: expected numbers`);
273
+ return out;
274
+ }
275
+ }
276
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
277
+ function mul(a, b) {
278
+ const o = new Array(16).fill(0);
279
+ for (let c = 0; c < 4; c++)
280
+ for (let r = 0; r < 4; r++)
281
+ for (let k = 0; k < 4; k++)
282
+ o[c * 4 + r] += a[k * 4 + r] * b[c * 4 + k];
283
+ return o;
284
+ }
285
+ /**
286
+ * Parses a DirectX `.x` file, text (`txt `) or binary (`bin `), 32 or 64-bit floats. Compressed files (`tzip`, `bzip`)
287
+ * throw `'unsupported'`. Returns the frame hierarchy, meshes (as triangles; polygons are fanned; normals indexed apart
288
+ * from positions split the vertices), materials, skin weights as per-vertex joints and weights, and animation sets with
289
+ * keys in seconds. Counts that claim more data than the file holds, bad indices, runaway nesting and files past the
290
+ * limits throw a `LoaderError`; nothing is allocated from a count before it is checked against the data present.
291
+ */
292
+ export function parseX(input, options = {}) {
293
+ const maxVertices = options.maxVertices ?? DEFAULT_MAX_VERTICES, maxTriangles = options.maxTriangles ?? DEFAULT_MAX_TRIANGLES, maxDepth = options.maxDepth ?? 128, maxNodes = options.maxNodes ?? 100_000, rh = options.rightHanded ?? true;
294
+ for (const [k, v] of Object.entries({ maxVertices, maxTriangles, maxDepth, maxNodes }))
295
+ if (!Number.isSafeInteger(v) || v < 0)
296
+ throw new LoaderError(F, 'range', `${k} must be a non-negative integer`);
297
+ const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : toBytes(input, F);
298
+ if (bytes.length < 16)
299
+ throw new LoaderError(F, 'truncated', 'file is shorter than the 16-byte header');
300
+ const tag = (o) => String.fromCharCode(bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]);
301
+ if (tag(0) !== 'xof ')
302
+ throw new LoaderError(F, 'header', 'missing the "xof " signature');
303
+ const major = tag(4), kind = tag(8), floats = tag(12);
304
+ if (!/^0[0-9]{3}$/.test(major))
305
+ throw new LoaderError(F, 'header', `bad version "${major}"`);
306
+ if (floats !== '0032' && floats !== '0064')
307
+ throw new LoaderError(F, 'header', `float size "${floats}" is not 0032 or 0064`);
308
+ if (kind === 'tzip' || kind === 'bzip')
309
+ throw new LoaderError(F, 'unsupported', 'compressed .x files (MSZip) are not read');
310
+ if (kind !== 'txt ' && kind !== 'bin ')
311
+ throw new LoaderError(F, 'header', `format "${kind}" is not txt or bin`);
312
+ const budget = Math.max(1024, bytes.length * 2);
313
+ const tokens = kind === 'txt '
314
+ ? textTokens(new TextDecoder('latin1').decode(bytes.subarray(16)), budget)
315
+ : binaryTokens(bytes, 16, floats === '0064' ? 8 : 4, budget + 64);
316
+ const roots = buildTree(tokens, maxDepth, maxNodes);
317
+ const warnings = [];
318
+ const M = (m) => {
319
+ if (!rh)
320
+ return m;
321
+ const o = m.slice();
322
+ for (let i = 0; i < 16; i++)
323
+ if (((i & 3) === 2) !== (i >> 2 === 2))
324
+ o[i] = 0 - o[i];
325
+ return o;
326
+ };
327
+ const named = new Map();
328
+ const collectNames = (n, depth) => {
329
+ if (n.name && !named.has(`${n.type}:${n.name}`))
330
+ named.set(`${n.type}:${n.name}`, n);
331
+ for (const c of n.children)
332
+ collectNames(c, depth + 1);
333
+ };
334
+ for (const r of roots)
335
+ collectNames(r, 0);
336
+ const materials = [];
337
+ const made = new Map();
338
+ const material = (n) => {
339
+ const cached = made.get(n);
340
+ if (cached)
341
+ return cached;
342
+ const r = new Reader(n.values, `Material ${n.name}`);
343
+ const c = r.take(4), power = r.num(), spec = r.take(3), emis = r.take(3);
344
+ const out = {
345
+ name: n.name,
346
+ color: [c[0], c[1], c[2], c[3]],
347
+ specularPower: power,
348
+ specular: [spec[0], spec[1], spec[2]],
349
+ emissive: [emis[0], emis[1], emis[2]],
350
+ };
351
+ const tex = n.children.find((x) => x.type === 'TextureFilename');
352
+ if (tex && typeof tex.values[0] === 'string')
353
+ out.texture = tex.values[0];
354
+ materials.push(out);
355
+ made.set(n, out);
356
+ return out;
357
+ };
358
+ let vertexTotal = 0, triangleTotal = 0;
359
+ const meshes = [];
360
+ const meshOf = (n) => {
361
+ const what = `Mesh ${n.name}`;
362
+ const r = new Reader(n.values, what);
363
+ const nv = r.int();
364
+ if (nv * 3 > r.left)
365
+ bad('truncated', `${what}: ${nv} vertices announced, data for fewer`);
366
+ const verts = r.take(nv * 3);
367
+ const nf = r.int();
368
+ if (nf > r.left)
369
+ bad('truncated', `${what}: ${nf} faces announced, data for fewer`);
370
+ const faces = [];
371
+ let cornerCount = 0;
372
+ for (let f = 0; f < nf; f++) {
373
+ const k = r.int();
374
+ if (k < 3 || k > r.left)
375
+ bad('syntax', `${what}: face ${f} has ${k} indices`);
376
+ const face = r.take(k);
377
+ for (const v of face)
378
+ if (!Number.isInteger(v) || v < 0 || v >= nv)
379
+ bad('range', `${what}: face ${f} names vertex ${v} of ${nv}`);
380
+ faces.push(face);
381
+ cornerCount += k;
382
+ if (cornerCount > maxTriangles * 3 * 4)
383
+ bad('limit', `${what}: too many face corners`);
384
+ }
385
+ // Per-corner extras
386
+ let normals, normalFaces, uvs, colorOf, faceMaterial, meshMaterials = [];
387
+ for (const c of n.children) {
388
+ const cr = new Reader(c.values, `${what} ${c.type}`);
389
+ if (c.type === 'MeshNormals') {
390
+ const nn = cr.int();
391
+ if (nn * 3 > cr.left)
392
+ bad('truncated', `${what}: ${nn} normals announced, data for fewer`);
393
+ normals = cr.take(nn * 3);
394
+ const nfn = cr.int();
395
+ if (nfn !== nf)
396
+ bad('syntax', `${what}: ${nfn} normal faces for ${nf} faces`);
397
+ normalFaces = [];
398
+ for (let f = 0; f < nfn; f++) {
399
+ const k = cr.int();
400
+ if (k !== faces[f].length || k > cr.left)
401
+ bad('syntax', `${what}: normal face ${f} has ${k} indices, the face has ${faces[f].length}`);
402
+ const nf2 = cr.take(k);
403
+ for (const v of nf2)
404
+ if (!Number.isInteger(v) || v < 0 || v >= nn)
405
+ bad('range', `${what}: normal face ${f} names normal ${v} of ${nn}`);
406
+ normalFaces.push(nf2);
407
+ }
408
+ }
409
+ else if (c.type === 'MeshTextureCoords') {
410
+ const nt = cr.int();
411
+ if (nt !== nv)
412
+ bad('syntax', `${what}: ${nt} texture coordinates for ${nv} vertices`);
413
+ uvs = cr.take(nt * 2);
414
+ }
415
+ else if (c.type === 'MeshVertexColors') {
416
+ const nc = cr.int();
417
+ if (nc * 5 > cr.left)
418
+ bad('truncated', `${what}: ${nc} vertex colours announced, data for fewer`);
419
+ colorOf = new Map();
420
+ for (let i = 0; i < nc; i++) {
421
+ const idx = cr.int(), rgba = cr.take(4);
422
+ if (idx >= nv)
423
+ bad('range', `${what}: vertex colour for vertex ${idx} of ${nv}`);
424
+ colorOf.set(idx, rgba);
425
+ }
426
+ }
427
+ else if (c.type === 'MeshMaterialList') {
428
+ const nm = cr.int(), ni = cr.int();
429
+ if (ni > cr.left)
430
+ bad('truncated', `${what}: ${ni} material indices announced, data for fewer`);
431
+ const idx = cr.take(ni);
432
+ faceMaterial = ni === nf ? idx : Array.from({ length: nf }, (_, i) => idx[i % Math.max(ni, 1)] ?? 0);
433
+ if (ni !== nf && ni !== 1 && ni !== 0)
434
+ bad('syntax', `${what}: ${ni} material indices for ${nf} faces`);
435
+ for (const v of faceMaterial)
436
+ if (!Number.isInteger(v) || v < 0 || (nm > 0 && v >= nm))
437
+ bad('range', `${what}: material index ${v} of ${nm}`);
438
+ for (const item of c.items) {
439
+ if (typeof item !== 'string') {
440
+ if (item.type === 'Material')
441
+ meshMaterials.push(material(item));
442
+ continue;
443
+ }
444
+ const m = named.get(`Material:${item}`);
445
+ if (m)
446
+ meshMaterials.push(material(m));
447
+ else
448
+ warnings.push(`${what}: material "${item}" is not in the file`);
449
+ }
450
+ }
451
+ }
452
+ // Output vertices: one per distinct (position, normal) pair.
453
+ const key = new Map(); // (v * (nNormals + 1) + normal + 1) -> output index
454
+ const nNormals = normals ? normals.length / 3 : 0;
455
+ const source = [], normalSource = [];
456
+ const corner = (f, i) => {
457
+ const v = faces[f][i], ni = normalFaces ? normalFaces[f][i] : -1;
458
+ const k = v * (nNormals + 1) + ni + 1;
459
+ let o = key.get(k);
460
+ if (o === undefined) {
461
+ o = source.length;
462
+ if (o >= maxVertices)
463
+ bad('limit', `${what}: more than ${maxVertices} vertices`);
464
+ key.set(k, o);
465
+ source.push(v);
466
+ normalSource.push(ni);
467
+ }
468
+ return o;
469
+ };
470
+ // Triangles sorted (stably) by material so each material is one group.
471
+ const order = faces.map((_, i) => i);
472
+ if (faceMaterial)
473
+ order.sort((a, b) => faceMaterial[a] - faceMaterial[b] || a - b);
474
+ const tris = [], groups = [];
475
+ let groupMaterial = -1, groupStart = 0;
476
+ for (const f of order) {
477
+ const face = faces[f];
478
+ const m = faceMaterial ? faceMaterial[f] : 0;
479
+ if (faceMaterial && m !== groupMaterial) {
480
+ if (groupMaterial >= 0)
481
+ groups.push({
482
+ start: groupStart,
483
+ count: tris.length - groupStart,
484
+ properties: { materialIndex: groupMaterial },
485
+ });
486
+ groupMaterial = m;
487
+ groupStart = tris.length;
488
+ }
489
+ for (let i = 1; i + 1 < face.length; i++) {
490
+ triangleTotal++;
491
+ if (triangleTotal > maxTriangles)
492
+ bad('limit', `more than ${maxTriangles} triangles`);
493
+ const a = corner(f, 0), b = corner(f, i), c = corner(f, i + 1);
494
+ tris.push(a, rh ? c : b, rh ? b : c);
495
+ }
496
+ }
497
+ if (faceMaterial && groupMaterial >= 0)
498
+ groups.push({ start: groupStart, count: tris.length - groupStart, properties: { materialIndex: groupMaterial } });
499
+ const count = source.length;
500
+ vertexTotal += count;
501
+ if (vertexTotal > maxVertices)
502
+ bad('limit', `vertex count ${vertexTotal} exceeds the limit of ${maxVertices}`);
503
+ const positions = new Float32Array(count * 3), outNormals = normals ? new Float32Array(count * 3) : undefined, outUvs = uvs ? new Float32Array(count * 2) : undefined, outColors = colorOf ? new Float32Array(count * 3) : undefined;
504
+ for (let i = 0; i < count; i++) {
505
+ const v = source[i];
506
+ positions[i * 3] = verts[v * 3];
507
+ positions[i * 3 + 1] = verts[v * 3 + 1];
508
+ positions[i * 3 + 2] = rh ? 0 - verts[v * 3 + 2] : verts[v * 3 + 2];
509
+ if (outNormals) {
510
+ const ni = normalSource[i];
511
+ outNormals[i * 3] = normals[ni * 3];
512
+ outNormals[i * 3 + 1] = normals[ni * 3 + 1];
513
+ outNormals[i * 3 + 2] = rh ? 0 - normals[ni * 3 + 2] : normals[ni * 3 + 2];
514
+ }
515
+ if (outUvs) {
516
+ outUvs[i * 2] = uvs[v * 2];
517
+ outUvs[i * 2 + 1] = uvs[v * 2 + 1];
518
+ }
519
+ if (outColors) {
520
+ const c = colorOf.get(v);
521
+ outColors.set(c ? [c[0], c[1], c[2]] : [1, 1, 1], i * 3);
522
+ }
523
+ }
524
+ const geometry = { kind: 'mesh', positions, indices: new Uint32Array(tris) };
525
+ if (outNormals)
526
+ geometry.normals = outNormals;
527
+ if (outUvs)
528
+ geometry.uvs = outUvs;
529
+ if (outColors)
530
+ geometry.colors = outColors;
531
+ if (groups.length)
532
+ geometry.groups = groups;
533
+ geometry.attributes = { sourceVertex: Float32Array.from(source) };
534
+ const mesh = { name: n.name, geometry, materials: meshMaterials, bones: [] };
535
+ // Skin weights: per bone lists to per-vertex influences.
536
+ const skins = n.children.filter((c) => c.type === 'SkinWeights');
537
+ if (skins.length) {
538
+ if (skins.length > 4096)
539
+ bad('limit', `${what}: more than 4096 bones`);
540
+ const influences = Array.from({ length: nv }, () => []);
541
+ skins.forEach((s, bone) => {
542
+ const sr = new Reader(s.values, `${what} SkinWeights`);
543
+ const boneName = sr.str(), nw = sr.int();
544
+ if (nw * 2 + 16 > sr.left)
545
+ bad('truncated', `${what}: ${nw} skin weights announced, data for fewer`);
546
+ const idx = sr.take(nw), w = sr.take(nw), offset = sr.take(16);
547
+ for (let i = 0; i < nw; i++) {
548
+ if (!Number.isInteger(idx[i]) || idx[i] < 0 || idx[i] >= nv)
549
+ bad('range', `${what}: skin weight for vertex ${idx[i]} of ${nv}`);
550
+ influences[idx[i]].push([bone, w[i]]);
551
+ }
552
+ mesh.bones.push({ name: boneName, frame: -1, inverseBind: M(offset) });
553
+ });
554
+ const j = new Uint16Array(count * 4), wt = new Float32Array(count * 4);
555
+ let j1, w1;
556
+ for (let i = 0; i < count; i++) {
557
+ const list = influences[source[i]].sort((a, b) => b[1] - a[1]);
558
+ const kept = list.slice(0, 8);
559
+ const sum = kept.reduce((t, x) => t + x[1], 0) || 1;
560
+ kept.forEach(([bone, weight], k) => {
561
+ const target = k < 4 ? [j, wt] : [(j1 ??= new Uint16Array(count * 4)), (w1 ??= new Float32Array(count * 4))];
562
+ target[0][i * 4 + (k & 3)] = bone;
563
+ target[1][i * 4 + (k & 3)] = list.length > 8 ? weight / sum : weight;
564
+ });
565
+ }
566
+ mesh.joints = j;
567
+ mesh.weights = wt;
568
+ if (j1) {
569
+ mesh.joints1 = j1;
570
+ mesh.weights1 = w1;
571
+ }
572
+ }
573
+ meshes.push(mesh);
574
+ return mesh;
575
+ };
576
+ // Frames
577
+ const frames = [];
578
+ const meshOfNode = new Map();
579
+ let nodeCount = 0;
580
+ const frameOf = (n, parent) => {
581
+ if (++nodeCount > maxNodes)
582
+ bad('limit', `more than ${maxNodes} frames`);
583
+ const own = frames.length;
584
+ const t = n.children.find((c) => c.type === 'FrameTransformMatrix');
585
+ let matrix = IDENTITY.slice();
586
+ if (t)
587
+ matrix = M(new Reader(t.values, 'FrameTransformMatrix').take(16));
588
+ frames.push({
589
+ name: n.name,
590
+ parent,
591
+ matrix,
592
+ world: parent >= 0 ? mul(frames[parent].world, matrix) : matrix.slice(),
593
+ meshes: [],
594
+ });
595
+ for (const item of n.items) {
596
+ if (typeof item !== 'string') {
597
+ if (item.type === 'Frame')
598
+ frameOf(item, own);
599
+ else if (item.type === 'Mesh') {
600
+ meshOfNode.set(item, meshes.length);
601
+ frames[own].meshes.push(meshes.length);
602
+ meshOf(item);
603
+ }
604
+ continue;
605
+ }
606
+ const m = named.get(`Mesh:${item}`);
607
+ if (!m)
608
+ continue;
609
+ let at = meshOfNode.get(m);
610
+ if (at === undefined) {
611
+ at = meshes.length;
612
+ meshOfNode.set(m, at);
613
+ meshOf(m);
614
+ }
615
+ frames[own].meshes.push(at);
616
+ }
617
+ };
618
+ for (const r of roots) {
619
+ if (r.type === 'Frame')
620
+ frameOf(r, -1);
621
+ else if (r.type === 'Mesh') {
622
+ frames.push({
623
+ name: r.name,
624
+ parent: -1,
625
+ matrix: IDENTITY.slice(),
626
+ world: IDENTITY.slice(),
627
+ meshes: [meshes.length],
628
+ });
629
+ meshOf(r);
630
+ }
631
+ else if (r.type === 'Material')
632
+ material(r);
633
+ }
634
+ const byName = new Map();
635
+ frames.forEach((f, i) => f.name && !byName.has(f.name) && byName.set(f.name, i));
636
+ for (const m of meshes)
637
+ for (const b of m.bones)
638
+ b.frame = byName.get(b.name) ?? -1;
639
+ // Animation
640
+ let ticks = 4800;
641
+ const tps = roots.find((r) => r.type === 'AnimTicksPerSecond');
642
+ if (tps && typeof tps.values[0] === 'number' && tps.values[0] > 0)
643
+ ticks = tps.values[0];
644
+ const animationSets = [];
645
+ for (const set of roots.filter((r) => r.type === 'AnimationSet')) {
646
+ const animations = [];
647
+ let duration = 0;
648
+ for (const a of set.children.filter((c) => c.type === 'Animation')) {
649
+ const animation = { frame: a.refs[0] ?? '' };
650
+ for (const k of a.children.filter((c) => c.type === 'AnimationKey')) {
651
+ const kr = new Reader(k.values, 'AnimationKey');
652
+ const type = kr.int(), nk = kr.int();
653
+ if (nk * 3 > kr.left)
654
+ bad('truncated', `AnimationKey: ${nk} keys announced, data for fewer`);
655
+ const width = [4, 3, 3, 16, 16][type];
656
+ if (width === undefined) {
657
+ warnings.push(`AnimationKey type ${type} is not read`);
658
+ continue;
659
+ }
660
+ const times = new Float64Array(nk), values = new Float32Array(nk * width);
661
+ for (let i = 0; i < nk; i++) {
662
+ times[i] = kr.int() / ticks;
663
+ const nv = kr.int();
664
+ if (nv !== width)
665
+ bad('syntax', `AnimationKey type ${type} key ${i} has ${nv} values, not ${width}`);
666
+ const v = kr.take(nv);
667
+ if (type === 0) {
668
+ // stored w, x, y, z; the engine's order is x, y, z, w
669
+ const [w, x, y, z] = v;
670
+ values.set(rh ? [0 - x, 0 - y, z, w] : [x, y, z, w], i * 4);
671
+ }
672
+ else if (type === 2)
673
+ values.set(rh ? [v[0], v[1], 0 - v[2]] : v, i * 3);
674
+ else if (type === 1)
675
+ values.set(v, i * 3);
676
+ else
677
+ values.set(M(v), i * 16);
678
+ if (i && times[i] < times[i - 1])
679
+ bad('syntax', 'AnimationKey times go backwards');
680
+ }
681
+ if (nk)
682
+ duration = Math.max(duration, times[nk - 1]);
683
+ const track = { times, values };
684
+ if (type === 0)
685
+ animation.rotation = track;
686
+ else if (type === 1)
687
+ animation.scale = track;
688
+ else if (type === 2)
689
+ animation.position = track;
690
+ else
691
+ animation.matrix = track;
692
+ }
693
+ animations.push(animation);
694
+ }
695
+ animationSets.push({ name: set.name, animations, duration });
696
+ }
697
+ return {
698
+ format: kind === 'txt ' ? 'text' : 'binary',
699
+ frames,
700
+ meshes,
701
+ materials,
702
+ animationSets,
703
+ ticksPerSecond: ticks,
704
+ warnings,
705
+ };
706
+ }