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