SuperDex Physics C++ API
Loading...
Searching...
No Matches
quaternion_inl.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19#include "quaternion.h" // For IntelliSense
20
21namespace superdex {
22
23/************************************************************************************
24 Quaternion Inlines
25*/
29
33
35 return Quaternion{Sin(a * 0.5_r), 0_r, 0_r, Cos(a * 0.5_r)};
36}
37
39 return Quaternion{0_r, Sin(a * 0.5_r), 0_r, Cos(a * 0.5_r)};
40}
41
43 return Quaternion{0_r, 0_r, Sin(a * 0.5_r), Cos(a * 0.5_r)};
44}
45
47 return Real4{data[0], data[1], data[2], data[3]};
48}
49
50inline Quaternion Quaternion::FromUnitAxisAngle(Vec4r normalizedAxis, real angleRadians) {
51 // Log a warning in debug builds if the axis is not unit length (non-fatal unlike an assert).
52#if MOCHI_ASSERT_VERBOSE_ENABLED && MOCHI_LOG_ENABLED
53 auto norm = Norm<3>(normalizedAxis);
56 "Quaternion::FromUnitAxisAngle expects a unit length vector, but got [%g, %g, %g] (magnitude %g).",
57 normalizedAxis[0],
58 normalizedAxis[1],
59 normalizedAxis[2],
60 norm);
61 }
62#endif
63 // Use double precision to avoid rounding error in the trig functions.
64 double c = Cos(static_cast<double>(angleRadians) * 0.5);
65 double s = Sin(static_cast<double>(angleRadians) * 0.5);
66 Vec4d v = Set<3>(StaticCast<Vec4d>(normalizedAxis) * s, c);
68}
69
70inline Quaternion Quaternion::FromAxisAngle(Vec4r axis, real angleRadians) {
71 return FromUnitAxisAngle(Normalize<3>(axis), angleRadians);
72}
73
74inline Quaternion Quaternion::FromAxisAngle(Real3 const& axis, real angleRadians) {
75 return FromAxisAngle(Vec4r{axis[0], axis[1], axis[2], 0_r}, angleRadians);
76}
77
79 Vec4r angle = VNorm<3>(rotVector);
80 real rangle = Get0(angle);
81 if (rangle > 1e-9_r) MOCHI_LIKELY {
82 Vec4r axis = ToSimdDirection(rotVector) / angle;
83 return FromUnitAxisAngle(axis, rangle);
84 } else {
85 // q = (xyz, w)
86 // xyz = v/|v| * sin(|v|/2) ≈ v/|v| * |v|/2 = 0.5 * v
87 // w = cos(|v|/2) ≈ 1 - |v|^2/8 ≈ 1
88 return Quaternion(ToSimdPoint(0.5_r * rotVector));
89 }
90}
91
93 Vec4r vrotVector(rotVector[0], rotVector[1], rotVector[2], 0.0_r);
94 return FromRotationVector(vrotVector);
95}
96
97inline real Quaternion::GetAngleImpl(Quaternion& qPositiveNormalized, real& vectorMag) const {
98 // We compute the angle using the part of the quaternion (the vector part (x, y, z) or the scalar
99 // part w) that is smaller, as this provides higher precision.
100 qPositiveNormalized = Quaternion{Normalize<4>(this->data)};
101 // For simplicity, use always the quaternion with positive scalar part.
102 if (qPositiveNormalized.data[3] < 0_r) {
103 qPositiveNormalized.data = -qPositiveNormalized.data;
104 }
105 real w = qPositiveNormalized.data[3]; // Scalar part (always >= 0)
106 vectorMag = Norm<3>(qPositiveNormalized.data); // Norm of the vector part
107 // Note that vectorMag^2 + w^2 = 1. However, we do not compute vectorMag = sqrt(1 - w^2) to avoid
108 // catastrophic cancellation when vectorMag is small but w = 1. This can often happen with single
109 // precision for small angles.
110 return 2_r * (w < vectorMag ? ACos(w) : ASin(vectorMag));
111}
112
114 Quaternion qPositiveNormalized MOCHI_NO_INIT; // discarded
115 real vectorMag MOCHI_NO_INIT; // discarded
116 return GetAngleImpl(qPositiveNormalized, vectorMag);
117}
118
119inline void Quaternion::ToAxisAngle(Real3* outAxis, real* outAngleRad) const {
120 Quaternion qPositiveNormalized MOCHI_NO_INIT;
121 real vectorMag MOCHI_NO_INIT;
122 *outAngleRad = GetAngleImpl(qPositiveNormalized, vectorMag);
123 auto axis =
124 vectorMag > 1e-9_r ? (qPositiveNormalized.data / vectorMag) : Vec4r{1_r, 0_r, 0_r, 0_r};
125 *outAxis = Real3{axis[0], axis[1], axis[2]};
126}
127
128inline void Quaternion::ToAxisAngle(Vec4r* outAxis, real* outAngleRad) const {
129 Real3 outAxisTemp MOCHI_NO_INIT;
130 this->ToAxisAngle(&outAxisTemp, outAngleRad);
131 *outAxis = Vec4r{outAxisTemp[0], outAxisTemp[1], outAxisTemp[2], 0_r};
132}
133
135 Vec4r outAxis MOCHI_NO_INIT; // NOLINT(cppcoreguidelines-init-variables)
136 real outAngle MOCHI_NO_INIT; // NOLINT(cppcoreguidelines-init-variables)
137 this->ToAxisAngle(&outAxis, &outAngle);
138 return outAxis * outAngle;
139}
140
142 auto r = VToRotationVector();
143 return Real3{r[0], r[1], r[2]};
144}
145
147 return data == rhs.data;
148}
149
151 return data != rhs.data;
152}
153
166
170
172 // The canonical way to multiply this quaternion q by vector v is:
173 //
174 // v' = q * v * conjugate(q)
175 //
176 // where the vector v is treated as a quaternion with w=0, but that is rather expensive since
177 // quaternion multiplication is not very SIMD friendly (unless you do multiple pairs of
178 // quaternions at once). Fortunately, there is a faster way:
179 //
180 // t = 2 * cross(q.xyz, v)
181 // v' = v + q.w * t + cross(q.xyz, t)
182 //
183 // With the MSVC x64 compiler, this results in 27 total instructions vs 55 instructions for the
184 // canonical approach. A derivation of the formula can be found here:
185 // https://fgiesen.wordpress.com/2019/02/09/rotating-a-single-vector-using-a-quaternion/
186 //
187 Vec4r c = Cross3(this->data, v);
188 Vec4r t = c + c;
189 Vec4r qw = Broadcast<3>(this->data);
190 return MulAdd(qw, t, v) + Cross3(this->data, t);
191}
192
194 auto r = *this * Vec4r{v[0], v[1], v[2], 0_r};
195 return Real3{r[0], r[1], r[2]};
196}
197
201
205
209
210} // namespace superdex
211
212/************************************************************************************
213 Reflection support for Quaternion.
214 Serializes like std::array<real, 4>.
215*/
216#if MOCHI_USE_REFLECTION
217template <>
218struct SReflectTypeTraits<superdex::Quaternion> {
219 static constexpr SReflect::CoreType coreType = SReflect::CoreType::CT_array;
220 static SReflect::ArrayTypeInfo const& GetTypeInfo() {
221 static auto const* s_typeInfo =
222 SReflect::MakeFixedArrayTypeInfo<superdex::Quaternion, superdex::real, 4>("superdex::Quaternion");
223 return *s_typeInfo;
224 }
225};
226#endif // MOCHI_USE_REFLECTION
static Quaternion RotationY(real a)
Quaternion operator*(Quaternion const &rhs) const
static Quaternion FromUnitAxisAngle(Vec4r normalizedAxis, real angleRadians)
Quaternion GetConjugate() const
Real3 ToRotationVector() const
void ToAxisAngle(Real3 *outAxis, real *outAngleRad) const
bool operator!=(Quaternion const &rhs) const
static Quaternion Identity()
static Quaternion RotationX(real a)
bool operator==(Quaternion const &rhs) const
static Quaternion RotationZ(real a)
static Quaternion FromAxisAngle(Vec4r axis, real angleRadians)
static Quaternion Zero()
Quaternion operator-() const
Vec4r VToRotationVector() const
static Quaternion FromRotationVector(Vec4r rotVector)
Quaternion operator+(Quaternion const &a) const
Real4 ToReal4() const
#define MOCHI_LOG_WARNING(...)
Definition log.h:43
#define MOCHI_UNLIKELY
#define MOCHI_FORCE_INLINE
#define MOCHI_LIKELY
#define MOCHI_NO_INIT
constexpr T ACos(T a)
Simd< T, 2 > Shuffle(Simd< T, 2 > a)
Definition simd_inl.h:286
Simd< T, N > Cross3(Simd< T, N > a, Simd< T, N > b)
Definition simd_inl.h:919
constexpr T Sin(T a)
constexpr To StaticCast(From const &a)
Definition basic_utils.h:79
constexpr T kDefaultNearEqualEpsilon
T Norm(Simd< T, N > a)
Definition simd_inl.h:941
V ToSimdDirection(V a)
Definition simd_inl.h:180
Simd< T, N > Set(Simd< T, N > a, T value)
Definition simd_inl.h:326
Simd< real, 4 > Vec4r
Definition simd.h:206
constexpr T Cos(T a)
V SimdZero()
Definition simd_inl.h:147
V Broadcast(typename V::Scalar a)
Definition simd_inl.h:116
Simd< T, N > Normalize(Simd< T, N > a)
Definition simd_inl.h:946
Simd< double, 4 > Vec4d
Definition simd.h:202
NdArray< real, 3 > Real3
Definition nd_array.h:115
constexpr T ASin(T a)
NdArray< real, 4 > Real4
Definition nd_array.h:116
T Get0(Simd< T, N > v)
Definition simd_inl.h:311
Simd< T, N > VNorm(Simd< T, N > a)
Definition simd_inl.h:931
constexpr T MulAdd(T a, T b, T c)
bool NearEqual(TransformRT const &a, TransformRT const &b, real epsilon=kDefaultNearEqualEpsilon< real >)
Simd< T, N > Neg(Simd< T, N > a)
Definition simd_inl.h:351
V ToSimdPoint(V a)
Definition simd_inl.h:175