Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
urdf_io.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
11
13#include "momentum/common/log.h"
15
16#include <fmt/format.h>
17
18#include <algorithm>
19#include <array>
20#include <cmath>
21#include <optional>
22#include <string_view>
23#include <unordered_map>
24#include <utility>
25#include <vector>
26
27namespace momentum {
28
29namespace {
30
32struct LinkVisualData {
33 size_t jointIndex{};
34 std::vector<urdf::VisualSharedPtr> visuals;
35};
36
38struct MimicData {
39 std::string mimickedJointName; // URDF joint name to mimic
40 float multiplier{};
41 float offset{}; // radians for revolute, meters for prismatic
42 std::vector<std::pair<Eigen::Index, float>> jointParamCoefficients;
43 bool isRotation{}; // true for revolute/continuous, false for prismatic
44};
45
46struct ParsingData {
47 Skeleton skeleton;
48 ParameterTransform parameterTransform;
49 std::vector<Eigen::Triplet<float>> triplets;
50 ParameterLimits limits;
51 PhysicalProperties physicalProperties;
52 CollisionGeometry collision;
53 size_t totalDoFs = 0;
54
55 std::vector<LinkVisualData> linkVisuals;
56
58 std::unordered_map<std::string, Eigen::Index> urdfJointNameToModelParamIdx;
59
61 std::vector<MimicData> mimicJoints;
62};
63
64template <typename S>
65[[nodiscard]] Vector3<S> toMomentumVector3(const urdf::Vector3& urdfVector3) {
66 return Vector3<S>(urdfVector3.x, urdfVector3.y, urdfVector3.z);
67}
68
69template <typename S>
70[[nodiscard]] Quaternion<S> toMomentumQuaternion(const urdf::Rotation& urdfRotation) {
71 return Quaternion<S>(urdfRotation.w, urdfRotation.x, urdfRotation.y, urdfRotation.z);
72}
73
74template <typename S>
75[[nodiscard]] TransformT<S> toMomentumTransform(const urdf::Pose& urdfPose) {
76 return TransformT<S>(
77 toMomentumVector3<S>(urdfPose.position), toMomentumQuaternion<S>(urdfPose.rotation));
78}
79
80[[nodiscard]] Matrix3f toMomentumInertia(const urdf::Inertial& inertial) {
81 constexpr float kInertiaScale = toCm<float>() * toCm<float>();
82 Matrix3f result;
83 result << static_cast<float>(inertial.ixx), static_cast<float>(inertial.ixy),
84 static_cast<float>(inertial.ixz), static_cast<float>(inertial.ixy),
85 static_cast<float>(inertial.iyy), static_cast<float>(inertial.iyz),
86 static_cast<float>(inertial.ixz), static_cast<float>(inertial.iyz),
87 static_cast<float>(inertial.izz);
88 return (result * kInertiaScale).eval();
89}
90
91void addPhysicalPropertiesForUrdfLink(
92 PhysicalProperties& physicalProperties,
93 const urdf::Link& urdfLink,
94 const size_t jointIndex) {
95 if (!urdfLink.inertial) {
96 return;
97 }
98
99 JointPhysicalProperties jointProperties;
100 jointProperties.jointName = urdfLink.name;
101 jointProperties.jointIndex = jointIndex;
102 jointProperties.mass = static_cast<float>(urdfLink.inertial->mass);
103 jointProperties.centerOfMassOffset =
104 toMomentumVector3<float>(urdfLink.inertial->origin.position) * toCm<float>();
105 jointProperties.inertia = toMomentumInertia(*urdfLink.inertial);
106 jointProperties.inertiaRotation =
107 toMomentumQuaternion<float>(urdfLink.inertial->origin.rotation).normalized();
108 physicalProperties.push_back(std::move(jointProperties));
109}
110
111[[nodiscard]] std::string_view toString(int jointType) {
112 switch (jointType) {
113 case urdf::Joint::REVOLUTE:
114 return "REVOLUTE";
115 case urdf::Joint::CONTINUOUS:
116 return "CONTINUOUS";
117 case urdf::Joint::PRISMATIC:
118 return "PRISMATIC";
119 case urdf::Joint::FLOATING:
120 return "FLOATING";
121 case urdf::Joint::PLANAR:
122 return "PLANAR";
123 default:
124 return "UNKNOWN";
125 }
126}
127
128[[nodiscard]] std::string_view toString(const urdf::Geometry& geometry) {
129 switch (geometry.type) {
130 case urdf::Geometry::SPHERE:
131 return "SPHERE";
132 case urdf::Geometry::BOX:
133 return "BOX";
134 case urdf::Geometry::CYLINDER:
135 return "CYLINDER";
136 case urdf::Geometry::MESH:
137 return "MESH";
138 }
139
140 return "UNKNOWN";
141}
142
143struct PrincipalAxis {
144 int index{}; // principal axis index (0=X, 1=Y, 2=Z)
145 float sign{}; // axis sign (+1/-1)
146};
147
148struct JointDofMapping {
149 std::vector<std::pair<Eigen::Index, float>> jointParamCoefficients;
150 bool isRotation{};
151};
152
153struct JointFrameData {
154 Eigen::Index modelParamsBaseIndex{};
155 Eigen::Index axisJointId{};
156 Eigen::Index linkJointId{};
157 Eigen::Index motionJointParamsBaseIndex{};
158 Quaternionf originRotation = Quaternionf::Identity();
159 Vector3f originTranslation = Vector3f::Zero();
160 // For a revolute/continuous joint whose axis is a principal axis, the resolved axis is cached
161 // here so the DOF mapping does not recompute it. Null for arbitrary axes (which use
162 // arbitraryAxisFrameRotation instead) and for non-rotational joints.
163 std::optional<PrincipalAxis> principalRotationAxis;
164 std::optional<Quaternionf> arbitraryAxisFrameRotation;
165
166 [[nodiscard]] bool hasArbitraryRotationAxis() const {
167 return arbitraryAxisFrameRotation.has_value();
168 }
169};
170
171[[nodiscard]] Vector3f normalizedAxis(const urdf::Vector3& axis, std::string_view jointName) {
172 const Vector3f result{
173 static_cast<float>(axis.x), static_cast<float>(axis.y), static_cast<float>(axis.z)};
175 !result.allFinite(),
176 "Joint '{}' has invalid non-finite axis ({}, {}, {}).",
177 jointName,
178 result.x(),
179 result.y(),
180 result.z());
181 const float norm = result.norm();
183 norm < 1e-8f,
184 "Joint '{}' has invalid zero-length axis ({}, {}, {}).",
185 jointName,
186 result.x(),
187 result.y(),
188 result.z());
189 return result / norm;
190}
191
192[[nodiscard]] std::optional<PrincipalAxis> getPrincipalAxis(const Vector3f& axis) {
193 constexpr float kTol = 1e-4f;
194
195 const float ax = axis.x();
196 const float ay = axis.y();
197 const float az = axis.z();
198 if (std::abs(std::abs(ax) - 1.0f) < kTol && std::abs(ay) < kTol && std::abs(az) < kTol) {
199 return PrincipalAxis{0, ax > 0 ? 1.0f : -1.0f};
200 }
201 if (std::abs(ax) < kTol && std::abs(std::abs(ay) - 1.0f) < kTol && std::abs(az) < kTol) {
202 return PrincipalAxis{1, ay > 0 ? 1.0f : -1.0f};
203 }
204 if (std::abs(ax) < kTol && std::abs(ay) < kTol && std::abs(std::abs(az) - 1.0f) < kTol) {
205 return PrincipalAxis{2, az > 0 ? 1.0f : -1.0f};
206 }
207
208 return std::nullopt;
209}
210
211[[nodiscard]] PrincipalAxis requirePrincipalAxis(
212 const urdf::Vector3& axis,
213 std::string_view jointName) {
214 const Vector3f normalized = normalizedAxis(axis, jointName);
215 const auto principalAxis = getPrincipalAxis(normalized);
216 if (principalAxis) {
217 return *principalAxis;
218 }
219
220 MT_THROW(
221 "Joint '{}' has non-principal planar axis ({}, {}, {}). "
222 "Only axes aligned with X, Y, or Z are supported for planar joints.",
223 jointName,
224 normalized.x(),
225 normalized.y(),
226 normalized.z());
227}
228
234std::optional<Mesh> loadVisualMesh(
235 const urdf::Geometry& geometry,
236 const filesystem::path& urdfDir) {
237 switch (geometry.type) {
238 case urdf::Geometry::MESH: {
239 const auto& urdfMesh = dynamic_cast<const urdf::Mesh&>(geometry);
240 if (urdfDir.empty()) {
241 MT_LOGW("Cannot resolve mesh path without URDF directory: {}", urdfMesh.filename);
242 return std::nullopt;
243 }
244 const auto resolvedPath = resolveMeshPath(urdfMesh.filename, urdfDir);
245 if (!resolvedPath) {
246 return std::nullopt;
247 }
248
249 const auto ext = resolvedPath->extension().string();
250 std::optional<Mesh> mesh;
251 if (ext == ".stl" || ext == ".STL") {
252 mesh = loadStlMesh(*resolvedPath);
253 } else if (ext == ".obj" || ext == ".OBJ") {
254 mesh = loadObjMesh(*resolvedPath);
255 } else {
256 MT_LOGW("Unsupported mesh format '{}': {}", ext, resolvedPath->string());
257 return std::nullopt;
258 }
259
260 if (!mesh) {
261 return std::nullopt;
262 }
263
264 // Apply scale from URDF mesh element
265 const Eigen::Vector3f scale(
266 static_cast<float>(urdfMesh.scale.x),
267 static_cast<float>(urdfMesh.scale.y),
268 static_cast<float>(urdfMesh.scale.z));
269 if (!scale.isApprox(Eigen::Vector3f::Ones())) {
270 for (auto& v : mesh->vertices) {
271 v = v.cwiseProduct(scale);
272 }
273 }
274 return mesh;
275 }
276 case urdf::Geometry::BOX: {
277 const auto& box = dynamic_cast<const urdf::Box&>(geometry);
278 return generateBoxMesh(
279 static_cast<float>(box.dim.x),
280 static_cast<float>(box.dim.y),
281 static_cast<float>(box.dim.z));
282 }
283 case urdf::Geometry::CYLINDER: {
284 const auto& cyl = dynamic_cast<const urdf::Cylinder&>(geometry);
285 return generateCylinderMesh(static_cast<float>(cyl.radius), static_cast<float>(cyl.length));
286 }
287 case urdf::Geometry::SPHERE: {
288 const auto& sphere = dynamic_cast<const urdf::Sphere&>(geometry);
289 return generateSphereMesh(static_cast<float>(sphere.radius));
290 }
291 default:
292 MT_LOGW("Unknown URDF geometry type: {}", static_cast<int>(geometry.type));
293 return std::nullopt;
294 }
295}
296
297[[nodiscard]] TaperedCapsule loadCollisionCapsule(
298 const urdf::Cylinder& cylinder,
299 const TransformT<float>& collisionOrigin,
300 size_t jointIndex) {
301 // Convention conversion: URDF cylinders are centered at the origin with their axis along
302 // +Z, while Momentum TaperedCapsules start at the origin with their axis along +X.
303 // - Rotation: compose the URDF collision origin rotation with a UnitX→UnitZ rotation so the
304 // local +X axis of the Momentum capsule maps to the local +Z axis of the URDF cylinder.
305 // - Translation: convert the URDF center position to centimeters, then shift along the
306 // URDF cylinder's local +Z by -length/2 so the capsule starts where the cylinder ends.
307 TaperedCapsule capsule;
308 capsule.parent = jointIndex;
309 capsule.length = static_cast<float>(cylinder.length) * toCm<float>();
310 capsule.radius = Eigen::Vector2f::Constant(static_cast<float>(cylinder.radius) * toCm<float>());
311 capsule.transformation.rotation = collisionOrigin.rotation *
312 Eigen::Quaternionf::FromTwoVectors(Eigen::Vector3f::UnitX(), Eigen::Vector3f::UnitZ());
313 capsule.transformation.translation = collisionOrigin.translation * toCm<float>() +
314 collisionOrigin.rotation * Eigen::Vector3f(0.0f, 0.0f, -0.5f * capsule.length);
315 return capsule;
316}
317
318[[nodiscard]] CollisionEllipsoid loadCollisionSphere(
319 const urdf::Sphere& sphere,
320 const TransformT<float>& collisionOrigin,
321 size_t jointIndex) {
322 // A URDF sphere has a single radius and is centered at the collision origin. It maps directly to
323 // a Momentum ellipsoid with equal radii along all three local axes (a sphere is the special case
324 // of an ellipsoid). The collision origin becomes the ellipsoid center and orientation.
325 CollisionEllipsoid ellipsoid;
326 ellipsoid.parent = jointIndex;
327 ellipsoid.radii = Eigen::Vector3f::Constant(static_cast<float>(sphere.radius) * toCm<float>());
328 ellipsoid.transformation.rotation = collisionOrigin.rotation;
329 ellipsoid.transformation.translation = collisionOrigin.translation * toCm<float>();
330 return ellipsoid;
331}
332
333[[nodiscard]] CollisionBox loadCollisionBox(
334 const urdf::Box& box,
335 const TransformT<float>& collisionOrigin,
336 size_t jointIndex) {
337 // A URDF box is centered at the collision origin with full extents box.dim along its local axes,
338 // whereas a Momentum box stores half extents. The collision origin becomes the box center and
339 // orientation.
340 CollisionBox collisionBox;
341 collisionBox.parent = jointIndex;
342 collisionBox.halfExtents = Eigen::Vector3f(
343 static_cast<float>(box.dim.x),
344 static_cast<float>(box.dim.y),
345 static_cast<float>(box.dim.z)) *
346 (0.5f * toCm<float>());
347 collisionBox.transformation.rotation = collisionOrigin.rotation;
348 collisionBox.transformation.translation = collisionOrigin.translation * toCm<float>();
349 return collisionBox;
350}
351
356[[nodiscard]] std::optional<CollisionPrimitive> loadCollisionPrimitive(
357 const urdf::Collision& collision,
358 std::string_view linkName,
359 size_t jointIndex) {
360 if (!collision.geometry) {
361 MT_LOGW("Ignoring URDF collision on link '{}' because it has no geometry.", linkName);
362 return std::nullopt;
363 }
364
365 const auto& geometry = *collision.geometry;
366 const auto collisionOrigin = toMomentumTransform<float>(collision.origin);
367
368 switch (geometry.type) {
369 case urdf::Geometry::CYLINDER:
370 return CollisionPrimitive(loadCollisionCapsule(
371 dynamic_cast<const urdf::Cylinder&>(geometry), collisionOrigin, jointIndex));
372 case urdf::Geometry::SPHERE:
373 return CollisionPrimitive(loadCollisionSphere(
374 dynamic_cast<const urdf::Sphere&>(geometry), collisionOrigin, jointIndex));
375 case urdf::Geometry::BOX:
376 return CollisionPrimitive(
377 loadCollisionBox(dynamic_cast<const urdf::Box&>(geometry), collisionOrigin, jointIndex));
378 case urdf::Geometry::MESH:
379 MT_LOGW(
380 "Ignoring unsupported URDF mesh collision geometry on link '{}'. Only cylinder, sphere, "
381 "and box collision geometry can be imported.",
382 linkName);
383 return std::nullopt;
384 }
385
386 MT_LOGW(
387 "Ignoring unknown URDF collision geometry '{}' on link '{}'.", toString(geometry), linkName);
388 return std::nullopt;
389}
390
391constexpr std::array<const char*, 3> kTranslationNames = {"tx", "ty", "tz"};
392constexpr std::array<const char*, 3> kRotationNames = {"rx", "ry", "rz"};
393
394void addModelDof(
395 ParsingData& data,
396 const std::string& urdfJointName,
397 const JointDofMapping& mapping,
398 Eigen::Index modelParamsBaseIndex) {
399 data.parameterTransform.name.push_back(urdfJointName);
400 for (const auto& [jointParamIndex, coefficient] : mapping.jointParamCoefficients) {
401 data.triplets.emplace_back(jointParamIndex, modelParamsBaseIndex, coefficient);
402 }
403 data.urdfJointNameToModelParamIdx[urdfJointName] = modelParamsBaseIndex;
404 data.totalDoFs += 1;
405}
406
407void addMimicDof(ParsingData& data, const urdf::Joint& urdfJoint, const JointDofMapping& mapping) {
408 MimicData mimic;
409 mimic.mimickedJointName = urdfJoint.mimic->joint_name;
410 mimic.multiplier = static_cast<float>(urdfJoint.mimic->multiplier);
411 mimic.offset = static_cast<float>(urdfJoint.mimic->offset);
412 mimic.jointParamCoefficients = mapping.jointParamCoefficients;
413 mimic.isRotation = mapping.isRotation;
414 data.mimicJoints.push_back(std::move(mimic));
415}
416
417[[nodiscard]] JointDofMapping rotationDofMapping(
418 Eigen::Index jointParamsBaseIndex,
419 const PrincipalAxis& axis) {
420 JointDofMapping result;
421 result.jointParamCoefficients.emplace_back(jointParamsBaseIndex + RX + axis.index, axis.sign);
422 result.isRotation = true;
423 return result;
424}
425
426[[nodiscard]] JointDofMapping prismaticDofMapping(
427 Eigen::Index jointParamsBaseIndex,
428 const Vector3f& axisInParentFrame) {
429 JointDofMapping result;
430 result.isRotation = false;
431 constexpr float kTol = 1e-6f;
432 for (int index = 0; index < 3; ++index) {
433 if (std::abs(axisInParentFrame[index]) > kTol) {
434 result.jointParamCoefficients.emplace_back(
435 jointParamsBaseIndex + index, axisInParentFrame[index]);
436 }
437 }
438 return result;
439}
440
441[[nodiscard]] bool isRevoluteLike(const urdf::Joint& urdfJoint) {
442 return urdfJoint.type == urdf::Joint::REVOLUTE || urdfJoint.type == urdf::Joint::CONTINUOUS;
443}
444
445[[nodiscard]] JointFrameData makeJointFrameData(
446 const ParsingData& data,
447 const urdf::Joint* urdfJoint) {
448 JointFrameData result;
449 result.modelParamsBaseIndex = data.totalDoFs;
450 result.axisJointId = data.skeleton.joints.size();
451
452 const urdf::Pose* urdfPose =
453 urdfJoint != nullptr ? &urdfJoint->parent_to_joint_origin_transform : nullptr;
454 result.originRotation = urdfPose != nullptr ? toMomentumQuaternion<float>(urdfPose->rotation)
455 : Quaternionf::Identity();
456 result.originTranslation = urdfPose != nullptr
457 ? (toMomentumVector3<float>(urdfPose->position) * toCm<float>()).eval()
458 : Vector3f::Zero();
459
460 if (urdfJoint != nullptr && isRevoluteLike(*urdfJoint)) {
461 const Vector3f axis = normalizedAxis(urdfJoint->axis, urdfJoint->name);
462 result.principalRotationAxis = getPrincipalAxis(axis);
463 if (!result.principalRotationAxis) {
464 result.arbitraryAxisFrameRotation =
465 Quaternionf::FromTwoVectors(Vector3f::UnitX(), axis).normalized();
466 }
467 }
468
469 result.linkJointId = result.axisJointId + (result.hasArbitraryRotationAxis() ? 1 : 0);
470 // The motion DOF always lands on the first node this joint pushes: the axis-aligned helper
471 // when present, otherwise the link node — both share the same index (axisJointId).
472 result.motionJointParamsBaseIndex = result.axisJointId * kParametersPerJoint;
473 return result;
474}
475
476void addModelOrMimicDof(
477 ParsingData& data,
478 const urdf::Joint& urdfJoint,
479 const JointDofMapping& mapping,
480 Eigen::Index modelParamsBaseIndex) {
481 if (urdfJoint.mimic != nullptr) {
482 addMimicDof(data, urdfJoint, mapping);
483 } else {
484 addModelDof(data, urdfJoint.name, mapping, modelParamsBaseIndex);
485 }
486}
487
488void addPrismaticJointDof(
489 ParsingData& data,
490 const urdf::Joint& urdfJoint,
491 const JointFrameData& frame) {
492 const Vector3f axis = normalizedAxis(urdfJoint.axis, urdfJoint.name);
493 const JointDofMapping mapping =
494 prismaticDofMapping(frame.motionJointParamsBaseIndex, frame.originRotation * axis);
495 addModelOrMimicDof(data, urdfJoint, mapping, frame.modelParamsBaseIndex);
496}
497
498void addRevoluteJointDof(
499 ParsingData& data,
500 const urdf::Joint& urdfJoint,
501 const JointFrameData& frame) {
502 JointDofMapping mapping;
503 if (frame.principalRotationAxis) {
504 mapping = rotationDofMapping(frame.motionJointParamsBaseIndex, *frame.principalRotationAxis);
505 } else {
506 // Arbitrary axis: the inserted axis-aligned helper node carries a single rotation about its
507 // local X axis.
508 mapping.jointParamCoefficients.emplace_back(frame.motionJointParamsBaseIndex + RX, 1.0f);
509 mapping.isRotation = true;
510 }
511
512 addModelOrMimicDof(data, urdfJoint, mapping, frame.modelParamsBaseIndex);
513}
514
515void addFloatingJointDofs(
516 ParsingData& data,
517 const urdf::Joint& urdfJoint,
518 const JointFrameData& frame) {
519 // Floating joints have 6 DOFs (3 translation, then 3 rotation); use the URDF joint name with
520 // axis suffixes. Translation parameters use a 10x scaling factor so that a unit change in
521 // model parameter space produces 10 cm of translation. This makes translation easier to
522 // change relative to rotation in optimization.
523 constexpr float kFloatingTranslationScale = 10.0f;
524 const auto& jn = urdfJoint.name;
525 for (int index = 0; index < 3; ++index) {
526 data.parameterTransform.name.push_back(fmt::format("{}_{}", jn, kTranslationNames[index]));
527 data.triplets.emplace_back(
528 frame.motionJointParamsBaseIndex + TX + index,
529 frame.modelParamsBaseIndex + index,
530 kFloatingTranslationScale);
531 }
532 for (int index = 0; index < 3; ++index) {
533 data.parameterTransform.name.push_back(fmt::format("{}_{}", jn, kRotationNames[index]));
534 data.triplets.emplace_back(
535 frame.motionJointParamsBaseIndex + RX + index,
536 frame.modelParamsBaseIndex + 3 + index,
537 1.0f);
538 }
539 data.totalDoFs += 6;
540}
541
542void addPlanarJointDofs(
543 ParsingData& data,
544 const urdf::Joint& urdfJoint,
545 const JointFrameData& frame) {
546 // The axis defines the plane normal. DOFs are translation along the two in-plane
547 // axes and rotation around the normal.
548 const int normalIdx = requirePrincipalAxis(urdfJoint.axis, urdfJoint.name).index;
549 const int planeAxis0 = (normalIdx + 1) % 3;
550 const int planeAxis1 = (normalIdx + 2) % 3;
551 const auto& jn = urdfJoint.name;
552 data.parameterTransform.name.push_back(fmt::format("{}_{}", jn, kTranslationNames[planeAxis0]));
553 data.triplets.emplace_back(
554 frame.motionJointParamsBaseIndex + planeAxis0, frame.modelParamsBaseIndex + 0, 1.0f);
555 data.parameterTransform.name.push_back(fmt::format("{}_{}", jn, kTranslationNames[planeAxis1]));
556 data.triplets.emplace_back(
557 frame.motionJointParamsBaseIndex + planeAxis1, frame.modelParamsBaseIndex + 1, 1.0f);
558 data.parameterTransform.name.push_back(fmt::format("{}_{}", jn, kRotationNames[normalIdx]));
559 data.triplets.emplace_back(
560 frame.motionJointParamsBaseIndex + RX + normalIdx, frame.modelParamsBaseIndex + 2, 1.0f);
561 data.totalDoFs += 3;
562}
563
564void addJointDofs(ParsingData& data, const urdf::Joint& urdfJoint, const JointFrameData& frame) {
565 //---------------------------
566 // Parse Parameter transform
567 //---------------------------
568 //
569 // URDF expresses motion on a joint between links, but attached data is authored in the child
570 // link frame. Our imported Momentum node therefore keeps the child link frame as its local
571 // frame whenever the URDF axis already matches a Momentum principal axis. For arbitrary
572 // revolute axes, we insert an internal axis-aligned helper followed by a fixed child-link node:
573 // parent -> origin * axisFrame -> revolute X(q) -> axisFrame^-1 -> child link
574 // so the composite transform is exactly origin * Rot(axis, q) while the visible child-link
575 // node remains in the URDF child-link frame.
576 //
577 // Revolute model parameters stay in the URDF scalar coordinate. Prismatic parameters keep the
578 // existing Momentum convention of centimeters. Negative principal axes, arbitrary prismatic
579 // direction vectors, and mimic offsets are represented by coefficients in the parameter
580 // transform rather than by changing the underlying joint frame.
581
582 switch (urdfJoint.type) {
583 case urdf::Joint::PRISMATIC: {
584 addPrismaticJointDof(data, urdfJoint, frame);
585 break;
586 }
587 case urdf::Joint::REVOLUTE:
588 case urdf::Joint::CONTINUOUS: {
589 addRevoluteJointDof(data, urdfJoint, frame);
590 break;
591 }
592 case urdf::Joint::FLOATING: {
593 addFloatingJointDofs(data, urdfJoint, frame);
594 break;
595 }
596 case urdf::Joint::PLANAR: {
597 addPlanarJointDofs(data, urdfJoint, frame);
598 break;
599 }
600 case urdf::Joint::FIXED: {
601 // No degrees of freedom
602 break;
603 }
604 case urdf::Joint::UNKNOWN: {
605 MT_THROW("Unsupported joint type: {}", toString(urdfJoint.type));
606 }
607 }
608}
609
610void addJointLimits(
611 ParsingData& data,
612 const urdf::Joint& urdfJoint,
613 Eigen::Index modelParamsBaseIndex) {
614 // Mimic joints are driven by the mimicked joint's parameter, so their limits don't
615 // correspond to an independent model parameter.
616 if (urdfJoint.mimic != nullptr || !urdfJoint.limits) {
617 return;
618 }
619
620 switch (urdfJoint.type) {
621 case urdf::Joint::REVOLUTE: {
622 ParameterLimit jointLimits;
623 jointLimits.type = MinMax;
624 jointLimits.data.minMax.parameterIndex = modelParamsBaseIndex;
625 jointLimits.data.minMax.limits[0] = urdfJoint.limits->lower; // rad
626 jointLimits.data.minMax.limits[1] = urdfJoint.limits->upper;
627 jointLimits.weight = 1.0f;
628 data.limits.push_back(jointLimits);
629 break;
630 }
631 case urdf::Joint::PRISMATIC: {
632 ParameterLimit jointLimits;
633 jointLimits.type = MinMax;
634 jointLimits.data.minMax.parameterIndex = modelParamsBaseIndex;
635 jointLimits.data.minMax.limits[0] = toCm<float>(urdfJoint.limits->lower);
636 jointLimits.data.minMax.limits[1] = toCm<float>(urdfJoint.limits->upper);
637 jointLimits.weight = 1.0f;
638 data.limits.push_back(jointLimits);
639 break;
640 }
641 case urdf::Joint::UNKNOWN:
642 case urdf::Joint::CONTINUOUS:
643 case urdf::Joint::FLOATING:
644 case urdf::Joint::PLANAR:
645 case urdf::Joint::FIXED: {
646 // No independent min/max parameter limit to add.
647 break;
648 }
649 }
650}
651
652void appendSkeletonJointsForUrdfLink(
653 ParsingData& data,
654 size_t parentJointId,
655 const urdf::Link& urdfLink,
656 const urdf::Joint* urdfJoint,
657 const JointFrameData& frame) {
658 if (frame.hasArbitraryRotationAxis()) {
659 MT_THROW_IF(urdfJoint == nullptr, "Internal URDF axis node requires a URDF joint.");
660 Joint axisJoint;
661 axisJoint.name = fmt::format("{}_urdf_axis", urdfJoint->name);
662 axisJoint.parent = parentJointId;
663 axisJoint.preRotation = frame.originRotation * *frame.arbitraryAxisFrameRotation;
664 axisJoint.translationOffset = frame.originTranslation;
665 data.skeleton.joints.push_back(axisJoint);
666 }
667
668 Joint linkJoint;
669 linkJoint.name = urdfLink.name;
670 linkJoint.parent =
671 frame.hasArbitraryRotationAxis() ? static_cast<size_t>(frame.axisJointId) : parentJointId;
672 linkJoint.preRotation = frame.hasArbitraryRotationAxis()
673 ? frame.arbitraryAxisFrameRotation->inverse()
674 : frame.originRotation;
675 linkJoint.translationOffset =
676 frame.hasArbitraryRotationAxis() ? Vector3f::Zero() : frame.originTranslation;
677 data.skeleton.joints.push_back(linkJoint);
678}
679
680void collectLinkVisuals(ParsingData& data, const urdf::Link& urdfLink, size_t linkJointId) {
681 if (urdfLink.visual_array.empty()) {
682 return;
683 }
684
685 LinkVisualData visualData;
686 visualData.jointIndex = linkJointId;
687 visualData.visuals = urdfLink.visual_array;
688 data.linkVisuals.push_back(std::move(visualData));
689}
690
691void collectCollisionGeometry(ParsingData& data, const urdf::Link& urdfLink, size_t linkJointId) {
692 for (const auto& collision : urdfLink.collision_array) {
693 if (!collision) {
694 MT_LOGW("Ignoring null URDF collision on link '{}'.", urdfLink.name);
695 continue;
696 }
697 auto primitive = loadCollisionPrimitive(*collision, urdfLink.name, linkJointId);
698 if (primitive) {
699 data.collision.push_back(*primitive);
700 }
701 }
702}
703
704bool loadUrdfSkeletonRecursive(
705 ParsingData& data,
706 size_t parentJointId,
707 const urdf::Link* urdfLink) {
708 MT_THROW_IF(urdfLink == nullptr, "URDF link is null.");
709
710 auto* urdfJoint = urdfLink->parent_joint.get();
712 parentJointId != kInvalidIndex && urdfJoint == nullptr,
713 "URDF parent joint is null for a non root link ({}).",
714 urdfLink->name);
715
716 const JointFrameData frame = makeJointFrameData(data, urdfJoint);
717 if (urdfJoint != nullptr) {
718 addJointDofs(data, *urdfJoint, frame);
719 addJointLimits(data, *urdfJoint, frame.modelParamsBaseIndex);
720 }
721
722 appendSkeletonJointsForUrdfLink(data, parentJointId, *urdfLink, urdfJoint, frame);
723 addPhysicalPropertiesForUrdfLink(
724 data.physicalProperties, *urdfLink, static_cast<size_t>(frame.linkJointId));
725
726 collectLinkVisuals(data, *urdfLink, static_cast<size_t>(frame.linkJointId));
727 collectCollisionGeometry(data, *urdfLink, static_cast<size_t>(frame.linkJointId));
728
729 for (const auto& childLink : urdfLink->child_links) {
730 if (!loadUrdfSkeletonRecursive(data, static_cast<size_t>(frame.linkJointId), childLink.get())) {
731 return false;
732 }
733 }
734
735 return true;
736}
737
740void resolveMimicJoints(ParsingData& data) {
741 for (const auto& mimic : data.mimicJoints) {
742 auto it = data.urdfJointNameToModelParamIdx.find(mimic.mimickedJointName);
743 if (it == data.urdfJointNameToModelParamIdx.end()) {
744 MT_LOGW("Mimic joint references unknown joint '{}', skipping.", mimic.mimickedJointName);
745 continue;
746 }
747 const Eigen::Index mimickedModelParamIdx = it->second;
748 const float offset = mimic.isRotation ? mimic.offset : toCm<float>(mimic.offset);
749
750 for (const auto& [jointParamIndex, coefficient] : mimic.jointParamCoefficients) {
751 data.triplets.emplace_back(
752 jointParamIndex, mimickedModelParamIdx, coefficient * mimic.multiplier);
753 data.parameterTransform.offsets[jointParamIndex] = coefficient * offset;
754 }
755 }
756}
757
758[[nodiscard]] Eigen::Vector3b toVertexColor(const urdf::Color& color) {
759 return {
760 static_cast<uint8_t>(std::clamp(color.r, 0.0f, 1.0f) * 255.0f),
761 static_cast<uint8_t>(std::clamp(color.g, 0.0f, 1.0f) * 255.0f),
762 static_cast<uint8_t>(std::clamp(color.b, 0.0f, 1.0f) * 255.0f)};
763}
764
766std::optional<Eigen::Vector3b> extractVertexColor(const urdf::Visual& visual) {
767 if (!visual.material) {
768 return std::nullopt;
769 }
770
771 const auto& material = *visual.material;
772 const bool looksLikeTextureOnlyMaterial = !material.texture_filename.empty() &&
773 material.color.r == 0.0f && material.color.g == 0.0f && material.color.b == 0.0f &&
774 material.color.a == 1.0f;
775 if (looksLikeTextureOnlyMaterial) {
776 return std::nullopt;
777 }
778
779 return toVertexColor(material.color);
780}
781
784std::optional<std::pair<Mesh, SkinWeights>> buildCombinedMesh(
785 const ParsingData& data,
786 const filesystem::path& urdfDir) {
787 if (data.linkVisuals.empty()) {
788 return std::nullopt;
789 }
790
791 const SkeletonStateT<float> bindState(data.parameterTransform.bindPose(), data.skeleton, false);
792
793 Mesh combinedMesh;
794 SkinWeights skinWeights;
795 bool hasAnyColor = false;
796
797 for (const auto& linkVisual : data.linkVisuals) {
798 const size_t jointIdx = linkVisual.jointIndex;
799 const auto& jointWorldTransform = bindState.jointState[jointIdx].transform;
800
801 for (const auto& visual : linkVisual.visuals) {
802 if (!visual || !visual->geometry) {
803 continue;
804 }
805
806 auto meshOpt = loadVisualMesh(*visual->geometry, urdfDir);
807 if (!meshOpt) {
808 continue;
809 }
810
811 // Convert from meters (URDF) to centimeters (Momentum) and apply transforms
812 for (auto& v : meshOpt->vertices) {
813 v *= toCm<float>();
814 }
815 const auto visualOrigin = toMomentumTransform<float>(visual->origin);
816 const Eigen::Vector3f visualTranslation = visualOrigin.translation * toCm<float>();
817 for (auto& v : meshOpt->vertices) {
818 v = visualOrigin.rotation * v + visualTranslation;
819 }
820 for (auto& v : meshOpt->vertices) {
821 v = jointWorldTransform.rotation * v + jointWorldTransform.translation;
822 }
823
824 const auto vertexColor = extractVertexColor(*visual);
825 hasAnyColor = hasAnyColor || vertexColor.has_value();
826
827 // Merge into the combined mesh
828 const auto vertexOffset = static_cast<int32_t>(combinedMesh.vertices.size());
829 combinedMesh.vertices.insert(
830 combinedMesh.vertices.end(), meshOpt->vertices.begin(), meshOpt->vertices.end());
831 for (const auto& face : meshOpt->faces) {
832 combinedMesh.faces.emplace_back(
833 face[0] + vertexOffset, face[1] + vertexOffset, face[2] + vertexOffset);
834 }
835 combinedMesh.colors.resize(
836 combinedMesh.vertices.size(), vertexColor.value_or(Eigen::Vector3b{255, 255, 255}));
837
838 // Extend skin weights: all new vertices are rigidly bound to this joint
839 const auto prevVertexCount = skinWeights.index.rows();
840 const auto newVertexCount =
841 prevVertexCount + static_cast<Eigen::Index>(meshOpt->vertices.size());
842 skinWeights.index.conservativeResize(newVertexCount, Eigen::NoChange);
843 skinWeights.weight.conservativeResize(newVertexCount, Eigen::NoChange);
844 skinWeights.index.bottomRows(newVertexCount - prevVertexCount).setZero();
845 skinWeights.weight.bottomRows(newVertexCount - prevVertexCount).setZero();
846 for (auto vi = prevVertexCount; vi < newVertexCount; ++vi) {
847 skinWeights.index(vi, 0) = static_cast<uint32_t>(jointIdx);
848 skinWeights.weight(vi, 0) = 1.0f;
849 }
850 }
851 }
852
853 if (!hasAnyColor) {
854 combinedMesh.colors.clear();
855 }
856
857 if (combinedMesh.vertices.empty()) {
858 return std::nullopt;
859 }
860
861 combinedMesh.updateNormals();
862 return std::make_pair(std::move(combinedMesh), std::move(skinWeights));
863}
864
865Character loadUrdfCharacterFromUrdfModel(
866 urdf::ModelInterfaceSharedPtr urdfModel,
867 const filesystem::path& urdfDir) {
868 const urdf::Link* root = urdfModel->getRoot().get();
869 MT_THROW_IF(!root, "Failed to parse URDF file from. No root link found.");
870
871 ParsingData data;
872
873 // Special Case: If the root link is named "world", it is treated as a world link. In this case,
874 // the actual root link is the first child link. Otherwise, the root link itself is considered the
875 // actual root link, and it is assumed to have a fixed joint (hence, no degrees of freedom).
876 if (root->name == "world") {
877 if (root->child_links.empty()) {
878 MT_THROW(
879 "Failed to parse URDF. The world link must have at least one child link, but it has none.");
880 } else if (root->child_links.size() > 1) {
881 MT_THROW(
882 "Failed to parse URDF. The world link must have only one child link, but it has {}.",
883
884 root->child_links.size());
885 }
886 root = root->child_links[0].get();
887 }
888
889 if (!loadUrdfSkeletonRecursive(data, kInvalidIndex, root)) {
890 MT_THROW("Failed to parse URDF.");
891 }
892
893 const size_t numJoints = data.skeleton.joints.size();
894 const size_t numJointParameters = numJoints * kParametersPerJoint;
895 const size_t numModelParameters = data.totalDoFs;
896 data.parameterTransform.offsets.setZero(numJointParameters);
897
898 resolveMimicJoints(data);
899
900 data.parameterTransform.transform.resize(numJointParameters, numModelParameters);
901 data.parameterTransform.transform.setFromTriplets(data.triplets.begin(), data.triplets.end());
902 data.parameterTransform.activeJointParams = data.parameterTransform.computeActiveJointParams();
903
904 const std::string robotName = urdfModel->getName();
905 const CollisionGeometry* collision = data.collision.empty() ? nullptr : &data.collision;
906
907 auto meshResult = buildCombinedMesh(data, urdfDir);
908 if (meshResult) {
909 auto& [mesh, skinWeights] = *meshResult;
910 return {
911 data.skeleton,
912 data.parameterTransform,
913 data.limits,
914 LocatorList{},
915 &mesh,
916 &skinWeights,
917 collision,
918 nullptr, // poseShapes
919 {}, // blendShapes
920 {}, // faceExpressionBlendShapes
921 robotName,
922 {}, // inverseBindPose
923 {}, // skinnedLocators
924 {}, // metadata
925 data.physicalProperties};
926 }
927
928 return {
929 data.skeleton,
930 data.parameterTransform,
931 data.limits,
932 LocatorList{},
933 nullptr, // mesh
934 nullptr, // skinWeights
935 collision,
936 nullptr, // poseShapes
937 {}, // blendShapes
938 {}, // faceExpressionBlendShapes
939 robotName,
940 {}, // inverseBindPose
941 {}, // skinnedLocators
942 {}, // metadata
943 data.physicalProperties};
944}
945
946} // namespace
947
948Character loadUrdfCharacter(const filesystem::path& filepath) {
949 urdf::ModelInterfaceSharedPtr urdfModel;
950
951 try {
952 urdfModel = urdf::parseURDFFile(filepath.string());
953 } catch (const std::exception& e) {
954 MT_THROW("Failed to parse URDF file from: {}. Error: {}", filepath.string(), e.what());
955 } catch (...) {
956 MT_THROW("Failed to parse URDF file from: {}", filepath.string());
957 }
958
959 try {
960 return loadUrdfCharacterFromUrdfModel(urdfModel, filepath.parent_path());
961 } catch (const std::exception& e) {
962 MT_THROW(
963 "Failed to create Character from URDF file: {}. Error: {}", filepath.string(), e.what());
964 } catch (...) {
965 MT_THROW("Failed to create Character from URDF file: {}", filepath.string());
966 }
967}
968
969Character loadUrdfCharacter(std::span<const std::byte> bytes) {
970 urdf::ModelInterfaceSharedPtr urdfModel;
971
972 try {
973 // Convert the byte span to a string
974 std::string urdfString(reinterpret_cast<const char*>(bytes.data()), bytes.size());
975 // Parse the URDF from the string
976 urdfModel = urdf::parseURDF(urdfString);
977 } catch (const std::exception& e) {
978 MT_THROW("Failed to read URDF file from URDF bytes. Error: {}", e.what());
979 } catch (...) {
980 MT_THROW("Failed to read URDF file from URDF bytes");
981 }
982
983 try {
984 return loadUrdfCharacterFromUrdfModel(urdfModel, {});
985 } catch (const std::exception& e) {
986 MT_THROW("Failed to create Character from URDF bytes. Error: {}", e.what());
987 } catch (...) {
988 MT_THROW("Failed to create Character from URDF bytes");
989 }
990}
991
993 std::span<const std::byte> bytes,
994 const filesystem::path& meshBasePath) {
995 urdf::ModelInterfaceSharedPtr urdfModel;
996
997 try {
998 std::string urdfString(reinterpret_cast<const char*>(bytes.data()), bytes.size());
999 urdfModel = urdf::parseURDF(urdfString);
1000 } catch (const std::exception& e) {
1001 MT_THROW("Failed to read URDF file from URDF bytes. Error: {}", e.what());
1002 } catch (...) {
1003 MT_THROW("Failed to read URDF file from URDF bytes");
1004 }
1005
1006 try {
1007 return loadUrdfCharacterFromUrdfModel(urdfModel, meshBasePath);
1008 } catch (const std::exception& e) {
1009 MT_THROW("Failed to create Character from URDF bytes. Error: {}", e.what());
1010 } catch (...) {
1011 MT_THROW("Failed to create Character from URDF bytes");
1012 }
1013}
1014
1015} // namespace momentum
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
Definition exception.h:31
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
#define MT_LOGW(...)
Definition log.h:180
Vector3< uint8_t > Vector3b
3D vector of unsigned bytes; commonly used for RGB color storage in momentum (see ColorArray).
Definition types.h:30
Matrix3< float > Matrix3f
Definition types.h:107
CollisionGeometryT< float > CollisionGeometry
SkeletonT< float > Skeleton
Definition fwd.h:263
Quaternion< float > Quaternionf
Definition types.h:386
Mesh generateCylinderMesh(float radius, float length, int segments)
Generates a cylinder mesh centered at the origin with the Z axis as its axis.
CollisionEllipsoidT< float > CollisionEllipsoid
Definition fwd.h:168
@ TX
Definition types.h:22
@ RX
Definition types.h:22
CollisionPrimitiveT< float > CollisionPrimitive
Definition fwd.h:111
std::vector< ParameterLimit > ParameterLimits
MeshT< float > Mesh
Definition fwd.h:20
constexpr T toCm(T x=T(1)) noexcept
Converts the given length x (in meters) to centimeters.
Definition constants.h:96
Quaternion< T > toMomentumQuaternion(const Quaternion< T > &q, const CoordinateSystem &from)
Converts a quaternion rotation from from into Momentum's canonical coordinate system.
Mesh generateSphereMesh(float radius, int latSegments, int lonSegments)
Generates a UV sphere mesh centered at the origin.
Character loadUrdfCharacter(const filesystem::path &filepath)
Loads a character from a URDF file.
Definition urdf_io.cpp:948
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
Eigen::Quaternion< T > Quaternion
Unit quaternion representing a 3D rotation.
Definition types.h:385
std::vector< JointPhysicalProperties > PhysicalProperties
Optional physical mass properties for a character.
Definition joint.h:114
CollisionBoxT< float > CollisionBox
Definition fwd.h:187
Mesh generateBoxMesh(float dimX, float dimY, float dimZ)
Generates a box mesh with the given dimensions centered at the origin.
constexpr size_t kParametersPerJoint
Definition types.h:21
std::optional< filesystem::path > resolveMeshPath(const std::string &filename, const filesystem::path &urdfDir)
Resolves a mesh filename from a URDF visual element to a filesystem path.
JointT< float > Joint
Definition fwd.h:206
Vector3< T > toMomentumVector3(const Vector3< T > &vec, UpVector up, Unit unit)
This function converts a 3D vector in the mocap marker coordinate system to the Momentum coordinate s...
std::optional< Mesh > loadStlMesh(const filesystem::path &filepath)
Loads a mesh from an STL file (binary or ASCII).
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
Vector< T, 3 > Vector3
Definition types.h:236
Vector3< float > Vector3f
Definition types.h:251
std::string_view toString(const LimitType type)
TaperedCapsuleT< float > TaperedCapsule
Definition fwd.h:320
std::optional< Mesh > loadObjMesh(const filesystem::path &filepath)
Loads a mesh from a Wavefront OBJ file (vertices and triangular/polygon faces).
std::vector< Locator > LocatorList
A collection of locators attached to a skeleton.
Definition locator.h:79
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
Physical mass properties attached to one skeleton joint.
Definition joint.h:88
std::string jointName
Skeleton joint that owns this physical body.
Definition joint.h:93
Represents the complete state of a skeleton.
Linear blend skinning weights for a character mesh: per-vertex joint indices and influence weights.
Lightweight transform with separate rotation, translation, and uniform scaling.
Definition transform.h:36
URDF character loader for Momentum.