@margoengine/loaders 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1665 -2
  4. package/dist/3dm.d.ts +161 -0
  5. package/dist/3dm.js +289 -0
  6. package/dist/3ds.d.ts +124 -0
  7. package/dist/3ds.js +392 -0
  8. package/dist/acclaim.d.ts +90 -0
  9. package/dist/acclaim.js +312 -0
  10. package/dist/amf.d.ts +45 -0
  11. package/dist/amf.js +256 -0
  12. package/dist/babylon.d.ts +197 -0
  13. package/dist/babylon.js +701 -0
  14. package/dist/common.d.ts +7 -0
  15. package/dist/common.js +6 -0
  16. package/dist/crease.d.ts +7 -0
  17. package/dist/crease.js +67 -0
  18. package/dist/dae-animation.d.ts +66 -0
  19. package/dist/dae-animation.js +266 -0
  20. package/dist/dae-common.d.ts +95 -0
  21. package/dist/dae-common.js +226 -0
  22. package/dist/dae-controllers.d.ts +57 -0
  23. package/dist/dae-controllers.js +164 -0
  24. package/dist/dae-kinematics.d.ts +65 -0
  25. package/dist/dae-kinematics.js +461 -0
  26. package/dist/dae-pose.d.ts +131 -0
  27. package/dist/dae-pose.js +381 -0
  28. package/dist/dae-scene.d.ts +203 -0
  29. package/dist/dae-scene.js +279 -0
  30. package/dist/dae.d.ts +166 -0
  31. package/dist/dae.js +644 -0
  32. package/dist/detect.d.ts +20 -0
  33. package/dist/detect.js +72 -0
  34. package/dist/dxf-hatch.d.ts +8 -0
  35. package/dist/dxf-hatch.js +346 -0
  36. package/dist/dxf-leaders.d.ts +59 -0
  37. package/dist/dxf-leaders.js +258 -0
  38. package/dist/dxf.d.ts +122 -0
  39. package/dist/dxf.js +985 -0
  40. package/dist/engine.d.ts +41 -0
  41. package/dist/engine.js +120 -0
  42. package/dist/font-opentype.d.ts +14 -0
  43. package/dist/font-opentype.js +33 -0
  44. package/dist/font-woff.d.ts +23 -0
  45. package/dist/font-woff.js +293 -0
  46. package/dist/font.d.ts +41 -0
  47. package/dist/font.js +26 -0
  48. package/dist/gcode.d.ts +92 -0
  49. package/dist/gcode.js +369 -0
  50. package/dist/geo-model.d.ts +84 -0
  51. package/dist/geo-model.js +220 -0
  52. package/dist/geo-mvt.d.ts +15 -0
  53. package/dist/geo-mvt.js +302 -0
  54. package/dist/geo-shp.d.ts +15 -0
  55. package/dist/geo-shp.js +234 -0
  56. package/dist/geo-xml.d.ts +6 -0
  57. package/dist/geo-xml.js +165 -0
  58. package/dist/geo.d.ts +8 -0
  59. package/dist/geo.js +59 -0
  60. package/dist/geometry.d.ts +60 -0
  61. package/dist/geometry.js +273 -0
  62. package/dist/index.d.ts +54 -0
  63. package/dist/index.js +28 -0
  64. package/dist/kmz.d.ts +78 -0
  65. package/dist/kmz.js +173 -0
  66. package/dist/las.d.ts +92 -0
  67. package/dist/las.js +110 -0
  68. package/dist/ldraw.d.ts +118 -0
  69. package/dist/ldraw.js +474 -0
  70. package/dist/load.d.ts +72 -0
  71. package/dist/load.js +205 -0
  72. package/dist/lottie.d.ts +154 -0
  73. package/dist/lottie.js +893 -0
  74. package/dist/lwo.d.ts +81 -0
  75. package/dist/lwo.js +454 -0
  76. package/dist/lzf.d.ts +13 -0
  77. package/dist/lzf.js +56 -0
  78. package/dist/materialx.d.ts +120 -0
  79. package/dist/materialx.js +563 -0
  80. package/dist/md2.d.ts +52 -0
  81. package/dist/md2.js +112 -0
  82. package/dist/mmcif.d.ts +14 -0
  83. package/dist/mmcif.js +246 -0
  84. package/dist/mmd.d.ts +244 -0
  85. package/dist/mmd.js +958 -0
  86. package/dist/mocap.d.ts +71 -0
  87. package/dist/mocap.js +178 -0
  88. package/dist/molecule-common.d.ts +4 -0
  89. package/dist/molecule-common.js +54 -0
  90. package/dist/mtl.d.ts +125 -0
  91. package/dist/mtl.js +550 -0
  92. package/dist/normals.d.ts +7 -0
  93. package/dist/normals.js +31 -0
  94. package/dist/nrrd.d.ts +70 -0
  95. package/dist/nrrd.js +785 -0
  96. package/dist/nurbs.d.ts +118 -0
  97. package/dist/nurbs.js +265 -0
  98. package/dist/obj.d.ts +145 -0
  99. package/dist/obj.js +462 -0
  100. package/dist/off.d.ts +10 -0
  101. package/dist/off.js +155 -0
  102. package/dist/outline-font.d.ts +87 -0
  103. package/dist/outline-font.js +110 -0
  104. package/dist/outline.d.ts +20 -0
  105. package/dist/outline.js +215 -0
  106. package/dist/pcd.d.ts +34 -0
  107. package/dist/pcd.js +258 -0
  108. package/dist/pdb.d.ts +67 -0
  109. package/dist/pdb.js +126 -0
  110. package/dist/ply.d.ts +35 -0
  111. package/dist/ply.js +392 -0
  112. package/dist/polygon.d.ts +9 -0
  113. package/dist/polygon.js +49 -0
  114. package/dist/prwm.d.ts +24 -0
  115. package/dist/prwm.js +114 -0
  116. package/dist/render.d.ts +32 -0
  117. package/dist/render.js +181 -0
  118. package/dist/sfnt-cff.d.ts +37 -0
  119. package/dist/sfnt-cff.js +749 -0
  120. package/dist/sfnt-layout.d.ts +24 -0
  121. package/dist/sfnt-layout.js +266 -0
  122. package/dist/sfnt-reader.d.ts +28 -0
  123. package/dist/sfnt-reader.js +87 -0
  124. package/dist/sfnt-variation.d.ts +40 -0
  125. package/dist/sfnt-variation.js +318 -0
  126. package/dist/shared/asset-url.js +82 -0
  127. package/dist/shared/crc32.d.ts +2 -0
  128. package/dist/shared/crc32.js +47 -0
  129. package/dist/shared/errors.js +36 -0
  130. package/dist/shared/inflate.js +284 -0
  131. package/dist/shared/normals.js +26 -0
  132. package/dist/shared/scene-scope.js +56 -0
  133. package/dist/shared/trailing-data.js +45 -0
  134. package/dist/stl.d.ts +64 -0
  135. package/dist/stl.js +309 -0
  136. package/dist/svg.d.ts +90 -0
  137. package/dist/svg.js +1007 -0
  138. package/dist/tds.d.ts +2 -0
  139. package/dist/tds.js +2 -0
  140. package/dist/textures.d.ts +42 -0
  141. package/dist/textures.js +53 -0
  142. package/dist/threemf-beam-reader.d.ts +19 -0
  143. package/dist/threemf-beam-reader.js +165 -0
  144. package/dist/threemf-beams.d.ts +52 -0
  145. package/dist/threemf-beams.js +268 -0
  146. package/dist/threemf-boolean-read.d.ts +10 -0
  147. package/dist/threemf-boolean-read.js +113 -0
  148. package/dist/threemf-boolean.d.ts +59 -0
  149. package/dist/threemf-boolean.js +20 -0
  150. package/dist/threemf-csg.d.ts +14 -0
  151. package/dist/threemf-csg.js +193 -0
  152. package/dist/threemf-displacement-read.d.ts +8 -0
  153. package/dist/threemf-displacement-read.js +213 -0
  154. package/dist/threemf-displacement.d.ts +71 -0
  155. package/dist/threemf-displacement.js +18 -0
  156. package/dist/threemf-evaluate.d.ts +36 -0
  157. package/dist/threemf-evaluate.js +86 -0
  158. package/dist/threemf-functions.d.ts +33 -0
  159. package/dist/threemf-functions.js +359 -0
  160. package/dist/threemf-lattice-mesh.d.ts +9 -0
  161. package/dist/threemf-lattice-mesh.js +115 -0
  162. package/dist/threemf-lattice.d.ts +139 -0
  163. package/dist/threemf-lattice.js +379 -0
  164. package/dist/threemf-levelset.d.ts +23 -0
  165. package/dist/threemf-levelset.js +105 -0
  166. package/dist/threemf-materials.d.ts +162 -0
  167. package/dist/threemf-materials.js +497 -0
  168. package/dist/threemf-mesh.d.ts +75 -0
  169. package/dist/threemf-mesh.js +422 -0
  170. package/dist/threemf-secure.d.ts +50 -0
  171. package/dist/threemf-secure.js +153 -0
  172. package/dist/threemf-tessellate.d.ts +37 -0
  173. package/dist/threemf-tessellate.js +277 -0
  174. package/dist/threemf-volume-colour.d.ts +25 -0
  175. package/dist/threemf-volume-colour.js +233 -0
  176. package/dist/threemf-volume-sample.d.ts +8 -0
  177. package/dist/threemf-volume-sample.js +65 -0
  178. package/dist/threemf-volumetric-read.d.ts +15 -0
  179. package/dist/threemf-volumetric-read.js +539 -0
  180. package/dist/threemf-volumetric.d.ts +177 -0
  181. package/dist/threemf-volumetric.js +28 -0
  182. package/dist/threemf.d.ts +170 -0
  183. package/dist/threemf.js +609 -0
  184. package/dist/tilt.d.ts +62 -0
  185. package/dist/tilt.js +186 -0
  186. package/dist/tmx.d.ts +151 -0
  187. package/dist/tmx.js +394 -0
  188. package/dist/ttf.d.ts +78 -0
  189. package/dist/ttf.js +568 -0
  190. package/dist/types.d.ts +108 -0
  191. package/dist/types.js +35 -0
  192. package/dist/usd.d.ts +2 -0
  193. package/dist/usd.js +2 -0
  194. package/dist/usd.worker.d.ts +1 -0
  195. package/dist/usdz.d.ts +50 -0
  196. package/dist/usdz.js +646 -0
  197. package/dist/util.d.ts +75 -0
  198. package/dist/util.js +241 -0
  199. package/dist/vdb.d.ts +111 -0
  200. package/dist/vdb.js +663 -0
  201. package/dist/vrml.d.ts +53 -0
  202. package/dist/vrml.js +532 -0
  203. package/dist/vtk-cells.d.ts +29 -0
  204. package/dist/vtk-cells.js +211 -0
  205. package/dist/vtk-legacy.d.ts +57 -0
  206. package/dist/vtk-legacy.js +439 -0
  207. package/dist/vtk-reader.d.ts +19 -0
  208. package/dist/vtk-reader.js +134 -0
  209. package/dist/vtk-xml.d.ts +96 -0
  210. package/dist/vtk-xml.js +578 -0
  211. package/dist/vtk.d.ts +13 -0
  212. package/dist/vtk.js +234 -0
  213. package/dist/woff-glyf.d.ts +17 -0
  214. package/dist/woff-glyf.js +215 -0
  215. package/dist/worker.d.ts +10 -0
  216. package/dist/worker.js +93 -0
  217. package/dist/workers/usd.js +3 -0
  218. package/dist/xfile.d.ts +99 -0
  219. package/dist/xfile.js +706 -0
  220. package/dist/xml.d.ts +107 -0
  221. package/dist/xml.js +843 -0
  222. package/dist/xyz.d.ts +16 -0
  223. package/dist/xyz.js +110 -0
  224. package/dist/zip.d.ts +38 -0
  225. package/dist/zip.js +150 -0
  226. package/package.json +289 -4
@@ -0,0 +1,71 @@
1
+ import { type BinaryInput } from './util.js';
2
+ /** One bone of {@link BVH.bones}: what `new Skeleton(bones)` in `@margoengine/animation` reads. */
3
+ export interface BVHBone {
4
+ /** The joint's name, unique in the file. */
5
+ name: string;
6
+ /** Index of the parent bone, parents first; -1 for a root. */
7
+ parent: number;
8
+ /** The joint's OFFSET times `scale`. */
9
+ translation: [number, number, number];
10
+ /** Rest rotation: BVH rests with no rotation. */
11
+ rotation: [number, number, number, number];
12
+ /** The End Site OFFSET times `scale` when this joint ends a chain. */
13
+ endSite?: [number, number, number];
14
+ }
15
+ /** One key of a {@link BVHTrack}. */
16
+ export interface BVHKey {
17
+ time: number;
18
+ value: number[];
19
+ }
20
+ /** One bone's translation or rotation over the file's frames; rotations are quaternions [x, y, z, w]. */
21
+ export interface BVHTrack {
22
+ target: string;
23
+ path: 'translation' | 'rotation';
24
+ keys: BVHKey[];
25
+ }
26
+ /** What {@link parseBVH} returns. */
27
+ export interface BVH {
28
+ /** The skeleton, parents first. */
29
+ bones: BVHBone[];
30
+ /** `{name, tracks}`, ready for `createKeyframeClip` in `@margoengine/animation`. */
31
+ clip: {
32
+ name: string;
33
+ tracks: BVHTrack[];
34
+ };
35
+ /** The file's frame count. */
36
+ frames: number;
37
+ /** Seconds per frame. */
38
+ frameTime: number;
39
+ }
40
+ /** Options of {@link parseBVH}. */
41
+ export interface BVHOptions {
42
+ /** Multiplies offsets and positions; BVH has no unit, so 0.01 turns centimetres to metres. Default 1. */
43
+ scale?: number;
44
+ /** The clip's name. Default `'mocap'`. */
45
+ name?: string;
46
+ /** Most joints. Default 4,096. */
47
+ maxJoints?: number;
48
+ /** Most keys, frames times tracks. Default 4,000,000. */
49
+ maxKeys?: number;
50
+ }
51
+ /**
52
+ * Parses a Biovision BVH file. Euler channels apply in the order the file lists them, each about the joint's own axes
53
+ * after the ones before it. A position channel moves the joint from its OFFSET. Keys sit at `frame * frameTime`.
54
+ *
55
+ * @param input The file's bytes or text.
56
+ * @param options Scale, clip name and limits.
57
+ * @returns The bones, the clip and the frame timing.
58
+ * @throws LoaderError with code `header`, `syntax`, `range`, `truncated` or `limit`.
59
+ *
60
+ * @example
61
+ * ```ts
62
+ * import { parseBVH } from '@margoengine/loaders/mocap';
63
+ *
64
+ * const { bones, clip, frameTime } = parseBVH(
65
+ * 'HIERARCHY ROOT Hip { OFFSET 0 0 0 CHANNELS 3 Zrotation Xrotation Yrotation } MOTION Frames: 1 Frame Time: 0.5 0 0 0',
66
+ * );
67
+ * console.log(bones[0].name, clip.tracks.length, frameTime);
68
+ * ```
69
+ */
70
+ export declare function parseBVH(input: BinaryInput | string, options?: BVHOptions): BVH;
71
+ export { parseAMC, parseASF, type AMCOptions, type ASFBoneData, type ASFOptions, type ASFSkeleton } from './acclaim.js';
package/dist/mocap.js ADDED
@@ -0,0 +1,178 @@
1
+ // Biovision BVH motion capture: HIERARCHY to bones, MOTION to keyframe tracks in the animation package's clip shape.
2
+ import { LoaderError } from './types.js';
3
+ import { toText } from './util.js';
4
+ const F = 'BVH';
5
+ const POSITION = { xposition: 0, yposition: 1, zposition: 2 }, ROTATION = { xrotation: 0, yrotation: 1, zrotation: 2 };
6
+ /**
7
+ * Parses a Biovision BVH file. Euler channels apply in the order the file lists them, each about the joint's own axes
8
+ * after the ones before it. A position channel moves the joint from its OFFSET. Keys sit at `frame * frameTime`.
9
+ *
10
+ * @param input The file's bytes or text.
11
+ * @param options Scale, clip name and limits.
12
+ * @returns The bones, the clip and the frame timing.
13
+ * @throws LoaderError with code `header`, `syntax`, `range`, `truncated` or `limit`.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { parseBVH } from '@margoengine/loaders/mocap';
18
+ *
19
+ * const { bones, clip, frameTime } = parseBVH(
20
+ * 'HIERARCHY ROOT Hip { OFFSET 0 0 0 CHANNELS 3 Zrotation Xrotation Yrotation } MOTION Frames: 1 Frame Time: 0.5 0 0 0',
21
+ * );
22
+ * console.log(bones[0].name, clip.tracks.length, frameTime);
23
+ * ```
24
+ */
25
+ export function parseBVH(input, options = {}) {
26
+ const text = toText(input, F), { scale = 1, name = 'mocap', maxJoints = 4096, maxKeys = 4_000_000 } = options;
27
+ if (!Number.isFinite(scale) || scale <= 0)
28
+ throw new LoaderError(F, 'range', 'scale must be positive and finite');
29
+ for (const [label, value] of [
30
+ ['maxJoints', maxJoints],
31
+ ['maxKeys', maxKeys],
32
+ ])
33
+ if (!Number.isSafeInteger(value) || value < 0)
34
+ throw new LoaderError(F, 'range', `${label} must be a non-negative integer`);
35
+ const scan = /[{}]|[^\s{}]+/g;
36
+ const next = () => scan.exec(text)?.[0] ?? null;
37
+ const need = (what) => {
38
+ const token = next();
39
+ if (token === null)
40
+ throw new LoaderError(F, 'truncated', `file ends where ${what} should be`);
41
+ return token;
42
+ };
43
+ const number = (what) => {
44
+ const token = need(what), value = Number(token);
45
+ if (!Number.isFinite(value))
46
+ throw new LoaderError(F, 'syntax', `invalid number "${token.slice(0, 32)}" for ${what}`);
47
+ return value;
48
+ };
49
+ const expect = (word) => {
50
+ const token = need(word);
51
+ if (token !== word)
52
+ throw new LoaderError(F, 'syntax', `expected ${word}, found "${token.slice(0, 32)}"`);
53
+ };
54
+ const offset = () => {
55
+ expect('OFFSET');
56
+ return [number('OFFSET x') * scale, number('OFFSET y') * scale, number('OFFSET z') * scale];
57
+ };
58
+ if (next() !== 'HIERARCHY')
59
+ throw new LoaderError(F, 'header', 'missing HIERARCHY keyword');
60
+ const bones = [], channels = [], seen = new Set(), stack = [];
61
+ let token = need('ROOT');
62
+ // Joints open and close by the stack, so a deep file cannot run out the call stack.
63
+ while (token !== 'MOTION') {
64
+ if (token === 'ROOT' || token === 'JOINT') {
65
+ if ((token === 'ROOT') !== (stack.length === 0))
66
+ throw new LoaderError(F, 'syntax', `${token} is in the wrong place; ROOT is outermost, JOINT is inside a joint`);
67
+ const joint = need('a joint name');
68
+ if (seen.has(joint))
69
+ throw new LoaderError(F, 'syntax', `joint "${joint.slice(0, 32)}" is named twice`);
70
+ if (bones.length >= maxJoints)
71
+ throw new LoaderError(F, 'limit', `joint count exceeds the limit of ${maxJoints}`);
72
+ seen.add(joint);
73
+ expect('{');
74
+ const translation = offset();
75
+ expect('CHANNELS');
76
+ const count = number('the channel count');
77
+ if (!Number.isInteger(count) || count < 0 || count > 6)
78
+ throw new LoaderError(F, 'syntax', `joint "${joint.slice(0, 32)}" has ${count} channels; expected 0 to 6`);
79
+ const entry = { position: [], rotation: [], order: [] };
80
+ for (let i = 0; i < count; i++) {
81
+ const channel = need('a channel name').toLowerCase();
82
+ if (!Object.hasOwn(POSITION, channel) && !Object.hasOwn(ROTATION, channel))
83
+ throw new LoaderError(F, 'syntax', `unknown channel "${channel.slice(0, 32)}"`);
84
+ entry.order.push(channel);
85
+ }
86
+ bones.push({
87
+ name: joint,
88
+ parent: stack.length ? stack[stack.length - 1] : -1,
89
+ translation,
90
+ rotation: [0, 0, 0, 1],
91
+ });
92
+ channels.push(entry);
93
+ stack.push(bones.length - 1);
94
+ }
95
+ else if (token === 'End') {
96
+ if (!stack.length)
97
+ throw new LoaderError(F, 'syntax', 'End Site is outside every joint');
98
+ expect('Site');
99
+ expect('{');
100
+ bones[stack[stack.length - 1]].endSite = offset();
101
+ expect('}');
102
+ }
103
+ else if (token === '}') {
104
+ if (!stack.length)
105
+ throw new LoaderError(F, 'syntax', 'a closing brace has no joint to close');
106
+ stack.pop();
107
+ }
108
+ else
109
+ throw new LoaderError(F, 'syntax', `unexpected "${token.slice(0, 32)}" in HIERARCHY`);
110
+ token = need('MOTION');
111
+ }
112
+ if (stack.length)
113
+ throw new LoaderError(F, 'syntax', `MOTION starts inside joint "${bones[stack[stack.length - 1]].name}"`);
114
+ if (!bones.length)
115
+ throw new LoaderError(F, 'header', 'HIERARCHY has no ROOT');
116
+ expect('Frames:');
117
+ const frames = number('the frame count');
118
+ if (!Number.isSafeInteger(frames) || frames < 0)
119
+ throw new LoaderError(F, 'header', `invalid frame count ${frames}`);
120
+ expect('Frame');
121
+ expect('Time:');
122
+ const frameTime = number('the frame time');
123
+ if (!(frameTime > 0))
124
+ throw new LoaderError(F, 'range', `frame time ${frameTime} is not positive`);
125
+ const tracks = [], plan = [];
126
+ let width = 0;
127
+ bones.forEach((bone, b) => {
128
+ const entry = channels[b], item = {};
129
+ width += entry.order.length;
130
+ if (entry.order.some((c) => Object.hasOwn(POSITION, c))) {
131
+ item.positions = [];
132
+ tracks.push({ target: bone.name, path: 'translation', keys: item.positions });
133
+ }
134
+ if (entry.order.some((c) => Object.hasOwn(ROTATION, c))) {
135
+ item.rotations = [];
136
+ tracks.push({ target: bone.name, path: 'rotation', keys: item.rotations });
137
+ }
138
+ plan.push(item);
139
+ });
140
+ if (frames * tracks.length > maxKeys)
141
+ throw new LoaderError(F, 'limit', `${frames} frames of ${tracks.length} tracks exceed the limit of ${maxKeys} keys`);
142
+ // Budget before the keys: every value takes a digit and a separator, so a short file cannot claim millions of frames.
143
+ if (frames * width * 2 - 1 > text.length - scan.lastIndex)
144
+ throw new LoaderError(F, 'truncated', `file is too short for ${frames} frames of ${width} values`);
145
+ for (let frame = 0; frame < frames; frame++) {
146
+ const time = frame * frameTime;
147
+ bones.forEach((bone, b) => {
148
+ const { order } = channels[b], item = plan[b], position = [0, 0, 0];
149
+ let qx = 0, qy = 0, qz = 0, qw = 1;
150
+ for (const channel of order) {
151
+ const value = number(`frame ${frame}, joint "${bone.name}"`);
152
+ if (Object.hasOwn(POSITION, channel)) {
153
+ position[POSITION[channel]] = value * scale;
154
+ continue;
155
+ }
156
+ // Each listed rotation multiplies on the right: about the axes the ones before it left.
157
+ const half = (value * Math.PI) / 360, sin = Math.sin(half), cos = Math.cos(half), axis = ROTATION[channel], x = axis === 0 ? sin : 0, y = axis === 1 ? sin : 0, z = axis === 2 ? sin : 0, nx = qw * x + qx * cos + qy * z - qz * y, ny = qw * y - qx * z + qy * cos + qz * x, nz = qw * z + qx * y - qy * x + qz * cos, nw = qw * cos - qx * x - qy * y - qz * z;
158
+ qx = nx;
159
+ qy = ny;
160
+ qz = nz;
161
+ qw = nw;
162
+ }
163
+ if (item.positions)
164
+ item.positions.push({
165
+ time,
166
+ value: [
167
+ bone.translation[0] + position[0],
168
+ bone.translation[1] + position[1],
169
+ bone.translation[2] + position[2],
170
+ ],
171
+ });
172
+ if (item.rotations)
173
+ item.rotations.push({ time, value: [qx, qy, qz, qw] });
174
+ });
175
+ }
176
+ return { bones, clip: { name, tracks: frames ? tracks : [] }, frames, frameTime };
177
+ }
178
+ export { parseAMC, parseASF } from './acclaim.js';
@@ -0,0 +1,4 @@
1
+ /** Every pair of atoms close enough for their radii, through a grid of the largest bond length. */
2
+ export declare function nearbyPairs(positions: Float32Array, radii: Float32Array, add: (a: number, b: number) => void): void;
3
+ /** Internal element display style and Cordero covalent radius; unknowns use pink and 1.5 angstrom. */
4
+ export declare function elementProperties(symbol: string): [number, number];
@@ -0,0 +1,54 @@
1
+ /** Colour and covalent radius in angstroms of the common elements. Other elements draw pink at 1.5. */
2
+ const ELEMENTS = Object.assign(Object.create(null), {
3
+ H: [0xffffff, 0.31],
4
+ C: [0x909090, 0.76],
5
+ N: [0x3050f8, 0.71],
6
+ O: [0xff0d0d, 0.66],
7
+ F: [0x90e050, 0.57],
8
+ NA: [0xab5cf2, 1.66],
9
+ MG: [0x8aff00, 1.41],
10
+ P: [0xff8000, 1.07],
11
+ S: [0xffff30, 1.05],
12
+ CL: [0x1ff01f, 1.02],
13
+ K: [0x8f40d4, 2.03],
14
+ CA: [0x3dff00, 1.76],
15
+ MN: [0x9c7ac7, 1.39],
16
+ FE: [0xe06633, 1.32],
17
+ CO: [0xf090a0, 1.26],
18
+ NI: [0x50d050, 1.24],
19
+ CU: [0xc88033, 1.32],
20
+ ZN: [0x7d80b0, 1.22],
21
+ SE: [0xffa100, 1.2],
22
+ BR: [0xa62929, 1.2],
23
+ I: [0x940094, 1.39],
24
+ });
25
+ const OTHER = [0xff1493, 1.5];
26
+ /** Slack added to two covalent radii when finding bonds by distance. */
27
+ const BOND_SLACK = 0.45;
28
+ /** Every pair of atoms close enough for their radii, through a grid of the largest bond length. */
29
+ export function nearbyPairs(positions, radii, add) {
30
+ let largest = 0;
31
+ for (const radius of radii)
32
+ largest = Math.max(largest, radius);
33
+ const cell = largest * 2 + BOND_SLACK, grid = new Map(), id = (x, y, z) => `${x} ${y} ${z}`;
34
+ for (let i = 0; i < radii.length; i++) {
35
+ const x = Math.floor(positions[i * 3] / cell), y = Math.floor(positions[i * 3 + 1] / cell), z = Math.floor(positions[i * 3 + 2] / cell);
36
+ for (let dx = -1; dx <= 1; dx++)
37
+ for (let dy = -1; dy <= 1; dy++)
38
+ for (let dz = -1; dz <= 1; dz++)
39
+ for (const j of grid.get(id(x + dx, y + dy, z + dz)) ?? []) {
40
+ const limit = radii[i] + radii[j] + BOND_SLACK, distance = Math.hypot(positions[i * 3] - positions[j * 3], positions[i * 3 + 1] - positions[j * 3 + 1], positions[i * 3 + 2] - positions[j * 3 + 2]);
41
+ if (distance > 0.4 && distance <= limit)
42
+ add(j, i);
43
+ }
44
+ const own = id(x, y, z), list = grid.get(own);
45
+ if (list)
46
+ list.push(i);
47
+ else
48
+ grid.set(own, [i]);
49
+ }
50
+ }
51
+ /** Internal element display style and Cordero covalent radius; unknowns use pink and 1.5 angstrom. */
52
+ export function elementProperties(symbol) {
53
+ return ELEMENTS[symbol.toUpperCase()] ?? OTHER;
54
+ }
package/dist/mtl.d.ts ADDED
@@ -0,0 +1,125 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ // @ts-ignore optional peer: its types apply when it is installed
3
+ import { Material, type MaterialMesh, type MeshGeometry, type Texture, type TextureOptions } from '@margoengine/materials';
4
+ import { type FetchOptions } from './load.js';
5
+ import { type LoadedOBJ, type MTLMaterial, type OBJMaterialLimits } from './obj.js';
6
+ import { type ParseLimits } from './types.js';
7
+ /**
8
+ * Loads one texture for `createMTLMaterials`: the URL and the texture options the map needs, with the `signal` and
9
+ * `fetch` given to createMTLMaterials (`fetch` only when one was given).
10
+ */
11
+ export type MTLTextureLoader = (url: string, options: TextureOptions & {
12
+ signal?: AbortSignal;
13
+ fetch?: typeof fetch;
14
+ }) => Promise<Texture>;
15
+ /** Options of `createMTLMaterials`. */
16
+ export interface MTLMaterialsOptions {
17
+ /**
18
+ * URL that map paths are relative to: the .mtl URL for `parseMTL` output, the .obj URL for `parseOBJ`'s
19
+ * `materials` (their paths already include the library folder). Default: the page URL.
20
+ */
21
+ baseUrl?: string | URL;
22
+ /**
23
+ * URL prefixes a map may load from besides `baseUrl`'s own directory. A map path from the file that leaves that
24
+ * directory (an absolute or cross-origin URL, `../` past it, a scheme other than http(s) and data:) is not
25
+ * requested: it is a warning and its maps are left out. Default none.
26
+ */
27
+ allowedURLs?: readonly string[];
28
+ /** Texture loader. Default: materials' `loadTexture` (http(s), blob: and data: URLs). */
29
+ loadTexture?: MTLTextureLoader;
30
+ /**
31
+ * What `bump` / `map_Bump` holds: `'height'` (the MTL meaning, scaled by `-bm`) or `'normal'` (a tangent-space
32
+ * normal map, as many exporters write). Default `'height'`.
33
+ */
34
+ bump?: 'height' | 'normal';
35
+ /** Draw both faces. Default false. */
36
+ doubleSided?: boolean;
37
+ /** Aborts texture loading; the promise then rejects with a `LoaderError` with code `'aborted'`. */
38
+ signal?: AbortSignal;
39
+ /**
40
+ * Fetch handed to the texture loader for every map, for example an AssetCache's or a LoadingManager's `fetch`
41
+ * (loadOBJ passes its own). Default: the loader's own (`globalThis.fetch` for materials' `loadTexture`).
42
+ */
43
+ fetch?: typeof fetch;
44
+ }
45
+ /** The materials `createMTLMaterials` built, and the textures they use. */
46
+ export interface MTLMaterialSet {
47
+ /** One material per `newmtl` name, in input order. */
48
+ materials: Map<string, Material>;
49
+ /** Every texture loaded, once per (file, colour space, wrap mode). */
50
+ textures: Texture[];
51
+ /** Maps that failed to load and MTL values with no Margo equivalent. */
52
+ warnings: string[];
53
+ /** Disposes every material and texture of the set. */
54
+ dispose(): void;
55
+ }
56
+ /**
57
+ * Builds one materials `Material` per `newmtl` of `parseMTL` output (or `parseOBJ`'s `materials`), mapped to
58
+ * metallic-roughness: `Kd` is the base colour (sRGB in the file, linear in the material), `d` (else 1 - `Tr`) the
59
+ * opacity, `Ke` the emission (a peak above 1 moves into `emissiveIntensity`), and roughness comes from the Phong
60
+ * exponent `Ns` as (2 / (Ns + 2))^(1/4) (Walter et al. 2007's Blinn-Phong to Beckmann match with glTF's
61
+ * alpha = roughness^2). `Ks` (and `map_Ks`, times it) is the specular reflectance at normal incidence, held as
62
+ * KHR_materials_specular's `specularColor` and `specularColorMap`; `illum 1` and a black `Ks` have no highlight. The
63
+ * PBR extension's `Pr`, `Pm` and `norm` are read when present, and a material with `Pr` or `Pm` leaves `Ks` out.
64
+ * `illum 0` is unlit. `disp` displaces vertices along their normals (`-mm base gain`: bias and scale). `refl` becomes
65
+ * the material's `envMap`: `-type sphere` a latitude-longitude image, or six `-type cube_*` faces (front is -Z).
66
+ * `map_Kd`, `map_d`, `map_Ke`, `map_Ks`, `disp`, `refl`, `bump` and `norm` load as textures, each (file, colour
67
+ * space, wrap) once; their `-o` and `-s` become the slot's UV transform and `-clamp on` a clamped wrap. A map that
68
+ * fails to load is a warning. `Ka` has no equivalent (ambient light shades the base colour) and is a warning.
69
+ * Rejects with `TypeError` / `RangeError` for bad arguments and with a `LoaderError` (code `'aborted'`) when
70
+ * `signal` aborts; whatever was built is disposed first.
71
+ */
72
+ export declare function createMTLMaterials(mtl: readonly MTLMaterial[], options?: MTLMaterialsOptions): Promise<MTLMaterialSet>;
73
+ /** Options of `prepareOBJMesh` and `createOBJMesh`. */
74
+ export interface OBJMeshOptions {
75
+ /** Material for groups without `usemtl` or naming an unknown material. Default: a new white `Material`. */
76
+ fallback?: Material;
77
+ }
78
+ /**
79
+ * Turns a parsed OBJ and its materials into materials-ready geometry plus one material per slot, without a GPU:
80
+ * groups map to materials by their `usemtl` name. Positions and indices are the OBJ's own arrays. Normals are the
81
+ * OBJ's (normalised) or, without them, smooth normals shared across UV seams; zero normals become +z. UVs go back to
82
+ * OBJ's v-up orientation for flipY textures, and vertex colours from sRGB to linear. Throws a `LoaderError` (code
83
+ * `'unsupported'`) for an OBJ without faces and `TypeError` when `materials` is neither a Map nor a set.
84
+ */
85
+ export declare function prepareOBJMesh(obj: LoadedOBJ, materials: MTLMaterialSet | ReadonlyMap<string, Material>, options?: OBJMeshOptions): {
86
+ geometry: MeshGeometry;
87
+ materials: Material[];
88
+ };
89
+ /**
90
+ * `prepareOBJMesh`, then materials' `createMesh` with one material slot per OBJ material. Dispose the mesh with
91
+ * `destroy()`; the materials stay owned by their set.
92
+ */
93
+ export declare function createOBJMesh(engine: EngineKernel, obj: LoadedOBJ, materials: MTLMaterialSet | ReadonlyMap<string, Material>, options?: OBJMeshOptions & {
94
+ renderOrder?: number;
95
+ }): MaterialMesh<Material[]>;
96
+ /** Options of `loadOBJ`: fetching, parse limits, material building and the mesh. */
97
+ export interface LoadOBJOptions extends FetchOptions, ParseLimits, OBJMaterialLimits, Omit<MTLMaterialsOptions, 'baseUrl' | 'signal'>, OBJMeshOptions {
98
+ /** Draw order of the mesh. Default 0. */
99
+ renderOrder?: number;
100
+ }
101
+ /** What `loadOBJ` returns. */
102
+ export interface LoadedOBJMesh {
103
+ mesh: MaterialMesh<Material[]>;
104
+ /** The parsed OBJ, with its MTL materials as data. */
105
+ obj: LoadedOBJ;
106
+ materials: MTLMaterialSet;
107
+ /** The OBJ's warnings followed by the material set's. */
108
+ warnings: string[];
109
+ /**
110
+ * Destroys the mesh and disposes the material set (and the fallback material when loadOBJ made it). A scene that
111
+ * removes the mesh (removePlugin, scene or engine disposal) releases them the same way.
112
+ */
113
+ dispose(): void;
114
+ }
115
+ /**
116
+ * Loads a textured OBJ in one call: fetches the OBJ, then each `mtllib` relative to it, builds the materials with
117
+ * `createMTLMaterials` (textures relative to their library) and the mesh with `createOBJMesh`. A library that cannot
118
+ * be read is a warning. The OBJ is untrusted: its `mtllib` files and textures load only from the OBJ's directory or
119
+ * an `allowedURLs` prefix (a library elsewhere throws a `LoaderError` with code `'url'`, a texture elsewhere is a
120
+ * warning), `init` (headers, credentials) goes only to the OBJ's own origin, and the libraries share the
121
+ * `maxMaterialLibraries` and `maxMaterialBytes` budget (code `'limit'`). Throws `TypeError` when `url` is not absolute
122
+ * and there is no page URL, and the `LoaderError` of a failed fetch or parse. When the mesh cannot be built,
123
+ * everything loaded is disposed first.
124
+ */
125
+ export declare function loadOBJ(engine: EngineKernel, url: string | URL, options?: LoadOBJOptions): Promise<LoadedOBJMesh>;