blob: 0cccfa7f3bbc403c7b706d5b695e08f0484c82ae [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Ceres Solver - A fast non-linear least squares minimizer
Austin Schuh3de38b02024-06-25 18:25:10 -07002// Copyright 2023 Google Inc. All rights reserved.
Austin Schuh70cc9552019-01-21 19:46:48 -08003// http://ceres-solver.org/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are met:
7//
8// * Redistributions of source code must retain the above copyright notice,
9// this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above copyright notice,
11// this list of conditions and the following disclaimer in the documentation
12// and/or other materials provided with the distribution.
13// * Neither the name of Google Inc. nor the names of its contributors may be
14// used to endorse or promote products derived from this software without
15// specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27// POSSIBILITY OF SUCH DAMAGE.
28//
29// Author: keir@google.com (Keir Mierle)
30// sameeragarwal@google.com (Sameer Agarwal)
31//
32// Templated functions for manipulating rotations. The templated
33// functions are useful when implementing functors for automatic
34// differentiation.
35//
36// In the following, the Quaternions are laid out as 4-vectors, thus:
37//
38// q[0] scalar part.
39// q[1] coefficient of i.
40// q[2] coefficient of j.
41// q[3] coefficient of k.
42//
43// where: i*i = j*j = k*k = -1 and i*j = k, j*k = i, k*i = j.
44
45#ifndef CERES_PUBLIC_ROTATION_H_
46#define CERES_PUBLIC_ROTATION_H_
47
48#include <algorithm>
49#include <cmath>
Austin Schuh70cc9552019-01-21 19:46:48 -080050
Austin Schuh3de38b02024-06-25 18:25:10 -070051#include "ceres/constants.h"
52#include "ceres/internal/euler_angles.h"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080053#include "glog/logging.h"
54
Austin Schuh70cc9552019-01-21 19:46:48 -080055namespace ceres {
56
57// Trivial wrapper to index linear arrays as matrices, given a fixed
58// column and row stride. When an array "T* array" is wrapped by a
59//
60// (const) MatrixAdapter<T, row_stride, col_stride> M"
61//
62// the expression M(i, j) is equivalent to
63//
Austin Schuh3de38b02024-06-25 18:25:10 -070064// array[i * row_stride + j * col_stride]
Austin Schuh70cc9552019-01-21 19:46:48 -080065//
66// Conversion functions to and from rotation matrices accept
67// MatrixAdapters to permit using row-major and column-major layouts,
68// and rotation matrices embedded in larger matrices (such as a 3x4
69// projection matrix).
70template <typename T, int row_stride, int col_stride>
71struct MatrixAdapter;
72
73// Convenience functions to create a MatrixAdapter that treats the
74// array pointed to by "pointer" as a 3x3 (contiguous) column-major or
75// row-major matrix.
76template <typename T>
77MatrixAdapter<T, 1, 3> ColumnMajorAdapter3x3(T* pointer);
78
79template <typename T>
80MatrixAdapter<T, 3, 1> RowMajorAdapter3x3(T* pointer);
81
82// Convert a value in combined axis-angle representation to a quaternion.
83// The value angle_axis is a triple whose norm is an angle in radians,
84// and whose direction is aligned with the axis of rotation,
85// and quaternion is a 4-tuple that will contain the resulting quaternion.
86// The implementation may be used with auto-differentiation up to the first
87// derivative, higher derivatives may have unexpected results near the origin.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080088template <typename T>
Austin Schuh70cc9552019-01-21 19:46:48 -080089void AngleAxisToQuaternion(const T* angle_axis, T* quaternion);
90
91// Convert a quaternion to the equivalent combined axis-angle representation.
92// The value quaternion must be a unit quaternion - it is not normalized first,
93// and angle_axis will be filled with a value whose norm is the angle of
94// rotation in radians, and whose direction is the axis of rotation.
95// The implementation may be used with auto-differentiation up to the first
96// derivative, higher derivatives may have unexpected results near the origin.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080097template <typename T>
Austin Schuh70cc9552019-01-21 19:46:48 -080098void QuaternionToAngleAxis(const T* quaternion, T* angle_axis);
99
100// Conversions between 3x3 rotation matrix (in column major order) and
101// quaternion rotation representations. Templated for use with
102// autodifferentiation.
103template <typename T>
104void RotationMatrixToQuaternion(const T* R, T* quaternion);
105
106template <typename T, int row_stride, int col_stride>
107void RotationMatrixToQuaternion(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800108 const MatrixAdapter<const T, row_stride, col_stride>& R, T* quaternion);
Austin Schuh70cc9552019-01-21 19:46:48 -0800109
110// Conversions between 3x3 rotation matrix (in column major order) and
111// axis-angle rotation representations. Templated for use with
112// autodifferentiation.
113template <typename T>
114void RotationMatrixToAngleAxis(const T* R, T* angle_axis);
115
116template <typename T, int row_stride, int col_stride>
117void RotationMatrixToAngleAxis(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800118 const MatrixAdapter<const T, row_stride, col_stride>& R, T* angle_axis);
Austin Schuh70cc9552019-01-21 19:46:48 -0800119
120template <typename T>
121void AngleAxisToRotationMatrix(const T* angle_axis, T* R);
122
123template <typename T, int row_stride, int col_stride>
124void AngleAxisToRotationMatrix(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800125 const T* angle_axis, const MatrixAdapter<T, row_stride, col_stride>& R);
Austin Schuh70cc9552019-01-21 19:46:48 -0800126
127// Conversions between 3x3 rotation matrix (in row major order) and
128// Euler angle (in degrees) rotation representations.
129//
130// The {pitch,roll,yaw} Euler angles are rotations around the {x,y,z}
131// axes, respectively. They are applied in that same order, so the
132// total rotation R is Rz * Ry * Rx.
133template <typename T>
134void EulerAnglesToRotationMatrix(const T* euler, int row_stride, T* R);
135
136template <typename T, int row_stride, int col_stride>
137void EulerAnglesToRotationMatrix(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800138 const T* euler, const MatrixAdapter<T, row_stride, col_stride>& R);
Austin Schuh70cc9552019-01-21 19:46:48 -0800139
Austin Schuh3de38b02024-06-25 18:25:10 -0700140// Convert a generic Euler Angle sequence (in radians) to a 3x3 rotation matrix.
141//
142// Euler Angles define a sequence of 3 rotations about a sequence of axes,
143// typically taken to be the X, Y, or Z axes. The last axis may be the same as
144// the first axis (e.g. ZYZ) per Euler's original definition of his angles
145// (proper Euler angles) or not (e.g. ZYX / yaw-pitch-roll), per common usage in
146// the nautical and aerospace fields (Tait-Bryan angles). The three rotations
147// may be in a global frame of reference (Extrinsic) or in a body fixed frame of
148// reference (Intrinsic) that moves with the rotating object.
149//
150// Internally, Euler Axis sequences are classified by Ken Shoemake's scheme from
151// "Euler angle conversion", Graphics Gems IV, where a choice of axis for the
152// first rotation and 3 binary choices:
153// 1. Parity of the axis permutation. The axis sequence has Even parity if the
154// second axis of rotation is 'greater-than' the first axis of rotation
155// according to the order X<Y<Z<X, otherwise it has Odd parity.
156// 2. Proper Euler Angles v.s. Tait-Bryan Angles
157// 3. Extrinsic Rotations v.s. Intrinsic Rotations
158// compactly represent all 24 possible Euler Angle Conventions
159//
160// One template parameter: EulerSystem must be explicitly given. This parameter
161// is a tag named by 'Extrinsic' or 'Intrinsic' followed by three characters in
162// the set '[XYZ]', specifying the axis sequence, e.g. ceres::ExtrinsicYZY
163// (robotic arms), ceres::IntrinsicZYX (for aerospace), etc.
164//
165// The order of elements in the input array 'euler' follows the axis sequence
166template <typename EulerSystem, typename T>
167inline void EulerAnglesToRotation(const T* euler, T* R);
168
169template <typename EulerSystem, typename T, int row_stride, int col_stride>
170void EulerAnglesToRotation(const T* euler,
171 const MatrixAdapter<T, row_stride, col_stride>& R);
172
173// Convert a 3x3 rotation matrix to a generic Euler Angle sequence (in radians)
174//
175// Euler Angles define a sequence of 3 rotations about a sequence of axes,
176// typically taken to be the X, Y, or Z axes. The last axis may be the same as
177// the first axis (e.g. ZYZ) per Euler's original definition of his angles
178// (proper Euler angles) or not (e.g. ZYX / yaw-pitch-roll), per common usage in
179// the nautical and aerospace fields (Tait-Bryan angles). The three rotations
180// may be in a global frame of reference (Extrinsic) or in a body fixed frame of
181// reference (Intrinsic) that moves with the rotating object.
182//
183// Internally, Euler Axis sequences are classified by Ken Shoemake's scheme from
184// "Euler angle conversion", Graphics Gems IV, where a choice of axis for the
185// first rotation and 3 binary choices:
186// 1. Oddness of the axis permutation, that defines whether the second axis is
187// 'greater-than' the first axis according to the order X>Y>Z>X)
188// 2. Proper Euler Angles v.s. Tait-Bryan Angles
189// 3. Extrinsic Rotations v.s. Intrinsic Rotations
190// compactly represent all 24 possible Euler Angle Conventions
191//
192// One template parameter: EulerSystem must be explicitly given. This parameter
193// is a tag named by 'Extrinsic' or 'Intrinsic' followed by three characters in
194// the set '[XYZ]', specifying the axis sequence, e.g. ceres::ExtrinsicYZY
195// (robotic arms), ceres::IntrinsicZYX (for aerospace), etc.
196//
197// The order of elements in the output array 'euler' follows the axis sequence
198template <typename EulerSystem, typename T>
199inline void RotationMatrixToEulerAngles(const T* R, T* euler);
200
201template <typename EulerSystem, typename T, int row_stride, int col_stride>
202void RotationMatrixToEulerAngles(
203 const MatrixAdapter<const T, row_stride, col_stride>& R, T* euler);
204
Austin Schuh70cc9552019-01-21 19:46:48 -0800205// Convert a 4-vector to a 3x3 scaled rotation matrix.
206//
207// The choice of rotation is such that the quaternion [1 0 0 0] goes to an
208// identity matrix and for small a, b, c the quaternion [1 a b c] goes to
209// the matrix
210//
211// [ 0 -c b ]
212// I + 2 [ c 0 -a ] + higher order terms
213// [ -b a 0 ]
214//
215// which corresponds to a Rodrigues approximation, the last matrix being
216// the cross-product matrix of [a b c]. Together with the property that
217// R(q1 * q2) = R(q1) * R(q2) this uniquely defines the mapping from q to R.
218//
219// No normalization of the quaternion is performed, i.e.
220// R = ||q||^2 * Q, where Q is an orthonormal matrix
221// such that det(Q) = 1 and Q*Q' = I
222//
223// WARNING: The rotation matrix is ROW MAJOR
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800224template <typename T>
225inline void QuaternionToScaledRotation(const T q[4], T R[3 * 3]);
Austin Schuh70cc9552019-01-21 19:46:48 -0800226
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800227template <typename T, int row_stride, int col_stride>
228inline void QuaternionToScaledRotation(
229 const T q[4], const MatrixAdapter<T, row_stride, col_stride>& R);
Austin Schuh70cc9552019-01-21 19:46:48 -0800230
231// Same as above except that the rotation matrix is normalized by the
232// Frobenius norm, so that R * R' = I (and det(R) = 1).
233//
234// WARNING: The rotation matrix is ROW MAJOR
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800235template <typename T>
236inline void QuaternionToRotation(const T q[4], T R[3 * 3]);
Austin Schuh70cc9552019-01-21 19:46:48 -0800237
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800238template <typename T, int row_stride, int col_stride>
239inline void QuaternionToRotation(
240 const T q[4], const MatrixAdapter<T, row_stride, col_stride>& R);
Austin Schuh70cc9552019-01-21 19:46:48 -0800241
242// Rotates a point pt by a quaternion q:
243//
244// result = R(q) * pt
245//
246// Assumes the quaternion is unit norm. This assumption allows us to
247// write the transform as (something)*pt + pt, as is clear from the
248// formula below. If you pass in a quaternion with |q|^2 = 2 then you
249// WILL NOT get back 2 times the result you get for a unit quaternion.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800250//
251// Inplace rotation is not supported. pt and result must point to different
252// memory locations, otherwise the result will be undefined.
253template <typename T>
254inline void UnitQuaternionRotatePoint(const T q[4], const T pt[3], T result[3]);
Austin Schuh70cc9552019-01-21 19:46:48 -0800255
256// With this function you do not need to assume that q has unit norm.
257// It does assume that the norm is non-zero.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800258//
259// Inplace rotation is not supported. pt and result must point to different
260// memory locations, otherwise the result will be undefined.
261template <typename T>
262inline void QuaternionRotatePoint(const T q[4], const T pt[3], T result[3]);
Austin Schuh70cc9552019-01-21 19:46:48 -0800263
264// zw = z * w, where * is the Quaternion product between 4 vectors.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800265//
266// Inplace quaternion product is not supported. The resulting quaternion zw must
267// not share the memory with the input quaternion z and w, otherwise the result
268// will be undefined.
269template <typename T>
270inline void QuaternionProduct(const T z[4], const T w[4], T zw[4]);
Austin Schuh70cc9552019-01-21 19:46:48 -0800271
272// xy = x cross y;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800273//
274// Inplace cross product is not supported. The resulting vector x_cross_y must
275// not share the memory with the input vectors x and y, otherwise the result
276// will be undefined.
277template <typename T>
278inline void CrossProduct(const T x[3], const T y[3], T x_cross_y[3]);
Austin Schuh70cc9552019-01-21 19:46:48 -0800279
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800280template <typename T>
281inline T DotProduct(const T x[3], const T y[3]);
Austin Schuh70cc9552019-01-21 19:46:48 -0800282
283// y = R(angle_axis) * x;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800284//
285// Inplace rotation is not supported. pt and result must point to different
286// memory locations, otherwise the result will be undefined.
287template <typename T>
288inline void AngleAxisRotatePoint(const T angle_axis[3],
289 const T pt[3],
290 T result[3]);
Austin Schuh70cc9552019-01-21 19:46:48 -0800291
292// --- IMPLEMENTATION
293
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800294template <typename T, int row_stride, int col_stride>
Austin Schuh70cc9552019-01-21 19:46:48 -0800295struct MatrixAdapter {
296 T* pointer_;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800297 explicit MatrixAdapter(T* pointer) : pointer_(pointer) {}
Austin Schuh70cc9552019-01-21 19:46:48 -0800298
299 T& operator()(int r, int c) const {
300 return pointer_[r * row_stride + c * col_stride];
301 }
302};
303
304template <typename T>
305MatrixAdapter<T, 1, 3> ColumnMajorAdapter3x3(T* pointer) {
306 return MatrixAdapter<T, 1, 3>(pointer);
307}
308
309template <typename T>
310MatrixAdapter<T, 3, 1> RowMajorAdapter3x3(T* pointer) {
311 return MatrixAdapter<T, 3, 1>(pointer);
312}
313
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800314template <typename T>
Austin Schuh70cc9552019-01-21 19:46:48 -0800315inline void AngleAxisToQuaternion(const T* angle_axis, T* quaternion) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700316 using std::fpclassify;
317 using std::hypot;
Austin Schuh70cc9552019-01-21 19:46:48 -0800318 const T& a0 = angle_axis[0];
319 const T& a1 = angle_axis[1];
320 const T& a2 = angle_axis[2];
Austin Schuh3de38b02024-06-25 18:25:10 -0700321 const T theta = hypot(a0, a1, a2);
Austin Schuh70cc9552019-01-21 19:46:48 -0800322
323 // For points not at the origin, the full conversion is numerically stable.
Austin Schuh3de38b02024-06-25 18:25:10 -0700324 if (fpclassify(theta) != FP_ZERO) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800325 const T half_theta = theta * T(0.5);
326 const T k = sin(half_theta) / theta;
327 quaternion[0] = cos(half_theta);
328 quaternion[1] = a0 * k;
329 quaternion[2] = a1 * k;
330 quaternion[3] = a2 * k;
331 } else {
332 // At the origin, sqrt() will produce NaN in the derivative since
333 // the argument is zero. By approximating with a Taylor series,
334 // and truncating at one term, the value and first derivatives will be
335 // computed correctly when Jets are used.
336 const T k(0.5);
337 quaternion[0] = T(1.0);
338 quaternion[1] = a0 * k;
339 quaternion[2] = a1 * k;
340 quaternion[3] = a2 * k;
341 }
342}
343
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800344template <typename T>
Austin Schuh70cc9552019-01-21 19:46:48 -0800345inline void QuaternionToAngleAxis(const T* quaternion, T* angle_axis) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700346 using std::fpclassify;
347 using std::hypot;
Austin Schuh70cc9552019-01-21 19:46:48 -0800348 const T& q1 = quaternion[1];
349 const T& q2 = quaternion[2];
350 const T& q3 = quaternion[3];
Austin Schuh3de38b02024-06-25 18:25:10 -0700351 const T sin_theta = hypot(q1, q2, q3);
Austin Schuh70cc9552019-01-21 19:46:48 -0800352
353 // For quaternions representing non-zero rotation, the conversion
354 // is numerically stable.
Austin Schuh3de38b02024-06-25 18:25:10 -0700355 if (fpclassify(sin_theta) != FP_ZERO) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800356 const T& cos_theta = quaternion[0];
357
358 // If cos_theta is negative, theta is greater than pi/2, which
359 // means that angle for the angle_axis vector which is 2 * theta
360 // would be greater than pi.
361 //
362 // While this will result in the correct rotation, it does not
363 // result in a normalized angle-axis vector.
364 //
365 // In that case we observe that 2 * theta ~ 2 * theta - 2 * pi,
366 // which is equivalent saying
367 //
368 // theta - pi = atan(sin(theta - pi), cos(theta - pi))
369 // = atan(-sin(theta), -cos(theta))
370 //
371 const T two_theta =
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800372 T(2.0) * ((cos_theta < T(0.0)) ? atan2(-sin_theta, -cos_theta)
373 : atan2(sin_theta, cos_theta));
Austin Schuh70cc9552019-01-21 19:46:48 -0800374 const T k = two_theta / sin_theta;
375 angle_axis[0] = q1 * k;
376 angle_axis[1] = q2 * k;
377 angle_axis[2] = q3 * k;
378 } else {
379 // For zero rotation, sqrt() will produce NaN in the derivative since
380 // the argument is zero. By approximating with a Taylor series,
381 // and truncating at one term, the value and first derivatives will be
382 // computed correctly when Jets are used.
383 const T k(2.0);
384 angle_axis[0] = q1 * k;
385 angle_axis[1] = q2 * k;
386 angle_axis[2] = q3 * k;
387 }
388}
389
390template <typename T>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800391void RotationMatrixToQuaternion(const T* R, T* quaternion) {
392 RotationMatrixToQuaternion(ColumnMajorAdapter3x3(R), quaternion);
Austin Schuh70cc9552019-01-21 19:46:48 -0800393}
394
395// This algorithm comes from "Quaternion Calculus and Fast Animation",
396// Ken Shoemake, 1987 SIGGRAPH course notes
397template <typename T, int row_stride, int col_stride>
398void RotationMatrixToQuaternion(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800399 const MatrixAdapter<const T, row_stride, col_stride>& R, T* quaternion) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800400 const T trace = R(0, 0) + R(1, 1) + R(2, 2);
401 if (trace >= 0.0) {
402 T t = sqrt(trace + T(1.0));
403 quaternion[0] = T(0.5) * t;
404 t = T(0.5) / t;
405 quaternion[1] = (R(2, 1) - R(1, 2)) * t;
406 quaternion[2] = (R(0, 2) - R(2, 0)) * t;
407 quaternion[3] = (R(1, 0) - R(0, 1)) * t;
408 } else {
409 int i = 0;
410 if (R(1, 1) > R(0, 0)) {
411 i = 1;
412 }
413
414 if (R(2, 2) > R(i, i)) {
415 i = 2;
416 }
417
418 const int j = (i + 1) % 3;
419 const int k = (j + 1) % 3;
420 T t = sqrt(R(i, i) - R(j, j) - R(k, k) + T(1.0));
421 quaternion[i + 1] = T(0.5) * t;
422 t = T(0.5) / t;
423 quaternion[0] = (R(k, j) - R(j, k)) * t;
424 quaternion[j + 1] = (R(j, i) + R(i, j)) * t;
425 quaternion[k + 1] = (R(k, i) + R(i, k)) * t;
426 }
427}
428
429// The conversion of a rotation matrix to the angle-axis form is
430// numerically problematic when then rotation angle is close to zero
431// or to Pi. The following implementation detects when these two cases
432// occurs and deals with them by taking code paths that are guaranteed
433// to not perform division by a small number.
434template <typename T>
435inline void RotationMatrixToAngleAxis(const T* R, T* angle_axis) {
436 RotationMatrixToAngleAxis(ColumnMajorAdapter3x3(R), angle_axis);
437}
438
439template <typename T, int row_stride, int col_stride>
440void RotationMatrixToAngleAxis(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800441 const MatrixAdapter<const T, row_stride, col_stride>& R, T* angle_axis) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800442 T quaternion[4];
443 RotationMatrixToQuaternion(R, quaternion);
444 QuaternionToAngleAxis(quaternion, angle_axis);
445 return;
446}
447
448template <typename T>
449inline void AngleAxisToRotationMatrix(const T* angle_axis, T* R) {
450 AngleAxisToRotationMatrix(angle_axis, ColumnMajorAdapter3x3(R));
451}
452
453template <typename T, int row_stride, int col_stride>
454void AngleAxisToRotationMatrix(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800455 const T* angle_axis, const MatrixAdapter<T, row_stride, col_stride>& R) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700456 using std::fpclassify;
457 using std::hypot;
Austin Schuh70cc9552019-01-21 19:46:48 -0800458 static const T kOne = T(1.0);
Austin Schuh3de38b02024-06-25 18:25:10 -0700459 const T theta = hypot(angle_axis[0], angle_axis[1], angle_axis[2]);
460 if (fpclassify(theta) != FP_ZERO) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800461 // We want to be careful to only evaluate the square root if the
462 // norm of the angle_axis vector is greater than zero. Otherwise
463 // we get a division by zero.
Austin Schuh70cc9552019-01-21 19:46:48 -0800464 const T wx = angle_axis[0] / theta;
465 const T wy = angle_axis[1] / theta;
466 const T wz = angle_axis[2] / theta;
467
468 const T costheta = cos(theta);
469 const T sintheta = sin(theta);
470
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800471 // clang-format off
Austin Schuh70cc9552019-01-21 19:46:48 -0800472 R(0, 0) = costheta + wx*wx*(kOne - costheta);
473 R(1, 0) = wz*sintheta + wx*wy*(kOne - costheta);
474 R(2, 0) = -wy*sintheta + wx*wz*(kOne - costheta);
475 R(0, 1) = wx*wy*(kOne - costheta) - wz*sintheta;
476 R(1, 1) = costheta + wy*wy*(kOne - costheta);
477 R(2, 1) = wx*sintheta + wy*wz*(kOne - costheta);
478 R(0, 2) = wy*sintheta + wx*wz*(kOne - costheta);
479 R(1, 2) = -wx*sintheta + wy*wz*(kOne - costheta);
480 R(2, 2) = costheta + wz*wz*(kOne - costheta);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800481 // clang-format on
Austin Schuh70cc9552019-01-21 19:46:48 -0800482 } else {
Austin Schuh3de38b02024-06-25 18:25:10 -0700483 // At zero, we switch to using the first order Taylor expansion.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800484 R(0, 0) = kOne;
485 R(1, 0) = angle_axis[2];
Austin Schuh70cc9552019-01-21 19:46:48 -0800486 R(2, 0) = -angle_axis[1];
487 R(0, 1) = -angle_axis[2];
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800488 R(1, 1) = kOne;
489 R(2, 1) = angle_axis[0];
490 R(0, 2) = angle_axis[1];
Austin Schuh70cc9552019-01-21 19:46:48 -0800491 R(1, 2) = -angle_axis[0];
492 R(2, 2) = kOne;
493 }
494}
495
Austin Schuh3de38b02024-06-25 18:25:10 -0700496template <typename EulerSystem, typename T>
497inline void EulerAnglesToRotation(const T* euler, T* R) {
498 EulerAnglesToRotation<EulerSystem>(euler, RowMajorAdapter3x3(R));
499}
500
501template <typename EulerSystem, typename T, int row_stride, int col_stride>
502void EulerAnglesToRotation(const T* euler,
503 const MatrixAdapter<T, row_stride, col_stride>& R) {
504 using std::cos;
505 using std::sin;
506
507 const auto [i, j, k] = EulerSystem::kAxes;
508
509 T ea[3];
510 ea[1] = euler[1];
511 if constexpr (EulerSystem::kIsIntrinsic) {
512 ea[0] = euler[2];
513 ea[2] = euler[0];
514 } else {
515 ea[0] = euler[0];
516 ea[2] = euler[2];
517 }
518 if constexpr (EulerSystem::kIsParityOdd) {
519 ea[0] = -ea[0];
520 ea[1] = -ea[1];
521 ea[2] = -ea[2];
522 }
523
524 const T ci = cos(ea[0]);
525 const T cj = cos(ea[1]);
526 const T ch = cos(ea[2]);
527 const T si = sin(ea[0]);
528 const T sj = sin(ea[1]);
529 const T sh = sin(ea[2]);
530 const T cc = ci * ch;
531 const T cs = ci * sh;
532 const T sc = si * ch;
533 const T ss = si * sh;
534 if constexpr (EulerSystem::kIsProperEuler) {
535 R(i, i) = cj;
536 R(i, j) = sj * si;
537 R(i, k) = sj * ci;
538 R(j, i) = sj * sh;
539 R(j, j) = -cj * ss + cc;
540 R(j, k) = -cj * cs - sc;
541 R(k, i) = -sj * ch;
542 R(k, j) = cj * sc + cs;
543 R(k, k) = cj * cc - ss;
544 } else {
545 R(i, i) = cj * ch;
546 R(i, j) = sj * sc - cs;
547 R(i, k) = sj * cc + ss;
548 R(j, i) = cj * sh;
549 R(j, j) = sj * ss + cc;
550 R(j, k) = sj * cs - sc;
551 R(k, i) = -sj;
552 R(k, j) = cj * si;
553 R(k, k) = cj * ci;
554 }
555}
556
557template <typename EulerSystem, typename T>
558inline void RotationMatrixToEulerAngles(const T* R, T* euler) {
559 RotationMatrixToEulerAngles<EulerSystem>(RowMajorAdapter3x3(R), euler);
560}
561
562template <typename EulerSystem, typename T, int row_stride, int col_stride>
563void RotationMatrixToEulerAngles(
564 const MatrixAdapter<const T, row_stride, col_stride>& R, T* euler) {
565 using std::atan2;
566 using std::fpclassify;
567 using std::hypot;
568
569 const auto [i, j, k] = EulerSystem::kAxes;
570
571 T ea[3];
572 if constexpr (EulerSystem::kIsProperEuler) {
573 const T sy = hypot(R(i, j), R(i, k));
574 if (fpclassify(sy) != FP_ZERO) {
575 ea[0] = atan2(R(i, j), R(i, k));
576 ea[1] = atan2(sy, R(i, i));
577 ea[2] = atan2(R(j, i), -R(k, i));
578 } else {
579 ea[0] = atan2(-R(j, k), R(j, j));
580 ea[1] = atan2(sy, R(i, i));
581 ea[2] = T(0.0);
582 }
583 } else {
584 const T cy = hypot(R(i, i), R(j, i));
585 if (fpclassify(cy) != FP_ZERO) {
586 ea[0] = atan2(R(k, j), R(k, k));
587 ea[1] = atan2(-R(k, i), cy);
588 ea[2] = atan2(R(j, i), R(i, i));
589 } else {
590 ea[0] = atan2(-R(j, k), R(j, j));
591 ea[1] = atan2(-R(k, i), cy);
592 ea[2] = T(0.0);
593 }
594 }
595 if constexpr (EulerSystem::kIsParityOdd) {
596 ea[0] = -ea[0];
597 ea[1] = -ea[1];
598 ea[2] = -ea[2];
599 }
600 euler[1] = ea[1];
601 if constexpr (EulerSystem::kIsIntrinsic) {
602 euler[0] = ea[2];
603 euler[2] = ea[0];
604 } else {
605 euler[0] = ea[0];
606 euler[2] = ea[2];
607 }
608
609 // Proper euler angles are defined for angles in
610 // [-pi, pi) x [0, pi / 2) x [-pi, pi)
611 // which is enforced here
612 if constexpr (EulerSystem::kIsProperEuler) {
613 const T kPi(constants::pi);
614 const T kTwoPi(2.0 * kPi);
615 if (euler[1] < T(0.0) || ea[1] > kPi) {
616 euler[0] += kPi;
617 euler[1] = -euler[1];
618 euler[2] -= kPi;
619 }
620
621 for (int i = 0; i < 3; ++i) {
622 if (euler[i] < -kPi) {
623 euler[i] += kTwoPi;
624 } else if (euler[i] > kPi) {
625 euler[i] -= kTwoPi;
626 }
627 }
628 }
629}
630
Austin Schuh70cc9552019-01-21 19:46:48 -0800631template <typename T>
632inline void EulerAnglesToRotationMatrix(const T* euler,
633 const int row_stride_parameter,
634 T* R) {
635 EulerAnglesToRotationMatrix(euler, RowMajorAdapter3x3(R));
636}
637
638template <typename T, int row_stride, int col_stride>
639void EulerAnglesToRotationMatrix(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800640 const T* euler, const MatrixAdapter<T, row_stride, col_stride>& R) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800641 const double kPi = 3.14159265358979323846;
642 const T degrees_to_radians(kPi / 180.0);
643
644 const T pitch(euler[0] * degrees_to_radians);
645 const T roll(euler[1] * degrees_to_radians);
646 const T yaw(euler[2] * degrees_to_radians);
647
648 const T c1 = cos(yaw);
649 const T s1 = sin(yaw);
650 const T c2 = cos(roll);
651 const T s2 = sin(roll);
652 const T c3 = cos(pitch);
653 const T s3 = sin(pitch);
654
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800655 R(0, 0) = c1 * c2;
656 R(0, 1) = -s1 * c3 + c1 * s2 * s3;
657 R(0, 2) = s1 * s3 + c1 * s2 * c3;
Austin Schuh70cc9552019-01-21 19:46:48 -0800658
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800659 R(1, 0) = s1 * c2;
660 R(1, 1) = c1 * c3 + s1 * s2 * s3;
661 R(1, 2) = -c1 * s3 + s1 * s2 * c3;
Austin Schuh70cc9552019-01-21 19:46:48 -0800662
663 R(2, 0) = -s2;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800664 R(2, 1) = c2 * s3;
665 R(2, 2) = c2 * c3;
Austin Schuh70cc9552019-01-21 19:46:48 -0800666}
667
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800668template <typename T>
669inline void QuaternionToScaledRotation(const T q[4], T R[3 * 3]) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800670 QuaternionToScaledRotation(q, RowMajorAdapter3x3(R));
671}
672
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800673template <typename T, int row_stride, int col_stride>
674inline void QuaternionToScaledRotation(
675 const T q[4], const MatrixAdapter<T, row_stride, col_stride>& R) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800676 // Make convenient names for elements of q.
677 T a = q[0];
678 T b = q[1];
679 T c = q[2];
680 T d = q[3];
681 // This is not to eliminate common sub-expression, but to
682 // make the lines shorter so that they fit in 80 columns!
683 T aa = a * a;
684 T ab = a * b;
685 T ac = a * c;
686 T ad = a * d;
687 T bb = b * b;
688 T bc = b * c;
689 T bd = b * d;
690 T cc = c * c;
691 T cd = c * d;
692 T dd = d * d;
693
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800694 // clang-format off
695 R(0, 0) = aa + bb - cc - dd; R(0, 1) = T(2) * (bc - ad); R(0, 2) = T(2) * (ac + bd);
696 R(1, 0) = T(2) * (ad + bc); R(1, 1) = aa - bb + cc - dd; R(1, 2) = T(2) * (cd - ab);
697 R(2, 0) = T(2) * (bd - ac); R(2, 1) = T(2) * (ab + cd); R(2, 2) = aa - bb - cc + dd;
698 // clang-format on
Austin Schuh70cc9552019-01-21 19:46:48 -0800699}
700
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800701template <typename T>
702inline void QuaternionToRotation(const T q[4], T R[3 * 3]) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800703 QuaternionToRotation(q, RowMajorAdapter3x3(R));
704}
705
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800706template <typename T, int row_stride, int col_stride>
707inline void QuaternionToRotation(
708 const T q[4], const MatrixAdapter<T, row_stride, col_stride>& R) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800709 QuaternionToScaledRotation(q, R);
710
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800711 T normalizer = q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3];
Austin Schuh70cc9552019-01-21 19:46:48 -0800712 normalizer = T(1) / normalizer;
713
714 for (int i = 0; i < 3; ++i) {
715 for (int j = 0; j < 3; ++j) {
716 R(i, j) *= normalizer;
717 }
718 }
719}
720
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800721template <typename T>
722inline void UnitQuaternionRotatePoint(const T q[4],
723 const T pt[3],
724 T result[3]) {
725 DCHECK_NE(pt, result) << "Inplace rotation is not supported.";
726
727 // clang-format off
Austin Schuh3de38b02024-06-25 18:25:10 -0700728 T uv0 = q[2] * pt[2] - q[3] * pt[1];
729 T uv1 = q[3] * pt[0] - q[1] * pt[2];
730 T uv2 = q[1] * pt[1] - q[2] * pt[0];
731 uv0 += uv0;
732 uv1 += uv1;
733 uv2 += uv2;
734 result[0] = pt[0] + q[0] * uv0;
735 result[1] = pt[1] + q[0] * uv1;
736 result[2] = pt[2] + q[0] * uv2;
737 result[0] += q[2] * uv2 - q[3] * uv1;
738 result[1] += q[3] * uv0 - q[1] * uv2;
739 result[2] += q[1] * uv1 - q[2] * uv0;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800740 // clang-format on
Austin Schuh70cc9552019-01-21 19:46:48 -0800741}
742
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800743template <typename T>
744inline void QuaternionRotatePoint(const T q[4], const T pt[3], T result[3]) {
745 DCHECK_NE(pt, result) << "Inplace rotation is not supported.";
746
Austin Schuh70cc9552019-01-21 19:46:48 -0800747 // 'scale' is 1 / norm(q).
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800748 const T scale =
749 T(1) / sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]);
Austin Schuh70cc9552019-01-21 19:46:48 -0800750
751 // Make unit-norm version of q.
752 const T unit[4] = {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800753 scale * q[0],
754 scale * q[1],
755 scale * q[2],
756 scale * q[3],
Austin Schuh70cc9552019-01-21 19:46:48 -0800757 };
758
759 UnitQuaternionRotatePoint(unit, pt, result);
760}
761
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800762template <typename T>
763inline void QuaternionProduct(const T z[4], const T w[4], T zw[4]) {
764 DCHECK_NE(z, zw) << "Inplace quaternion product is not supported.";
765 DCHECK_NE(w, zw) << "Inplace quaternion product is not supported.";
766
767 // clang-format off
Austin Schuh70cc9552019-01-21 19:46:48 -0800768 zw[0] = z[0] * w[0] - z[1] * w[1] - z[2] * w[2] - z[3] * w[3];
769 zw[1] = z[0] * w[1] + z[1] * w[0] + z[2] * w[3] - z[3] * w[2];
770 zw[2] = z[0] * w[2] - z[1] * w[3] + z[2] * w[0] + z[3] * w[1];
771 zw[3] = z[0] * w[3] + z[1] * w[2] - z[2] * w[1] + z[3] * w[0];
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800772 // clang-format on
Austin Schuh70cc9552019-01-21 19:46:48 -0800773}
774
775// xy = x cross y;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800776template <typename T>
777inline void CrossProduct(const T x[3], const T y[3], T x_cross_y[3]) {
778 DCHECK_NE(x, x_cross_y) << "Inplace cross product is not supported.";
779 DCHECK_NE(y, x_cross_y) << "Inplace cross product is not supported.";
780
Austin Schuh70cc9552019-01-21 19:46:48 -0800781 x_cross_y[0] = x[1] * y[2] - x[2] * y[1];
782 x_cross_y[1] = x[2] * y[0] - x[0] * y[2];
783 x_cross_y[2] = x[0] * y[1] - x[1] * y[0];
784}
785
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800786template <typename T>
787inline T DotProduct(const T x[3], const T y[3]) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800788 return (x[0] * y[0] + x[1] * y[1] + x[2] * y[2]);
789}
790
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800791template <typename T>
792inline void AngleAxisRotatePoint(const T angle_axis[3],
793 const T pt[3],
794 T result[3]) {
795 DCHECK_NE(pt, result) << "Inplace rotation is not supported.";
Austin Schuh3de38b02024-06-25 18:25:10 -0700796 using std::fpclassify;
797 using std::hypot;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800798
Austin Schuh3de38b02024-06-25 18:25:10 -0700799 const T theta = hypot(angle_axis[0], angle_axis[1], angle_axis[2]);
800
801 if (fpclassify(theta) != FP_ZERO) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800802 // Away from zero, use the rodriguez formula
803 //
804 // result = pt costheta +
805 // (w x pt) * sintheta +
806 // w (w . pt) (1 - costheta)
807 //
808 // We want to be careful to only evaluate the square root if the
809 // norm of the angle_axis vector is greater than zero. Otherwise
810 // we get a division by zero.
811 //
Austin Schuh70cc9552019-01-21 19:46:48 -0800812 const T costheta = cos(theta);
813 const T sintheta = sin(theta);
814 const T theta_inverse = T(1.0) / theta;
815
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800816 const T w[3] = {angle_axis[0] * theta_inverse,
817 angle_axis[1] * theta_inverse,
818 angle_axis[2] * theta_inverse};
Austin Schuh70cc9552019-01-21 19:46:48 -0800819
820 // Explicitly inlined evaluation of the cross product for
821 // performance reasons.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800822 const T w_cross_pt[3] = {w[1] * pt[2] - w[2] * pt[1],
823 w[2] * pt[0] - w[0] * pt[2],
824 w[0] * pt[1] - w[1] * pt[0]};
Austin Schuh70cc9552019-01-21 19:46:48 -0800825 const T tmp =
826 (w[0] * pt[0] + w[1] * pt[1] + w[2] * pt[2]) * (T(1.0) - costheta);
827
828 result[0] = pt[0] * costheta + w_cross_pt[0] * sintheta + w[0] * tmp;
829 result[1] = pt[1] * costheta + w_cross_pt[1] * sintheta + w[1] * tmp;
830 result[2] = pt[2] * costheta + w_cross_pt[2] * sintheta + w[2] * tmp;
831 } else {
Austin Schuh3de38b02024-06-25 18:25:10 -0700832 // At zero, the first order Taylor approximation of the rotation
833 // matrix R corresponding to a vector w and angle theta is
Austin Schuh70cc9552019-01-21 19:46:48 -0800834 //
835 // R = I + hat(w) * sin(theta)
836 //
837 // But sintheta ~ theta and theta * w = angle_axis, which gives us
838 //
Austin Schuh3de38b02024-06-25 18:25:10 -0700839 // R = I + hat(angle_axis)
Austin Schuh70cc9552019-01-21 19:46:48 -0800840 //
841 // and actually performing multiplication with the point pt, gives us
Austin Schuh3de38b02024-06-25 18:25:10 -0700842 // R * pt = pt + angle_axis x pt.
Austin Schuh70cc9552019-01-21 19:46:48 -0800843 //
Austin Schuh3de38b02024-06-25 18:25:10 -0700844 // Switching to the Taylor expansion at zero provides meaningful
Austin Schuh70cc9552019-01-21 19:46:48 -0800845 // derivatives when evaluated using Jets.
846 //
847 // Explicitly inlined evaluation of the cross product for
848 // performance reasons.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800849 const T w_cross_pt[3] = {angle_axis[1] * pt[2] - angle_axis[2] * pt[1],
850 angle_axis[2] * pt[0] - angle_axis[0] * pt[2],
851 angle_axis[0] * pt[1] - angle_axis[1] * pt[0]};
Austin Schuh70cc9552019-01-21 19:46:48 -0800852
853 result[0] = pt[0] + w_cross_pt[0];
854 result[1] = pt[1] + w_cross_pt[1];
855 result[2] = pt[2] + w_cross_pt[2];
856 }
857}
858
859} // namespace ceres
860
861#endif // CERES_PUBLIC_ROTATION_H_