Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
joint_to_joint_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
17
18namespace momentum {
19
20template <typename T>
25
26template <typename T>
28 const Character& character)
29 : JointToJointDistanceErrorFunctionT(character.skeleton, character.parameterTransform) {}
30
31template <typename T>
33 size_t joint1,
34 const Vector3<T>& offset1,
35 size_t joint2,
36 const Vector3<T>& offset2,
37 T targetDistance,
38 T weight) {
39 MT_CHECK(joint1 < this->skeleton_.joints.size(), "Invalid joint1 index: {}", joint1);
40 MT_CHECK(joint2 < this->skeleton_.joints.size(), "Invalid joint2 index: {}", joint2);
41 MT_CHECK(joint1 != joint2, "joint1 and joint2 must be different");
42 MT_CHECK(targetDistance >= 0, "targetDistance must be non-negative");
43
44 constraints_.push_back(
45 JointToJointDistanceConstraintT<T>{joint1, offset1, joint2, offset2, targetDistance, weight});
46}
47
48template <typename T>
50 constraints_.clear();
51}
52
53template <typename T>
55 const ModelParametersT<T>& /* params */,
56 const SkeletonStateT<T>& state,
57 const MeshStateT<T>& /* meshState */) {
58 if (state.jointState.empty() || constraints_.empty()) {
59 return 0.0;
60 }
61
62 double error = 0.0;
63
64 for (const auto& constr : constraints_) {
65 const auto& jointState1 = state.jointState[constr.joint1];
66 const auto& jointState2 = state.jointState[constr.joint2];
67
68 const Vector3<T> worldPos1 = jointState1.transform * constr.offset1;
69 const Vector3<T> worldPos2 = jointState2.transform * constr.offset2;
70
71 const Vector3<T> diff = worldPos1 - worldPos2;
72 const T actualDistance = diff.norm();
73 const T distanceError = actualDistance - constr.targetDistance;
74
75 error += constr.weight * sqr(distanceError) * kDistanceWeight * this->weight_;
76 }
77
78 return error;
79}
80
81template <typename T>
83 const ModelParametersT<T>& /* params */,
84 const SkeletonStateT<T>& state,
85 const MeshStateT<T>& /* meshState */,
86 Ref<VectorX<T>> gradient) {
87 if (state.jointState.empty() || constraints_.empty()) {
88 return 0.0;
89 }
90
91 double error = 0.0;
92
93 for (const auto& constr : constraints_) {
94 const auto& jointState1 = state.jointState[constr.joint1];
95 const auto& jointState2 = state.jointState[constr.joint2];
96
97 const Vector3<T> worldPos1 = jointState1.transform * constr.offset1;
98 const Vector3<T> worldPos2 = jointState2.transform * constr.offset2;
99
100 const Vector3<T> diff = worldPos1 - worldPos2;
101 const T actualDistance = diff.norm();
102
103 if (actualDistance < Eps<T>(1e-8f, 1e-14)) {
104 continue;
105 }
106
107 const T distanceError = actualDistance - constr.targetDistance;
108 error += constr.weight * sqr(distanceError) * kDistanceWeight * this->weight_;
109
110 const Vector3<T> direction = diff / actualDistance;
111 const T wgt = T(2) * constr.weight * distanceError * kDistanceWeight * this->weight_;
112
113 auto processJoint = [&](size_t jointIndex, const Vector3<T>& worldPos, T sign) {
114 size_t currentJoint = jointIndex;
115 while (currentJoint != kInvalidIndex) {
116 const auto& currentJointState = state.jointState[currentJoint];
117 const size_t paramIndex = currentJoint * kParametersPerJoint;
118 const Vector3<T> posd = worldPos - currentJointState.translation();
119
120 for (size_t d = 0; d < 3; d++) {
121 if (this->activeJointParams_[paramIndex + d]) {
122 const T val = sign * direction.dot(currentJointState.getTranslationDerivative(d)) * wgt;
123 for (auto index = this->parameterTransform_.transform.outerIndexPtr()[paramIndex + d];
124 index < this->parameterTransform_.transform.outerIndexPtr()[paramIndex + d + 1];
125 ++index) {
126 gradient[this->parameterTransform_.transform.innerIndexPtr()[index]] +=
127 val * this->parameterTransform_.transform.valuePtr()[index];
128 }
129 }
130 if (this->activeJointParams_[paramIndex + 3 + d]) {
131 const T val =
132 sign * direction.dot(currentJointState.getRotationDerivative(d, posd)) * wgt;
133 for (auto index =
134 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d];
135 index <
136 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
137 ++index) {
138 gradient[this->parameterTransform_.transform.innerIndexPtr()[index]] +=
139 val * this->parameterTransform_.transform.valuePtr()[index];
140 }
141 }
142 }
143 if (this->activeJointParams_[paramIndex + 6]) {
144 const T val = sign * direction.dot(currentJointState.getScaleDerivative(posd)) * wgt;
145 for (auto index = this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 6];
146 index < this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 6 + 1];
147 ++index) {
148 gradient[this->parameterTransform_.transform.innerIndexPtr()[index]] +=
149 val * this->parameterTransform_.transform.valuePtr()[index];
150 }
151 }
152
153 currentJoint = this->skeleton_.joints[currentJoint].parent;
154 }
155 };
156
157 processJoint(constr.joint1, worldPos1, T(1));
158 processJoint(constr.joint2, worldPos2, T(-1));
159 }
160
161 return error;
162}
163
164template <typename T>
166 const ModelParametersT<T>& /* params */,
167 const SkeletonStateT<T>& state,
168 const MeshStateT<T>& /* meshState */,
169 Ref<MatrixX<T>> jacobian,
170 Ref<VectorX<T>> residual,
171 int& usedRows) {
173 MT_CHECK(
174 jacobian.rows() >= gsl::narrow<Eigen::Index>(constraints_.size()),
175 "Jacobian rows mismatch: Actual {}, Expected {}",
176 jacobian.rows(),
177 gsl::narrow<Eigen::Index>(constraints_.size()));
178
179 MT_CHECK(
180 residual.rows() >= gsl::narrow<Eigen::Index>(constraints_.size()),
181 "Residual rows mismatch: Actual {}, Expected {}",
182 residual.rows(),
183 gsl::narrow<Eigen::Index>(constraints_.size()));
184
185 if (state.jointState.empty() || constraints_.empty()) {
186 usedRows = 0;
187 return 0.0;
188 }
189
190 const T wgt = std::sqrt(kDistanceWeight * this->weight_);
191
192 int pos = 0;
193 double error = 0.0;
194
195 for (const auto& constr : constraints_) {
196 const auto& jointState1 = state.jointState[constr.joint1];
197 const auto& jointState2 = state.jointState[constr.joint2];
198
199 const Vector3<T> worldPos1 = jointState1.transform * constr.offset1;
200 const Vector3<T> worldPos2 = jointState2.transform * constr.offset2;
201
202 const Vector3<T> diff = worldPos1 - worldPos2;
203 const T actualDistance = diff.norm();
204
205 if (actualDistance < Eps<T>(1e-8f, 1e-14)) {
206 continue;
207 }
208
209 const T distanceError = actualDistance - constr.targetDistance;
210 error += constr.weight * sqr(distanceError) * kDistanceWeight * this->weight_;
211
212 const Vector3<T> direction = diff / actualDistance;
213 const T fac = std::sqrt(constr.weight) * wgt;
214
215 const int row = pos++;
216
217 auto processJoint = [&](size_t jointIndex, const Vector3<T>& worldPos, T sign) {
218 size_t currentJoint = jointIndex;
219 while (currentJoint != kInvalidIndex) {
220 const auto& currentJointState = state.jointState[currentJoint];
221 const size_t paramIndex = currentJoint * kParametersPerJoint;
222 const Vector3<T> posd = worldPos - currentJointState.translation();
223
224 for (size_t d = 0; d < 3; d++) {
225 if (this->activeJointParams_[paramIndex + d]) {
226 const T val = sign * direction.dot(currentJointState.getTranslationDerivative(d)) * fac;
227 for (auto index = this->parameterTransform_.transform.outerIndexPtr()[paramIndex + d];
228 index < this->parameterTransform_.transform.outerIndexPtr()[paramIndex + d + 1];
229 ++index) {
230 jacobian(row, this->parameterTransform_.transform.innerIndexPtr()[index]) +=
231 val * this->parameterTransform_.transform.valuePtr()[index];
232 }
233 }
234 if (this->activeJointParams_[paramIndex + 3 + d]) {
235 const T val =
236 sign * direction.dot(currentJointState.getRotationDerivative(d, posd)) * fac;
237 for (auto index =
238 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d];
239 index <
240 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
241 ++index) {
242 jacobian(row, this->parameterTransform_.transform.innerIndexPtr()[index]) +=
243 val * this->parameterTransform_.transform.valuePtr()[index];
244 }
245 }
246 }
247 if (this->activeJointParams_[paramIndex + 6]) {
248 const T val = sign * direction.dot(currentJointState.getScaleDerivative(posd)) * fac;
249 for (auto index = this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 6];
250 index < this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 6 + 1];
251 ++index) {
252 jacobian(row, this->parameterTransform_.transform.innerIndexPtr()[index]) +=
253 val * this->parameterTransform_.transform.valuePtr()[index];
254 }
255 }
256
257 currentJoint = this->skeleton_.joints[currentJoint].parent;
258 }
259 };
260
261 processJoint(constr.joint1, worldPos1, T(1));
262 processJoint(constr.joint2, worldPos2, T(-1));
263
264 residual(row) = distanceError * fac;
265 }
266
267 usedRows = pos;
268
269 return error;
270}
271
272template <typename T>
274 return constraints_.size();
275}
276
279
280} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Error function that penalizes deviation from a target distance between two points attached to differe...
double getError(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
double getJacobian(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< MatrixX< T > > jacobian, Ref< VectorX< T > > residual, int &usedRows) override
void addConstraint(size_t joint1, const Vector3< T > &offset1, size_t joint2, const Vector3< T > &offset2, T targetDistance, T weight=T(1))
Add a constraint between two joints with local offsets.
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< VectorX< T > > gradient) override
static constexpr T kDistanceWeight
Default weight for distance constraints.
JointToJointDistanceErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
const ParameterTransform & parameterTransform_
constexpr T Eps(T FloatEps=T(1e-7), T DoubleEps=T(1e-16))
Returns a type-appropriate tolerance/epsilon value.
Definition constants.h:30
SkeletonT< float > Skeleton
Definition fwd.h:263
Eigen::Ref< T > Ref
Definition types.h:43
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
Eigen::Matrix< T, Dynamic, Dynamic > MatrixX
Dynamic-size, column-major dense matrix.
Definition types.h:80
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
T sqr(const T &x)
Computes the square of a value.
Definition utility.h:47
constexpr size_t kParametersPerJoint
Definition types.h:21
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
Vector< T, 3 > Vector3
Definition types.h:236
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
Constraint that enforces a distance relationship between two points attached to different joints.
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.