16#include <pxr/base/tf/staticTokens.h>
18#include <pxr/base/gf/half.h>
19#include <pxr/base/gf/quatf.h>
20#include <pxr/base/gf/vec3d.h>
21#include <pxr/base/gf/vec3f.h>
22#include <pxr/base/gf/vec3h.h>
23#include <pxr/base/vt/array.h>
24#include <pxr/usd/sdf/valueTypeName.h>
25#include <pxr/usd/usd/primRange.h>
26#include <pxr/usd/usdGeom/scope.h>
27#include <pxr/usd/usdGeom/xform.h>
28#include <pxr/usd/usdGeom/xformCommonAPI.h>
29#include <pxr/usd/usdSkel/animation.h>
30#include <pxr/usd/usdSkel/bindingAPI.h>
33#include <unordered_map>
34#include <unordered_set>
36PXR_NAMESPACE_USING_DIRECTIVE
40 (Animation)(Markers)((momentumMotionFps,
"momentum:motion:fps"))(
41 (momentumMotionParameterNames,
42 "momentum:motion:parameterNames"))((momentumMotionPoses,
"momentum:motion:poses"))(
43 (momentumMotionNumFrames,
44 "momentum:motion:numFrames"))((momentumMotionNumParams,
"momentum:motion:numParams"))(
45 (momentumMotionJointNames,
46 "momentum:motion:jointNames"))((momentumMotionOffsets,
"momentum:motion:offsets"))(
48 "momentum:marker:name"))((momentumMarkerOccluded,
"momentum:marker:occluded"))(
49 (momentumMarkerConfidence,
50 "momentum:marker:confidence"))((momentumMarkersFps,
"momentum:markers:fps")));
55 const UsdStageRefPtr& stage,
56 UsdSkelSkeleton& skelPrim,
58 std::span<const SkeletonState> skeletonStates,
62 const auto numJoints = skeleton.
joints.size();
65 auto animPath = skelPrim.GetPath().AppendChild(_tokens->Animation);
66 auto animPrim = UsdSkelAnimation::Define(stage, animPath);
71 VtArray<TfToken> jointTokens;
72 jointTokens.reserve(numJoints);
73 for (
const auto& path : paths) {
74 jointTokens.push_back(TfToken(path));
76 animPrim.GetJointsAttr().Set(jointTokens);
79 UsdSkelBindingAPI bindingAPI = UsdSkelBindingAPI::Apply(skelPrim.GetPrim());
80 bindingAPI.GetAnimationSourceRel().SetTargets({animPath});
83 const double startTime = 0.0;
84 const auto endTime =
static_cast<double>(skeletonStates.size() - 1);
85 stage->SetStartTimeCode(startTime);
86 stage->SetEndTimeCode(endTime);
87 stage->SetTimeCodesPerSecond(
static_cast<double>(fps));
90 VtArray<GfVec3f> translations;
91 VtArray<GfQuatf> rotations;
92 VtArray<GfVec3h> scales;
93 translations.reserve(numJoints);
94 rotations.reserve(numJoints);
95 scales.reserve(numJoints);
97 auto translationsAttr = animPrim.GetTranslationsAttr();
98 auto rotationsAttr = animPrim.GetRotationsAttr();
99 auto scalesAttr = animPrim.GetScalesAttr();
101 for (
size_t frame = 0; frame < skeletonStates.size(); ++frame) {
102 const auto& state = skeletonStates[frame];
103 const auto timeCode = UsdTimeCode(
static_cast<double>(frame));
105 translations.clear();
109 for (
size_t j = 0; j < numJoints; ++j) {
110 const auto& localTransform = state.jointState[j].localTransform;
112 const auto& t = localTransform.translation;
113 translations.push_back(GfVec3f(t.x(), t.y(), t.z()));
115 const auto& q = localTransform.rotation;
116 rotations.push_back(GfQuatf(q.w(), q.x(), q.y(), q.z()));
118 const GfHalf s =
static_cast<GfHalf
>(localTransform.scale);
119 scales.push_back(GfVec3h(s, s, s));
122 translationsAttr.Set(translations, timeCode);
123 rotationsAttr.Set(rotations, timeCode);
124 scalesAttr.Set(scales, timeCode);
129 const UsdStageRefPtr& stage,
131 std::vector<SkeletonState> states;
132 std::vector<float> frameTimes;
134 const auto numJoints = skeleton.
joints.size();
137 for (
const auto& prim : stage->Traverse()) {
138 if (!prim.IsA<UsdSkelAnimation>()) {
142 UsdSkelAnimation animPrim(prim);
144 const double tps = stage->GetTimeCodesPerSecond();
150 std::vector<double> timeSamples;
151 animPrim.GetTranslationsAttr().GetTimeSamples(&timeSamples);
152 if (timeSamples.empty()) {
156 states.reserve(timeSamples.size());
157 frameTimes.reserve(timeSamples.size());
159 VtArray<GfVec3f> translations;
160 VtArray<GfQuatf> rotations;
161 VtArray<GfVec3h> scales;
163 auto translationsAttr = animPrim.GetTranslationsAttr();
164 auto rotationsAttr = animPrim.GetRotationsAttr();
165 auto scalesAttr = animPrim.GetScalesAttr();
167 for (
const double sample : timeSamples) {
168 const auto timeCode = UsdTimeCode(sample);
170 translationsAttr.Get(&translations, timeCode);
171 rotationsAttr.Get(&rotations, timeCode);
172 scalesAttr.Get(&scales, timeCode);
177 for (
size_t j = 0; j < numJoints; ++j) {
179 const auto& joint = skeleton.
joints[j];
182 if (j < translations.size()) {
183 jointParams[base + 0] = translations[j][0] - joint.translationOffset.x();
184 jointParams[base + 1] = translations[j][1] - joint.translationOffset.y();
185 jointParams[base + 2] = translations[j][2] - joint.translationOffset.z();
189 if (j < rotations.size()) {
190 const auto& gfQ = rotations[j];
191 Eigen::Quaternionf fullRotation(
192 gfQ.GetReal(), gfQ.GetImaginary()[0], gfQ.GetImaginary()[1], gfQ.GetImaginary()[2]);
195 Eigen::Quaternionf jointRotation = joint.preRotation.inverse() * fullRotation;
197 jointParams[base + 3] = euler[0];
198 jointParams[base + 4] = euler[1];
199 jointParams[base + 5] = euler[2];
203 if (j < scales.size()) {
204 const auto scaleVal =
static_cast<float>(scales[j][0]);
205 jointParams[base + 6] = scaleVal > 0.0f ? std::log2(scaleVal) : 0.0f;
209 states.emplace_back(std::move(jointParams), skeleton,
false);
210 frameTimes.push_back(
static_cast<float>(sample / tps));
216 return {std::move(states), std::move(frameTimes)};
224 const auto& [paramNames, poses] = motion;
225 const auto& [jointNames, offsetValues] = offsets;
227 if (paramNames.empty() || poses.cols() == 0) {
231 prim.CreateAttribute(_tokens->momentumMotionFps, SdfValueTypeNames->Float).Set(fps);
234 VtArray<std::string> paramNamesArray(paramNames.begin(), paramNames.end());
235 prim.CreateAttribute(_tokens->momentumMotionParameterNames, SdfValueTypeNames->StringArray)
236 .Set(paramNamesArray);
239 const Eigen::Index numParams = poses.rows();
240 const Eigen::Index numFrames = poses.cols();
241 VtArray<float> posesArray(numParams * numFrames);
242 for (Eigen::Index f = 0; f < numFrames; ++f) {
243 for (Eigen::Index p = 0; p < numParams; ++p) {
244 posesArray[f * numParams + p] = poses(p, f);
247 prim.CreateAttribute(_tokens->momentumMotionPoses, SdfValueTypeNames->FloatArray).Set(posesArray);
248 prim.CreateAttribute(_tokens->momentumMotionNumFrames, SdfValueTypeNames->Int)
249 .Set(
static_cast<int>(numFrames));
250 prim.CreateAttribute(_tokens->momentumMotionNumParams, SdfValueTypeNames->Int)
251 .Set(
static_cast<int>(numParams));
254 if (!jointNames.empty() && offsetValues.size() > 0) {
255 VtArray<std::string> jointNamesArray(jointNames.begin(), jointNames.end());
256 prim.CreateAttribute(_tokens->momentumMotionJointNames, SdfValueTypeNames->StringArray)
257 .Set(jointNamesArray);
259 VtArray<float> offsetsArray(offsetValues.size());
260 for (Eigen::Index i = 0; i < offsetValues.size(); ++i) {
261 offsetsArray[i] = offsetValues[i];
263 prim.CreateAttribute(_tokens->momentumMotionOffsets, SdfValueTypeNames->FloatArray)
273 auto fpsAttr = prim.GetAttribute(_tokens->momentumMotionFps);
275 return {motion, identity, fps};
281 prim.GetAttribute(_tokens->momentumMotionNumFrames).Get(&numFrames);
282 prim.GetAttribute(_tokens->momentumMotionNumParams).Get(&numParams);
284 if (numFrames <= 0 || numParams <= 0) {
285 return {motion, identity, fps};
289 VtArray<std::string> paramNamesArray;
290 if (
auto attr = prim.GetAttribute(_tokens->momentumMotionParameterNames); attr) {
291 attr.Get(¶mNamesArray);
293 auto& [paramNames, poses] = motion;
294 paramNames.assign(paramNamesArray.begin(), paramNamesArray.end());
297 VtArray<float> posesArray;
298 if (
auto attr = prim.GetAttribute(_tokens->momentumMotionPoses); attr) {
299 attr.Get(&posesArray);
302 const auto expectedSize =
static_cast<size_t>(numParams) *
static_cast<size_t>(numFrames);
303 if (posesArray.size() == expectedSize) {
304 poses.resize(numParams, numFrames);
305 for (
int f = 0; f < numFrames; ++f) {
306 for (
int p = 0; p < numParams; ++p) {
307 poses(p, f) = posesArray[f * numParams + p];
312 "Poses array size ({}) does not match numParams * numFrames ({} * {})",
319 auto& [jointNames, offsetValues] = identity;
321 VtArray<std::string> jointNamesArray;
322 if (
auto attr = prim.GetAttribute(_tokens->momentumMotionJointNames); attr) {
323 attr.Get(&jointNamesArray);
325 jointNames.assign(jointNamesArray.begin(), jointNamesArray.end());
327 VtArray<float> offsetsArray;
328 if (
auto attr = prim.GetAttribute(_tokens->momentumMotionOffsets); attr) {
329 attr.Get(&offsetsArray);
330 Eigen::VectorXf offsetVec(offsetsArray.size());
331 for (
size_t i = 0; i < offsetsArray.size(); ++i) {
332 offsetVec[i] = offsetsArray[i];
337 return {std::move(motion), std::move(identity), fps};
341 const UsdStageRefPtr& stage,
342 const SdfPath& skelRootPath,
344 std::span<
const std::vector<Marker>> markerSequence) {
345 if (markerSequence.empty()) {
350 std::vector<std::string> markerNames;
351 markerNames.reserve(markerSequence[0].size());
352 std::unordered_set<std::string> seenNames;
353 for (
const auto& frameMarkers : markerSequence) {
354 for (
const auto& marker : frameMarkers) {
355 if (seenNames.insert(marker.name).second) {
356 markerNames.push_back(marker.name);
361 if (markerNames.empty()) {
366 std::vector<std::unordered_map<std::string_view, size_t>> frameIndices(markerSequence.size());
368 for (
size_t f = 0; f < markerSequence.size(); ++f) {
369 frameIndices[f].reserve(markerSequence[f].size());
370 for (
size_t i = 0; i < markerSequence[f].size(); ++i) {
371 frameIndices[f][markerSequence[f][i].name] = i;
376 auto markersPath = skelRootPath.AppendChild(_tokens->Markers);
377 UsdGeomScope::Define(stage, markersPath);
380 auto markersPrim = stage->GetPrimAtPath(markersPath);
381 markersPrim.CreateAttribute(_tokens->momentumMarkersFps, SdfValueTypeNames->Float).Set(fps);
384 std::unordered_set<std::string> usedSafeNames;
387 for (
const auto& name : markerNames) {
389 std::string safeName = name;
390 for (
auto& c : safeName) {
391 if (!std::isalnum(
static_cast<unsigned char>(c)) && c !=
'_') {
397 std::string baseName = safeName;
399 while (!usedSafeNames.insert(safeName).second) {
400 safeName = baseName +
"_" + std::to_string(suffix++);
403 auto markerPath = markersPath.AppendChild(TfToken(safeName));
404 auto xformPrim = UsdGeomXform::Define(stage, markerPath);
408 .CreateAttribute(_tokens->momentumMarkerName, SdfValueTypeNames->String)
411 auto xformAPI = UsdGeomXformCommonAPI(xformPrim);
414 auto occludedAttr = xformPrim.GetPrim().CreateAttribute(
415 _tokens->momentumMarkerOccluded, SdfValueTypeNames->Bool);
416 auto confidenceAttr = xformPrim.GetPrim().CreateAttribute(
417 _tokens->momentumMarkerConfidence, SdfValueTypeNames->Float);
420 for (
size_t frame = 0; frame < markerSequence.size(); ++frame) {
421 const auto timeCode = UsdTimeCode(
static_cast<double>(frame));
424 auto it = frameIndices[frame].find(name);
425 if (it != frameIndices[frame].end()) {
426 const auto& marker = markerSequence[frame][it->second];
427 xformAPI.SetTranslate(GfVec3d(marker.pos.x(), marker.pos.y(), marker.pos.z()), timeCode);
428 occludedAttr.Set(marker.occluded, timeCode);
429 confidenceAttr.Set(marker.confidence, timeCode);
432 xformAPI.SetTranslate(GfVec3d(0.0, 0.0, 0.0), timeCode);
433 occludedAttr.Set(
true, timeCode);
434 confidenceAttr.Set(0.0f, timeCode);
440 const auto endTime =
static_cast<double>(markerSequence.size() - 1);
441 if (stage->GetEndTimeCode() < endTime) {
442 stage->SetEndTimeCode(endTime);
444 if (stage->GetStartTimeCode() > 0.0) {
445 stage->SetStartTimeCode(0.0);
447 stage->SetTimeCodesPerSecond(
static_cast<double>(fps));
454 UsdPrim markersScopePrim;
455 for (
const auto& prim : stage->Traverse()) {
456 if (prim.GetName() == _tokens->Markers && prim.IsA<UsdGeomScope>()) {
457 markersScopePrim = prim;
462 if (!markersScopePrim) {
467 auto fpsAttr = markersScopePrim.GetAttribute(_tokens->momentumMarkersFps);
469 fpsAttr.Get(&result.
fps);
474 struct MarkerPrimInfo {
478 std::vector<MarkerPrimInfo> markerPrims;
480 for (
const auto& child : markersScopePrim.GetChildren()) {
481 if (!child.IsA<UsdGeomXform>()) {
485 std::string markerName;
486 auto nameAttr = child.GetAttribute(_tokens->momentumMarkerName);
488 nameAttr.Get(&markerName);
490 markerName = child.GetName().GetString();
493 markerPrims.push_back({markerName, UsdGeomXform(child)});
496 if (markerPrims.empty()) {
501 std::vector<double> timeSamples;
502 auto firstOccludedAttr =
503 markerPrims[0].xform.GetPrim().GetAttribute(_tokens->momentumMarkerOccluded);
504 if (firstOccludedAttr) {
505 firstOccludedAttr.GetTimeSamples(&timeSamples);
508 if (timeSamples.empty()) {
512 const auto numFrames =
static_cast<int>(timeSamples.size());
514 result.
frames.resize(numFrames);
517 struct CachedMarkerInfo {
519 UsdGeomXformCommonAPI xformAPI;
520 UsdAttribute occludedAttr;
521 UsdAttribute confidenceAttr;
523 std::vector<CachedMarkerInfo> cachedMarkers;
524 cachedMarkers.reserve(markerPrims.size());
525 for (
const auto& [name, xform] : markerPrims) {
526 cachedMarkers.push_back(
528 UsdGeomXformCommonAPI(xform),
529 xform.GetPrim().GetAttribute(_tokens->momentumMarkerOccluded),
530 xform.GetPrim().GetAttribute(_tokens->momentumMarkerConfidence)});
533 for (
int frame = 0; frame < numFrames; ++frame) {
534 const auto timeCode = UsdTimeCode(timeSamples[frame]);
535 auto& frameMarkers = result.
frames[frame];
536 frameMarkers.reserve(cachedMarkers.size());
538 for (
const auto& cached : cachedMarkers) {
540 marker.
name = cached.name;
547 UsdGeomXformCommonAPI::RotationOrder rotOrder{};
548 if (cached.xformAPI.GetXformVectors(
549 &translate, &rotation, &scale, &pivot, &rotOrder, timeCode)) {
550 marker.
pos =
Vector3d(translate[0], translate[1], translate[2]);
554 if (cached.occludedAttr) {
555 bool occluded =
true;
556 cached.occludedAttr.Get(&occluded, timeCode);
561 if (cached.confidenceAttr) {
562 float confidence = 1.0f;
563 cached.confidenceAttr.Get(&confidence, timeCode);
567 frameMarkers.push_back(std::move(marker));
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Vector3< double > Vector3d
SkeletonT< float > Skeleton
std::tuple< std::vector< std::string >, JointParameters > IdentityParameters
A tuple of skeleton joint names and identity parameters.
Vector3< T > quaternionToEuler(const Quaternion< T > &q)
Converts a quaternion to Euler angles using the Extrinsic XYZ convention.
std::tuple< std::vector< std::string >, Eigen::MatrixXf > MotionParameters
A tuple of model parameter names and a matrix of poses across a sequence of frames.
void saveSkeletonStatesToUsd(const UsdStageRefPtr &stage, UsdSkelSkeleton &skelPrim, const Skeleton &skeleton, std::span< const SkeletonState > skeletonStates, float fps)
Save skeleton states as a UsdSkelAnimation on the stage.
JointParametersT< float > JointParameters
void saveMotionToUsd(const UsdPrim &prim, float fps, const MotionParameters &motion, const IdentityParameters &offsets)
Save model-parameter motion as custom attributes on a USD prim.
constexpr size_t kParametersPerJoint
void saveMarkerSequenceToUsd(const UsdStageRefPtr &stage, const SdfPath &skelRootPath, float fps, std::span< const std::vector< Marker > > markerSequence)
Save marker sequence as animated Xform prims under a Markers scope.
std::tuple< MotionParameters, IdentityParameters, float > loadMotionFromUsd(const UsdPrim &prim)
Load model-parameter motion from custom attributes on a USD prim.
MarkerSequence loadMarkerSequenceFromUsd(const UsdStageRefPtr &stage)
Load marker sequence from animated Xform prims.
std::tuple< std::vector< SkeletonState >, std::vector< float > > loadSkeletonStatesFromUsd(const UsdStageRefPtr &stage, const Skeleton &skeleton)
Load skeleton states from a USD stage.
std::vector< std::string > buildHierarchicalPaths(const Skeleton &skeleton)
Build hierarchical joint paths from flat names and parent indices.
static EIGEN_DEVICE_FUNC Derived< Scalar > Zero(::Eigen::Index size)
All frames from a single motion capture sequence for one subject (actor).
float fps
Frame rate of the capture, in frames per second.
std::vector< std::vector< Marker > > frames
All marker observations across the sequence. Layout: [numFrames][numMarkers].
A single motion capture marker observation (position, occlusion, confidence).
Vector3d pos
The 3D position of the marker, in centimeters.
bool occluded
True if the marker is occluded in this frame, false if visible.
float confidence
Trust weight for this observation (e.g.
std::string name
The name of the marker.
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,(Animation)(Markers)((momentumMotionFps, "momentum:motion:fps"))((momentumMotionParameterNames, "momentum:motion:parameterNames"))((momentumMotionPoses, "momentum:motion:poses"))((momentumMotionNumFrames, "momentum:motion:numFrames"))((momentumMotionNumParams, "momentum:motion:numParams"))((momentumMotionJointNames, "momentum:motion:jointNames"))((momentumMotionOffsets, "momentum:motion:offsets"))((momentumMarkerName, "momentum:marker:name"))((momentumMarkerOccluded, "momentum:marker:occluded"))((momentumMarkerConfidence, "momentum:marker:confidence"))((momentumMarkersFps, "momentum:markers:fps")))