Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
skinned_locator_triangle_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
11
19#include "momentum/common/log.h"
21#include "momentum/math/mesh.h"
22
23#include <axel/math/PointTriangleProjectionDefinitions.h>
24
25#include <memory>
26
27namespace momentum {
28
29template <typename T>
31 const Character& character_in,
33 : SkeletonErrorFunctionT<T>(character_in.skeleton, character_in.parameterTransform),
34 character_(character_in),
35 constraintType_(type) {
36 MT_CHECK(static_cast<bool>(character_in.mesh));
39 "SkinnedLocatorTriangleErrorFunction only supports Position and Plane constraint types");
40}
41
42template <typename T>
44
45template <typename T>
49
50template <typename T>
52 const std::vector<SkinnedLocatorTriangleConstraintT<T>>& constraints) {
53 constraints_ = constraints;
54}
55
56template <typename T>
58 int locatorIndex,
59 const Eigen::Vector3i& triangleIndices,
60 const Eigen::Vector3<T>& triangleBaryCoords,
61 float depth,
62 T weight) {
63 MT_CHECK(locatorIndex >= 0 && ((size_t)locatorIndex) < character_.skinnedLocators.size());
64 constraints_.push_back(
66 locatorIndex, triangleIndices, triangleBaryCoords, depth, weight, {}});
67}
68
69template <typename T>
77
78template <typename T>
80 const MeshT<T>& mesh,
82 return (mesh.vertices[c.tgtTriangleIndices[1]] - mesh.vertices[c.tgtTriangleIndices[0]])
83 .cross(mesh.vertices[c.tgtTriangleIndices[2]] - mesh.vertices[c.tgtTriangleIndices[0]])
84 .normalized();
85}
86
87template <typename T>
88Eigen::Vector3<T> computeTargetPosition(
89 const MeshT<T>& mesh,
91 return computeTargetBaryPosition(mesh, c) + c.depth * computeTargetTriangleNormal(mesh, c);
92}
93
94namespace {
95
96// Helper struct for reprojection result
97template <typename T>
98struct ReprojectionResult {
99 Eigen::Vector3i triangleIndices = Eigen::Vector3i::Constant(-1);
100 Eigen::Vector3<T> baryCoords = Eigen::Vector3<T>::Zero();
101 Eigen::Vector3<T> closestPoint = Eigen::Vector3<T>::Zero();
102 bool valid = false;
103};
104
105// Find the closest candidate triangle and compute reprojection
106template <typename T>
107ReprojectionResult<T> findClosestCandidateTriangle(
108 const MeshT<T>& mesh,
109 const Eigen::Vector3<T>& locatorPos,
110 const std::vector<CandidateTriangle>& candidates,
111 T depth) {
112 ReprojectionResult<T> result;
113 T minDistSq = std::numeric_limits<T>::max();
114
115 for (const auto& candidate : candidates) {
116 const Eigen::Vector3<T>& v0 = mesh.vertices[candidate.vertexIndices[0]];
117 const Eigen::Vector3<T>& v1 = mesh.vertices[candidate.vertexIndices[1]];
118 const Eigen::Vector3<T>& v2 = mesh.vertices[candidate.vertexIndices[2]];
119
120 Eigen::Vector3<T> projPoint;
121 Eigen::Vector3<T> bary;
122 axel::projectOnTriangle(locatorPos, v0, v1, v2, projPoint, &bary);
123
124 // Compute normal and apply depth offset
125 Eigen::Vector3<T> normal = (v1 - v0).cross(v2 - v0);
126 const T normalNorm = normal.norm();
127 if (normalNorm > T(1e-8)) {
128 normal /= normalNorm;
129 } else {
130 normal.setZero();
131 }
132 const Eigen::Vector3<T> targetPoint = projPoint + depth * normal;
133
134 const T distSq = (locatorPos - targetPoint).squaredNorm();
135 if (distSq < minDistSq) {
136 minDistSq = distSq;
137 result.triangleIndices = candidate.vertexIndices;
138 result.baryCoords = bary;
139 result.closestPoint = targetPoint;
140 result.valid = true;
141 }
142 }
143
144 return result;
145}
146
147// Helper to get effective constraint after potential reprojection
148template <typename T>
149SkinnedLocatorTriangleConstraintT<T> getEffectiveConstraint(
150 const MeshT<T>& mesh,
152 const Eigen::Vector3<T>& locatorPos) {
153 if (constr.candidateTriangles.empty()) {
154 return constr;
155 }
156
157 // Find closest candidate triangle
158 ReprojectionResult<T> reproj =
159 findClosestCandidateTriangle(mesh, locatorPos, constr.candidateTriangles, constr.depth);
160
161 // If reprojection failed (e.g., NaN vertices → all candidates skipped), fall back to original
162 if (!reproj.valid) {
163 MT_LOGI(
164 "SkinnedLocatorTriangle: reprojection failed for locatorIndex {} "
165 "({} candidates, all had NaN/Inf distances). Using original constraint.",
166 constr.locatorIndex,
167 constr.candidateTriangles.size());
168 return constr;
169 }
170
171 // Create effective constraint with reprojected triangle
173 effective.locatorIndex = constr.locatorIndex;
174 effective.tgtTriangleIndices = reproj.triangleIndices;
175 effective.tgtTriangleBaryCoords = reproj.baryCoords;
176 effective.depth = constr.depth;
177 effective.weight = constr.weight;
178 // Don't copy candidateTriangles - effective constraint is for single evaluation
179 return effective;
180}
181
182} // namespace
183
184template <typename T>
185Eigen::Vector3<T> SkinnedLocatorTriangleErrorFunctionT<T>::getLocatorRestPosition(
186 const ModelParametersT<T>& modelParams,
187 int locatorIndex) const {
188 MT_CHECK(locatorIndex >= 0 && locatorIndex < static_cast<int>(character_.skinnedLocators.size()));
189 const auto& locator = character_.skinnedLocators[locatorIndex];
190
191 Vector3<T> result = locator.position.template cast<T>();
192 int locatorParameterIndex = getSkinnedLocatorParameterIndex(locatorIndex);
193 if (locatorParameterIndex >= 0 && locatorParameterIndex + 2 < modelParams.size()) {
194 result += modelParams.v.template segment<3>(locatorParameterIndex);
195 }
196
197 return result;
198}
199
200template <typename T>
201std::array<Eigen::Matrix3<T>, 3> compute_d_targetNormal_d_vertexPos(
203 const MeshT<T>& mesh) {
204 std::array<Eigen::Matrix3<T>, 3> result;
205 for (auto& r : result) {
206 r.setZero();
207 }
208
209 const std::array<Eigen::Vector3<T>, 3> tgtTrianglePositions = {
210 mesh.vertices[cons.tgtTriangleIndices[0]],
211 mesh.vertices[cons.tgtTriangleIndices[1]],
212 mesh.vertices[cons.tgtTriangleIndices[2]]};
213
214 Eigen::Vector3<T> n = (tgtTrianglePositions[1] - tgtTrianglePositions[0])
215 .cross(tgtTrianglePositions[2] - tgtTrianglePositions[0]);
216 T n_norm = n.norm();
217 if (n_norm < 1e-6) {
218 // ignore normal gradients
219 return result;
220 }
221 n /= n_norm;
222
223 const T area_times_2 = n_norm;
224
225 for (int k = 0; k < 3; ++k) {
226 // https://www.cs.cmu.edu/~kmcrane/Projects/Other/TriangleMeshDerivativesCheatSheet.pdf
227 const Eigen::Vector3<T> e =
228 tgtTrianglePositions[(k + 2) % 3] - tgtTrianglePositions[(k + 1) % 3];
229 result[k] += (e.cross(n) * n.transpose()) / area_times_2;
230 }
231
232 return result;
233}
234
235template <typename T>
236std::array<Eigen::Matrix3<T>, 3> compute_d_targetPos_d_vertexPos(
238 const MeshT<T>& mesh) {
239 std::array<Eigen::Matrix3<T>, 3> result;
240 result[0] = Eigen::Matrix3<T>::Identity() * cons.tgtTriangleBaryCoords[0];
241 result[1] = Eigen::Matrix3<T>::Identity() * cons.tgtTriangleBaryCoords[1];
242 result[2] = Eigen::Matrix3<T>::Identity() * cons.tgtTriangleBaryCoords[2];
243
244 const auto dNormal = compute_d_targetNormal_d_vertexPos(cons, mesh);
245 for (int k = 0; k < 3; ++k) {
246 result[k] += cons.depth * dNormal[k];
247 }
248
249 return result;
250}
251
252template <typename T>
254 const ModelParametersT<T>& modelParameters,
255 const SkeletonStateT<T>& /* state */,
256 const MeshStateT<T>& meshState) {
258
259 MT_CHECK_NOTNULL(meshState.restMesh_);
260
261 double error = 0.0;
262
263 if (constraintType_ == VertexConstraintType::Position) {
264 for (const auto& constr : constraints_) {
265 // Get the skinned locator position
266 const Eigen::Vector3<T> locatorRestPos =
267 getLocatorRestPosition(modelParameters, constr.locatorIndex);
268
269 // Get effective constraint (potentially reprojected onto closest candidate triangle)
270 const SkinnedLocatorTriangleConstraintT<T> effectiveConstr =
271 getEffectiveConstraint(*meshState.restMesh_, constr, locatorRestPos);
272
273 // Get the target position on the triangle
274 const Eigen::Vector3<T> tgtPoint =
275 computeTargetPosition(*meshState.restMesh_, effectiveConstr);
276
277 // Calculate position error
278 const Eigen::Vector3<T> diff = locatorRestPos - tgtPoint;
279 error += constr.weight * diff.squaredNorm();
280 }
281 } else {
282 MT_CHECK(constraintType_ == VertexConstraintType::Plane);
283 for (const auto& constr : constraints_) {
284 // Get the skinned locator position
285 const Eigen::Vector3<T> locatorRestPos =
286 getLocatorRestPosition(modelParameters, constr.locatorIndex);
287
288 // Get effective constraint (potentially reprojected onto closest candidate triangle)
289 const SkinnedLocatorTriangleConstraintT<T> effectiveConstr =
290 getEffectiveConstraint(*meshState.restMesh_, constr, locatorRestPos);
291
292 // Get the target position and normal
293 const Eigen::Vector3<T> targetNormal =
294 computeTargetTriangleNormal(*meshState.restMesh_, effectiveConstr);
295 const Eigen::Vector3<T> tgtPoint =
296 computeTargetBaryPosition(*meshState.restMesh_, effectiveConstr) +
297 effectiveConstr.depth * targetNormal;
298 // Calculate plane error (projection onto normal)
299 const T dist = targetNormal.dot(locatorRestPos - tgtPoint);
300 error += constr.weight * dist * dist;
301 }
302 }
303
304 return error * this->weight_;
305}
306
307template <typename T>
308double SkinnedLocatorTriangleErrorFunctionT<T>::calculatePositionGradient(
309 const ModelParametersT<T>& modelParameters,
310 const MeshStateT<T>& meshState,
312 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
313 // Get the skinned locator position
314 const Eigen::Vector3<T> locatorRestPos =
315 getLocatorRestPosition(modelParameters, constr.locatorIndex);
316
317 // Get the target position on the triangle
318 const Eigen::Vector3<T> tgtPoint = computeTargetPosition(*meshState.restMesh_, constr);
319
320 // Calculate position error
321 const Eigen::Vector3<T> diff = locatorRestPos - tgtPoint;
322
323 // Calculate gradient weight
324 const T wgt = 2.0f * constr.weight * this->weight_;
325
326 // Get the derivative of the target position with respect to the triangle vertices
327 const auto d_targetPos_d_tgtTriVertexPos =
328 compute_d_targetPos_d_vertexPos(constr, *meshState.restMesh_);
329
330 // Apply gradient for locator parameter if it exists
331 int paramIndex = getSkinnedLocatorParameterIndex(constr.locatorIndex);
332 if (paramIndex >= 0 && paramIndex + 2 < modelParameters.size()) {
333 // Each skinned locator has 3 parameters (x, y, z)
334 for (int d = 0; d < 3; ++d) {
335 Eigen::Vector3<T> d_restPos = Eigen::Vector3<T>::Zero();
336 d_restPos[d] = 1.0;
337
338 gradient(paramIndex + d) += diff.dot(d_restPos) * wgt;
339 }
340 }
341
342 // IN handle derivatives wrt blend shape parameters
343 if (this->character_.blendShape) {
344 for (int iTriVert = 0; iTriVert < 3; ++iTriVert) {
345 const int vertexIndex = constr.tgtTriangleIndices[iTriVert];
346 const Eigen::Matrix3<T>& d_targetPos_d_vertexPos = d_targetPos_d_tgtTriVertexPos[iTriVert];
347 for (Eigen::Index iBlendShape = 0;
348 iBlendShape < this->parameterTransform_.blendShapeParameters.size();
349 ++iBlendShape) {
350 const auto paramIdx = this->parameterTransform_.blendShapeParameters[iBlendShape];
351 if (paramIdx < 0) {
352 continue;
353 }
354
355 const Eigen::Vector3<T> d_restPos =
356 this->character_.blendShape->getShapeVectors()
357 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
358 .template cast<T>();
359
360 gradient[paramIdx] += -wgt * diff.dot(d_targetPos_d_vertexPos * d_restPos);
361 }
362 }
363 }
364 // OUT handle derivatives wrt blend shape parameters
365
366 return constr.weight * diff.squaredNorm();
367}
368
369template <typename T>
370double SkinnedLocatorTriangleErrorFunctionT<T>::calculatePlaneGradient(
371 const ModelParametersT<T>& modelParameters,
372 const MeshStateT<T>& meshState,
374 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
375 // Get the skinned locator position
376 const Eigen::Vector3<T> locatorRestPos =
377 getLocatorRestPosition(modelParameters, constr.locatorIndex);
378
379 // Get the target position and normal
380 const Eigen::Vector3<T> targetNormal = computeTargetTriangleNormal(*meshState.restMesh_, constr);
381 const Eigen::Vector3<T> tgtPoint =
382 computeTargetBaryPosition(*meshState.restMesh_, constr) + constr.depth * targetNormal;
383
384 // Calculate plane error (projection onto normal)
385 const Vector3<T> diff = locatorRestPos - tgtPoint;
386 const T dist = targetNormal.dot(diff);
387 const T wgt = 2.0f * constr.weight * this->weight_;
388
389 // Get the derivative of the target position with respect to the triangle vertices
390 const auto d_targetPos_d_tgtTriVertexPos =
391 compute_d_targetPos_d_vertexPos(constr, *meshState.restMesh_);
392 const auto d_targetNormal_d_tgtTriVertexPos =
393 compute_d_targetNormal_d_vertexPos(constr, *meshState.restMesh_);
394
395 // Apply gradient for locator parameter if it exists
396 int paramIndex = getSkinnedLocatorParameterIndex(constr.locatorIndex);
397 if (paramIndex >= 0) {
398 // Each skinned locator has 3 parameters (x, y, z)
399 for (int k = 0; k < 3; ++k) {
400 Eigen::Vector3<T> d_restPos = Eigen::Vector3<T>::Zero();
401 d_restPos[k] = 1.0;
402 gradient(paramIndex + k) += wgt * d_restPos.dot(targetNormal) * dist;
403 }
404 }
405
406 // IN handle derivatives wrt blend shape parameters:
407 for (int kTriVert = 0; kTriVert < 3; ++kTriVert) {
408 const int vertexIndex = constr.tgtTriangleIndices[kTriVert];
409 const Eigen::Matrix3<T>& d_targetPos_d_vertexPos = d_targetPos_d_tgtTriVertexPos[kTriVert];
410 for (Eigen::Index iBlendShape = 0;
411 iBlendShape < this->parameterTransform_.blendShapeParameters.size();
412 ++iBlendShape) {
413 const auto paramIdx = this->parameterTransform_.blendShapeParameters[iBlendShape];
414 if (paramIdx < 0) {
415 continue;
416 }
417
418 const Eigen::Vector3<T> d_restPos =
419 this->character_.blendShape->getShapeVectors()
420 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
421 .template cast<T>();
422
423 gradient(paramIdx) -= wgt * dist * targetNormal.dot(d_targetPos_d_vertexPos * d_restPos);
424 const Eigen::Vector3<T> diff_tgt_normal =
425 d_targetNormal_d_tgtTriVertexPos[kTriVert] * d_restPos;
426 gradient(paramIdx) += wgt * dist * diff.dot(diff_tgt_normal);
427 }
428 }
429 // OUT handle derivatives wrt blend shape parameters:
430
431 return constr.weight * dist * dist;
432}
433
434template <typename T>
435double SkinnedLocatorTriangleErrorFunctionT<T>::calculatePositionJacobian(
436 const ModelParametersT<T>& modelParameters,
437 const MeshStateT<T>& meshState,
439 Ref<Eigen::MatrixX<T>> jac,
440 Ref<Eigen::VectorX<T>> res) const {
441 // Get the skinned locator position
442 const Eigen::Vector3<T> locatorRestPos =
443 getLocatorRestPosition(modelParameters, constr.locatorIndex);
444
445 // Get the target position on the triangle
446 const Eigen::Vector3<T> tgtPoint = computeTargetPosition(*meshState.restMesh_, constr);
447
448 // Calculate position error
449 const Eigen::Vector3<T> diff = locatorRestPos - tgtPoint;
450
451 // Set residual
452 const T wgt = std::sqrt(constr.weight * this->weight_);
453 res = wgt * diff;
454
455 // Get the derivative of the target position with respect to the triangle vertices
456 const auto d_targetPos_d_tgtTriVertexPos =
457 compute_d_targetPos_d_vertexPos(constr, *meshState.restMesh_);
458
459 // Apply Jacobian for locator parameter if it exists
460 int paramIndex = getSkinnedLocatorParameterIndex(constr.locatorIndex);
461 if (paramIndex >= 0) {
462 for (int k = 0; k < 3; ++k) {
463 Eigen::Vector3<T> d_restPos = Eigen::Vector3<T>::Zero();
464 d_restPos[k] = 1.0;
465 jac.template block<3, 1>(0, paramIndex + k) += wgt * d_restPos;
466 }
467 }
468
469 // IN handle derivatives wrt blend shape parameters:
470 if (this->character_.blendShape) {
471 const auto& shapeVectors = this->character_.blendShape->getShapeVectors();
472 for (int iTriVert = 0; iTriVert < 3; ++iTriVert) {
473 const int vertexIndex = constr.tgtTriangleIndices[iTriVert];
474 const Eigen::Matrix3<T>& d_targetPos_d_vertexPos = d_targetPos_d_tgtTriVertexPos[iTriVert];
475
476 // loop over blend shape parameters:
477 for (Eigen::Index iBlendShape = 0;
478 iBlendShape < this->parameterTransform_.blendShapeParameters.size();
479 ++iBlendShape) {
480 const auto paramIdx = this->parameterTransform_.blendShapeParameters[iBlendShape];
481 if (paramIdx < 0) {
482 continue;
483 }
484
485 const Eigen::Vector3<T> d_restPos =
486 shapeVectors.template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
487 .template cast<T>();
488
489 jac.col(paramIdx) -= wgt * d_targetPos_d_vertexPos * d_restPos;
490 }
491 }
492 } // blendShape
493 // OUT handle derivatives wrt blend shape parameters:
494
495 return wgt * wgt * diff.squaredNorm();
496}
497
498template <typename T>
499double SkinnedLocatorTriangleErrorFunctionT<T>::calculatePlaneJacobian(
500 const ModelParametersT<T>& modelParameters,
501 const MeshStateT<T>& meshState,
503 Ref<Eigen::MatrixX<T>> jac,
504 T& res) const {
505 // Get the skinned locator position
506 const Eigen::Vector3<T> locatorRestPos =
507 getLocatorRestPosition(modelParameters, constr.locatorIndex);
508
509 // Get the target position and normal
510 const Eigen::Vector3<T> targetNormal = computeTargetTriangleNormal(*meshState.restMesh_, constr);
511 const Eigen::Vector3<T> tgtPoint =
512 computeTargetBaryPosition(*meshState.restMesh_, constr) + constr.depth * targetNormal;
513
514 // Calculate plane error (projection onto normal)
515 const Eigen::Vector3<T> diff = locatorRestPos - tgtPoint;
516 const T dist = targetNormal.dot(diff);
517
518 const T wgt = std::sqrt(constr.weight * this->weight_);
519 res = wgt * dist;
520
521 // Get the derivative of the target position with respect to the triangle vertices
522 const auto d_targetPos_d_tgtTriVertexPos =
523 compute_d_targetPos_d_vertexPos(constr, *meshState.restMesh_);
524 const auto d_targetNormal_d_tgtTriVertexPos =
525 compute_d_targetNormal_d_vertexPos(constr, *meshState.restMesh_);
526
527 // Apply Jacobian for locator parameter if it exists
528 int paramIndex = getSkinnedLocatorParameterIndex(constr.locatorIndex);
529 if (paramIndex >= 0) {
530 for (int k = 0; k < 3; ++k) {
531 Eigen::Vector3<T> d_restPos = Eigen::Vector3<T>::Zero();
532 d_restPos[k] = 1.0;
533 jac(0, paramIndex + k) += wgt * d_restPos.dot(targetNormal);
534 }
535 }
536
537 // IN handle derivatives wrt blend shape parameters:
538 for (int kTriVert = 0; kTriVert < 3; ++kTriVert) {
539 const int vertexIndex = constr.tgtTriangleIndices[kTriVert];
540 const Eigen::Matrix3<T>& d_targetPos_d_vertexPos = d_targetPos_d_tgtTriVertexPos[kTriVert];
541 for (Eigen::Index iBlendShape = 0;
542 iBlendShape < this->parameterTransform_.blendShapeParameters.size();
543 ++iBlendShape) {
544 const auto paramIdx = this->parameterTransform_.blendShapeParameters[iBlendShape];
545 if (paramIdx < 0) {
546 continue;
547 }
548
549 const Eigen::Vector3<T> d_restPos =
550 this->character_.blendShape->getShapeVectors()
551 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
552 .template cast<T>();
553
554 jac(0, paramIdx) -= wgt * targetNormal.dot(d_targetPos_d_vertexPos * d_restPos);
555 const Eigen::Vector3<T> diff_tgt_normal =
556 d_targetNormal_d_tgtTriVertexPos[kTriVert] * d_restPos;
557 jac(0, paramIdx) += wgt * diff.dot(diff_tgt_normal);
558 }
559 }
560 // OUT handle derivatives wrt blend shape parameters:
561
562 return wgt * wgt * dist * dist;
563}
564
565template <typename T>
567 const ModelParametersT<T>& modelParameters,
568 const SkeletonStateT<T>& /* state */,
569 const MeshStateT<T>& meshState,
570 Eigen::Ref<Eigen::VectorX<T>> gradient) {
571 MT_CHECK_NOTNULL(meshState.restMesh_);
572
573 double error = 0;
574
575 if (constraintType_ == VertexConstraintType::Position) {
576 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
577 const SkinnedLocatorTriangleConstraintT<T>& constr = constraints_[iCons];
578 // Get locator position for reprojection
579 const Eigen::Vector3<T> locatorRestPos =
580 getLocatorRestPosition(modelParameters, constr.locatorIndex);
581 // Get effective constraint (potentially reprojected)
582 const SkinnedLocatorTriangleConstraintT<T> effectiveConstr =
583 getEffectiveConstraint(*meshState.restMesh_, constr, locatorRestPos);
584 error += calculatePositionGradient(modelParameters, meshState, effectiveConstr, gradient);
585 }
586 } else {
587 MT_CHECK(constraintType_ == VertexConstraintType::Plane);
588 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
589 const SkinnedLocatorTriangleConstraintT<T>& constr = constraints_[iCons];
590 // Get locator position for reprojection
591 const Eigen::Vector3<T> locatorRestPos =
592 getLocatorRestPosition(modelParameters, constr.locatorIndex);
593 // Get effective constraint (potentially reprojected)
594 const SkinnedLocatorTriangleConstraintT<T> effectiveConstr =
595 getEffectiveConstraint(*meshState.restMesh_, constr, locatorRestPos);
596 error += calculatePlaneGradient(modelParameters, meshState, effectiveConstr, gradient);
597 }
598 }
599
600 return this->weight_ * error;
601}
602
603template <typename T>
605 const ModelParametersT<T>& modelParameters,
606 const SkeletonStateT<T>& /* state */,
607 const MeshStateT<T>& meshState,
608 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
609 Eigen::Ref<Eigen::VectorX<T>> residual,
610 int& usedRows) {
611 MT_CHECK(
612 jacobian.cols() == static_cast<Eigen::Index>(this->parameterTransform_.transform.cols()));
613 MT_CHECK(jacobian.rows() >= (Eigen::Index)(1 * constraints_.size()));
614 MT_CHECK(residual.rows() >= (Eigen::Index)(1 * constraints_.size()));
615
616 MT_CHECK(
617 meshState.restMesh_, "MeshState must have rest mesh for SkinnedLocatorTriangleErrorFunction");
618
619 double error = 0;
620
621 if (constraintType_ == VertexConstraintType::Position) {
622 for (size_t i = 0; i < constraints_.size(); ++i) {
623 const SkinnedLocatorTriangleConstraintT<T>& constr = constraints_[i];
624 // Get locator position for reprojection
625 const Eigen::Vector3<T> locatorRestPos =
626 getLocatorRestPosition(modelParameters, constr.locatorIndex);
627 // Get effective constraint (potentially reprojected)
628 const SkinnedLocatorTriangleConstraintT<T> effectiveConstr =
629 getEffectiveConstraint(*meshState.restMesh_, constr, locatorRestPos);
630 error += calculatePositionJacobian(
631 modelParameters,
632 meshState,
633 effectiveConstr,
634 jacobian.block(3 * i, 0, 3, modelParameters.size()),
635 residual.middleRows(3 * i, 3));
636 }
637 usedRows = static_cast<int>(3 * constraints_.size());
638 } else {
639 MT_CHECK(constraintType_ == VertexConstraintType::Plane);
640 for (size_t i = 0; i < constraints_.size(); ++i) {
641 const SkinnedLocatorTriangleConstraintT<T>& constr = constraints_[i];
642 // Get locator position for reprojection
643 const Eigen::Vector3<T> locatorRestPos =
644 getLocatorRestPosition(modelParameters, constr.locatorIndex);
645 // Get effective constraint (potentially reprojected)
646 const SkinnedLocatorTriangleConstraintT<T> effectiveConstr =
647 getEffectiveConstraint(*meshState.restMesh_, constr, locatorRestPos);
648 T residualValue;
649 error += calculatePlaneJacobian(
650 modelParameters,
651 meshState,
652 effectiveConstr,
653 jacobian.block(i, 0, 1, modelParameters.size()),
654 residualValue);
655 residual(i) = residualValue;
656 }
657 usedRows = static_cast<int>(constraints_.size());
658 }
659
660 return error;
661}
662
663template <typename T>
665 if (constraintType_ == VertexConstraintType::Position) {
666 return constraints_.size() * 3;
667 } else if (constraintType_ == VertexConstraintType::Plane) {
668 return constraints_.size();
669 }
670 return 0;
671}
672
673} // namespace momentum
674
675// Explicit template instantiations
This file provides functions for applying blend shape deformations and skeletal transformations to ch...
#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
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
Support constraining a skinned locator to a location on the mesh defined by a target triangle and its...
double getGradient(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::VectorX< T > > gradient) final
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
double getError(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
void addConstraint(int locatorIndex, const Eigen::Vector3i &triangleIndices, const Eigen::Vector3< T > &triangleBaryCoords, float depth=0, T weight=1)
SkinnedLocatorTriangleErrorFunctionT(const Character &character, VertexConstraintType type=VertexConstraintType::Position)
void setConstraints(const std::vector< SkinnedLocatorTriangleConstraintT< T > > &constraints)
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
Functions for linear blend skinning (Skeletal Subspace Deformation).
#define MT_LOGI(...)
Definition log.h:179
T normal(const T &mean, const T &sigma)
Normally distributed value via the global Random singleton.
Definition random-inl.h:382
Eigen::Vector3< T > computeTargetBaryPosition(const MeshT< T > &mesh, const PointTriangleVertexConstraintT< T > &c)
Eigen::Ref< T > Ref
Definition types.h:43
Eigen::Vector3< T > computeTargetPosition(const MeshT< T > &mesh, const PointTriangleVertexConstraintT< T > &c)
Eigen::Vector3< T > computeTargetTriangleNormal(const MeshT< T > &mesh, const PointTriangleVertexConstraintT< T > &c)
std::array< Eigen::Matrix3< T >, 3 > compute_d_targetPos_d_vertexPos(const PointTriangleVertexConstraintT< T > &cons, const MeshT< T > &mesh)
std::array< Eigen::Matrix3< T >, 3 > compute_d_targetNormal_d_vertexPos(const PointTriangleVertexConstraintT< T > &cons, const MeshT< T > &mesh)
Vector3P< S > cross(const Eigen::MatrixBase< Derived > &v1, const Vector3P< S > &v2)
Computes cross product of Eigen::Vector3f and Vector3P.
Definition simd.h:309
Vector< T, 3 > Vector3
Definition types.h:236
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
VertexConstraintType
Type of vertex constraint mode.
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
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 > > restMesh_
Rest positions of the mesh after the shape basis (and potentially facial expression basis) has been a...
Definition mesh_state.h:30
A generic mesh representation with support for vertices, faces, lines, and texture coordinates.
Definition mesh.h:20
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
Definition mesh.h:22
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.
Eigen::Vector3< T > tgtTriangleBaryCoords
Initial barycentric coordinates.
Eigen::Vector3i tgtTriangleIndices
Initial/reference triangle vertex indices.