three-usd-robot 0.11.0 → 0.13.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 (43) hide show
  1. package/README.md +32 -280
  2. package/dist/MeshBinding-B_8RhuQE.d.ts +288 -0
  3. package/dist/{ThreeUsdRobot-BxnCluuK.d.ts → ThreeUsdRobot-X1zbpRZo.d.ts} +38 -8
  4. package/dist/{ThreeUsdRobotLoader-C-E9uwEe.d.ts → ThreeUsdRobotLoader-u3d1yoLM.d.ts} +11 -3
  5. package/dist/{buildKinematicTree-BCySuZZn.d.ts → buildKinematicTree-Q9JOjAjM.d.ts} +17 -3
  6. package/dist/bytes-CxGRGry_.d.ts +14 -0
  7. package/dist/{chunk-BCRRXGNB.js → chunk-5ZPHZ5ZH.js} +81 -6
  8. package/dist/chunk-5ZPHZ5ZH.js.map +1 -0
  9. package/dist/{chunk-AXPMXEQC.js → chunk-FUVHAORT.js} +77 -717
  10. package/dist/chunk-FUVHAORT.js.map +1 -0
  11. package/dist/{chunk-5SVRTKS4.js → chunk-GRJGPHLW.js} +18 -11
  12. package/dist/chunk-GRJGPHLW.js.map +1 -0
  13. package/dist/chunk-JGIVJXBU.js +54 -0
  14. package/dist/chunk-JGIVJXBU.js.map +1 -0
  15. package/dist/{chunk-ENWFOYHU.js → chunk-JN2QPDB3.js} +101 -14
  16. package/dist/chunk-JN2QPDB3.js.map +1 -0
  17. package/dist/chunk-PPPRB6KE.js +963 -0
  18. package/dist/chunk-PPPRB6KE.js.map +1 -0
  19. package/dist/{chunk-LDO5FKQS.js → chunk-YGJ23CG3.js} +4 -53
  20. package/dist/chunk-YGJ23CG3.js.map +1 -0
  21. package/dist/core.d.ts +8 -65
  22. package/dist/core.js +5 -3
  23. package/dist/extras.d.ts +2 -2
  24. package/dist/helpers.d.ts +2 -2
  25. package/dist/helpers.js +3 -2
  26. package/dist/helpers.js.map +1 -1
  27. package/dist/index.d.ts +22 -263
  28. package/dist/index.js +35 -9
  29. package/dist/index.js.map +1 -1
  30. package/dist/nodes.d.ts +49 -0
  31. package/dist/nodes.js +439 -0
  32. package/dist/nodes.js.map +1 -0
  33. package/dist/parseMdl-vfzBGoMr.d.ts +87 -0
  34. package/dist/react.d.ts +6 -4
  35. package/dist/react.js +6 -4
  36. package/dist/react.js.map +1 -1
  37. package/package.json +6 -2
  38. package/dist/bytes-MOJ2oN-u.d.ts +0 -42
  39. package/dist/chunk-5SVRTKS4.js.map +0 -1
  40. package/dist/chunk-AXPMXEQC.js.map +0 -1
  41. package/dist/chunk-BCRRXGNB.js.map +0 -1
  42. package/dist/chunk-ENWFOYHU.js.map +0 -1
  43. package/dist/chunk-LDO5FKQS.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import * as THREE from 'three';
2
- import { J as JointType, A as Axis, a as JointDescription, L as LinkDescription, R as RobotDescription, K as KinematicTree, S as Stage } from './buildKinematicTree-BCySuZZn.js';
2
+ import { g as JointType, A as Axis, f as JointMimicDescription, e as JointDescription, j as LinkDescription, R as RobotDescription, K as KinematicTree, S as Stage } from './buildKinematicTree-Q9JOjAjM.js';
3
3
 
4
4
  /**
5
5
  * The articulated "motion" node of a joint, inserted between the joint's two
@@ -17,6 +17,8 @@ declare class JointObject extends THREE.Object3D {
17
17
  readonly axis: THREE.Vector3;
18
18
  readonly lower: number | undefined;
19
19
  readonly upper: number | undefined;
20
+ /** Mimic constraint this joint follows, if any (see {@link JointMimicDescription}). */
21
+ readonly mimic: JointMimicDescription | undefined;
20
22
  private _value;
21
23
  constructor(joint: JointDescription);
22
24
  get value(): number;
@@ -156,6 +158,10 @@ declare class ThreeUsdRobot extends THREE.Object3D {
156
158
  private readonly jointObjects;
157
159
  private readonly linkKeyByPath;
158
160
  private readonly jointKeyByPath;
161
+ /** Mimic edges among realized joints: leader key → followers. */
162
+ private readonly mimicFollowers;
163
+ private readonly mimicLeaderByFollower;
164
+ private warnedMimicDrive;
159
165
  private dirty;
160
166
  /** Constructed (fk rest) local matrix of every link, for baked→fk restore. */
161
167
  private readonly restLocal;
@@ -180,6 +186,17 @@ declare class ThreeUsdRobot extends THREE.Object3D {
180
186
  private applyStageNormalization;
181
187
  /** Apply each joint's authored initial value, if any. */
182
188
  private applyInitialPose;
189
+ /** Index the mimic edges realized in the tree (leader and follower both driven). */
190
+ private registerMimicFollowers;
191
+ /** Drive the followers of `leaderKey` from its current value (recursive, cycle-safe). */
192
+ private propagateMimic;
193
+ /** Re-derive every follower from its chain's top-most leader. */
194
+ private propagateAllMimic;
195
+ /** Whether the joint (key or prim path) is a mimic follower, driven by its leader. */
196
+ isMimicFollower(name: string): boolean;
197
+ /** Keys of the mimic-follower joints (excluded from {@link getJointNames}). */
198
+ getMimicJointNames(): string[];
199
+ private warnMimicDriveOnce;
183
200
  private attachRoot;
184
201
  private attachTreeEdges;
185
202
  /** Build `parent → frame0 → motion → frame1⁻¹ → child` for one joint. */
@@ -191,12 +208,15 @@ declare class ThreeUsdRobot extends THREE.Object3D {
191
208
  private jointKey;
192
209
  /**
193
210
  * Set one joint value, addressed by key or full prim path. Unknown joints
194
- * are ignored. Returns whether it applied. Always restores `"fk"` display
211
+ * are ignored, and so are mimic followers (their value derives from the
212
+ * leader; a warning is logged once). Driving a leader also updates its
213
+ * followers. Returns whether it applied. Always restores `"fk"` display
195
214
  * mode first (see {@link setLinkTransforms}).
196
215
  */
197
216
  setJointValue(name: string, value: number): boolean;
198
217
  /**
199
- * Set several joint values at once (matrix update is coalesced). Always
218
+ * Set several joint values at once (matrix update is coalesced). Mimic
219
+ * followers in the batch are skipped like in {@link setJointValue}. Always
200
220
  * restores `"fk"` display mode first, recomputing every link purely from
201
221
  * joint values — even an empty batch returns from baked playback (see
202
222
  * {@link setLinkTransforms}).
@@ -250,9 +270,11 @@ declare class ThreeUsdRobot extends THREE.Object3D {
250
270
  /**
251
271
  * Project a link-pose batch onto the joint manifold: the closed-form 1-DOF
252
272
  * joint values that best reproduce it, plus the same residuals as
253
- * {@link validateLinkTransforms}. `values` covers the articulated tree
254
- * joints, keyed by joint prim path, and feeds {@link setJointValues}
255
- * directly the constraint-respecting playback of the same track:
273
+ * {@link validateLinkTransforms}. `values` covers the commandable
274
+ * articulated tree joints (mimic followers excluded their leaders
275
+ * re-derive them), keyed by joint prim path, and feeds
276
+ * {@link setJointValues} directly — the constraint-respecting playback of
277
+ * the same track:
256
278
  *
257
279
  * ```ts
258
280
  * robot.setJointValues(robot.jointValuesFromLinkTransforms(poses, { previous }).values);
@@ -311,7 +333,11 @@ declare class ThreeUsdRobot extends THREE.Object3D {
311
333
  getJointObjectsByPath(): Map<string, JointObject>;
312
334
  getJoints(): JointDescription[];
313
335
  getLinks(): LinkDescription[];
314
- /** Names of the articulated (controllable) joints. */
336
+ /**
337
+ * Names of the commandable joints — articulated tree joints minus mimic
338
+ * followers, whose values derive from their leader
339
+ * (see {@link getMimicJointNames}).
340
+ */
315
341
  getJointNames(): string[];
316
342
  getLinkNames(): string[];
317
343
  getKinematicTree(): KinematicTree;
@@ -331,7 +357,11 @@ declare class ThreeUsdRobot extends THREE.Object3D {
331
357
  start: number;
332
358
  end: number;
333
359
  } | null;
334
- /** Sample every animated joint at time code `t` and apply the values (an fk drive — leaves baked mode). */
360
+ /**
361
+ * Sample every animated joint at time code `t` and apply the values (an fk
362
+ * drive — leaves baked mode). Samples on mimic followers are ignored; the
363
+ * constraint re-derives them from their leader.
364
+ */
335
365
  setTime(t: number): void;
336
366
  get showVisual(): boolean;
337
367
  set showVisual(v: boolean);
@@ -1,6 +1,8 @@
1
- import { R as RobotDescription } from './buildKinematicTree-BCySuZZn.js';
2
- import { A as AssetResolver, U as UsdSource, B as BinarySource } from './bytes-MOJ2oN-u.js';
3
- import { W as WorldUpAxis, a as ThreeUsdRobotOptions, T as ThreeUsdRobot } from './ThreeUsdRobot-BxnCluuK.js';
1
+ import { R as RobotDescription } from './buildKinematicTree-Q9JOjAjM.js';
2
+ import { A as AssetResolver } from './parseMdl-vfzBGoMr.js';
3
+ import { U as UsdSource, B as BinarySource } from './bytes-CxGRGry_.js';
4
+ import { M as MaterialFactory } from './MeshBinding-B_8RhuQE.js';
5
+ import { W as WorldUpAxis, a as ThreeUsdRobotOptions, T as ThreeUsdRobot } from './ThreeUsdRobot-X1zbpRZo.js';
4
6
 
5
7
  type ThreeUsdRobotLoaderOptions = {
6
8
  /** Resolver for references / payloads / sublayers (default {@link DefaultAssetResolver}). */
@@ -51,6 +53,12 @@ type ThreeUsdRobotLoaderOptions = {
51
53
  robotName?: string;
52
54
  /** Receives non-fatal load diagnostics. */
53
55
  onWarn?: (message: string) => void;
56
+ /**
57
+ * Overrides material creation for mesh-like gprims (M22) — e.g. the TSL
58
+ * MaterialX factory from `three-usd-robot/nodes`. Return `null` per prim to
59
+ * keep the default `UsdShade` resolution.
60
+ */
61
+ materialFactory?: MaterialFactory;
54
62
  };
55
63
  /**
56
64
  * Loads Isaac Sim / OpenUSD robot assets into a controllable {@link ThreeUsdRobot}.
@@ -223,8 +223,6 @@ declare function decomposeRigid(m: Mat4): {
223
223
  * {@link RobotDescription}; the kinematics builder (M4) trees it; the Three.js
224
224
  * runtime (M5) realizes it as an `Object3D` hierarchy. Keeping the IR free of
225
225
  * Three.js lets the same data drive tooling, validation, and (later) IK.
226
- *
227
- * See concept.md §9 for the rationale behind each field.
228
226
  */
229
227
 
230
228
  type JointType = "fixed" | "revolute" | "continuous" | "prismatic";
@@ -306,6 +304,22 @@ type JointDescription = {
306
304
  /** Time-sampled joint value trajectory (SI), if authored — drives playback. */
307
305
  valueSamples?: SampleChannel;
308
306
  drive?: JointDriveDescription;
307
+ /** Mimic constraint: this joint follows another joint's value. */
308
+ mimic?: JointMimicDescription;
309
+ };
310
+ /**
311
+ * A mimic constraint — `follower = multiplier · leader + offset` (URDF
312
+ * convention, SI units) — read from `NewtonMimicAPI` (Isaac Sim 6 / Newton
313
+ * authoring) or the legacy PhysX `PhysxMimicJointAPI`. Leader and follower
314
+ * must share the motion kind (angular ↔ angular, linear ↔ linear).
315
+ */
316
+ type JointMimicDescription = {
317
+ /** Leader joint key (same key space as {@link RobotDescription.joints}). */
318
+ joint: string;
319
+ /** Scale on the leader value (dimensionless between same-type joints). */
320
+ multiplier: number;
321
+ /** Offset added after scaling, in SI (radians / stage linear units). */
322
+ offset: number;
309
323
  };
310
324
  /** Authored joint drive parameters (`UsdPhysicsDriveAPI`), as read in M3. */
311
325
  type JointDriveDescription = {
@@ -528,4 +542,4 @@ type BuildTreeOptions = {
528
542
  };
529
543
  declare function buildKinematicTree(robot: RobotDescription, options?: BuildTreeOptions): KinematicTree;
530
544
 
531
- export { makeRotationZ as $, type Axis as A, type BuildTreeOptions as B, type CompositionArc as C, DEFAULT_METERS_PER_UNIT as D, buildKinematicTree as E, channelFromSamples as F, decomposeRigid as G, fromUsdMatrix as H, getTranslation as I, type JointType as J, type KinematicTree as K, type LinkDescription as L, type Mat4 as M, identity4 as N, interpolate as O, Prim as P, Quat as Q, type RobotDescription as R, Stage as S, type TreeEdge as T, type UsdaFile as U, type Vec2 as V, invert as W, makeEuler as X, makeRotationFromQuat as Y, makeRotationX as Z, makeRotationY as _, type JointDescription as a, makeScale as a0, makeTranslation as a1, multiply as a2, multiplyAll as a3, toUsdMatrix as a4, type Vec3 as b, type JointDriveDescription as c, type LinkInertialDescription as d, AssetPath as e, Attribute as f, type AttributeSpec as g, DEG2RAD as h, type KinematicNode as i, Layer as j, type ListOp as k, type MetadataMap as l, type PrimSpec as m, type PropertySpec as n, RAD2DEG as o, Relationship as p, type RelationshipSpec as q, type SampleChannel as r, type SdfPath as s, type Specifier as t, type UpAxis as u, type UsdDictionary as v, UsdMatrix as w, type UsdValue as x, type Variability as y, type Vec4 as z };
545
+ export { makeRotationY as $, type Axis as A, type BuildTreeOptions as B, type CompositionArc as C, DEFAULT_METERS_PER_UNIT as D, type Vec4 as E, buildKinematicTree as F, channelFromSamples as G, decomposeRigid as H, fromUsdMatrix as I, type JointDriveDescription as J, type KinematicTree as K, type LinkInertialDescription as L, type Mat4 as M, getTranslation as N, identity4 as O, Prim as P, Quat as Q, type RobotDescription as R, Stage as S, type TreeEdge as T, type UsdaFile as U, type Variability as V, interpolate as W, invert as X, makeEuler as Y, makeRotationFromQuat as Z, makeRotationX as _, AssetPath as a, makeRotationZ as a0, makeScale as a1, makeTranslation as a2, multiply as a3, multiplyAll as a4, toUsdMatrix as a5, Attribute as b, type AttributeSpec as c, DEG2RAD as d, type JointDescription as e, type JointMimicDescription as f, type JointType as g, type KinematicNode as h, Layer as i, type LinkDescription as j, type ListOp as k, type MetadataMap as l, type PrimSpec as m, type PropertySpec as n, RAD2DEG as o, Relationship as p, type RelationshipSpec as q, type SampleChannel as r, type SdfPath as s, type Specifier as t, type UpAxis as u, type UsdDictionary as v, UsdMatrix as w, type UsdValue as x, type Vec2 as y, type Vec3 as z };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * In-memory input normalization for the loader entry points. Callers hold USD
3
+ * content in many shapes — a `fetch` response's `ArrayBuffer`, a `Uint8Array`
4
+ * (or any typed-array view), a dropped `File` / `Blob` — and every byte-eating
5
+ * API here funnels through {@link toBytes} so all of them are accepted.
6
+ */
7
+ /** Binary USD content: an `ArrayBuffer`, any typed-array view, or a `Blob`/`File`. */
8
+ type BinarySource = ArrayBuffer | ArrayBufferView | Blob;
9
+ /** In-memory USD content: USDA source text, or {@link BinarySource} bytes. */
10
+ type UsdSource = string | BinarySource;
11
+ /** Normalize a {@link BinarySource} to bytes, honoring a view's offset/length. */
12
+ declare function toBytes(data: BinarySource): Promise<Uint8Array>;
13
+
14
+ export { type BinarySource as B, type UsdSource as U, toBytes as t };
@@ -1,5 +1,7 @@
1
- import { buildKinematicTree, ARTICULATION_ROOT_API, COLLISION_API, MESH_COLLISION_API, PHYSICS_MATERIAL_API, driveKindFor, jointValueFromSI, getMaterialSubsets, resolveBoundMaterial, computeLocalTransform, RIGID_BODY_API, MASS_API } from './chunk-AXPMXEQC.js';
2
- import { multiply, invert, identity4, Quat, AssetPath, toUsdMatrix, decomposeRigid } from './chunk-LDO5FKQS.js';
1
+ import { buildKinematicTree, ARTICULATION_ROOT_API, COLLISION_API, MESH_COLLISION_API, PHYSICS_MATERIAL_API, driveKindFor, jointValueFromSI, NEWTON_MIMIC_API, getMaterialSubsets, computeLocalTransform, RIGID_BODY_API, MASS_API } from './chunk-FUVHAORT.js';
2
+ import { multiply, invert, identity4, toUsdMatrix, decomposeRigid } from './chunk-YGJ23CG3.js';
3
+ import { resolveBoundMaterial } from './chunk-PPPRB6KE.js';
4
+ import { Quat, AssetPath } from './chunk-JGIVJXBU.js';
3
5
  import { strToU8, zipSync } from 'fflate';
4
6
 
5
7
  // src/version.ts
@@ -102,7 +104,20 @@ function exportRobotUsda(desc, options = {}) {
102
104
  continue;
103
105
  }
104
106
  emittedJoints.add(key);
105
- children.push(buildJointPrim(jointNames.get(key), key, joint, linkPath, isaac, warn));
107
+ }
108
+ const jointPath = (key) => emittedJoints.has(key) ? `/${robotName}/${jointNames.get(key)}` : void 0;
109
+ for (const key of emittedJoints) {
110
+ children.push(
111
+ buildJointPrim(
112
+ jointNames.get(key),
113
+ key,
114
+ desc.joints[key],
115
+ linkPath,
116
+ jointPath,
117
+ isaac,
118
+ warn
119
+ )
120
+ );
106
121
  }
107
122
  if (looksName) {
108
123
  children.push(buildLooksPrim(looksName, materials, materialNames, materialPath));
@@ -417,7 +432,7 @@ function transformProps(m) {
417
432
  arrayAttr("xformOpOrder", "token", ["xformOp:transform"], void 0, "uniform")
418
433
  ];
419
434
  }
420
- function buildJointPrim(name, key, joint, linkPath, isaac, warn) {
435
+ function buildJointPrim(name, key, joint, linkPath, jointPath, isaac, warn) {
421
436
  const kind = driveKindFor(joint.type);
422
437
  const angular = kind === "angular";
423
438
  const properties = [];
@@ -479,6 +494,19 @@ function buildJointPrim(name, key, joint, linkPath, isaac, warn) {
479
494
  }
480
495
  apiSchemas.push(`PhysicsDriveAPI:${kind}`);
481
496
  }
497
+ if (joint.mimic) {
498
+ const leaderPath = jointPath(joint.mimic.joint);
499
+ if (!leaderPath) {
500
+ warn(`joint "${key}": mimic leader "${joint.mimic.joint}" is not exported; mimic dropped`);
501
+ } else {
502
+ apiSchemas.push(NEWTON_MIMIC_API);
503
+ properties.push(rel("newton:mimicJoint", [leaderPath]));
504
+ properties.push(attr("newton:mimicCoef1", "float", joint.mimic.multiplier));
505
+ properties.push(
506
+ attr("newton:mimicCoef0", "float", jointValueFromSI(angular, joint.mimic.offset))
507
+ );
508
+ }
509
+ }
482
510
  if (isaac) {
483
511
  apiSchemas.push("IsaacJointAPI");
484
512
  if (joint.type !== "fixed") {
@@ -818,6 +846,7 @@ function writeUsdz(entries) {
818
846
  }
819
847
 
820
848
  // src/robot/RobotValidator.ts
849
+ var isAngular = (type) => type === "revolute" || type === "continuous";
821
850
  function validateRobotDescription(desc, options = {}) {
822
851
  const issues = [];
823
852
  const add = (severity, code, message, subject) => issues.push({ severity, code, message, ...subject !== void 0 ? { subject } : {} });
@@ -866,6 +895,52 @@ function validateRobotDescription(desc, options = {}) {
866
895
  );
867
896
  }
868
897
  }
898
+ const mimic = joint.mimic;
899
+ if (mimic) {
900
+ const leader = desc.joints[mimic.joint];
901
+ if (!leader) {
902
+ add(
903
+ "error",
904
+ "mimic-unknown-joint",
905
+ `joint "${key}" mimics unknown joint "${mimic.joint}"`,
906
+ key
907
+ );
908
+ } else if (joint.type === "fixed" || leader.type === "fixed") {
909
+ add(
910
+ "error",
911
+ "mimic-fixed-joint",
912
+ `joint "${key}" mimic involves a fixed joint (inert)`,
913
+ key
914
+ );
915
+ } else if (isAngular(joint.type) !== isAngular(leader.type)) {
916
+ add(
917
+ "error",
918
+ "mimic-type-mismatch",
919
+ `joint "${key}" (${joint.type}) mimics "${mimic.joint}" (${leader.type}) \u2014 leader and follower must share the motion kind`,
920
+ key
921
+ );
922
+ }
923
+ }
924
+ }
925
+ for (const startKey of Object.keys(desc.joints)) {
926
+ if (!desc.joints[startKey]?.mimic) continue;
927
+ const seen = /* @__PURE__ */ new Set();
928
+ let current = startKey;
929
+ while (current !== void 0 && desc.joints[current]?.mimic) {
930
+ const next = desc.joints[current].mimic.joint;
931
+ if (next === startKey) {
932
+ add(
933
+ "error",
934
+ "mimic-cycle",
935
+ `joint "${startKey}" is part of a mimic cycle \u2014 followers cannot be driven`,
936
+ startKey
937
+ );
938
+ break;
939
+ }
940
+ if (seen.has(next)) break;
941
+ seen.add(next);
942
+ current = next;
943
+ }
869
944
  }
870
945
  const tree = buildKinematicTree(desc);
871
946
  for (const jointKey of tree.loopJoints) {
@@ -932,5 +1007,5 @@ function validateRobotDescription(desc, options = {}) {
932
1007
  }
933
1008
 
934
1009
  export { PACKAGE_NAME, VERSION, exportRobotUsda, stageGeometryProvider, validateRobotDescription, writeUsdz };
935
- //# sourceMappingURL=chunk-BCRRXGNB.js.map
936
- //# sourceMappingURL=chunk-BCRRXGNB.js.map
1010
+ //# sourceMappingURL=chunk-5ZPHZ5ZH.js.map
1011
+ //# sourceMappingURL=chunk-5ZPHZ5ZH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/version.ts","../src/export/exportRobot.ts","../src/export/GeometryProvider.ts","../src/export/writeUsdz.ts","../src/robot/RobotValidator.ts"],"names":["attr"],"mappings":";;;;;;;AACO,IAAM,YAAA,GAAe;AAGrB,IAAM,OAAA,GAAU;;;ACsDvB,IAAM,sBAAA,GAAyB,sBAAA;AAsB/B,IAAM,oBAAA,GAAkD;AAAA,EACtD,KAAA,EAAO,mBAAA;AAAA,EACP,QAAA,EAAU,sBAAA;AAAA,EACV,UAAA,EAAY,sBAAA;AAAA,EACZ,SAAA,EAAW;AACb,CAAA;AAGO,SAAS,eAAA,CACd,IAAA,EACA,OAAA,GAA8B,EAAC,EACrB;AACV,EAAA,MAAM,IAAA,GAAO,CAAC,CAAA,KAAc,OAAA,CAAQ,SAAS,CAAC,CAAA;AAC9C,EAAA,MAAM,OAAO,kBAAA,CAAmB,IAAA,EAAM,EAAE,MAAA,EAAQ,MAAM,CAAA;AAEtD,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A,EAAG,MAAO,CAAA,CAAE,QAAA,KAAa,CAAA,CAAE,QAAA,GAAW,CAAA,GAAI,CAAA,CAAE,QAAA,KAAa,OAAA,GAAU,KAAK,CAAE,CAAA;AAChG","file":"chunk-5ZPHZ5ZH.js","sourcesContent":["/** Package identity. Kept in one place so every entry point can re-export it. */\nexport const PACKAGE_NAME = \"three-usd-robot\";\n\n/** Library version. Replaced by the release tooling at publish time. */\nexport const VERSION = \"0.0.0\";\n","/**\n * Robot IR → USDA layer (M13).\n *\n * Builds a self-contained UsdPhysics robot layer from a {@link RobotDescription}:\n * one `Xform` prim per link placed at its **zero-pose** world transform\n * (folding joint frames root-down, `T_child = T_parent · frame0 · frame1⁻¹`),\n * one `Physics*Joint` prim per joint, and the\n * link meshes supplied by a {@link RobotGeometryProvider}. Initial joint values\n * author as `PhysicsJointStateAPI` opinions rather than being baked into link\n * transforms, so a re-import applies them exactly once. Values convert back\n * from SI to authored units (angular radians → degrees).\n */\n\nimport {\n type Mat4,\n decomposeRigid,\n identity4,\n invert,\n multiply,\n toUsdMatrix,\n} from \"../kinematics/transforms.js\";\nimport type {\n AttributeSpec,\n MetadataMap,\n PrimSpec,\n PropertySpec,\n RelationshipSpec,\n UsdValue,\n UsdaFile,\n} from \"../parser/ast.js\";\nimport { AssetPath, Quat } from \"../parser/ast.js\";\nimport type {\n JointDescription,\n JointType,\n LinkInertialDescription,\n RobotDescription,\n} from \"../robot/RobotDescription.js\";\nimport { buildKinematicTree } from \"../robot/buildKinematicTree.js\";\nimport { jointValueFromSI } from \"../robot/normalize.js\";\nimport {\n ARTICULATION_ROOT_API,\n COLLISION_API,\n MASS_API,\n MESH_COLLISION_API,\n NEWTON_MIMIC_API,\n PHYSICS_MATERIAL_API,\n RIGID_BODY_API,\n driveKindFor,\n} from \"../schemas/usdPhysics.js\";\nimport type {\n ExportMaterial,\n ExportMesh,\n ExportPhysicsMaterial,\n RobotGeometryProvider,\n TextureChannel,\n} from \"./GeometryProvider.js\";\n\n/** PhysX articulation tuning API (Isaac / Omniverse). */\nconst PHYSX_ARTICULATION_API = \"PhysxArticulationAPI\";\n\nexport type ExportRobotOptions = {\n /** Supplies each link's meshes; omit for a kinematics-only layer. */\n geometry?: RobotGeometryProvider;\n /** Root prim name; defaults to the (sanitized) robot name. */\n robotName?: string;\n /**\n * Author `physxArticulation:enabledSelfCollisions` on the articulation root\n * (M16). `false` is the common Isaac stabilizer for adjacent-link contact.\n */\n enabledSelfCollisions?: boolean;\n /**\n * Apply the Isaac Sim Robot Schema (M16): `IsaacRobotAPI` on the root with\n * ordered `isaac:physics:robotLinks` / `robotJoints` relationships,\n * `IsaacLinkAPI` per link, and `IsaacJointAPI` (+ DOF order) per joint.\n */\n isaacRobotSchema?: boolean;\n /** Receives non-fatal export diagnostics. */\n onWarn?: (message: string) => void;\n};\n\nconst JOINT_SCHEMA_BY_TYPE: Record<JointType, string> = {\n fixed: \"PhysicsFixedJoint\",\n revolute: \"PhysicsRevoluteJoint\",\n continuous: \"PhysicsRevoluteJoint\",\n prismatic: \"PhysicsPrismaticJoint\",\n};\n\n/** Serialize a robot IR into a single-layer USDA AST (pass to `serializeUsda`). */\nexport function exportRobotUsda(\n desc: RobotDescription,\n options: ExportRobotOptions = {},\n): UsdaFile {\n const warn = (m: string) => options.onWarn?.(m);\n const tree = buildKinematicTree(desc, { onWarn: warn });\n\n const robotName = sanitizeName(options.robotName ?? desc.name ?? \"robot\");\n\n // One flat sibling namespace under the root prim for links and joints.\n const alloc = nameAllocator(warn);\n const linkNames = new Map<string, string>();\n for (const key of Object.keys(desc.links)) linkNames.set(key, alloc(key, `link \"${key}\"`));\n const jointNames = new Map<string, string>();\n for (const key of Object.keys(desc.joints)) jointNames.set(key, alloc(key, `joint \"${key}\"`));\n const linkPath = (key: string) => `/${robotName}/${linkNames.get(key)}`;\n\n // Zero-pose world placement per link, folded root-down along the tree.\n // Links no joint chain reaches (floating root / isolated) keep their\n // authored stage placement when the IR carries one.\n const authoredWorld = (key: string) => desc.links[key]?.worldTransform ?? identity4();\n const worldByLink = new Map<string, Mat4>();\n for (const key of tree.order) {\n const node = tree.nodes[key]!;\n if (node.parent === null || node.jointToParent === null) {\n const rootJoint = tree.rootJoint ? desc.joints[tree.rootJoint] : undefined;\n worldByLink.set(\n key,\n rootJoint\n ? multiply(rootJoint.jointFrame0, invert(rootJoint.jointFrame1))\n : authoredWorld(key),\n );\n continue;\n }\n const joint = desc.joints[node.jointToParent]!;\n const parentWorld = worldByLink.get(node.parent) ?? identity4();\n worldByLink.set(\n key,\n multiply(multiply(parentWorld, joint.jointFrame0), invert(joint.jointFrame1)),\n );\n }\n for (const key of tree.isolatedLinks) worldByLink.set(key, authoredWorld(key));\n\n // Articulation root: preserve link-level APIs from the IR; otherwise apply it\n // on the container prim (never both — nested articulation roots are invalid).\n const articulationLinks = new Set(desc.articulationRoots ?? []);\n\n // Gather meshes once, then dedupe their (physics) materials by name.\n const meshesByLink = new Map<string, ExportMesh[]>();\n const materials = new Map<string, ExportMaterial>();\n const physicsMaterials = new Map<string, ExportPhysicsMaterial>();\n for (const [key, link] of Object.entries(desc.links)) {\n const meshes = options.geometry?.(key, link) ?? [];\n meshesByLink.set(key, meshes);\n for (const mesh of meshes) {\n if (mesh.material && !materials.has(mesh.material.name)) {\n materials.set(mesh.material.name, mesh.material);\n }\n if (mesh.physicsMaterial && !physicsMaterials.has(mesh.physicsMaterial.name)) {\n physicsMaterials.set(mesh.physicsMaterial.name, mesh.physicsMaterial);\n }\n }\n }\n const looksName = materials.size > 0 ? alloc(\"Looks\") : undefined;\n const materialAlloc = nameAllocator();\n const materialNames = new Map<string, string>();\n for (const name of materials.keys()) materialNames.set(name, materialAlloc(name));\n const materialPath = (name: string) =>\n looksName ? `/${robotName}/${looksName}/${materialNames.get(name)}` : undefined;\n\n const physicsScopeName = physicsMaterials.size > 0 ? alloc(\"PhysicsMaterials\") : undefined;\n const physicsMaterialAlloc = nameAllocator();\n const physicsMaterialNames = new Map<string, string>();\n for (const name of physicsMaterials.keys()) {\n physicsMaterialNames.set(name, physicsMaterialAlloc(name));\n }\n const physicsMaterialPath = (name: string) =>\n physicsScopeName\n ? `/${robotName}/${physicsScopeName}/${physicsMaterialNames.get(name)}`\n : undefined;\n\n const isaac = options.isaacRobotSchema === true;\n const children: PrimSpec[] = [];\n for (const [key, link] of Object.entries(desc.links)) {\n const apiSchemas = [RIGID_BODY_API];\n if (articulationLinks.has(key)) apiSchemas.push(ARTICULATION_ROOT_API);\n if (link.inertial) apiSchemas.push(MASS_API);\n if (isaac) apiSchemas.push(\"IsaacLinkAPI\");\n const selfCollision = articulationLinks.has(key) ? options.enabledSelfCollisions : undefined;\n if (selfCollision !== undefined) apiSchemas.push(PHYSX_ARTICULATION_API);\n children.push(\n buildLinkPrim({\n name: linkNames.get(key)!,\n world: worldByLink.get(key) ?? identity4(),\n apiSchemas,\n meshes: meshesByLink.get(key) ?? [],\n materialPath,\n physicsMaterialPath,\n warn,\n ...(link.inertial ? { inertial: link.inertial } : {}),\n ...(selfCollision !== undefined ? { selfCollision } : {}),\n }),\n );\n }\n const emittedJoints = new Set<string>();\n for (const [key, joint] of Object.entries(desc.joints)) {\n if (!desc.links[joint.child] || (joint.parent !== \"\" && !desc.links[joint.parent])) {\n warn(`joint \"${key}\" references an unknown link; skipped`);\n continue;\n }\n emittedJoints.add(key);\n }\n const jointPath = (key: string) =>\n emittedJoints.has(key) ? `/${robotName}/${jointNames.get(key)}` : undefined;\n for (const key of emittedJoints) {\n children.push(\n buildJointPrim(\n jointNames.get(key)!,\n key,\n desc.joints[key]!,\n linkPath,\n jointPath,\n isaac,\n warn,\n ),\n );\n }\n if (looksName) {\n children.push(buildLooksPrim(looksName, materials, materialNames, materialPath));\n }\n if (physicsScopeName) {\n children.push(\n buildPhysicsMaterialsPrim(physicsScopeName, physicsMaterials, physicsMaterialNames),\n );\n }\n\n const rootApiSchemas: string[] = [];\n const rootProperties: PropertySpec[] = [];\n if (articulationLinks.size === 0) {\n rootApiSchemas.push(ARTICULATION_ROOT_API);\n if (options.enabledSelfCollisions !== undefined) {\n rootApiSchemas.push(PHYSX_ARTICULATION_API);\n rootProperties.push(\n attr(\"physxArticulation:enabledSelfCollisions\", \"bool\", options.enabledSelfCollisions),\n );\n }\n }\n if (isaac) {\n rootApiSchemas.push(\"IsaacRobotAPI\");\n const orderedLinks = [...tree.order, ...tree.isolatedLinks];\n const orderedJoints: string[] = [];\n const pushJoint = (key: string | null | undefined) => {\n if (key && emittedJoints.has(key) && !orderedJoints.includes(key)) orderedJoints.push(key);\n };\n pushJoint(tree.rootJoint);\n for (const linkKey of tree.order) pushJoint(tree.nodes[linkKey]?.jointToParent);\n for (const jointKey of tree.loopJoints) pushJoint(jointKey);\n for (const jointKey of Object.keys(desc.joints)) pushJoint(jointKey);\n\n rootProperties.push(rel(\"isaac:physics:robotLinks\", orderedLinks.map(linkPath)));\n rootProperties.push(\n rel(\n \"isaac:physics:robotJoints\",\n orderedJoints.map((key) => `/${robotName}/${jointNames.get(key)}`),\n ),\n );\n }\n\n const root: PrimSpec = {\n specifier: \"def\",\n typeName: \"Xform\",\n name: robotName,\n metadata: rootApiSchemas.length > 0 ? { apiSchemas: rootApiSchemas } : {},\n properties: rootProperties,\n children,\n line: 0,\n };\n\n const metadata: MetadataMap = {\n defaultPrim: robotName,\n metersPerUnit: desc.metersPerUnit,\n upAxis: desc.upAxis,\n ...(desc.timeCodesPerSecond !== undefined\n ? { timeCodesPerSecond: desc.timeCodesPerSecond }\n : {}),\n ...(desc.startTimeCode !== undefined ? { startTimeCode: desc.startTimeCode } : {}),\n ...(desc.endTimeCode !== undefined ? { endTimeCode: desc.endTimeCode } : {}),\n };\n\n return { version: \"1.0\", metadata, prims: [root] };\n}\n\n// ---------------------------------------------------------------------------\n// Links & meshes\n// ---------------------------------------------------------------------------\n\ntype LinkPrimArgs = {\n name: string;\n world: Mat4;\n apiSchemas: string[];\n meshes: ExportMesh[];\n inertial?: LinkInertialDescription;\n /** `physxArticulation:enabledSelfCollisions` for link-level articulation roots. */\n selfCollision?: boolean;\n materialPath: (name: string) => string | undefined;\n physicsMaterialPath: (name: string) => string | undefined;\n warn: (message: string) => void;\n};\n\nfunction buildLinkPrim(args: LinkPrimArgs): PrimSpec {\n const meshAlloc = nameAllocator();\n const properties: PropertySpec[] = transformProps(args.world);\n if (args.inertial) properties.push(...massProps(args.inertial, args.name, args.warn));\n if (args.selfCollision !== undefined) {\n properties.push(attr(\"physxArticulation:enabledSelfCollisions\", \"bool\", args.selfCollision));\n }\n return {\n specifier: \"def\",\n typeName: \"Xform\",\n name: args.name,\n metadata: { apiSchemas: args.apiSchemas },\n properties,\n children: args.meshes.map((mesh) =>\n buildMeshPrim(mesh, meshAlloc(mesh.name), args.materialPath, args.physicsMaterialPath),\n ),\n line: 0,\n };\n}\n\n/**\n * `UsdPhysicsMassAPI` attributes for a link's mass properties. UsdPhysics\n * requires `diagonalInertia` and `principalAxes` to be authored together, so a\n * missing principal-axes frame is completed with the identity quaternion\n * (equivalent — the diagonal is then in the body frame) and axes without a\n * diagonal are dropped (meaningless alone).\n */\nfunction massProps(\n inertial: LinkInertialDescription,\n linkName: string,\n warn: (message: string) => void,\n): PropertySpec[] {\n const out: PropertySpec[] = [];\n if (inertial.mass !== undefined) out.push(attr(\"physics:mass\", \"float\", inertial.mass));\n if (inertial.density !== undefined) out.push(attr(\"physics:density\", \"float\", inertial.density));\n if (inertial.centerOfMass) {\n out.push(attr(\"physics:centerOfMass\", \"point3f\", inertial.centerOfMass));\n }\n if (inertial.diagonalInertia) {\n out.push(attr(\"physics:diagonalInertia\", \"float3\", inertial.diagonalInertia));\n out.push(attr(\"physics:principalAxes\", \"quatf\", inertial.principalAxes ?? Quat.identity()));\n } else if (inertial.principalAxes) {\n warn(`link \"${linkName}\": principalAxes without diagonalInertia is meaningless; dropped`);\n }\n return out;\n}\n\nfunction buildMeshPrim(\n mesh: ExportMesh,\n name: string,\n materialPath: (name: string) => string | undefined,\n physicsMaterialPath: (name: string) => string | undefined,\n): PrimSpec {\n const properties: PropertySpec[] = [];\n if (mesh.transform) properties.push(...transformProps(mesh.transform));\n properties.push(\n arrayAttr(\"faceVertexCounts\", \"int\", mesh.faceVertexCounts),\n arrayAttr(\"faceVertexIndices\", \"int\", mesh.faceVertexIndices),\n arrayAttr(\"points\", \"point3f\", mesh.points),\n );\n if (mesh.normals) properties.push(arrayAttr(\"normals\", \"normal3f\", mesh.normals));\n if (mesh.st) {\n properties.push(arrayAttr(\"primvars:st\", \"texCoord2f\", mesh.st, { interpolation: \"vertex\" }));\n }\n if (mesh.displayColor) {\n properties.push(arrayAttr(\"primvars:displayColor\", \"color3f\", [mesh.displayColor]));\n }\n if (mesh.doubleSided) properties.push(attr(\"doubleSided\", \"bool\", true));\n properties.push(uniformToken(\"subdivisionScheme\", \"none\"));\n\n const apiSchemas: string[] = [];\n if (mesh.kind === \"collision\") {\n apiSchemas.push(COLLISION_API);\n // `guide` keeps collision shapes out of the render pass (usdview, Isaac Sim,\n // and this package's own loader) while PhysX still collides with them.\n properties.push(uniformToken(\"purpose\", \"guide\"));\n if (mesh.collisionApproximation) {\n apiSchemas.push(MESH_COLLISION_API);\n properties.push(uniformToken(\"physics:approximation\", mesh.collisionApproximation));\n }\n }\n const binding = mesh.material ? materialPath(mesh.material.name) : undefined;\n if (binding) properties.push(rel(\"material:binding\", [binding]));\n const physicsBinding =\n mesh.kind === \"collision\" && mesh.physicsMaterial\n ? physicsMaterialPath(mesh.physicsMaterial.name)\n : undefined;\n if (physicsBinding) properties.push(rel(\"material:binding:physics\", [physicsBinding]));\n if (binding || physicsBinding) apiSchemas.push(\"MaterialBindingAPI\");\n\n return {\n specifier: \"def\",\n typeName: \"Mesh\",\n name,\n metadata: apiSchemas.length > 0 ? { apiSchemas } : {},\n properties,\n children: [],\n line: 0,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Physics materials\n// ---------------------------------------------------------------------------\n\n/** `Scope` holding one `PhysicsMaterialAPI` material per unique name. */\nfunction buildPhysicsMaterialsPrim(\n scopeName: string,\n materials: Map<string, ExportPhysicsMaterial>,\n names: Map<string, string>,\n): PrimSpec {\n const children: PrimSpec[] = [];\n for (const [key, material] of materials) {\n children.push(buildPhysicsMaterialPrim(names.get(key)!, material));\n }\n return {\n specifier: \"def\",\n typeName: \"Scope\",\n name: scopeName,\n metadata: {},\n properties: [],\n children,\n line: 0,\n };\n}\n\nfunction buildPhysicsMaterialPrim(name: string, material: ExportPhysicsMaterial): PrimSpec {\n const properties: PropertySpec[] = [];\n if (material.staticFriction !== undefined) {\n properties.push(attr(\"physics:staticFriction\", \"float\", material.staticFriction));\n }\n if (material.dynamicFriction !== undefined) {\n properties.push(attr(\"physics:dynamicFriction\", \"float\", material.dynamicFriction));\n }\n if (material.restitution !== undefined) {\n properties.push(attr(\"physics:restitution\", \"float\", material.restitution));\n }\n if (material.density !== undefined) {\n properties.push(attr(\"physics:density\", \"float\", material.density));\n }\n return {\n specifier: \"def\",\n typeName: \"Material\",\n name,\n metadata: { apiSchemas: [PHYSICS_MATERIAL_API] },\n properties,\n children: [],\n line: 0,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Materials\n// ---------------------------------------------------------------------------\n\n/** `Scope` holding one `Material` + `UsdPreviewSurface` shader per material. */\nfunction buildLooksPrim(\n looksName: string,\n materials: Map<string, ExportMaterial>,\n materialNames: Map<string, string>,\n materialPath: (name: string) => string | undefined,\n): PrimSpec {\n const children: PrimSpec[] = [];\n for (const [key, material] of materials) {\n children.push(buildMaterialPrim(materialNames.get(key)!, material, materialPath(key)!));\n }\n return {\n specifier: \"def\",\n typeName: \"Scope\",\n name: looksName,\n metadata: {},\n properties: [],\n children,\n line: 0,\n };\n}\n\n/** How each texture channel wires into `UsdPreviewSurface`. */\nconst TEXTURE_WIRING: Record<\n TextureChannel,\n { input: string; inputType: string; output: string; outputType: string; colorSpace: string }\n> = {\n color: {\n input: \"inputs:diffuseColor\",\n inputType: \"color3f\",\n output: \"outputs:rgb\",\n outputType: \"float3\",\n colorSpace: \"sRGB\",\n },\n emissive: {\n input: \"inputs:emissiveColor\",\n inputType: \"color3f\",\n output: \"outputs:rgb\",\n outputType: \"float3\",\n colorSpace: \"sRGB\",\n },\n normal: {\n input: \"inputs:normal\",\n inputType: \"normal3f\",\n output: \"outputs:rgb\",\n outputType: \"float3\",\n colorSpace: \"raw\",\n },\n opacity: {\n input: \"inputs:opacity\",\n inputType: \"float\",\n output: \"outputs:a\",\n outputType: \"float\",\n colorSpace: \"raw\",\n },\n roughness: {\n input: \"inputs:roughness\",\n inputType: \"float\",\n output: \"outputs:r\",\n outputType: \"float\",\n colorSpace: \"raw\",\n },\n metalness: {\n input: \"inputs:metallic\",\n inputType: \"float\",\n output: \"outputs:r\",\n outputType: \"float\",\n colorSpace: \"raw\",\n },\n occlusion: {\n input: \"inputs:occlusion\",\n inputType: \"float\",\n output: \"outputs:r\",\n outputType: \"float\",\n colorSpace: \"raw\",\n },\n};\n\nfunction buildMaterialPrim(name: string, material: ExportMaterial, selfPath: string): PrimSpec {\n const textures = material.textures ?? {};\n const shaderProps: PropertySpec[] = [uniformToken(\"info:id\", \"UsdPreviewSurface\")];\n\n // A surface input: constant value, texture connection, or both (the\n // connection wins per UsdShade; the constant stays for flat consumers).\n const input = (channel: TextureChannel, value?: UsdValue) => {\n const wiring = TEXTURE_WIRING[channel];\n const texturePath = textures[channel];\n if (value === undefined && texturePath === undefined) return;\n const spec = attr(wiring.input, wiring.inputType, value);\n if (texturePath !== undefined) {\n spec.connections = [`${selfPath}/${channel}Texture.${wiring.output}`];\n }\n shaderProps.push(spec);\n };\n input(\"color\", material.diffuseColor);\n input(\"metalness\", material.metallic);\n input(\"roughness\", material.roughness);\n input(\"opacity\", material.opacity);\n input(\"emissive\", material.emissiveColor);\n input(\"normal\");\n input(\"occlusion\");\n shaderProps.push(attr(\"outputs:surface\", \"token\", undefined));\n\n const children: PrimSpec[] = [shaderPrim(\"PreviewSurface\", shaderProps)];\n const textureEntries = Object.entries(textures) as [TextureChannel, string][];\n if (textureEntries.length > 0) {\n children.push(\n shaderPrim(\"stReader\", [\n uniformToken(\"info:id\", \"UsdPrimvarReader_float2\"),\n attr(\"inputs:varname\", \"string\", \"st\"),\n attr(\"outputs:result\", \"float2\", undefined),\n ]),\n );\n for (const [channel, path] of textureEntries) {\n children.push(buildUvTexturePrim(channel, path, selfPath));\n }\n }\n\n const surfaceConnect = attr(\"outputs:surface\", \"token\", undefined);\n surfaceConnect.connections = [`${selfPath}/PreviewSurface.outputs:surface`];\n\n return {\n specifier: \"def\",\n typeName: \"Material\",\n name,\n metadata: {},\n properties: [surfaceConnect],\n children,\n line: 0,\n };\n}\n\n/** `UsdUVTexture` node for one channel, fed by the material's `stReader`. */\nfunction buildUvTexturePrim(channel: TextureChannel, path: string, selfPath: string): PrimSpec {\n const wiring = TEXTURE_WIRING[channel];\n const st = attr(\"inputs:st\", \"float2\", undefined);\n st.connections = [`${selfPath}/stReader.outputs:result`];\n return shaderPrim(`${channel}Texture`, [\n uniformToken(\"info:id\", \"UsdUVTexture\"),\n attr(\"inputs:file\", \"asset\", new AssetPath(path)),\n uniformToken(\"inputs:sourceColorSpace\", wiring.colorSpace),\n st,\n attr(wiring.output, wiring.outputType, undefined),\n ]);\n}\n\nfunction shaderPrim(name: string, properties: PropertySpec[]): PrimSpec {\n return {\n specifier: \"def\",\n typeName: \"Shader\",\n name,\n metadata: {},\n properties,\n children: [],\n line: 0,\n };\n}\n\n/** `xformOp:transform` + `xformOpOrder` for an explicit matrix placement. */\nfunction transformProps(m: Mat4): PropertySpec[] {\n return [\n attr(\"xformOp:transform\", \"matrix4d\", toUsdMatrix(m)),\n arrayAttr(\"xformOpOrder\", \"token\", [\"xformOp:transform\"], undefined, \"uniform\"),\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Joints\n// ---------------------------------------------------------------------------\n\nfunction buildJointPrim(\n name: string,\n key: string,\n joint: JointDescription,\n linkPath: (key: string) => string,\n jointPath: (key: string) => string | undefined,\n isaac: boolean,\n warn: (m: string) => void,\n): PrimSpec {\n const kind = driveKindFor(joint.type);\n const angular = kind === \"angular\";\n const properties: PropertySpec[] = [];\n const apiSchemas: string[] = [];\n\n if (joint.parent !== \"\") properties.push(rel(\"physics:body0\", [linkPath(joint.parent)]));\n properties.push(rel(\"physics:body1\", [linkPath(joint.child)]));\n if (joint.type !== \"fixed\") properties.push(uniformToken(\"physics:axis\", joint.axis));\n if (joint.lower !== undefined) {\n properties.push(attr(\"physics:lowerLimit\", \"float\", jointValueFromSI(angular, joint.lower)));\n }\n if (joint.upper !== undefined) {\n properties.push(attr(\"physics:upperLimit\", \"float\", jointValueFromSI(angular, joint.upper)));\n }\n\n for (const index of [0, 1] as const) {\n const frame = index === 0 ? joint.jointFrame0 : joint.jointFrame1;\n const { position, orientation, rigid } = decomposeRigid(frame);\n if (!rigid) {\n warn(`joint \"${key}\": jointFrame${index} is not rigid; scale/shear was discarded`);\n }\n properties.push(attr(`physics:localPos${index}`, \"point3f\", position));\n properties.push(attr(`physics:localRot${index}`, \"quatf\", orientation));\n }\n\n // Joint state: the initial value and/or the sampled trajectory (SI → authored).\n if (joint.initialValue !== undefined || joint.valueSamples) {\n const state = attr(\n `state:${kind}:physics:position`,\n \"float\",\n joint.initialValue !== undefined ? jointValueFromSI(angular, joint.initialValue) : undefined,\n );\n if (joint.valueSamples) {\n state.timeSamples = new Map(\n joint.valueSamples.times.map((t, i) => [\n t,\n jointValueFromSI(angular, joint.valueSamples!.values[i] ?? 0),\n ]),\n );\n }\n properties.push(state);\n apiSchemas.push(`PhysicsJointStateAPI:${kind}`);\n }\n\n if (joint.drive) {\n const d = joint.drive;\n if (d.targetPosition !== undefined) {\n properties.push(\n attr(\n `drive:${kind}:physics:targetPosition`,\n \"float\",\n jointValueFromSI(angular, d.targetPosition),\n ),\n );\n }\n if (d.stiffness !== undefined) {\n properties.push(attr(`drive:${kind}:physics:stiffness`, \"float\", d.stiffness));\n }\n if (d.damping !== undefined) {\n properties.push(attr(`drive:${kind}:physics:damping`, \"float\", d.damping));\n }\n if (d.maxForce !== undefined) {\n properties.push(attr(`drive:${kind}:physics:maxForce`, \"float\", d.maxForce));\n }\n apiSchemas.push(`PhysicsDriveAPI:${kind}`);\n }\n\n // Mimic constraint → NewtonMimicAPI (`follower = coef0 + coef1 · leader`),\n // the form Isaac Sim 6 / Newton author and consume. Offset back to authored\n // units (degrees for angular).\n if (joint.mimic) {\n const leaderPath = jointPath(joint.mimic.joint);\n if (!leaderPath) {\n warn(`joint \"${key}\": mimic leader \"${joint.mimic.joint}\" is not exported; mimic dropped`);\n } else {\n apiSchemas.push(NEWTON_MIMIC_API);\n properties.push(rel(\"newton:mimicJoint\", [leaderPath]));\n properties.push(attr(\"newton:mimicCoef1\", \"float\", joint.mimic.multiplier));\n properties.push(\n attr(\"newton:mimicCoef0\", \"float\", jointValueFromSI(angular, joint.mimic.offset)),\n );\n }\n }\n\n if (isaac) {\n apiSchemas.push(\"IsaacJointAPI\");\n if (joint.type !== \"fixed\") {\n const prefix = joint.type === \"prismatic\" ? \"Trans\" : \"Rot\";\n properties.push(\n arrayAttr(\"isaac:physics:DofOffsetOpOrder\", \"token\", [`${prefix}${joint.axis}`]),\n );\n }\n }\n\n return {\n specifier: \"def\",\n typeName: JOINT_SCHEMA_BY_TYPE[joint.type],\n name,\n metadata: apiSchemas.length > 0 ? { apiSchemas } : {},\n properties,\n children: [],\n line: 0,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Naming & spec helpers\n// ---------------------------------------------------------------------------\n\n/** Make a valid USD identifier out of an arbitrary key (`/a/b c` → `_a_b_c`). */\nfunction sanitizeName(raw: string): string {\n const cleaned = raw.replace(/[^A-Za-z0-9_]/g, \"_\");\n const named = cleaned.length > 0 ? cleaned : \"_\";\n return /^[0-9]/.test(named) ? `_${named}` : named;\n}\n\n/** Allocates unique sanitized sibling names, warning when a name changes. */\nfunction nameAllocator(warn?: (m: string) => void): (raw: string, label?: string) => string {\n const used = new Set<string>();\n return (raw, label) => {\n let name = sanitizeName(raw);\n for (let i = 2; used.has(name); i++) name = `${sanitizeName(raw)}_${i}`;\n used.add(name);\n if (name !== raw && label && warn) warn(`${label} exported as prim \"${name}\"`);\n return name;\n };\n}\n\nfunction attr(\n name: string,\n typeName: string,\n value: UsdValue | undefined,\n metadata: MetadataMap = {},\n): AttributeSpec {\n return {\n kind: \"attribute\",\n name,\n typeName,\n isArray: false,\n variability: \"varying\",\n custom: false,\n ...(value !== undefined ? { value } : {}),\n metadata,\n line: 0,\n };\n}\n\nfunction arrayAttr(\n name: string,\n typeName: string,\n value: UsdValue[],\n metadata: MetadataMap = {},\n variability: \"varying\" | \"uniform\" = \"varying\",\n): AttributeSpec {\n return {\n kind: \"attribute\",\n name,\n typeName,\n isArray: true,\n variability,\n custom: false,\n value,\n metadata,\n line: 0,\n };\n}\n\nfunction uniformToken(name: string, value: string): AttributeSpec {\n return {\n kind: \"attribute\",\n name,\n typeName: \"token\",\n isArray: false,\n variability: \"uniform\",\n custom: false,\n value,\n metadata: {},\n line: 0,\n };\n}\n\nfunction rel(name: string, targets: string[]): RelationshipSpec {\n return {\n kind: \"relationship\",\n name,\n custom: false,\n listOp: \"explicit\",\n targets,\n metadata: {},\n line: 0,\n };\n}\n","/**\n * Geometry access for the robot exporter (M13).\n *\n * `exportRobotUsda` is geometry-agnostic: a {@link RobotGeometryProvider}\n * supplies each link's meshes as plain data. {@link stageGeometryProvider}\n * reads them back off a loaded {@link Stage} for round-trip export; the\n * Three.js authoring side (M14) supplies one backed by `BufferGeometry`.\n */\n\nimport { type Mat4, identity4, multiply } from \"../kinematics/transforms.js\";\nimport type { Vec2, Vec3 } from \"../parser/ast.js\";\nimport type { LinkDescription } from \"../robot/RobotDescription.js\";\nimport { getMaterialSubsets } from \"../schemas/usdGeom.js\";\nimport { resolveBoundMaterial } from \"../three/MaterialBinding.js\";\nimport type { Prim } from \"../usd/Prim.js\";\nimport type { Stage } from \"../usd/Stage.js\";\nimport { computeLocalTransform } from \"../usd/xformOps.js\";\n\n/** Texture channels a `UsdPreviewSurface` network can reference (M15). */\nexport type TextureChannel =\n | \"color\"\n | \"opacity\"\n | \"normal\"\n | \"roughness\"\n | \"metalness\"\n | \"occlusion\"\n | \"emissive\";\n\n/**\n * PBR parameters for a mesh, written as a `UsdPreviewSurface` material (M14).\n * `textures` holds per-channel image **asset paths** (M15) — emitted as a\n * `UsdUVTexture` + `UsdPrimvarReader_float2` network; sampler details\n * (wrap/scale/bias/transform) are not carried. Bundle the image bytes\n * themselves with `writeUsdz` under the same paths.\n */\nexport type ExportMaterial = {\n /** Material identity: meshes sharing a name share one Material prim. */\n name: string;\n diffuseColor?: Vec3;\n metallic?: number;\n roughness?: number;\n /** Sub-unit opacity renders as a translucent blend. */\n opacity?: number;\n emissiveColor?: Vec3;\n /** Per-channel texture asset paths. */\n textures?: Partial<Record<TextureChannel, string>>;\n};\n\n/** `UsdPhysicsMaterialAPI` parameters, bound via `material:binding:physics` (M16). */\nexport type ExportPhysicsMaterial = {\n /** Identity: meshes sharing a name share one physics-material prim. */\n name: string;\n staticFriction?: number;\n dynamicFriction?: number;\n restitution?: number;\n density?: number;\n};\n\n/** `physics:approximation` tokens of `UsdPhysicsMeshCollisionAPI`. */\nexport type CollisionApproximation =\n | \"none\"\n | \"convexHull\"\n | \"convexDecomposition\"\n | \"boundingSphere\"\n | \"boundingCube\"\n | \"meshSimplification\";\n\n/** One mesh of a link, as plain exportable data (stage units, link-relative). */\nexport type ExportMesh = {\n /** Prim-name hint; the exporter sanitizes and uniquifies it. */\n name: string;\n kind: \"visual\" | \"collision\";\n points: Vec3[];\n /** Authored polygon topology (not re-triangulated). */\n faceVertexCounts: number[];\n faceVertexIndices: number[];\n /** Per-vertex normals (only written when one per point). */\n normals?: Vec3[];\n /** `primvars:st` UVs, vertex interpolation (one per point). */\n st?: Vec2[];\n displayColor?: Vec3;\n doubleSided?: boolean;\n /** Transform relative to the link frame (column-major); identity when omitted. */\n transform?: Mat4;\n /** Bound material constants, if any. */\n material?: ExportMaterial;\n /** Collision approximation token (collision meshes only, M16). */\n collisionApproximation?: CollisionApproximation;\n /** Bound physics material (collision meshes only, M16). */\n physicsMaterial?: ExportPhysicsMaterial;\n};\n\n/** Supplies the meshes of a link for export. */\nexport type RobotGeometryProvider = (linkKey: string, link: LinkDescription) => ExportMesh[];\n\n/** Provider that reads each link's visual/collision Mesh prims from a stage. */\nexport function stageGeometryProvider(stage: Stage): RobotGeometryProvider {\n return (_linkKey, link) => {\n const linkPrim = stage.GetPrimAtPath(link.primPath);\n if (!linkPrim) return [];\n\n // Meshes that are both visual and collision export once, as visual.\n const visualSet = new Set(link.visualPrims);\n const out: ExportMesh[] = [];\n for (const path of link.visualPrims) {\n out.push(...readMeshes(stage, linkPrim, path, \"visual\"));\n }\n for (const path of link.collisionPrims ?? []) {\n if (visualSet.has(path)) continue;\n out.push(...readMeshes(stage, linkPrim, path, \"collision\"));\n }\n return out;\n };\n}\n\n/**\n * Read a Mesh prim as exportable data. A mesh painted by `materialBind` face\n * subsets becomes one {@link ExportMesh} per subset (points re-indexed to the\n * faces each one covers), so the export keeps its materials instead of\n * collapsing to a single colour.\n */\nfunction readMeshes(\n stage: Stage,\n linkPrim: Prim,\n meshPath: string,\n kind: \"visual\" | \"collision\",\n): ExportMesh[] {\n const prim = stage.GetPrimAtPath(meshPath);\n if (!prim) return [];\n\n const points = prim.GetAttribute(\"points\").Get();\n if (!isVec3Array(points) || points.length === 0) return [];\n\n const countsValue = prim.GetAttribute(\"faceVertexCounts\").Get();\n const indicesValue = prim.GetAttribute(\"faceVertexIndices\").Get();\n const counts = isNumberArray(countsValue) ? countsValue : [];\n const indices = isNumberArray(indicesValue) ? indicesValue : [];\n const normalsValue = prim.GetAttribute(\"normals\").Get();\n const stValue = prim.GetAttribute(\"primvars:st\").Get();\n const displayColor = prim.GetAttribute(\"primvars:displayColor\").Get();\n const normals =\n isVec3Array(normalsValue) && normalsValue.length === points.length ? normalsValue : undefined;\n const st = isVec2Array(stValue) && stValue.length === points.length ? stValue : undefined;\n\n // Attributes shared by every piece of this mesh.\n const transform = relativeTransform(linkPrim, prim);\n const common = {\n kind,\n ...(isVec3Array(displayColor) && displayColor[0] ? { displayColor: displayColor[0] } : {}),\n ...(prim.GetAttribute(\"doubleSided\").Get() === true ? { doubleSided: true } : {}),\n ...(isIdentity(transform) ? {} : { transform }),\n } satisfies Partial<ExportMesh>;\n\n const withPhysics = (mesh: ExportMesh): ExportMesh => {\n if (kind !== \"collision\") return mesh;\n const approximation = prim.GetAttribute(\"physics:approximation\").Get();\n if (typeof approximation === \"string\" && APPROXIMATIONS.has(approximation)) {\n mesh.collisionApproximation = approximation as CollisionApproximation;\n }\n const physicsMaterial = readBoundPhysicsMaterial(stage, prim);\n if (physicsMaterial) mesh.physicsMaterial = physicsMaterial;\n return mesh;\n };\n\n const subsets = getMaterialSubsets(prim);\n if (subsets.length === 0) {\n const material = readBoundMaterial(stage, prim);\n return [\n withPhysics({\n ...common,\n name: prim.GetName(),\n points: points.slice(),\n faceVertexCounts: counts.slice(),\n faceVertexIndices: indices.slice(),\n ...(normals ? { normals: normals.slice() } : {}),\n ...(st ? { st: st.slice() } : {}),\n ...(material ? { material } : {}),\n }),\n ];\n }\n\n const faceStart: number[] = [];\n let offset = 0;\n for (const count of counts) {\n faceStart.push(offset);\n offset += count;\n }\n\n /** Re-index the given faces onto their own point list. */\n const piece = (faces: number[], name: string, material?: ExportMaterial): ExportMesh | null => {\n const remap = new Map<number, number>();\n const outPoints: Vec3[] = [];\n const outNormals: Vec3[] = [];\n const outSt: Vec2[] = [];\n const outCounts: number[] = [];\n const outIndices: number[] = [];\n\n for (const face of faces) {\n const start = faceStart[face];\n const count = counts[face];\n if (start === undefined || count === undefined) continue;\n outCounts.push(count);\n for (let k = 0; k < count; k++) {\n const vertex = indices[start + k];\n if (vertex === undefined || !points[vertex]) continue;\n let mapped = remap.get(vertex);\n if (mapped === undefined) {\n mapped = outPoints.length;\n remap.set(vertex, mapped);\n outPoints.push(points[vertex]!);\n if (normals) outNormals.push(normals[vertex]!);\n if (st) outSt.push(st[vertex]!);\n }\n outIndices.push(mapped);\n }\n }\n if (outPoints.length === 0) return null;\n\n return withPhysics({\n ...common,\n name,\n points: outPoints,\n faceVertexCounts: outCounts,\n faceVertexIndices: outIndices,\n ...(normals ? { normals: outNormals } : {}),\n ...(st ? { st: outSt } : {}),\n ...(material ? { material } : {}),\n });\n };\n\n const out: ExportMesh[] = [];\n const claimed = new Set<number>();\n subsets.forEach((subset, index) => {\n const faces = subset.faces.filter((f) => f >= 0 && f < counts.length && !claimed.has(f));\n for (const f of faces) claimed.add(f);\n const material = readBoundMaterial(stage, subset.prim);\n const mesh = piece(faces, `${prim.GetName()}_${material?.name ?? index}`, material);\n if (mesh) out.push(mesh);\n });\n\n const leftover = counts.map((_, f) => f).filter((f) => !claimed.has(f));\n if (leftover.length > 0) {\n const material = readBoundMaterial(stage, prim);\n const mesh = piece(leftover, prim.GetName(), material);\n if (mesh) out.push(mesh);\n }\n return out;\n}\n\nconst APPROXIMATIONS: ReadonlySet<string> = new Set([\n \"none\",\n \"convexHull\",\n \"convexDecomposition\",\n \"boundingSphere\",\n \"boundingCube\",\n \"meshSimplification\",\n]);\n\n/** `UsdPhysicsMaterialAPI` parameters bound via `material:binding:physics`. */\nfunction readBoundPhysicsMaterial(stage: Stage, prim: Prim): ExportPhysicsMaterial | undefined {\n const target = firstBindingTarget(prim, \"material:binding:physics\");\n if (!target) return undefined;\n const materialPrim = stage.GetPrimAtPath(target);\n if (!materialPrim) return undefined;\n\n const out: ExportPhysicsMaterial = {\n name: target.split(\"/\").filter(Boolean).pop() ?? \"PhysicsMaterial\",\n };\n const read = (attr: string): number | undefined => {\n const v = materialPrim.GetAttribute(attr).Get();\n return typeof v === \"number\" ? v : undefined;\n };\n const staticFriction = read(\"physics:staticFriction\");\n if (staticFriction !== undefined) out.staticFriction = staticFriction;\n const dynamicFriction = read(\"physics:dynamicFriction\");\n if (dynamicFriction !== undefined) out.dynamicFriction = dynamicFriction;\n const restitution = read(\"physics:restitution\");\n if (restitution !== undefined) out.restitution = restitution;\n const density = read(\"physics:density\");\n if (density !== undefined) out.density = density;\n return Object.keys(out).length > 1 ? out : undefined;\n}\n\n/** First target of `relName` on the prim or an ancestor. */\nfunction firstBindingTarget(prim: Prim, relName: string): string | undefined {\n let p: Prim | null = prim;\n while (p) {\n const targets = p.GetRelationship(relName).GetTargets();\n if (targets.length > 0) return targets[0];\n p = p.GetParent();\n }\n return undefined;\n}\n\n/** PBR constants + texture asset paths of the bound material. */\nfunction readBoundMaterial(stage: Stage, prim: Prim): ExportMaterial | undefined {\n const bound = resolveBoundMaterial(stage, prim);\n if (!bound) return undefined;\n const material: ExportMaterial = { name: boundMaterialName(prim) ?? \"Material\" };\n if (bound.color) material.diffuseColor = bound.color;\n if (bound.metalness !== undefined) material.metallic = bound.metalness;\n if (bound.roughness !== undefined) material.roughness = bound.roughness;\n if (bound.opacity !== undefined) material.opacity = bound.opacity;\n if (bound.emissiveColor) material.emissiveColor = bound.emissiveColor;\n\n const textures: Partial<Record<TextureChannel, string>> = {};\n if (bound.colorTexture) textures.color = bound.colorTexture.path;\n if (bound.opacityTexture) textures.opacity = bound.opacityTexture.path;\n if (bound.normalTexture) textures.normal = bound.normalTexture.path;\n if (bound.roughnessTexture) textures.roughness = bound.roughnessTexture.path;\n if (bound.metalnessTexture) textures.metalness = bound.metalnessTexture.path;\n if (bound.occlusionTexture) textures.occlusion = bound.occlusionTexture.path;\n if (bound.emissiveTexture) textures.emissive = bound.emissiveTexture.path;\n if (Object.keys(textures).length > 0) material.textures = textures;\n\n return Object.keys(material).length > 1 ? material : undefined;\n}\n\n/** Leaf name of the first `material:binding` target on the prim or an ancestor. */\nfunction boundMaterialName(prim: Prim): string | undefined {\n let p: Prim | null = prim;\n while (p) {\n const targets = p.GetRelationship(\"material:binding\").GetTargets();\n if (targets.length > 0) return targets[0]!.split(\"/\").filter(Boolean).pop();\n p = p.GetParent();\n }\n return undefined;\n}\n\n/** Accumulated local transform from `linkPrim` (exclusive) down to `meshPrim` (inclusive). */\nfunction relativeTransform(linkPrim: Prim, meshPrim: Prim): Mat4 {\n const chain: Prim[] = [];\n let p: Prim | null = meshPrim;\n const stop = linkPrim.GetPath();\n while (p && p.GetPath() !== stop) {\n chain.push(p);\n p = p.GetParent();\n }\n chain.reverse();\n\n let m = identity4();\n for (const prim of chain) {\n m = multiply(m, computeLocalTransform(prim).matrix);\n }\n return m;\n}\n\nfunction isIdentity(m: Mat4): boolean {\n for (let i = 0; i < 16; i++) {\n if (m[i] !== (i % 5 === 0 ? 1 : 0)) return false;\n }\n return true;\n}\n\nfunction isNumberArray(v: unknown): v is number[] {\n return Array.isArray(v) && v.every((n) => typeof n === \"number\");\n}\n\nfunction isVec3Array(v: unknown): v is Vec3[] {\n return Array.isArray(v) && v.every((e) => Array.isArray(e) && e.length === 3);\n}\n\nfunction isVec2Array(v: unknown): v is Vec2[] {\n return Array.isArray(v) && v.every((e) => Array.isArray(e) && e.length === 2);\n}\n","/**\n * USDZ package writer (M15) — the write-direction counterpart of `openUsdz`.\n *\n * A `.usdz` is a **stored** (uncompressed) zip whose entries' file data must\n * start on 64-byte boundaries; alignment is achieved with padding placed in a\n * local-header extra field (the fflate-sanctioned trick, as used by Three.js's\n * USDZExporter). The first entry is the package's root USD layer — `openUsdz`\n * and other USDZ readers open that one.\n */\n\nimport { type Zippable, strToU8, zipSync } from \"fflate\";\n\nconst USD_ENTRY = /\\.(usda|usdc|usd)$/i;\n/** Private extra-field id used purely as alignment padding. */\nconst PAD_EXTRA_ID = 12345;\n/** Bytes of a zip local file header before the name/extra fields. */\nconst LOCAL_HEADER_SIZE = 30;\n/** An extra field costs 4 header bytes (id + size) plus its data. */\nconst EXTRA_HEADER_SIZE = 4;\n\n/**\n * Pack entries into USDZ bytes. `entries` maps archive paths to file contents\n * (strings are UTF-8 encoded — pass the `serializeUsda` output directly). One\n * entry must be a USD layer (`.usda`/`.usdc`/`.usd`); the first such entry\n * becomes the package root and is moved to the front of the archive.\n */\nexport function writeUsdz(entries: Record<string, Uint8Array | string>): Uint8Array {\n const names = Object.keys(entries);\n const root = names.find((n) => USD_ENTRY.test(n));\n if (!root) {\n throw new Error(\"writeUsdz: entries must include a root USD layer (.usda/.usdc/.usd)\");\n }\n const ordered = [root, ...names.filter((n) => n !== root)];\n\n const files: Zippable = {};\n let offset = 0;\n for (const name of ordered) {\n const raw = entries[name]!;\n const data = typeof raw === \"string\" ? strToU8(raw) : raw;\n const nameLength = strToU8(name).length;\n\n // Where this entry's data would start without an extra field.\n const dataStart = offset + LOCAL_HEADER_SIZE + nameLength;\n if ((dataStart & 63) === 0) {\n files[name] = data;\n offset = dataStart + data.length;\n } else {\n // Pad so the data starts on the next 64-byte boundary past the 4-byte\n // extra-field header.\n const padLength = (64 - ((dataStart + EXTRA_HEADER_SIZE) & 63)) & 63;\n files[name] = [data, { extra: { [PAD_EXTRA_ID]: new Uint8Array(padLength) } }];\n offset = dataStart + EXTRA_HEADER_SIZE + padLength + data.length;\n }\n }\n\n return zipSync(files, { level: 0 });\n}\n","/**\n * Simulation-readiness checks for a {@link RobotDescription} (M16).\n *\n * Validates what Isaac Sim's Asset Validator cares about that is visible from\n * the IR (plus, optionally, the export geometry): graph connectivity, limit\n * sanity, mass properties, and collision setup. `error` issues break\n * simulation; `warning` issues are quality gaps a physics engine tolerates\n * but misbehaves on.\n */\n\nimport type { RobotGeometryProvider } from \"../export/GeometryProvider.js\";\nimport { decomposeRigid } from \"../kinematics/transforms.js\";\nimport type { JointType, RobotDescription } from \"./RobotDescription.js\";\nimport { buildKinematicTree } from \"./buildKinematicTree.js\";\n\nconst isAngular = (type: JointType): boolean => type === \"revolute\" || type === \"continuous\";\n\nexport type ValidationSeverity = \"error\" | \"warning\";\n\nexport type ValidationIssue = {\n severity: ValidationSeverity;\n /** Stable machine-readable code (e.g. `unknown-link`, `no-collision`). */\n code: string;\n message: string;\n /** Link or joint key the issue refers to, when applicable. */\n subject?: string;\n};\n\nexport type ValidateRobotOptions = {\n /** Enables mesh-level checks (collision presence / approximation). */\n geometry?: RobotGeometryProvider;\n};\n\n/** Check a robot IR for simulation-readiness; returns errors first. */\nexport function validateRobotDescription(\n desc: RobotDescription,\n options: ValidateRobotOptions = {},\n): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const add = (severity: ValidationSeverity, code: string, message: string, subject?: string) =>\n issues.push({ severity, code, message, ...(subject !== undefined ? { subject } : {}) });\n\n if (Object.keys(desc.links).length === 0) {\n add(\"error\", \"no-links\", \"robot has no links\");\n }\n\n for (const [key, joint] of Object.entries(desc.joints)) {\n if (joint.parent !== \"\" && !desc.links[joint.parent]) {\n add(\n \"error\",\n \"unknown-link\",\n `joint \"${key}\" references unknown parent \"${joint.parent}\"`,\n key,\n );\n }\n if (!desc.links[joint.child]) {\n add(\"error\", \"unknown-link\", `joint \"${key}\" references unknown child \"${joint.child}\"`, key);\n }\n if (joint.lower !== undefined && joint.upper !== undefined && joint.lower > joint.upper) {\n add(\n \"error\",\n \"invalid-limits\",\n `joint \"${key}\" lower limit ${joint.lower} exceeds upper ${joint.upper}`,\n key,\n );\n }\n if (\n joint.initialValue !== undefined &&\n ((joint.lower !== undefined && joint.initialValue < joint.lower) ||\n (joint.upper !== undefined && joint.initialValue > joint.upper))\n ) {\n add(\n \"warning\",\n \"initial-out-of-limits\",\n `joint \"${key}\" initial value ${joint.initialValue} is outside its limits`,\n key,\n );\n }\n const frames = [\n [\"jointFrame0\", joint.jointFrame0],\n [\"jointFrame1\", joint.jointFrame1],\n ] as const;\n for (const [label, frame] of frames) {\n if (!decomposeRigid(frame).rigid) {\n add(\n \"warning\",\n \"non-rigid-frame\",\n `joint \"${key}\" ${label} carries scale/shear/reflection (discarded on export)`,\n key,\n );\n }\n }\n\n const mimic = joint.mimic;\n if (mimic) {\n const leader = desc.joints[mimic.joint];\n if (!leader) {\n add(\n \"error\",\n \"mimic-unknown-joint\",\n `joint \"${key}\" mimics unknown joint \"${mimic.joint}\"`,\n key,\n );\n } else if (joint.type === \"fixed\" || leader.type === \"fixed\") {\n add(\n \"error\",\n \"mimic-fixed-joint\",\n `joint \"${key}\" mimic involves a fixed joint (inert)`,\n key,\n );\n } else if (isAngular(joint.type) !== isAngular(leader.type)) {\n add(\n \"error\",\n \"mimic-type-mismatch\",\n `joint \"${key}\" (${joint.type}) mimics \"${mimic.joint}\" (${leader.type}) — leader and follower must share the motion kind`,\n key,\n );\n }\n }\n }\n\n // Mimic cycles: follow follower → leader edges; a walk that returns to its\n // start is a cycle (each member reports once).\n for (const startKey of Object.keys(desc.joints)) {\n if (!desc.joints[startKey]?.mimic) continue;\n const seen = new Set<string>();\n let current: string | undefined = startKey;\n while (current !== undefined && desc.joints[current]?.mimic) {\n const next: string = desc.joints[current]!.mimic!.joint;\n if (next === startKey) {\n add(\n \"error\",\n \"mimic-cycle\",\n `joint \"${startKey}\" is part of a mimic cycle — followers cannot be driven`,\n startKey,\n );\n break;\n }\n if (seen.has(next)) break;\n seen.add(next);\n current = next;\n }\n }\n\n const tree = buildKinematicTree(desc);\n for (const jointKey of tree.loopJoints) {\n add(\n \"warning\",\n \"closed-loop\",\n `joint \"${jointKey}\" closes a kinematic loop (dropped from the spanning tree)`,\n jointKey,\n );\n }\n for (const linkKey of tree.isolatedLinks) {\n add(\n \"warning\",\n \"isolated-link\",\n `link \"${linkKey}\" is unreachable from root \"${tree.root}\"`,\n linkKey,\n );\n }\n if ((desc.articulationRoots ?? []).length === 0 && !tree.rootJoint) {\n add(\n \"warning\",\n \"no-articulation-root\",\n \"no ArticulationRootAPI link and no world-fixed joint — the base will float\",\n );\n }\n\n for (const [key, link] of Object.entries(desc.links)) {\n const inertial = link.inertial;\n if (!inertial || (inertial.mass === undefined && inertial.density === undefined)) {\n add(\"warning\", \"no-inertial\", `link \"${key}\" has no mass or density (PhysicsMassAPI)`, key);\n }\n if (inertial?.mass !== undefined && inertial.mass <= 0) {\n add(\"error\", \"bad-mass\", `link \"${key}\" has non-positive mass ${inertial.mass}`, key);\n }\n if (inertial?.diagonalInertia?.some((v) => v < 0)) {\n add(\"error\", \"bad-inertia\", `link \"${key}\" has a negative diagonal-inertia component`, key);\n }\n if (inertial?.principalAxes && !inertial.diagonalInertia) {\n add(\n \"warning\",\n \"inertia-pairing\",\n `link \"${key}\" authors principalAxes without diagonalInertia (dropped on export)`,\n key,\n );\n }\n\n if (options.geometry) {\n const meshes = options.geometry(key, link);\n const collisions = meshes.filter((mesh) => mesh.kind === \"collision\");\n if (collisions.length === 0) {\n add(\"warning\", \"no-collision\", `link \"${key}\" has no collision geometry`, key);\n }\n for (const mesh of collisions) {\n if (!mesh.collisionApproximation) {\n add(\n \"warning\",\n \"collision-approximation\",\n `link \"${key}\" collision mesh \"${mesh.name}\" has no physics:approximation (PhysX dynamic bodies need a convex or primitive approximation)`,\n key,\n );\n }\n }\n }\n }\n\n return issues.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === \"error\" ? -1 : 1));\n}\n"]}