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