Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
center_of_mass_error_function.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
14
15#include <array>
16#include <cmath>
17#include <numeric>
18#include <utility>
19#include <vector>
20
21namespace momentum {
22
23namespace {
24
25template <typename T>
26Eigen::Vector3<T> worldMassPosition(
27 const JointStateT<T>& jointState,
28 const CenterOfMassConstraintT<T>& constraint,
29 const size_t index) {
30 if (constraint.offsets.empty()) {
31 return jointState.translation();
32 }
33 return jointState.transform * constraint.offsets[index];
34}
35
36template <typename T>
37Eigen::Vector3<T> centerOfMass(
38 const CenterOfMassConstraintT<T>& constraint,
39 const JointStateListT<T>& jointStates) {
40 const T invTotalMass = T(1) / constraint.totalMass();
41
42 Eigen::Vector3<T> com = Eigen::Vector3<T>::Zero();
43 for (size_t i = 0; i < constraint.jointIndices.size(); ++i) {
44 const Eigen::Vector3<T> worldPos =
45 worldMassPosition(jointStates[constraint.jointIndices[i]], constraint, i);
46 com += constraint.masses[i] * worldPos;
47 }
48 return com * invTotalMass;
49}
50
51template <typename T>
52Eigen::Vector3<T> projectToPlane(
53 const Eigen::Vector3<T>& position,
54 const CenterOfMassConstraintT<T>& constraint) {
55 return position -
56 constraint.projectionNormal *
57 (position.dot(constraint.projectionNormal) - constraint.projectionD);
58}
59
60template <typename T>
61Eigen::Matrix<T, 3, 3> residualDerivative(const CenterOfMassConstraintT<T>& constraint) {
62 if (!constraint.projectToPlane) {
63 return Eigen::Matrix<T, 3, 3>::Identity();
64 }
65
66 return Eigen::Matrix<T, 3, 3>::Identity() -
67 constraint.projectionNormal * constraint.projectionNormal.transpose();
68}
69
70template <typename T>
71Eigen::Vector3<T> centerOfMassResidual(
72 const Eigen::Vector3<T>& com,
73 const CenterOfMassConstraintT<T>& constraint) {
74 if (!constraint.projectToPlane) {
75 return com - constraint.target;
76 }
77
78 return projectToPlane(com, constraint) - constraint.target;
79}
80
81} // namespace
82
83// CenterOfMassConstraintT methods
84template <typename T>
86 return std::accumulate(masses.begin(), masses.end(), T(0));
87}
88
89template struct CenterOfMassConstraintT<float>;
91
92// CenterOfMassErrorFunctionT methods
93template <typename T>
95 const Skeleton& skeleton,
96 const ParameterTransform& parameterTransform)
97 : SkeletonErrorFunctionT<T>(skeleton, parameterTransform),
98 skeletonDerivative_(
99 skeleton,
100 parameterTransform,
101 this->activeJointParams_,
102 this->enabledParameters_) {}
103
104template <typename T>
106 MT_CHECK(
107 constraint.jointIndices.size() == constraint.masses.size(),
108 "Joint indices and masses must have the same size");
109 MT_CHECK(
110 constraint.offsets.empty() || constraint.offsets.size() == constraint.jointIndices.size(),
111 "Offsets must be empty or have the same size as joint indices");
112 MT_CHECK(!constraint.jointIndices.empty(), "Constraint must have at least one joint");
113 MT_CHECK(constraint.totalMass() > T(0), "Total mass must be positive");
114
115 // Validate joint indices are within bounds
116 for (const auto jointIdx : constraint.jointIndices) {
117 MT_CHECK(jointIdx < this->skeleton_.joints.size(), "Invalid joint index: {}", jointIdx);
118 }
119
120 ConstraintType normalizedConstraint = constraint;
121 if (normalizedConstraint.projectToPlane) {
122 MT_CHECK(
123 normalizedConstraint.projectionNormal.allFinite(),
124 "Projection plane normal must contain only finite values");
125 MT_CHECK(
126 std::isfinite(normalizedConstraint.projectionD), "Projection plane offset must be finite");
127 const T normalNorm = normalizedConstraint.projectionNormal.norm();
128 MT_CHECK(normalNorm > T(1e-6), "Projection plane normal must be non-zero");
129 normalizedConstraint.projectionNormal /= normalNorm;
130 normalizedConstraint.projectionD /= normalNorm;
131 }
132
133 constraints_.push_back(std::move(normalizedConstraint));
134}
135
136template <typename T>
137void CenterOfMassErrorFunctionT<T>::setConstraints(std::span<const ConstraintType> constraints) {
138 constraints_.clear();
139 constraints_.reserve(constraints.size());
140 for (const auto& constraint : constraints) {
141 addConstraint(constraint);
142 }
143}
144
145template <typename T>
147 constraints_.clear();
148}
149
150template <typename T>
151const std::vector<CenterOfMassConstraintT<T>>& CenterOfMassErrorFunctionT<T>::getConstraints()
152 const {
153 return constraints_;
154}
155
156template <typename T>
158 return constraints_.size();
159}
160
161template <typename T>
163 const ModelParametersT<T>& /*params*/,
164 const SkeletonStateT<T>& state,
165 const MeshStateT<T>& /*meshState*/) {
166 if (state.jointState.empty() || constraints_.empty()) {
167 return 0.0;
168 }
169
170 double error = 0.0;
171
172 for (const auto& constr : constraints_) {
173 const Eigen::Vector3<T> com = centerOfMass(constr, state.jointState);
174 const Eigen::Vector3<T> res = centerOfMassResidual(com, constr);
175 error += constr.weight * res.squaredNorm() * this->weight_;
176 }
177
178 return error;
179}
180
181template <typename T>
183 const ModelParametersT<T>& /*params*/,
184 const SkeletonStateT<T>& state,
185 const MeshStateT<T>& /*meshState*/,
186 Eigen::Ref<Eigen::VectorX<T>> gradient) {
188
189 if (state.jointState.empty() || constraints_.empty()) {
190 return 0.0;
191 }
192
193 double error = 0.0;
194
195 // Pre-allocate joint gradient storage
196 Eigen::VectorX<T> jointGrad =
197 Eigen::VectorX<T>::Zero(this->parameterTransform_.numAllModelParameters());
198 std::vector<Eigen::Vector3<T>> worldPositions;
199
200 for (const auto& constr : constraints_) {
201 const T invTotalMass = T(1) / constr.totalMass();
202 const bool hasOffsets = !constr.offsets.empty();
203 if (hasOffsets) {
204 worldPositions.resize(constr.jointIndices.size());
205 }
206
207 // Compute center of mass
208 Eigen::Vector3<T> com = Eigen::Vector3<T>::Zero();
209 for (size_t i = 0; i < constr.jointIndices.size(); ++i) {
210 const Eigen::Vector3<T> worldPos =
211 worldMassPosition(state.jointState[constr.jointIndices[i]], constr, i);
212 if (hasOffsets) {
213 worldPositions[i] = worldPos;
214 }
215 com += constr.masses[i] * worldPos;
216 }
217 com *= invTotalMass;
218
219 // Residual: f = project(CoM) - target (projection applied when configured)
220 const Eigen::Vector3<T> residual = centerOfMassResidual(com, constr);
221 error += constr.weight * residual.squaredNorm() * this->weight_;
222
223 const T wgt = T(2) * constr.weight * this->weight_;
224
225 // The weighted residual for accumulateJointGradient is 2 * weight * f.
226 // The dfdv encodes the normalizedMass factor and optional projection derivative.
227 // accumulateJointGradient computes: gradient += weightedResidual^T * dfdv * d(worldPos)/dq
228 const Eigen::Vector3<T> weightedRes = wgt * residual;
229 const Eigen::Matrix<T, 3, 3> dResidualDCom = residualDerivative(constr);
230
231 for (size_t i = 0; i < constr.jointIndices.size(); ++i) {
232 const size_t jointIdx = constr.jointIndices[i];
233 const T normalizedMass = constr.masses[i] * invTotalMass;
234 const Eigen::Vector3<T> worldPos =
235 hasOffsets ? worldPositions[i] : state.jointState[jointIdx].translation();
236
237 const Eigen::Matrix<T, 3, 3> dfdv = normalizedMass * dResidualDCom;
238 std::array<Eigen::Vector3<T>, 1> worldVecs = {worldPos};
239 std::array<Eigen::Matrix<T, 3, 3>, 1> dfdvArr = {dfdv};
240 std::array<uint8_t, 1> isPoints = {1};
241
242 skeletonDerivative_.template accumulateJointGradient<3>(
243 jointIdx,
244 std::span<const Eigen::Vector3<T>>(worldVecs.data(), 1),
245 std::span<const Eigen::Matrix<T, 3, 3>>(dfdvArr.data(), 1),
246 std::span<const uint8_t>(isPoints.data(), 1),
247 weightedRes,
248 state.jointState,
249 jointGrad);
250 }
251 }
252
253 gradient += jointGrad;
254 return error;
255}
256
257template <typename T>
259 const ModelParametersT<T>& /*params*/,
260 const SkeletonStateT<T>& state,
261 const MeshStateT<T>& /*meshState*/,
262 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
263 Eigen::Ref<Eigen::VectorX<T>> residual,
264 int& usedRows) {
266
267 if (state.jointState.empty() || constraints_.empty()) {
268 usedRows = 0;
269 return 0.0;
270 }
271
272 double error = 0.0;
273 size_t rowIndex = 0;
274 std::vector<Eigen::Vector3<T>> worldPositions;
275
276 for (const auto& constr : constraints_) {
277 const T invTotalMass = T(1) / constr.totalMass();
278 const bool hasOffsets = !constr.offsets.empty();
279 if (hasOffsets) {
280 worldPositions.resize(constr.jointIndices.size());
281 }
282
283 // Compute center of mass
284 Eigen::Vector3<T> com = Eigen::Vector3<T>::Zero();
285 for (size_t i = 0; i < constr.jointIndices.size(); ++i) {
286 const Eigen::Vector3<T> worldPos =
287 worldMassPosition(state.jointState[constr.jointIndices[i]], constr, i);
288 if (hasOffsets) {
289 worldPositions[i] = worldPos;
290 }
291 com += constr.masses[i] * worldPos;
292 }
293 com *= invTotalMass;
294
295 // Residual: f = project(CoM) - target (projection applied when configured)
296 const Eigen::Vector3<T> res = centerOfMassResidual(com, constr);
297 error += constr.weight * res.squaredNorm() * this->weight_;
298
299 const T wgt = std::sqrt(constr.weight * this->weight_);
300 residual.template segment<3>(rowIndex) = wgt * res;
301 const Eigen::Matrix<T, 3, 3> dResidualDCom = residualDerivative(constr);
302
303 // For each joint, accumulate Jacobian
304 for (size_t i = 0; i < constr.jointIndices.size(); ++i) {
305 const size_t jointIdx = constr.jointIndices[i];
306 const T normalizedMass = constr.masses[i] * invTotalMass;
307 const Eigen::Vector3<T> worldPos =
308 hasOffsets ? worldPositions[i] : state.jointState[jointIdx].translation();
309
310 const Eigen::Matrix<T, 3, 3> dfdv = normalizedMass * dResidualDCom;
311 std::array<Eigen::Vector3<T>, 1> worldVecs = {worldPos};
312 std::array<Eigen::Matrix<T, 3, 3>, 1> dfdvArr = {dfdv};
313 std::array<uint8_t, 1> isPoints = {1};
314
315 skeletonDerivative_.template accumulateJointJacobian<3>(
316 jointIdx,
317 std::span<const Eigen::Vector3<T>>(worldVecs.data(), 1),
318 std::span<const Eigen::Matrix<T, 3, 3>>(dfdvArr.data(), 1),
319 std::span<const uint8_t>(isPoints.data(), 1),
320 wgt,
321 state.jointState,
322 jacobian,
323 rowIndex);
324 }
325
326 rowIndex += 3;
327 }
328
329 usedRows = static_cast<int>(rowIndex);
330 return error;
331}
332
333template <typename T>
335 return 3 * constraints_.size();
336}
337
338// Explicit template instantiations
341
342} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Error function that constrains the center of mass to a target position.
CenterOfMassErrorFunctionT(const Skeleton &skeleton, const ParameterTransform &parameterTransform)
Constructs the error function.
void addConstraint(const ConstraintType &constraint)
Adds a center of mass constraint.
double getJacobian(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::MatrixX< T > > jacobian, Eigen::Ref< Eigen::VectorX< T > > residual, int &usedRows) override
double getError(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
const std::vector< ConstraintType > & getConstraints() const
Returns the current constraints.
size_t getNumConstraints() const
Returns the number of constraints.
void setConstraints(std::span< const ConstraintType > constraints)
Sets all constraints, replacing any existing ones.
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::VectorX< T > > gradient) override
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
const ParameterTransform & parameterTransform_
SkeletonT< float > Skeleton
Definition fwd.h:263
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
std::vector< JointStateT< T > > JointStateListT
Structure describing the state of all joints in a skeleton.
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
Constraint data for a center of mass target.
T totalMass() const
Returns the total mass (sum of all masses).
bool projectToPlane
If true, project the computed center of mass to projectionNormal dot x - projectionD = 0 before compa...
T projectionD
Offset for the optional projection plane in the equation normal dot x - d = 0.
std::vector< Eigen::Vector3< T > > offsets
Optional local center-of-mass offsets for each joint.
std::vector< T > masses
Mass values for each joint (must match jointIndices size).
std::vector< size_t > jointIndices
Indices of joints contributing to this CoM constraint.
Eigen::Vector3< T > projectionNormal
Normal for the optional projection plane.
Represents the state of a joint with local and global transformations.
Definition joint_state.h:50
Represents the complete state of a model's mesh.
Definition mesh_state.h:24
A vector of size numModelParams holding the values of all model parameters for a character.
Definition types.h:99
Represents the complete state of a skeleton.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.