15#include <pxr/base/tf/staticTokens.h>
17#include <pxr/base/gf/matrix4d.h>
18#include <pxr/base/gf/quatf.h>
19#include <pxr/base/gf/vec2f.h>
20#include <pxr/base/gf/vec3f.h>
21#include <pxr/base/gf/vec3i.h>
22#include <pxr/base/vt/array.h>
23#include <pxr/usd/sdf/valueTypeName.h>
24#include <pxr/usd/usd/primRange.h>
25#include <pxr/usd/usdGeom/scope.h>
26#include <pxr/usd/usdGeom/xform.h>
27#include <pxr/usd/usdSkel/cache.h>
28#include <pxr/usd/usdSkel/skeletonQuery.h>
32PXR_NAMESPACE_USING_DIRECTIVE
36 (Collision)(Locators)((momentumType,
"momentum:type"))((momentumParent,
"momentum:parent"))(
37 (momentumLength,
"momentum:length"))((momentumRadius,
"momentum:radius"))(
38 (momentumRadii,
"momentum:radii"))((momentumHalfExtents,
"momentum:halfExtents"))(
39 (momentumTranslation,
"momentum:translation"))((momentumRotation,
"momentum:rotation"))(
40 (momentumName,
"momentum:name"))((momentumOffset,
"momentum:offset"))(
41 (momentumWeight,
"momentum:weight"))((momentumLocked,
"momentum:locked"))(
43 "momentum:limitOrigin"))((momentumLimitWeight,
"momentum:limitWeight"))(
44 (momentumAttachedToSkin,
45 "momentum:attachedToSkin"))((momentumSkinOffset,
"momentum:skinOffset")));
51Eigen::Matrix4f toEigenMatrix4f(
const GfMatrix4d& gfMatrix) {
52 return Eigen::Map<const Eigen::Matrix4d>(gfMatrix.GetArray()).cast<
float>();
55GfMatrix4d toGfMatrix4d(
const Eigen::Matrix4f& eigenMatrix) {
56 GfMatrix4d gfMatrix{};
57 Eigen::Map<Eigen::Matrix4d>(gfMatrix.GetArray()) = eigenMatrix.cast<
double>();
62Eigen::Matrix4f jointToLocalTransform(
const Joint& joint) {
63 Eigen::Matrix4f transform = Eigen::Matrix4f::Identity();
64 transform.block<3, 3>(0, 0) = joint.preRotation.toRotationMatrix();
65 transform.block<3, 1>(0, 3) = joint.translationOffset;
70Eigen::Matrix4f computeWorldTransform(
const Skeleton& skeleton,
size_t jointIndex) {
72 jointIndex >= skeleton.joints.size(),
73 "Joint index {} exceeds skeleton joint count {}",
75 skeleton.joints.size());
77 const auto& joint = skeleton.joints.at(jointIndex);
78 Eigen::Matrix4f world = jointToLocalTransform(joint);
79 size_t parent = joint.parent;
82 parent >= skeleton.joints.size(),
83 "Parent joint index {} exceeds skeleton joint count {}",
85 skeleton.joints.size());
86 const auto& parentJoint = skeleton.joints.at(parent);
87 world = jointToLocalTransform(parentJoint) * world;
88 parent = parentJoint.parent;
94std::string leafName(
const std::string& path) {
95 auto pos = path.rfind(
'/');
96 if (pos == std::string::npos) {
99 return path.substr(pos + 1);
109 std::vector<std::string> paths(skeleton.
joints.size());
110 for (
size_t i = 0; i < skeleton.
joints.size(); ++i) {
111 const auto& joint = skeleton.
joints.at(i);
113 paths.at(i) = joint.name;
116 joint.parent >= paths.size(),
117 "Parent joint index {} exceeds paths size {} for joint {}",
121 paths.at(i) = paths.at(joint.parent) +
"/" + joint.name;
130 UsdSkelCache skelCache;
132 for (
const auto& prim : stage->Traverse()) {
133 if (!prim.IsA<UsdSkelSkeleton>()) {
137 UsdSkelSkeleton skelPrim(prim);
138 UsdSkelSkeletonQuery skelQuery = skelCache.GetSkelQuery(skelPrim);
143 VtArray<TfToken> jointNames = skelQuery.GetJointOrder();
144 if (jointNames.empty()) {
148 skeleton.
joints.reserve(jointNames.size());
151 VtArray<int> topology = skelQuery.GetTopology().GetParentIndices();
153 for (
size_t i = 0; i < jointNames.size(); ++i) {
156 joint.
name = leafName(jointNames[i].GetString());
158 if (i < topology.size() && topology[i] >= 0) {
159 joint.
parent = topology[i];
164 joint.
preRotation = Eigen::Quaternionf::Identity();
167 skeleton.
joints.push_back(joint);
171 VtArray<GfMatrix4d> restTransforms;
172 if (skelPrim.GetRestTransformsAttr().Get(&restTransforms) &&
173 restTransforms.size() == skeleton.
joints.size()) {
174 for (
size_t i = 0; i < restTransforms.size(); ++i) {
175 auto matrix = toEigenMatrix4f(restTransforms[i]);
176 skeleton.
joints[i].translationOffset = matrix.block<3, 1>(0, 3);
177 Eigen::Matrix3f rotMatrix = matrix.block<3, 3>(0, 0);
178 skeleton.
joints[i].preRotation = Eigen::Quaternionf(rotMatrix).normalized();
182 VtArray<GfMatrix4d> bindTransforms;
183 if (skelQuery.GetJointWorldBindTransforms(&bindTransforms)) {
186 for (
size_t i = 0; i < bindTransforms.size(); ++i) {
187 Eigen::Matrix4f worldMatrix = toEigenMatrix4f(bindTransforms[i]);
190 Eigen::Matrix4f localMatrix;
193 skeleton.
joints[i].parent >= bindTransforms.size(),
194 "Parent joint index {} exceeds bindTransforms size {}",
195 skeleton.
joints[i].parent,
196 bindTransforms.size());
197 Eigen::Matrix4f parentWorld =
198 toEigenMatrix4f(bindTransforms[skeleton.
joints[i].parent]);
199 localMatrix = parentWorld.inverse() * worldMatrix;
201 localMatrix = worldMatrix;
204 skeleton.
joints[i].translationOffset = localMatrix.block<3, 1>(0, 3);
205 Eigen::Matrix3f rotMatrix = localMatrix.block<3, 3>(0, 0);
206 skeleton.
joints[i].preRotation = Eigen::Quaternionf(rotMatrix).normalized();
220 VtArray<TfToken> jointTokens;
221 jointTokens.reserve(skeleton.
joints.size());
222 for (
const auto& path : paths) {
223 jointTokens.push_back(TfToken(path));
225 skelPrim.GetJointsAttr().Set(jointTokens);
228 VtArray<GfMatrix4d> restTransforms;
229 restTransforms.reserve(skeleton.
joints.size());
230 for (
const auto& joint : skeleton.
joints) {
231 restTransforms.push_back(toGfMatrix4d(jointToLocalTransform(joint)));
233 skelPrim.GetRestTransformsAttr().Set(restTransforms);
236 VtArray<GfMatrix4d> bindTransforms;
237 bindTransforms.reserve(skeleton.
joints.size());
238 for (
size_t i = 0; i < skeleton.
joints.size(); ++i) {
239 bindTransforms.push_back(toGfMatrix4d(computeWorldTransform(skeleton, i)));
241 skelPrim.GetBindTransformsAttr().Set(bindTransforms);
247 const UsdStageRefPtr& stage,
248 const SdfPath& skelRootPath) {
249 if (collision.empty() || skeleton.
joints.empty()) {
253 auto collisionScope = UsdGeomScope::Define(stage, skelRootPath.AppendChild(_tokens->Collision));
255 for (
size_t i = 0; i < collision.size(); ++i) {
256 const auto& primitive = collision[i];
259 switch (primitive.type) {
261 type =
"collision_capsule";
264 type =
"collision_ellipsoid";
267 type =
"collision_box";
271 const std::string jointName = (primitive.parent < skeleton.
joints.size())
272 ? skeleton.
joints.at(primitive.parent).name
274 const std::string primName =
sanitizePrimName(jointName +
"_col_" + std::to_string(i));
276 auto primPath = collisionScope.GetPath().AppendChild(TfToken(primName));
277 auto prim = stage->DefinePrim(primPath);
280 "Failed to create collision prim '{}' (from joint '{}')",
284 prim.CreateAttribute(_tokens->momentumType, SdfValueTypeNames->String).Set(type);
285 prim.CreateAttribute(_tokens->momentumParent, SdfValueTypeNames->String).Set(jointName);
287 prim.CreateAttribute(_tokens->momentumLength, SdfValueTypeNames->Float).Set(primitive.length);
288 prim.CreateAttribute(_tokens->momentumRadius, SdfValueTypeNames->Float2)
289 .Set(GfVec2f(primitive.radius.x(), primitive.radius.y()));
291 prim.CreateAttribute(_tokens->momentumRadii, SdfValueTypeNames->Float3)
293 primitive.ellipsoidRadii.x(),
294 primitive.ellipsoidRadii.y(),
295 primitive.ellipsoidRadii.z()));
297 prim.CreateAttribute(_tokens->momentumHalfExtents, SdfValueTypeNames->Float3)
299 primitive.boxHalfExtents.x(),
300 primitive.boxHalfExtents.y(),
301 primitive.boxHalfExtents.z()));
304 const auto& t = primitive.transformation.translation;
305 prim.CreateAttribute(_tokens->momentumTranslation, SdfValueTypeNames->Float3)
306 .Set(GfVec3f(t.x(), t.y(), t.z()));
308 const auto& q = primitive.transformation.rotation;
309 prim.CreateAttribute(_tokens->momentumRotation, SdfValueTypeNames->Quatf)
310 .Set(GfQuatf(q.w(), q.x(), q.y(), q.z()));
315 const UsdStageRefPtr& stage,
319 for (
const auto& prim : stage->Traverse()) {
320 auto typeAttr = prim.GetAttribute(_tokens->momentumType);
326 if (!typeAttr.Get(&type) ||
327 (type !=
"collision_capsule" && type !=
"collision_ellipsoid" && type !=
"collision_box")) {
333 std::string parentName;
334 if (
auto attr = prim.GetAttribute(_tokens->momentumParent); attr) {
335 attr.Get(&parentName);
339 if (type ==
"collision_capsule") {
341 if (
auto attr = prim.GetAttribute(_tokens->momentumLength); attr) {
342 attr.Get(&primitive.
length);
345 GfVec2f radius(0.0f, 0.0f);
346 if (
auto attr = prim.GetAttribute(_tokens->momentumRadius); attr) {
348 primitive.
radius = Eigen::Vector2f(radius[0], radius[1]);
350 }
else if (type ==
"collision_ellipsoid") {
352 GfVec3f radii(0.0f, 0.0f, 0.0f);
353 if (
auto attr = prim.GetAttribute(_tokens->momentumRadii); attr) {
355 primitive.
ellipsoidRadii = Eigen::Vector3f(radii[0], radii[1], radii[2]);
357 }
else if (type ==
"collision_box") {
359 GfVec3f halfExtents(0.0f, 0.0f, 0.0f);
360 if (
auto attr = prim.GetAttribute(_tokens->momentumHalfExtents); attr) {
361 attr.Get(&halfExtents);
362 primitive.
boxHalfExtents = Eigen::Vector3f(halfExtents[0], halfExtents[1], halfExtents[2]);
366 GfVec3f translation(0.0f, 0.0f, 0.0f);
367 if (
auto attr = prim.GetAttribute(_tokens->momentumTranslation); attr) {
368 attr.Get(&translation);
370 Eigen::Vector3f(translation[0], translation[1], translation[2]);
373 GfQuatf rotation(1.0f);
374 if (
auto attr = prim.GetAttribute(_tokens->momentumRotation); attr) {
378 rotation.GetImaginary()[0],
379 rotation.GetImaginary()[1],
380 rotation.GetImaginary()[2]);
383 result.push_back(primitive);
392 const UsdStageRefPtr& stage,
393 const SdfPath& skelRootPath) {
394 if (locators.empty() || skeleton.
joints.empty()) {
398 auto locatorScope = UsdGeomScope::Define(stage, skelRootPath.AppendChild(_tokens->Locators));
400 for (
size_t i = 0; i < locators.size(); ++i) {
401 const auto& loc = locators[i];
402 const std::string baseName = loc.name.empty() ?
"locator" : loc.name;
403 const std::string primName =
sanitizePrimName(baseName +
"_" + std::to_string(i));
405 auto primPath = locatorScope.GetPath().AppendChild(TfToken(primName));
406 auto prim = stage->DefinePrim(primPath);
409 "Failed to create locator prim '{}' (from locator '{}')",
413 prim.CreateAttribute(_tokens->momentumType, SdfValueTypeNames->String)
414 .Set(std::string(
"locator"));
416 prim.CreateAttribute(_tokens->momentumName, SdfValueTypeNames->String).Set(loc.name);
418 const std::string parentName =
419 (loc.parent < skeleton.
joints.size()) ? skeleton.
joints.at(loc.parent).name :
"";
420 prim.CreateAttribute(_tokens->momentumParent, SdfValueTypeNames->String).Set(parentName);
422 prim.CreateAttribute(_tokens->momentumOffset, SdfValueTypeNames->Float3)
423 .Set(GfVec3f(loc.offset.x(), loc.offset.y(), loc.offset.z()));
425 prim.CreateAttribute(_tokens->momentumWeight, SdfValueTypeNames->Float).Set(loc.weight);
427 prim.CreateAttribute(_tokens->momentumLocked, SdfValueTypeNames->Int3)
428 .Set(GfVec3i(loc.locked.x(), loc.locked.y(), loc.locked.z()));
430 prim.CreateAttribute(_tokens->momentumLimitOrigin, SdfValueTypeNames->Float3)
431 .Set(GfVec3f(loc.limitOrigin.x(), loc.limitOrigin.y(), loc.limitOrigin.z()));
433 prim.CreateAttribute(_tokens->momentumLimitWeight, SdfValueTypeNames->Float3)
434 .Set(GfVec3f(loc.limitWeight.x(), loc.limitWeight.y(), loc.limitWeight.z()));
436 if (loc.attachedToSkin) {
437 prim.CreateAttribute(_tokens->momentumAttachedToSkin, SdfValueTypeNames->Bool).Set(
true);
438 prim.CreateAttribute(_tokens->momentumSkinOffset, SdfValueTypeNames->Float)
439 .Set(loc.skinOffset);
447 for (
const auto& prim : stage->Traverse()) {
448 auto typeAttr = prim.GetAttribute(_tokens->momentumType);
454 if (!typeAttr.Get(&type) || type !=
"locator") {
459 if (
auto attr = prim.GetAttribute(_tokens->momentumName); attr) {
462 loc.
name = prim.GetName().GetString();
465 std::string parentName;
466 if (
auto attr = prim.GetAttribute(_tokens->momentumParent); attr) {
467 attr.Get(&parentName);
468 if (!parentName.empty()) {
473 GfVec3f offset(0.0f, 0.0f, 0.0f);
474 if (
auto attr = prim.GetAttribute(_tokens->momentumOffset); attr) {
476 loc.
offset = Eigen::Vector3f(offset[0], offset[1], offset[2]);
479 if (
auto attr = prim.GetAttribute(_tokens->momentumWeight); attr) {
483 GfVec3i locked(0, 0, 0);
484 if (
auto attr = prim.GetAttribute(_tokens->momentumLocked); attr) {
486 loc.
locked = Eigen::Vector3i(locked[0], locked[1], locked[2]);
489 GfVec3f limitOrigin(0.0f, 0.0f, 0.0f);
490 if (
auto attr = prim.GetAttribute(_tokens->momentumLimitOrigin); attr) {
491 attr.Get(&limitOrigin);
492 loc.
limitOrigin = Eigen::Vector3f(limitOrigin[0], limitOrigin[1], limitOrigin[2]);
495 GfVec3f limitWeight(0.0f, 0.0f, 0.0f);
496 if (
auto attr = prim.GetAttribute(_tokens->momentumLimitWeight); attr) {
497 attr.Get(&limitWeight);
498 loc.
limitWeight = Eigen::Vector3f(limitWeight[0], limitWeight[1], limitWeight[2]);
501 if (
auto attr = prim.GetAttribute(_tokens->momentumAttachedToSkin); attr) {
505 if (
auto attr = prim.GetAttribute(_tokens->momentumSkinOffset); attr) {
509 result.push_back(std::move(loc));
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Skeleton loadSkeletonFromUsd(const UsdStageRefPtr &stage)
Load a skeleton from a USD stage.
CollisionGeometryT< float > CollisionGeometry
SkeletonT< float > Skeleton
void saveSkeletonToUsd(const Skeleton &skeleton, UsdSkelSkeleton &skelPrim)
Save a skeleton to a USD stage.
void saveCollisionGeometryToUsd(const CollisionGeometry &collision, const Skeleton &skeleton, const UsdStageRefPtr &stage, const SdfPath &skelRootPath)
Save collision geometry as child prims under the skeleton.
CollisionPrimitiveT< float > CollisionPrimitive
std::string sanitizePrimName(const std::string &name)
Sanitize a string for use as a USD SDF prim name.
LocatorList loadLocatorsFromUsd(const UsdStageRefPtr &stage, const Skeleton &skeleton)
Load locators from child prims.
void saveLocatorsToUsd(const LocatorList &locators, const Skeleton &skeleton, const UsdStageRefPtr &stage, const SdfPath &skelRootPath)
Save locators as child prims under the skeleton.
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
CollisionGeometry loadCollisionGeometryFromUsd(const UsdStageRefPtr &stage, const Skeleton &skeleton)
Load collision geometry from child prims.
std::vector< std::string > buildHierarchicalPaths(const Skeleton &skeleton)
Build hierarchical joint paths from flat names and parent indices.
std::vector< Locator > LocatorList
A collection of locators attached to a skeleton.
S length
Length of a tapered capsule along the x-axis.
Vector3< S > boxHalfExtents
Half extents along the local axes of a box.
TransformT< S > transformation
Transformation defining the primitive pose relative to the parent coordinate system.
size_t parent
Parent joint to which the geometry is attached.
Vector2< S > radius
Radii at the two endpoints of a tapered capsule.
CollisionPrimitiveType type
Primitive kind.
Vector3< S > ellipsoidRadii
Radii along the local axes of an ellipsoid.
size_t parent
Index of the parent joint in the skeleton hierarchy, or kInvalidIndex for the root.
Quaternion< T > preRotation
Pre-rotation from the parent joint's axes to this joint's local axes.
Vector3< T > translationOffset
Constant translation offset from the parent joint's origin to this joint's origin,...
Represents a point attached to a joint in a skeleton.
float weight
Influence weight when used as a constraint in error functions.
size_t parent
Index of the parent joint in the skeleton.
float skinOffset
Offset from the skin surface, used when solving for body shape using locators.
Vector3f limitWeight
Per-axis strength pulling the locator back toward limitOrigin.
Vector3i locked
Per-axis lock flags (x, y, z): 1 = locked, 0 = free.
bool attachedToSkin
True if the locator is attached to the skin of a person (e.g.
Vector3f offset
Position in the parent joint's local coordinate frame.
Vector3f limitOrigin
Reference position for limit constraints; typically equals offset when loaded.
size_t getJointIdByName(std::string_view name) const
Returns the index of a joint with the given name, or kInvalidIndex if not found.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
PXR_NAMESPACE_USING_DIRECTIVE TF_DEFINE_PRIVATE_TOKENS(_tokens,(Collision)(Locators)((momentumType, "momentum:type"))((momentumParent, "momentum:parent"))((momentumLength, "momentum:length"))((momentumRadius, "momentum:radius"))((momentumRadii, "momentum:radii"))((momentumHalfExtents, "momentum:halfExtents"))((momentumTranslation, "momentum:translation"))((momentumRotation, "momentum:rotation"))((momentumName, "momentum:name"))((momentumOffset, "momentum:offset"))((momentumWeight, "momentum:weight"))((momentumLocked, "momentum:locked"))((momentumLimitOrigin, "momentum:limitOrigin"))((momentumLimitWeight, "momentum:limitWeight"))((momentumAttachedToSkin, "momentum:attachedToSkin"))((momentumSkinOffset, "momentum:skinOffset")))