Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
point_triangle_vertex_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
23#include "momentum/math/mesh.h"
24
25#include <memory>
26#include <numeric>
27
28namespace momentum {
29
30template <typename T>
32 const Character& character_in,
34 : SkeletonErrorFunctionT<T>(character_in.skeleton, character_in.parameterTransform),
35 character_(character_in),
36 constraintType_(type) {
37 MT_CHECK(static_cast<bool>(character_in.mesh));
38 MT_CHECK(static_cast<bool>(character_in.skinWeights));
41 "Constraint type {} not implemented yet for face. Only Position type is supported.",
42 toString(type));
43}
44
45template <typename T>
47 return this->character_.mesh->vertices.size();
48}
49
50template <typename T>
52
53template <typename T>
55 constraints_.clear();
56}
57
58template <typename T>
60 int vertexIndex,
61 const Eigen::Vector3i& triangleIndices,
62 const Eigen::Vector3<T>& triangleBaryCoords,
63 float depth,
64 T weight) {
65 MT_CHECK(vertexIndex >= 0 && ((size_t)vertexIndex) < character_.mesh->vertices.size());
66 constraints_.push_back(
68 vertexIndex, triangleIndices, triangleBaryCoords, depth, weight});
69}
70
71template <typename T>
72Eigen::Vector3<T> computeTargetBaryPosition(
73 const MeshT<T>& mesh,
75 return c.tgtTriangleBaryCoords[0] * mesh.vertices[c.tgtTriangleIndices[0]] +
78}
79
80template <typename T>
82 const MeshT<T>& mesh,
84 return (mesh.vertices[c.tgtTriangleIndices[1]] - mesh.vertices[c.tgtTriangleIndices[0]])
85 .cross(mesh.vertices[c.tgtTriangleIndices[2]] - mesh.vertices[c.tgtTriangleIndices[0]])
86 .normalized();
87}
88
89template <typename T>
90Eigen::Vector3<T> computeTargetPosition(
91 const MeshT<T>& mesh,
93 return computeTargetBaryPosition(mesh, c) + c.depth * computeTargetTriangleNormal(mesh, c);
94}
95
96template <typename T>
98 const ModelParametersT<T>& /* modelParameters */,
99 const SkeletonStateT<T>& /* state */,
100 const MeshStateT<T>& meshState) {
102
103 MT_CHECK_NOTNULL(meshState.posedMesh_);
104
105 // loop over all constraints and calculate the error
106 double error = 0.0;
107
108 if (constraintType_ == VertexConstraintType::Position) {
109 for (size_t i = 0; i < constraints_.size(); ++i) {
110 const PointTriangleVertexConstraintT<T>& constr = constraints_[i];
111
112 const Eigen::Vector3<T> srcPoint = meshState.posedMesh_->vertices[constr.srcVertexIndex];
113 const Eigen::Vector3<T> tgtPoint = computeTargetPosition(*meshState.posedMesh_, constr);
114 const Eigen::Vector3<T> diff = srcPoint - tgtPoint;
115 error += constr.weight * diff.squaredNorm() * kPositionWeight;
116 }
117 } else {
118 const auto [sourceNormalWeight, targetNormalWeight] = computeNormalWeights();
119 for (size_t i = 0; i < constraints_.size(); ++i) {
120 const PointTriangleVertexConstraintT<T>& constr = constraints_[i];
121
122 const Eigen::Vector3<T> srcPoint = meshState.posedMesh_->vertices[constr.srcVertexIndex];
123
124 const Eigen::Vector3<T> sourceNormal = meshState.posedMesh_->normals[constr.srcVertexIndex];
125 Eigen::Vector3<T> targetNormal = computeTargetTriangleNormal(*meshState.posedMesh_, constr);
126
127 const Eigen::Vector3<T> tgtPoint =
128 computeTargetBaryPosition(*meshState.posedMesh_, constr) + constr.depth * targetNormal;
129
130 if (sourceNormal.dot(targetNormal) < 0) {
131 targetNormal *= -1;
132 }
133 const Eigen::Vector3<T> normal =
134 sourceNormalWeight * sourceNormal + targetNormalWeight * targetNormal;
135
136 // calculate point->plane distance and error
137 const Eigen::Vector3<T> diff = srcPoint - tgtPoint;
138 const T dist = normal.dot(diff);
139 error += constr.weight * dist * dist * kPlaneWeight;
140 }
141 }
142
143 // return error
144 return error * this->weight_;
145}
146
147template <typename T>
149 const T grad_jointParams,
150 const Eigen::Index iJointParam,
151 const ParameterTransform& parameterTransform,
152 Eigen::Ref<Eigen::VectorX<T>> gradient) {
153 // explicitly multiply with the parameter transform to generate parameter space gradients
154 for (auto index = parameterTransform.transform.outerIndexPtr()[iJointParam];
155 index < parameterTransform.transform.outerIndexPtr()[iJointParam + 1];
156 ++index) {
157 gradient[parameterTransform.transform.innerIndexPtr()[index]] +=
158 grad_jointParams * parameterTransform.transform.valuePtr()[index];
159 }
160}
161
162template <typename T>
164 const T jacobian_jointParams,
165 const Eigen::Index iJointParam,
166 const ParameterTransform& parameterTransform,
167 Eigen::Ref<Eigen::MatrixX<T>> jacobian) {
168 // explicitly multiply with the parameter transform to generate parameter space gradients
169 for (auto index = parameterTransform.transform.outerIndexPtr()[iJointParam];
170 index < parameterTransform.transform.outerIndexPtr()[iJointParam + 1];
171 ++index) {
172 jacobian(0, parameterTransform.transform.innerIndexPtr()[index]) +=
173 jacobian_jointParams * parameterTransform.transform.valuePtr()[index];
174 }
175}
176
177template <typename T>
178Eigen::Vector3<T> calculateDWorldPos(
179 const momentum::Character& character,
180 const SkeletonStateT<T>& state,
181 const int vertexIndex,
182 const Eigen::Vector3<T>& d_restPos) {
183 const auto& skinWeights = *character.skinWeights;
184
185 Eigen::Vector3<T> d_worldPos = Eigen::Vector3<T>::Zero();
186 for (uint32_t i = 0; i < kMaxSkinJoints; ++i) {
187 const auto w = skinWeights.weight(vertexIndex, i);
188 const auto parentBone = skinWeights.index(vertexIndex, i);
189 if (w > 0) {
191 parentBone >= state.jointState.size() || parentBone >= character.inverseBindPose.size(),
192 "Parent bone index {} exceeds jointState size {} or inverseBindPose size {}",
193 parentBone,
194 state.jointState.size(),
195 character.inverseBindPose.size());
196 d_worldPos += w *
197 (state.jointState[parentBone].transform.toLinear() *
198 (character.inverseBindPose[parentBone].linear().template cast<T>() * d_restPos));
199 }
200 }
201
202 return d_worldPos;
203}
204
205template <typename T>
206std::array<Eigen::Matrix3<T>, 3> compute_d_targetNormal_d_vertexPos(
208 const MeshT<T>& mesh) {
209 std::array<Eigen::Matrix3<T>, 3> result;
210 for (auto& r : result) {
211 r.setZero();
212 }
213
214 const std::array<Eigen::Vector3<T>, 3> tgtTrianglePositions = {
215 mesh.vertices[cons.tgtTriangleIndices[0]],
216 mesh.vertices[cons.tgtTriangleIndices[1]],
217 mesh.vertices[cons.tgtTriangleIndices[2]]};
218
219 Eigen::Vector3<T> n = (tgtTrianglePositions[1] - tgtTrianglePositions[0])
220 .cross(tgtTrianglePositions[2] - tgtTrianglePositions[0]);
221 T n_norm = n.norm();
222 if (n_norm < 1e-6) {
223 // ignore normal gradients
224 return result;
225 }
226 n /= n_norm;
227
228 const T area_times_2 = n_norm;
229
230 for (int k = 0; k < 3; ++k) {
231 // https://www.cs.cmu.edu/~kmcrane/Projects/Other/TriangleMeshDerivativesCheatSheet.pdf
232 const Eigen::Vector3<T> e =
233 tgtTrianglePositions[(k + 2) % 3] - tgtTrianglePositions[(k + 1) % 3];
234 result[k] += (e.cross(n) * n.transpose()) / area_times_2;
235 }
236
237 return result;
238}
239
240template <typename T>
241std::array<Eigen::Matrix3<T>, 3> compute_d_targetPos_d_vertexPos(
243 const MeshT<T>& mesh) {
244 std::array<Eigen::Matrix3<T>, 3> result;
245 result[0] = Eigen::Matrix3<T>::Identity() * cons.tgtTriangleBaryCoords[0];
246 result[1] = Eigen::Matrix3<T>::Identity() * cons.tgtTriangleBaryCoords[1];
247 result[2] = Eigen::Matrix3<T>::Identity() * cons.tgtTriangleBaryCoords[2];
248
249 const auto dNormal = compute_d_targetNormal_d_vertexPos(cons, mesh);
250 for (int k = 0; k < 3; ++k) {
251 result[k] += cons.depth * dNormal[k];
252 }
253
254 return result;
255}
256
257template <typename T>
258double PointTriangleVertexErrorFunctionT<T>::calculatePositionGradient(
259 const ModelParametersT<T>& /* modelParameters */,
260 const SkeletonStateT<T>& state,
261 const MeshStateT<T>& meshState,
262 const PointTriangleVertexConstraintT<T>& constr,
263 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
264 const Eigen::Vector3<T> srcPos = meshState.posedMesh_->vertices[constr.srcVertexIndex];
265 const Eigen::Vector3<T> tgtPos = computeTargetPosition(*meshState.posedMesh_, constr);
266
267 const Eigen::Vector3<T> diff = srcPos - tgtPos;
268
269 // calculate the difference between target and position and error
270 const T wgt = constr.weight * 2.0f * kPositionWeight * this->weight_;
271
272 const auto d_targetPos_d_tgtTriVertexPos =
273 compute_d_targetPos_d_vertexPos(constr, *meshState.posedMesh_);
274
275 // weightedResidual = 2 * weight * loss_deriv * f
276 // For position: f = diff, loss = 0.5 * f^2, loss_deriv = 1
277 // So weightedResidual = 2 * weight * diff (already scaled by wgt)
278 const Eigen::Vector3<T> weightedResidual = wgt * diff;
279
280 SkeletonDerivativeT<T> skeletonDerivative(
281 this->skeleton_,
282 this->parameterTransform_,
283 this->activeJointParams_,
284 this->enabledParameters_);
285
286 // To simplify things we'll have one loop that goes through all 3 target triangle vertices _and_
287 // the source vertex.
288 // iter 0-2: target triangle vertices
289 // iter 3: source vertex
290 for (int iTriVert = 0; iTriVert < 4; ++iTriVert) {
291 const auto vertexIndex =
292 iTriVert < 3 ? constr.tgtTriangleIndices[iTriVert] : constr.srcVertexIndex;
293 const Eigen::Vector3<T>& vertexPos = meshState.posedMesh_->vertices[vertexIndex];
294
295 // Flip sign for the target vertex since the actual error is (srcPoint - tgtPoint)
296 const Eigen::Matrix3<T> dfdv = iTriVert < 3
297 ? Eigen::Matrix3<T>(-d_targetPos_d_tgtTriVertexPos[iTriVert])
298 : Eigen::Matrix3<T>::Identity();
299
300 skeletonDerivative.template accumulateVertexGradient<3>(
301 vertexIndex, vertexPos, dfdv, weightedResidual, state, meshState, character_, gradient);
302 }
303
304 return constr.weight * diff.squaredNorm() * kPositionWeight;
305}
306
307template <typename T>
308double PointTriangleVertexErrorFunctionT<T>::calculatePositionJacobian(
309 const ModelParametersT<T>& /* modelParameters */,
310 const SkeletonStateT<T>& state,
311 const MeshStateT<T>& meshState,
313 Ref<Eigen::MatrixX<T>> jac,
314 Ref<Eigen::VectorX<T>> res) const {
315 // calculate the difference between target and position and error
316 const Eigen::Vector3<T> tgtPos = computeTargetPosition(*meshState.posedMesh_, constr);
317
318 const Eigen::Vector3<T> diff = meshState.posedMesh_->vertices[constr.srcVertexIndex] - tgtPos;
319
320 const T wgt = std::sqrt(constr.weight * kPositionWeight * this->weight_);
321
322 const auto d_targetPos_d_tgtTriVertexPos =
323 compute_d_targetPos_d_vertexPos(constr, *meshState.posedMesh_);
324
325 SkeletonDerivativeT<T> skeletonDerivative(
326 this->skeleton_,
327 this->parameterTransform_,
328 this->activeJointParams_,
329 this->enabledParameters_);
330
331 // To simplify things we'll have one loop that goes through all 3 target triangle vertices _and_
332 // the source vertex.
333 // iter 0-2: target triangle vertices
334 // iter 3: source vertex
335 for (int iTriVert = 0; iTriVert < 4; ++iTriVert) {
336 const auto vertexIndex =
337 iTriVert < 3 ? constr.tgtTriangleIndices[iTriVert] : constr.srcVertexIndex;
338 const Eigen::Vector3<T>& vertexPos = meshState.posedMesh_->vertices[vertexIndex];
339
340 // Flip sign for the target vertex since the actual error is (srcPoint - tgtPoint)
341 const Eigen::Matrix3<T> dfdv = iTriVert < 3
342 ? Eigen::Matrix3<T>(-d_targetPos_d_tgtTriVertexPos[iTriVert])
343 : Eigen::Matrix3<T>::Identity();
344
345 skeletonDerivative.template accumulateVertexJacobian<3>(
346 vertexIndex, vertexPos, dfdv, wgt, state, meshState, character_, jac, 0);
347 }
348
349 res = diff * wgt;
350
351 return wgt * wgt * diff.squaredNorm();
352}
353
354template <typename T>
355double PointTriangleVertexErrorFunctionT<T>::calculateNormalGradient(
356 const ModelParametersT<T>& /* modelParameters */,
357 const SkeletonStateT<T>& state,
358 const MeshStateT<T>& meshState,
360 const T sourceNormalWeight,
361 const T targetNormalWeight,
362 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
363 const Eigen::Vector3<T> sourceNormal = meshState.posedMesh_->normals[constr.srcVertexIndex];
364 Eigen::Vector3<T> targetNormal = computeTargetTriangleNormal(*meshState.posedMesh_, constr);
365 const Eigen::Vector3<T> tgtPosition = computeTargetPosition(*meshState.posedMesh_, constr);
366
367 T targetNormalSign = 1;
368 if (sourceNormal.dot(targetNormal) < 0) {
369 targetNormal *= -1;
370 targetNormalSign = -1;
371 }
372 const Eigen::Vector3<T> normal =
373 sourceNormalWeight * sourceNormal + targetNormalWeight * targetNormal;
374
375 // calculate the difference between target and position and error
376 const Eigen::Vector3<T> diff =
377 meshState.posedMesh_->vertices[constr.srcVertexIndex] - tgtPosition;
378 const T dist = diff.dot(normal);
379
380 const T wgt = constr.weight * 2.0f * kPlaneWeight * this->weight_;
381
382 const auto d_targetPos_d_tgtTriVertexPos =
383 compute_d_targetPos_d_vertexPos(constr, *meshState.posedMesh_);
384 const auto d_targetNormal_d_tgtTriVertexPos =
385 compute_d_targetNormal_d_vertexPos(constr, *meshState.posedMesh_);
386
387 for (int iTriVert = 0; iTriVert < 4; ++iTriVert) {
388 const auto vertexIndex =
389 iTriVert < 3 ? constr.tgtTriangleIndices[iTriVert] : constr.srcVertexIndex;
390 // Flip sign for the target vertex since the actual error is (srcPoint - tgtPoint)
391 const Eigen::Matrix3<T> d_targetPos_d_vertexPos = iTriVert < 3
392 ? Eigen::Matrix3<T>(-d_targetPos_d_tgtTriVertexPos[iTriVert])
393 : Eigen::Matrix3<T>::Identity();
394
395 SkinningWeightIteratorT<T> skinningIter(
396 this->character_, *meshState.restMesh_, state, vertexIndex);
397
398 // IN handle derivatives wrt jointParameters
399 while (!skinningIter.finished()) {
400 const auto [jointIndex, boneWeight, pos] = skinningIter.next();
401
402 // check for valid index
403 MT_CHECK(jointIndex < this->skeleton_.joints.size());
404
405 const auto& jointState = state.jointState[jointIndex];
406 const size_t paramIndex = jointIndex * kParametersPerJoint;
407 const Eigen::Vector3<T> posd = pos - jointState.translation();
408
409 // calculate derivatives based on active joints
410 for (size_t d = 0; d < 3; d++) {
411 if (this->activeJointParams_[paramIndex + d]) {
412 // Gradient wrt translation:
414 boneWeight * dist *
415 normal.dot(d_targetPos_d_vertexPos * jointState.getTranslationDerivative(d)) *
416 wgt,
417 paramIndex + d,
418 this->parameterTransform_,
419 gradient);
420 }
421 if (this->activeJointParams_[paramIndex + 3 + d]) {
422 // Error is (p_src - p_tgt) . (w_src * n_src + w_tgt * n_tgt)
423 // Full derivative will be:
424 // (d/dTheta (p_src - p_tgt)) . (w_src * n_src + w_tgt * n_tgt) +
425 // (p_src - p_tgt) . (w_src * dn_src/dTheta) +
426 // (p_src - p_tgt) . (w_tgt * dn_tgt/dTheta))
427
428 // Jacobian wrt rotation:
429 T diff_total =
430 normal.dot(d_targetPos_d_vertexPos * jointState.getRotationDerivative(d, posd));
431
432 if (iTriVert < 3) {
433 const Eigen::Vector3<T> diff_tgt_normal = targetNormalSign *
434 d_targetNormal_d_tgtTriVertexPos[iTriVert] *
435 jointState.getRotationDerivative(d, posd);
436 diff_total += targetNormalWeight * diff.dot(diff_tgt_normal);
437 } else {
438 // Jacobian wrt rotation:
439 const Eigen::Vector3<T> diff_src_normal =
440 jointState.getRotationDerivative(d, sourceNormal);
441 diff_total += sourceNormalWeight * diff.dot(diff_src_normal);
442 }
443
445 boneWeight * wgt * diff_total * dist,
446 paramIndex + d + 3,
447 this->parameterTransform_,
448 gradient);
449 }
450 }
451 if (this->activeJointParams_[paramIndex + 6]) {
452 // Jacobian wrt scale:
454 boneWeight * wgt *
455 normal.dot(d_targetPos_d_vertexPos * jointState.getScaleDerivative(posd)) * dist,
456 paramIndex + 6,
457 this->parameterTransform_,
458 gradient);
459 }
460 }
461 // OUT handle derivatives wrt jointParameters
462
463 // IN handle derivatives wrt blend shape parameters:
464 for (Eigen::Index iBlendShape = 0;
465 iBlendShape < this->parameterTransform_.blendShapeParameters.size();
466 ++iBlendShape) {
467 const auto paramIdx = this->parameterTransform_.blendShapeParameters[iBlendShape];
468 if (paramIdx < 0) {
469 continue;
470 }
471
472 const Eigen::Vector3<T> d_restPos =
473 this->character_.blendShape->getShapeVectors()
474 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
475 .template cast<T>();
476 Eigen::Vector3<T> d_worldPos = calculateDWorldPos(character_, state, vertexIndex, d_restPos);
477
478 gradient(paramIdx) += wgt * dist * normal.dot(d_targetPos_d_vertexPos * d_worldPos);
479 if (iTriVert < 3) {
480 const Eigen::Vector3<T> diff_tgt_normal =
481 d_targetNormal_d_tgtTriVertexPos[iTriVert] * d_worldPos;
482 gradient(paramIdx) += targetNormalSign * wgt * dist * diff.dot(diff_tgt_normal);
483 }
484 }
485 // OUT handle derivatives wrt blend shape parameters:
486 }
487
488 return constr.weight * dist * dist * kPlaneWeight;
489}
490
491template <typename T>
492double PointTriangleVertexErrorFunctionT<T>::calculateNormalJacobian(
493 const ModelParametersT<T>& /* modelParameters */,
494 const SkeletonStateT<T>& state,
495 const MeshStateT<T>& meshState,
497 const T sourceNormalWeight,
498 const T targetNormalWeight,
499 Ref<Eigen::MatrixX<T>> jac,
500 T& res) const {
501 const Eigen::Vector3<T> sourceNormal = meshState.posedMesh_->normals[constr.srcVertexIndex];
502 Eigen::Vector3<T> targetNormal = computeTargetTriangleNormal(*meshState.posedMesh_, constr);
503 const Eigen::Vector3<T> tgtPosition = computeTargetPosition(*meshState.posedMesh_, constr);
504
505 T targetNormalSign = 1;
506 if (sourceNormal.dot(targetNormal) < 0) {
507 targetNormal *= -1;
508 targetNormalSign = -1;
509 }
510 const Eigen::Vector3<T> normal =
511 sourceNormalWeight * sourceNormal + targetNormalWeight * targetNormal;
512
513 // calculate the difference between target and position and error
514 const Eigen::Vector3<T> diff =
515 meshState.posedMesh_->vertices[constr.srcVertexIndex] - tgtPosition;
516 const T dist = diff.dot(normal);
517
518 const T wgt = std::sqrt(constr.weight * kPositionWeight * this->weight_);
519
520 const auto d_targetPos_d_tgtTriVertexPos =
521 compute_d_targetPos_d_vertexPos(constr, *meshState.posedMesh_);
522 const auto d_targetNormal_d_tgtTriVertexPos =
523 compute_d_targetNormal_d_vertexPos(constr, *meshState.posedMesh_);
524
525 for (int iTriVert = 0; iTriVert < 4; ++iTriVert) {
526 const auto vertexIndex =
527 iTriVert < 3 ? constr.tgtTriangleIndices[iTriVert] : constr.srcVertexIndex;
528 // Flip sign for the target vertex since the actual error is (srcPoint - tgtPoint)
529 const Eigen::Matrix3<T> d_targetPos_d_vertexPos = iTriVert < 3
530 ? Eigen::Matrix3<T>(-d_targetPos_d_tgtTriVertexPos[iTriVert])
531 : Eigen::Matrix3<T>::Identity();
532
533 SkinningWeightIteratorT<T> skinningIter(
534 this->character_, *meshState.restMesh_, state, vertexIndex);
535
536 // IN handle derivatives wrt jointParameters
537 while (!skinningIter.finished()) {
538 const auto [jointIndex, boneWeight, pos] = skinningIter.next();
539
540 // check for valid index
541 MT_CHECK(jointIndex < this->skeleton_.joints.size());
542
543 const auto& jointState = state.jointState[jointIndex];
544 const size_t paramIndex = jointIndex * kParametersPerJoint;
545 const Eigen::Vector3<T> posd = pos - jointState.translation();
546
547 // calculate derivatives based on active joints
548 for (size_t d = 0; d < 3; d++) {
549 if (this->activeJointParams_[paramIndex + d]) {
550 // Jacobian wrt translation:
552 boneWeight * wgt *
553 normal.dot(d_targetPos_d_vertexPos * jointState.getTranslationDerivative(d)),
554 paramIndex + d,
555 this->parameterTransform_,
556 jac);
557 }
558 if (this->activeJointParams_[paramIndex + 3 + d]) {
559 // Error is (p_src - p_tgt) . (w_src * n_src + w_tgt * n_tgt)
560 // Full derivative will be:
561 // (d/dTheta (p_src - p_tgt)) . (w_src * n_src + w_tgt * n_tgt) +
562 // (p_src - p_tgt) . (w_src * dn_src/dTheta) +
563 // (p_src - p_tgt) . (w_tgt * dn_tgt/dTheta))
564
565 // Jacobian wrt rotation:
566 T diff_total =
567 normal.dot(d_targetPos_d_vertexPos * jointState.getRotationDerivative(d, posd));
568
569 if (iTriVert < 3) {
570 const Eigen::Vector3<T> diff_tgt_normal = targetNormalSign *
571 d_targetNormal_d_tgtTriVertexPos[iTriVert] *
572 jointState.getRotationDerivative(d, posd);
573 diff_total += targetNormalWeight * diff.dot(diff_tgt_normal);
574 } else {
575 // Jacobian wrt rotation:
576 const Eigen::Vector3<T> diff_src_normal =
577 jointState.getRotationDerivative(d, sourceNormal);
578 diff_total += sourceNormalWeight * diff.dot(diff_src_normal);
579 }
580
582 boneWeight * wgt * diff_total, paramIndex + d + 3, this->parameterTransform_, jac);
583 }
584 }
585 if (this->activeJointParams_[paramIndex + 6]) {
586 // Jacobian wrt scale:
588 boneWeight * wgt *
589 normal.dot(d_targetPos_d_vertexPos * jointState.getScaleDerivative(posd)),
590 paramIndex + 6,
591 this->parameterTransform_,
592 jac);
593 }
594 }
595 // OUT handle derivatives wrt jointParameters
596
597 // IN handle derivatives wrt blend shape parameters:
598 for (Eigen::Index iBlendShape = 0;
599 iBlendShape < this->parameterTransform_.blendShapeParameters.size();
600 ++iBlendShape) {
601 const auto paramIdx = this->parameterTransform_.blendShapeParameters[iBlendShape];
602 if (paramIdx < 0) {
603 continue;
604 }
605
606 const Eigen::Vector3<T> d_restPos =
607 this->character_.blendShape->getShapeVectors()
608 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
609 .template cast<T>();
610 Eigen::Vector3<T> d_worldPos = calculateDWorldPos(character_, state, vertexIndex, d_restPos);
611
612 jac(0, paramIdx) += wgt * normal.dot(d_targetPos_d_vertexPos * d_worldPos);
613 if (iTriVert < 3) {
614 const Eigen::Vector3<T> diff_tgt_normal =
615 d_targetNormal_d_tgtTriVertexPos[iTriVert] * d_worldPos;
616 jac(0, paramIdx) += targetNormalSign * wgt * diff.dot(diff_tgt_normal);
617 }
618 }
619 // OUT handle derivatives wrt blend shape parameters:
620 }
621
622 res = dist * wgt;
623
624 return wgt * wgt * dist * dist;
625}
626
627template <typename T>
628std::pair<T, T> PointTriangleVertexErrorFunctionT<T>::computeNormalWeights() const {
629 switch (constraintType_) {
631 return {T(0), T(1)};
633 return {T(1), T(0)};
635 default:
636 return {T(0.5), T(0.5)};
637 }
638}
639
640template <typename T>
642 const ModelParametersT<T>& modelParameters,
643 const SkeletonStateT<T>& state,
644 const MeshStateT<T>& meshState,
645 Eigen::Ref<Eigen::VectorX<T>> gradient) {
646 MT_CHECK_NOTNULL(meshState.posedMesh_);
647
648 double error = 0;
649
650 if (constraintType_ == VertexConstraintType::Position) {
651 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
652 error += calculatePositionGradient(
653 modelParameters, state, meshState, constraints_[iCons], gradient);
654 }
655 } else {
656 T sourceNormalWeight;
657 T targetNormalWeight;
658 std::tie(sourceNormalWeight, targetNormalWeight) = computeNormalWeights();
659
660 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
661 error += calculateNormalGradient(
662 modelParameters,
663 state,
664 meshState,
665 constraints_[iCons],
666 sourceNormalWeight,
667 targetNormalWeight,
668 gradient);
669 }
670 }
671
672 return this->weight_ * error;
673}
674
675template <typename T>
677 const ModelParametersT<T>& modelParameters,
678 const SkeletonStateT<T>& state,
679 const MeshStateT<T>& meshState,
680 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
681 Eigen::Ref<Eigen::VectorX<T>> residual,
682 int& usedRows) {
683 MT_CHECK(
684 jacobian.cols() == static_cast<Eigen::Index>(this->parameterTransform_.transform.cols()));
685 MT_CHECK(jacobian.rows() >= (Eigen::Index)(1 * constraints_.size()));
686 MT_CHECK(residual.rows() >= (Eigen::Index)(1 * constraints_.size()));
687
688 MT_CHECK_NOTNULL(meshState.posedMesh_);
689
690 double error = 0;
691
692 if (constraintType_ == VertexConstraintType::Position) {
693 MT_PROFILE_EVENT("VertexErrorFunction - position jacobians");
694
695 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
696 error += calculatePositionJacobian(
697 modelParameters,
698 state,
699 meshState,
700 constraints_[iCons],
701 jacobian.block(3 * iCons, 0, 3, modelParameters.size()),
702 residual.middleRows(3 * iCons, 3));
703 }
704 usedRows = static_cast<int>(3 * constraints_.size());
705 } else {
706 MT_PROFILE_EVENT("VertexErrorFunction - normal jacobians");
707 T sourceNormalWeight;
708 T targetNormalWeight;
709 std::tie(sourceNormalWeight, targetNormalWeight) = computeNormalWeights();
710
711 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
712 error += calculateNormalJacobian(
713 modelParameters,
714 state,
715 meshState,
716 constraints_[iCons],
717 sourceNormalWeight,
718 targetNormalWeight,
719 jacobian.block(iCons, 0, 1, modelParameters.size()),
720 residual(iCons));
721 }
722
723 usedRows = static_cast<int>(constraints_.size());
724 }
725
726 return error;
727}
728
729template <typename T>
731 switch (constraintType_) {
733 return 3 * constraints_.size();
737 default:
738 return constraints_.size();
739 }
740}
741
744
745} // namespace momentum
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
Support constraining different parts of the mesh together by specifying that a source vertex should t...
PointTriangleVertexErrorFunctionT(const Character &character, VertexConstraintType type=VertexConstraintType::Position)
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
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 vertexIndex, const Eigen::Vector3i &triangleIndices, const Eigen::Vector3< T > &triangleBaryCoords, float depth=0, T weight=1)
Shared utility for derivative computation in error functions.
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
#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).
Definition types.h:28
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::Matrix< T, 3, 3 > Matrix3
Definition types.h:96
void jacobian_jointParams_to_modelParams(const Eigen::Ref< const Eigen::VectorX< T > > &jacobian_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::MatrixX< T > > jacobian)
Eigen::Ref< T > Ref
Definition types.h:43
Eigen::Vector3< T > computeTargetPosition(const MeshT< T > &mesh, const PointTriangleVertexConstraintT< T > &c)
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
void gradient_jointParams_to_modelParams(const T &grad_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::VectorX< T > > gradient)
Eigen::Vector3< T > calculateDWorldPos(const momentum::Character &character, const SkeletonStateT< T > &state, const int vertexIndex, const Eigen::Vector3< T > &d_restPos)
Eigen::Vector3< T > computeTargetTriangleNormal(const MeshT< T > &mesh, const PointTriangleVertexConstraintT< T > &c)
constexpr size_t kParametersPerJoint
Definition types.h:21
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
std::string_view toString(const LimitType type)
constexpr uint32_t kMaxSkinJoints
Maximum number of joints that can influence a single vertex.
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_EVENT(NAME)
Definition profile.h:112
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
TransformationList inverseBindPose
Inverse of the bind pose transformations for each joint.
Definition character.h:76
SkinWeights_u skinWeights
Defines how mesh vertices are influenced by joints.
Definition character.h:58
BlendShapeBase_const_p faceExpressionBlendShape
Facial expression blend shapes.
Definition character.h:73
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 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
SparseRowMatrix< T > transform
The sparse mapping matrix that maps model parameters to joint parameters.
Represents the complete state of a skeleton.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.