@margoengine/loaders 0.1.0 → 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 (82) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +4 -4
  3. package/README.md +1666 -1198
  4. package/dist/crease.d.ts +7 -0
  5. package/dist/crease.js +67 -0
  6. package/dist/dae-common.js +1 -1
  7. package/dist/dae-kinematics.d.ts +65 -0
  8. package/dist/dae-kinematics.js +461 -0
  9. package/dist/dae.d.ts +9 -4
  10. package/dist/dae.js +16 -5
  11. package/dist/dxf-hatch.d.ts +8 -0
  12. package/dist/dxf-hatch.js +346 -0
  13. package/dist/dxf-leaders.d.ts +59 -0
  14. package/dist/dxf-leaders.js +258 -0
  15. package/dist/dxf.d.ts +42 -1
  16. package/dist/dxf.js +226 -15
  17. package/dist/engine.d.ts +5 -0
  18. package/dist/engine.js +3 -0
  19. package/dist/gcode.d.ts +37 -0
  20. package/dist/gcode.js +91 -0
  21. package/dist/geometry.d.ts +1 -1
  22. package/dist/index.d.ts +1 -1
  23. package/dist/mtl.d.ts +8 -3
  24. package/dist/mtl.js +91 -10
  25. package/dist/nrrd.d.ts +12 -5
  26. package/dist/nrrd.js +68 -26
  27. package/dist/obj.d.ts +3 -1
  28. package/dist/obj.js +7 -1
  29. package/dist/render.d.ts +9 -4
  30. package/dist/render.js +31 -3
  31. package/dist/shared/asset-url.js +82 -82
  32. package/dist/shared/crc32.d.ts +2 -2
  33. package/dist/shared/crc32.js +47 -47
  34. package/dist/shared/errors.js +36 -36
  35. package/dist/shared/inflate.js +284 -284
  36. package/dist/shared/normals.js +26 -26
  37. package/dist/shared/scene-scope.js +54 -54
  38. package/dist/shared/trailing-data.js +45 -42
  39. package/dist/threemf-beam-reader.d.ts +19 -0
  40. package/dist/threemf-beam-reader.js +165 -0
  41. package/dist/threemf-beams.d.ts +52 -0
  42. package/dist/threemf-beams.js +268 -0
  43. package/dist/threemf-boolean-read.d.ts +10 -0
  44. package/dist/threemf-boolean-read.js +113 -0
  45. package/dist/threemf-boolean.d.ts +59 -0
  46. package/dist/threemf-boolean.js +20 -0
  47. package/dist/threemf-csg.d.ts +14 -0
  48. package/dist/threemf-csg.js +193 -0
  49. package/dist/threemf-displacement-read.d.ts +8 -0
  50. package/dist/threemf-displacement-read.js +213 -0
  51. package/dist/threemf-displacement.d.ts +71 -0
  52. package/dist/threemf-displacement.js +18 -0
  53. package/dist/threemf-evaluate.d.ts +36 -0
  54. package/dist/threemf-evaluate.js +86 -0
  55. package/dist/threemf-functions.d.ts +33 -0
  56. package/dist/threemf-functions.js +359 -0
  57. package/dist/threemf-lattice-mesh.d.ts +9 -0
  58. package/dist/threemf-lattice-mesh.js +115 -0
  59. package/dist/threemf-lattice.js +10 -145
  60. package/dist/threemf-levelset.d.ts +23 -0
  61. package/dist/threemf-levelset.js +105 -0
  62. package/dist/threemf-materials.d.ts +89 -2
  63. package/dist/threemf-materials.js +194 -11
  64. package/dist/threemf-mesh.d.ts +21 -6
  65. package/dist/threemf-mesh.js +266 -45
  66. package/dist/threemf-secure.d.ts +50 -0
  67. package/dist/threemf-secure.js +153 -0
  68. package/dist/threemf-tessellate.d.ts +37 -0
  69. package/dist/threemf-tessellate.js +277 -0
  70. package/dist/threemf-volume-colour.d.ts +25 -0
  71. package/dist/threemf-volume-colour.js +233 -0
  72. package/dist/threemf-volume-sample.d.ts +8 -0
  73. package/dist/threemf-volume-sample.js +65 -0
  74. package/dist/threemf-volumetric-read.d.ts +15 -0
  75. package/dist/threemf-volumetric-read.js +539 -0
  76. package/dist/threemf-volumetric.d.ts +177 -0
  77. package/dist/threemf-volumetric.js +28 -0
  78. package/dist/threemf.d.ts +73 -4
  79. package/dist/threemf.js +235 -41
  80. package/dist/types.d.ts +18 -0
  81. package/dist/workers/usd.js +1 -1
  82. package/package.json +291 -246
@@ -0,0 +1,7 @@
1
+ import { type LoadedGeometry } from './types.js';
2
+ /**
3
+ * `loaded` with a normal for every corner: a vertex whose corners get different normals is copied, at the end of each
4
+ * per-vertex array, so indices into the first vertices (lines included) keep their meaning. Groups are unchanged.
5
+ * Returned as it is when it has normals of its own, has no triangles, or `angle` is 180.
6
+ */
7
+ export declare function creased(loaded: LoadedGeometry, angle?: number): LoadedGeometry;
package/dist/crease.js ADDED
@@ -0,0 +1,67 @@
1
+ // Sharp edges for a mesh whose file has no normals: createMeshes and createPBRMeshes smooth only across faces within
2
+ // a crease angle of each other, so a box keeps its edges and a curved surface stays smooth.
3
+ import { creasedNormals } from '@margoengine/geometry/utils';
4
+ import { LoaderError } from './types.js';
5
+ /** The crease angle in degrees when none is given, as for create3MFMesh. */
6
+ const CREASE_ANGLE = 40;
7
+ /**
8
+ * `loaded` with a normal for every corner: a vertex whose corners get different normals is copied, at the end of each
9
+ * per-vertex array, so indices into the first vertices (lines included) keep their meaning. Groups are unchanged.
10
+ * Returned as it is when it has normals of its own, has no triangles, or `angle` is 180.
11
+ */
12
+ export function creased(loaded, angle = CREASE_ANGLE) {
13
+ if (!(angle >= 0 && angle <= 180))
14
+ throw new LoaderError('Engine', 'range', 'creaseAngle must be 0 to 180 degrees');
15
+ const { positions, indices, normals } = loaded;
16
+ if (loaded.kind !== 'mesh' || normals || !indices?.length || angle === 180)
17
+ return loaded;
18
+ const count = positions.length / 3;
19
+ // A malformed mesh is left for toGeometries to refuse.
20
+ if (indices.length % 3 || indices.some((v) => v >= count))
21
+ return loaded;
22
+ const corners = new Float32Array(indices.length * 3);
23
+ for (let c = 0; c < indices.length; c++)
24
+ for (let k = 0; k < 3; k++)
25
+ corners[c * 3 + k] = positions[indices[c] * 3 + k];
26
+ const own = creasedNormals(corners, { angle, tolerance: 0 }), out = indices.slice(),
27
+ /** The input vertex of each output vertex, and the first corner that gave it its normal. */
28
+ source = Array.from({ length: count }, (_, v) => v), corner = new Array(count).fill(-1), next = new Array(count).fill(-1);
29
+ for (let c = 0; c < indices.length; c++) {
30
+ let at = indices[c];
31
+ while (corner[at] >= 0 && ![0, 1, 2].every((k) => own[corner[at] * 3 + k] === own[c * 3 + k])) {
32
+ if (next[at] < 0) {
33
+ next[at] = source.length;
34
+ source.push(indices[c]);
35
+ corner.push(-1);
36
+ next.push(-1);
37
+ }
38
+ at = next[at];
39
+ }
40
+ if (corner[at] < 0)
41
+ corner[at] = c;
42
+ out[c] = at;
43
+ }
44
+ const copied = (values) => {
45
+ const size = values.length / count;
46
+ if (!Number.isInteger(size))
47
+ return values;
48
+ const result = new Float32Array(source.length * size);
49
+ result.set(values);
50
+ for (let v = count; v < source.length; v++)
51
+ result.set(values.subarray(source[v] * size, (source[v] + 1) * size), v * size);
52
+ return result;
53
+ };
54
+ const made = new Float32Array(source.length * 3);
55
+ corner.forEach((c, v) => {
56
+ if (c >= 0)
57
+ made.set(own.subarray(c * 3, c * 3 + 3), v * 3);
58
+ });
59
+ const result = { ...loaded, positions: copied(positions), normals: made, indices: out };
60
+ if (loaded.colors)
61
+ result.colors = copied(loaded.colors);
62
+ if (loaded.uvs)
63
+ result.uvs = copied(loaded.uvs);
64
+ if (loaded.attributes)
65
+ result.attributes = Object.fromEntries(Object.entries(loaded.attributes).map(([name, values]) => [name, copied(values)]));
66
+ return result;
67
+ }
@@ -216,7 +216,7 @@ export function transformInto(m, positions, normals, i, outPositions, outNormals
216
216
  const { n, determinant } = co, a = normals[i], b = normals[i + 1], c = normals[i + 2];
217
217
  let nx = n[0] * a + n[3] * b + n[6] * c, ny = n[1] * a + n[4] * b + n[7] * c, nz = n[2] * a + n[5] * b + n[8] * c;
218
218
  // Cofactors carry the determinant's sign; the normal transform (inverse transpose) does not.
219
- const length = (Math.hypot(nx, ny, nz) || 1) * Math.sign(determinant || 1);
219
+ const length = (Math.hypot(nx, ny, nz) || 1) * (determinant < 0 ? -1 : 1);
220
220
  nx /= length;
221
221
  ny /= length;
222
222
  nz /= length;
@@ -0,0 +1,65 @@
1
+ import { type DAENode, type DAEParseOptions, type LoadedDAE } from './dae.js';
2
+ import type { DAEPose } from './dae-pose.js';
3
+ import type { BinaryInput } from './util.js';
4
+ /** A node transform a joint axis drives. */
5
+ export interface DAEJointTarget {
6
+ node: DAENode;
7
+ /** Index into `node.transforms`: a `rotate` for a revolute axis, a `translate` for a prismatic one. */
8
+ transform: number;
9
+ }
10
+ /** One degree of freedom: a `<revolute>` or `<prismatic>` of one instance of a joint. */
11
+ export interface DAEJointAxis {
12
+ /**
13
+ * The key {@link poseDAEJoints} takes: the joint's SID, with the axis SID or the whole instance path added only when
14
+ * needed to tell axes apart.
15
+ */
16
+ name: string;
17
+ /** The SIDs from the kinematics scene down to the axis, joined by `/`; unique in the file. */
18
+ path: string;
19
+ /** The `<joint>`'s name, else its SID or id. */
20
+ joint: string;
21
+ type: 'revolute' | 'prismatic';
22
+ /** Unit axis of rotation or travel in the driven node's frame, Y-up. */
23
+ axis: [number, number, number];
24
+ /** Lower limit: degrees for revolute, meters for prismatic. `axis_info` limits replace the joint's own. */
25
+ min?: number;
26
+ max?: number;
27
+ /** The value the file binds the axis at (degrees or meters). */
28
+ value: number;
29
+ /** `axis_info` `<active>`: false for a passive axis. Default true. */
30
+ active: boolean;
31
+ /** `axis_info` `<locked>`: a locked axis stays at `value`. Default false. */
32
+ locked: boolean;
33
+ /** `axis_info` `<index>`: the axis' number in the controller's order. */
34
+ index?: number;
35
+ /** Motion `axis_info` bounds, per second (squared, cubed), in the axis' units. */
36
+ speed?: number;
37
+ acceleration?: number;
38
+ deceleration?: number;
39
+ jerk?: number;
40
+ /** The node transforms `bind_joint_axis` ties to this axis; empty when the file binds none. */
41
+ targets: DAEJointTarget[];
42
+ }
43
+ /** A parsed COLLADA document with its joint axes. */
44
+ export interface DAEKinematicScene extends LoadedDAE {
45
+ /** Every joint axis of the instanced kinematics scenes, in document order. */
46
+ joints: DAEJointAxis[];
47
+ }
48
+ /** Options of {@link poseDAEJoints}. */
49
+ export interface DAEJointPoseOptions {
50
+ /** Hold values inside the axis' `min` and `max`. Default true. */
51
+ clamp?: boolean;
52
+ }
53
+ /**
54
+ * `parseDAE` plus the document's COLLADA 1.5 kinematics: `joints` lists every revolute and prismatic axis of the
55
+ * instanced kinematics scenes with its limits, its `axis_info` data and the node transforms it drives. What cannot be
56
+ * resolved is reported in `warnings`. Formulas, closed-loop attachments and tool frames are not evaluated.
57
+ */
58
+ export declare function parseDAEKinematics(input: BinaryInput | string, options?: DAEParseOptions): DAEKinematicScene;
59
+ /**
60
+ * The scene with its joints at the given values (degrees for revolute axes, meters for prismatic ones), for
61
+ * `flattenDAE` or your own meshes: `world` holds every node's matrix. An axis left out stands at its `value`. Each
62
+ * bound transform becomes the axis' motion: a rotation about `axis`, or a translation along it. Values are held
63
+ * inside the limits unless `clamp` is false.
64
+ */
65
+ export declare function poseDAEJoints(dae: DAEKinematicScene, values?: Readonly<Record<string, number>>, options?: DAEJointPoseOptions): DAEPose;
@@ -0,0 +1,461 @@
1
+ // COLLADA 1.5 kinematics, clean room from the Khronos COLLADA 1.5.0 specification and schema (Khronos Group, 2008,
2
+ // https://www.khronos.org/files/collada_schema_1_5): joints, kinematics models, articulated systems and kinematics
3
+ // scenes, whose `bind_joint_axis` ties a joint axis to one transform of a visual scene node. Parameters and SID
4
+ // paths are resolved through the instance tree, so two instances of one model keep their own joints.
5
+ import { LoaderError } from './types.js';
6
+ import { daeRoot, readDAE } from './dae.js';
7
+ import { AXES, converter, F, IDENTITY, kid, kids, multiply, ref, stackMatrix } from './dae-common.js';
8
+ /** Instantiated kinematics elements per file. */
9
+ const MAX_SCOPES = 100_000;
10
+ const MAX_DEPTH = 64;
11
+ /** Elements and nodes visited while resolving SID paths, so a hostile file cannot cost the square of its size. */
12
+ const MAX_VISITS = 20_000_000;
13
+ // `link` trees hold no joint of their own and nest two levels per joint, so a long chain is not walked.
14
+ const SKIPPED = new Set(['asset', 'extra', 'technique', 'link', 'formula', 'instance_formula']);
15
+ const INSTANCES = new Set([
16
+ 'instance_kinematics_scene',
17
+ 'instance_articulated_system',
18
+ 'instance_kinematics_model',
19
+ 'instance_joint',
20
+ ]);
21
+ const PRIMITIVES = new Set(['revolute', 'prismatic']);
22
+ const textOf = (e) => e.attributes.ref ?? e.text.trim();
23
+ /** An address without a trailing member selector (".ANGLE", "(2)"), which names part of a value, not an element. */
24
+ const withoutMember = (sid) => sid.replace(/(\.\w+|\(\d+\))+$/, '');
25
+ class Resolver {
26
+ constructor(ids, warn) {
27
+ this.ids = ids;
28
+ this.warn = warn;
29
+ this.scopes = 0;
30
+ this.visits = 0;
31
+ /** `setparam` replacements, by the `newparam` they replace. */
32
+ this.overrides = new Map();
33
+ }
34
+ expand(element, parent, depth) {
35
+ if (++this.scopes > MAX_SCOPES || depth > MAX_DEPTH)
36
+ throw new LoaderError(F, 'limit', `the kinematics instances expand past ${MAX_SCOPES} elements or ${MAX_DEPTH} levels (an instance cycle?)`);
37
+ const scope = { element, children: [] };
38
+ if (parent)
39
+ scope.parent = parent;
40
+ const add = (from) => {
41
+ for (const child of from.children)
42
+ if (SKIPPED.has(child.name)) {
43
+ if (child.name.endsWith('formula'))
44
+ this.warn('kinematics formulas (coupled joints) are not evaluated: pose the dependent axes yourself');
45
+ }
46
+ else
47
+ scope.children.push(this.expand(child, scope, depth + 1));
48
+ };
49
+ add(element);
50
+ if (INSTANCES.has(element.name)) {
51
+ const url = element.attributes.url ?? '', target = url.startsWith('#') ? this.ids.get(ref(url)) : undefined;
52
+ if (target && target.name === element.name.slice('instance_'.length)) {
53
+ scope.target = target;
54
+ add(target);
55
+ }
56
+ else
57
+ this.warn(`${element.name} "${url}" names nothing in this file, so its joints are not imported`);
58
+ }
59
+ return scope;
60
+ }
61
+ /** Counts one element or node looked at. */
62
+ visit() {
63
+ if (++this.visits > MAX_VISITS)
64
+ throw new LoaderError(F, 'limit', 'resolving the kinematics SID paths visits too many elements');
65
+ }
66
+ /** The `newparam` of SID `sid` nearest below `owner`. */
67
+ parameter(owner, sid) {
68
+ const queue = [owner];
69
+ for (let i = 0; i < queue.length; i++) {
70
+ this.visit();
71
+ const scope = queue[i];
72
+ if (scope.element.name === 'newparam' && scope.element.attributes.sid === sid)
73
+ return scope;
74
+ for (const child of scope.children)
75
+ queue.push(child);
76
+ }
77
+ return undefined;
78
+ }
79
+ /** Breadth-first from `start`, as SID addresses are searched. */
80
+ search(start, token, seen) {
81
+ const queue = [start];
82
+ for (let i = 0; i < queue.length; i++) {
83
+ const scope = queue[i];
84
+ this.visit();
85
+ const { sid, id } = scope.element.attributes;
86
+ if ((sid === token || id === token || scope.target?.attributes.id === token) && !seen.has(scope))
87
+ return scope;
88
+ for (const child of scope.children)
89
+ queue.push(child);
90
+ }
91
+ return undefined;
92
+ }
93
+ /** A `newparam` holding a SIDREF stands for what the SIDREF names. */
94
+ follow(scope, seen) {
95
+ if (scope.element.name !== 'newparam')
96
+ return scope;
97
+ const value = (this.overrides.get(scope) ?? scope).children[0];
98
+ if (value?.element.name !== 'SIDREF')
99
+ return scope;
100
+ if (seen.size >= MAX_DEPTH)
101
+ return undefined;
102
+ return this.resolve(textOf(value.element), value, new Set(seen).add(scope));
103
+ }
104
+ /**
105
+ * The element a SID path or parameter name addresses, seen from `from`: the first segment is an id or SID searched
106
+ * in the nearest enclosing scope outward (`.` is `from` itself), each later one a SID below the last.
107
+ */
108
+ resolve(path, from, seen = new Set()) {
109
+ this.visit();
110
+ const [first, ...rest] = path.split('/');
111
+ let hit = first === '.' ? from : undefined;
112
+ for (let scope = from; scope && !hit; scope = scope.parent)
113
+ hit = this.search(scope, first, seen);
114
+ for (let i = 0; hit; i++) {
115
+ hit = this.follow(hit, seen);
116
+ if (!hit || i === rest.length)
117
+ break;
118
+ const token = rest[i], found = this.below(hit, token, seen);
119
+ hit = found ?? (i === rest.length - 1 ? this.below(hit, withoutMember(token), seen) : undefined);
120
+ }
121
+ return hit;
122
+ }
123
+ below(scope, token, seen) {
124
+ for (const child of scope.children) {
125
+ this.visit();
126
+ if (child.element.attributes.sid === token && !seen.has(child))
127
+ return child;
128
+ }
129
+ for (const child of scope.children) {
130
+ const found = this.search(child, token, seen);
131
+ if (found)
132
+ return found;
133
+ }
134
+ return undefined;
135
+ }
136
+ /** The text of a value written plainly, as a typed child, or through a parameter. */
137
+ value(holder) {
138
+ const typed = holder.children.find((c) => /^(float|int|bool|param|SIDREF)$/.test(c.element.name));
139
+ if (!typed)
140
+ return holder.element.text.trim() || undefined;
141
+ if (typed.element.name !== 'param' && typed.element.name !== 'SIDREF')
142
+ return typed.element.text.trim();
143
+ const target = this.resolve(textOf(typed.element), holder);
144
+ const held = target && (this.overrides.get(target) ?? target);
145
+ return held && held !== holder ? held.children[0]?.element.text.trim() : undefined;
146
+ }
147
+ /** The `<revolute>` or `<prismatic>` an address leads to. */
148
+ axis(found, seen = 0) {
149
+ if (!found || seen > MAX_DEPTH)
150
+ return undefined;
151
+ const name = found.element.name;
152
+ if (PRIMITIVES.has(name))
153
+ return found;
154
+ if (name === 'axis' && found.parent && PRIMITIVES.has(found.parent.element.name))
155
+ return found.parent;
156
+ if (name === 'axis_info') {
157
+ const next = this.resolve(found.element.attributes.axis ?? '', found, new Set([found]));
158
+ return this.axis(next, seen + 1);
159
+ }
160
+ if (name === 'joint' || name === 'instance_joint') {
161
+ const primitives = found.children.filter((c) => PRIMITIVES.has(c.element.name));
162
+ if (primitives.length === 1)
163
+ return primitives[0];
164
+ }
165
+ return undefined;
166
+ }
167
+ }
168
+ const walk = (scope, visit) => {
169
+ visit(scope);
170
+ for (const child of scope.children)
171
+ walk(child, visit);
172
+ };
173
+ const part = (scope, name) => scope?.children.find((c) => c.element.name === name);
174
+ /** The transform of SID `sid` in `start` or nearest below it. */
175
+ function transformBelow(start, sid, resolver) {
176
+ const queue = [start];
177
+ for (let i = 0; i < queue.length; i++) {
178
+ resolver.visit();
179
+ const node = queue[i], transform = node.transforms.findIndex((t) => t.sid === sid);
180
+ if (transform >= 0)
181
+ return { node, transform };
182
+ for (const child of node.children)
183
+ queue.push(child);
184
+ }
185
+ return undefined;
186
+ }
187
+ /** The node of SID `sid` nearest below `start`. */
188
+ function nodeBelow(start, sid, resolver) {
189
+ const queue = [...start.children];
190
+ for (let i = 0; i < queue.length; i++) {
191
+ resolver.visit();
192
+ if (queue[i].sid === sid)
193
+ return queue[i];
194
+ for (const child of queue[i].children)
195
+ queue.push(child);
196
+ }
197
+ return undefined;
198
+ }
199
+ /** The node transforms `target` ("nodeId/sid/.../transformSid") names, one per copy of the node. */
200
+ function boundTransforms(byId, target, resolver) {
201
+ const [id, ...sids] = target.split('/'), last = sids.pop();
202
+ if (last === undefined)
203
+ return [];
204
+ const out = [];
205
+ for (const node of byId.get(id) ?? []) {
206
+ let from = node;
207
+ for (const step of sids)
208
+ from = from && nodeBelow(from, step, resolver);
209
+ if (!from)
210
+ continue;
211
+ // A trailing member selector (".ANGLE", "(2)") names one value of the transform.
212
+ const found = transformBelow(from, last, resolver) ?? transformBelow(from, withoutMember(last), resolver);
213
+ if (found)
214
+ out.push(found);
215
+ }
216
+ return out;
217
+ }
218
+ function readJoints(root, dae, warn) {
219
+ const ids = new Map();
220
+ const index = (e) => {
221
+ if (e.attributes.id)
222
+ ids.set(e.attributes.id, e);
223
+ for (const child of e.children)
224
+ index(child);
225
+ };
226
+ index(root);
227
+ let elements = kids(kid(root, 'scene'), 'instance_kinematics_scene');
228
+ if (!elements.length) {
229
+ elements = kids(root, 'library_kinematics_scenes').flatMap((l) => kids(l, 'kinematics_scene'));
230
+ if (!elements.length) {
231
+ if (kid(root, 'library_joints') || kid(root, 'library_kinematics_models'))
232
+ warn('the file has joints but no kinematics scene, so no joint is imported');
233
+ return [];
234
+ }
235
+ warn('<scene> instances no kinematics scene, so the joints drive no node');
236
+ }
237
+ const resolver = new Resolver(ids, warn), roots = elements.map((e) => resolver.expand(e, undefined, 0));
238
+ // setparam: inner instances first, so that an outer one has the last word.
239
+ const setters = [];
240
+ for (const scope of roots)
241
+ walk(scope, (s) => s.element.name === 'setparam' && setters.push(s));
242
+ for (const setter of setters.reverse()) {
243
+ const name = setter.element.attributes.ref ?? '', from = setter.parent;
244
+ // The reference names the parameter itself, so it is found without following what the parameter holds.
245
+ const split = name.lastIndexOf('/'), owner = split < 0 ? from : resolver.resolve(name.slice(0, split), from), last = name.slice(split + 1);
246
+ const found = owner && resolver.parameter(owner, last);
247
+ if (found)
248
+ resolver.overrides.set(found, setter);
249
+ else
250
+ warn(`setparam "${name}" names no parameter`);
251
+ }
252
+ const upAxis = AXES[dae.upAxis], axes = new Map(),
253
+ /** How many axes already have each path. */
254
+ taken = new Map(), tokens = [];
255
+ const number = (holder, scale, what) => {
256
+ if (!holder)
257
+ return undefined;
258
+ const text = resolver.value(holder), value = text === undefined ? Number.NaN : Number(text);
259
+ if (Number.isFinite(value))
260
+ return value * scale;
261
+ warn(`${what} has no finite value`);
262
+ return undefined;
263
+ };
264
+ const unit = (axis) => (axis.type === 'prismatic' ? dae.meter : 1);
265
+ const limit = (axis, limits) => {
266
+ for (const end of ['min', 'max']) {
267
+ const value = number(part(limits, end), unit(axis), `axis "${axis.path}" <${end}>`);
268
+ if (value !== undefined)
269
+ axis[end] = value;
270
+ }
271
+ };
272
+ const collect = (scope, path, joint) => {
273
+ const { name, attributes } = scope.element;
274
+ if (name === 'joint' || name === 'instance_joint')
275
+ joint = scope;
276
+ if (PRIMITIVES.has(name)) {
277
+ const text = part(scope, 'axis')?.element.text.trim() ?? '', v = text.split(/\s+/).map(Number), length = Math.hypot(...v);
278
+ if (v.length !== 3 || !(length > 0 && Number.isFinite(length)))
279
+ throw new LoaderError(F, 'syntax', `<${name}> needs an <axis> of three finite numbers, not all zero`);
280
+ const owner = joint?.element, definition = joint?.target ?? owner, token = owner?.attributes.sid ?? definition?.attributes.sid ?? definition?.attributes.id ?? 'joint', sid = attributes.sid ?? name;
281
+ const written = [...path, sid].join('/'), copy = (taken.get(written) ?? 0) + 1, full = copy > 1 ? `${written}#${copy}` : written;
282
+ taken.set(written, copy);
283
+ const axis = {
284
+ name: full,
285
+ path: full,
286
+ joint: definition?.attributes.name ?? token,
287
+ type: name,
288
+ axis: [0, 1, 2].map((r) => (upAxis[r * 3] * v[0] + upAxis[r * 3 + 1] * v[1] + upAxis[r * 3 + 2] * v[2]) / length),
289
+ value: 0,
290
+ active: true,
291
+ locked: false,
292
+ targets: [],
293
+ };
294
+ limit(axis, part(scope, 'limits'));
295
+ axes.set(scope, axis);
296
+ tokens.push({ joint: token, axis: sid });
297
+ return;
298
+ }
299
+ // technique_common and library containers have no SID, so they leave no step in the path.
300
+ const next = attributes.sid === undefined ? path : [...path, attributes.sid];
301
+ for (const child of scope.children)
302
+ collect(child, next, joint);
303
+ };
304
+ for (const scope of roots)
305
+ collect(scope, [], undefined);
306
+ const infos = [];
307
+ for (const scope of roots)
308
+ walk(scope, (s) => s.element.name === 'axis_info' && infos.push(s));
309
+ // A motion system's technique follows the system it instances, so document order applies inner bounds first.
310
+ for (const info of infos) {
311
+ const scope = resolver.axis(info), axis = scope && axes.get(scope);
312
+ if (!axis) {
313
+ warn(`axis_info "${info.element.attributes.axis ?? ''}" names no joint axis`);
314
+ continue;
315
+ }
316
+ limit(axis, part(info, 'limits'));
317
+ for (const flag of ['active', 'locked']) {
318
+ const holder = part(info, flag), text = holder && resolver.value(holder);
319
+ if (text !== undefined)
320
+ axis[flag] = text === 'true' || text === '1';
321
+ }
322
+ const order = number(part(info, 'index'), 1, `axis "${axis.path}" <index>`);
323
+ if (order !== undefined)
324
+ axis.index = order;
325
+ for (const bound of ['speed', 'acceleration', 'deceleration', 'jerk']) {
326
+ const value = number(part(info, bound), unit(axis), `axis "${axis.path}" <${bound}>`);
327
+ if (value !== undefined)
328
+ axis[bound] = value;
329
+ }
330
+ }
331
+ for (const axis of axes.values())
332
+ if (axis.min !== undefined && axis.max !== undefined && axis.min > axis.max) {
333
+ warn(`axis "${axis.path}" has its lower limit above its upper one, so it has no limits`);
334
+ delete axis.min;
335
+ delete axis.max;
336
+ }
337
+ const byId = new Map();
338
+ const register = (node) => {
339
+ if (node.id !== undefined) {
340
+ const list = byId.get(node.id);
341
+ if (list)
342
+ list.push(node);
343
+ else
344
+ byId.set(node.id, [node]);
345
+ }
346
+ for (const child of node.children)
347
+ register(child);
348
+ };
349
+ for (const node of dae.nodes)
350
+ register(node);
351
+ const initial = new Set();
352
+ for (const scope of roots)
353
+ for (const bind of scope.children) {
354
+ if (bind.element.name !== 'bind_joint_axis')
355
+ continue;
356
+ const target = bind.element.attributes.target ?? '', holder = part(bind, 'axis'), written = holder?.children[0], found = written
357
+ ? resolver.resolve(textOf(written.element), written)
358
+ : holder && resolver.resolve(holder.element.text.trim(), holder), primitive = resolver.axis(found), axis = primitive && axes.get(primitive);
359
+ if (!axis) {
360
+ warn(`bind_joint_axis "${target}" names no joint axis`);
361
+ continue;
362
+ }
363
+ const value = number(part(bind, 'value'), unit(axis), `bind_joint_axis "${target}" <value>`);
364
+ if (value !== undefined) {
365
+ axis.value = value;
366
+ initial.add(axis);
367
+ }
368
+ if (!target)
369
+ continue;
370
+ const wanted = axis.type === 'revolute' ? 'rotate' : 'translate', targets = boundTransforms(byId, target, resolver);
371
+ if (!targets.length)
372
+ warn(`bind_joint_axis target "${target}" names no node transform`);
373
+ for (const t of targets)
374
+ if (t.node.transforms[t.transform].type !== wanted)
375
+ warn(`bind_joint_axis target "${target}" is not a <${wanted}>, which a ${axis.type} axis needs`);
376
+ else
377
+ axis.targets.push(t);
378
+ }
379
+ // Without a bound value, an axis starts where its first target stands.
380
+ for (const axis of axes.values()) {
381
+ const first = axis.targets[0];
382
+ if (initial.has(axis) || !first)
383
+ continue;
384
+ const v = first.node.transforms[first.transform].values, along = fileAxis(upAxis, axis.axis), dot = along[0] * v[0] + along[1] * v[1] + along[2] * v[2];
385
+ axis.value = axis.type === 'revolute' ? v[3] * Math.sign(dot) : dot * dae.meter;
386
+ }
387
+ const list = [...axes.values()], candidates = tokens.map((t, i) => [t.joint, `${t.joint}/${t.axis}`, list[i].path]);
388
+ for (let level = 0; level < 2; level++) {
389
+ const count = new Map();
390
+ for (const c of candidates)
391
+ count.set(c[level], (count.get(c[level]) ?? 0) + 1);
392
+ list.forEach((axis, i) => {
393
+ if (axis.name === axis.path && count.get(candidates[i][level]) === 1)
394
+ axis.name = candidates[i][level];
395
+ });
396
+ }
397
+ return list;
398
+ }
399
+ /** The inverse of the up-axis rotation: a Y-up direction back in the file's axes. */
400
+ const fileAxis = (upAxis, v) => [0, 1, 2].map((c) => upAxis[c] * v[0] + upAxis[3 + c] * v[1] + upAxis[6 + c] * v[2]);
401
+ /**
402
+ * `parseDAE` plus the document's COLLADA 1.5 kinematics: `joints` lists every revolute and prismatic axis of the
403
+ * instanced kinematics scenes with its limits, its `axis_info` data and the node transforms it drives. What cannot be
404
+ * resolved is reported in `warnings`. Formulas, closed-loop attachments and tool frames are not evaluated.
405
+ */
406
+ export function parseDAEKinematics(input, options = {}) {
407
+ const root = daeRoot(input, options), dae = readDAE(root, options), warnings = new Set(dae.warnings), joints = readJoints(root, dae, (message) => void warnings.add(message));
408
+ return { ...dae, warnings: [...warnings], joints };
409
+ }
410
+ /**
411
+ * The scene with its joints at the given values (degrees for revolute axes, meters for prismatic ones), for
412
+ * `flattenDAE` or your own meshes: `world` holds every node's matrix. An axis left out stands at its `value`. Each
413
+ * bound transform becomes the axis' motion: a rotation about `axis`, or a translation along it. Values are held
414
+ * inside the limits unless `clamp` is false.
415
+ */
416
+ export function poseDAEJoints(dae, values = {}, options = {}) {
417
+ const byName = new Map(dae.joints.map((j) => [j.name, j]));
418
+ for (const name of Object.keys(values))
419
+ if (!byName.has(name))
420
+ throw new RangeError(`DAE joint "${name}" does not exist; pass one of ${[...byName.keys()].slice(0, 32).join(', ') || '(none)'}`);
421
+ const upAxis = AXES[dae.upAxis], changed = new Map();
422
+ for (const axis of dae.joints) {
423
+ let value = axis.value;
424
+ if (Object.hasOwn(values, axis.name)) {
425
+ value = values[axis.name];
426
+ if (typeof value !== 'number' || !Number.isFinite(value))
427
+ throw new RangeError(`DAE joint "${axis.name}" value ${value} is invalid; pass a finite number`);
428
+ if (axis.locked && value !== axis.value)
429
+ throw new RangeError(`DAE joint "${axis.name}" is locked at ${axis.value}; leave it out`);
430
+ if (options.clamp !== false)
431
+ value = Math.min(axis.max ?? Infinity, Math.max(axis.min ?? -Infinity, value));
432
+ }
433
+ const along = fileAxis(upAxis, axis.axis);
434
+ for (const { node, transform } of axis.targets) {
435
+ let list = changed.get(node);
436
+ if (!list)
437
+ changed.set(node, (list = node.transforms.slice()));
438
+ const moved = axis.type === 'revolute'
439
+ ? { type: 'rotate', values: [...along, value] }
440
+ : {
441
+ type: 'translate',
442
+ values: along.map((a) => (a * value) / dae.meter),
443
+ };
444
+ const sid = list[transform].sid;
445
+ if (sid !== undefined)
446
+ moved.sid = sid;
447
+ list[transform] = moved;
448
+ }
449
+ }
450
+ const convert = converter(dae.upAxis, dae.meter), local = new Map(), world = new Map();
451
+ const place = (node, parent) => {
452
+ const list = changed.get(node), matrix = list ? convert(stackMatrix(list)) : node.matrix, w = multiply(parent, matrix);
453
+ local.set(node, matrix);
454
+ world.set(node, w);
455
+ for (const child of node.children)
456
+ place(child, w);
457
+ };
458
+ for (const node of dae.nodes)
459
+ place(node, IDENTITY);
460
+ return { local, world, weights: dae.morphs.map((m) => [...m.weights]) };
461
+ }
package/dist/dae.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type LoadedGeometry, type LoadedGroup, type ParseLimits } from './types.js';
2
2
  import { type BinaryInput } from './util.js';
3
- import { type XMLExternalOptions } from './xml.js';
3
+ import { type XMLElement, type XMLExternalOptions } from './xml.js';
4
4
  import { type DAETransform } from './dae-common.js';
5
5
  import { type DAEMorph, type DAESkin } from './dae-controllers.js';
6
6
  import { type DAEAnimation, type DAEClip } from './dae-animation.js';
@@ -144,11 +144,16 @@ export interface DAEParseOptions extends ParseLimits, XMLExternalOptions {
144
144
  * node transform elements and morph weights) and animation clips are read too. `up_axis` and `unit` are converted to
145
145
  * Y-up meters, alike for geometry, node, bind shape and inverse bind matrices. `lookat` and `skew` join the transform
146
146
  * stack; `<instance_camera>` and `<instance_light>` give `cameras` and `lights` (technique_common optics and lights)
147
- * with their frames. Lines, polygon holes, and cameras, lights, channels or controllers that do not fit are not
148
- * imported; each is reported in `warnings`. Image paths are
149
- * relative to the .dae folder, for the caller's resolver.
147
+ * with their frames. `<lines>` and `<linestrips>` come back as each geometry's `lines`. Polygon holes, and cameras,
148
+ * lights, channels or controllers that do not fit, are not imported; each is reported in `warnings`. Image paths are
149
+ * relative to the .dae folder, for the caller's resolver. Joints are read by `parseDAEKinematics` of
150
+ * `@margoengine/loaders/dae-kinematics`.
150
151
  */
151
152
  export declare function parseDAE(input: BinaryInput | string, options?: DAEParseOptions): LoadedDAE;
153
+ /** The document's `<COLLADA>` element. */
154
+ export declare function daeRoot(input: BinaryInput | string, options: DAEParseOptions): XMLElement;
155
+ /** {@link parseDAE} of a document already read, for entries that also read other libraries of it. */
156
+ export declare function readDAE(root: XMLElement, options: DAEParseOptions): LoadedDAE;
152
157
  /**
153
158
  * Bakes a parsed COLLADA scene into one `LoadedGeometry` for `createMeshes` and `toGeometry`: every node instance's
154
159
  * geometry transformed by its world matrix (mirroring transforms keep outward winding), one group per instance and