Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
tracker_utils.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
9
19#include "momentum/math/mesh.h"
21
23#include "momentum/common/log.h"
24
25#include "axel/math/PointTriangleProjectionDefinitions.h"
26
27#include <algorithm>
28#include <queue>
29#include <span>
30#include <unordered_map>
31#include <unordered_set>
32
33using namespace momentum;
34
35namespace momentum {
36
37std::vector<std::vector<PositionData>> createConstraintData(
38 const std::span<const std::vector<Marker>> markerData,
39 const LocatorList& locators) {
40 std::vector<std::vector<PositionData>> results(markerData.size());
41
42 // map locator name to its index
43 std::map<std::string, size_t> locatorLookup;
44 for (size_t i = 0; i < locators.size(); i++) {
45 locatorLookup[locators[i].name] = i;
46 }
47
48 // create a list of position constraints per frame
49 for (size_t iFrame = 0; iFrame < markerData.size(); ++iFrame) {
50 const auto& markerList = markerData[iFrame];
51 for (const auto& jMarker : markerList) {
52 if (jMarker.occluded) {
53 continue;
54 }
55 auto query = locatorLookup.find(jMarker.name);
56 if (query == locatorLookup.end()) {
57 continue;
58 }
59 size_t locatorIdx = query->second;
60
61 results.at(iFrame).emplace_back(PositionData(
62 locators.at(locatorIdx).offset,
63 jMarker.pos.cast<float>(),
64 locators.at(locatorIdx).parent,
65 locators.at(locatorIdx).weight * jMarker.confidence));
66 }
67 }
68
69 return results;
70}
71
72std::vector<std::vector<SkinnedLocatorConstraint>> createSkinnedConstraintData(
73 const std::span<const std::vector<Marker>> markerData,
74 const SkinnedLocatorList& locators) {
75 std::vector<std::vector<SkinnedLocatorConstraint>> results(markerData.size());
76
77 // map locator name to its index
78 std::map<std::string, size_t> locatorLookup;
79 for (size_t i = 0; i < locators.size(); i++) {
80 locatorLookup[locators[i].name] = i;
81 }
82
83 // create a list of position constraints per frame
84 for (size_t iFrame = 0; iFrame < markerData.size(); ++iFrame) {
85 const auto& markerList = markerData[iFrame];
86 for (const auto& jMarker : markerList) {
87 if (jMarker.occluded) {
88 continue;
89 }
90 auto query = locatorLookup.find(jMarker.name);
91 if (query == locatorLookup.end()) {
92 continue;
93 }
94 size_t locatorIdx = query->second;
95
97 locatorIdx >= locators.size(),
98 "Skinned locator index {} exceeds locators size {}",
99 locatorIdx,
100 locators.size());
101 SkinnedLocatorConstraint skinnedConstraint;
102 skinnedConstraint.locatorIndex = gsl::narrow_cast<int>(locatorIdx);
103 skinnedConstraint.targetPosition = jMarker.pos.cast<float>();
104 skinnedConstraint.weight = locators[locatorIdx].weight * jMarker.confidence;
105 results.at(iFrame).push_back(skinnedConstraint);
106 }
107 }
108
109 return results;
110}
111
112std::pair<Eigen::Vector<uint32_t, kMaxSkinJoints>, Eigen::Vector<float, kMaxSkinJoints>>
114 const Character& character,
115 int triangleIndex,
116 const Eigen::Vector3f& barycentric) {
117 Eigen::VectorXf skinWeights = Eigen::VectorXf::Zero(character.skeleton.joints.size());
118
119 const auto& mesh = *character.mesh;
120 const auto& skin = *character.skinWeights;
121
122 // get the triangle
123 const auto& triangle = mesh.faces[triangleIndex];
124 for (int kTriVert = 0; kTriVert < 3; ++kTriVert) {
125 for (int kSkinWeight = 0; kSkinWeight < skin.index.cols(); ++kSkinWeight) {
126 const auto& skinIndex = skin.index(triangle(kTriVert), kSkinWeight);
127 const auto& skinWeight = skin.weight(triangle(kTriVert), kSkinWeight);
128 skinWeights[skinIndex] += skinWeight * barycentric[kTriVert];
129 }
130 }
131
132 std::vector<std::pair<float, uint32_t>> sortedWeights;
133 for (Eigen::Index i = 0; i < skinWeights.size(); ++i) {
134 if (skinWeights[i] > 0.0f) {
135 sortedWeights.emplace_back(skinWeights[i], static_cast<uint32_t>(i));
136 }
137 }
138 std::sort(sortedWeights.begin(), sortedWeights.end(), std::greater<>());
139
140 Eigen::Vector<float, kMaxSkinJoints> resultWeights = Eigen::Vector<float, kMaxSkinJoints>::Zero();
141 Eigen::Vector<uint32_t, kMaxSkinJoints> resultIndices =
142 Eigen::Vector<uint32_t, kMaxSkinJoints>::Zero();
143 for (size_t i = 0; i < kMaxSkinJoints; ++i) {
144 if (i < sortedWeights.size()) {
145 resultWeights[i] = sortedWeights[i].first;
146 resultIndices[i] = sortedWeights[i].second;
147 }
148 }
149
150 resultWeights /= resultWeights.sum();
151
152 return {resultIndices, resultWeights};
153}
154
155namespace {
156
157struct ClosestPointOnMeshResult {
158 bool valid = false;
159 size_t triangleIdx = kInvalidIndex;
160 Eigen::Vector3f baryCoords = Eigen::Vector3f::Zero();
161 Eigen::Vector3f trianglePoint = Eigen::Vector3f::Zero();
162 float distance = std::numeric_limits<float>::max();
163};
164
165} // namespace
166
172bool isRelatedJoint(const momentum::Skeleton& skeleton, uint32_t jointA, uint32_t jointB) {
173 if (jointA == jointB) {
174 return true;
175 }
176 // Check if jointB is the parent of jointA
177 if (jointA < skeleton.joints.size() && skeleton.joints[jointA].parent == jointB) {
178 return true;
179 }
180 // Check if jointA is the parent of jointB
181 if (jointB < skeleton.joints.size() && skeleton.joints[jointB].parent == jointA) {
182 return true;
183 }
184 return false;
185}
186
187ClosestPointOnMeshResult closestPointOnMeshMatchingParent(
188 const momentum::Mesh& mesh,
189 const momentum::SkinWeights& skin,
190 const momentum::Skeleton& skeleton,
191 const Eigen::Vector3f& p_world,
192 uint32_t parentIdx,
193 float cutoffWeight = 0.02) {
194 ClosestPointOnMeshResult result;
195
196 for (size_t iTri = 0; iTri < mesh.faces.size(); ++iTri) {
197 const auto& f = mesh.faces[iTri];
198
199 // Check bounds for face indices (including negative values)
201 f(0) < 0 || f(1) < 0 || f(2) < 0 || f(0) >= static_cast<int>(mesh.vertices.size()) ||
202 f(1) >= static_cast<int>(mesh.vertices.size()) ||
203 f(2) >= static_cast<int>(mesh.vertices.size()),
204 "Face index out of bounds at triangle {}: face indices ({}, {}, {}), mesh vertices size {}",
205 iTri,
206 f(0),
207 f(1),
208 f(2),
209 mesh.vertices.size());
210
211 // Sum skin weights across the joint, its parent, and its children
212 float skinWeight = 0;
213 for (int kTriVert = 0; kTriVert < 3; ++kTriVert) {
214 for (int kSkinWeight = 0; kSkinWeight < skin.index.cols(); ++kSkinWeight) {
215 const uint32_t skinJointIdx = skin.index(f(kTriVert), kSkinWeight);
216 if (isRelatedJoint(skeleton, skinJointIdx, parentIdx)) {
217 skinWeight += skin.weight(f(kTriVert), kSkinWeight);
218 }
219 }
220 }
221 skinWeight /= 3.0f;
222
223 if (skinWeight < cutoffWeight) {
224 continue;
225 }
226
227 // Note: the return value from the does _not_ have anything to do with
228 // whether the projection is valid, it just indicates whether the projection is
229 // inside the triangle or not, so we can ignore it and just use the projected point directly.
230 Eigen::Vector3f p_tri;
231 Eigen::Vector3f bary;
232 axel::projectOnTriangle(
233 p_world, mesh.vertices[f(0)], mesh.vertices[f(1)], mesh.vertices[f(2)], p_tri, &bary);
234 const float dist = (p_tri - p_world).norm();
235 if (!result.valid || dist < result.distance) {
236 result = {true, iTri, bary, p_tri, dist};
237 }
238 }
239
240 return result;
241}
242
244 const momentum::Character& sourceCharacter,
245 float maxDistance,
246 float minSkinWeight,
247 bool verbose,
248 float markerDiameter) {
249 if (!sourceCharacter.mesh || !sourceCharacter.skinWeights) {
251 verbose,
252 "Can't convert locators to skinned locators because mesh or skin weights are missing");
253 return sourceCharacter;
254 }
255
256 const JointParameters restJointParams =
258 const SkeletonState restState(restJointParams, sourceCharacter.skeleton);
259
260 SkinnedLocatorList skinnedLocators;
261 LocatorList locators;
262 for (size_t i = 0; i < sourceCharacter.locators.size(); ++i) {
263 const auto& locator = sourceCharacter.locators[i];
264
265 if (!locator.attachedToSkin) {
267 verbose,
268 "Not converting locator {} to skinned locator because it is not attached to skin",
269 locator.name);
270 locators.push_back(locator);
271 continue;
272 }
273
274 const auto& offset = locator.offset;
275 const auto& parent = locator.parent;
276 const Eigen::Vector3f p_world = restState.jointState[parent].transform * offset;
277
278 // Find the closest point on the mesh to the locator.
279 const auto closestPointResult = closestPointOnMeshMatchingParent(
280 *sourceCharacter.mesh,
281 *sourceCharacter.skinWeights,
282 sourceCharacter.skeleton,
283 p_world,
284 gsl::narrow_cast<uint32_t>(parent),
285 minSkinWeight);
286 if (!closestPointResult.valid) {
288 verbose,
289 "Not converting locator {} to skinned locator because no closest point found matching parent {} ({})",
290 locator.name,
291 sourceCharacter.skeleton.joints.at(parent).name,
292 parent);
293 locators.push_back(locator);
294 continue;
295 }
296
297 if (closestPointResult.distance > maxDistance) {
299 verbose,
300 "Not converting locator {} to skinned locator because distance {} is greater than threshold {}",
301 locator.name,
302 closestPointResult.distance,
303 maxDistance);
304 locators.push_back(locator);
305 continue;
306 }
307
308 SkinnedLocator skinnedLocator;
309 skinnedLocator.name = locator.name;
310 skinnedLocator.position = p_world;
311 skinnedLocator.weight = locator.weight;
312 skinnedLocator.skinOffset = locator.skinOffset + markerDiameter * 0.5f;
313 MT_LOGT("Converting locator {} to skinned locator", locator.name);
314
315 // Set the locator's parent to the closest face.
316 std::tie(skinnedLocator.parents, skinnedLocator.skinWeights) = averageTriangleSkinWeights(
317 sourceCharacter,
318 gsl::narrow_cast<int>(closestPointResult.triangleIdx),
319 closestPointResult.baryCoords);
320 skinnedLocators.push_back(skinnedLocator);
321 }
322
323 // Strip out regular locators and replace with skinned locators:
324 return {
325 sourceCharacter.skeleton,
326 sourceCharacter.parameterTransform,
327 sourceCharacter.parameterLimits,
328 locators,
329 sourceCharacter.mesh.get(),
330 sourceCharacter.skinWeights.get(),
331 sourceCharacter.collision.get(),
332 sourceCharacter.poseShapes.get(),
333 sourceCharacter.blendShape,
334 sourceCharacter.faceExpressionBlendShape,
335 sourceCharacter.name,
336 sourceCharacter.inverseBindPose,
337 skinnedLocators};
338}
339
341 if (sourceCharacter.skinnedLocators.empty()) {
342 MT_LOGI("No skinned locators to convert");
343 return sourceCharacter;
344 }
345
346 const JointParameters restJointParams =
348 const SkeletonState restState(restJointParams, sourceCharacter.skeleton);
349
350 LocatorList locators = sourceCharacter.locators;
351
352 for (const auto& skinnedLocator : sourceCharacter.skinnedLocators) {
353 // Find the bone with the highest skin weight
354 int maxWeightIdx = 0;
355 float maxWeight = skinnedLocator.skinWeights[0];
356
357 for (int i = 1; i < kMaxSkinJoints; ++i) {
358 if (skinnedLocator.skinWeights[i] > maxWeight) {
359 maxWeight = skinnedLocator.skinWeights[i];
360 maxWeightIdx = i;
361 }
362 }
363
364 // Get the parent bone index
365 const uint32_t parentBoneIdx = skinnedLocator.parents[maxWeightIdx];
366
367 // Transform the position from rest pose space to local bone space
368 const Eigen::Vector3f offset =
369 restState.jointState[parentBoneIdx].transform.inverse() * skinnedLocator.position;
370
371 // Create a regular locator
372 Locator locator;
373 locator.name = skinnedLocator.name;
374 locator.parent = parentBoneIdx;
375 locator.offset = offset;
376 locator.weight = skinnedLocator.weight;
377 locator.locked = Vector3i::Zero();
378 locator.limitOrigin = offset;
379 locator.limitWeight = Vector3f::Zero();
380
381 MT_LOGT(
382 "Converting skinned locator {} to regular locator attached to bone {} ({})",
383 skinnedLocator.name,
384 sourceCharacter.skeleton.joints.at(parentBoneIdx).name,
385 parentBoneIdx);
386
387 locators.push_back(locator);
388 }
389
390 // Return character with skinned locators converted to regular locators
391 return {
392 sourceCharacter.skeleton,
393 sourceCharacter.parameterTransform,
394 sourceCharacter.parameterLimits,
395 locators,
396 sourceCharacter.mesh.get(),
397 sourceCharacter.skinWeights.get(),
398 sourceCharacter.collision.get(),
399 sourceCharacter.poseShapes.get(),
400 sourceCharacter.blendShape,
401 sourceCharacter.faceExpressionBlendShape,
402 sourceCharacter.name,
403 sourceCharacter.inverseBindPose,
404 {}};
405}
406
407std::vector<std::vector<size_t>> buildTriangleAdjacency(const Mesh& mesh) {
408 std::vector<std::vector<size_t>> adjacency(mesh.faces.size());
409
410 if (mesh.faces.empty()) {
411 return adjacency;
412 }
413
414 // Build edge-to-triangles map
415 // Edge is represented as pair of sorted vertex indices
416 struct PairHash {
417 size_t operator()(const std::pair<int, int>& p) const {
418 return std::hash<int64_t>{}(
419 (static_cast<int64_t>(p.first) << 32) | static_cast<uint32_t>(p.second));
420 }
421 };
422 std::unordered_map<std::pair<int, int>, std::vector<size_t>, PairHash> edgeToTriangles;
423
424 for (size_t iTri = 0; iTri < mesh.faces.size(); ++iTri) {
425 const Eigen::Vector3i& face = mesh.faces[iTri];
426 for (int i = 0; i < 3; ++i) {
427 int v0 = face(i);
428 int v1 = face((i + 1) % 3);
429 // Sort to create canonical edge representation
430 if (v0 > v1) {
431 std::swap(v0, v1);
432 }
433 edgeToTriangles[{v0, v1}].push_back(iTri);
434 }
435 }
436
437 // Build adjacency from edge-to-triangles map
438 for (const auto& [edge, triangles] : edgeToTriangles) {
439 // For each pair of triangles sharing this edge, mark them as adjacent
440 for (size_t i = 0; i < triangles.size(); ++i) {
441 for (size_t j = i + 1; j < triangles.size(); ++j) {
442 // NOLINTBEGIN(facebook-hte-LocalUncheckedArrayBounds)
443 adjacency[triangles[i]].push_back(triangles[j]);
444 adjacency[triangles[j]].push_back(triangles[i]);
445 // NOLINTEND(facebook-hte-LocalUncheckedArrayBounds)
446 }
447 }
448 }
449
450 // Remove duplicates from adjacency lists
451 for (auto& neighbors : adjacency) {
452 std::sort(neighbors.begin(), neighbors.end());
453 neighbors.erase(std::unique(neighbors.begin(), neighbors.end()), neighbors.end());
454 }
455
456 return adjacency;
457}
458
459std::vector<CandidateTriangle> findCandidateTrianglesDfs(
460 const Mesh& mesh,
461 const SkinWeights& skin,
462 const Skeleton& skeleton,
463 std::span<const std::vector<size_t>> adjacency,
464 size_t startTriangleIdx,
465 const Eigen::Vector3f& initialPoint,
466 const Eigen::Vector3f& referenceNormal,
467 uint32_t parentJointIdx,
468 float maxSearchDistanceCm,
469 float maxNormalAngleDeg) {
470 std::vector<CandidateTriangle> candidates;
471
472 if (startTriangleIdx >= mesh.faces.size()) {
473 return candidates;
474 }
475
476 const float cosMaxAngle = std::cos(maxNormalAngleDeg * pi<float>() / 180.0f);
477 const float cutoffWeight = 0.02f;
478
479 std::unordered_set<size_t> visited;
480 std::queue<size_t> toVisit;
481
482 toVisit.push(startTriangleIdx);
483 visited.insert(startTriangleIdx);
484
485 while (!toVisit.empty()) {
486 size_t triIdx = toVisit.front();
487 toVisit.pop();
488
489 MT_CHECK(triIdx < mesh.faces.size());
490
491 const Eigen::Vector3i& face = mesh.faces[triIdx];
492 const Eigen::Vector3f& v0 = mesh.vertices[face(0)];
493 const Eigen::Vector3f& v1 = mesh.vertices[face(1)];
494 const Eigen::Vector3f& v2 = mesh.vertices[face(2)];
495
496 // Compute centroid
497 const Eigen::Vector3f centroid = (v0 + v1 + v2) / 3.0f;
498
499 // Distance check - if too far, don't add and don't continue DFS from here
500 const float dist = (centroid - initialPoint).norm();
501 if (dist > maxSearchDistanceCm) {
502 continue;
503 }
504
505 // Compute triangle normal
506 Eigen::Vector3f normal = (v1 - v0).cross(v2 - v0);
507 const float normalNorm = normal.norm();
508 if (normalNorm < 1e-8f) {
509 continue; // Degenerate triangle
510 }
511 normal /= normalNorm;
512
513 // Normal angle check
514 if (normal.dot(referenceNormal) < cosMaxAngle) {
515 continue;
516 }
517
518 // Skin weight check - sum skin weights across the joint and related joints
519 float skinWeight = 0;
520 for (int kTriVert = 0; kTriVert < 3; ++kTriVert) {
521 for (int kSkinWeight = 0; kSkinWeight < skin.index.cols(); ++kSkinWeight) {
522 const uint32_t skinJointIdx = skin.index(face(kTriVert), kSkinWeight);
523 if (isRelatedJoint(skeleton, skinJointIdx, parentJointIdx)) {
524 skinWeight += skin.weight(face(kTriVert), kSkinWeight);
525 }
526 }
527 }
528 skinWeight /= 3.0f;
529
530 if (skinWeight < cutoffWeight) {
531 continue;
532 }
533
534 // All checks passed - add to candidates
535 CandidateTriangle candidate;
536 candidate.triangleIdx = triIdx;
537 candidate.vertexIndices = face;
538 candidates.push_back(candidate);
539
540 // Continue DFS to adjacent triangles
541 if (triIdx < adjacency.size()) {
542 for (size_t neighborIdx : adjacency[triIdx]) {
543 if (visited.insert(neighborIdx).second) {
544 toVisit.push(neighborIdx);
545 }
546 }
547 }
548 }
549
550 return candidates;
551}
552
553std::vector<momentum::SkinnedLocatorTriangleConstraintT<float>> createSkinnedLocatorMeshConstraints(
554 const momentum::Character& character,
555 float cutoffWeight,
556 float maxSearchDistanceCm,
557 float maxNormalAngleDeg) {
558 if (!character.mesh || !character.skinWeights) {
559 return {};
560 }
561
562 // skip the triangle tree if we don't need it:
563 if (character.skinnedLocators.empty()) {
564 return {};
565 }
566
567 const Mesh& mesh = *character.mesh;
568
569 // Build triangle adjacency if we need to find candidate triangles
570 std::vector<std::vector<size_t>> adjacency;
571 if (maxSearchDistanceCm > 0.0f) {
572 adjacency = buildTriangleAdjacency(mesh);
573 }
574
575 std::vector<momentum::SkinnedLocatorTriangleConstraintT<float>> result;
576 result.reserve(character.skinnedLocators.size());
577 for (size_t i = 0; i < character.skinnedLocators.size(); ++i) {
578 const auto& locator = character.skinnedLocators[i];
579 const Eigen::Vector3f p_world = locator.position;
580
581 // Find the closest point on the mesh to the locator.
582 const auto closestPointResult = closestPointOnMeshMatchingParent(
583 *character.mesh,
584 *character.skinWeights,
585 character.skeleton,
586 p_world,
587 locator.parents[0],
588 cutoffWeight);
589 if (!closestPointResult.valid) {
590 MT_LOGW(
591 "Skinned locator '{}': no valid mesh triangle found (parent={})",
592 locator.name,
593 locator.parents[0]);
594 continue;
595 }
596
598 constr.locatorIndex = gsl::narrow_cast<int>(i);
599 constr.tgtTriangleIndices = mesh.faces[closestPointResult.triangleIdx];
600 constr.tgtTriangleBaryCoords = closestPointResult.baryCoords;
601 constr.depth = locator.skinOffset;
602
603 // Populate candidate triangles if sliding is enabled
604 if (maxSearchDistanceCm > 0.0f) {
605 // Compute reference normal from the initial triangle
606 const Eigen::Vector3f& v0 = mesh.vertices[constr.tgtTriangleIndices[0]];
607 const Eigen::Vector3f& v1 = mesh.vertices[constr.tgtTriangleIndices[1]];
608 const Eigen::Vector3f& v2 = mesh.vertices[constr.tgtTriangleIndices[2]];
609 Eigen::Vector3f referenceNormal = (v1 - v0).cross(v2 - v0);
610 const float normalNorm = referenceNormal.norm();
611 if (normalNorm > 1e-8f) {
612 referenceNormal /= normalNorm;
613 } else {
614 referenceNormal = Eigen::Vector3f::UnitZ();
615 }
616
618 mesh,
619 *character.skinWeights,
620 character.skeleton,
621 adjacency,
622 closestPointResult.triangleIdx,
623 p_world,
624 referenceNormal,
625 locator.parents[0],
626 maxSearchDistanceCm,
627 maxNormalAngleDeg);
628 }
629
630 result.push_back(constr);
631 }
632
633 return result;
634}
635
636Character createLocatorCharacter(const Character& sourceCharacter, const std::string& prefix) {
637 // create a copy
638 Character character = sourceCharacter;
639
640 auto& newSkel = character.skeleton;
641 auto& newTransform = character.parameterTransform;
642 auto& newLocators = character.locators;
643 auto& newLimits = character.parameterLimits;
644 auto& newInvBindPose = character.inverseBindPose;
645
646 ParameterSet locatorSet;
647
648 // create a new additional joint for each locator
649 std::vector<Eigen::Triplet<float>> triplets;
650 for (auto& newLocator : newLocators) {
651 // ignore locator if it is fixed
652 if (newLocator.locked.all()) {
653 continue;
654 }
655
656 // create a new joint for the locator
657 Joint joint;
658 joint.name = std::string(prefix + newLocator.name);
659 joint.parent = newLocator.parent;
660 joint.translationOffset = newLocator.offset;
661
662 // insert joint
663 const size_t id = newSkel.joints.size();
664 newSkel.joints.push_back(joint);
665 newInvBindPose.push_back(Affine3f::Identity());
666
667 // create parameter for the added joint
668 static const std::array<std::string, 3> tNames{"_tx", "_ty", "_tz"};
669 for (size_t j = 0; j < 3; j++) {
670 if (newLocator.locked[j] != 0) {
671 continue;
672 }
673 const std::string jname = joint.name + tNames[j];
674 triplets.emplace_back(
675 static_cast<int>(id * kParametersPerJoint + j),
676 static_cast<int>(newTransform.name.size()),
677 1.0f);
678 MT_CHECK(
679 newTransform.name.size() < kMaxModelParams,
680 "Number of model parameters reached the {} limit.",
682 locatorSet.set(newTransform.name.size());
683 newTransform.name.push_back(jname);
684
685 // check if we need joint limit
686 if (newLocator.limitWeight[j] > 0.0f) {
688 p.type = MinMaxJoint;
691 const float referencePosition = newLocator.limitOrigin[j] - newLocator.offset[j];
692 p.data.minMaxJoint.limits = Vector2f(referencePosition, referencePosition);
693 p.weight = newLocator.limitWeight[j];
694 newLimits.push_back(p);
695 }
696 }
697 newTransform.offsets.conservativeResize(newTransform.offsets.size() + kParametersPerJoint);
698 newTransform.activeJointParams.conservativeResize(
699 newTransform.activeJointParams.size() + kParametersPerJoint);
700 for (size_t j = newTransform.offsets.size() - gsl::narrow<int>(kParametersPerJoint);
701 j < newTransform.offsets.size();
702 ++j) {
703 newTransform.offsets(j) = 0.0;
704 }
705
706 for (size_t j = newTransform.activeJointParams.size() - gsl::narrow<int>(kParametersPerJoint);
707 j < newTransform.activeJointParams.size();
708 ++j) {
709 newTransform.activeJointParams(j) = true;
710 }
711
712 // reattach locator to new joint
713 newLocator.parent = id;
714 newLocator.offset.setZero();
715 }
716 newTransform.parameterSets["locators"] = locatorSet;
717
718 // update parameter transform
719 const int newRows = static_cast<int>(newSkel.joints.size()) * kParametersPerJoint;
720 const int newCols = static_cast<int>(newTransform.name.size());
721 newTransform.transform.conservativeResize(newRows, newCols);
722 SparseRowMatrixf additionalTransforms(newRows, newCols);
723 additionalTransforms.setFromTriplets(triplets.begin(), triplets.end());
724 newTransform.transform += additionalTransforms;
725
726 // return the new character
727 return character;
728}
729
731 const Character& locatorCharacter,
732 const CharacterParameters& calibParams) {
733 const SkeletonState state(
734 locatorCharacter.parameterTransform.apply(calibParams), locatorCharacter.skeleton);
735 const LocatorList& locators = locatorCharacter.locators;
736 const auto& skeleton = locatorCharacter.skeleton;
737
738 LocatorList result = locators;
739
740 // Check if locators is empty
741 if (locators.empty()) {
742 return result;
743 }
744
745 // revert each locator to the original attachment and add an offset
746 for (size_t i = 0; i < locators.size(); i++) {
747 // only map locators back that are not fixed
748 if (locators[i].locked.all()) {
749 continue;
750 }
751
752 // joint id
753 const size_t jointId = locators[i].parent;
754
755 // Check bounds for jointState access
757 jointId >= state.jointState.size(),
758 "Joint ID {} is out of bounds for jointState (size: {})",
759 jointId,
760 state.jointState.size());
761
762 // get global locator position
763 const Vector3f pos = state.jointState[jointId].transform * locators[i].offset;
764
765 // change attachment to original joint
766 result[i].parent = skeleton.joints[jointId].parent;
767
768 // Check bounds for parent joint access
770 result[i].parent >= state.jointState.size(),
771 "Parent joint ID {} is out of bounds for jointState (size: {})",
772 result[i].parent,
773 state.jointState.size());
774
775 // calculate new offset
776 const Vector3f offset = state.jointState[result[i].parent].transform.inverse() * pos;
777
778 // change offset to current state
779 result[i].offset = offset;
780 }
781
782 // return
783 return result;
784}
785
787 const Character& locatorCharacter,
788 const CharacterParameters& calibParams) {
789 const SkeletonState state(
790 locatorCharacter.parameterTransform.apply(calibParams), locatorCharacter.skeleton);
791 const SkinnedLocatorList& skinnedLocators = locatorCharacter.skinnedLocators;
792 const auto& pt = locatorCharacter.parameterTransform;
793
794 SkinnedLocatorList result = skinnedLocators;
795
796 for (size_t i = 0; i < skinnedLocators.size(); i++) {
797 if (i < pt.skinnedLocatorParameters.size()) {
798 auto paramIdx = pt.skinnedLocatorParameters[i];
799 for (int k = 0; k < 3; ++k) {
800 result.at(i).position(k) += calibParams.pose[paramIdx + k];
801 }
802 }
803 }
804 // return
805
806 return result;
807}
808
810 ModelParameters newParams = params;
811 for (size_t iParam = 0; iParam < newParams.size(); ++iParam) {
812 // TODO: check index out of bound
813 if (!parameterSet[iParam]) {
814 newParams[iParam] = 0.0;
815 }
816 }
817 return newParams;
818}
819
820std::tuple<Eigen::VectorXf, LocatorList, SkinnedLocatorList> extractIdAndLocatorsFromParams(
821 const ModelParameters& param,
822 const Character& sourceCharacter,
823 const Character& targetCharacter) {
824 ModelParameters idParam =
826 CharacterParameters fullParams;
827 fullParams.pose = param;
828 LocatorList locators = extractLocatorsFromCharacter(sourceCharacter, fullParams);
829 SkinnedLocatorList skinnedLocators =
830 extractSkinnedLocatorsFromCharacter(sourceCharacter, fullParams);
831
832 return {
833 idParam.v.head(targetCharacter.parameterTransform.numAllModelParameters()),
834 locators,
835 skinnedLocators};
836}
837
839 const momentum::ModelParameters& param,
840 const momentum::Character& sourceCharacter) {
841 MT_CHECK(param.size() == sourceCharacter.parameterTransform.numAllModelParameters());
842 Mesh result = *sourceCharacter.mesh;
843 auto blendWeights = extractBlendWeights(sourceCharacter.parameterTransform, param);
844 result.vertices = sourceCharacter.blendShape->computeShape<float>(blendWeights);
845 return result;
846}
847
849 const ParameterSet& idSet,
850 const ModelParameters& identity,
851 Eigen::MatrixXf& motionNoId) {
852 MT_CHECK(identity.v.size() == motionNoId.rows());
853
854 const size_t numParams = motionNoId.rows();
855 const size_t numFrames = motionNoId.cols();
856
857 for (size_t iParam = 0; iParam < numParams; ++iParam) {
858 if (!idSet.test(iParam)) {
859 continue;
860 }
861 for (size_t jFrame = 0; jFrame < numFrames; ++jFrame) {
862 motionNoId(iParam, jFrame) += identity.v(iParam);
863 }
864 }
865}
866
868 const ParameterSet& idSet,
869 const ModelParameters& identity,
870 Eigen::MatrixXf& motionWithId) {
871 const size_t numParams = motionWithId.rows();
872 const size_t numFrames = motionWithId.cols();
873
874 for (size_t iParam = 0; iParam < numParams; ++iParam) {
875 if (!idSet.test(iParam)) {
876 continue;
877 }
878 for (size_t jFrame = 0; jFrame < numFrames; ++jFrame) {
879 motionWithId(iParam, jFrame) -= identity.v(iParam);
880 }
881 }
882}
883
885 const Character& c,
886 const ParameterSet& idSet,
887 const JointParameters& jointIdentity) {
888 // convert from joint to model parameters using only the parameters active in idSet
889 auto scalingTransform = c.parameterTransform.simplify(idSet);
890 momentum::ModelParameters scaleParameters =
891 InverseParameterTransform(scalingTransform).apply(jointIdentity).pose;
894 size_t iScale = 0;
895 for (size_t iParam = 0; iParam < c.parameterTransform.numAllModelParameters(); iParam++) {
896 if (idSet.test(iParam)) {
897 identity[iParam] = scaleParameters[iScale];
898 ++iScale;
899 }
900 }
901
902 return identity;
903}
904
905std::vector<std::vector<Marker>> extractMarkersFromMotion(
906 const Character& character,
907 const Eigen::MatrixXf& motion) {
908 const size_t nFrames = motion.cols();
909 std::vector<std::vector<Marker>> result(nFrames);
910 for (size_t iFrame = 0; iFrame < nFrames; ++iFrame) {
911 const JointParameters params(motion.col(iFrame));
912 const auto& states = SkeletonState(params, character.skeleton).jointState;
913
914 std::vector<Marker>& markers = result.at(iFrame);
915 for (const auto& loc : character.locators) {
916 const Vector3d pos = (states.at(loc.parent).transform * loc.offset).cast<double>();
917 markers.emplace_back(Marker{loc.name, pos, false});
918 }
919 }
920
921 return result;
922}
923
924std::vector<std::pair<std::string, float>> computeSkinnedLocatorMeshDistances(
925 const Character& character) {
926 std::vector<std::pair<std::string, float>> result;
927 if (!character.mesh || !character.skinWeights || character.skinnedLocators.empty()) {
928 return result;
929 }
930
931 const Mesh& mesh = *character.mesh;
932 const SkinWeights& skin = *character.skinWeights;
933 result.reserve(character.skinnedLocators.size());
934
935 for (const auto& locator : character.skinnedLocators) {
936 const auto closest = closestPointOnMeshMatchingParent(
937 mesh, skin, character.skeleton, locator.position, locator.parents[0]);
938 result.emplace_back(locator.name, closest.valid ? closest.distance : -1.0f);
939 }
940
941 return result;
942}
943
944std::vector<std::vector<PlaneDataT<float>>> computeFloorContactConstraints(
945 const Character& character,
946 const MatrixXf& motion,
947 const std::vector<PlaneDataT<float>>& floorConstraints,
948 const std::vector<size_t>& frameIndices,
949 float percentile) {
950 const size_t nFrames = frameIndices.size();
951 std::vector<std::vector<PlaneDataT<float>>> result(nFrames);
952 if (floorConstraints.empty() || nFrames == 0) {
953 return result;
954 }
955
956 const auto& pt = character.parameterTransform;
957 const size_t nParams = pt.numAllModelParameters();
958 const size_t nLocators = floorConstraints.size();
959
960 // heights[locator][frame] = signed distance to floor plane
961 std::vector<std::vector<float>> heights(nLocators, std::vector<float>(nFrames));
962 for (size_t fi = 0; fi < nFrames; ++fi) {
963 const size_t iFrame = frameIndices[fi];
964 SkeletonState skelState;
965 skelState.set(
966 pt.apply(ModelParameters(motion.col(iFrame).head(nParams))), character.skeleton, false);
967 for (size_t li = 0; li < nLocators; ++li) {
968 const auto& constr = floorConstraints[li];
969 const auto worldPos = skelState.jointState[constr.parent].transform * constr.offset;
970 heights[li][fi] = worldPos.dot(constr.normal) - constr.d;
971 }
972 }
973
974 // For each locator independently, find the percentile threshold and mark
975 // frames where that locator is in contact
976 size_t totalContactPairs = 0;
977 for (size_t li = 0; li < nLocators; ++li) {
978 auto sorted = heights[li];
979 std::sort(sorted.begin(), sorted.end());
980 const size_t pIdx = std::min(static_cast<size_t>(percentile * nFrames), nFrames - 1);
981 const float threshold = sorted[pIdx];
982 for (size_t fi = 0; fi < nFrames; ++fi) {
983 if (heights[li][fi] <= threshold) {
984 result[fi].push_back(floorConstraints[li]);
985 ++totalContactPairs;
986 }
987 }
988 }
989
990 const size_t framesWithContact =
991 std::count_if(result.begin(), result.end(), [](const auto& v) { return !v.empty(); });
992 MT_LOGI(
993 "Floor contact: {}/{} frames have contact ({} locator-frame pairs, {} locators, percentile={})",
994 framesWithContact,
995 nFrames,
996 totalContactPairs,
997 nLocators,
998 percentile);
999
1000 return result;
1001}
1002
1003} // namespace momentum
This file provides functions for applying blend shape deformations and skeletal transformations to ch...
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
#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_LOGI(...)
Definition log.h:179
#define MT_LOGW(...)
Definition log.h:180
#define MT_LOGT(...)
Definition log.h:177
#define MT_LOGI_IF(condition,...)
Definition log.h:185
Vector2< float > Vector2f
Definition types.h:250
T normal(const T &mean, const T &sigma)
Normally distributed value via the global Random singleton.
Definition random-inl.h:382
Vector3< double > Vector3d
Definition types.h:261
SkeletonT< float > Skeleton
Definition fwd.h:263
bool isRelatedJoint(const momentum::Skeleton &skeleton, uint32_t jointA, uint32_t jointB)
Check if two joints are related (same joint, parent-child, or child-parent relationship).
LocatorList extractLocatorsFromCharacter(const Character &locatorCharacter, const CharacterParameters &calibParams)
constexpr size_t kMaxModelParams
Maximum number of model parameters supported per frame across any character.
Definition types.h:427
std::vector< CandidateTriangle > findCandidateTrianglesDfs(const Mesh &mesh, const SkinWeights &skin, const Skeleton &skeleton, std::span< const std::vector< size_t > > adjacency, size_t startTriangleIdx, const Eigen::Vector3f &initialPoint, const Eigen::Vector3f &referenceNormal, uint32_t parentJointIdx, float maxSearchDistanceCm, float maxNormalAngleDeg)
Find candidate triangles by walking along the mesh surface using DFS.
Mesh extractBlendShapeFromParams(const momentum::ModelParameters &param, const momentum::Character &sourceCharacter)
std::tuple< Eigen::VectorXf, LocatorList, SkinnedLocatorList > extractIdAndLocatorsFromParams(const ModelParameters &param, const Character &sourceCharacter, const Character &targetCharacter)
momentum::Character locatorsToSkinnedLocators(const momentum::Character &sourceCharacter, float maxDistance, float minSkinWeight, bool verbose, float markerDiameter)
Convert locators to skinned locators by finding the closest point on the mesh surface that matches th...
MeshT< float > Mesh
Definition fwd.h:20
SkinnedLocatorConstraintT< float > SkinnedLocatorConstraint
Definition fwd.h:307
SkinnedLocatorList extractSkinnedLocatorsFromCharacter(const Character &locatorCharacter, const CharacterParameters &calibParams)
std::vector< std::vector< size_t > > buildTriangleAdjacency(const Mesh &mesh)
Build triangle adjacency: for each triangle, find triangles that share an edge.
std::vector< std::vector< SkinnedLocatorConstraint > > createSkinnedConstraintData(const std::span< const std::vector< Marker > > markerData, const SkinnedLocatorList &locators)
std::vector< std::pair< std::string, float > > computeSkinnedLocatorMeshDistances(const Character &character)
Compute the distance from each skinned locator to the closest point on the mesh surface.
void fillIdentity(const ParameterSet &idSet, const ModelParameters &identity, Eigen::MatrixXf &motionNoId)
Character createLocatorCharacter(const Character &sourceCharacter, const std::string &prefix)
void removeIdentity(const ParameterSet &idSet, const ModelParameters &identity, Eigen::MatrixXf &motionWithId)
SkeletonStateT< float > SkeletonState
Definition fwd.h:282
std::vector< momentum::SkinnedLocatorTriangleConstraintT< float > > createSkinnedLocatorMeshConstraints(const momentum::Character &character, float cutoffWeight, float maxSearchDistanceCm, float maxNormalAngleDeg)
std::vector< SkinnedLocator > SkinnedLocatorList
A collection of locators attached to a skeleton.
JointParametersT< float > JointParameters
Definition types.h:135
ModelParameters jointIdentityToModelIdentity(const Character &c, const ParameterSet &idSet, const JointParameters &jointIdentity)
InverseParameterTransformT< float > InverseParameterTransform
PositionDataT< float > PositionData
Definition fwd.h:269
momentum::Character skinnedLocatorsToLocators(const momentum::Character &sourceCharacter)
Convert skinned locators to regular locators by selecting the bone with the highest skin weight.
CharacterParametersT< float > CharacterParameters
Definition types.h:168
std::vector< std::vector< PositionData > > createConstraintData(const std::span< const std::vector< Marker > > markerData, const LocatorList &locators)
constexpr size_t kParametersPerJoint
Definition types.h:21
ModelParameters extractParameters(const ModelParameters &params, const ParameterSet &parameterSet)
ClosestPointOnMeshResult closestPointOnMeshMatchingParent(const momentum::Mesh &mesh, const momentum::SkinWeights &skin, const momentum::Skeleton &skeleton, const Eigen::Vector3f &p_world, uint32_t parentIdx, float cutoffWeight=0.02)
JointT< float > Joint
Definition fwd.h:206
Vector3P< S > cross(const Eigen::MatrixBase< Derived > &v1, const Vector3P< S > &v2)
Computes cross product of Eigen::Vector3f and Vector3P.
Definition simd.h:309
ModelParametersT< float > ModelParameters
Definition types.h:105
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
Vector3< float > Vector3f
Definition types.h:251
std::vector< std::vector< PlaneDataT< float > > > computeFloorContactConstraints(const Character &character, const MatrixXf &motion, const std::vector< PlaneDataT< float > > &floorConstraints, const std::vector< size_t > &frameIndices, float percentile)
constexpr T pi() noexcept
Returns the mathematical constant pi.
Definition constants.h:50
constexpr uint32_t kMaxSkinJoints
Maximum number of joints that can influence a single vertex.
std::bitset< kMaxModelParams > ParameterSet
Bitset for model parameter enablement.
Definition types.h:430
BlendWeightsT< T > extractBlendWeights(const ParameterTransform &paramTransform, const ModelParametersT< T > &modelParams)
Extracts blend shape weights from model parameters.
SparseRowMatrix< float > SparseRowMatrixf
Definition types.h:193
std::vector< std::vector< Marker > > extractMarkersFromMotion(const Character &character, const Eigen::MatrixXf &motion)
MatrixX< float > MatrixXf
Definition types.h:82
std::pair< Eigen::Vector< uint32_t, kMaxSkinJoints >, Eigen::Vector< float, kMaxSkinJoints > > averageTriangleSkinWeights(const Character &character, int triangleIndex, const Eigen::Vector3f &barycentric)
std::vector< Locator > LocatorList
A collection of locators attached to a skeleton.
Definition locator.h:79
Represents a candidate triangle for sliding constraints.
Eigen::Vector3i vertexIndices
The 3 vertex indices (cached from mesh.faces).
ModelParametersT< T > pose
The model parameter vector representing the pose of the character.
Definition types.h:161
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
TransformationList inverseBindPose
Inverse of the bind pose transformations for each joint.
Definition character.h:76
LocatorList locators
Points of interest attached to joints.
Definition character.h:49
SkinWeights_u skinWeights
Defines how mesh vertices are influenced by joints.
Definition character.h:58
BlendShapeBase_const_p faceExpressionBlendShape
Facial expression blend shapes.
Definition character.h:73
ParameterLimits parameterLimits
Constraints on model parameters.
Definition character.h:46
Mesh_u mesh
3D mesh representing the character's surface
Definition character.h:55
PoseShape_u poseShapes
Pose-dependent shape corrections.
Definition character.h:61
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
Definition character.h:36
std::string name
Character identifier.
Definition character.h:82
SkinnedLocatorList skinnedLocators
Points of interest attached to joints, with skinning weights.
Definition character.h:52
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
Definition character.h:39
BlendShape_const_p blendShape
Shape variations that can be blended.
Definition character.h:70
CollisionGeometry_u collision
Collision volumes for the character.
Definition character.h:64
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE auto size() const
Definition types.h:87
static EIGEN_DEVICE_FUNC Derived< Scalar > Zero(::Eigen::Index size)
Definition types.h:92
CharacterParametersT< T > apply(const JointParametersT< T > &parameters) const
Map joint parameters to model parameters.
size_t parent
Index of the parent joint in the skeleton hierarchy, or kInvalidIndex for the root.
Definition joint.h:24
Vector3< T > translationOffset
Constant translation offset from the parent joint's origin to this joint's origin,...
Definition joint.h:36
std::string name
Definition joint.h:21
size_t jointParameter
One of [tx, ty, tz, rx, ry, rz, sc].
Represents a point attached to a joint in a skeleton.
Definition locator.h:19
float weight
Influence weight when used as a constraint in error functions.
Definition locator.h:32
size_t parent
Index of the parent joint in the skeleton.
Definition locator.h:23
std::string name
Definition locator.h:20
Vector3f limitWeight
Per-axis strength pulling the locator back toward limitOrigin.
Definition locator.h:39
Vector3i locked
Per-axis lock flags (x, y, z): 1 = locked, 0 = free.
Definition locator.h:29
Vector3f offset
Position in the parent joint's local coordinate frame.
Definition locator.h:26
Vector3f limitOrigin
Reference position for limit constraints; typically equals offset when loaded.
Definition locator.h:35
A single motion capture marker observation (position, occlusion, confidence).
Definition marker.h:18
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
Definition mesh.h:22
std::vector< Eigen::Vector3i > faces
List of triangular faces defined by vertex indices.
Definition mesh.h:28
ParameterSet getScalingParameters() const
Get a list of scaling parameters (with prefix "scale_").
JointParametersT< T > apply(const ModelParametersT< T > &parameters) const
Map model parameters to joint parameters using a linear transformation.
Eigen::Index numJointParameters() const
Dimension of the output jointParameters vector.
Eigen::Index numAllModelParameters() const
Dimension of all model parameters, including pose, scaling, marker joints, and blendshape parameters ...
ParameterTransformT< T > simplify(const ParameterSet &enabledParameters) const
Create a simplified transform given the enabled parameters.
Point-on-plane or Point-in-half-plane constraint data.
void set(const JointParametersT< T > &jointParameters, const Skeleton &referenceSkeleton, bool computeDeriv=true)
Updates the skeleton state with new joint parameters.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
Definition skeleton.h:25
Linear blend skinning weights for a character mesh: per-vertex joint indices and influence weights.
WeightMatrix weight
Joint influence weights per vertex.
IndexMatrix index
Joint indices influencing each vertex.
Eigen::Vector3< T > tgtTriangleBaryCoords
Initial barycentric coordinates.
std::vector< CandidateTriangle > candidateTriangles
List of candidate triangles for sliding.
Eigen::Vector3i tgtTriangleIndices
Initial/reference triangle vertex indices.
A locator attached to multiple joints, with its runtime position determined by blending the skinning ...
Eigen::Matrix< uint32_t, kMaxSkinJoints, 1 > parents
Indices of the parent joints used for skinning.
Eigen::Matrix< float, kMaxSkinJoints, 1 > skinWeights
Skinning weight for each entry in parents. Typically sums to 1.0.
float weight
Influence weight when used as a constraint in error functions.
Vector3f position
Position in the character's rest-pose coordinate frame.
float skinOffset
Offset from the skin surface in centimeters, used when solving for body shape.
LimitMinMaxJoint minMaxJoint