13#include <Eigen/Eigenvalues>
24constexpr T eulerTol() {
28 return Eps<T>(T(1e-6), T(1e-12));
40 const T theta = v.norm();
44 constexpr T kSmallAngleThreshold =
Eps<T>(T(3.5e-4), T(1.5e-8));
46 if (theta < kSmallAngleThreshold) {
55 const T theta2 = theta * theta;
56 const T w = T(1) - theta2 / T(8);
57 const T scale = T(0.5) * (T(1) - theta2 / T(24));
59 Quaternion<T> q(w, scale * v.x(), scale * v.y(), scale * v.z());
64 const T halfTheta = theta / T(2);
65 const T sinHalfTheta = std::sin(halfTheta);
66 const T cosHalfTheta = std::cos(halfTheta);
67 const T scale = sinHalfTheta / theta;
69 return Quaternion<T>(cosHalfTheta, scale * v.x(), scale * v.y(), scale * v.z());
83 const T w = qNorm.w();
84 const Vector3<T> vec(qNorm.x(), qNorm.y(), qNorm.z());
85 const T vecNorm = vec.norm();
89 constexpr T kSmallAngleThreshold =
Eps<T>(T(3.5e-4), T(1.5e-8));
91 if (vecNorm < kSmallAngleThreshold) {
96 const T vecNorm2 = vec.squaredNorm();
97 const T scale = T(2) * (T(1) + vecNorm2 / T(6));
110 const T theta = T(2) * std::atan2(vecNorm, w);
111 const T scale = theta / vecNorm;
125 const T w = qNorm.w();
126 const Vector3<T> vec(qNorm.x(), qNorm.y(), qNorm.z());
127 const T vecNorm = vec.norm();
130 constexpr T kSmallAngleThreshold =
Eps<T>(T(3.5e-4), T(1.5e-8));
132 Eigen::Matrix<T, 3, 4> jacobian;
134 if (vecNorm < kSmallAngleThreshold) {
137 const T vecNorm2 = vec.squaredNorm();
138 const T scale = T(2) * (T(1) + vecNorm2 / T(6));
142 for (
int i = 0; i < 3; ++i) {
143 for (
int j = 0; j < 3; ++j) {
144 jacobian(i, j) = (i == j ? scale : T(0)) + T(2) * vec(i) * vec(j) / T(3);
150 jacobian.col(3).setZero();
154 const T theta = T(2) * std::atan2(vecNorm, w);
155 const T scale = theta / vecNorm;
161 const T denom = w * w + vecNorm * vecNorm;
162 const T dthetaDw = -T(2) * vecNorm / denom;
163 const Vector3<T> dthetaDvec = T(2) * w * vec / (vecNorm * denom);
168 for (
int j = 0; j < 3; ++j) {
169 const T dScaleDvecj =
170 dthetaDvec(j) / vecNorm - theta * vec(j) / (vecNorm * vecNorm * vecNorm);
171 for (
int i = 0; i < 3; ++i) {
172 jacobian(i, j) = dScaleDvecj * vec(i) + (i == j ? scale : T(0));
180 jacobian.col(3) = dthetaDw / vecNorm * vec;
197 return m.eulerAngles(axis0, axis1, axis2);
217 if (m(0, 2) < T(1) - eulerTol<T>()) {
218 if (m(0, 2) > T(-1) + eulerTol<T>()) {
219 res.x() = std::atan2(-m(1, 2), m(2, 2));
220 res.y() = std::asin(m(0, 2));
221 res.z() = std::atan2(-m(0, 1), m(0, 0));
228 res.y() = -
pi<T>() * T(0.5);
229 res.z() = std::atan2(m(1, 0), m(1, 1));
235 res.y() =
pi<T>() * T(0.5);
236 res.z() = std::atan2(m(1, 0), m(1, 1));
262 if (m(2, 0) < T(1) - eulerTol<T>()) {
263 if (m(2, 0) > T(-1) + eulerTol<T>()) {
264 res.x() = std::atan2(m(1, 0), m(0, 0));
265 res.y() = std::asin(-m(2, 0));
266 res.z() = std::atan2(m(2, 1), m(2, 2));
273 res.y() =
pi<T>() * T(0.5);
274 res.z() = std::atan2(m(0, 1), m(0, 2));
282 res.y() = -
pi<T>() * T(0.5);
283 res.z() = std::atan2(-m(0, 1), -m(0, 2));
328 const T cx = std::cos(angles[0]);
329 const T sx = std::sin(angles[0]);
330 const T cy = std::cos(angles[1]);
331 const T sy = std::sin(angles[1]);
332 const T cz = std::cos(angles[2]);
333 const T sz = std::sin(angles[2]);
336 res(1, 0) = cx * sz + cz * sx * sy;
337 res(2, 0) = sx * sz - cx * cz * sy;
339 res(0, 1) = -cy * sz;
340 res(1, 1) = cx * cz - sx * sy * sz;
341 res(2, 1) = cz * sx + cx * sy * sz;
344 res(1, 2) = -cy * sx;
362 const T cz = std::cos(angles[0]);
363 const T sz = std::sin(angles[0]);
364 const T cy = std::cos(angles[1]);
365 const T sy = std::sin(angles[1]);
366 const T cx = std::cos(angles[2]);
367 const T sx = std::sin(angles[2]);
373 res(0, 1) = cz * sy * sx - sz * cx;
374 res(1, 1) = sz * sy * sx + cz * cx;
377 res(0, 2) = cz * sy * cx + sz * sx;
378 res(1, 2) = sz * sy * cx - cz * sx;
388 std::atan2(T(2) * (q.w() * q.x() + q.y() * q.z()), T(1) - T(2) * (
sqr(q.x()) +
sqr(q.y())));
390 const T sinY = std::clamp(T(2) * (q.w() * q.y() - q.z() * q.x()), T(-1), T(1));
391 res.y() = std::asin(sinY);
393 std::atan2(T(2) * (q.w() * q.z() + q.x() * q.y()), T(1) - T(2) * (
sqr(q.y()) +
sqr(q.z())));
408 for (
size_t i = 0; i < q.size(); i++) {
410 Q += (q[i].coeffs() * w[i]) * (q[i].coeffs() * w[i]).transpose();
412 Q += q[i].coeffs() * q[i].coeffs().transpose();
418 return Quaternionf(Eigen::SelfAdjointEigenSolver<Matrix4f>(Q).eigenvectors().col(3));
423 const auto svd = mat.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);
424 VectorX<T> singularValues_inv = svd.singularValues();
425 const T maxSingularValue = singularValues_inv.size() > 0 ? singularValues_inv(0) : T(0);
426 if (maxSingularValue <= T(0)) {
432 T(std::max(mat.rows(), mat.cols())) * std::numeric_limits<T>::epsilon() * maxSingularValue;
433 for (
int j = 0; j < singularValues_inv.size(); ++j) {
434 if (singularValues_inv(j) > pinvtoler) {
435 singularValues_inv(j) = T(1.0) / singularValues_inv(j);
437 singularValues_inv(j) = T(0);
440 return (svd.matrixV() * singularValues_inv.asDiagonal() * svd.matrixU().transpose());
450 const Eigen::Vector3<T>& o1,
451 const Eigen::Vector3<T>& d1,
452 const Eigen::Vector3<T>& o2,
453 const Eigen::Vector3<T>& d2,
462 Eigen::Vector2<T> res;
464 const T maxSquareDist = maxDist * maxDist;
467 const auto w = o1 - o2;
468 const auto a = d1.squaredNorm();
469 const auto b = d1.dot(d2);
470 const auto c = d2.squaredNorm();
471 const auto d = d1.dot(w);
472 const auto e = d2.dot(w);
473 const auto D = (a * c - b * b);
482 constexpr T kTolerance =
Eps<T>(T(1e-7), T(1e-15));
483 if (D < kTolerance) {
490 if (w.squaredNorm() > maxSquareDist) {
491 return std::make_tuple(
false, std::numeric_limits<T>::max(), Eigen::Vector2<T>::Zero());
494 sN = (b * e - c * d);
495 tN = (a * e - b * d);
498 if ((w + (d1 * sN / D) - (d2 * tN / D)).squaredNorm() > maxSquareDist) {
499 return std::make_tuple(
false, std::numeric_limits<T>::max(), Eigen::Vector2<T>::Zero());
507 }
else if (sN > sD) {
527 }
else if (tN > tD) {
531 if ((-d + b) < T(0)) {
533 }
else if ((-d + b) > a) {
543 res[0] = (std::abs(sN) < kTolerance || std::abs(sD) < kTolerance) ? T(0) : sN / sD;
544 res[1] = (std::abs(tN) < kTolerance || std::abs(tD) < kTolerance) ? T(0) : tN / tD;
547 const auto dP = w + (d1 * res[0]) - (d2 * res[1]);
550 const T distance = dP.squaredNorm();
551 if (distance > maxSquareDist) {
552 return std::make_tuple(
false, std::numeric_limits<T>::max(), Eigen::Vector2<T>::Zero());
555 return std::make_tuple(
true, std::sqrt(distance), res);
650 const Eigen::Vector3<float>& o1,
651 const Eigen::Vector3<float>& d1,
652 const Eigen::Vector3<float>& o2,
653 const Eigen::Vector3<float>& d2,
654 const float maxDist);
657 const Eigen::Vector3<double>& o1,
658 const Eigen::Vector3<double>& d1,
659 const Eigen::Vector3<double>& o2,
660 const Eigen::Vector3<double>& d2,
661 const double maxDist);
667Matrix3<T> singleAxisRotationMatrix(
int axis, T angle) {
673Matrix3<T> singleAxisRotationMatrixDerivative(
int axis, T angle) {
675 const T c = std::cos(angle);
676 const T s = std::sin(angle);
683 }
else if (axis == 1) {
703 return singleAxisRotationMatrix(axis1, angles[1]) * singleAxisRotationMatrix(axis0, angles[0]);
709twoAxisRotationMatrixDerivatives(
int axis0,
int axis1,
const Vector2<T>& angles) {
710 const Matrix3<T> R0 = singleAxisRotationMatrix(axis0, angles[0]);
711 const Matrix3<T> R1 = singleAxisRotationMatrix(axis1, angles[1]);
712 const Matrix3<T> dR0 = singleAxisRotationMatrixDerivative(axis0, angles[0]);
713 const Matrix3<T> dR1 = singleAxisRotationMatrixDerivative(axis1, angles[1]);
715 return {R1 * dR0, dR1 * R0};
720T gaussNewtonSolveScalar(
723 T initialGuess = T(0),
724 int maxIterations = 20,
725 T tolerance = eulerTol<T>()) {
726 T angle = initialGuess;
728 T previousResidual = std::numeric_limits<T>::max();
729 for (
int iter = 0; iter < maxIterations; ++iter) {
731 const Matrix3<T> R = singleAxisRotationMatrix(axis, angle);
735 const T residual = residualMatrix.squaredNorm();
742 if (residual < tolerance || (previousResidual - residual) < tolerance) {
745 previousResidual = residual;
751 const Matrix3<T> dR = singleAxisRotationMatrixDerivative(axis, angle);
752 const Eigen::Matrix<T, 9, 1> jacobian = dR.reshaped(9, 1);
754 const Eigen::Vector<T, 9> residualVector = residualMatrix.reshaped(9, 1);
756 const Eigen::Vector<T, 1> delta = jacobian.householderQr().solve(-residualVector);
773 int maxIterations = 20,
774 T tolerance = eulerTol<T>()) {
777 T previousResidualNorm = std::numeric_limits<T>::max();
778 for (
int iter = 0; iter < maxIterations; ++iter) {
780 const Matrix3<T> R = twoAxisRotationMatrix(axis0, axis1, angles);
781 const auto [dR0, dR1] = twoAxisRotationMatrixDerivatives(axis0, axis1, angles);
785 const T residualNorm = residualMatrix.squaredNorm();
790 if (residualNorm < tolerance || (previousResidualNorm - residualNorm) < tolerance) {
793 previousResidualNorm = residualNorm;
796 const Eigen::Matrix<T, 9, 1> residualVector = residualMatrix.reshaped(9, 1);
798 Eigen::Matrix<T, 9, 2> jacobian;
799 jacobian.template block<9, 1>(0, 0) = dR0.reshaped(9, 1);
800 jacobian.template block<9, 1>(0, 1) = dR1.reshaped(9, 1);
803 const Vector2<T> delta = jacobian.householderQr().solve(-residualVector);
806 if (!delta.allFinite()) {
810 angles = angles + delta;
820 MT_CHECK(axis0 >= 0 && axis0 <= 2,
"Invalid axis0");
823 T initialGuess = T(0);
826 initialGuess = std::atan2(m(2, 1), m(1, 1));
827 }
else if (axis0 == 1) {
829 initialGuess = std::atan2(m(0, 2), m(0, 0));
832 initialGuess = std::atan2(m(1, 0), m(0, 0));
836 return gaussNewtonSolveScalar(m, axis0, initialGuess);
841 MT_CHECK(axis0 != axis1,
"Can't call two-axis rotation with the same axis");
842 MT_CHECK(axis0 >= 0 && axis0 <= 2,
"Invalid axis0");
843 MT_CHECK(axis1 >= 0 && axis1 <= 2,
"Invalid axis1");
845 return gaussNewtonSolveTwoAxis(
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Quaternionf quaternionAverage(momentum::span< const Quaternionf > q, momentum::span< const float > w)
Computes the weighted average of multiple quaternions.
constexpr T Eps(T FloatEps=T(1e-7), T DoubleEps=T(1e-16))
Returns a type-appropriate tolerance/epsilon value.
Vector3< double > Vector3d
Quaternion< double > Quaterniond
T rotationMatrixToOneAxisEuler(const Matrix3< T > &m, int axis0)
Fits a single-axis Euler rotation to a rotation matrix.
Vector3< T > rotationMatrixToEuler(const Matrix3< T > &m, int axis0, int axis1, int axis2, EulerConvention convention)
Converts rotation matrix to Euler angles.
Quaternion< float > Quaternionf
Vector3< T > rotationMatrixToEulerXYZ(const Matrix3< T > &m, EulerConvention convention)
An optimized version of rotationMatrixToEuler(m, 0, 1, 2, convention) or rotationMatrixToEuler(m,...
Matrix3< T > eulerXYZToRotationMatrix(const Vector3< T > &angles, EulerConvention convention)
An optimized version of eulerToRotationMatrix(angles, 0, 1, 2, convention) or eulerToRotationMatrix(a...
template std::tuple< bool, double, Eigen::Vector2< double > > closestPointsOnSegments< double >(const Eigen::Vector3< double > &o1, const Eigen::Vector3< double > &d1, const Eigen::Vector3< double > &o2, const Eigen::Vector3< double > &d2, const double maxDist)
Vector3< T > quaternionToEuler(const Quaternion< T > &q)
Converts a quaternion to Euler angles using the Extrinsic XYZ convention.
Eigen::Matrix< T, 3, 3 > Matrix3
Vector3< T > rotationMatrixToEulerZYX(const Matrix3< T > &m, EulerConvention convention)
An optimized version of rotationMatrixToEuler(m, 2, 1, 0, convention) or rotationMatrixToEuler(m,...
Vector3< T > quaternionLogMap(const Quaternion< T > &q)
Computes the logarithmic map from a quaternion to a rotation vector (axis-angle in R^3).
Eigen::AngleAxis< T > AngleAxis
EulerConvention
The Euler angles convention.
@ Extrinsic
The extrinsic convention.
@ Intrinsic
The intrinsic convention.
Vector2< T > rotationMatrixToTwoAxisEuler(const Matrix3< T > &m, int axis0, int axis1)
Fits a two-axis Euler rotation to a rotation matrix.
MatrixX< T > pseudoInverse(const MatrixX< T > &mat)
Calculates the pseudo-inverse of a matrix.
Eigen::Quaternion< T > Quaternion
Unit quaternion representing a 3D rotation.
Eigen::Matrix< T, Dynamic, Dynamic > MatrixX
Dynamic-size, column-major dense matrix.
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
template std::tuple< bool, float, Eigen::Vector2< float > > closestPointsOnSegments< float >(const Eigen::Vector3< float > &o1, const Eigen::Vector3< float > &d1, const Eigen::Vector3< float > &o2, const Eigen::Vector3< float > &d2, const float maxDist)
Eigen::SparseMatrix< T > SparseMatrix
Column-major sparse matrix.
Matrix4< float > Matrix4f
T sqr(const T &x)
Computes the square of a value.
std::tuple< bool, T, Eigen::Vector2< T > > closestPointsOnSegments(const Eigen::Vector3< T > &o1, const Eigen::Vector3< T > &d1, const Eigen::Vector3< T > &o2, const Eigen::Vector3< T > &d2, const T maxDist)
Returns the closest points on two line segments where the line segments are represented in origin and...
Matrix3< T > eulerToRotationMatrix(const Vector3< T > &angles, int axis0, int axis1, int axis2, EulerConvention convention)
Converts Euler angles to rotation matrix.
Matrix3< T > eulerZYXToRotationMatrix(const Vector3< T > &angles, EulerConvention convention)
An optimized version of eulerToRotationMatrix(angles, 2, 1, 0, convention) or eulerToRotationMatrix(a...
Quaternion< T > eulerToQuaternion(const Vector3< T > &angles, int axis0, int axis1, int axis2, EulerConvention convention)
Converts Euler angles to quaternion.
gsl::span< T > span
Span type alias using gsl::span (C++17 fallback).
Eigen::Matrix< T, 3, 4 > quaternionLogMapDerivative(const Quaternion< T > &q)
Computes the derivative of the logarithmic map with respect to quaternion components.
Vector3< float > Vector3f
Quaternion< T > quaternionExpMap(const Vector3< T > &v)
Computes the exponential map from a rotation vector (axis-angle in R^3) to a quaternion.
constexpr T pi() noexcept
Returns the mathematical constant pi.