Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
vertex_vertex_distance_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
16#include "momentum/math/mesh.h"
17
18namespace momentum {
19
20template <typename T>
22 const Character& character)
23 : SkeletonErrorFunctionT<T>(character.skeleton, character.parameterTransform),
24 character_(character) {
25 MT_CHECK(static_cast<bool>(character.mesh));
26 MT_CHECK(static_cast<bool>(character.skinWeights));
27}
28
29template <typename T>
31
32template <typename T>
34 int vertexIndex1,
35 int vertexIndex2,
36 T weight,
37 T targetDistance) {
38 MT_CHECK(vertexIndex1 >= 0 && ((size_t)vertexIndex1) < character_.mesh->vertices.size());
39 MT_CHECK(vertexIndex2 >= 0 && ((size_t)vertexIndex2) < character_.mesh->vertices.size());
40 MT_CHECK(vertexIndex1 != vertexIndex2);
41
42 constraints_.push_back(
43 VertexVertexDistanceConstraintT<T>{vertexIndex1, vertexIndex2, weight, targetDistance});
44}
45
46template <typename T>
48 constraints_.clear();
49}
50
51template <typename T>
53 const ModelParametersT<T>& /* modelParameters */,
54 const SkeletonStateT<T>& /* state */,
55 const MeshStateT<T>& meshState) {
57
59
60 double error = 0.0;
61
62 for (const auto& constraint : constraints_) {
63 const auto& pos1 = meshState.posedMesh_->vertices[constraint.vertexIndex1];
64 const auto& pos2 = meshState.posedMesh_->vertices[constraint.vertexIndex2];
65
66 const T actualDistance = (pos1 - pos2).norm();
67 const T distanceDiff = actualDistance - constraint.targetDistance;
68
69 error += constraint.weight * distanceDiff * distanceDiff;
70 }
71
72 return error * this->weight_;
73}
74
75template <typename T>
77 const ModelParametersT<T>& modelParameters,
78 const SkeletonStateT<T>& state,
79 const MeshStateT<T>& meshState,
80 Eigen::Ref<Eigen::VectorX<T>> gradient) {
82
84 meshState.posedMesh_, "MeshState must have posed mesh for VertexVertexDistanceErrorFunction");
85
86 double error = 0.0;
87
88 for (const auto& constraint : constraints_) {
89 error += calculateGradient(modelParameters, state, meshState, constraint, gradient);
90 }
91
92 return error * this->weight_;
93}
94
95template <typename T>
97 const ModelParametersT<T>& modelParameters,
98 const SkeletonStateT<T>& state,
99 const MeshStateT<T>& meshState,
100 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
101 Eigen::Ref<Eigen::VectorX<T>> residual,
102 int& usedRows) {
104
105 MT_CHECK(
106 jacobian.cols() == static_cast<Eigen::Index>(this->parameterTransform_.transform.cols()));
107 MT_CHECK(jacobian.rows() >= static_cast<Eigen::Index>(constraints_.size()));
108 MT_CHECK(residual.rows() >= static_cast<Eigen::Index>(constraints_.size()));
109
110 MT_CHECK_NOTNULL(meshState.posedMesh_);
111
112 double error = 0.0;
113
114 for (size_t i = 0; i < constraints_.size(); i++) {
115 T residualValue;
116 error += calculateJacobian(
117 modelParameters,
118 state,
119 meshState,
120 constraints_[i],
121 jacobian.block(i, 0, 1, modelParameters.size()),
122 residualValue);
123 residual(i) = residualValue;
124 }
125
126 usedRows = static_cast<int>(constraints_.size());
127 return error;
128}
129
130template <typename T>
132 return constraints_.size();
133}
134
135template <typename T>
136double VertexVertexDistanceErrorFunctionT<T>::calculateJacobian(
137 const ModelParametersT<T>& /* modelParameters */,
138 const SkeletonStateT<T>& state,
139 const MeshStateT<T>& meshState,
140 const VertexVertexDistanceConstraintT<T>& constraint,
141 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
142 T& residual) const {
144
145 const auto& pos1 = meshState.posedMesh_->vertices[constraint.vertexIndex1];
146 const auto& pos2 = meshState.posedMesh_->vertices[constraint.vertexIndex2];
147
148 const Eigen::Vector3<T> diff = pos1 - pos2;
149 const T actualDistance = diff.norm();
150
151 // Handle degenerate case where vertices are at the same position
152 if (actualDistance == T(0)) {
153 residual = T(0);
154 return T(0); // No meaningful jacobian when distance is zero
155 }
156
157 const T distanceDiff = actualDistance - constraint.targetDistance;
158 const Eigen::Vector3<T> distanceGradient = diff / actualDistance; // normalized difference vector
159
160 // Weight for the jacobian: sqrt(weight * this->weight_)
161 const T wgt = std::sqrt(constraint.weight * this->weight_);
162
163 // Set residual: wgt * distanceDiff
164 residual = wgt * distanceDiff;
165
166 // df/dv for distance function is the normalized direction (1×3 matrix)
167 // For vertex1: positive contribution, for vertex2: negative contribution
168 const Eigen::Matrix<T, 1, 3> dfdv1 = distanceGradient.transpose();
169 const Eigen::Matrix<T, 1, 3> dfdv2 = -distanceGradient.transpose();
170
171 SkeletonDerivativeT<T> deriv(
172 this->skeleton_,
173 this->parameterTransform_,
174 this->activeJointParams_,
175 this->enabledParameters_);
176
177 // Calculate jacobian contribution from vertex1 (positive contribution)
178 deriv.template accumulateVertexJacobian<1>(
179 constraint.vertexIndex1, pos1, dfdv1, wgt, state, meshState, character_, jacobian, 0);
180
181 // Calculate jacobian contribution from vertex2 (negative contribution)
182 deriv.template accumulateVertexJacobian<1>(
183 constraint.vertexIndex2, pos2, dfdv2, wgt, state, meshState, character_, jacobian, 0);
184
185 return wgt * wgt * distanceDiff * distanceDiff;
186}
187
188template <typename T>
189double VertexVertexDistanceErrorFunctionT<T>::calculateGradient(
190 const ModelParametersT<T>& /* modelParameters */,
191 const SkeletonStateT<T>& state,
192 const MeshStateT<T>& meshState,
193 const VertexVertexDistanceConstraintT<T>& constraint,
194 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
196
197 const auto& pos1 = meshState.posedMesh_->vertices[constraint.vertexIndex1];
198 const auto& pos2 = meshState.posedMesh_->vertices[constraint.vertexIndex2];
199
200 const Eigen::Vector3<T> diff = pos1 - pos2;
201 const T actualDistance = diff.norm();
202
203 // Handle degenerate case where vertices are at the same position
204 if (actualDistance == T(0)) {
205 return T(0); // No meaningful gradient when distance is zero
206 }
207
208 const T distanceDiff = actualDistance - constraint.targetDistance;
209 const Eigen::Vector3<T> distanceGradient = diff / actualDistance; // normalized difference vector
210
211 // df/dv for distance function is the normalized direction (1×3 matrix)
212 // For vertex1: positive contribution, for vertex2: negative contribution
213 const Eigen::Matrix<T, 1, 3> dfdv1 = distanceGradient.transpose();
214 const Eigen::Matrix<T, 1, 3> dfdv2 = -distanceGradient.transpose();
215
216 // weightedResidual = 2 * weight * loss_deriv * f
217 // For distance: f = distanceDiff, loss = 0.5 * f^2, loss_deriv = 1
218 // So weightedResidual = 2 * weight * distanceDiff
219 const Eigen::Matrix<T, 1, 1> weightedResidual =
220 Eigen::Matrix<T, 1, 1>::Constant(T(2) * constraint.weight * this->weight_ * distanceDiff);
221
223 this->skeleton_,
224 this->parameterTransform_,
225 this->activeJointParams_,
226 this->enabledParameters_);
227
228 // Calculate gradient contribution from vertex1 (positive contribution)
229 deriv.template accumulateVertexGradient<1>(
230 constraint.vertexIndex1,
231 pos1,
232 dfdv1,
233 weightedResidual,
234 state,
235 meshState,
236 character_,
237 gradient);
238
239 // Calculate gradient contribution from vertex2 (negative contribution)
240 deriv.template accumulateVertexGradient<1>(
241 constraint.vertexIndex2,
242 pos2,
243 dfdv2,
244 weightedResidual,
245 state,
246 meshState,
247 character_,
248 gradient);
249
250 return constraint.weight * distanceDiff * distanceDiff;
251}
252
253// Explicit template instantiations
256
259
260} // namespace momentum
#define MT_CHECK_NOTNULL(ptr,...)
Asserts that ptr is not null; on failure, throws std::runtime_error with the optional fmt-style messa...
Definition checks.h:45
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Shared utility for derivative computation in error functions.
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
Error function for vertex-to-vertex distance constraints.
double getJacobian(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::MatrixX< T > > jacobian, Eigen::Ref< Eigen::VectorX< T > > residual, int &usedRows) final
void addConstraint(int vertexIndex1, int vertexIndex2, T weight, T targetDistance)
Add a vertex-to-vertex distance constraint.
double getError(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
double getGradient(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::VectorX< T > > gradient) final
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
SkinWeights_u skinWeights
Defines how mesh vertices are influenced by joints.
Definition character.h:58
Mesh_u mesh
3D mesh representing the character's surface
Definition character.h:55
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE auto size() const
Definition types.h:87
Represents the complete state of a model's mesh.
Definition mesh_state.h:24
std::unique_ptr< MeshT< T > > posedMesh_
Posed mesh after the skeleton transforms have been applied.
Definition mesh_state.h:32
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.
Constraint for vertex-to-vertex distance errors.
T targetDistance
Desired distance between the two vertices.