quaternion_core/lib.rs
1//! Quaternion library written in Rust.
2//!
3//! This crate provides Quaternion operations and conversions between several rotation
4//! representations. Functions are generic and support `f32` and `f64`.
5//!
6//! ## Generics
7//!
8//! Functions implementing the `QuaternionOps` trait can take both `Quaternion<T>`
9//! and `Vector3<T>` types as arguments (How convenient...!!).
10//!
11//! For example:
12//! ```
13//! use quaternion_core::{Vector3, Quaternion, add};
14//!
15//! // --- Vector3 --- //
16//! let v1: Vector3<f32> = [1.0, 2.0, 3.0];
17//! let v2: Vector3<f32> = [0.1, 0.2, 0.3];
18//!
19//! let added_v = add(v1, v2); // <--- [1.1, 2.2, 3.3]
20//!
21//! // --- Quaternion --- //
22//! let q1: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
23//! let q2: Quaternion<f64> = (0.1, [0.2, 0.3, 0.4]);
24//!
25//! let added_q = add(q1, q2); // <--- (1.1, [2.2, 3.3, 4.4])
26//! ```
27//!
28//! ## What is Versor?
29//!
30//! Versor denotes a Quaternion representing rotation, with a norm of 1.
31//! This is precisely what is meant by a Unit Quaternion.
32//!
33//! The documentation for this crate basically writes Versor instead of Unit Quaternion,
34//! but the difference in usage is not clear.
35//! Please think Versor = Unit Quaternion.
36
37#![no_std]
38#[cfg(feature = "std")]
39extern crate std;
40
41#[cfg(any(feature = "std", feature = "libm"))]
42use num_traits::float::{Float, FloatConst};
43
44mod euler;
45mod generics;
46mod pfs;
47pub use generics::QuaternionOps;
48
49/// Three dimensional vector (Pure Quaternion)
50///
51/// The type `[q1, q2, q3]` is equivalent to the expression `q1i + q2j + q3k`,
52/// where `i`, `j`, `k` are basis of quaternions and satisfy the following equality:
53///
54/// `i^2 = j^2 = k^2 = ijk = -1`
55pub type Vector3<T> = [T; 3];
56
57/// Quaternion
58///
59/// The type `(q0, [q1, q2, q3])` is equivalent to the expression `q0 + q1i + q2j + q3k`,
60/// where `1`, `i`, `j`, `k` are basis of quaternions and satisfy the following equality:
61///
62/// `i^2 = j^2 = k^2 = ijk = -1`
63pub type Quaternion<T> = (T, Vector3<T>);
64
65/// Direction Cosine Matrix
66///
67/// `mij`: row `i`, column `j`
68///
69/// ```ignore
70/// [
71/// [m11, m12, m13],
72/// [m21, m22, m23],
73/// [m31, m32, m33]
74/// ]
75/// ```
76pub type DCM<T> = [Vector3<T>; 3];
77
78/// Specifies the rotation type of Euler angles.
79///
80/// Considering a fixed `Reference frame` and a rotating `Body frame`,
81/// `Intrinsic rotation` and `Extrinsic rotation` represent the following rotations:
82///
83/// * `Intrinsic`: Rotate around the axes of the `Body frame`
84/// * `Extrinsic`: Rotate around the axes of the `Reference frame`
85#[cfg_attr(feature = "serde-serialize", derive(serde::Serialize, serde::Deserialize))]
86#[derive(Debug, Clone, Copy)]
87pub enum RotationType {
88 Intrinsic,
89 Extrinsic,
90}
91
92/// Specifies the rotation sequence of Euler angles.
93///
94/// Each variant reads from left to right.
95/// For example, `RotationSequence::XYZ` represents first a rotation
96/// around the X axis, then around the Y axis, and finally around
97/// the Z axis (X ---> Y ---> Z).
98#[cfg_attr(feature = "serde-serialize", derive(serde::Serialize, serde::Deserialize))]
99#[derive(Debug, Clone, Copy)]
100pub enum RotationSequence {
101 // Proper (z-x-z, x-y-x, y-z-y, z-y-z, x-z-x, y-x-y)
102 ZXZ, XYX, YZY, ZYZ, XZX, YXY,
103 // Tait–Bryan (x-y-z, y-z-x, z-x-y, x-z-y, z-y-x, y-x-z)
104 XYZ, YZX, ZXY, XZY, ZYX, YXZ,
105}
106
107/// Specifies the axis.
108#[cfg_attr(feature = "serde-serialize", derive(serde::Serialize, serde::Deserialize))]
109#[derive(Debug, Clone, Copy)]
110pub enum Axis { X, Y, Z }
111
112/// Generate identity quaternion.
113///
114/// It returns `(1.0, [0.0, 0.0, 0.0])`.
115#[inline]
116pub fn identity<T>() -> Quaternion<T>
117where T: Float {
118 (T::one(), [T::zero(); 3])
119}
120
121/// Converts a Quaternion between right-handed and left-handed coordinate systems.
122///
123/// The two systems are mirror images of each other: one coordinate axis points
124/// the opposite way, and the positive direction of rotation is reversed as well.
125/// This function accounts for both, returning the Quaternion that describes the
126/// same rotation in the other coordinate system.
127///
128/// The `axis` argument specifies which coordinate axis is reversed between the
129/// source and destination coordinate systems. For example, pass `Axis::Z` when
130/// the Z-axis is reversed between the two systems.
131///
132/// # Examples
133///
134/// ```
135/// # use quaternion_core::{Axis, from_axis_angle, convert_handedness};
136/// # let PI = std::f64::consts::PI;
137/// // Rotation of pi/2[rad] around the axis (1, 1, 1), described in a right-handed system.
138/// let q_rh = from_axis_angle([1.0, 1.0, 1.0], PI/2.0);
139///
140/// // The same rotation, described in a left-handed system
141/// // whose z-axis points the opposite way.
142/// let q_lh = convert_handedness(q_rh, Axis::Z);
143///
144/// // In the mirrored system, this rotation is described as -pi/2[rad]
145/// // around the axis (1, 1, -1).
146/// let expected = from_axis_angle([1.0, 1.0, -1.0], -PI/2.0);
147/// assert!( (q_lh.0 - expected.0).abs() < 1e-12 );
148/// assert!( (q_lh.1[0] - expected.1[0]).abs() < 1e-12 );
149/// assert!( (q_lh.1[1] - expected.1[1]).abs() < 1e-12 );
150/// assert!( (q_lh.1[2] - expected.1[2]).abs() < 1e-12 );
151///
152/// // Applying the conversion twice restores the original Quaternion.
153/// let q = convert_handedness(q_lh, Axis::Z);
154/// assert!( (q_rh.0 - q.0).abs() < 1e-12 );
155/// assert!( (q_rh.1[0] - q.1[0]).abs() < 1e-12 );
156/// assert!( (q_rh.1[1] - q.1[1]).abs() < 1e-12 );
157/// assert!( (q_rh.1[2] - q.1[2]).abs() < 1e-12 );
158/// ```
159#[inline]
160pub fn convert_handedness<T>(q: Quaternion<T>, axis: Axis) -> Quaternion<T>
161where T: Float {
162 // 右手系と左手系の変換は、x,y,zのうちの特定の1軸を反転させて、
163 // 更に全ての軸回りの回転方向を逆にすれば良い。
164 match axis {
165 Axis::X => (q.0, [ q.1[0], -q.1[1], -q.1[2]]),
166 Axis::Y => (q.0, [-q.1[0], q.1[1], -q.1[2]]),
167 Axis::Z => (q.0, [-q.1[0], -q.1[1], q.1[2]]),
168 }
169}
170
171/// Generate Versor by specifying rotation `angle`\[rad\] and `axis` vector.
172///
173/// The `axis` vector does not have to be a unit vector.
174///
175/// If you enter a zero vector, it returns an identity quaternion.
176///
177/// # Examples
178///
179/// ```
180/// # use quaternion_core::{from_axis_angle, point_rotation};
181/// # let PI = std::f64::consts::PI;
182/// // Generates a quaternion representing the
183/// // rotation of pi/2[rad] around the y-axis.
184/// let q = from_axis_angle([0.0, 1.0, 0.0], PI/2.0);
185///
186/// // Rotate the point.
187/// let r = point_rotation(q, [2.0, 2.0, 0.0]);
188///
189/// assert!( (r[0] - 0.0).abs() < 1e-12 );
190/// assert!( (r[1] - 2.0).abs() < 1e-12 );
191/// assert!( (r[2] + 2.0).abs() < 1e-12 );
192/// ```
193#[inline]
194pub fn from_axis_angle<T>(axis: Vector3<T>, angle: T) -> Quaternion<T>
195where T: Float + FloatConst {
196 let theta = angle % ( T::PI() + T::PI() ); // Range reduction: (-2π, 2π)
197 let (sin, cos) = ( theta * pfs::cast(0.5) ).sin_cos();
198 let coef = sin / norm(axis);
199 // axisがゼロベクトルのとき,sinの値によってcoefはInfにもNaNにもなる
200 // (angleが2πの整数倍のときはsin=0となり,0/0=NaNとなる).
201 if coef.is_finite() {
202 ( cos, scale(coef, axis) )
203 } else {
204 identity()
205 }
206}
207
208/// Extracts the rotation `axis` and the rotation `angle` around the `axis` from the Versor.
209///
210/// # Returns
211///
212/// The function returns a tuple `(axis, angle)`, where:
213///
214/// * **`axis`**: The rotation axis as a **unit vector** (`Vector3`).
215/// * **`angle`**: The rotation angle in **radians**. The range is `(-PI, PI]`.
216///
217/// ## Special Case: Identity Quaternion
218///
219/// If the input is the **Identity Quaternion** `(1.0, [0.0, 0.0, 0.0])`,
220/// the function returns an angle of zero and a zero axis vector.
221///
222/// # Singularity
223///
224/// Because this function returns a normalized rotation axis,
225/// when the norm of the vector part of Versor is zero, a singularity
226/// occurs and accuracy decreases.
227///
228/// If you want to use the calculated `angle` and `axis` as `scale(angle, axis)`,
229/// it is better to use the `to_rotation_vector` function.
230/// The `to_rotation_vector` function can be calculated without singularities.
231///
232/// # Examples
233///
234/// ```
235/// # use quaternion_core::{from_axis_angle, to_axis_angle, sub, normalize};
236/// # let PI = std::f64::consts::PI;
237/// let axis_ori = [0.0, 1.0, 2.0];
238/// let angle_ori = PI / 2.0;
239/// let q = from_axis_angle(axis_ori, angle_ori);
240///
241/// let (axis, angle) = to_axis_angle(q);
242///
243/// let diff = sub( normalize(axis_ori), normalize(axis) );
244/// assert!( diff[0].abs() < 1e-12 );
245/// assert!( diff[1].abs() < 1e-12 );
246/// assert!( diff[2].abs() < 1e-12 );
247/// assert!( (angle_ori - angle).abs() < 1e-12 );
248/// ```
249#[inline]
250pub fn to_axis_angle<T>(q: Quaternion<T>) -> (Vector3<T>, T)
251where T: Float {
252 let norm_v = norm(q.1);
253 let norm_inv = norm_v.recip();
254 if norm_inv.is_infinite() {
255 ( [T::zero(); 3], T::zero() )
256 } else {
257 let mut angle = pfs::cast::<T>(2.0) * norm_v.min( T::one() ).asin();
258 if q.0 < T::zero() {
259 angle = -angle;
260 }
261 ( scale(norm_inv, q.1), angle )
262 }
263}
264
265/// Converts a **Direction Cosine Matrix (DCM)** into a **Versor**
266///
267/// Crucially, this function assumes the input DCM represents a
268/// Point Rotation (Frame Fixed), where a vector `v` is rotated by the operation `q v q*`.
269///
270/// If your input DCM represents a **Frame Rotation (Point Fixed)**,
271/// which corresponds to the rotation `q* v q`, you must take the conjugate
272/// of the resulting Versor to get the correct rotation:
273///
274/// ```
275/// # use quaternion_core::{from_dcm, conj, to_dcm};
276/// # let dcm = to_dcm(conj((1.0, [0.0; 3])));
277/// // q_pr represents the Versor for Point Rotation.
278/// let q_pr = from_dcm(dcm);
279/// // q_fr is the Versor for the Frame Rotation.
280/// let q_fr = conj(q_pr);
281/// ```
282///
283/// # Examples
284///
285/// ```
286/// # use quaternion_core::{
287/// # from_axis_angle, dot, conj, negate, to_dcm, from_dcm,
288/// # matrix_product, point_rotation, frame_rotation
289/// # };
290/// # let PI = std::f64::consts::PI;
291/// // Make these as you like.
292/// let v = [1.0, 0.5, -8.0];
293/// let q = from_axis_angle([0.2, 1.0, -2.0], PI/4.0);
294///
295/// // --- Point rotation --- //
296/// {
297/// let m = to_dcm(q);
298/// let q_check = from_dcm(m);
299///
300/// assert!( (q.0 - q_check.0).abs() < 1e-12 );
301/// assert!( (q.1[0] - q_check.1[0]).abs() < 1e-12 );
302/// assert!( (q.1[1] - q_check.1[1]).abs() < 1e-12 );
303/// assert!( (q.1[2] - q_check.1[2]).abs() < 1e-12 );
304/// }
305///
306/// // --- Frame rotation --- //
307/// {
308/// let m = to_dcm( conj(q) );
309/// let q_check = conj( from_dcm(m) );
310///
311/// assert!( (q.0 - q_check.0).abs() < 1e-12 );
312/// assert!( (q.1[0] - q_check.1[0]).abs() < 1e-12 );
313/// assert!( (q.1[1] - q_check.1[1]).abs() < 1e-12 );
314/// assert!( (q.1[2] - q_check.1[2]).abs() < 1e-12 );
315/// }
316/// ```
317#[inline]
318pub fn from_dcm<T>(m: DCM<T>) -> Quaternion<T>
319where T: Float {
320 // ゼロ除算を避けるために,4通りの式で求めたうちの最大値を係数として使う.
321 let m22_p_m33 = m[1][1] + m[2][2];
322 let m22_m_m33 = m[1][1] - m[2][2];
323 let (index, max_num) = pfs::max4([
324 m[0][0] + m22_p_m33,
325 m[0][0] - m22_p_m33,
326 -m[0][0] + m22_m_m33,
327 -m[0][0] - m22_m_m33,
328 ]);
329
330 let half: T = pfs::cast(0.5);
331 let tmp = ( max_num + T::one() ).sqrt();
332 let coef = half / tmp;
333
334 let (q0, [q1, q2, q3]): Quaternion<T>;
335 match index {
336 0 => {
337 q0 = half * tmp;
338 q1 = (m[2][1] - m[1][2]) * coef;
339 q2 = (m[0][2] - m[2][0]) * coef;
340 q3 = (m[1][0] - m[0][1]) * coef;
341 },
342 1 => {
343 q0 = (m[2][1] - m[1][2]) * coef;
344 q1 = half * tmp;
345 q2 = (m[0][1] + m[1][0]) * coef;
346 q3 = (m[0][2] + m[2][0]) * coef;
347 },
348 2 => {
349 q0 = (m[0][2] - m[2][0]) * coef;
350 q1 = (m[0][1] + m[1][0]) * coef;
351 q2 = half * tmp;
352 q3 = (m[1][2] + m[2][1]) * coef;
353 },
354 3 => {
355 q0 = (m[1][0] - m[0][1]) * coef;
356 q1 = (m[0][2] + m[2][0]) * coef;
357 q2 = (m[1][2] + m[2][1]) * coef;
358 q3 = half * tmp;
359 },
360 _ => unreachable!(),
361 };
362
363 (q0, [q1, q2, q3])
364}
365
366/// Converts a **Versor** into a **Direction Cosine Matrix (DCM)**.
367///
368/// **By default, the output DCM represents a Point Rotation (Frame Fixed)**,
369/// which rotates a vector `v` by the quaternion operation `q v q*`.
370///
371/// If you need a DCM that represents a **Frame Rotation (Point Fixed)**
372/// (the rotation `q* v q`), you must take the conjugate of the Versor:
373///
374/// ```
375/// # use quaternion_core::{to_dcm, conj};
376/// # let q = (1.0, [0.0; 3]);
377/// // This DCM represents the Frame Rotation.
378/// let dcm = to_dcm( conj(q) );
379/// ```
380///
381/// # Examples
382///
383/// ```
384/// # use quaternion_core::{
385/// # from_axis_angle, to_dcm, conj,
386/// # matrix_product, point_rotation, frame_rotation
387/// # };
388/// # let PI = std::f64::consts::PI;
389/// // Make these as you like.
390/// let v = [1.0, 0.5, -8.0];
391/// let q = from_axis_angle([0.2, 1.0, -2.0], PI/4.0);
392///
393/// // --- Point rotation --- //
394/// {
395/// let m = to_dcm(q);
396///
397/// let rm = matrix_product(m, v);
398/// let rq = point_rotation(q, v);
399/// assert!( (rm[0] - rq[0]).abs() < 1e-12 );
400/// assert!( (rm[1] - rq[1]).abs() < 1e-12 );
401/// assert!( (rm[2] - rq[2]).abs() < 1e-12 );
402/// }
403///
404/// // --- Frame rotation --- //
405/// {
406/// let m = to_dcm( conj(q) );
407///
408/// let rm = matrix_product(m, v);
409/// let rq = frame_rotation(q, v);
410/// assert!( (rm[0] - rq[0]).abs() < 1e-12 );
411/// assert!( (rm[1] - rq[1]).abs() < 1e-12 );
412/// assert!( (rm[2] - rq[2]).abs() < 1e-12 );
413/// }
414/// ```
415#[inline]
416pub fn to_dcm<T>(q: Quaternion<T>) -> DCM<T>
417where T: Float {
418 let neg_one = -T::one();
419 let two = pfs::cast(2.0);
420
421 // Compute these value only once.
422 let (q0_q0, [q0_q1, q0_q2, q0_q3]) = scale(q.0, q);
423 let q1_q2 = q.1[0] * q.1[1];
424 let q1_q3 = q.1[0] * q.1[2];
425 let q2_q3 = q.1[1] * q.1[2];
426
427 let m11 = pfs::mul_add(pfs::mul_add(q.1[0], q.1[0], q0_q0), two, neg_one);
428 let m12 = (q1_q2 - q0_q3) * two;
429 let m13 = (q1_q3 + q0_q2) * two;
430 let m21 = (q1_q2 + q0_q3) * two;
431 let m22 = pfs::mul_add(pfs::mul_add(q.1[1], q.1[1], q0_q0), two, neg_one);
432 let m23 = (q2_q3 - q0_q1) * two;
433 let m31 = (q1_q3 - q0_q2) * two;
434 let m32 = (q2_q3 + q0_q1) * two;
435 let m33 = pfs::mul_add(pfs::mul_add(q.1[2], q.1[2], q0_q0), two, neg_one);
436
437 [
438 [m11, m12, m13],
439 [m21, m22, m23],
440 [m31, m32, m33],
441 ]
442}
443
444/// Converts a **Euler Angles** into a **Versor**.
445///
446/// This function requires two parameters to fully define the rotation:
447///
448/// 1. `RotationType`: Specifies whether the rotation is **Intrinsic** or **Extrinsic**.
449/// 2. `RotationSequence`: Defines the three-axis sequence (e.g., XYZ, ZYX, XZX, ...).
450///
451/// The input `angles` array must contain the three angles in **radians**,
452/// corresponding to the specified rotation sequence: `angles[0]` -> `angles[1]` -> `angles[2]`.
453/// (Each angle should be within the range: `[-2*PI, 2*PI]`).
454///
455/// # Examples
456///
457/// ```
458/// # use quaternion_core::{from_axis_angle, mul, from_euler_angles, point_rotation};
459/// # let PI = std::f64::consts::PI;
460/// use quaternion_core::{RotationType::*, RotationSequence::XYZ};
461///
462/// let angles = [PI/6.0, 1.6*PI, -PI/4.0];
463/// let v = [1.0, 0.5, -0.4];
464///
465/// // Quaternions representing rotation around each axis.
466/// let x = from_axis_angle([1.0, 0.0, 0.0], angles[0]);
467/// let y = from_axis_angle([0.0, 1.0, 0.0], angles[1]);
468/// let z = from_axis_angle([0.0, 0.0, 1.0], angles[2]);
469///
470/// // ---- Intrinsic (X-Y-Z) ---- //
471/// // These represent the same rotation.
472/// let q_in = mul( mul(x, y), z );
473/// let e2q_in = from_euler_angles(Intrinsic, XYZ, angles);
474/// // Confirmation
475/// let a_in = point_rotation(q_in, v);
476/// let b_in = point_rotation(e2q_in, v);
477/// assert!( (a_in[0] - b_in[0]).abs() < 1e-12 );
478/// assert!( (a_in[1] - b_in[1]).abs() < 1e-12 );
479/// assert!( (a_in[2] - b_in[2]).abs() < 1e-12 );
480///
481/// // ---- Extrinsic (X-Y-Z) ---- //
482/// // These represent the same rotation.
483/// let q_ex = mul( mul(z, y), x );
484/// let e2q_ex = from_euler_angles(Extrinsic, XYZ, angles);
485/// // Confirmation
486/// let a_ex = point_rotation(q_ex, v);
487/// let b_ex = point_rotation(e2q_ex, v);
488/// assert!( (a_ex[0] - b_ex[0]).abs() < 1e-12 );
489/// assert!( (a_ex[1] - b_ex[1]).abs() < 1e-12 );
490/// assert!( (a_ex[2] - b_ex[2]).abs() < 1e-12 );
491/// ```
492#[inline]
493pub fn from_euler_angles<T>(rt: RotationType, rs: RotationSequence, angles: Vector3<T>) -> Quaternion<T>
494where T: Float {
495 match rt {
496 RotationType::Intrinsic => euler::from_intrinsic_euler_angles(rs, angles),
497 RotationType::Extrinsic => euler::from_extrinsic_euler_angles(rs, angles),
498 }
499}
500
501/// Converts a **Versor** into a **Euler Angles**.
502///
503/// This function requires two parameters to fully define the rotation:
504///
505/// 1. `RotationType`: Specifies whether the rotation is **Intrinsic** or **Extrinsic**.
506/// 2. `RotationSequence`: Defines the three-axis sequence (e.g., XYZ, ZYX, XZX, ...).
507///
508/// The output `angles` array contains the three angles, corresponding to the sequence:
509/// `angles[0]` -> `angles[1]` -> `angles[2]`.
510/// Each angle is returned in the range: `(-PI, PI]`.
511///
512/// # Singularity (Gimbal Lock)
513///
514/// ## RotationType::Intrinsic
515///
516/// For Proper Euler Angles (ZXZ, XYX, YZY, ZYZ, XZX, YXY), the singularity is reached
517/// when the sine of the second rotation angle is 0 (angle = 0, ±π, ...), and for
518/// Tait-Bryan angles (XYZ, YZX, ZXY, XZY, ZYX, YXZ), the singularity is reached when
519/// the cosine of the second rotation angle is 0 (angle = ±π/2).
520///
521/// ## RotationType::Extrinsic
522///
523/// As in the case of Intrinsic rotation, for Proper Euler Angles, the singularity occurs
524/// when the sine of the second rotation angle is 0 (angle = 0, ±π, ...), and for
525/// Tait-Bryan angles, the singularity occurs when the cosine of the second rotation angle
526/// is 0 (angle = ±π/2).
527///
528/// ## Resolution at Singularity
529/// * For **Intrinsic** rotation, the **third angle** (`angles[2]`) is set to 0 \[rad\].
530/// * For **Extrinsic** rotation, the **first angle** (`angles[0]`) is set to 0 \[rad\].
531///
532/// # Examples
533///
534/// Depending on the rotation angle of each axis, it may not be possible to recover
535/// the same rotation angle as the original. However, they represent the same rotation in 3D space.
536///
537/// ```
538/// # use quaternion_core::{from_euler_angles, to_euler_angles, point_rotation};
539/// # let PI = std::f64::consts::PI;
540/// use quaternion_core::{RotationType::*, RotationSequence::XYZ};
541///
542/// let angles = [PI/6.0, PI/4.0, PI/3.0];
543///
544/// // ---- Intrinsic (X-Y-Z) ---- //
545/// let q_in = from_euler_angles(Intrinsic, XYZ, angles);
546/// let e_in = to_euler_angles(Intrinsic, XYZ, q_in);
547/// assert!( (angles[0] - e_in[0]).abs() < 1e-12 );
548/// assert!( (angles[1] - e_in[1]).abs() < 1e-12 );
549/// assert!( (angles[2] - e_in[2]).abs() < 1e-12 );
550///
551/// // ---- Extrinsic (X-Y-Z) ---- //
552/// let q_ex = from_euler_angles(Extrinsic, XYZ, angles);
553/// let e_ex = to_euler_angles(Extrinsic, XYZ, q_ex);
554/// assert!( (angles[0] - e_ex[0]).abs() < 1e-12 );
555/// assert!( (angles[1] - e_ex[1]).abs() < 1e-12 );
556/// assert!( (angles[2] - e_ex[2]).abs() < 1e-12 );
557/// ```
558#[inline]
559pub fn to_euler_angles<T>(rt: RotationType, rs: RotationSequence, q: Quaternion<T>) -> Vector3<T>
560where T: Float + FloatConst {
561 match rt {
562 RotationType::Intrinsic => euler::to_intrinsic_euler_angles(rs, q),
563 RotationType::Extrinsic => euler::to_extrinsic_euler_angles(rs, q),
564 }
565}
566
567/// Converts a **Rotation Vector** into a **Versor**.
568///
569/// A Rotation Vector is a convenient representation where:
570///
571/// 1. Its **direction** defines the **rotation axis**.
572/// 2. Its **norm** defines the **rotation angle** (in radians).
573///
574/// There are no particular restrictions on the norm of the input Rotation Vector.
575/// Also, even if a zero vector is input, the conversion to a Versor can be performed
576/// without falling into a singularity.
577///
578/// # Examples
579///
580/// ```
581/// # use quaternion_core::{from_rotation_vector, scale, point_rotation};
582/// # let PI = std::f64::consts::PI;
583/// let angle = PI / 2.0;
584/// let axis = [1.0, 0.0, 0.0];
585///
586/// // This represents a rotation of pi/2 around the x-axis.
587/// let rot_vec = scale(angle, axis); // Rotation vector
588///
589/// // Rotation vector ---> Quaternion
590/// let q = from_rotation_vector(rot_vec);
591///
592/// let r = point_rotation(q, [1.0, 1.0, 0.0]);
593///
594/// assert!( (r[0] - 1.0).abs() < 1e-12 );
595/// assert!( (r[1] - 0.0).abs() < 1e-12 );
596/// assert!( (r[2] - 1.0).abs() < 1e-12 );
597/// ```
598#[inline]
599pub fn from_rotation_vector<T>(r: Vector3<T>) -> Quaternion<T>
600where T: Float + FloatConst {
601 let half: T = pfs::cast(0.5);
602
603 let theta = norm(r) % ( T::PI() + T::PI() ); // Range reduction: [0, 2π)
604 let half_theta = half * theta;
605 (half_theta.cos(), scale(half * pfs::sinc(half_theta), r))
606}
607
608/// Converts a **Versor** into a **Rotation Vector**.
609///
610/// A Rotation Vector is a convenient representation where:
611///
612/// 1. Its **direction** defines the **rotation axis**.
613/// 2. Its **norm** defines the **rotation angle** (in radians).
614///
615/// The resulting vector's norm (the rotation angle) is always constrained
616/// to the range: `[0, PI]`
617///
618/// # Examples
619///
620/// ```
621/// # use quaternion_core::{from_axis_angle, to_rotation_vector, scale};
622/// # let PI = std::f64::consts::PI;
623/// let angle = PI / 2.0;
624/// let axis = [1.0, 0.0, 0.0];
625///
626/// // These represent the same rotation.
627/// let rv = scale(angle, axis); // Rotation vector
628/// let q = from_axis_angle(axis, angle); // Quaternion
629///
630/// // Quaternion ---> Rotation vector
631/// let q2rv = to_rotation_vector(q);
632///
633/// assert!( (rv[0] - q2rv[0]).abs() < 1e-12 );
634/// assert!( (rv[1] - q2rv[1]).abs() < 1e-12 );
635/// assert!( (rv[2] - q2rv[2]).abs() < 1e-12 );
636/// ```
637#[inline]
638pub fn to_rotation_vector<T>(q: Quaternion<T>) -> Vector3<T>
639where T: Float {
640 // half_thetaをasinで求めるとhalf_theta=±pi/2のときに精度低下するのでatanを使う.
641 let half_theta = (norm(q.1) / q.0).atan(); // [-pi/2, pi/2]
642 let coef = pfs::cast::<T>(2.0) / pfs::sinc(half_theta); // [2, pi]
643 scale(coef.copysign(q.0), q.1) // sinc関数は偶関数なので,half_thetaの符号をここで反映する必要がある.
644}
645
646/// Product of **Direction Cosine Matrix (DCM)** and **Vector3**
647///
648/// This is the product of a 3x3 matrix and a 3D vector.
649/// It is used to apply the rotation represented by the DCM to the vector.
650///
651/// # Examples
652///
653/// ```
654/// # use quaternion_core::{Vector3, Quaternion, matrix_product};
655/// # let PI = std::f64::consts::PI;
656/// let theta = PI / 2.0;
657/// let rot_x = [
658/// [1.0, 0.0, 0.0],
659/// [0.0, theta.cos(), -theta.sin()],
660/// [0.0, theta.sin(), theta.cos()]
661/// ];
662/// let v = [0.0, 1.0, 0.0];
663///
664/// let r = matrix_product(rot_x, v);
665/// assert!( (r[0] - 0.0).abs() < 1e-12 );
666/// assert!( (r[1] - 0.0).abs() < 1e-12 );
667/// assert!( (r[2] - 1.0).abs() < 1e-12 );
668/// ```
669#[inline]
670pub fn matrix_product<T>(m: DCM<T>, v: Vector3<T>) -> Vector3<T>
671where T: Float {
672 [
673 dot(m[0], v),
674 dot(m[1], v),
675 dot(m[2], v),
676 ]
677}
678
679/// Sum all elements of a Quaternion or Vector3.
680///
681/// # Examples
682///
683/// ```
684/// # use quaternion_core::{Vector3, Quaternion, sum};
685/// // --- Vector3 --- //
686/// let v: Vector3<f64> = [1.0, 2.0, 3.0];
687///
688/// assert!( (6.0 - sum(v)).abs() < 1e-12 );
689///
690/// // --- Quaternion --- //
691/// let q: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
692///
693/// assert!( (10.0 - sum(q)).abs() < 1e-12 );
694/// ```
695#[inline]
696pub fn sum<T, U>(a: U) -> T
697where T: Float, U: QuaternionOps<T> {
698 a.sum()
699}
700
701/// Addition of two Quaternions or Vector3s: `a + b`
702///
703/// # Examples
704///
705/// ```
706/// # use quaternion_core::{Vector3, Quaternion, add};
707/// // --- Vector3 --- //
708/// let v1: Vector3<f64> = [1.0, 2.0, 3.0];
709/// let v2: Vector3<f64> = [0.1, 0.2, 0.3];
710/// let v_result = add(v1, v2);
711///
712/// assert!( (1.1 - v_result[0]).abs() < 1e-12 );
713/// assert!( (2.2 - v_result[1]).abs() < 1e-12 );
714/// assert!( (3.3 - v_result[2]).abs() < 1e-12 );
715///
716/// // --- Quaternion --- //
717/// let q1: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
718/// let q2: Quaternion<f64> = (0.1, [0.2, 0.3, 0.4]);
719/// let q_result = add(q1, q2);
720///
721/// assert!( (1.1 - q_result.0).abs() < 1e-12 );
722/// assert!( (2.2 - q_result.1[0]).abs() < 1e-12 );
723/// assert!( (3.3 - q_result.1[1]).abs() < 1e-12 );
724/// assert!( (4.4 - q_result.1[2]).abs() < 1e-12 );
725/// ```
726#[inline]
727pub fn add<T, U>(a: U, b: U) -> U
728where T: Float, U: QuaternionOps<T> {
729 a.add(b)
730}
731
732/// Subtraction of two Quaternions or Vector3s: `a - b`
733///
734/// # Examples
735///
736/// ```
737/// # use quaternion_core::{Vector3, Quaternion, sub};
738/// // --- Vector3 --- //
739/// let v1: Vector3<f64> = [1.0, 2.0, 3.0];
740/// let v2: Vector3<f64> = [0.1, 0.2, 0.3];
741/// let v_result = sub(v1, v2);
742///
743/// assert!( (0.9 - v_result[0]).abs() < 1e-12 );
744/// assert!( (1.8 - v_result[1]).abs() < 1e-12 );
745/// assert!( (2.7 - v_result[2]).abs() < 1e-12 );
746///
747/// // --- Quaternion --- //
748/// let q1: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
749/// let q2: Quaternion<f64> = (0.1, [0.2, 0.3, 0.4]);
750/// let q_result = sub(q1, q2);
751///
752/// assert!( (0.9 - q_result.0).abs() < 1e-12 );
753/// assert!( (1.8 - q_result.1[0]).abs() < 1e-12 );
754/// assert!( (2.7 - q_result.1[1]).abs() < 1e-12 );
755/// assert!( (3.6 - q_result.1[2]).abs() < 1e-12 );
756/// ```
757#[inline]
758pub fn sub<T, U>(a: U, b: U) -> U
759where T: Float, U: QuaternionOps<T> {
760 a.sub(b)
761}
762
763/// Scaling a Quaternion or Vector3 by a scalar factor: `s * a`
764///
765/// # Examples
766///
767/// ```
768/// # use quaternion_core::{Vector3, Quaternion, scale};
769/// // --- Vector3 --- //
770/// let v: Vector3<f64> = [1.0, 2.0, 3.0];
771/// let v_result = scale(2.0, v);
772///
773/// assert!( (2.0 - v_result[0]).abs() < 1e-12 );
774/// assert!( (4.0 - v_result[1]).abs() < 1e-12 );
775/// assert!( (6.0 - v_result[2]).abs() < 1e-12 );
776///
777/// // --- Quaternion --- //
778/// let q: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
779/// let q_result = scale(2.0, q);
780///
781/// assert!( (2.0 - q_result.0).abs() < 1e-12 );
782/// assert!( (4.0 - q_result.1[0]).abs() < 1e-12 );
783/// assert!( (6.0 - q_result.1[1]).abs() < 1e-12 );
784/// assert!( (8.0 - q_result.1[2]).abs() < 1e-12 );
785/// ```
786#[inline]
787pub fn scale<T, U>(s: T, a: U) -> U
788where T: Float, U: QuaternionOps<T> {
789 a.scale(s)
790}
791
792/// Scaling and addition in one step: `s * a + b`
793///
794/// If the `fma` feature is enabled, the FMA calculation is performed using
795/// the `mul_add` method (`s.mul_add(a, b)`).
796/// If not enabled, it's computed by unfused multiply-add (`s * a + b`).
797///
798/// # Examples
799///
800/// ```
801/// # use quaternion_core::{Vector3, Quaternion, scale_add};
802/// // --- Vector3 --- //
803/// let v1: Vector3<f64> = [1.0, 2.0, 3.0];
804/// let v2: Vector3<f64> = [0.1, 0.2, 0.3];
805/// let v_result = scale_add(2.0, v1, v2);
806///
807/// assert!( (2.1 - v_result[0]).abs() < 1e-12 );
808/// assert!( (4.2 - v_result[1]).abs() < 1e-12 );
809/// assert!( (6.3 - v_result[2]).abs() < 1e-12 );
810///
811/// // --- Quaternion --- //
812/// let q1: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
813/// let q2: Quaternion<f64> = (0.1, [0.2, 0.3, 0.4]);
814/// let q_result = scale_add(2.0, q1, q2);
815///
816/// assert!( (2.1 - q_result.0).abs() < 1e-12 );
817/// assert!( (4.2 - q_result.1[0]).abs() < 1e-12 );
818/// assert!( (6.3 - q_result.1[1]).abs() < 1e-12 );
819/// assert!( (8.4 - q_result.1[2]).abs() < 1e-12 );
820/// ```
821#[inline]
822pub fn scale_add<T, U>(s: T, a: U, b: U) -> U
823where T: Float, U: QuaternionOps<T> {
824 a.scale_add(s, b)
825}
826
827/// Calculate the element-wise product of two Quaternions or Vector3s.
828///
829/// # Examples
830///
831/// ```
832/// # use quaternion_core::{Vector3, Quaternion, hadamard};
833/// // --- Vector3 --- //
834/// let v1: Vector3<f64> = [1.0, 2.0, 3.0];
835/// let v2: Vector3<f64> = [0.1, 0.2, 0.3];
836/// let v_result = hadamard(v1, v2);
837///
838/// assert!( (0.1 - v_result[0]).abs() < 1e-12 );
839/// assert!( (0.4 - v_result[1]).abs() < 1e-12 );
840/// assert!( (0.9 - v_result[2]).abs() < 1e-12 );
841///
842/// // --- Quaternion --- //
843/// let q1: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
844/// let q2: Quaternion<f64> = (0.1, [0.2, 0.3, 0.4]);
845/// let q_result = hadamard(q1, q2);
846///
847/// assert!( (0.1 - q_result.0).abs() < 1e-12 );
848/// assert!( (0.4 - q_result.1[0]).abs() < 1e-12 );
849/// assert!( (0.9 - q_result.1[1]).abs() < 1e-12 );
850/// assert!( (1.6 - q_result.1[2]).abs() < 1e-12 );
851/// ```
852#[inline]
853pub fn hadamard<T, U>(a: U, b: U) -> U
854where T: Float, U: QuaternionOps<T> {
855 a.hadamard(b)
856}
857
858/// Hadamard product and addition in one step.
859///
860/// If the `fma` feature is enabled, the FMA calculation is performed using
861/// the `mul_add` method (`s.mul_add(a, b)`).
862/// If not enabled, it's computed by unfused multiply-add (`s * a + b`).
863///
864/// # Examples
865///
866/// ```
867/// # use quaternion_core::{Vector3, Quaternion, hadamard_add};
868/// // --- Vector3 --- //
869/// let v1: Vector3<f64> = [1.0, 2.0, 3.0];
870/// let v2: Vector3<f64> = [0.1, 0.2, 0.3];
871/// let v3: Vector3<f64> = [0.4, 0.5, 0.6];
872/// let v_result = hadamard_add(v1, v2, v3);
873///
874/// assert!( (0.5 - v_result[0]).abs() < 1e-12 );
875/// assert!( (0.9 - v_result[1]).abs() < 1e-12 );
876/// assert!( (1.5 - v_result[2]).abs() < 1e-12 );
877///
878/// // --- Quaternion --- //
879/// let q1: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
880/// let q2: Quaternion<f64> = (0.1, [0.2, 0.3, 0.4]);
881/// let q3: Quaternion<f64> = (0.5, [0.6, 0.7, 0.8]);
882/// let q_result = hadamard_add(q1, q2, q3);
883///
884/// assert!( (0.6 - q_result.0).abs() < 1e-12 );
885/// assert!( (1.0 - q_result.1[0]).abs() < 1e-12 );
886/// assert!( (1.6 - q_result.1[1]).abs() < 1e-12 );
887/// assert!( (2.4 - q_result.1[2]).abs() < 1e-12 );
888/// ```
889#[inline]
890pub fn hadamard_add<T, U>(a: U, b: U, c: U) -> U
891where T: Float, U: QuaternionOps<T> {
892 a.hadamard_add(b, c)
893}
894
895/// Dot product of two Quaternions or Vector3s: `a · b`
896///
897/// # Examples
898///
899/// ```
900/// # use quaternion_core::{Vector3, Quaternion, dot};
901/// // --- Vector3 --- //
902/// let v1: Vector3<f64> = [1.0, 2.0, 3.0];
903/// let v2: Vector3<f64> = [0.1, 0.2, 0.3];
904///
905/// assert!( (1.4 - dot(v1, v2)).abs() < 1e-12 );
906///
907/// // --- Quaternion --- //
908/// let q1: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
909/// let q2: Quaternion<f64> = (0.1, [0.2, 0.3, 0.4]);
910///
911/// assert!( (3.0 - dot(q1, q2)).abs() < 1e-12 );
912/// ```
913#[inline]
914pub fn dot<T, U>(a: U, b: U) -> T
915where T: Float, U: QuaternionOps<T> {
916 a.dot(b)
917}
918
919/// Cross product of two Quaternions or Vector3s: `a × b`
920///
921/// The product order is `a × b (!= b × a)`
922///
923/// # Examples
924///
925/// ```
926/// # use quaternion_core::{Vector3, scale, cross};
927/// let v1: Vector3<f64> = [0.5, -1.0, 0.8];
928/// let v2: Vector3<f64> = scale(2.0, v1);
929/// let v_result = cross(v1, v2);
930///
931/// // The cross product of parallel vectors is a zero vector.
932/// assert!( v_result[0].abs() < 1e-12 );
933/// assert!( v_result[1].abs() < 1e-12 );
934/// assert!( v_result[2].abs() < 1e-12 );
935/// ```
936#[inline]
937pub fn cross<T>(a: Vector3<T>, b: Vector3<T>) -> Vector3<T>
938where T: Float {
939 [
940 a[1]*b[2] - a[2]*b[1],
941 a[2]*b[0] - a[0]*b[2],
942 a[0]*b[1] - a[1]*b[0],
943 ]
944}
945
946/// Calculate L2 norm of Vector3s or Quaternions.
947///
948/// Compared to `dot(a, a).sqrt()`, this function is less likely
949/// to cause overflow and underflow.
950///
951/// When the `norm-sqrt` feature is enabled, the default
952/// implementation is compiled with `dot(a, a).sqrt()` instead.
953///
954/// # Examples
955///
956/// ```
957/// # use quaternion_core::{Vector3, Quaternion, sum, dot, norm};
958/// // --- Vector3 --- //
959/// let v: Vector3<f64> = [1.0, 2.0, 3.0];
960/// assert!( (14.0_f64.sqrt() - norm(v)).abs() < 1e-12 );
961///
962/// // --- Quaternion --- //
963/// let q: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
964/// assert!( (30.0_f64.sqrt() - norm(q)).abs() < 1e-12 );
965///
966/// // --- Check about overflow --- //
967/// let v: Vector3<f32> = [1e15, 2e20, -3e15];
968/// assert_eq!( dot(v, v).sqrt(), f32::INFINITY ); // Oh...
969///
970/// #[cfg(not(feature = "norm-sqrt"))]
971/// assert_eq!( norm(v), 2e20 ); // Excellent!
972/// ```
973#[inline]
974pub fn norm<T, U>(a: U) -> T
975where T: Float, U: QuaternionOps<T> {
976 a.norm()
977}
978
979/// Normalize a Vector3 or Quaternion.
980///
981/// # Examples
982///
983/// ```
984/// # use quaternion_core::{Vector3, Quaternion, norm, normalize};
985/// // --- Vector3 --- //
986/// // This norm is not 1.
987/// let v: Vector3<f64> = [1.0, 2.0, 3.0];
988/// assert!( (1.0 - norm(v)).abs() > 1e-12 );
989///
990/// // Now that normalized, this norm is 1!
991/// let v_n = normalize(v);
992/// assert!( (1.0 - norm(v_n)).abs() < 1e-12 );
993///
994/// // --- Quaternion --- //
995/// // This norm is not 1.
996/// let q: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
997/// assert!( (1.0 - norm(q)).abs() > 1e-12 );
998///
999/// // Now that normalized, this norm is 1!
1000/// let q_n = normalize(q);
1001/// assert!( (1.0 - norm(q_n)).abs() < 1e-12 );
1002/// ```
1003#[inline]
1004pub fn normalize<T, U>(a: U) -> U
1005where T: Float, U: QuaternionOps<T> {
1006 scale(norm(a).recip(), a)
1007}
1008
1009/// Invert the sign of a Vector3s or Quaternions.
1010///
1011/// # Examples
1012///
1013/// ```
1014/// # use quaternion_core::{Vector3, Quaternion, negate};
1015/// // --- Vector3 --- //
1016/// let v: Vector3<f64> = [1.0, 2.0, 3.0];
1017/// let v_n = negate(v);
1018///
1019/// assert_eq!(-v[0], v_n[0]);
1020/// assert_eq!(-v[1], v_n[1]);
1021/// assert_eq!(-v[2], v_n[2]);
1022///
1023/// // --- Quaternion --- //
1024/// let q: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
1025/// let q_n = negate(q);
1026///
1027/// assert_eq!(-q.0, q_n.0);
1028/// assert_eq!(-q.1[0], q_n.1[0]);
1029/// assert_eq!(-q.1[1], q_n.1[1]);
1030/// assert_eq!(-q.1[2], q_n.1[2]);
1031/// ```
1032#[inline]
1033pub fn negate<T, U>(a: U) -> U
1034where T: Float, U: QuaternionOps<T> {
1035 a.negate()
1036}
1037
1038/// Multiplication of two Quaternions or Pure Quaternoins (Vector3).
1039///
1040/// This is an operation also known as the Hamilton product.
1041/// In this operation, the Vector3 is treated as a pure quaternoin (which is a quaternion with zero real part).
1042///
1043/// The product order is `ab (!= ba)`
1044///
1045/// # Examples
1046///
1047/// ```
1048/// # use quaternion_core::{Vector3, Quaternion, inv, mul};
1049/// // ---- Pure Quaternion (Vector3) ---- //
1050/// let v: Vector3<f64> = [1.0, 2.0, 3.0];
1051///
1052/// // Identity quaternion
1053/// let id = mul( v, inv(v) ); // = mul( inv(v), v );
1054///
1055/// assert!( (1.0 - id.0).abs() < 1e-12 );
1056/// assert!( id.1[0].abs() < 1e-12 );
1057/// assert!( id.1[1].abs() < 1e-12 );
1058/// assert!( id.1[2].abs() < 1e-12 );
1059///
1060/// // ---- Quaternion ---- //
1061/// let q: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
1062///
1063/// // Identity quaternion
1064/// let id = mul( q, inv(q) ); // = mul( inv(q), q );
1065///
1066/// assert!( (1.0 - id.0).abs() < 1e-12 );
1067/// assert!( id.1[0].abs() < 1e-12 );
1068/// assert!( id.1[1].abs() < 1e-12 );
1069/// assert!( id.1[2].abs() < 1e-12 );
1070/// ```
1071#[inline]
1072pub fn mul<T, U>(a: U, b: U) -> Quaternion<T>
1073where T: Float, U: QuaternionOps<T> {
1074 a.mul(b)
1075}
1076
1077/// Calculate the conjugate of a Quaternion.
1078///
1079/// # Examples
1080///
1081/// ```
1082/// # use quaternion_core::{Quaternion, conj};
1083/// let q: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
1084/// let q_conj = conj(q);
1085///
1086/// assert_eq!( q.0, q_conj.0);
1087/// assert_eq!(-q.1[0], q_conj.1[0]);
1088/// assert_eq!(-q.1[1], q_conj.1[1]);
1089/// assert_eq!(-q.1[2], q_conj.1[2]);
1090/// ```
1091#[inline]
1092pub fn conj<T>(q: Quaternion<T>) -> Quaternion<T>
1093where T: Float {
1094 ( q.0, negate(q.1) )
1095}
1096
1097/// Calculate the inverse of a Quaternion or Pure Quaternion (Vector3).
1098///
1099/// # Examples
1100///
1101/// ```
1102/// # use quaternion_core::{Vector3, Quaternion, inv, mul};
1103/// // ---- Pure Quaternion (Vector3) ---- //
1104/// let v: Vector3<f64> = [1.0, 2.0, 3.0];
1105///
1106/// // Identity quaternion
1107/// let id = mul( v, inv(v) ); // = mul( inv(v), v );
1108///
1109/// assert!( (id.0 - 1.0).abs() < 1e-12 );
1110/// assert!( id.1[0].abs() < 1e-12 );
1111/// assert!( id.1[1].abs() < 1e-12 );
1112/// assert!( id.1[2].abs() < 1e-12 );
1113///
1114/// // ---- Quaternion ---- //
1115/// let q: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
1116///
1117/// // Identity quaternion
1118/// let id = mul( q, inv(q) ); // = mul( inv(q), q );
1119///
1120/// assert!( (id.0 - 1.0).abs() < 1e-12 );
1121/// assert!( id.1[0].abs() < 1e-12 );
1122/// assert!( id.1[1].abs() < 1e-12 );
1123/// assert!( id.1[2].abs() < 1e-12 );
1124/// ```
1125#[inline]
1126pub fn inv<T, U>(a: U) -> U
1127where T: Float, U: QuaternionOps<T> {
1128 a.inv()
1129}
1130
1131// acosは[-pi/2, pi/2]の範囲でしか値を返さないので、qのとり方によってはlnで完全に復元できない。
1132// q == ln(exp(q)) が成り立つのはcos(norm(q.1))が[-pi/2, pi/2]の範囲内にある場合のみ。
1133//
1134/// Exponential function of a Quaternion or Pure Quaternion (Vector3).
1135///
1136/// # Examples
1137///
1138/// ```
1139/// # use quaternion_core::{Vector3, Quaternion, scale, exp, ln};
1140/// // ---- Pure Quaternion (Vector3) ---- //
1141/// let v: Vector3<f64> = [0.1, 0.2, 0.3];
1142/// let v_r = ln( exp(v) );
1143///
1144/// assert!( v_r.0.abs() < 1e-12 );
1145/// assert!( (v[0] - v_r.1[0]).abs() < 1e-12 );
1146/// assert!( (v[1] - v_r.1[1]).abs() < 1e-12 );
1147/// assert!( (v[2] - v_r.1[2]).abs() < 1e-12 );
1148///
1149/// // ---- Quaternion ---- //
1150/// let q: Quaternion<f64> = (0.1, [0.2, 0.3, 0.4]);
1151/// let q_r = ln( exp(q) );
1152///
1153/// assert!( (q.0 - q_r.0).abs() < 1e-12 );
1154/// assert!( (q.1[0] - q_r.1[0]).abs() < 1e-12 );
1155/// assert!( (q.1[1] - q_r.1[1]).abs() < 1e-12 );
1156/// assert!( (q.1[2] - q_r.1[2]).abs() < 1e-12 );
1157///
1158/// // The relationship between exp(q) and exp(q.1)
1159/// let exp_q = exp(q);
1160/// let exp_check = scale( q.0.exp(), exp(q.1) );
1161/// assert!( (exp_q.0 - exp_check.0).abs() < 1e-12 );
1162/// assert!( (exp_q.1[0] - exp_check.1[0]).abs() < 1e-12 );
1163/// assert!( (exp_q.1[1] - exp_check.1[1]).abs() < 1e-12 );
1164/// assert!( (exp_q.1[2] - exp_check.1[2]).abs() < 1e-12 );
1165/// ```
1166#[inline]
1167pub fn exp<T, U>(a: U) -> Quaternion<T>
1168where T: Float, U: QuaternionOps<T> {
1169 a.exp()
1170}
1171
1172// acosは[-pi/2, pi/2]の範囲でしか値を返さないので、qのとり方によってはlnで完全に復元できない。
1173// q == ln(exp(q)) が成り立つのはcos(norm(q.1))が[-pi/2, pi/2]の範囲内にある場合のみ。
1174//
1175/// Natural logarithm of a Quaternion.
1176///
1177/// # Examples
1178///
1179/// ```
1180/// # use quaternion_core::{Vector3, Quaternion, exp, ln};
1181/// let q: Quaternion<f64> = (0.1, [0.2, 0.3, 0.4]);
1182/// let q_r = ln( exp(q) );
1183///
1184/// assert!( (q.0 - q_r.0).abs() < 1e-12 );
1185/// assert!( (q.1[0] - q_r.1[0]).abs() < 1e-12 );
1186/// assert!( (q.1[1] - q_r.1[1]).abs() < 1e-12 );
1187/// assert!( (q.1[2] - q_r.1[2]).abs() < 1e-12 );
1188/// ```
1189#[inline]
1190pub fn ln<T>(q: Quaternion<T>) -> Quaternion<T>
1191where T: Float {
1192 let norm_v = norm(q.1);
1193 let norm_q = pfs::norm2(q.0, norm_v);
1194 let omega = (norm_v / q.0).atan();
1195 let coef = (norm_q * pfs::sinc(omega)).recip();
1196
1197 ( norm_q.ln(), scale(coef, q.1) )
1198}
1199
1200// exp(q)の結果がVersorとなる条件は,qのスカラー部が0(つまりqが純虚四元数).
1201//
1202/// Natural logarithm of a Versor.
1203///
1204/// If the argument `q` is guaranteed to be a Versor,
1205/// it is less calculation cost than the `ln(...)` function.
1206///
1207/// Only the vector part is returned since the real part is always zero.
1208///
1209/// # Examples
1210///
1211/// ```
1212/// # use quaternion_core::{Vector3, exp, ln_versor};
1213/// let v: Vector3<f64> = [0.1, 0.2, 0.3];
1214/// let r = ln_versor( exp(v) );
1215///
1216/// assert!( (v[0] - r[0]).abs() < 1e-12 );
1217/// assert!( (v[1] - r[1]).abs() < 1e-12 );
1218/// assert!( (v[2] - r[2]).abs() < 1e-12 );
1219/// ```
1220#[inline]
1221pub fn ln_versor<T>(q: Quaternion<T>) -> Vector3<T>
1222where T: Float {
1223 let omega = (norm(q.1) / q.0).atan();
1224 let coef = pfs::sinc(omega).recip();
1225
1226 scale(coef, q.1)
1227}
1228
1229/// Power function of a Quaternion.
1230///
1231/// # Examples
1232///
1233/// ```
1234/// # use quaternion_core::{Quaternion, mul, inv, pow, sqrt};
1235/// let q: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
1236///
1237/// let q_pow_0 = pow(q, 0.0);
1238/// assert!( (1.0 - q_pow_0.0).abs() < 1e-12 );
1239/// assert!( (0.0 - q_pow_0.1[0]).abs() < 1e-12 );
1240/// assert!( (0.0 - q_pow_0.1[1]).abs() < 1e-12 );
1241/// assert!( (0.0 - q_pow_0.1[2]).abs() < 1e-12 );
1242///
1243/// let q_q = mul(q, q);
1244/// let q_pow_2 = pow(q, 2.0);
1245/// assert!( (q_q.0 - q_pow_2.0).abs() < 1e-12 );
1246/// assert!( (q_q.1[0] - q_pow_2.1[0]).abs() < 1e-12 );
1247/// assert!( (q_q.1[1] - q_pow_2.1[1]).abs() < 1e-12 );
1248/// assert!( (q_q.1[2] - q_pow_2.1[2]).abs() < 1e-12 );
1249///
1250/// let q_sqrt = sqrt(q);
1251/// let q_pow_0p5 = pow(q, 0.5);
1252/// assert!( (q_sqrt.0 - q_pow_0p5.0).abs() < 1e-12 );
1253/// assert!( (q_sqrt.1[0] - q_pow_0p5.1[0]).abs() < 1e-12 );
1254/// assert!( (q_sqrt.1[1] - q_pow_0p5.1[1]).abs() < 1e-12 );
1255/// assert!( (q_sqrt.1[2] - q_pow_0p5.1[2]).abs() < 1e-12 );
1256///
1257/// let q_inv = inv(q);
1258/// let q_pow_m1 = pow(q, -1.0);
1259/// assert!( (q_inv.0 - q_pow_m1.0).abs() < 1e-12 );
1260/// assert!( (q_inv.1[0] - q_pow_m1.1[0]).abs() < 1e-12 );
1261/// assert!( (q_inv.1[1] - q_pow_m1.1[1]).abs() < 1e-12 );
1262/// assert!( (q_inv.1[2] - q_pow_m1.1[2]).abs() < 1e-12 );
1263/// ```
1264#[inline]
1265pub fn pow<T>(q: Quaternion<T>, t: T) -> Quaternion<T>
1266where T: Float {
1267 let norm_v = norm(q.1);
1268 let norm_q = pfs::norm2(q.0, norm_v);
1269 let omega = (norm_v / q.0).atan();
1270 let coef = norm_q.powf(t);
1271 let tmp = t * omega;
1272 let numer = coef * t * pfs::sinc(tmp);
1273 let denom = norm_q * pfs::sinc(omega);
1274 ( coef * tmp.cos(), scale(numer / denom, q.1) )
1275}
1276
1277/// Power function of a Versor.
1278///
1279/// If the argument `q` is guaranteed to be a Versor,
1280/// it is less calculation cost than the `pow(...)` function.
1281///
1282/// # Examples
1283///
1284/// ```
1285/// # use quaternion_core::{Quaternion, normalize, mul, inv, pow_versor, sqrt};
1286/// let q: Quaternion<f64> = normalize( (1.0, [2.0, 3.0, 4.0]) );
1287///
1288/// let q_pow_0 = pow_versor(q, 0.0);
1289/// assert!( (1.0 - q_pow_0.0).abs() < 1e-12 );
1290/// assert!( (0.0 - q_pow_0.1[0]).abs() < 1e-12 );
1291/// assert!( (0.0 - q_pow_0.1[1]).abs() < 1e-12 );
1292/// assert!( (0.0 - q_pow_0.1[2]).abs() < 1e-12 );
1293///
1294/// let q_q = mul(q, q);
1295/// let q_pow_2 = pow_versor(q, 2.0);
1296/// assert!( (q_q.0 - q_pow_2.0).abs() < 1e-12 );
1297/// assert!( (q_q.1[0] - q_pow_2.1[0]).abs() < 1e-12 );
1298/// assert!( (q_q.1[1] - q_pow_2.1[1]).abs() < 1e-12 );
1299/// assert!( (q_q.1[2] - q_pow_2.1[2]).abs() < 1e-12 );
1300///
1301/// let q_sqrt = sqrt(q);
1302/// let q_pow_0p5 = pow_versor(q, 0.5);
1303/// assert!( (q_sqrt.0 - q_pow_0p5.0).abs() < 1e-12 );
1304/// assert!( (q_sqrt.1[0] - q_pow_0p5.1[0]).abs() < 1e-12 );
1305/// assert!( (q_sqrt.1[1] - q_pow_0p5.1[1]).abs() < 1e-12 );
1306/// assert!( (q_sqrt.1[2] - q_pow_0p5.1[2]).abs() < 1e-12 );
1307///
1308/// let q_inv = inv(q);
1309/// let q_pow_m1 = pow_versor(q, -1.0);
1310/// assert!( (q_inv.0 - q_pow_m1.0).abs() < 1e-12 );
1311/// assert!( (q_inv.1[0] - q_pow_m1.1[0]).abs() < 1e-12 );
1312/// assert!( (q_inv.1[1] - q_pow_m1.1[1]).abs() < 1e-12 );
1313/// assert!( (q_inv.1[2] - q_pow_m1.1[2]).abs() < 1e-12 );
1314/// ```
1315#[inline]
1316pub fn pow_versor<T>(q: Quaternion<T>, t: T) -> Quaternion<T>
1317where T: Float {
1318 let omega = ( norm(q.1) / q.0 ).atan();
1319 let tmp = t * omega;
1320 ( tmp.cos(), scale(t * pfs::sinc(tmp) / pfs::sinc(omega), q.1) )
1321}
1322
1323/// Square root of a Quaternion.
1324///
1325/// # Examples
1326///
1327/// ```
1328/// # use quaternion_core::{Quaternion, mul, sqrt};
1329/// let q: Quaternion<f64> = (1.0, [2.0, 3.0, 4.0]);
1330/// let q_sqrt = sqrt(q);
1331///
1332/// let result = mul(q_sqrt, q_sqrt);
1333/// assert!( (q.0 - result.0).abs() < 1e-12 );
1334/// assert!( (q.1[0] - result.1[0]).abs() < 1e-12 );
1335/// assert!( (q.1[1] - result.1[1]).abs() < 1e-12 );
1336/// assert!( (q.1[2] - result.1[2]).abs() < 1e-12 );
1337/// ```
1338#[inline]
1339pub fn sqrt<T>(q: Quaternion<T>) -> Quaternion<T>
1340where T: Float {
1341 let half = pfs::cast(0.5);
1342 let norm_v = norm(q.1);
1343 let norm_q = pfs::norm2(q.0, norm_v);
1344 let omega = (norm_v / q.0).atan();
1345 let coef = half * pfs::sinc(omega*half) / (norm_q.sqrt() * pfs::sinc(omega));
1346 ( ((norm_q + q.0) * half).sqrt(), scale(coef, q.1) )
1347}
1348
1349/// Square root of a Versor.
1350///
1351/// If the argument `q` is guaranteed to be a Versor,
1352/// it is less calculation cost than the `sqrt(...)` function.
1353///
1354/// # Examples
1355///
1356/// ```
1357/// # use quaternion_core::{Quaternion, normalize, mul, sqrt_versor};
1358/// let q: Quaternion<f64> = normalize( (1.0, [2.0, 3.0, 4.0]) );
1359/// let q_sqrt = sqrt_versor(q);
1360///
1361/// let result = mul(q_sqrt, q_sqrt);
1362/// assert!( (q.0 - result.0).abs() < 1e-12 );
1363/// assert!( (q.1[0] - result.1[0]).abs() < 1e-12 );
1364/// assert!( (q.1[1] - result.1[1]).abs() < 1e-12 );
1365/// assert!( (q.1[2] - result.1[2]).abs() < 1e-12 );
1366/// ```
1367#[inline]
1368pub fn sqrt_versor<T>(q: Quaternion<T>) -> Quaternion<T>
1369where T: Float {
1370 let half = pfs::cast(0.5);
1371 let omega = (norm(q.1) / q.0).atan();
1372 let coef = half * pfs::sinc(omega*half) / pfs::sinc(omega);
1373 ( pfs::mul_add(q.0, half, half).sqrt(), scale(coef, q.1) )
1374}
1375
1376/// Rotates a point by the Versor (Point Rotation - Frame Fixed)
1377///
1378/// `q v q* (||q|| = 1)`
1379///
1380/// Since it is implemented with an optimized formula,
1381/// it can be calculated with the amount of operations shown in the table below:
1382///
1383/// | Operation | Num |
1384/// |:------------:|:---:|
1385/// | Multiply | 18 |
1386/// | Add/Subtract | 12 |
1387///
1388/// # Examples
1389///
1390/// ```
1391/// # use quaternion_core::{from_axis_angle, point_rotation, mul, conj};
1392/// # let PI = std::f64::consts::PI;
1393/// // Make these as you like.
1394/// let v = [1.0, 0.5, -8.0];
1395/// let q = from_axis_angle([0.2, 1.0, -2.0], PI);
1396///
1397/// let r = point_rotation(q, v);
1398///
1399/// // This makes a lot of wasted calculations.
1400/// let r_check = mul( mul(q, (0.0, v)), conj(q) ).1;
1401///
1402/// assert!( (r[0] - r_check[0]).abs() < 1e-12 );
1403/// assert!( (r[1] - r_check[1]).abs() < 1e-12 );
1404/// assert!( (r[2] - r_check[2]).abs() < 1e-12 );
1405/// ```
1406#[inline]
1407pub fn point_rotation<T>(q: Quaternion<T>, v: Vector3<T>) -> Vector3<T>
1408where T: Float {
1409 let tmp = scale_add(q.0, v, cross(q.1, v));
1410 scale_add(pfs::cast(2.0), cross(q.1, tmp), v)
1411}
1412
1413/// Rotates a frame by the Versor (Frame Rotation - Point Fixed)
1414///
1415/// `q* v q (||q|| = 1)`
1416///
1417/// Since it is implemented with an optimized formula,
1418/// it can be calculated with the amount of operations shown in the table below:
1419///
1420/// | Operation | Num |
1421/// |:------------:|:---:|
1422/// | Multiply | 18 |
1423/// | Add/Subtract | 12 |
1424///
1425/// # Examples
1426///
1427/// ```
1428/// # use quaternion_core::{from_axis_angle, point_rotation, mul, conj};
1429/// # let PI = std::f64::consts::PI;
1430/// // Make these as you like.
1431/// let v = [1.0, 0.5, -8.0];
1432/// let q = from_axis_angle([0.2, 1.0, -2.0], PI);
1433///
1434/// let r = point_rotation(q, v);
1435///
1436/// // This makes a lot of wasted calculations.
1437/// let r_check = mul( mul(conj(q), (0.0, v)), q ).1;
1438///
1439/// assert!( (r[0] - r_check[0]).abs() < 1e-12 );
1440/// assert!( (r[1] - r_check[1]).abs() < 1e-12 );
1441/// assert!( (r[2] - r_check[2]).abs() < 1e-12 );
1442/// ```
1443#[inline]
1444pub fn frame_rotation<T>(q: Quaternion<T>, v: Vector3<T>) -> Vector3<T>
1445where T: Float {
1446 let tmp = scale_add(q.0, v, cross(v, q.1));
1447 scale_add(pfs::cast(2.0), cross(tmp, q.1), v)
1448}
1449
1450/// Calculate the Versor to rotate from vector `a` to vector `b` (Without singularity!).
1451///
1452/// This function calculates `q` satisfying `b = point_rotation(q, a)` when `norm(a) = norm(b)`.
1453///
1454/// # Characteristics
1455///
1456/// * **Robustness:** This function can accurately calculate the versor regardless of the
1457/// combination of vector orientations (however, `norm(a) > 0` and `norm(b) > 0`).
1458/// * **Axis Ambiguity:** This function provides **no guarantees** regarding the direction
1459/// or regularity of the rotation axis. If you require a rotation axis that is **orthogonal**
1460/// to both vector `a` and vector `b`, you should use `rotate_a_to_b_shortest` function.
1461///
1462/// # Returns
1463///
1464/// Returns `None` if either input vector `a` or `b` is a zero vector,
1465/// as a rotation cannot be uniquely defined in that case.
1466///
1467/// # Examples
1468///
1469/// ```
1470/// # use quaternion_core::{Vector3, cross, rotate_a_to_b, point_rotation, normalize};
1471/// let a: Vector3<f64> = [1.5, -0.5, 0.2];
1472/// let b: Vector3<f64> = [0.1, 0.6, 1.0];
1473///
1474/// let q = rotate_a_to_b(a, b).unwrap();
1475/// let b_check = point_rotation(q, a);
1476///
1477/// let b_u = normalize(b);
1478/// let b_check_u = normalize(b_check);
1479/// assert!( (b_u[0] - b_check_u[0]).abs() < 1e-12 );
1480/// assert!( (b_u[1] - b_check_u[1]).abs() < 1e-12 );
1481/// assert!( (b_u[2] - b_check_u[2]).abs() < 1e-12 );
1482/// ```
1483#[inline]
1484pub fn rotate_a_to_b<T>(a: Vector3<T>, b: Vector3<T>) -> Option<Quaternion<T>>
1485where T: Float {
1486 let norm_inv_a = norm(a).recip();
1487 let norm_inv_b = norm(b).recip();
1488 if norm_inv_a.is_infinite() || norm_inv_b.is_infinite() {
1489 return None;
1490 }
1491 let a = scale(norm_inv_a, a);
1492 let b = scale(norm_inv_b, b);
1493
1494 let a_add_b = add(a, b);
1495 let dot_a_add_b = dot(a_add_b, a_add_b);
1496 if dot_a_add_b >= T::one() { // arccos(a・b) = 120degで切り替え
1497 Some( (T::zero(), scale(dot_a_add_b.sqrt().recip(), a_add_b)) )
1498 } else {
1499 let norm_a_sub_b = (pfs::cast::<T>(4.0) - dot_a_add_b).sqrt();
1500 let axis_a2mb = scale(norm_a_sub_b.recip(), sub(a, b)); // a ==> -b
1501 let axis_mb2b = pfs::orthogonal_vector(b); // -b ==> b
1502 Some( mul(axis_mb2b, axis_a2mb) )
1503 }
1504}
1505
1506/// Calculate the versor to rotate from vector `a` to vector `b` by the shortest path.
1507///
1508/// This function calculates `q` satisfying `b = point_rotation(q, a)` when `norm(a) = norm(b)`.
1509///
1510/// # Characteristics
1511///
1512/// * **Shortest Path:** This method guarantees the rotation axis is always **orthogonal** to
1513/// both vector **a** and vector **b**, representing the geometrically shortest path between
1514/// the two directions.
1515/// * **Rotation Angle:** The rotation angle is in the range `[0, PI]` radians.
1516/// * **Parallel Vectors:** If vector `a` and `b` are **opposite** and parallel, the
1517/// rotation axis is theoretically ambiguous. This function provides a valid rotation,
1518/// but the axis direction is not guaranteed (although it will be orthogonal to the `a` and `b`).
1519///
1520/// # Performance Consideration
1521///
1522/// This function is slightly more computationally intensive than `rotate_a_to_b`,
1523/// especially when the angle between the vectors is near PI. If an orthogonal rotation
1524/// axis is not strictly required, `rotate_a_to_b` may be preferred for performance.
1525///
1526/// # Returns
1527///
1528/// Returns `None` if either input vector **a** or **b** is a zero vector,
1529/// as a rotation cannot be uniquely defined in that case.
1530///
1531/// # Examples
1532///
1533/// ```
1534/// # use quaternion_core::{Vector3, scale, cross, to_rotation_vector, from_rotation_vector, rotate_a_to_b_shortest, point_rotation, normalize};
1535/// let a: Vector3<f64> = [1.5, -0.5, 0.2];
1536/// let b: Vector3<f64> = [0.1, 0.6, 1.0];
1537///
1538/// let q = rotate_a_to_b_shortest(a, b).unwrap();
1539/// let b_check = point_rotation(q, a);
1540///
1541/// let b_u = normalize(b);
1542/// let b_check_u = normalize(b_check);
1543/// assert!( (b_u[0] - b_check_u[0]).abs() < 1e-12 );
1544/// assert!( (b_u[1] - b_check_u[1]).abs() < 1e-12 );
1545/// assert!( (b_u[2] - b_check_u[2]).abs() < 1e-12 );
1546///
1547/// // --- If the amount of displacement of vector `a` is to be adjusted --- //
1548/// // The parameter `t` adjusts the amount of movement from `a` to `b`.
1549/// // When `t = 1`, `a` moves completely to position `b`.
1550/// let t = 0.5;
1551/// let mut q = rotate_a_to_b_shortest(a, b).unwrap();
1552/// let r = to_rotation_vector(q); // To avoid singularities, proceed via the rotation vector.
1553/// q = from_rotation_vector(scale(t, r));
1554/// ```
1555#[inline]
1556pub fn rotate_a_to_b_shortest<T>(a: Vector3<T>, b: Vector3<T>) -> Option<Quaternion<T>>
1557where T: Float {
1558 let norm_inv_a = norm(a).recip();
1559 let norm_inv_b = norm(b).recip();
1560 if norm_inv_a.is_infinite() || norm_inv_b.is_infinite() {
1561 return None;
1562 }
1563 let a = scale(norm_inv_a, a);
1564 let b = scale(norm_inv_b, b);
1565
1566 let half = pfs::cast::<T>(0.5);
1567 let a_dot_b = dot(a, b); // == cos(theta)
1568 if a_dot_b > pfs::cast(-0.94) { // theta < 160 deg
1569 let q_s = (half + half * a_dot_b).sqrt(); // == cos(theta/2)
1570 Some( (q_s, scale(half / q_s, cross(a, b))) ) // a --> b
1571 } else {
1572 let b_cross_a = cross(b, a);
1573 let q_s = (half - half * a_dot_b).sqrt(); // == cos((pi-theta)/2)
1574 let q_a2mb = (q_s, scale(half / q_s, b_cross_a)); // a --> -b
1575 let r_o = pfs::orthogonal_vector(b);
1576
1577 let c = sub(b_cross_a, r_o);
1578 let r_o_cross_c = cross(r_o, c);
1579
1580 // rho < pi/2
1581 let norm_c = norm(c); // norm_c > 0
1582 let norm_c_sin_rho = norm(r_o_cross_c).copysign( dot(r_o_cross_c, b) ); // norm(c) * sin(rho)
1583 let norm_c_cos_rho = (norm_c * norm_c - norm_c_sin_rho * norm_c_sin_rho).sqrt(); // norm(c) * cos(rho)
1584
1585 // r_o と b_cross_a の間の角度lambdaを求める
1586 let lambda = norm_c_sin_rho.atan2(T::one() - norm_c_cos_rho); // (-pi, pi]
1587
1588 let (sin, cos) = (half * lambda).sin_cos();
1589 let q_b = (cos, scale(sin, b));
1590 let r = point_rotation(q_b, r_o); // -b --> a
1591
1592 let q_a2b_s = -dot(r, q_a2mb.1);
1593 let q_a2b_v = scale_add(q_a2mb.0, r, cross(r, q_a2mb.1));
1594 Some( (q_a2b_s, q_a2b_v) ) // a --> b
1595 }
1596}
1597
1598/// Lerp (Linear interpolation)
1599///
1600/// Generate a Versor that interpolate the shortest path from `a` to `b`.
1601/// The argument `t (0 <= t <= 1)` is the interpolation parameter.
1602///
1603/// The arguments `a` and `b` must be Versor.
1604///
1605/// Normalization is not performed internally because
1606/// it increases the computational complexity.
1607#[inline]
1608pub fn lerp<T>(a: Quaternion<T>, b: Quaternion<T>, t: T) -> Quaternion<T>
1609where T: Float {
1610 // 最短経路で補間する
1611 if dot(a, b).is_sign_negative() {
1612 // bの符号を反転
1613 scale_add(-t, add(a, b), a)
1614 } else {
1615 scale_add( t, sub(b, a), a)
1616 }
1617}
1618
1619/// Slerp (Spherical linear interpolation)
1620///
1621/// Generate a Versor that interpolate the shortest path from `a` to `b`.
1622/// The argument `t (0 <= t <= 1)` is the interpolation parameter.
1623///
1624/// The arguments `a` and `b` must be Versor.
1625#[inline]
1626pub fn slerp<T>(a: Quaternion<T>, mut b: Quaternion<T>, t: T) -> Quaternion<T>
1627where T: Float {
1628 // 最短経路で補間する
1629 let mut dot = dot(a, b);
1630 if dot.is_sign_negative() {
1631 b = negate(b);
1632 dot = -dot;
1633 }
1634 // If the distance between quaternions is close enough, use lerp.
1635 if dot > pfs::cast(0.9995) { // Approximation error < 0.017%
1636 scale_add(t, sub(b, a), a) // lerp
1637 } else {
1638 let omega = dot.acos(); // Angle between the two quaternions.
1639 let tmp = t * omega;
1640 let s1 = (omega - tmp).sin();
1641 let s2 = tmp.sin();
1642 let coef = (T::one() - dot*dot).sqrt().recip();
1643 let term1 = scale(s1 * coef, a);
1644 let term2 = scale(s2 * coef, b);
1645 add(term1, term2)
1646 }
1647}