Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
glove_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/common/log.h"
21
22#include <Eigen/Core>
23#include <Eigen/Geometry>
24
25#include <string>
26#include <unordered_map>
27#include <vector>
28
29namespace momentum {
30
32 Character character,
33 const GloveConfig& cfg,
34 const std::array<GloveOffset, 2>& offsets,
35 const std::string& prefix) {
36 MT_THROW_IF(prefix.empty(), "addGloveBones: prefix must not be empty.");
37 auto& newSkel = character.skeleton;
38 auto& newTransform = character.parameterTransform;
39 auto& newInvBindPose = character.inverseBindPose;
40
41 for (size_t hand = 0; hand < 2; ++hand) {
42 const auto& wristName = cfg.wristJointNames[hand];
44 wristName.empty(), "addGloveBones: wrist joint name for hand {} must not be empty.", hand);
45
46 const size_t wristIdx = newSkel.getJointIdByName(wristName);
47 if (wristIdx == kInvalidIndex) {
48 MT_LOGW("addGloveBones: wrist joint '{}' not found, skipping", wristName);
49 continue;
50 }
51
52 // Skip if glove bone already exists
53 const std::string gloveBoneName = prefix + wristName;
54 if (newSkel.getJointIdByName(gloveBoneName) != kInvalidIndex) {
55 continue;
56 }
57
58 // Create a new joint as child of the wrist
59 Joint joint;
60 joint.name = gloveBoneName;
61 joint.parent = wristIdx;
62 joint.translationOffset = offsets[hand].translation;
64 offsets[hand].rotationEulerXYZ.cast<float>(), 0, 1, 2, EulerConvention::Intrinsic);
65
66 newSkel.joints.push_back(joint);
67 newInvBindPose.push_back(Affine3f::Identity());
68
69 // Resize offsets and activeJointParams for the new joint
70 newTransform.offsets.conservativeResize(newTransform.offsets.size() + kParametersPerJoint);
71 newTransform.activeJointParams.conservativeResize(
72 newTransform.activeJointParams.size() + kParametersPerJoint);
73 for (size_t j = newTransform.offsets.size() - kParametersPerJoint;
74 j < static_cast<size_t>(newTransform.offsets.size());
75 ++j) {
76 newTransform.offsets(j) = 0.0f;
77 }
78 for (size_t j = newTransform.activeJointParams.size() - kParametersPerJoint;
79 j < static_cast<size_t>(newTransform.activeJointParams.size());
80 ++j) {
81 newTransform.activeJointParams(j) = true;
82 }
83
84 // Resize the transform matrix rows for the new joint (no new columns)
85 const int newRows = static_cast<int>(newSkel.joints.size() * kParametersPerJoint);
86 const int curCols = static_cast<int>(newTransform.name.size());
87 newTransform.transform.conservativeResize(newRows, curCols);
88 }
89
90 return character;
91}
92
94 Character character,
95 const GloveConfig& cfg,
96 const std::string& prefix) {
97 MT_THROW_IF(prefix.empty(), "addGloveCalibrationParameters: prefix must not be empty.");
98 auto& newSkel = character.skeleton;
99 auto& newTransform = character.parameterTransform;
100
101 ParameterSet gloveSet;
102 std::vector<Eigen::Triplet<float>> triplets;
103
104 // Parameter name suffixes for translation and rotation DOFs
105 static const std::array<std::string, 6> dofNames{"_tx", "_ty", "_tz", "_rx", "_ry", "_rz"};
106 // Corresponding joint parameter indices: TX=0, TY=1, TZ=2, RX=3, RY=4, RZ=5
107 static const std::array<size_t, 6> dofIndices{TX, TY, TZ, RX, RY, RZ};
108
109 for (size_t hand = 0; hand < 2; ++hand) {
111 cfg.wristJointNames[hand].empty(),
112 "addGloveCalibrationParameters: wrist joint name for hand {} must not be empty.",
113 hand);
114 const std::string gloveBoneName = prefix + cfg.wristJointNames[hand];
115 const size_t jointIdx = newSkel.getJointIdByName(gloveBoneName);
116 if (jointIdx == kInvalidIndex) {
117 MT_LOGW("addGloveCalibrationParameters: glove bone '{}' not found, skipping", gloveBoneName);
118 continue;
119 }
120
121 // Add 6 DOF parameters (TX, TY, TZ, RX, RY, RZ) for this glove bone
122 for (size_t d = 0; d < 6; ++d) {
123 const std::string paramName = gloveBoneName + dofNames[d];
124 const int row = static_cast<int>(jointIdx * kParametersPerJoint + dofIndices[d]);
125 const auto col = static_cast<int>(newTransform.name.size());
126
127 triplets.emplace_back(row, col, 1.0f);
128
129 MT_CHECK(
130 newTransform.name.size() < kMaxModelParams,
131 "Number of model parameters reached the {} limit.",
133 gloveSet.set(newTransform.name.size());
134 newTransform.name.push_back(paramName);
135 }
136 }
137
138 newTransform.parameterSets["gloves"] = gloveSet;
139
140 // Update the parameter transform matrix
141 const int newRows = static_cast<int>(newSkel.joints.size() * kParametersPerJoint);
142 const int newCols = static_cast<int>(newTransform.name.size());
143 newTransform.transform.conservativeResize(newRows, newCols);
144 SparseRowMatrixf additionalTransforms(newRows, newCols);
145 additionalTransforms.setFromTriplets(triplets.begin(), triplets.end());
146 newTransform.transform += additionalTransforms;
147
148 return character;
149}
150
151Character
152createGloveCharacter(const Character& src, const GloveConfig& cfg, const std::string& prefix) {
153 return addGloveCalibrationParameters(addGloveBones(src, cfg, {}, prefix), cfg, prefix);
154}
155
156std::array<GloveOffset, 2> extractGloveOffsetsFromCharacter(
157 const Character& gloveChar,
158 const CharacterParameters& params,
159 const GloveConfig& cfg) {
160 std::array<GloveOffset, 2> result;
161
162 // Apply parameter transform to get joint parameters
163 const JointParameters jointParams = gloveChar.parameterTransform.apply(params);
164
165 for (size_t hand = 0; hand < 2; ++hand) {
166 const std::string gloveBoneName = "glove_" + cfg.wristJointNames[hand];
167 const size_t jointIdx = gloveChar.skeleton.getJointIdByName(gloveBoneName);
168 if (jointIdx == kInvalidIndex) {
169 continue;
170 }
171
172 const size_t base = jointIdx * kParametersPerJoint;
173 result[hand].translation =
174 Vector3f(jointParams.v(base + TX), jointParams.v(base + TY), jointParams.v(base + TZ));
175 result[hand].rotationEulerXYZ =
176 Vector3f(jointParams.v(base + RX), jointParams.v(base + RY), jointParams.v(base + RZ));
177 }
178
179 return result;
180}
181
183 Character& character,
184 const ModelParameters& solvedParams,
185 const Character& solvingCharacter,
186 const std::optional<GloveConfig>& cfg) {
187 if (!cfg) {
188 return;
189 }
190 // Extract offsets from the solving character's calibration parameters
191 CharacterParameters params;
192 params.pose = solvedParams;
193 params.offsets =
194 JointParameters::Zero(solvingCharacter.skeleton.joints.size() * kParametersPerJoint);
195 const auto offsets = extractGloveOffsetsFromCharacter(solvingCharacter, params, *cfg);
196
197 for (size_t hand = 0; hand < 2; ++hand) {
198 MT_LOGI(
199 "Baking glove offset for '{}': translation=({:.4f}, {:.4f}, {:.4f}), "
200 "rotation_xyz=({:.4f}, {:.4f}, {:.4f})",
201 cfg->wristJointNames[hand],
202 offsets[hand].translation.x(),
203 offsets[hand].translation.y(),
204 offsets[hand].translation.z(),
205 offsets[hand].rotationEulerXYZ.x(),
206 offsets[hand].rotationEulerXYZ.y(),
207 offsets[hand].rotationEulerXYZ.z());
208 }
209
210 // Add glove bones with the solved offsets baked into the joint
211 character = addGloveBones(character, *cfg, offsets);
212}
213
214std::vector<std::vector<JointToJointPositionDataT<float>>> createGlovePositionConstraintData(
215 std::span<const GloveFrameData> gloveData,
216 const Character& character,
217 const GloveConfig& cfg,
218 size_t handIndex) {
219 if (gloveData.empty() || handIndex >= 2) {
220 return {};
221 }
222
223 std::vector<std::vector<JointToJointPositionDataT<float>>> results(gloveData.size());
224
225 // Find the glove bone for this hand; fall back to the wrist joint itself
226 const std::string gloveBoneName = "glove_" + cfg.wristJointNames[handIndex];
227 size_t referenceIdx = character.skeleton.getJointIdByName(gloveBoneName);
228 if (referenceIdx == kInvalidIndex) {
229 referenceIdx = character.skeleton.getJointIdByName(cfg.wristJointNames[handIndex]);
230 if (referenceIdx == kInvalidIndex) {
231 return results;
232 }
233 }
234
235 // Build name-to-index map for the skeleton
236 std::unordered_map<std::string, size_t> jointLookup;
237 jointLookup.reserve(character.skeleton.joints.size());
238 for (size_t i = 0; i < character.skeleton.joints.size(); ++i) {
239 jointLookup[character.skeleton.joints[i].name] = i;
240 }
241
242 for (size_t iFrame = 0; iFrame < results.size(); ++iFrame) {
243 results[iFrame].reserve(gloveData[iFrame].size());
244 for (const auto& obs : gloveData[iFrame]) {
245 if (!obs.valid) {
246 continue;
247 }
248
249 auto it = jointLookup.find(obs.jointName);
250 if (it == jointLookup.end()) {
251 continue;
252 }
253
255 constraint.sourceJoint = it->second;
256 constraint.sourceOffset = Vector3f::Zero();
257 constraint.referenceJoint = referenceIdx;
258 constraint.referenceOffset = Vector3f::Zero();
259 constraint.target = obs.position;
260 constraint.weight = 1.0f;
261 constraint.name = obs.jointName;
262 results[iFrame].push_back(std::move(constraint));
263 }
264 }
265
266 return results;
267}
268
269std::vector<std::vector<JointToJointOrientationDataT<float>>> createGloveOrientationConstraintData(
270 std::span<const GloveFrameData> gloveData,
271 const Character& character,
272 const GloveConfig& cfg,
273 size_t handIndex) {
274 if (gloveData.empty() || handIndex >= 2) {
275 return {};
276 }
277
278 std::vector<std::vector<JointToJointOrientationDataT<float>>> results(gloveData.size());
279
280 // Find the glove bone for this hand; fall back to the wrist joint itself
281 const std::string gloveBoneName = "glove_" + cfg.wristJointNames[handIndex];
282 size_t referenceIdx = character.skeleton.getJointIdByName(gloveBoneName);
283 if (referenceIdx == kInvalidIndex) {
284 referenceIdx = character.skeleton.getJointIdByName(cfg.wristJointNames[handIndex]);
285 if (referenceIdx == kInvalidIndex) {
286 return results;
287 }
288 }
289
290 // Build name-to-index map for the skeleton
291 std::unordered_map<std::string, size_t> jointLookup;
292 jointLookup.reserve(character.skeleton.joints.size());
293 for (size_t i = 0; i < character.skeleton.joints.size(); ++i) {
294 jointLookup[character.skeleton.joints[i].name] = i;
295 }
296
297 for (size_t iFrame = 0; iFrame < results.size(); ++iFrame) {
298 results[iFrame].reserve(gloveData[iFrame].size());
299 for (const auto& obs : gloveData[iFrame]) {
300 if (!obs.valid) {
301 continue;
302 }
303
304 auto it = jointLookup.find(obs.jointName);
305 if (it == jointLookup.end()) {
306 continue;
307 }
308
310 constraint.sourceJoint = it->second;
311 constraint.referenceJoint = referenceIdx;
312 constraint.target = obs.orientation;
313 constraint.weight = 1.0f;
314 constraint.name = obs.jointName;
315 results[iFrame].push_back(std::move(constraint));
316 }
317 }
318
319 return results;
320}
321
324 size_t solverFrame,
325 const Character& character,
326 const std::vector<std::vector<JointToJointPositionDataT<float>>>& posData,
327 const std::vector<std::vector<JointToJointOrientationDataT<float>>>& oriData,
328 size_t iFrame,
329 float posWeight,
330 float oriWeight) {
331 // Add position constraints for this frame
332 if (iFrame < posData.size() && !posData[iFrame].empty()) {
333 auto posFunc = std::make_shared<JointToJointPositionErrorFunctionT<float>>(character);
334 for (const auto& c : posData[iFrame]) {
335 posFunc->addConstraint(c);
336 }
337 posFunc->setWeight(PositionErrorFunction::kLegacyWeight * posWeight);
338 solverFunc.addErrorFunction(solverFrame, posFunc);
339 }
340
341 // Add orientation constraints for this frame
342 if (iFrame < oriData.size() && !oriData[iFrame].empty()) {
343 auto oriFunc = std::make_shared<JointToJointOrientationErrorFunctionT<float>>(character);
344 for (const auto& c : oriData[iFrame]) {
345 oriFunc->addConstraint(c);
346 }
347 oriFunc->setWeight(OrientationErrorFunction::kLegacyWeight * oriWeight);
348 solverFunc.addErrorFunction(solverFrame, oriFunc);
349 }
350}
351
352std::optional<GloveErrorFunctions> setupGloveErrorFunctions(
354 const Character& character,
355 std::span<const GloveFrameData> gloveData,
356 const GloveConfig& cfg,
357 size_t handIndex) {
358 if (gloveData.empty()) {
359 return std::nullopt;
360 }
361
362 // Verify a reference joint exists (glove bone preferred, wrist as fallback)
363 if (handIndex >= 2) {
364 return std::nullopt;
365 }
366 const std::string gloveBoneName = "glove_" + cfg.wristJointNames[handIndex];
367 size_t referenceIdx = character.skeleton.getJointIdByName(gloveBoneName);
368 if (referenceIdx == kInvalidIndex) {
369 referenceIdx = character.skeleton.getJointIdByName(cfg.wristJointNames[handIndex]);
370 if (referenceIdx == kInvalidIndex) {
371 return std::nullopt;
372 }
373 }
374
376
377 // Build constraint data
378 funcs.posData = createGlovePositionConstraintData(gloveData, character, cfg, handIndex);
379 funcs.oriData = createGloveOrientationConstraintData(gloveData, character, cfg, handIndex);
380
381 // Create and register error functions
382 funcs.posFunc = std::make_shared<JointToJointPositionErrorFunctionT<float>>(character);
384 solverFunc.addErrorFunction(funcs.posFunc);
385
386 funcs.oriFunc = std::make_shared<JointToJointOrientationErrorFunctionT<float>>(character);
388 solverFunc.addErrorFunction(funcs.oriFunc);
389
390 return funcs;
391}
392
394 // Update position constraints
395 funcs.posFunc->clearConstraints();
396 if (iFrame < funcs.posData.size()) {
397 for (const auto& c : funcs.posData[iFrame]) {
398 funcs.posFunc->addConstraint(c);
399 }
400 }
401
402 // Update orientation constraints
403 funcs.oriFunc->clearConstraints();
404 if (iFrame < funcs.oriData.size()) {
405 for (const auto& c : funcs.oriData[iFrame]) {
406 funcs.oriFunc->addConstraint(c);
407 }
408 }
409}
410
411} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
void addErrorFunction(size_t frame, std::shared_ptr< SkeletonErrorFunctionT< T > > errorFunction)
void addErrorFunction(std::shared_ptr< SkeletonErrorFunctionT< T > > solvable)
#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
void bakeGloveOffsetsFromParams(Character &character, const ModelParameters &solvedParams, const Character &solvingCharacter, const std::optional< GloveConfig > &cfg)
Bake solved glove offsets from calibration parameters into the skeleton.
Character addGloveBones(Character character, const GloveConfig &cfg, const std::array< GloveOffset, 2 > &offsets, const std::string &prefix)
Add glove joints to the skeleton with given offsets but no model parameters.
constexpr size_t kMaxModelParams
Maximum number of model parameters supported per frame across any character.
Definition types.h:427
void addGloveConstraintsToSequenceSolver(SequenceSolverFunctionT< float > &solverFunc, size_t solverFrame, const Character &character, const std::vector< std::vector< JointToJointPositionDataT< float > > > &posData, const std::vector< std::vector< JointToJointOrientationDataT< float > > > &oriData, size_t iFrame, float posWeight, float oriWeight)
Add glove error functions to a SequenceSolverFunction for one frame.
@ TY
Definition types.h:22
@ TZ
Definition types.h:22
@ TX
Definition types.h:22
@ RX
Definition types.h:22
@ RZ
Definition types.h:22
@ RY
Definition types.h:22
@ Intrinsic
The intrinsic convention.
Definition utility.h:169
std::vector< std::vector< JointToJointOrientationDataT< float > > > createGloveOrientationConstraintData(std::span< const GloveFrameData > gloveData, const Character &character, const GloveConfig &cfg, size_t handIndex)
Convert per-frame glove observations to JointToJoint orientation constraints.
JointParametersT< float > JointParameters
Definition types.h:135
Character createGloveCharacter(const Character &src, const GloveConfig &cfg, const std::string &prefix)
Add glove bones with 6-DOF model parameters (convenience wrapper).
CharacterParametersT< float > CharacterParameters
Definition types.h:168
constexpr size_t kParametersPerJoint
Definition types.h:21
JointT< float > Joint
Definition fwd.h:206
std::array< GloveOffset, 2 > extractGloveOffsetsFromCharacter(const Character &gloveChar, const CharacterParameters &params, const GloveConfig &cfg)
Extract calibrated glove offsets from solved parameters.
Quaternion< T > eulerToQuaternion(const Vector3< T > &angles, int axis0, int axis1, int axis2, EulerConvention convention)
Converts Euler angles to quaternion.
Definition utility.cpp:289
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
void updateGloveConstraintsForFrame(GloveErrorFunctions &funcs, size_t iFrame)
Swap per-frame glove constraint data on already-registered error functions.
Vector3< float > Vector3f
Definition types.h:251
std::optional< GloveErrorFunctions > setupGloveErrorFunctions(SkeletonSolverFunctionT< float > &solverFunc, const Character &character, std::span< const GloveFrameData > gloveData, const GloveConfig &cfg, size_t handIndex)
Create and register glove error functions for the per-frame solver.
std::bitset< kMaxModelParams > ParameterSet
Bitset for model parameter enablement.
Definition types.h:430
SparseRowMatrix< float > SparseRowMatrixf
Definition types.h:193
std::vector< std::vector< JointToJointPositionDataT< float > > > createGlovePositionConstraintData(std::span< const GloveFrameData > gloveData, const Character &character, const GloveConfig &cfg, size_t handIndex)
Convert per-frame glove observations to JointToJoint position constraints.
Character addGloveCalibrationParameters(Character character, const GloveConfig &cfg, const std::string &prefix)
Add 6-DOF model parameters for existing glove bones.
JointParametersT< T > offsets
The joint parameter vector representing the unique bone lengths of the character, defining the charac...
Definition types.h:165
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
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
Definition character.h:36
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
Definition character.h:39
static EIGEN_DEVICE_FUNC Derived< Scalar > Zero(::Eigen::Index size)
Definition types.h:92
Configuration for glove constraints.
Definition glove_utils.h:55
std::array< std::string, 2 > wristJointNames
Names of the left and right wrist joints in the skeleton.
Definition glove_utils.h:67
float positionWeight
Weight for position constraints between glove and finger joints.
Definition glove_utils.h:59
float orientationWeight
Weight for orientation constraints between glove and finger joints.
Definition glove_utils.h:64
Holds per-frame glove error functions for the single-frame solver.
std::shared_ptr< JointToJointPositionErrorFunctionT< float > > posFunc
Position error function registered with the solver.
std::vector< std::vector< JointToJointOrientationDataT< float > > > oriData
Pre-built per-frame orientation constraint data.
std::shared_ptr< JointToJointOrientationErrorFunctionT< float > > oriFunc
Orientation error function registered with the solver.
std::vector< std::vector< JointToJointPositionDataT< float > > > posData
Pre-built per-frame position constraint data.
size_t parent
Index of the parent joint in the skeleton hierarchy, or kInvalidIndex for the root.
Definition joint.h:24
Quaternion< T > preRotation
Pre-rotation from the parent joint's axes to this joint's local axes.
Definition joint.h:32
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
Constraint data for joint-to-joint orientation error between two joints.
std::string name
Name of the constraint (for debugging).
Eigen::Quaternion< T > target
Target relative orientation as a quaternion (R_ref^T * R_src should match this).
size_t sourceJoint
Index of the source joint (the joint whose orientation we want to constrain).
size_t referenceJoint
Index of the reference joint (the joint whose coordinate frame we use).
Constraint data for joint-to-joint position error between two joints.
size_t referenceJoint
Index of the reference joint (the joint whose coordinate frame we use).
Vector3< T > referenceOffset
Offset from referenceJoint in the local coordinate system of referenceJoint.
size_t sourceJoint
Index of the source joint (the joint whose position we want to constrain).
std::string name
Name of the constraint (for debugging).
Vector3< T > target
Target position in the reference joint's coordinate frame.
Vector3< T > sourceOffset
Offset from sourceJoint in the local coordinate system of sourceJoint.
JointParametersT< T > apply(const ModelParametersT< T > &parameters) const
Map model parameters to joint parameters using a linear transformation.
size_t getJointIdByName(std::string_view name) const
Returns the index of a joint with the given name, or kInvalidIndex if not found.
Definition skeleton.cpp:25
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