Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
state_sequence_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
17namespace momentum {
18
19namespace {
20
33template <typename T>
34Vector3<T> quaternionLogMapRelativeDerivativeQ1(
35 const Quaternion<T>& q1,
36 const Quaternion<T>& q2,
37 const Vector3<T>& dir,
38 const Eigen::Matrix<T, 3, 4>& dLogDq) {
39 const Vector3<T> vHalf = dir / T(2);
40
41 // Compute d/dt [exp(t*v) * q1]|_{t=0} = [0, v/2] * q1
42 const Vector3<T> q1_vec(q1.x(), q1.y(), q1.z());
43 const T dq1_w = -vHalf.dot(q1_vec);
44 const Vector3<T> dq1_vec = vHalf * q1.w() + vHalf.cross(q1_vec);
45
46 // Then multiply by q2^{-1} on the left: q2^{-1} * [dq1_w, dq1_vec]
47 const Vector3<T> q2_vec(q2.x(), q2.y(), q2.z());
48 const T dqRel_w = q2.w() * dq1_w - (-q2_vec).dot(dq1_vec);
49 const Vector3<T> dqRel_vec = q2.w() * dq1_vec + dq1_w * (-q2_vec) + (-q2_vec).cross(dq1_vec);
50
51 // Apply chain rule: d(log)/d(t) = d(log)/d(q_rel) * d(q_rel)/d(t)
52 Eigen::Vector4<T> dqRelDt;
53 dqRelDt << dqRel_vec, dqRel_w;
54 return dLogDq * dqRelDt;
55}
56
58template <typename T>
59Vector3<T> quaternionLogMapRelativeDerivativeQ2(
60 const Quaternion<T>& q1,
61 const Quaternion<T>& q2,
62 const Vector3<T>& dir,
63 const Eigen::Matrix<T, 3, 4>& dLogDq) {
64 const Vector3<T> vHalf = dir / T(2);
65
66 // Compute q2^{-1} * [0, v/2]
67 const Vector3<T> q2_vec(q2.x(), q2.y(), q2.z());
68 const Vector3<T> q2inv_vec = -q2_vec;
69 const T temp_w = -q2inv_vec.dot(vHalf);
70 const Vector3<T> temp_vec = q2.w() * vHalf + q2inv_vec.cross(vHalf);
71
72 // Then multiply by q1 on the right: [temp_w, temp_vec] * q1
73 const Vector3<T> q1_vec(q1.x(), q1.y(), q1.z());
74 const T dqRel_w = temp_w * q1.w() - temp_vec.dot(q1_vec);
75 const Vector3<T> dqRel_vec = temp_w * q1_vec + q1.w() * temp_vec + temp_vec.cross(q1_vec);
76
77 // Apply chain rule with negative sign from derivative of inverse
78 Eigen::Vector4<T> dqRelDt;
79 dqRelDt << -dqRel_vec, -dqRel_w;
80 return dLogDq * dqRelDt;
81}
82
96template <typename T>
97T computeLogMapRotationGradientPrev(
98 const Quaternion<T>& prevRot,
99 const Quaternion<T>& nextRot,
100 const Quaternion<T>& targetRot,
101 const Vector3<T>& axis,
102 const Eigen::Matrix<T, 3, 4>& dLogDq) {
103 const Quaternion<T> transformedPrevRot = targetRot * prevRot;
104 const Quaternion<T> qRel = nextRot.conjugate() * transformedPrevRot;
105 const Vector3<T> logmapVec = quaternionLogMap(qRel);
106 const Vector3<T> transformedAxis = targetRot * axis;
107 const Vector3<T> jacobian =
108 quaternionLogMapRelativeDerivativeQ1(transformedPrevRot, nextRot, transformedAxis, dLogDq);
109 return T(2) * logmapVec.dot(jacobian);
110}
111
118template <typename T>
119T computeLogMapRotationGradientNext(
120 const Quaternion<T>& transformedPrevRot,
121 const Quaternion<T>& nextRot,
122 const Vector3<T>& axis,
123 const Eigen::Matrix<T, 3, 4>& dLogDq) {
124 const Quaternion<T> qRel = nextRot.conjugate() * transformedPrevRot;
125 const Vector3<T> logmapVec = quaternionLogMap(qRel);
126 const Vector3<T> jacobian =
127 quaternionLogMapRelativeDerivativeQ2(transformedPrevRot, nextRot, axis, dLogDq);
128 return T(2) * logmapVec.dot(jacobian);
129}
130
134template <typename T>
135T computeMatrixDiffRotationGradientPrev(
136 const Quaternion<T>& prevRot,
137 const Quaternion<T>& targetRot,
138 const Vector3<T>& axis,
139 const Matrix3<T>& rotDiff) {
140 const auto rotD = targetRot * crossProductMatrix(axis) * prevRot;
141 return -T(2) * rotD.cwiseProduct(rotDiff).sum();
142}
143
146template <typename T>
147T computeMatrixDiffRotationGradientNext(
148 const Quaternion<T>& nextRot,
149 const Vector3<T>& axis,
150 const Matrix3<T>& rotDiff) {
151 const auto rotD = crossProductMatrix(axis) * nextRot;
152 return T(2) * rotD.cwiseProduct(rotDiff).sum();
153}
154
162template <typename T>
163Eigen::Matrix<T, 3, 1> computeLogMapRotationJacobianPrev(
164 const Quaternion<T>& prevRot,
165 const Quaternion<T>& nextRot,
166 const Quaternion<T>& targetRot,
167 const Vector3<T>& axis,
168 T weight,
169 const Eigen::Matrix<T, 3, 4>& dLogDq) {
170 const Quaternion<T> transformedPrevRot = targetRot * prevRot;
171 const Vector3<T> transformedAxis = targetRot * axis;
172 return weight *
173 quaternionLogMapRelativeDerivativeQ1(transformedPrevRot, nextRot, transformedAxis, dLogDq);
174}
175
183template <typename T>
184Eigen::Matrix<T, 3, 1> computeLogMapRotationJacobianNext(
185 const Quaternion<T>& transformedPrevRot,
186 const Quaternion<T>& nextRot,
187 const Vector3<T>& axis,
188 T weight,
189 const Eigen::Matrix<T, 3, 4>& dLogDq) {
190 return weight * quaternionLogMapRelativeDerivativeQ2(transformedPrevRot, nextRot, axis, dLogDq);
191}
192
196template <typename T>
197Eigen::Matrix<T, 9, 1> computeMatrixDiffRotationJacobianPrev(
198 const Quaternion<T>& prevRot,
199 const Quaternion<T>& targetRot,
200 const Vector3<T>& axis,
201 T weight) {
202 const Eigen::Matrix3<T> rotD = -(targetRot * crossProductMatrix(axis) * prevRot) * weight;
203 return Map<const Eigen::Matrix<T, 9, 1>>(rotD.data(), rotD.size());
204}
205
207template <typename T>
208Eigen::Matrix<T, 9, 1>
209computeMatrixDiffRotationJacobianNext(const Quaternion<T>& rot, const Vector3<T>& axis, T weight) {
210 const Eigen::Matrix3<T> rotD = crossProductMatrix(axis) * rot * weight;
211 return Map<const Eigen::Matrix<T, 9, 1>>(rotD.data(), rotD.size());
212}
213
216enum class StateType { Prev, Next };
217
219template <typename T>
220struct GradientComputationParams {
221 size_t jointIndex{kInvalidIndex};
222 const TransformT<T>& targetTransform;
223 const Eigen::Quaternion<T>& prevRot;
224 const Eigen::Quaternion<T>& nextRot;
225 const Eigen::Vector3<T>& diff;
226 T pwgt{0};
227 T rwgt{0};
229 const Eigen::Matrix3<T>& rotDiff;
230 const Eigen::Matrix<T, 3, 4>& dLogDq;
231};
232
234template <typename T>
235void computeStateGradient(
236 StateType stateType,
237 const GradientComputationParams<T>& params,
238 const SkeletonStateT<T>& state,
239 const SkeletonStateT<T>& prevState,
240 const Skeleton& skeleton,
241 const Eigen::VectorX<bool>& activeJointParams,
242 const ParameterTransform& parameterTransform,
243 Eigen::Ref<Eigen::VectorX<T>> gradientSegment) {
244 const bool isPrev = (stateType == StateType::Prev);
245 const T posSign = isPrev ? T(-2) : T(2);
246
247 size_t ancestorJointIndex = params.jointIndex;
248 while (ancestorJointIndex != kInvalidIndex) {
249 const size_t paramIndex = ancestorJointIndex * kParametersPerJoint;
250 const Eigen::Vector3<T> posd = state.jointState[params.jointIndex].translation() -
251 state.jointState[ancestorJointIndex].translation();
252
253 for (size_t d = 0; d < 3; d++) {
254 if (activeJointParams[paramIndex + d]) {
255 const auto& jointState = state.jointState[ancestorJointIndex];
256 T val;
257 if (isPrev) {
258 val = posSign *
259 params.diff.dot(
260 params.targetTransform.rotate(jointState.getTranslationDerivative(d))) *
261 params.pwgt;
262 } else {
263 val = posSign * params.diff.dot(jointState.getTranslationDerivative(d)) * params.pwgt;
264 }
266 val, paramIndex + d, parameterTransform, gradientSegment);
267 }
268
269 if (activeJointParams[paramIndex + 3 + d]) {
270 const Eigen::Vector3<T> axis = state.jointState[ancestorJointIndex].rotationAxis.col(d);
271 const auto& jointState = state.jointState[ancestorJointIndex];
272
273 T positionErrorGradient;
274 if (isPrev) {
275 positionErrorGradient = posSign *
276 params.diff.dot(
277 params.targetTransform.rotate(jointState.getRotationDerivative(d, posd)));
278 } else {
279 positionErrorGradient =
280 posSign * params.diff.dot(jointState.getRotationDerivative(d, posd)) * params.pwgt;
281 }
282
283 T rotationErrorGradient = T(0);
284 switch (params.rotationErrorType) {
286 if (isPrev) {
287 rotationErrorGradient = computeLogMapRotationGradientPrev(
288 prevState.jointState[params.jointIndex].rotation(),
289 params.nextRot,
290 params.targetTransform.rotation,
291 axis,
292 params.dLogDq);
293 } else {
294 rotationErrorGradient = computeLogMapRotationGradientNext(
295 params.prevRot, params.nextRot, axis, params.dLogDq);
296 }
297 break;
299 if (isPrev) {
300 rotationErrorGradient = computeMatrixDiffRotationGradientPrev(
301 prevState.jointState[params.jointIndex].rotation(),
302 params.targetTransform.rotation,
303 axis,
304 params.rotDiff);
305 } else {
306 rotationErrorGradient = computeMatrixDiffRotationGradientNext(
307 state.jointState[params.jointIndex].rotation(), axis, params.rotDiff);
308 }
309 break;
310 }
311
312 const T val = isPrev
313 ? (params.pwgt * positionErrorGradient + params.rwgt * rotationErrorGradient)
314 : (positionErrorGradient + params.rwgt * rotationErrorGradient);
316 val, paramIndex + 3 + d, parameterTransform, gradientSegment);
317 }
318 }
319
320 if (activeJointParams[paramIndex + 6]) {
321 const auto& jointState = state.jointState[ancestorJointIndex];
322 T val;
323 if (isPrev) {
324 val = posSign *
325 params.diff.dot(params.targetTransform.rotate(jointState.getScaleDerivative(posd))) *
326 params.pwgt;
327 } else {
328 val = posSign * params.diff.dot(jointState.getScaleDerivative(posd)) * params.pwgt;
329 }
331 val, paramIndex + 6, parameterTransform, gradientSegment);
332 }
333
334 ancestorJointIndex = skeleton.joints[ancestorJointIndex].parent;
335 }
336}
337
339template <typename T>
340struct JacobianComputationParams {
341 size_t jointIndex{kInvalidIndex};
342 const TransformT<T>& targetTransform;
343 const Eigen::Quaternion<T>& prevRot;
344 const Eigen::Quaternion<T>& nextRot;
345 T wgt{0};
346 T awgt{0};
347 size_t rotationResidualSize{0};
348 size_t blockSize{0};
350 const Eigen::Matrix<T, 3, 4>& dLogDq;
351};
352
354template <typename T>
355void computeStateJacobian(
356 StateType stateType,
357 const JacobianComputationParams<T>& params,
358 const SkeletonStateT<T>& state,
359 const SkeletonStateT<T>& prevState,
360 const Skeleton& skeleton,
361 const Eigen::VectorX<bool>& activeJointParams,
362 const ParameterTransform& parameterTransform,
363 Eigen::Ref<Eigen::MatrixX<T>> jacobianBlock) {
364 const bool isPrev = (stateType == StateType::Prev);
365
366 size_t ancestorJointIndex = params.jointIndex;
367 while (ancestorJointIndex != kInvalidIndex) {
368 const auto& jointState = state.jointState[ancestorJointIndex];
369 const size_t paramIndex = ancestorJointIndex * kParametersPerJoint;
370 const Eigen::Vector3<T> posd =
371 state.jointState[params.jointIndex].translation() - jointState.translation();
372
373 for (size_t d = 0; d < 3; d++) {
374 if (activeJointParams[paramIndex + d]) {
375 Eigen::Vector3<T> jc;
376 if (isPrev) {
377 jc =
378 -(params.targetTransform.rotate(jointState.getTranslationDerivative(d))) * params.wgt;
379 } else {
380 jc = jointState.getTranslationDerivative(d) * params.wgt;
381 }
383 jc, paramIndex + d, parameterTransform, jacobianBlock.template topRows<3>());
384 }
385
386 if (activeJointParams[paramIndex + 3 + d]) {
387 const Eigen::Vector3<T> axis = state.jointState[ancestorJointIndex].rotationAxis.col(d);
388
389 Eigen::Vector3<T> jc;
390 if (isPrev) {
391 jc = -(params.targetTransform.rotate(jointState.getRotationDerivative(d, posd))) *
392 params.wgt;
393 } else {
394 jc = jointState.getRotationDerivative(d, posd) * params.wgt;
395 }
397 jc, paramIndex + d + 3, parameterTransform, jacobianBlock.template topRows<3>());
398
399 switch (params.rotationErrorType) {
401 Eigen::Matrix<T, 3, 1> rotJac;
402 if (isPrev) {
403 rotJac = computeLogMapRotationJacobianPrev(
404 prevState.jointState[params.jointIndex].rotation(),
405 params.nextRot,
406 params.targetTransform.rotation,
407 axis,
408 params.awgt,
409 params.dLogDq);
410 } else {
411 rotJac = computeLogMapRotationJacobianNext(
412 params.prevRot, params.nextRot, axis, params.awgt, params.dLogDq);
413 }
415 rotJac,
416 paramIndex + d + 3,
417 parameterTransform,
418 jacobianBlock.middleRows(3, params.rotationResidualSize));
419 break;
420 }
422 Eigen::Matrix<T, 9, 1> rotJac;
423 if (isPrev) {
424 rotJac = computeMatrixDiffRotationJacobianPrev(
425 prevState.jointState[params.jointIndex].rotation(),
426 params.targetTransform.rotation,
427 axis,
428 params.awgt);
429 } else {
430 rotJac = computeMatrixDiffRotationJacobianNext(
431 state.jointState[params.jointIndex].rotation(), axis, params.awgt);
432 }
434 rotJac,
435 paramIndex + d + 3,
436 parameterTransform,
437 jacobianBlock.middleRows(3, params.rotationResidualSize));
438 break;
439 }
440 }
441 }
442 }
443
444 if (activeJointParams[paramIndex + 6]) {
445 Eigen::Vector3<T> jc;
446 if (isPrev) {
447 jc = -(params.targetTransform.rotate(jointState.getScaleDerivative(posd))) * params.wgt;
448 } else {
449 jc = jointState.getScaleDerivative(posd) * params.wgt;
450 }
452 jc, paramIndex + 6, parameterTransform, jacobianBlock.template topRows<3>());
453 }
454
455 ancestorJointIndex = skeleton.joints[ancestorJointIndex].parent;
456 }
457}
458
459} // namespace
460
461template <typename T>
463 const Skeleton& skel,
464 const ParameterTransform& pt,
465 RotationErrorType rotationErrorType)
466 : SequenceErrorFunctionT<T>(skel, pt), rotationErrorType_(rotationErrorType) {
467 targetPositionWeights_.setOnes(this->skeleton_.joints.size());
468 targetRotationWeights_.setOnes(this->skeleton_.joints.size());
469 posWgt_ = T(1);
470 rotWgt_ = T(1);
471}
472
473template <typename T>
475 const Character& character,
476 RotationErrorType rotationErrorType)
478 character.skeleton,
479 character.parameterTransform,
480 rotationErrorType) {}
481
482template <typename T>
484 targetPositionWeights_.setOnes(this->skeleton_.joints.size());
485 targetRotationWeights_.setOnes(this->skeleton_.joints.size());
486}
487
488template <typename T>
490 MT_CHECK(target.size() == this->skeleton_.joints.size());
491 targetState_ = target;
492}
493
494template <typename T>
496 const Eigen::VectorX<T>& posWeight,
497 const Eigen::VectorX<T>& rotWeight) {
498 setPositionTargetWeights(posWeight);
499 setRotationTargetWeights(rotWeight);
500}
501
502template <typename T>
503void StateSequenceErrorFunctionT<T>::setPositionTargetWeights(const Eigen::VectorX<T>& posWeight) {
504 MT_CHECK(posWeight.size() == static_cast<Eigen::Index>(this->skeleton_.joints.size()));
505 targetPositionWeights_ = posWeight;
506}
507
508template <typename T>
509void StateSequenceErrorFunctionT<T>::setRotationTargetWeights(const Eigen::VectorX<T>& rotWeight) {
510 MT_CHECK(rotWeight.size() == static_cast<Eigen::Index>(this->skeleton_.joints.size()));
511 targetRotationWeights_ = rotWeight;
512}
513
514template <typename T>
516 std::span<const ModelParametersT<T>> /* modelParameters */,
517 std::span<const SkeletonStateT<T>> skelStates,
518 std::span<const MeshStateT<T>> /* meshStates */) const {
520
521 // loop over all joints and check for smoothness
522 double error = 0.0;
523
524 MT_CHECK(skelStates.size() == 2);
525
526 const auto& prevState = skelStates[0];
527 const auto& nextState = skelStates[1];
528
529 // go over the joint states and calculate the rotation difference contribution on joints that are
530 // at the end
531 for (size_t i = 0; i < this->skeleton_.joints.size(); ++i) {
532 // calculate orientation error based on the selected error type
533 T rotationError = T(0);
534
535 const TransformT<T> targetTransform =
536 (i < targetState_.size()) ? targetState_[i] : TransformT<T>();
537 const TransformT<T> transformedPrev = targetTransform * prevState.jointState[i].transform;
538 const Eigen::Quaternion<T>& prevRot = transformedPrev.rotation;
539 const Eigen::Quaternion<T>& nextRot = nextState.jointState[i].rotation();
540
541 switch (rotationErrorType_) {
543 // Compute the relative rotation: q_rel = nextRot^{-1} * prevRot
544 const Eigen::Quaternion<T> qRel = nextRot.conjugate() * prevRot;
545
546 // Compute the logmap of the relative rotation
547 const Eigen::Vector3<T> logmapVec = quaternionLogMap(qRel);
548
549 // The error is the squared norm of the logmap
550 rotationError = logmapVec.squaredNorm();
551 break;
552 }
554 // Note: |R0 - RT|² is a valid norm on SO3, it doesn't have the same slope as the squared
555 // angle difference but its derivative doesn't have a singularity at the minimum, so is more
556 // stable
557 const Eigen::Matrix3<T> rotDiff = nextRot.toRotationMatrix() - prevRot.toRotationMatrix();
558 rotationError = rotDiff.squaredNorm();
559 break;
560 }
561 }
562
563 error += rotationError * kOrientationWeight * rotWgt_ * targetRotationWeights_[i];
564
565 // calculate position error
566 const Eigen::Vector3<T> diff =
567 nextState.jointState[i].translation() - transformedPrev.translation;
568 error += diff.squaredNorm() * kPositionWeight * posWgt_ * targetPositionWeights_[i];
569 }
570
571 // return error
572 return error * this->weight_;
573}
574
575template <typename T>
577 std::span<const ModelParametersT<T>> /* modelParameters */,
578 std::span<const SkeletonStateT<T>> skelStates,
579 std::span<const MeshStateT<T>> /* meshStates */,
580 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
582
583 MT_CHECK(skelStates.size() == 2);
584 const auto& prevState = skelStates[0];
585 const auto& nextState = skelStates[1];
586
587 const Eigen::Index nParam = this->parameterTransform_.numAllModelParameters();
588 MT_CHECK(gradient.size() == 2 * nParam);
589
590 // loop over all joints and check for smoothness
591 double error = 0.0;
592
593 // also go over the joint states and calculate the rotation difference contribution on joints that
594 // are at the end
595 for (size_t i = 0; i < this->skeleton_.joints.size(); ++i) {
596 if (targetRotationWeights_[i] == 0 && targetPositionWeights_[i] == 0) {
597 continue;
598 }
599
600 // calculate orientation gradient
601 const TransformT<T> targetTransform =
602 (i < targetState_.size()) ? targetState_[i] : TransformT<T>();
603 const TransformT<T> transformedPrev = targetTransform * prevState.jointState[i].transform;
604 const Eigen::Quaternion<T>& prevRot = transformedPrev.rotation;
605 const Eigen::Quaternion<T>& nextRot = nextState.jointState[i].rotation();
606
607 T rotationError = T(0);
608 Eigen::Matrix3<T> rotDiff; // Only needed for RotationMatrixDifference
609 Eigen::Matrix<T, 3, 4> dLogDq; // Only needed for QuaternionLogMap
610
611 switch (rotationErrorType_) {
613 // Compute the relative rotation: q_rel = nextRot^{-1} * prevRot
614 const Eigen::Quaternion<T> qRel = nextRot.conjugate() * prevRot;
615
616 // Precompute the derivative of logmap w.r.t. quaternion components
617 dLogDq = quaternionLogMapDerivative(qRel);
618
619 // Compute the logmap of the relative rotation
620 const Eigen::Vector3<T> logmapVec = quaternionLogMap(qRel);
621
622 // The error is the squared norm of the logmap
623 rotationError = logmapVec.squaredNorm();
624 break;
625 }
627 rotDiff = nextRot.toRotationMatrix() - prevRot.toRotationMatrix();
628 rotationError = rotDiff.squaredNorm();
629 break;
630 }
631 }
632
633 const T rwgt = kOrientationWeight * rotWgt_ * this->weight_ * targetRotationWeights_[i];
634 error += rotationError * rwgt;
635
636 // calculate position gradient
637 const Eigen::Vector3<T> diff =
638 nextState.jointState[i].translation() - transformedPrev.translation;
639 const T pwgt = kPositionWeight * posWgt_ * this->weight_ * targetPositionWeights_[i];
640 error += diff.squaredNorm() * pwgt;
641 const GradientComputationParams<T> gradParams{
642 i,
643 targetTransform,
644 prevRot,
645 nextRot,
646 diff,
647 pwgt,
648 rwgt,
649 rotationErrorType_,
650 rotDiff,
651 dLogDq};
652
653 computeStateGradient<T>(
654 StateType::Prev,
655 gradParams,
656 prevState,
657 prevState,
658 this->skeleton_,
659 this->activeJointParams_,
661 gradient.segment(0, nParam));
662
663 computeStateGradient<T>(
664 StateType::Next,
665 gradParams,
666 nextState,
667 prevState,
668 this->skeleton_,
669 this->activeJointParams_,
671 gradient.segment(nParam, nParam));
672 }
673
674 // return error
675 return error;
676}
677
678template <typename T>
680 const auto nActiveJoints =
681 (targetPositionWeights_.array() != 0 || targetRotationWeights_.array() != 0).count();
682 if (rotationErrorType_ == RotationErrorType::QuaternionLogMap) {
683 // 3 (translation) + 3 (logmap) = 6 per joint
684 return nActiveJoints * 6;
685 } else {
686 // 3 (translation) + 9 (matrix) = 12 per joint
687 return nActiveJoints * 12;
688 }
689}
690
691template <typename T>
693 std::span<const ModelParametersT<T>> /* modelParameters */,
694 std::span<const SkeletonStateT<T>> skelStates,
695 std::span<const MeshStateT<T>> /* meshStates */,
696 Eigen::Ref<Eigen::MatrixX<T>> jacobian_full,
697 Eigen::Ref<Eigen::VectorX<T>> residual_full,
698 int& usedRows) const {
700
701 MT_CHECK(skelStates.size() == 2);
702 const auto& prevState = skelStates[0];
703 const auto& nextState = skelStates[1];
704
705 const Eigen::Index nParam = this->parameterTransform_.numAllModelParameters();
706 MT_CHECK(jacobian_full.cols() == 2 * nParam);
707
708 double error = 0.0;
709
710 Eigen::Index offset = 0;
711
712 // calculate state difference jacobians
713 for (size_t i = 0; i < this->skeleton_.joints.size(); ++i) {
714 if (targetRotationWeights_[i] == 0 && targetPositionWeights_[i] == 0) {
715 continue;
716 }
717
718 const TransformT<T> targetTransform =
719 (i < targetState_.size()) ? targetState_[i] : TransformT<T>();
720 const TransformT<T> transformedPrev = targetTransform * prevState.jointState[i].transform;
721
722 // Determine block size based on rotation error type
723 // QuaternionLogMap: 3 (translation) + 3 (logmap) = 6
724 // RotationMatrixDifference: 3 (translation) + 9 (matrix) = 12
725 const size_t rotationResidualSize =
726 (rotationErrorType_ == RotationErrorType::QuaternionLogMap) ? 3 : 9;
727 const size_t blockSize = 3 + rotationResidualSize;
728
729 // calculate translation gradient
730 const auto transDiff =
731 (nextState.jointState[i].translation() - transformedPrev.translation).eval();
732
733 // calculate orientation gradient and error
734 const Eigen::Quaternion<T>& prevRot = transformedPrev.rotation;
735 const Eigen::Quaternion<T>& nextRot = nextState.jointState[i].rotation();
736
737 // calculate the difference between target and position and error
738 const T pwgt = kPositionWeight * posWgt_ * this->weight_ * targetPositionWeights_[i];
739 const T wgt = std::sqrt(pwgt);
740 error += transDiff.squaredNorm() * pwgt;
741 residual_full.template segment<3>(offset).noalias() = transDiff * wgt;
742
743 const T rwgt = kOrientationWeight * rotWgt_ * this->weight_ * targetRotationWeights_[i];
744 const T awgt = std::sqrt(rwgt);
745
746 Eigen::Matrix<T, 3, 4> dLogDq; // Precomputed derivative (only needed for logmap)
747 switch (rotationErrorType_) {
749 // Compute the relative rotation: q_rel = nextRot^{-1} * prevRot
750 const Eigen::Quaternion<T> qRel = nextRot.conjugate() * prevRot;
751
752 // Precompute the derivative of logmap w.r.t. quaternion components
753 // This will be reused for all 3 rotation axes
754 dLogDq = quaternionLogMapDerivative(qRel);
755
756 // Compute the logmap of the relative rotation
757 const Eigen::Vector3<T> logmapVec = quaternionLogMap(qRel);
758
759 // The error is the squared norm of the logmap
760 error += logmapVec.squaredNorm() * rwgt;
761
762 // The residual for Jacobian is the logmap vector itself (not squared)
763 residual_full.template segment<3>(offset + 3).noalias() = logmapVec * awgt;
764 break;
765 }
767 // 9D RotationMatrixDifference
768 const Eigen::Matrix3<T> rotDiff = nextRot.toRotationMatrix() - prevRot.toRotationMatrix();
769 error += rotDiff.squaredNorm() * rwgt;
770 residual_full.template segment<9>(offset + 3).noalias() =
771 Map<const Eigen::Matrix<T, 9, 1>>(rotDiff.data(), rotDiff.size()) * awgt;
772 break;
773 }
774 }
775
776 const JacobianComputationParams<T> jacParams{
777 i,
778 targetTransform,
779 prevRot,
780 nextRot,
781 wgt,
782 awgt,
783 rotationResidualSize,
784 blockSize,
785 rotationErrorType_,
786 dLogDq};
787
788 computeStateJacobian<T>(
789 StateType::Prev,
790 jacParams,
791 prevState,
792 prevState,
793 this->skeleton_,
794 this->activeJointParams_,
796 jacobian_full.block(offset, 0, blockSize, nParam));
797
798 computeStateJacobian<T>(
799 StateType::Next,
800 jacParams,
801 nextState,
802 prevState,
803 this->skeleton_,
804 this->activeJointParams_,
806 jacobian_full.block(offset, nParam, blockSize, nParam));
807
808 offset += blockSize;
809 }
810
811 usedRows = gsl::narrow_cast<int>(offset);
812
813 // return error
814 return error;
815}
816
819
820} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
const ParameterTransform & parameterTransform_
SequenceErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
Error function that penalizes the difference between the current skeleton state and the next skeleton...
void setRotationTargetWeights(const Eigen::VectorX< T > &rotWeight)
Set the target rotation weights for each joint.
double getError(std::span< const ModelParametersT< T > > modelParameters, std::span< const SkeletonStateT< T > > skelStates, std::span< const MeshStateT< T > >) const final
double getGradient(std::span< const ModelParametersT< T > > modelParameters, std::span< const SkeletonStateT< T > > skelStates, std::span< const MeshStateT< T > >, Eigen::Ref< Eigen::VectorX< T > > gradient) const final
void setTargetState(TransformListT< T > target)
Set the target state for the skeleton.
double getJacobian(std::span< const ModelParametersT< T > > modelParameters, std::span< const SkeletonStateT< T > > skelStates, std::span< const MeshStateT< T > >, Eigen::Ref< Eigen::MatrixX< T > > jacobian, Eigen::Ref< Eigen::VectorX< T > > residual, int &usedRows) const final
void setTargetWeights(const Eigen::VectorX< T > &posWeight, const Eigen::VectorX< T > &rotWeight)
Set the target weights for each joint's position and rotation.
StateSequenceErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt, RotationErrorType rotationErrorType=RotationErrorType::RotationMatrixDifference)
void setPositionTargetWeights(const Eigen::VectorX< T > &posWeight)
Set the target position weights for each joint.
Eigen::Matrix< T, 3, 3 > crossProductMatrix(const Eigen::Vector3< T > &v)
Creates a skew-symmetric matrix for computing cross products.
Definition utility.h:343
RotationErrorType
Defines different methods for computing rotation error between two quaternions.
@ RotationMatrixDifference
Frobenius norm of rotation matrix difference: ||R1 - R2||_F^2.
@ QuaternionLogMap
Logarithmic map of relative rotation: ||log(R1^{-1} * R2)||^2.
SkeletonT< float > Skeleton
Definition fwd.h:263
std::vector< TransformT< T > > TransformListT
Per-joint transform list describing the state of all joints in a skeleton (one entry per joint,...
Definition transform.h:228
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)
Vector3< T > quaternionLogMap(const Quaternion< T > &q)
Computes the logarithmic map from a quaternion to a rotation vector (axis-angle in R^3).
Definition utility.cpp:74
FloatP dot(const Eigen::MatrixBase< Derived > &v1, const Vector3P< S > &v2)
Computes dot product of Eigen::Vector3f and 3-vector of packets.
Definition simd.h:191
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
Eigen::Quaternion< T > Quaternion
Unit quaternion representing a 3D rotation.
Definition types.h:385
void gradient_jointParams_to_modelParams(const T &grad_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::VectorX< T > > gradient)
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
Eigen::Matrix< T, 3, 4 > quaternionLogMapDerivative(const Quaternion< T > &q)
Computes the derivative of the logarithmic map with respect to quaternion components.
Definition utility.cpp:120
Eigen::Map< T > Map
Definition types.h:40
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
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.
Lightweight transform with separate rotation, translation, and uniform scaling.
Definition transform.h:36
Vector3< T > translation
Definition transform.h:40
Quaternion< T > rotation
Unit quaternion encoding the rotation.
Definition transform.h:39