@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/mmd.js ADDED
@@ -0,0 +1,958 @@
1
+ // MikuMikuDance files: PMD and PMX models, VMD motion and camera clips. Read from the public format descriptions (the PMD
2
+ // 1.0 layout, the PMX 2.0 and 2.1 specification and the VMD layout). MMD is left-handed and measures in units of about
3
+ // 8 cm; `rightHanded` (default true) mirrors Z into the engine's space and `scale` (default 0.08) turns units into metres.
4
+ // Rigid bodies and joints are parsed into data only: this package never simulates them.
5
+ import { LoaderError } from './types.js';
6
+ import { DEFAULT_MAX_TRIANGLES, DEFAULT_MAX_VERTICES, toBytes } from './util.js';
7
+ const F = 'MMD';
8
+ // ---- reading helpers ------------------------------------------------------------------------------------------------
9
+ const fail = (code, m) => {
10
+ throw new LoaderError(F, code, m);
11
+ };
12
+ class Reader {
13
+ constructor(bytes, sjis, utf16 = false) {
14
+ this.bytes = bytes;
15
+ this.sjis = sjis;
16
+ this.utf16 = utf16;
17
+ this.p = 0;
18
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
19
+ }
20
+ get left() {
21
+ return this.bytes.length - this.p;
22
+ }
23
+ need(n, what = 'data') {
24
+ if (!(n >= 0) || n > this.left)
25
+ fail('truncated', `${what} runs past the end of the file`);
26
+ }
27
+ /** `count` records of at least `size` bytes must fit in what is left. */
28
+ records(count, size, what) {
29
+ if (!Number.isSafeInteger(count) || count < 0)
30
+ fail('syntax', `bad ${what} count ${count}`);
31
+ if (count * size > this.left)
32
+ fail('truncated', `${count} ${what} announced, data for fewer`);
33
+ return count;
34
+ }
35
+ u8() {
36
+ this.need(1);
37
+ return this.bytes[this.p++];
38
+ }
39
+ i8() {
40
+ this.need(1);
41
+ return this.view.getInt8(this.p++);
42
+ }
43
+ u16() {
44
+ this.need(2);
45
+ const v = this.view.getUint16(this.p, true);
46
+ this.p += 2;
47
+ return v;
48
+ }
49
+ i16() {
50
+ this.need(2);
51
+ const v = this.view.getInt16(this.p, true);
52
+ this.p += 2;
53
+ return v;
54
+ }
55
+ u32() {
56
+ this.need(4);
57
+ const v = this.view.getUint32(this.p, true);
58
+ this.p += 4;
59
+ return v;
60
+ }
61
+ i32() {
62
+ this.need(4);
63
+ const v = this.view.getInt32(this.p, true);
64
+ this.p += 4;
65
+ return v;
66
+ }
67
+ f32() {
68
+ this.need(4);
69
+ const v = this.view.getFloat32(this.p, true);
70
+ this.p += 4;
71
+ return Number.isFinite(v) ? v : 0;
72
+ }
73
+ vec(n) {
74
+ const out = [];
75
+ for (let i = 0; i < n; i++)
76
+ out.push(this.f32());
77
+ return out;
78
+ }
79
+ skip(n) {
80
+ this.need(n);
81
+ this.p += n;
82
+ }
83
+ /** An index of `size` bytes: signed (-1 means none) for bones, textures and the like, unsigned for vertices. */
84
+ index(size, signed) {
85
+ if (size === 1)
86
+ return signed ? this.i8() : this.u8();
87
+ if (size === 2)
88
+ return signed ? this.i16() : this.u16();
89
+ return this.i32();
90
+ }
91
+ /** A fixed-width Shift-JIS field, cut at the first zero byte. */
92
+ fixed(n) {
93
+ this.need(n);
94
+ let end = 0;
95
+ while (end < n && this.bytes[this.p + end] !== 0)
96
+ end++;
97
+ const s = decode(this.bytes.subarray(this.p, this.p + end), 'shift_jis');
98
+ this.p += n;
99
+ return s;
100
+ }
101
+ /** A PMX text: a 32-bit byte length and the characters in the model's encoding. */
102
+ text() {
103
+ const n = this.i32();
104
+ if (n < 0)
105
+ fail('syntax', 'negative text length');
106
+ this.need(n, 'a text');
107
+ const s = decode(this.bytes.subarray(this.p, this.p + n), this.utf16 ? 'utf-16le' : 'utf-8');
108
+ this.p += n;
109
+ return s;
110
+ }
111
+ }
112
+ function decode(bytes, label) {
113
+ try {
114
+ return new TextDecoder(label).decode(bytes);
115
+ }
116
+ catch {
117
+ let s = '';
118
+ for (const b of bytes)
119
+ s += String.fromCharCode(b);
120
+ return s;
121
+ }
122
+ }
123
+ function conversion(options) {
124
+ const scale = options.scale ?? 0.08, rh = options.rightHanded ?? true;
125
+ if (!(scale > 0) || !Number.isFinite(scale))
126
+ throw new LoaderError(F, 'range', 'scale must be positive and finite');
127
+ const maxVertices = options.maxVertices ?? DEFAULT_MAX_VERTICES, maxTriangles = options.maxTriangles ?? DEFAULT_MAX_TRIANGLES;
128
+ for (const [k, v] of Object.entries({ maxVertices, maxTriangles }))
129
+ if (!Number.isSafeInteger(v) || v < 0)
130
+ throw new LoaderError(F, 'range', `${k} must be a non-negative integer`);
131
+ return {
132
+ scale,
133
+ rh,
134
+ maxVertices,
135
+ maxTriangles,
136
+ point: (v) => [v[0] * scale, v[1] * scale, (rh ? 0 - v[2] : v[2]) * scale],
137
+ dir: (v) => [v[0], v[1], rh ? 0 - v[2] : v[2]],
138
+ // Euler angles mirror like an axis does: x and y turn the other way.
139
+ euler: (v) => (rh ? [0 - v[0], 0 - v[1], v[2]] : [v[0], v[1], v[2]]),
140
+ quat: (q) => rh ? [0 - q[0], 0 - q[1], q[2], q[3]] : [q[0], q[1], q[2], q[3]],
141
+ size: (v) => [v[0] * scale, v[1] * scale, v[2] * scale],
142
+ };
143
+ }
144
+ /** Common tail of both model parsers: triangles into a geometry with one group per material. */
145
+ function geometryOf(positions, normals, uvs, faces, materials, c, vertexCount) {
146
+ if (faces.length % 3)
147
+ fail('syntax', `${faces.length} face indices is not a multiple of 3`);
148
+ if (faces.length / 3 > c.maxTriangles)
149
+ fail('limit', `triangle count ${faces.length / 3} exceeds the limit of ${c.maxTriangles}`);
150
+ for (let i = 0; i < faces.length; i++)
151
+ if (faces[i] >= vertexCount)
152
+ fail('range', `face index ${faces[i]} is past the ${vertexCount} vertices`);
153
+ const indices = new Uint32Array(faces.length);
154
+ for (let i = 0; i < faces.length; i += 3) {
155
+ indices[i] = faces[i];
156
+ indices[i + 1] = c.rh ? faces[i + 2] : faces[i + 1];
157
+ indices[i + 2] = c.rh ? faces[i + 1] : faces[i + 2];
158
+ }
159
+ const groups = [];
160
+ let start = 0;
161
+ materials.forEach((m, i) => {
162
+ const count = m.triangles * 3;
163
+ if (start + count > indices.length)
164
+ fail('range', `material ${i} covers faces past the face list`);
165
+ groups.push({ start, count, name: m.name, properties: { materialIndex: i } });
166
+ start += count;
167
+ });
168
+ const geometry = { kind: 'mesh', positions, normals, uvs, indices };
169
+ if (groups.length)
170
+ geometry.groups = groups;
171
+ return geometry;
172
+ }
173
+ // ---- PMD ------------------------------------------------------------------------------------------------------------
174
+ /**
175
+ * Parses a PMD model (Polygon Model Data 1.0): vertices with two-bone weights, triangles by material, bones and IK,
176
+ * morphs, the optional English names, and rigid bodies and joints as data. Shift-JIS names are decoded with
177
+ * `TextDecoder('shift_jis')`.
178
+ */
179
+ export function parsePMD(input, options = {}) {
180
+ const c = conversion(options), bytes = toBytes(input, F), r = new Reader(bytes, true);
181
+ if (bytes.length < 283 || bytes[0] !== 0x50 || bytes[1] !== 0x6d || bytes[2] !== 0x64)
182
+ throw new LoaderError(F, 'header', 'missing the "Pmd" signature');
183
+ r.p = 3;
184
+ const version = r.f32();
185
+ if (version !== 1)
186
+ fail('unsupported', `PMD version ${version} is not 1.0`);
187
+ const name = r.fixed(20), comment = r.fixed(256);
188
+ const nv = r.u32();
189
+ if (nv > c.maxVertices)
190
+ fail('limit', `vertex count ${nv} exceeds the limit of ${c.maxVertices}`);
191
+ r.records(nv, 38, 'vertices');
192
+ const positions = new Float32Array(nv * 3), normals = new Float32Array(nv * 3), uvs = new Float32Array(nv * 2), joints = new Uint16Array(nv * 4), weights = new Float32Array(nv * 4), edgeScale = new Float32Array(nv);
193
+ for (let i = 0; i < nv; i++) {
194
+ positions.set(c.point(r.vec(3)), i * 3);
195
+ normals.set(c.dir(r.vec(3)), i * 3);
196
+ uvs.set(r.vec(2), i * 2);
197
+ joints[i * 4] = r.u16();
198
+ joints[i * 4 + 1] = r.u16();
199
+ const w = Math.min(100, r.u8()) / 100;
200
+ weights[i * 4] = w;
201
+ weights[i * 4 + 1] = 1 - w;
202
+ edgeScale[i] = r.u8() ? 0 : 1; // edge_flag 1 turns the outline off for the vertex
203
+ }
204
+ const nf = r.u32();
205
+ r.records(nf, 2, 'face indices');
206
+ const faces = new Uint32Array(nf);
207
+ for (let i = 0; i < nf; i++)
208
+ faces[i] = r.u16();
209
+ const nm = r.u32();
210
+ r.records(nm, 70, 'materials');
211
+ const materials = [];
212
+ for (let i = 0; i < nm; i++) {
213
+ const diffuse = r.vec(4), power = r.f32(), specular = r.vec(3), ambient = r.vec(3), toon = r.u8(), edge = r.u8() !== 0, count = r.u32(), tex = r.fixed(20).split('*');
214
+ if (count % 3)
215
+ fail('syntax', `material ${i} has ${count} indices`);
216
+ const m = {
217
+ name: `material_${i}`,
218
+ nameEnglish: '',
219
+ diffuse: diffuse,
220
+ specular: specular,
221
+ specularPower: power,
222
+ ambient: ambient,
223
+ doubleSided: diffuse[3] < 0.9999,
224
+ edge,
225
+ edgeColor: [0, 0, 0, 1],
226
+ edgeSize: 1,
227
+ sphereMode: 0,
228
+ toon: toon === 255 ? undefined : toon,
229
+ triangles: count / 3,
230
+ };
231
+ if (tex[0])
232
+ m.texture = tex[0];
233
+ if (tex[1]) {
234
+ m.sphere = tex[1];
235
+ m.sphereMode = /\.spa$/i.test(tex[1]) ? 2 : 1;
236
+ }
237
+ materials.push(m);
238
+ }
239
+ const geometry = geometryOf(positions, normals, uvs, faces, materials, c, nv);
240
+ geometry.attributes = { edgeScale };
241
+ const nb = r.u16();
242
+ r.records(nb, 39, 'bones');
243
+ const bones = [];
244
+ for (let i = 0; i < nb; i++) {
245
+ const bn = r.fixed(20), parent = r.u16(), tail = r.u16(), type = r.u8();
246
+ r.u16(); // IK parent
247
+ const pos = r.vec(3);
248
+ bones.push({
249
+ name: bn,
250
+ nameEnglish: '',
251
+ position: c.point(pos),
252
+ parent: parent === 0xffff ? -1 : parent,
253
+ layer: 0,
254
+ rotatable: type !== 7 && type !== 8,
255
+ translatable: type === 1,
256
+ visible: type !== 7,
257
+ type,
258
+ tail: tail === 0xffff || tail === 0 ? -1 : tail,
259
+ inheritRotation: type === 5 || type === 9,
260
+ inheritTranslation: false,
261
+ inherit: -1,
262
+ inheritRate: 1,
263
+ afterPhysics: false,
264
+ });
265
+ }
266
+ for (const [i, b] of bones.entries()) {
267
+ if (b.parent >= nb)
268
+ fail('range', `bone ${i} has parent ${b.parent} of ${nb}`);
269
+ if (b.tail >= nb)
270
+ b.tail = -1;
271
+ }
272
+ const nik = r.u16();
273
+ r.records(nik, 11, 'IK chains');
274
+ for (let i = 0; i < nik; i++) {
275
+ const bone = r.u16(), target = r.u16(), chain = r.u8(), iterations = r.u16(), limit = r.f32();
276
+ r.records(chain, 2, 'IK links');
277
+ const links = [];
278
+ for (let k = 0; k < chain; k++) {
279
+ const l = r.u16();
280
+ if (l >= nb)
281
+ fail('range', `IK link ${l} of ${nb} bones`);
282
+ links.push({ bone: l });
283
+ }
284
+ if (bone >= nb || target >= nb)
285
+ fail('range', `IK chain ${i} names a bone past ${nb}`);
286
+ bones[bone].ik = { target, iterations, limitAngle: limit, links };
287
+ }
288
+ const nmo = r.u16();
289
+ const morphs = [];
290
+ r.records(nmo, 25, 'morphs');
291
+ for (let i = 0; i < nmo; i++) {
292
+ const mn = r.fixed(20), count = r.u32(), panel = r.u8();
293
+ r.records(count, 16, 'morph offsets');
294
+ const offsets = [];
295
+ for (let k = 0; k < count; k++) {
296
+ const vertex = r.u32();
297
+ const o = r.vec(3);
298
+ if (vertex >= nv && panel !== 0)
299
+ fail('range', `morph ${i} names vertex ${vertex} of ${nv}`);
300
+ offsets.push({ vertex, offset: c.point(o) });
301
+ }
302
+ // The first morph ("base") lists the vertices the others index into; it is kept as a vertex morph.
303
+ morphs.push({ name: mn, nameEnglish: '', panel, type: 'vertex', offsets });
304
+ }
305
+ // Display lists: morph panel, bone group names, bone display frames: parsed past, not kept.
306
+ const nd = r.u8();
307
+ r.skip(nd * 2);
308
+ const ng = r.u8();
309
+ r.skip(ng * 50);
310
+ const ndisp = r.u32();
311
+ r.records(ndisp, 3, 'bone display entries');
312
+ r.skip(ndisp * 3);
313
+ let nameEnglish = '', commentEnglish = '';
314
+ const warnings = [];
315
+ if (r.left > 0 && r.u8() === 1) {
316
+ nameEnglish = r.fixed(20);
317
+ commentEnglish = r.fixed(256);
318
+ for (let i = 0; i < nb; i++)
319
+ bones[i].nameEnglish = r.fixed(20);
320
+ for (let i = 1; i < nmo; i++)
321
+ morphs[i].nameEnglish = r.fixed(20);
322
+ r.skip(Math.max(0, ng) * 50);
323
+ }
324
+ if (r.left >= 1000)
325
+ r.skip(1000); // toon texture names
326
+ const rigidBodies = [], joints_ = [];
327
+ if (r.left >= 4) {
328
+ const nr = r.u32();
329
+ r.records(nr, 83, 'rigid bodies');
330
+ for (let i = 0; i < nr; i++) {
331
+ const rn = r.fixed(20), bone = r.u16(), group = r.u8(), noCollide = r.u16(), shape = r.u8(), size = r.vec(3), pos = r.vec(3), rot = r.vec(3), mass = r.f32(), ld = r.f32(), ad = r.f32(), rest = r.f32(), fr = r.f32(), type = r.u8();
332
+ rigidBodies.push({
333
+ name: rn,
334
+ nameEnglish: '',
335
+ bone: bone === 0xffff ? -1 : bone,
336
+ group,
337
+ noCollide,
338
+ shape: ['sphere', 'box', 'capsule'][shape] ?? 'sphere',
339
+ size: c.size(size),
340
+ position: c.point(pos),
341
+ rotation: c.euler(rot),
342
+ mass,
343
+ linearDamping: ld,
344
+ angularDamping: ad,
345
+ restitution: rest,
346
+ friction: fr,
347
+ mode: ['bone', 'physics', 'physicsBone'][type] ?? 'bone',
348
+ });
349
+ }
350
+ }
351
+ if (r.left >= 4) {
352
+ const nj = r.u32();
353
+ r.records(nj, 124, 'joints');
354
+ for (let i = 0; i < nj; i++) {
355
+ const jn = r.fixed(20), a = r.u32(), b = r.u32();
356
+ const v = (n) => r.vec(n);
357
+ joints_.push({
358
+ name: jn,
359
+ nameEnglish: '',
360
+ type: 0,
361
+ bodyA: a,
362
+ bodyB: b,
363
+ position: c.point(v(3)),
364
+ rotation: c.euler(v(3)),
365
+ limitPositionMin: c.size(v(3)),
366
+ limitPositionMax: c.size(v(3)),
367
+ limitRotationMin: v(3),
368
+ limitRotationMax: v(3),
369
+ springPosition: v(3),
370
+ springRotation: v(3),
371
+ });
372
+ }
373
+ }
374
+ return {
375
+ format: 'PMD',
376
+ version,
377
+ name,
378
+ nameEnglish,
379
+ comment,
380
+ commentEnglish,
381
+ geometry,
382
+ joints,
383
+ weights,
384
+ materials,
385
+ textures: [],
386
+ bones,
387
+ morphs,
388
+ rigidBodies,
389
+ joints_,
390
+ warnings,
391
+ };
392
+ }
393
+ // ---- PMX ------------------------------------------------------------------------------------------------------------
394
+ /**
395
+ * Parses a PMX 2.0 or 2.1 model: vertices with BDEF1, BDEF2, BDEF4, SDEF and QDEF weights and up to four extra UV sets,
396
+ * the texture table, materials with edge, sphere and toon settings, bones with IK, grants and axes, every morph kind,
397
+ * and rigid bodies and joints as data. Soft bodies (2.1) are not read. Index sizes of 1, 2 and 4 bytes are honoured.
398
+ */
399
+ export function parsePMX(input, options = {}) {
400
+ const c = conversion(options), bytes = toBytes(input, F);
401
+ if (bytes.length < 17 || bytes[0] !== 0x50 || bytes[1] !== 0x4d || bytes[2] !== 0x58 || bytes[3] !== 0x20)
402
+ throw new LoaderError(F, 'header', 'missing the "PMX " signature');
403
+ const probe = new Reader(bytes, false);
404
+ probe.p = 4;
405
+ const version = probe.f32();
406
+ if (version < 2 || version >= 3)
407
+ fail('unsupported', `PMX version ${version} is not 2.x`);
408
+ const nGlobals = probe.u8();
409
+ if (nGlobals < 8)
410
+ fail('header', `${nGlobals} globals, 8 needed`);
411
+ const g = Array.from({ length: nGlobals }, () => probe.u8());
412
+ const [encoding, extraUV, vSize, tSize, mSize, bSize, moSize, rSize] = g;
413
+ if (encoding > 1)
414
+ fail('header', `text encoding ${encoding} is not 0 or 1`);
415
+ if (extraUV > 4)
416
+ fail('header', `${extraUV} additional UV sets, 4 at most`);
417
+ for (const s of [vSize, tSize, mSize, bSize, moSize, rSize])
418
+ if (s !== 1 && s !== 2 && s !== 4)
419
+ fail('header', `index size ${s} is not 1, 2 or 4`);
420
+ const r = new Reader(bytes, false, encoding === 0);
421
+ r.p = probe.p;
422
+ const name = r.text(), nameEnglish = r.text(), comment = r.text(), commentEnglish = r.text();
423
+ const nv = r.i32();
424
+ if (nv < 0)
425
+ fail('syntax', 'negative vertex count');
426
+ if (nv > c.maxVertices)
427
+ fail('limit', `vertex count ${nv} exceeds the limit of ${c.maxVertices}`);
428
+ r.records(nv, 38 + extraUV * 16, 'vertices');
429
+ const positions = new Float32Array(nv * 3), normals = new Float32Array(nv * 3), uvs = new Float32Array(nv * 2), joints = new Uint16Array(nv * 4), weights = new Float32Array(nv * 4), edgeScale = new Float32Array(nv), extra = Array.from({ length: extraUV }, () => new Float32Array(nv * 4));
430
+ const sdefVertices = [], sdefData = [];
431
+ for (let i = 0; i < nv; i++) {
432
+ positions.set(c.point(r.vec(3)), i * 3);
433
+ normals.set(c.dir(r.vec(3)), i * 3);
434
+ uvs.set(r.vec(2), i * 2);
435
+ for (let k = 0; k < extraUV; k++)
436
+ extra[k].set(r.vec(4), i * 4);
437
+ const type = r.u8();
438
+ const bone = () => Math.max(0, r.index(bSize, true));
439
+ if (type === 0) {
440
+ joints[i * 4] = bone();
441
+ weights[i * 4] = 1;
442
+ }
443
+ else if (type === 1 || type === 3) {
444
+ joints[i * 4] = bone();
445
+ joints[i * 4 + 1] = bone();
446
+ const w = Math.min(1, Math.max(0, r.f32()));
447
+ weights[i * 4] = w;
448
+ weights[i * 4 + 1] = 1 - w;
449
+ if (type === 3) {
450
+ const cc = r.vec(3), r0 = r.vec(3), r1 = r.vec(3);
451
+ sdefVertices.push(i);
452
+ sdefData.push(...c.point(cc), ...c.point(r0), ...c.point(r1));
453
+ }
454
+ }
455
+ else if (type === 2 || type === 4) {
456
+ for (let k = 0; k < 4; k++)
457
+ joints[i * 4 + k] = bone();
458
+ for (let k = 0; k < 4; k++)
459
+ weights[i * 4 + k] = Math.max(0, r.f32());
460
+ }
461
+ else
462
+ fail('syntax', `vertex ${i} has weight type ${type}`);
463
+ edgeScale[i] = r.f32();
464
+ }
465
+ const nf = r.i32();
466
+ if (nf < 0)
467
+ fail('syntax', 'negative face count');
468
+ r.records(nf, vSize, 'face indices');
469
+ if (nf % 3)
470
+ fail('syntax', `${nf} face indices is not a multiple of 3`);
471
+ const faces = new Uint32Array(nf);
472
+ for (let i = 0; i < nf; i++)
473
+ faces[i] = r.index(vSize, false) >>> 0;
474
+ const ntex = r.i32();
475
+ r.records(ntex, 4, 'textures');
476
+ const textures = [];
477
+ for (let i = 0; i < ntex; i++)
478
+ textures.push(r.text());
479
+ const texture = (i) => {
480
+ if (i < 0)
481
+ return undefined;
482
+ if (i >= textures.length)
483
+ fail('range', `texture ${i} of ${textures.length}`);
484
+ return textures[i];
485
+ };
486
+ const nm = r.i32();
487
+ r.records(nm, 60, 'materials');
488
+ const materials = [];
489
+ for (let i = 0; i < nm; i++) {
490
+ const mn = r.text(), me = r.text(), diffuse = r.vec(4), specular = r.vec(3), power = r.f32(), ambient = r.vec(3), flags = r.u8(), edgeColor = r.vec(4), edgeSize = r.f32(), tex = r.index(tSize, true), sph = r.index(tSize, true), sphereMode = r.u8(), shared = r.u8();
491
+ const toon = shared ? r.u8() : r.index(tSize, true);
492
+ r.text(); // memo
493
+ const count = r.i32();
494
+ if (count < 0 || count % 3)
495
+ fail('syntax', `material ${i} has ${count} indices`);
496
+ const m = {
497
+ name: mn,
498
+ nameEnglish: me,
499
+ diffuse: diffuse,
500
+ specular: specular,
501
+ specularPower: power,
502
+ ambient: ambient,
503
+ doubleSided: !!(flags & 1),
504
+ edge: !!(flags & 16),
505
+ edgeColor: edgeColor,
506
+ edgeSize,
507
+ sphereMode,
508
+ triangles: count / 3,
509
+ };
510
+ const t = texture(tex);
511
+ if (t)
512
+ m.texture = t;
513
+ const s = texture(sph);
514
+ if (s)
515
+ m.sphere = s;
516
+ if (shared)
517
+ m.toon = toon;
518
+ else if (toon >= 0)
519
+ m.toon = texture(toon);
520
+ materials.push(m);
521
+ }
522
+ const geometry = geometryOf(positions, normals, uvs, faces, materials, c, nv);
523
+ geometry.attributes = { edgeScale };
524
+ extra.forEach((a, k) => (geometry.attributes[`uv${k + 1}`] = a));
525
+ const nb = r.i32();
526
+ r.records(nb, 20, 'bones');
527
+ const bones = [];
528
+ const checkBone = (b, what) => {
529
+ if (b < -1 || b >= nb)
530
+ fail('range', `${what} names bone ${b} of ${nb}`);
531
+ return b;
532
+ };
533
+ for (let i = 0; i < nb; i++) {
534
+ const bn = r.text(), be = r.text(), pos = r.vec(3), parent = r.index(bSize, true), layer = r.i32(), flags = r.u16();
535
+ const bone = {
536
+ name: bn,
537
+ nameEnglish: be,
538
+ position: c.point(pos),
539
+ parent: parent,
540
+ layer,
541
+ rotatable: !!(flags & 2),
542
+ translatable: !!(flags & 4),
543
+ visible: !!(flags & 8),
544
+ type: -1,
545
+ tail: -1,
546
+ inheritRotation: !!(flags & 0x100),
547
+ inheritTranslation: !!(flags & 0x200),
548
+ inherit: -1,
549
+ inheritRate: 1,
550
+ afterPhysics: !!(flags & 0x1000),
551
+ };
552
+ if (flags & 1)
553
+ bone.tail = r.index(bSize, true);
554
+ else
555
+ bone.tailOffset = c.point(r.vec(3));
556
+ if (flags & 0x300) {
557
+ bone.inherit = r.index(bSize, true);
558
+ bone.inheritRate = r.f32();
559
+ }
560
+ if (flags & 0x400)
561
+ r.skip(12);
562
+ if (flags & 0x800)
563
+ r.skip(24);
564
+ if (flags & 0x2000)
565
+ r.skip(4);
566
+ if (flags & 0x20) {
567
+ const target = r.index(bSize, true), iterations = r.i32(), limitAngle = r.f32(), links = r.i32();
568
+ r.records(links, bSize + 1, 'IK links');
569
+ const out = [];
570
+ for (let k = 0; k < links; k++) {
571
+ const lb = r.index(bSize, true);
572
+ const link = { bone: lb };
573
+ if (r.u8())
574
+ link.limit = { min: r.vec(3), max: r.vec(3) };
575
+ out.push(link);
576
+ }
577
+ bone.ik = { target, iterations, limitAngle, links: out };
578
+ }
579
+ bones.push(bone);
580
+ }
581
+ bones.forEach((b, i) => {
582
+ checkBone(b.parent, `bone ${i} parent`);
583
+ if (b.tail >= nb)
584
+ fail('range', `bone ${i} tail ${b.tail} of ${nb}`);
585
+ checkBone(b.inherit, `bone ${i} inherit`);
586
+ if (b.ik) {
587
+ checkBone(b.ik.target, `bone ${i} IK target`);
588
+ b.ik.links.forEach((l) => checkBone(l.bone, `bone ${i} IK link`));
589
+ }
590
+ });
591
+ for (let i = 0; i < nv; i++)
592
+ for (let k = 0; k < 4; k++)
593
+ if (joints[i * 4 + k] >= Math.max(nb, 1))
594
+ fail('range', `vertex ${i} is skinned to bone ${joints[i * 4 + k]} of ${nb}`);
595
+ const nmo = r.i32();
596
+ r.records(nmo, 10, 'morphs');
597
+ const morphs = [];
598
+ const TYPES = ['group', 'vertex', 'bone', 'uv', 'uv1', 'uv2', 'uv3', 'uv4', 'material', 'flip', 'impulse'];
599
+ for (let i = 0; i < nmo; i++) {
600
+ const mn = r.text(), me = r.text(), panel = r.u8(), kind = r.u8(), count = r.i32();
601
+ const type = TYPES[kind];
602
+ if (!type)
603
+ fail('syntax', `morph ${i} has type ${kind}`);
604
+ r.records(count, 5, 'morph offsets');
605
+ const offsets = [];
606
+ for (let k = 0; k < count; k++) {
607
+ switch (type) {
608
+ case 'group':
609
+ case 'flip':
610
+ offsets.push({ morph: r.index(moSize, true), rate: r.f32() });
611
+ break;
612
+ case 'vertex': {
613
+ const vertex = r.index(vSize, false) >>> 0;
614
+ if (vertex >= nv)
615
+ fail('range', `morph ${i} names vertex ${vertex} of ${nv}`);
616
+ offsets.push({ vertex, offset: c.point(r.vec(3)) });
617
+ break;
618
+ }
619
+ case 'bone':
620
+ offsets.push({ bone: r.index(bSize, true), translation: c.point(r.vec(3)), rotation: c.quat(r.vec(4)) });
621
+ break;
622
+ case 'material': {
623
+ const material = r.index(mSize, true), op = r.u8();
624
+ offsets.push({
625
+ material,
626
+ operation: op === 0 ? 'multiply' : 'add',
627
+ diffuse: r.vec(4),
628
+ specular: r.vec(3),
629
+ specularPower: r.f32(),
630
+ ambient: r.vec(3),
631
+ edgeColor: r.vec(4),
632
+ edgeSize: r.f32(),
633
+ texture: r.vec(4),
634
+ sphere: r.vec(4),
635
+ toon: r.vec(4),
636
+ });
637
+ break;
638
+ }
639
+ case 'impulse':
640
+ offsets.push({
641
+ rigidBody: r.index(rSize, true),
642
+ local: r.u8() !== 0,
643
+ velocity: c.point(r.vec(3)),
644
+ torque: r.vec(3),
645
+ });
646
+ break;
647
+ default: {
648
+ // uv, uv1 .. uv4
649
+ const vertex = r.index(vSize, false) >>> 0;
650
+ if (vertex >= nv)
651
+ fail('range', `morph ${i} names vertex ${vertex} of ${nv}`);
652
+ offsets.push({ vertex, offset: r.vec(4) });
653
+ }
654
+ }
655
+ }
656
+ morphs.push({ name: mn, nameEnglish: me, panel, type, offsets });
657
+ }
658
+ // Display frames: names and entries, parsed past.
659
+ const ndf = r.i32();
660
+ r.records(ndf, 10, 'display frames');
661
+ for (let i = 0; i < ndf; i++) {
662
+ r.text();
663
+ r.text();
664
+ r.u8();
665
+ const n = r.i32();
666
+ r.records(n, 1 + Math.min(bSize, moSize), 'display entries');
667
+ for (let k = 0; k < n; k++)
668
+ r.index(r.u8() === 0 ? bSize : moSize, true);
669
+ }
670
+ const rigidBodies = [], joints_ = [];
671
+ const warnings = [];
672
+ if (r.left >= 4) {
673
+ const nr = r.i32();
674
+ r.records(nr, 60, 'rigid bodies');
675
+ for (let i = 0; i < nr; i++) {
676
+ const rn = r.text(), re = r.text(), bone = r.index(bSize, true), group = r.u8(), noCollide = r.u16(), shape = r.u8(), size = r.vec(3), pos = r.vec(3), rot = r.vec(3), mass = r.f32(), ld = r.f32(), ad = r.f32(), rest = r.f32(), fr = r.f32(), mode = r.u8();
677
+ rigidBodies.push({
678
+ name: rn,
679
+ nameEnglish: re,
680
+ bone: checkBone(bone, `rigid body ${i}`),
681
+ group,
682
+ noCollide,
683
+ shape: ['sphere', 'box', 'capsule'][shape] ?? 'sphere',
684
+ size: c.size(size),
685
+ position: c.point(pos),
686
+ rotation: c.euler(rot),
687
+ mass,
688
+ linearDamping: ld,
689
+ angularDamping: ad,
690
+ restitution: rest,
691
+ friction: fr,
692
+ mode: ['bone', 'physics', 'physicsBone'][mode] ?? 'bone',
693
+ });
694
+ }
695
+ }
696
+ if (r.left >= 4) {
697
+ const nj = r.i32();
698
+ r.records(nj, 100, 'joints');
699
+ for (let i = 0; i < nj; i++) {
700
+ const jn = r.text(), je = r.text(), type = r.u8(), a = r.index(rSize, true), b = r.index(rSize, true);
701
+ const v = (n) => r.vec(n);
702
+ if (a >= rigidBodies.length || b >= rigidBodies.length)
703
+ fail('range', `joint ${i} names a rigid body past ${rigidBodies.length}`);
704
+ joints_.push({
705
+ name: jn,
706
+ nameEnglish: je,
707
+ type,
708
+ bodyA: a,
709
+ bodyB: b,
710
+ position: c.point(v(3)),
711
+ rotation: c.euler(v(3)),
712
+ limitPositionMin: c.size(v(3)),
713
+ limitPositionMax: c.size(v(3)),
714
+ limitRotationMin: v(3),
715
+ limitRotationMax: v(3),
716
+ springPosition: v(3),
717
+ springRotation: v(3),
718
+ });
719
+ }
720
+ }
721
+ if (r.left > 0)
722
+ warnings.push(`${r.left} bytes after the joints (soft bodies of PMX 2.1) are not read`);
723
+ const out = {
724
+ format: 'PMX',
725
+ version,
726
+ name,
727
+ nameEnglish,
728
+ comment,
729
+ commentEnglish,
730
+ geometry,
731
+ joints,
732
+ weights,
733
+ materials,
734
+ textures,
735
+ bones,
736
+ morphs,
737
+ rigidBodies,
738
+ joints_,
739
+ warnings,
740
+ };
741
+ if (sdefVertices.length)
742
+ out.sdef = { vertices: Uint32Array.from(sdefVertices), data: Float32Array.from(sdefData) };
743
+ return out;
744
+ }
745
+ /** Reads a PMD or a PMX file, by its signature. */
746
+ export function parseMMD(input, options = {}) {
747
+ const bytes = toBytes(input, F);
748
+ if (bytes.length >= 4 && bytes[0] === 0x50 && bytes[1] === 0x4d && bytes[2] === 0x58 && bytes[3] === 0x20)
749
+ return parsePMX(bytes, options);
750
+ if (bytes.length >= 3 && bytes[0] === 0x50 && bytes[1] === 0x6d && bytes[2] === 0x64)
751
+ return parsePMD(bytes, options);
752
+ throw new LoaderError(F, 'header', 'not a PMD or PMX file');
753
+ }
754
+ /** Parses a VMD motion or camera clip: bone, morph, camera, light, shadow and IK keys. Tracks are grouped by name. */
755
+ export function parseVMD(input, options = {}) {
756
+ const bytes = toBytes(input, F);
757
+ const c = conversion({ scale: options.scale, rightHanded: options.rightHanded });
758
+ const maxKeys = options.maxKeys ?? 2_000_000;
759
+ if (!Number.isSafeInteger(maxKeys) || maxKeys < 0)
760
+ throw new LoaderError(F, 'range', 'maxKeys must be a non-negative integer');
761
+ const header = decode(bytes.subarray(0, Math.min(30, bytes.length)), 'ascii');
762
+ if (!header.startsWith('Vocaloid Motion Data'))
763
+ throw new LoaderError(F, 'header', 'missing the "Vocaloid Motion Data" signature');
764
+ const v2 = header.startsWith('Vocaloid Motion Data 0002');
765
+ const r = new Reader(bytes, true);
766
+ r.p = 30;
767
+ const modelName = r.fixed(v2 ? 20 : 10);
768
+ const section = (size, what) => {
769
+ if (r.left < 4)
770
+ return 0; // older files end early
771
+ const n = r.u32();
772
+ if (n > maxKeys)
773
+ fail('limit', `${n} ${what} keys exceed the limit of ${maxKeys}`);
774
+ return r.records(n, size, `${what} keys`);
775
+ };
776
+ const lists = new Map();
777
+ const nb = section(111, 'bone');
778
+ const boneStart = r.p;
779
+ for (let i = 0; i < nb; i++) {
780
+ const name = r.fixed(15), frame = r.u32(), at = r.p;
781
+ r.skip(92 - 0);
782
+ let list = lists.get(name);
783
+ if (!list)
784
+ lists.set(name, (list = []));
785
+ list.push({ frame, at });
786
+ }
787
+ void boneStart;
788
+ const bones = [];
789
+ let duration = 0;
790
+ const view = r.view;
791
+ for (const [name, list] of lists) {
792
+ list.sort((a, b) => a.frame - b.frame);
793
+ const n = list.length;
794
+ const track = {
795
+ name,
796
+ frames: new Uint32Array(n),
797
+ positions: new Float32Array(n * 3),
798
+ rotations: new Float32Array(n * 4),
799
+ interpolation: new Uint8Array(n * 64),
800
+ };
801
+ list.forEach(({ frame, at }, i) => {
802
+ track.frames[i] = frame;
803
+ duration = Math.max(duration, frame);
804
+ const f = (k) => {
805
+ const v = view.getFloat32(at + k * 4, true);
806
+ return Number.isFinite(v) ? v : 0;
807
+ };
808
+ track.positions.set(c.point([f(0), f(1), f(2)]), i * 3);
809
+ track.rotations.set(c.quat([f(3), f(4), f(5), f(6)]), i * 4);
810
+ track.interpolation.set(bytes.subarray(at + 28, at + 92), i * 64);
811
+ });
812
+ bones.push(track);
813
+ }
814
+ const morphLists = new Map();
815
+ const nm = section(23, 'morph');
816
+ for (let i = 0; i < nm; i++) {
817
+ const name = r.fixed(15), frame = r.u32(), weight = r.f32();
818
+ let list = morphLists.get(name);
819
+ if (!list)
820
+ morphLists.set(name, (list = []));
821
+ list.push({ frame, weight });
822
+ }
823
+ const morphs = [];
824
+ for (const [name, list] of morphLists) {
825
+ list.sort((a, b) => a.frame - b.frame);
826
+ morphs.push({
827
+ name,
828
+ frames: Uint32Array.from(list, (k) => k.frame),
829
+ weights: Float32Array.from(list, (k) => k.weight),
830
+ });
831
+ duration = Math.max(duration, list[list.length - 1].frame);
832
+ }
833
+ let camera;
834
+ const nc = section(61, 'camera');
835
+ if (nc) {
836
+ const keys = [];
837
+ for (let i = 0; i < nc; i++) {
838
+ const frame = r.u32(), d = r.f32(), p = r.vec(3), rot = r.vec(3);
839
+ const interp = bytes.slice(r.p, r.p + 24);
840
+ r.skip(24);
841
+ const fov = r.u32(), persp = r.u8();
842
+ keys.push({ frame, d, p, rot, interp, fov, persp });
843
+ }
844
+ keys.sort((a, b) => a.frame - b.frame);
845
+ camera = {
846
+ frames: Uint32Array.from(keys, (k) => k.frame),
847
+ distance: Float32Array.from(keys, (k) => k.d * c.scale),
848
+ position: new Float32Array(keys.length * 3),
849
+ rotation: new Float32Array(keys.length * 3),
850
+ fov: Float32Array.from(keys, (k) => (k.fov * Math.PI) / 180),
851
+ perspective: Uint8Array.from(keys, (k) => (k.persp === 0 ? 1 : 0)),
852
+ interpolation: new Uint8Array(keys.length * 24),
853
+ };
854
+ keys.forEach((k, i) => {
855
+ camera.position.set(c.point(k.p), i * 3);
856
+ camera.rotation.set(c.euler(k.rot), i * 3);
857
+ camera.interpolation.set(k.interp, i * 24);
858
+ });
859
+ duration = Math.max(duration, keys[keys.length - 1].frame);
860
+ }
861
+ const lights = [];
862
+ const nl = section(28, 'light');
863
+ for (let i = 0; i < nl; i++)
864
+ lights.push({ frame: r.u32(), color: r.vec(3), position: c.dir(r.vec(3)) });
865
+ const shadows = [];
866
+ const ns = section(9, 'shadow');
867
+ for (let i = 0; i < ns; i++)
868
+ shadows.push({ frame: r.u32(), mode: r.u8(), distance: r.f32() });
869
+ const ik = [];
870
+ const ni = section(9, 'IK');
871
+ for (let i = 0; i < ni; i++) {
872
+ const frame = r.u32(), show = r.u8() !== 0, n = r.u32();
873
+ r.records(n, 21, 'IK states');
874
+ const states = [];
875
+ for (let k = 0; k < n; k++)
876
+ states.push({ name: r.fixed(20), enabled: r.u8() !== 0 });
877
+ ik.push({ frame, show, states });
878
+ }
879
+ return { modelName, fps: 30, bones, morphs, camera, lights, shadows, ik, duration };
880
+ }
881
+ /** A cubic Bezier easing through (0,0), (x1,y1), (x2,y2) and (1,1), with the control values 0 to 127 as VMD stores them. */
882
+ export function vmdBezier(x1, y1, x2, y2, t) {
883
+ if (t <= 0)
884
+ return 0;
885
+ if (t >= 1)
886
+ return 1;
887
+ const ax = x1 / 127, ay = y1 / 127, bx = x2 / 127, by = y2 / 127;
888
+ const at = (a, b, s) => 3 * a * s * (1 - s) * (1 - s) + 3 * b * s * s * (1 - s) + s * s * s;
889
+ let lo = 0, hi = 1;
890
+ for (let i = 0; i < 24; i++) {
891
+ const mid = (lo + hi) / 2;
892
+ if (at(ax, bx, mid) < t)
893
+ lo = mid;
894
+ else
895
+ hi = mid;
896
+ }
897
+ return at(ay, by, (lo + hi) / 2);
898
+ }
899
+ /**
900
+ * Samples a bone track at `frame` (fractional frames allowed): position and rotation between the two keys around it,
901
+ * each eased by the later key's Bezier curves (the X, Y, Z and rotation curves are the interleaved first 16 bytes of its
902
+ * `interpolation`: x1, y1, x2, y2 of curve k are at bytes k, k + 4, k + 8, k + 12). Before the first key and after the last
903
+ * it holds that key. Returns `{position, rotation}` in the track's space, or undefined for an empty track.
904
+ */
905
+ export function sampleVMDBone(track, frame) {
906
+ const n = track.frames.length;
907
+ if (!n)
908
+ return undefined;
909
+ const key = (i) => ({
910
+ p: [track.positions[i * 3], track.positions[i * 3 + 1], track.positions[i * 3 + 2]],
911
+ q: [track.rotations[i * 4], track.rotations[i * 4 + 1], track.rotations[i * 4 + 2], track.rotations[i * 4 + 3]],
912
+ });
913
+ if (frame <= track.frames[0])
914
+ return { position: key(0).p, rotation: key(0).q };
915
+ if (frame >= track.frames[n - 1])
916
+ return { position: key(n - 1).p, rotation: key(n - 1).q };
917
+ let lo = 0, hi = n - 1;
918
+ while (hi - lo > 1) {
919
+ const mid = (lo + hi) >> 1;
920
+ if (track.frames[mid] <= frame)
921
+ lo = mid;
922
+ else
923
+ hi = mid;
924
+ }
925
+ const a = key(lo), b = key(hi), t = (frame - track.frames[lo]) / (track.frames[hi] - track.frames[lo]);
926
+ const m = track.interpolation.subarray(hi * 64, hi * 64 + 16);
927
+ const ease = (k) => vmdBezier(m[k], m[4 + k], m[8 + k], m[12 + k], t);
928
+ const position = [
929
+ a.p[0] + (b.p[0] - a.p[0]) * ease(0),
930
+ a.p[1] + (b.p[1] - a.p[1]) * ease(1),
931
+ a.p[2] + (b.p[2] - a.p[2]) * ease(2),
932
+ ];
933
+ // Slerp along the shorter arc, eased by the rotation curve.
934
+ const s = ease(3);
935
+ let [bx, by, bz, bw] = b.q;
936
+ let dot = a.q[0] * bx + a.q[1] * by + a.q[2] * bz + a.q[3] * bw;
937
+ if (dot < 0) {
938
+ dot = -dot;
939
+ bx = -bx;
940
+ by = -by;
941
+ bz = -bz;
942
+ bw = -bw;
943
+ }
944
+ let wa = 1 - s, wb = s;
945
+ if (dot < 0.9995) {
946
+ const theta = Math.acos(dot), sin = Math.sin(theta);
947
+ wa = Math.sin((1 - s) * theta) / sin;
948
+ wb = Math.sin(s * theta) / sin;
949
+ }
950
+ const q = [
951
+ wa * a.q[0] + wb * bx,
952
+ wa * a.q[1] + wb * by,
953
+ wa * a.q[2] + wb * bz,
954
+ wa * a.q[3] + wb * bw,
955
+ ];
956
+ const len = Math.hypot(q[0], q[1], q[2], q[3]) || 1;
957
+ return { position, rotation: [q[0] / len, q[1] / len, q[2] / len, q[3] / len] };
958
+ }