Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
vertex_normal_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
12
14#include "momentum/math/mesh.h"
15
16#include <dispenso/parallel_for.h>
17
18#include <numeric>
19
20namespace momentum {
21
22template <typename T>
24 const Character& character,
25 const ParameterTransform& parameterTransform,
26 T sourceNormalWeight,
27 T targetNormalWeight,
28 const T& lossAlpha,
29 const T& lossC,
32 character,
33 parameterTransform,
34 lossAlpha,
35 lossC),
36 sourceNormalWeight_(sourceNormalWeight),
37 targetNormalWeight_(targetNormalWeight),
38 computeAccurateNormalDerivatives_(computeAccurateNormalDerivatives) {
39 this->legacyWeight_ = this->kLegacyWeight;
40}
41
42template <typename T>
44 size_t constrIndex,
45 const SkeletonStateT<T>& /*state*/,
46 const MeshStateT<T>& meshState,
47 std::span<const Eigen::Vector3<T>> worldVecs,
48 FuncType& f,
49 std::span<DfdvType> dfdv) const {
50 MT_CHECK(constrIndex < this->constraints_.size(), "Constraint index out of range");
51 MT_CHECK(!worldVecs.empty(), "World vectors must not be empty");
53
54 const auto& constr = this->constraints_[constrIndex];
55 const Eigen::Vector3<T>& worldPos = worldVecs[0];
56
57 // Get source normal from posed mesh
58 const Eigen::Vector3<T> sourceNormal =
59 meshState.posedMesh_->normals[constr.vertexIndex].template cast<T>();
60 Eigen::Vector3<T> targetNormal = constr.targetNormal.template cast<T>();
61
62 // Flip target normal if facing away from source
63 if (sourceNormal.dot(targetNormal) < T(0)) {
64 targetNormal *= T(-1);
65 }
66
67 const Eigen::Vector3<T> normal =
68 sourceNormalWeight_ * sourceNormal + targetNormalWeight_ * targetNormal;
69
70 const Eigen::Vector3<T> diff = worldPos - constr.targetPosition.template cast<T>();
71 f[0] = normal.dot(diff);
72
73 if (!dfdv.empty()) {
74 // df/d(worldPos) = normal^T
75 // The normal rotation correction is handled by the normal correction methods
76 // in SkeletonDerivativeT.
77 dfdv[0] = normal.transpose();
78 }
79}
80
81template <typename T>
82void VertexNormalErrorFunctionT<T>::buildVertexToFaceAdjacency(
83 const MeshStateT<T>& meshState) const {
84 if (vertexToFaceAdjacencyValid_) {
85 return;
86 }
87
88 MT_CHECK(meshState.posedMesh_ != nullptr);
89
90 const auto& faces = meshState.posedMesh_->faces;
91 const size_t numVertices = meshState.posedMesh_->vertices.size();
92
93 vertexToFaceAdjacency_.clear();
94 vertexToFaceAdjacency_.resize(numVertices);
95
96 for (size_t fIdx = 0; fIdx < faces.size(); ++fIdx) {
97 const auto& face = faces[fIdx];
98 vertexToFaceAdjacency_[face[0]].push_back(fIdx);
99 vertexToFaceAdjacency_[face[1]].push_back(fIdx);
100 vertexToFaceAdjacency_[face[2]].push_back(fIdx);
101 }
102
103 vertexToFaceAdjacencyValid_ = true;
104}
105
106template <typename T>
108 const ModelParametersT<T>& /*params*/,
109 const SkeletonStateT<T>& state,
110 const MeshStateT<T>& meshState,
111 Eigen::Ref<Eigen::VectorX<T>> gradient) {
112 const size_t numConstraints = this->constraints_.size();
113 if (numConstraints == 0) {
114 return 0.0;
115 }
116 MT_CHECK_NOTNULL(meshState.posedMesh_);
117
118 const SkeletonDerivativeT<T> skeletonDerivative(
119 this->skeleton_,
121 this->activeJointParams_,
122 this->enabledParameters_);
123
124 auto dispensoOptions = dispenso::ParForOptions();
125 dispensoOptions.maxThreads = static_cast<uint32_t>(this->maxThreads_);
126
127 // L2 fast path: skip loss_.value()/deriv() calls entirely when loss is L2
128 const bool isL2 = this->loss_.isL2();
129 const T lossInvC2 = this->loss_.invC2();
130
131 // Issue 1 fix: Check blend shape existence OUTSIDE the loop.
132 // Without blend shapes, accurate and approximate modes are identical in performance.
133 const bool hasBlendShapesForAccurate = (this->character_.blendShape != nullptr) ||
134 (this->character_.faceExpressionBlendShape != nullptr);
135 const bool doAccurateNormal =
136 computeAccurateNormalDerivatives_ && sourceNormalWeight_ != T(0) && hasBlendShapesForAccurate;
137
138 // Issue 2 fix: Pre-build vertex-to-face adjacency ONCE before the loop.
139 if (doAccurateNormal) {
140 buildVertexToFaceAdjacency(meshState);
141 }
142
143 std::vector<std::tuple<double, VectorX<T>>> errorGradThread;
144 dispenso::parallel_for(
145 errorGradThread,
146 [&]() -> std::tuple<double, VectorX<T>> {
147 return {0.0, VectorX<T>::Zero(this->parameterTransform_.numAllModelParameters())};
148 },
149 size_t(0),
150 numConstraints,
151 [&](std::tuple<double, VectorX<T>>& errorGradLocal, const size_t i) {
152 double& errorLocal = std::get<0>(errorGradLocal);
153 auto& gradLocal = std::get<1>(errorGradLocal);
154
155 const T constrWeight = static_cast<T>(this->constraints_[i].weight);
156 if (constrWeight == T(0)) {
157 return;
158 }
159
160 const auto& constr = this->constraints_[i];
161 const size_t vertexIndex = constr.vertexIndex;
162 const Eigen::Vector3<T> worldPos =
163 meshState.posedMesh_->vertices[vertexIndex].template cast<T>();
164
165 // INLINE evalFunction — NO virtual call
166 const Eigen::Vector3<T> sourceNormal =
167 meshState.posedMesh_->normals[vertexIndex].template cast<T>();
168 Eigen::Vector3<T> targetNormal = constr.targetNormal.template cast<T>();
169 if (sourceNormal.dot(targetNormal) < T(0)) {
170 targetNormal *= T(-1);
171 }
172 const Eigen::Vector3<T> normal =
173 sourceNormalWeight_ * sourceNormal + targetNormalWeight_ * targetNormal;
174 const Eigen::Vector3<T> diff = worldPos - constr.targetPosition.template cast<T>();
175 const T f = normal.dot(diff);
176
177 if (f == T(0)) {
178 return;
179 }
180
181 const T sqrError = f * f;
182 const T w = constrWeight * this->weight_ * this->legacyWeight_;
183
184 T weightedResidualScalar;
185 if (isL2) {
186 errorLocal += w * sqrError * lossInvC2;
187 weightedResidualScalar = T(2) * w * lossInvC2 * f;
188 } else {
189 errorLocal += w * this->loss_.value(sqrError);
190 weightedResidualScalar = T(2) * w * this->loss_.deriv(sqrError) * f;
191 }
192
193 // Use accumulateVertexGradientWithNormalCorrectionDirect for scalar operations
194 if (sourceNormalWeight_ != T(0)) {
195 const T normalScale = weightedResidualScalar * sourceNormalWeight_;
197 vertexIndex,
198 worldPos,
199 normal,
200 weightedResidualScalar,
201 sourceNormal,
202 constr.targetPosition,
203 normalScale,
204 state,
205 meshState,
206 this->character_,
207 gradLocal);
208 } else {
209 // No normal correction — use standard vertex gradient
210 DfdvType dfdv = normal.transpose();
211 FuncType wr;
212 wr[0] = weightedResidualScalar;
213 skeletonDerivative.template accumulateVertexGradient<1>(
214 vertexIndex, worldPos, dfdv, wr, state, meshState, this->character_, gradLocal);
215 }
216
217 // Accurate mode: d(normal)/d(blendShapeWeight) with cached adjacency
218 if (doAccurateNormal) {
219 const T normalScale = weightedResidualScalar * sourceNormalWeight_;
220 const Eigen::Vector3<T> leverArm = worldPos - constr.targetPosition;
222 vertexIndex,
223 leverArm,
224 normalScale,
225 std::span<const size_t>(vertexToFaceAdjacency_[vertexIndex]),
226 state,
227 meshState,
228 this->character_,
229 gradLocal);
230 }
231 },
232 dispensoOptions);
233
234 if (!errorGradThread.empty()) {
235 errorGradThread[0] = std::accumulate(
236 errorGradThread.begin() + 1,
237 errorGradThread.end(),
238 errorGradThread[0],
239 [](const auto& a, const auto& b) -> std::tuple<double, VectorX<T>> {
240 return {std::get<0>(a) + std::get<0>(b), std::get<1>(a) + std::get<1>(b)};
241 });
242
243 gradient += std::get<1>(errorGradThread[0]);
244 return std::get<0>(errorGradThread[0]);
245 }
246
247 return 0.0;
248}
249
250template <typename T>
252 const ModelParametersT<T>& /*params*/,
253 const SkeletonStateT<T>& state,
254 const MeshStateT<T>& meshState,
255 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
256 Eigen::Ref<Eigen::VectorX<T>> residual,
257 int& usedRows) {
258 const size_t numConstraints = this->constraints_.size();
259 usedRows = 0;
260 if (numConstraints == 0) {
261 return 0.0;
262 }
263 MT_CHECK_NOTNULL(meshState.posedMesh_);
264
265 const SkeletonDerivativeT<T> skeletonDerivative(
266 this->skeleton_,
268 this->activeJointParams_,
269 this->enabledParameters_);
270
271 auto dispensoOptions = dispenso::ParForOptions();
272 dispensoOptions.maxThreads = static_cast<uint32_t>(this->maxThreads_);
273
274 // L2 fast path: skip loss_.value()/deriv() calls entirely when loss is L2
275 const bool isL2Jac = this->loss_.isL2();
276 const T lossInvC2Jac = this->loss_.invC2();
277
278 // Issue 1 fix: Check blend shape existence OUTSIDE the loop.
279 const bool hasBlendShapesForAccurate = (this->character_.blendShape != nullptr) ||
280 (this->character_.faceExpressionBlendShape != nullptr);
281 const bool doAccurateNormal =
282 computeAccurateNormalDerivatives_ && sourceNormalWeight_ != T(0) && hasBlendShapesForAccurate;
283
284 // Issue 2 fix: Pre-build vertex-to-face adjacency ONCE before the loop.
285 if (doAccurateNormal) {
286 buildVertexToFaceAdjacency(meshState);
287 }
288
289 std::vector<double> errorThread;
290 dispenso::parallel_for(
291 errorThread,
292 [&]() -> double { return 0.0; },
293 size_t(0),
294 numConstraints,
295 [&](double& errorLocal, const size_t i) {
296 const T constrWeight = static_cast<T>(this->constraints_[i].weight);
297 if (constrWeight == T(0)) {
298 return;
299 }
300
301 const auto& constr = this->constraints_[i];
302 const size_t vertexIndex = constr.vertexIndex;
303 const Eigen::Vector3<T> worldPos =
304 meshState.posedMesh_->vertices[vertexIndex].template cast<T>();
305
306 // INLINE evalFunction — NO virtual call
307 const Eigen::Vector3<T> sourceNormal =
308 meshState.posedMesh_->normals[vertexIndex].template cast<T>();
309 Eigen::Vector3<T> targetNormal = constr.targetNormal.template cast<T>();
310 if (sourceNormal.dot(targetNormal) < T(0)) {
311 targetNormal *= T(-1);
312 }
313 const Eigen::Vector3<T> normal =
314 sourceNormalWeight_ * sourceNormal + targetNormalWeight_ * targetNormal;
315 const Eigen::Vector3<T> diff = worldPos - constr.targetPosition.template cast<T>();
316 const T f = normal.dot(diff);
317
318 const size_t rowIndex = i;
319 const T sqrError = f * f;
320 const T w = constrWeight * this->weight_ * this->legacyWeight_;
321
322 T deriv;
323 if (isL2Jac) {
324 errorLocal += w * sqrError * lossInvC2Jac;
325 deriv = std::sqrt(w * lossInvC2Jac);
326 } else {
327 errorLocal += w * this->loss_.value(sqrError);
328 deriv = std::sqrt(w * this->loss_.deriv(sqrError));
329 }
330
331 residual[rowIndex] = deriv * f;
332
333 if (deriv == T(0)) {
334 return;
335 }
336
337 // Use scalar-specialized Direct methods
338 if (sourceNormalWeight_ != T(0)) {
339 const T normalScale = deriv * sourceNormalWeight_;
340
342 vertexIndex,
343 worldPos,
344 normal,
345 deriv,
346 sourceNormal,
347 constr.targetPosition,
348 normalScale,
349 state,
350 meshState,
351 this->character_,
352 jacobian,
353 rowIndex);
354
355 // Accurate mode: d(normal)/d(blendShapeWeight) with cached adjacency
356 if (doAccurateNormal) {
357 const Eigen::Vector3<T> leverArm = worldPos - constr.targetPosition;
359 vertexIndex,
360 leverArm,
361 normalScale,
362 std::span<const size_t>(vertexToFaceAdjacency_[vertexIndex]),
363 state,
364 meshState,
365 this->character_,
366 jacobian,
367 rowIndex);
368 }
369 } else {
370 DfdvType dfdv = normal.transpose();
371 skeletonDerivative.template accumulateVertexJacobian<1>(
372 vertexIndex,
373 worldPos,
374 dfdv,
375 deriv,
376 state,
377 meshState,
378 this->character_,
379 jacobian,
380 rowIndex);
381 }
382 },
383 dispensoOptions);
384
385 usedRows = static_cast<int>(numConstraints);
386
387 if (!errorThread.empty()) {
388 return std::accumulate(errorThread.begin() + 1, errorThread.end(), errorThread[0]);
389 }
390
391 return 0.0;
392}
393
396
397} // 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.
void accumulateVertexNormalBlendShapeJacobian(size_t vertexIndex, const Eigen::Vector3< T > &leverArm, T scale, const SkeletonStateT< T > &skeletonState, const MeshStateT< T > &meshState, const Character &character, Eigen::Ref< Eigen::MatrixX< T > > jacobian, size_t rowIndex) const
Jacobian version of accumulateVertexNormalBlendShapeGradient.
void accumulateVertexGradientWithNormalCorrectionDirect(size_t vertexIndex, const Eigen::Vector3< T > &worldPos, const Eigen::Vector3< T > &normal, T weightedResidual, const Eigen::Vector3< T > &sourceNormal, const Eigen::Vector3< T > &targetPosition, T normalCorrectionScale, const SkeletonStateT< T > &skeletonState, const MeshStateT< T > &meshState, const Character &character, Eigen::Ref< Eigen::VectorX< T > > gradient) const
Scalar-specialized combined vertex gradient + normal rotation correction.
void accumulateVertexJacobianWithNormalCorrectionDirect(size_t vertexIndex, const Eigen::Vector3< T > &worldPos, const Eigen::Vector3< T > &normal, T scale, const Eigen::Vector3< T > &sourceNormal, const Eigen::Vector3< T > &targetPosition, T normalCorrectionScale, const SkeletonStateT< T > &skeletonState, const MeshStateT< T > &meshState, const Character &character, Eigen::Ref< Eigen::MatrixX< T > > jacobian, size_t rowIndex) const
Scalar-specialized combined vertex Jacobian + normal rotation correction.
void accumulateVertexNormalBlendShapeGradient(size_t vertexIndex, const Eigen::Vector3< T > &leverArm, T scale, const SkeletonStateT< T > &skeletonState, const MeshStateT< T > &meshState, const Character &character, Eigen::Ref< Eigen::VectorX< T > > gradient) const
Accumulates the gradient contribution from how mesh normals change with blend shape weights.
const ParameterTransform & parameterTransform_
VertexErrorFunctionT(const Character &character, const ParameterTransform &parameterTransform, const T &lossAlpha=GeneralizedLossT< T >::kL2, const T &lossC=T(1))
Error function for vertex Normal and SymmetricNormal constraints.
bool computeAccurateNormalDerivatives() const
Returns whether accurate normal blend shape derivatives are enabled.
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::VectorX< T > > gradient) override
Override to handle normal rotation correction terms via SkeletonDerivativeT.
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
Override to handle normal rotation correction terms via SkeletonDerivativeT.
VertexNormalErrorFunctionT(const Character &character, const ParameterTransform &parameterTransform, T sourceNormalWeight=T(1), T targetNormalWeight=T(0), const T &lossAlpha=GeneralizedLossT< T >::kL2, const T &lossC=T(1), bool computeAccurateNormalDerivatives=false)
Constructor.
void evalFunction(size_t constrIndex, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, std::span< const Eigen::Vector3< T > > worldVecs, FuncType &f, std::span< DfdvType > dfdv) const final
Computes the residual and derivatives.
T normal(const T &mean, const T &sigma)
Normally distributed value via the global Random singleton.
Definition random-inl.h:382
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
decltype(auto) cast(const ContainerType< ObjectType > &originalContainer)
Casts the scalar type of objects in a container that support the cast<>() method.
Definition types.h:466
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
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 data for a vertex normal constraint.