]> git.mxchange.org Git - simgear.git/blob - simgear/math/SGQuat.hxx
Mathias Fröhlich:
[simgear.git] / simgear / math / SGQuat.hxx
1 #ifndef SGQuat_H
2 #define SGQuat_H
3
4 /// 3D Vector Class
5 template<typename T>
6 class SGQuat {
7 public:
8   typedef T value_type;
9
10   /// Default constructor. Does not initialize at all.
11   /// If you need them zero initialized, SGQuat::zeros()
12   SGQuat(void)
13   {
14     /// Initialize with nans in the debug build, that will guarantee to have
15     /// a fast uninitialized default constructor in the release but shows up
16     /// uninitialized values in the debug build very fast ...
17 #ifndef NDEBUG
18     for (unsigned i = 0; i < 4; ++i)
19       _data[i] = SGLimits<T>::quiet_NaN();
20 #endif
21   }
22   /// Constructor. Initialize by the given values
23   SGQuat(T _x, T _y, T _z, T _w)
24   { x() = _x; y() = _y; z() = _z; w() = _w; }
25   /// Constructor. Initialize by the content of a plain array,
26   /// make sure it has at least 4 elements
27   explicit SGQuat(const T* d)
28   { _data[0] = d[0]; _data[1] = d[1]; _data[2] = d[2]; _data[3] = d[3]; }
29
30   /// Return a unit quaternion
31   static SGQuat unit(void)
32   { return fromRealImag(1, SGVec3<T>(0)); }
33
34   /// Return a quaternion from euler angles
35   static SGQuat fromEuler(T z, T y, T x)
36   {
37     SGQuat q;
38     T zd2 = T(0.5)*z; T yd2 = T(0.5)*y; T xd2 = T(0.5)*x;
39     T Szd2 = sin(zd2); T Syd2 = sin(yd2); T Sxd2 = sin(xd2);
40     T Czd2 = cos(zd2); T Cyd2 = cos(yd2); T Cxd2 = cos(xd2);
41     T Cxd2Czd2 = Cxd2*Czd2; T Cxd2Szd2 = Cxd2*Szd2;
42     T Sxd2Szd2 = Sxd2*Szd2; T Sxd2Czd2 = Sxd2*Czd2;
43     q.w() = Cxd2Czd2*Cyd2 + Sxd2Szd2*Syd2;
44     q.x() = Sxd2Czd2*Cyd2 - Cxd2Szd2*Syd2;
45     q.y() = Cxd2Czd2*Syd2 + Sxd2Szd2*Cyd2;
46     q.z() = Cxd2Szd2*Cyd2 - Sxd2Czd2*Syd2;
47     return q;
48   }
49
50   /// Return a quaternion from euler angles
51   static SGQuat fromYawPitchRoll(T y, T p, T r)
52   { return fromEuler(y, p, r); }
53
54   /// Return a quaternion from euler angles
55   static SGQuat fromHeadAttBank(T h, T a, T b)
56   { return fromEuler(h, a, b); }
57
58   /// Return a quaternion rotation the the horizontal local frame from given
59   /// longitude and latitude
60   static SGQuat fromLonLat(T lon, T lat)
61   {
62     SGQuat q;
63     T zd2 = T(0.5)*lon;
64     T yd2 = T(-0.25)*SGMisc<value_type>::pi() - T(0.5)*lat;
65     T Szd2 = sin(zd2);
66     T Syd2 = sin(yd2);
67     T Czd2 = cos(zd2);
68     T Cyd2 = cos(yd2);
69     q.w() = Czd2*Cyd2;
70     q.x() = -Szd2*Syd2;
71     q.y() = Czd2*Syd2;
72     q.z() = Szd2*Cyd2;
73     return q;
74   }
75
76   /// Create a quaternion from the angle axis representation
77   static SGQuat fromAngleAxis(T angle, const SGVec3<T>& axis)
78   {
79     T angle2 = 0.5*angle;
80     return fromRealImag(cos(angle2), T(sin(angle2))*axis);
81   }
82
83   /// Create a quaternion from the angle axis representation where the angle
84   /// is stored in the axis' length
85   static SGQuat fromAngleAxis(const SGVec3<T>& axis)
86   {
87     T nAxis = norm(axis);
88     if (nAxis <= SGLimits<T>::min())
89       return SGQuat(1, 0, 0, 0);
90     T angle2 = 0.5*nAxis;
91     return fromRealImag(cos(angle2), T(sin(angle2)/nAxis)*axis);
92   }
93
94   /// Return a quaternion from real and imaginary part
95   static SGQuat fromRealImag(T r, const SGVec3<T>& i)
96   {
97     SGQuat q;
98     q.w() = r;
99     q.x() = i(0);
100     q.y() = i(1);
101     q.z() = i(2);
102     return q;
103   }
104
105   /// Return an all zero vector
106   static SGQuat zeros(void)
107   { return SGQuat(0, 0, 0, 0); }
108
109   /// write the euler angles into the references
110   void getEulerRad(T& zRad, T& yRad, T& xRad) const
111   {
112     value_type sqrQW = w()*w();
113     value_type sqrQX = x()*x();
114     value_type sqrQY = y()*y();
115     value_type sqrQZ = z()*z();
116
117     value_type num = 2*(y()*z() + w()*x());
118     value_type den = sqrQW - sqrQX - sqrQY + sqrQZ;
119     if (fabs(den) < SGLimits<value_type>::min() &&
120         fabs(num) < SGLimits<value_type>::min())
121       xRad = 0;
122     else
123       xRad = atan2(num, den);
124     
125     value_type tmp = 2*(x()*z() - w()*y());
126     if (tmp < -1)
127       yRad = 0.5*SGMisc<value_type>::pi();
128     else if (1 < tmp)
129       yRad = -0.5*SGMisc<value_type>::pi();
130     else
131       yRad = -asin(tmp);
132    
133     num = 2*(x()*y() + w()*z()); 
134     den = sqrQW + sqrQX - sqrQY - sqrQZ;
135     if (fabs(den) < SGLimits<value_type>::min() &&
136         fabs(num) < SGLimits<value_type>::min())
137       zRad = 0;
138     else {
139       value_type psi = atan2(num, den);
140       if (psi < 0)
141         psi += 2*SGMisc<value_type>::pi();
142       zRad = psi;
143     }
144   }
145
146   /// write the euler angles in degrees into the references
147   void getEulerDeg(T& zDeg, T& yDeg, T& xDeg) const
148   {
149     getEulerRad(zDeg, yDeg, xDeg);
150     zDeg *= 180/SGMisc<value_type>::pi();
151     yDeg *= 180/SGMisc<value_type>::pi();
152     xDeg *= 180/SGMisc<value_type>::pi();
153   }
154
155   /// write the angle axis representation into the references
156   void getAngleAxis(T& angle, SGVec3<T>& axis) const
157   {
158     T nrm = norm(*this);
159     if (nrm < SGLimits<T>::min()) {
160       angle = 0;
161       axis = SGVec3<T>(0, 0, 0);
162     } else {
163       T rNrm = 1/nrm;
164       angle = acos(SGMisc<T>::max(-1, SGMisc<T>::min(1, rNrm*w())));
165       T sAng = sin(angle);
166       if (fabs(sAng) < SGLimits<T>::min())
167         axis = SGVec3<T>(1, 0, 0);
168       else 
169         axis = (rNrm/sAng)*imag(*this);
170       angle *= 2;
171     }
172   }
173
174   /// write the angle axis representation into the references
175   void getAngleAxis(SGVec3<T>& axis) const
176   {
177     T angle;
178     getAngleAxis(angle, axis);
179     axis *= angle;
180   }
181
182   /// Access by index, the index is unchecked
183   const T& operator()(unsigned i) const
184   { return _data[i]; }
185   /// Access by index, the index is unchecked
186   T& operator()(unsigned i)
187   { return _data[i]; }
188
189   /// Access the x component
190   const T& x(void) const
191   { return _data[0]; }
192   /// Access the x component
193   T& x(void)
194   { return _data[0]; }
195   /// Access the y component
196   const T& y(void) const
197   { return _data[1]; }
198   /// Access the y component
199   T& y(void)
200   { return _data[1]; }
201   /// Access the z component
202   const T& z(void) const
203   { return _data[2]; }
204   /// Access the z component
205   T& z(void)
206   { return _data[2]; }
207   /// Access the w component
208   const T& w(void) const
209   { return _data[3]; }
210   /// Access the w component
211   T& w(void)
212   { return _data[3]; }
213
214   /// Get the data pointer, usefull for interfacing with plib's sg*Vec
215   const T* data(void) const
216   { return _data; }
217   /// Get the data pointer, usefull for interfacing with plib's sg*Vec
218   T* data(void)
219   { return _data; }
220
221   /// Readonly interface function to ssg's sgQuat/sgdQuat
222   const T (&sg(void) const)[4]
223   { return _data; }
224   /// Interface function to ssg's sgQuat/sgdQuat
225   T (&sg(void))[4]
226   { return _data; }
227
228   /// Inplace addition
229   SGQuat& operator+=(const SGQuat& v)
230   { _data[0]+=v(0);_data[1]+=v(1);_data[2]+=v(2);_data[3]+=v(3);return *this; }
231   /// Inplace subtraction
232   SGQuat& operator-=(const SGQuat& v)
233   { _data[0]-=v(0);_data[1]-=v(1);_data[2]-=v(2);_data[3]-=v(3);return *this; }
234   /// Inplace scalar multiplication
235   template<typename S>
236   SGQuat& operator*=(S s)
237   { _data[0] *= s; _data[1] *= s; _data[2] *= s; _data[3] *= s; return *this; }
238   /// Inplace scalar multiplication by 1/s
239   template<typename S>
240   SGQuat& operator/=(S s)
241   { return operator*=(1/T(s)); }
242   /// Inplace quaternion multiplication
243   SGQuat& operator*=(const SGQuat& v);
244
245   /// Transform a vector from the current coordinate frame to a coordinate
246   /// frame rotated with the quaternion
247   SGVec3<T> transform(const SGVec3<T>& v) const
248   {
249     value_type r = 2/dot(*this, *this);
250     SGVec3<T> qimag = imag(*this);
251     value_type qr = real(*this);
252     return (r*qr*qr - 1)*v + (r*dot(qimag, v))*qimag - (r*qr)*cross(qimag, v);
253   }
254   /// Transform a vector from the coordinate frame rotated with the quaternion
255   /// to the current coordinate frame
256   SGVec3<T> backTransform(const SGVec3<T>& v) const
257   {
258     value_type r = 2/dot(*this, *this);
259     SGVec3<T> qimag = imag(*this);
260     value_type qr = real(*this);
261     return (r*qr*qr - 1)*v + (r*dot(qimag, v))*qimag + (r*qr)*cross(qimag, v);
262   }
263
264   /// Rotate a given vector with the quaternion
265   SGVec3<T> rotate(const SGVec3<T>& v) const
266   { return backTransform(v); }
267   /// Rotate a given vector with the inverse quaternion
268   SGVec3<T> rotateBack(const SGVec3<T>& v) const
269   { return transform(v); }
270
271   /// Return the time derivative of the quaternion given the angular velocity
272   SGQuat
273   derivative(const SGVec3<T>& angVel)
274   {
275     SGQuat deriv;
276
277     deriv.w() = 0.5*(-x()*angVel(0) - y()*angVel(1) - z()*angVel(2));
278     deriv.x() = 0.5*( w()*angVel(0) - z()*angVel(1) + y()*angVel(2));
279     deriv.y() = 0.5*( z()*angVel(0) + w()*angVel(1) - x()*angVel(2));
280     deriv.z() = 0.5*(-y()*angVel(0) + x()*angVel(1) + w()*angVel(2));
281     
282     return deriv;
283   }
284
285 private:
286   /// The actual data
287   T _data[4];
288 };
289
290 /// Unary +, do nothing ...
291 template<typename T>
292 inline
293 const SGQuat<T>&
294 operator+(const SGQuat<T>& v)
295 { return v; }
296
297 /// Unary -, do nearly nothing
298 template<typename T>
299 inline
300 SGQuat<T>
301 operator-(const SGQuat<T>& v)
302 { return SGQuat<T>(-v(0), -v(1), -v(2), -v(3)); }
303
304 /// Binary +
305 template<typename T>
306 inline
307 SGQuat<T>
308 operator+(const SGQuat<T>& v1, const SGQuat<T>& v2)
309 { return SGQuat<T>(v1(0)+v2(0), v1(1)+v2(1), v1(2)+v2(2), v1(3)+v2(3)); }
310
311 /// Binary -
312 template<typename T>
313 inline
314 SGQuat<T>
315 operator-(const SGQuat<T>& v1, const SGQuat<T>& v2)
316 { return SGQuat<T>(v1(0)-v2(0), v1(1)-v2(1), v1(2)-v2(2), v1(3)-v2(3)); }
317
318 /// Scalar multiplication
319 template<typename S, typename T>
320 inline
321 SGQuat<T>
322 operator*(S s, const SGQuat<T>& v)
323 { return SGQuat<T>(s*v(0), s*v(1), s*v(2), s*v(3)); }
324
325 /// Scalar multiplication
326 template<typename S, typename T>
327 inline
328 SGQuat<T>
329 operator*(const SGQuat<T>& v, S s)
330 { return SGQuat<T>(s*v(0), s*v(1), s*v(2), s*v(3)); }
331
332 /// Quaterion multiplication
333 template<typename T>
334 inline
335 SGQuat<T>
336 operator*(const SGQuat<T>& v1, const SGQuat<T>& v2)
337 {
338   SGQuat<T> v;
339   v.x() = v1.w()*v2.x() + v1.x()*v2.w() + v1.y()*v2.z() - v1.z()*v2.y();
340   v.y() = v1.w()*v2.y() - v1.x()*v2.z() + v1.y()*v2.w() + v1.z()*v2.x();
341   v.z() = v1.w()*v2.z() + v1.x()*v2.y() - v1.y()*v2.x() + v1.z()*v2.w();
342   v.w() = v1.w()*v2.w() - v1.x()*v2.x() - v1.y()*v2.y() - v1.z()*v2.z();
343   return v;
344 }
345
346 /// Now define the inplace multiplication
347 template<typename T>
348 inline
349 SGQuat<T>&
350 SGQuat<T>::operator*=(const SGQuat& v)
351 { (*this) = (*this)*v; return *this; }
352
353 /// The conjugate of the quaternion, this is also the
354 /// inverse for normalized quaternions
355 template<typename T>
356 inline
357 SGQuat<T>
358 conj(const SGQuat<T>& v)
359 { return SGQuat<T>(-v(0), -v(1), -v(2), v(3)); }
360
361 /// The conjugate of the quaternion, this is also the
362 /// inverse for normalized quaternions
363 template<typename T>
364 inline
365 SGQuat<T>
366 inverse(const SGQuat<T>& v)
367 { return (1/dot(v, v))*SGQuat<T>(-v(0), -v(1), -v(2), v(3)); }
368
369 /// The imagniary part of the quaternion
370 template<typename T>
371 inline
372 T
373 real(const SGQuat<T>& v)
374 { return v.w(); }
375
376 /// The imagniary part of the quaternion
377 template<typename T>
378 inline
379 SGVec3<T>
380 imag(const SGQuat<T>& v)
381 { return SGVec3<T>(v.x(), v.y(), v.z()); }
382
383 /// Scalar dot product
384 template<typename T>
385 inline
386 T
387 dot(const SGQuat<T>& v1, const SGQuat<T>& v2)
388 { return v1(0)*v2(0) + v1(1)*v2(1) + v1(2)*v2(2) + v1(3)*v2(3); }
389
390 /// The euclidean norm of the vector, that is what most people call length
391 template<typename T>
392 inline
393 T
394 norm(const SGQuat<T>& v)
395 { return sqrt(dot(v, v)); }
396
397 /// The euclidean norm of the vector, that is what most people call length
398 template<typename T>
399 inline
400 T
401 length(const SGQuat<T>& v)
402 { return sqrt(dot(v, v)); }
403
404 /// The 1-norm of the vector, this one is the fastest length function we
405 /// can implement on modern cpu's
406 template<typename T>
407 inline
408 T
409 norm1(const SGQuat<T>& v)
410 { return fabs(v(0)) + fabs(v(1)) + fabs(v(2)) + fabs(v(3)); }
411
412 /// The euclidean norm of the vector, that is what most people call length
413 template<typename T>
414 inline
415 SGQuat<T>
416 normalize(const SGQuat<T>& q)
417 { return (1/norm(q))*q; }
418
419 /// Return true if exactly the same
420 template<typename T>
421 inline
422 bool
423 operator==(const SGQuat<T>& v1, const SGQuat<T>& v2)
424 { return v1(0)==v2(0) && v1(1)==v2(1) && v1(2)==v2(2) && v1(3)==v2(3); }
425
426 /// Return true if not exactly the same
427 template<typename T>
428 inline
429 bool
430 operator!=(const SGQuat<T>& v1, const SGQuat<T>& v2)
431 { return ! (v1 == v2); }
432
433 /// Return true if equal to the relative tolerance tol
434 /// Note that this is not the same than comparing quaternions to represent
435 /// the same rotation
436 template<typename T>
437 inline
438 bool
439 equivalent(const SGQuat<T>& v1, const SGQuat<T>& v2, T tol)
440 { return norm1(v1 - v2) < tol*(norm1(v1) + norm1(v2)); }
441
442 /// Return true if about equal to roundoff of the underlying type
443 /// Note that this is not the same than comparing quaternions to represent
444 /// the same rotation
445 template<typename T>
446 inline
447 bool
448 equivalent(const SGQuat<T>& v1, const SGQuat<T>& v2)
449 { return equivalent(v1, v2, 100*SGLimits<T>::epsilon()); }
450
451 #ifndef NDEBUG
452 template<typename T>
453 inline
454 bool
455 isNaN(const SGQuat<T>& v)
456 {
457   return SGMisc<T>::isNaN(v(0)) || SGMisc<T>::isNaN(v(1))
458     || SGMisc<T>::isNaN(v(2)) || SGMisc<T>::isNaN(v(3));
459 }
460 #endif
461
462 /// quaternion interpolation for t in [0,1] interpolate between src (=0)
463 /// and dst (=1)
464 template<typename T>
465 inline
466 SGQuat<T>
467 interpolate(T t, const SGQuat<T>& src, const SGQuat<T>& dst)
468 {
469   T cosPhi = dot(src, dst);
470   // need to take the shorter way ...
471   int signCosPhi = SGMisc<T>::sign(cosPhi);
472   // cosPhi must be corrected for that sign
473   cosPhi = fabs(cosPhi);
474
475   // first opportunity to fail - make sure acos will succeed later -
476   // result is correct
477   if (1 <= cosPhi)
478     return dst;
479
480   // now the half angle between the orientations
481   T o = acos(cosPhi);
482
483   // need the scales now, if the angle is very small, do linear interpolation
484   // to avoid instabilities
485   T scale0, scale1;
486   if (fabs(o) < SGLimits<T>::epsilon()) {
487     scale0 = 1 - t;
488     scale1 = t;
489   } else {
490     // note that we can give a positive lower bound for sin(o) here
491     T sino = sin(o);
492     T so = 1/sino;
493     scale0 = sin((1 - t)*o)*so;
494     scale1 = sin(t*o)*so;
495   }
496
497   return scale0*src + signCosPhi*scale1*dst;
498 }
499
500 /// Output to an ostream
501 template<typename char_type, typename traits_type, typename T>
502 inline
503 std::basic_ostream<char_type, traits_type>&
504 operator<<(std::basic_ostream<char_type, traits_type>& s, const SGQuat<T>& v)
505 { return s << "[ " << v(0) << ", " << v(1) << ", " << v(2) << ", " << v(3) << " ]"; }
506
507 /// Two classes doing actually the same on different types
508 typedef SGQuat<float> SGQuatf;
509 typedef SGQuat<double> SGQuatd;
510
511 inline
512 SGQuatf
513 toQuatf(const SGQuatd& v)
514 { return SGQuatf(v(0), v(1), v(2), v(3)); }
515
516 inline
517 SGQuatd
518 toQuatd(const SGQuatf& v)
519 { return SGQuatd(v(0), v(1), v(2), v(3)); }
520
521 #endif