]> git.mxchange.org Git - simgear.git/blob - simgear/math/SGQuat.hxx
93f071effbcdc504602dd424b0b86bec8cc56980
[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 #ifdef min
22 #undef min
23 #endif
24
25 #ifdef max
26 #undef max
27 #endif
28
29 // for microsoft compiler
30 #ifdef _MSC_VER
31 #define copysign _copysign
32 #endif
33
34 #include <osg/Quat>
35
36 template<typename T>
37 struct SGQuatStorage {
38   /// Readonly raw storage interface
39   const T (&data(void) const)[4]
40   { return _data; }
41   /// Readonly raw storage interface
42   T (&data(void))[4]
43   { return _data; }
44
45   void osg() const
46   { }
47
48 private:
49   T _data[4];
50 };
51
52 template<>
53 struct SGQuatStorage<double> : public osg::Quat {
54   /// Access raw data by index, the index is unchecked
55   const double (&data(void) const)[4]
56   { return osg::Quat::_v; }
57   /// Access raw data by index, the index is unchecked
58   double (&data(void))[4]
59   { return osg::Quat::_v; }
60
61   const osg::Quat& osg() const
62   { return *this; }
63   osg::Quat& osg()
64   { return *this; }
65 };
66
67 /// 3D Vector Class
68 template<typename T>
69 class SGQuat : protected SGQuatStorage<T> {
70 public:
71   typedef T value_type;
72
73   /// Default constructor. Does not initialize at all.
74   /// If you need them zero initialized, SGQuat::zeros()
75   SGQuat(void)
76   {
77     /// Initialize with nans in the debug build, that will guarantee to have
78     /// a fast uninitialized default constructor in the release but shows up
79     /// uninitialized values in the debug build very fast ...
80 #ifndef NDEBUG
81     for (unsigned i = 0; i < 4; ++i)
82       data()[i] = SGLimits<T>::quiet_NaN();
83 #endif
84   }
85   /// Constructor. Initialize by the given values
86   SGQuat(T _x, T _y, T _z, T _w)
87   { x() = _x; y() = _y; z() = _z; w() = _w; }
88   /// Constructor. Initialize by the content of a plain array,
89   /// make sure it has at least 4 elements
90   explicit SGQuat(const T* d)
91   { data()[0] = d[0]; data()[1] = d[1]; data()[2] = d[2]; data()[3] = d[3]; }
92   explicit SGQuat(const osg::Quat& d)
93   { data()[0] = d[0]; data()[1] = d[1]; data()[2] = d[2]; data()[3] = d[3]; }
94
95   /// Return a unit quaternion
96   static SGQuat unit(void)
97   { return fromRealImag(1, SGVec3<T>(0, 0, 0)); }
98
99   /// Return a quaternion from euler angles
100   static SGQuat fromEulerRad(T z, T y, T x)
101   {
102     SGQuat q;
103     T zd2 = T(0.5)*z; T yd2 = T(0.5)*y; T xd2 = T(0.5)*x;
104     T Szd2 = sin(zd2); T Syd2 = sin(yd2); T Sxd2 = sin(xd2);
105     T Czd2 = cos(zd2); T Cyd2 = cos(yd2); T Cxd2 = cos(xd2);
106     T Cxd2Czd2 = Cxd2*Czd2; T Cxd2Szd2 = Cxd2*Szd2;
107     T Sxd2Szd2 = Sxd2*Szd2; T Sxd2Czd2 = Sxd2*Czd2;
108     q.w() = Cxd2Czd2*Cyd2 + Sxd2Szd2*Syd2;
109     q.x() = Sxd2Czd2*Cyd2 - Cxd2Szd2*Syd2;
110     q.y() = Cxd2Czd2*Syd2 + Sxd2Szd2*Cyd2;
111     q.z() = Cxd2Szd2*Cyd2 - Sxd2Czd2*Syd2;
112     return q;
113   }
114
115   /// Return a quaternion from euler angles in degrees
116   static SGQuat fromEulerDeg(T z, T y, T x)
117   {
118     return fromEulerRad(SGMisc<T>::deg2rad(z), SGMisc<T>::deg2rad(y),
119                         SGMisc<T>::deg2rad(x));
120   }
121
122   /// Return a quaternion from euler angles
123   static SGQuat fromYawPitchRoll(T y, T p, T r)
124   { return fromEulerRad(y, p, r); }
125
126   /// Return a quaternion from euler angles
127   static SGQuat fromYawPitchRollDeg(T y, T p, T r)
128   { return fromEulerDeg(y, p, r); }
129
130   /// Return a quaternion from euler angles
131   static SGQuat fromHeadAttBank(T h, T a, T b)
132   { return fromEulerRad(h, a, b); }
133
134   /// Return a quaternion from euler angles
135   static SGQuat fromHeadAttBankDeg(T h, T a, T b)
136   { return fromEulerDeg(h, a, b); }
137
138   /// Return a quaternion rotation the the horizontal local frame from given
139   /// longitude and latitude
140   static SGQuat fromLonLatRad(T lon, T lat)
141   {
142     SGQuat q;
143     T zd2 = T(0.5)*lon;
144     T yd2 = T(-0.25)*SGMisc<value_type>::pi() - T(0.5)*lat;
145     T Szd2 = sin(zd2);
146     T Syd2 = sin(yd2);
147     T Czd2 = cos(zd2);
148     T Cyd2 = cos(yd2);
149     q.w() = Czd2*Cyd2;
150     q.x() = -Szd2*Syd2;
151     q.y() = Czd2*Syd2;
152     q.z() = Szd2*Cyd2;
153     return q;
154   }
155
156   /// Return a quaternion rotation the the horizontal local frame from given
157   /// longitude and latitude
158   static SGQuat fromLonLatDeg(T lon, T lat)
159   { return fromLonLatRad(SGMisc<T>::deg2rad(lon), SGMisc<T>::deg2rad(lat)); }
160
161   /// Return a quaternion rotation the the horizontal local frame from given
162   /// longitude and latitude
163   static SGQuat fromLonLat(const SGGeod& geod)
164   { return fromLonLatRad(geod.getLongitudeRad(), geod.getLatitudeRad()); }
165
166   /// Create a quaternion from the angle axis representation
167   static SGQuat fromAngleAxis(T angle, const SGVec3<T>& axis)
168   {
169     T angle2 = 0.5*angle;
170     return fromRealImag(cos(angle2), T(sin(angle2))*axis);
171   }
172
173   /// Create a quaternion from the angle axis representation
174   static SGQuat fromAngleAxisDeg(T angle, const SGVec3<T>& axis)
175   { return fromAngleAxis(SGMisc<T>::deg2rad(angle), axis); }
176
177   /// Create a quaternion from the angle axis representation where the angle
178   /// is stored in the axis' length
179   static SGQuat fromAngleAxis(const SGVec3<T>& axis)
180   {
181     T nAxis = norm(axis);
182     if (nAxis <= SGLimits<T>::min())
183       return SGQuat(1, 0, 0, 0);
184     T angle2 = 0.5*nAxis;
185     return fromRealImag(cos(angle2), T(sin(angle2)/nAxis)*axis);
186   }
187
188   static SGQuat fromRotateTo(const SGVec3<T>& from, const SGVec3<T>& to)
189   {
190     T nfrom = norm(from);
191     T nto = norm(to);
192     if (nfrom < SGLimits<T>::min() || nto < SGLimits<T>::min())
193       return SGQuat::unit();
194
195     return SGQuat::fromRotateToNorm((1/nfrom)*from, (1/nto)*to);
196   }
197
198   // FIXME more finegrained error behavour.
199   static SGQuat fromRotateTo(const SGVec3<T>& v1, unsigned i1,
200                              const SGVec3<T>& v2, unsigned i2)
201   {
202     T nrmv1 = norm(v1);
203     T nrmv2 = norm(v2);
204     if (nrmv1 < SGLimits<T>::min() || nrmv2 < SGLimits<T>::min())
205       return SGQuat::unit();
206
207     SGVec3<T> nv1 = (1/nrmv1)*v1;
208     SGVec3<T> nv2 = (1/nrmv2)*v2;
209     T dv1v2 = dot(nv1, nv2);
210     if (fabs(fabs(dv1v2)-1) < SGLimits<T>::epsilon())
211       return SGQuat::unit();
212
213     // The target vector for the first rotation
214     SGVec3<T> nto1 = SGVec3<T>::zeros();
215     SGVec3<T> nto2 = SGVec3<T>::zeros();
216     nto1[i1] = 1;
217     nto2[i2] = 1;
218
219     // The first rotation can be done with the usual routine.
220     SGQuat q = SGQuat::fromRotateToNorm(nv1, nto1);
221
222     // The rotation axis for the second rotation is the
223     // target for the first one, so the rotation axis is nto1
224     // We need to get the angle.
225
226     // Make nv2 exactly orthogonal to nv1.
227     nv2 = normalize(nv2 - dv1v2*nv1);
228
229     SGVec3<T> tnv2 = q.transform(nv2);
230     T cosang = dot(nto2, tnv2);
231     T cos05ang = T(0.5+0.5*cosang);
232     if (cos05ang <= 0)
233       cosang = T(0);
234     cos05ang = sqrt(cos05ang);
235     T sig = dot(nto1, cross(nto2, tnv2));
236     T sin05ang = T(0.5-0.5*cosang);
237     if (sin05ang <= 0)
238       sin05ang = 0;
239     sin05ang = copysign(sqrt(sin05ang), sig);
240     q *= SGQuat::fromRealImag(cos05ang, sin05ang*nto1);
241
242     return q;
243   }
244
245
246   // Return a quaternion which rotates the vector given by v
247   // to the vector -v. Other directions are *not* preserved.
248   static SGQuat fromChangeSign(const SGVec3<T>& v)
249   {
250     // The vector from points to the oposite direction than to.
251     // Find a vector perpandicular to the vector to.
252     T absv1 = fabs(v(0));
253     T absv2 = fabs(v(1));
254     T absv3 = fabs(v(2));
255     
256     SGVec3<T> axis;
257     if (absv2 < absv1 && absv3 < absv1) {
258       T quot = v(1)/v(0);
259       axis = (1/sqrt(1+quot*quot))*SGVec3<T>(quot, -1, 0);
260     } else if (absv1 < absv2 && absv3 < absv2) {
261       T quot = v(2)/v(1);
262       axis = (1/sqrt(1+quot*quot))*SGVec3<T>(0, quot, -1);
263     } else if (absv1 < absv3 && absv2 < absv3) {
264       T quot = v(0)/v(2);
265       axis = (1/sqrt(1+quot*quot))*SGVec3<T>(-1, 0, quot);
266     } else {
267       // The all zero case.
268       return SGQuat::unit();
269     }
270
271     return SGQuat::fromRealImag(0, axis);
272   }
273
274   /// Return a quaternion from real and imaginary part
275   static SGQuat fromRealImag(T r, const SGVec3<T>& i)
276   {
277     SGQuat q;
278     q.w() = r;
279     q.x() = i.x();
280     q.y() = i.y();
281     q.z() = i.z();
282     return q;
283   }
284
285   /// Return an all zero vector
286   static SGQuat zeros(void)
287   { return SGQuat(0, 0, 0, 0); }
288
289   /// write the euler angles into the references
290   void getEulerRad(T& zRad, T& yRad, T& xRad) const
291   {
292     T sqrQW = w()*w();
293     T sqrQX = x()*x();
294     T sqrQY = y()*y();
295     T sqrQZ = z()*z();
296
297     T num = 2*(y()*z() + w()*x());
298     T den = sqrQW - sqrQX - sqrQY + sqrQZ;
299     if (fabs(den) < SGLimits<T>::min() &&
300         fabs(num) < SGLimits<T>::min())
301       xRad = 0;
302     else
303       xRad = atan2(num, den);
304     
305     T tmp = 2*(x()*z() - w()*y());
306     if (tmp < -1)
307       yRad = 0.5*SGMisc<T>::pi();
308     else if (1 < tmp)
309       yRad = -0.5*SGMisc<T>::pi();
310     else
311       yRad = -asin(tmp);
312    
313     num = 2*(x()*y() + w()*z()); 
314     den = sqrQW + sqrQX - sqrQY - sqrQZ;
315     if (fabs(den) < SGLimits<T>::min() &&
316         fabs(num) < SGLimits<T>::min())
317       zRad = 0;
318     else {
319       T psi = atan2(num, den);
320       if (psi < 0)
321         psi += 2*SGMisc<T>::pi();
322       zRad = psi;
323     }
324   }
325
326   /// write the euler angles in degrees into the references
327   void getEulerDeg(T& zDeg, T& yDeg, T& xDeg) const
328   {
329     getEulerRad(zDeg, yDeg, xDeg);
330     zDeg = SGMisc<T>::rad2deg(zDeg);
331     yDeg = SGMisc<T>::rad2deg(yDeg);
332     xDeg = SGMisc<T>::rad2deg(xDeg);
333   }
334
335   /// write the angle axis representation into the references
336   void getAngleAxis(T& angle, SGVec3<T>& axis) const
337   {
338     T nrm = norm(*this);
339     if (nrm < SGLimits<T>::min()) {
340       angle = 0;
341       axis = SGVec3<T>(0, 0, 0);
342     } else {
343       T rNrm = 1/nrm;
344       angle = acos(SGMisc<T>::max(-1, SGMisc<T>::min(1, rNrm*w())));
345       T sAng = sin(angle);
346       if (fabs(sAng) < SGLimits<T>::min())
347         axis = SGVec3<T>(1, 0, 0);
348       else 
349         axis = (rNrm/sAng)*imag(*this);
350       angle *= 2;
351     }
352   }
353
354   /// write the angle axis representation into the references
355   void getAngleAxis(SGVec3<T>& axis) const
356   {
357     T angle;
358     getAngleAxis(angle, axis);
359     axis *= angle;
360   }
361
362   /// Access by index, the index is unchecked
363   const T& operator()(unsigned i) const
364   { return data()[i]; }
365   /// Access by index, the index is unchecked
366   T& operator()(unsigned i)
367   { return data()[i]; }
368
369   /// Access raw data by index, the index is unchecked
370   const T& operator[](unsigned i) const
371   { return data()[i]; }
372   /// Access raw data by index, the index is unchecked
373   T& operator[](unsigned i)
374   { return data()[i]; }
375
376   /// Access the x component
377   const T& x(void) const
378   { return data()[0]; }
379   /// Access the x component
380   T& x(void)
381   { return data()[0]; }
382   /// Access the y component
383   const T& y(void) const
384   { return data()[1]; }
385   /// Access the y component
386   T& y(void)
387   { return data()[1]; }
388   /// Access the z component
389   const T& z(void) const
390   { return data()[2]; }
391   /// Access the z component
392   T& z(void)
393   { return data()[2]; }
394   /// Access the w component
395   const T& w(void) const
396   { return data()[3]; }
397   /// Access the w component
398   T& w(void)
399   { return data()[3]; }
400
401   /// Get the data pointer
402   using SGQuatStorage<T>::data;
403
404   /// Readonly interface function to ssg's sgQuat/sgdQuat
405   const T (&sg(void) const)[4]
406   { return data(); }
407   /// Interface function to ssg's sgQuat/sgdQuat
408   T (&sg(void))[4]
409   { return data(); }
410
411   /// Interface function to osg's Quat*
412   using SGQuatStorage<T>::osg;
413
414   /// Inplace addition
415   SGQuat& operator+=(const SGQuat& v)
416   { data()[0]+=v(0);data()[1]+=v(1);data()[2]+=v(2);data()[3]+=v(3);return *this; }
417   /// Inplace subtraction
418   SGQuat& operator-=(const SGQuat& v)
419   { data()[0]-=v(0);data()[1]-=v(1);data()[2]-=v(2);data()[3]-=v(3);return *this; }
420   /// Inplace scalar multiplication
421   template<typename S>
422   SGQuat& operator*=(S s)
423   { data()[0] *= s; data()[1] *= s; data()[2] *= s; data()[3] *= s; return *this; }
424   /// Inplace scalar multiplication by 1/s
425   template<typename S>
426   SGQuat& operator/=(S s)
427   { return operator*=(1/T(s)); }
428   /// Inplace quaternion multiplication
429   SGQuat& operator*=(const SGQuat& v);
430
431   /// Transform a vector from the current coordinate frame to a coordinate
432   /// frame rotated with the quaternion
433   SGVec3<T> transform(const SGVec3<T>& v) const
434   {
435     T r = 2/dot(*this, *this);
436     SGVec3<T> qimag = imag(*this);
437     T qr = real(*this);
438     return (r*qr*qr - 1)*v + (r*dot(qimag, v))*qimag - (r*qr)*cross(qimag, v);
439   }
440   /// Transform a vector from the coordinate frame rotated with the quaternion
441   /// to the current coordinate frame
442   SGVec3<T> backTransform(const SGVec3<T>& v) const
443   {
444     T r = 2/dot(*this, *this);
445     SGVec3<T> qimag = imag(*this);
446     T qr = real(*this);
447     return (r*qr*qr - 1)*v + (r*dot(qimag, v))*qimag + (r*qr)*cross(qimag, v);
448   }
449
450   /// Rotate a given vector with the quaternion
451   SGVec3<T> rotate(const SGVec3<T>& v) const
452   { return backTransform(v); }
453   /// Rotate a given vector with the inverse quaternion
454   SGVec3<T> rotateBack(const SGVec3<T>& v) const
455   { return transform(v); }
456
457   /// Return the time derivative of the quaternion given the angular velocity
458   SGQuat
459   derivative(const SGVec3<T>& angVel)
460   {
461     SGQuat deriv;
462
463     deriv.w() = 0.5*(-x()*angVel(0) - y()*angVel(1) - z()*angVel(2));
464     deriv.x() = 0.5*( w()*angVel(0) - z()*angVel(1) + y()*angVel(2));
465     deriv.y() = 0.5*( z()*angVel(0) + w()*angVel(1) - x()*angVel(2));
466     deriv.z() = 0.5*(-y()*angVel(0) + x()*angVel(1) + w()*angVel(2));
467     
468     return deriv;
469   }
470
471 private:
472
473   // Private because it assumes normalized inputs.
474   static SGQuat
475   fromRotateToSmaller90Deg(T cosang,
476                            const SGVec3<T>& from, const SGVec3<T>& to)
477   {
478     // In this function we assume that the angle required to rotate from
479     // the vector from to the vector to is <= 90 deg.
480     // That is done so because of possible instabilities when we rotate more
481     // then 90deg.
482
483     // Note that the next comment does actually cover a *more* *general* case
484     // than we need in this function. That shows that this formula is even
485     // valid for rotations up to 180deg.
486
487     // Because of the signs in the axis, it is sufficient to care for angles
488     // in the interval [-pi,pi]. That means that 0.5*angle is in the interval
489     // [-pi/2,pi/2]. But in that range the cosine is allways >= 0.
490     // So we do not need to care for egative roots in the following equation:
491     T cos05ang = sqrt(0.5+0.5*cosang);
492
493
494     // Now our assumption of angles <= 90 deg comes in play.
495     // For that reason, we know that cos05ang is not zero.
496     // It is even more, we can see from the above formula that 
497     // sqrt(0.5) < cos05ang.
498
499
500     // Compute the rotation axis, that is
501     // sin(angle)*normalized rotation axis
502     SGVec3<T> axis = cross(to, from);
503
504     // We need sin(0.5*angle)*normalized rotation axis.
505     // So rescale with sin(0.5*x)/sin(x).
506     // To do that we use the equation:
507     // sin(x) = 2*sin(0.5*x)*cos(0.5*x)
508     return SGQuat::fromRealImag( cos05ang, (1/(2*cos05ang))*axis);
509   }
510
511   // Private because it assumes normalized inputs.
512   static SGQuat
513   fromRotateToNorm(const SGVec3<T>& from, const SGVec3<T>& to)
514   {
515     // To avoid instabilities with roundoff, we distinguish between rotations
516     // with more then 90deg and rotations with less than 90deg.
517
518     // Compute the cosine of the angle.
519     T cosang = dot(from, to);
520
521     // For the small ones do direct computation
522     if (T(-0.5) < cosang)
523       return SGQuat::fromRotateToSmaller90Deg(cosang, from, to);
524
525     // For larger rotations. first rotate from to -from.
526     // Past that we will have a smaller angle again.
527     SGQuat q1 = SGQuat::fromChangeSign(from);
528     SGQuat q2 = SGQuat::fromRotateToSmaller90Deg(-cosang, -from, to);
529     return q1*q2;
530   }
531 };
532
533 /// Unary +, do nothing ...
534 template<typename T>
535 inline
536 const SGQuat<T>&
537 operator+(const SGQuat<T>& v)
538 { return v; }
539
540 /// Unary -, do nearly nothing
541 template<typename T>
542 inline
543 SGQuat<T>
544 operator-(const SGQuat<T>& v)
545 { return SGQuat<T>(-v(0), -v(1), -v(2), -v(3)); }
546
547 /// Binary +
548 template<typename T>
549 inline
550 SGQuat<T>
551 operator+(const SGQuat<T>& v1, const SGQuat<T>& v2)
552 { return SGQuat<T>(v1(0)+v2(0), v1(1)+v2(1), v1(2)+v2(2), v1(3)+v2(3)); }
553
554 /// Binary -
555 template<typename T>
556 inline
557 SGQuat<T>
558 operator-(const SGQuat<T>& v1, const SGQuat<T>& v2)
559 { return SGQuat<T>(v1(0)-v2(0), v1(1)-v2(1), v1(2)-v2(2), v1(3)-v2(3)); }
560
561 /// Scalar multiplication
562 template<typename S, typename T>
563 inline
564 SGQuat<T>
565 operator*(S s, const SGQuat<T>& v)
566 { return SGQuat<T>(s*v(0), s*v(1), s*v(2), s*v(3)); }
567
568 /// Scalar multiplication
569 template<typename S, typename T>
570 inline
571 SGQuat<T>
572 operator*(const SGQuat<T>& v, S s)
573 { return SGQuat<T>(s*v(0), s*v(1), s*v(2), s*v(3)); }
574
575 /// Quaterion multiplication
576 template<typename T>
577 inline
578 SGQuat<T>
579 operator*(const SGQuat<T>& v1, const SGQuat<T>& v2)
580 {
581   SGQuat<T> v;
582   v.x() = v1.w()*v2.x() + v1.x()*v2.w() + v1.y()*v2.z() - v1.z()*v2.y();
583   v.y() = v1.w()*v2.y() - v1.x()*v2.z() + v1.y()*v2.w() + v1.z()*v2.x();
584   v.z() = v1.w()*v2.z() + v1.x()*v2.y() - v1.y()*v2.x() + v1.z()*v2.w();
585   v.w() = v1.w()*v2.w() - v1.x()*v2.x() - v1.y()*v2.y() - v1.z()*v2.z();
586   return v;
587 }
588
589 /// Now define the inplace multiplication
590 template<typename T>
591 inline
592 SGQuat<T>&
593 SGQuat<T>::operator*=(const SGQuat& v)
594 { (*this) = (*this)*v; return *this; }
595
596 /// The conjugate of the quaternion, this is also the
597 /// inverse for normalized quaternions
598 template<typename T>
599 inline
600 SGQuat<T>
601 conj(const SGQuat<T>& v)
602 { return SGQuat<T>(-v(0), -v(1), -v(2), v(3)); }
603
604 /// The conjugate of the quaternion, this is also the
605 /// inverse for normalized quaternions
606 template<typename T>
607 inline
608 SGQuat<T>
609 inverse(const SGQuat<T>& v)
610 { return (1/dot(v, v))*SGQuat<T>(-v(0), -v(1), -v(2), v(3)); }
611
612 /// The imagniary part of the quaternion
613 template<typename T>
614 inline
615 T
616 real(const SGQuat<T>& v)
617 { return v.w(); }
618
619 /// The imagniary part of the quaternion
620 template<typename T>
621 inline
622 SGVec3<T>
623 imag(const SGQuat<T>& v)
624 { return SGVec3<T>(v.x(), v.y(), v.z()); }
625
626 /// Scalar dot product
627 template<typename T>
628 inline
629 T
630 dot(const SGQuat<T>& v1, const SGQuat<T>& v2)
631 { return v1(0)*v2(0) + v1(1)*v2(1) + v1(2)*v2(2) + v1(3)*v2(3); }
632
633 /// The euclidean norm of the vector, that is what most people call length
634 template<typename T>
635 inline
636 T
637 norm(const SGQuat<T>& v)
638 { return sqrt(dot(v, v)); }
639
640 /// The euclidean norm of the vector, that is what most people call length
641 template<typename T>
642 inline
643 T
644 length(const SGQuat<T>& v)
645 { return sqrt(dot(v, v)); }
646
647 /// The 1-norm of the vector, this one is the fastest length function we
648 /// can implement on modern cpu's
649 template<typename T>
650 inline
651 T
652 norm1(const SGQuat<T>& v)
653 { return fabs(v(0)) + fabs(v(1)) + fabs(v(2)) + fabs(v(3)); }
654
655 /// The euclidean norm of the vector, that is what most people call length
656 template<typename T>
657 inline
658 SGQuat<T>
659 normalize(const SGQuat<T>& q)
660 { return (1/norm(q))*q; }
661
662 /// Return true if exactly the same
663 template<typename T>
664 inline
665 bool
666 operator==(const SGQuat<T>& v1, const SGQuat<T>& v2)
667 { return v1(0)==v2(0) && v1(1)==v2(1) && v1(2)==v2(2) && v1(3)==v2(3); }
668
669 /// Return true if not exactly the same
670 template<typename T>
671 inline
672 bool
673 operator!=(const SGQuat<T>& v1, const SGQuat<T>& v2)
674 { return ! (v1 == v2); }
675
676 /// Return true if equal to the relative tolerance tol
677 /// Note that this is not the same than comparing quaternions to represent
678 /// the same rotation
679 template<typename T>
680 inline
681 bool
682 equivalent(const SGQuat<T>& v1, const SGQuat<T>& v2, T tol)
683 { return norm1(v1 - v2) < tol*(norm1(v1) + norm1(v2)); }
684
685 /// Return true if about equal to roundoff of the underlying type
686 /// Note that this is not the same than comparing quaternions to represent
687 /// the same rotation
688 template<typename T>
689 inline
690 bool
691 equivalent(const SGQuat<T>& v1, const SGQuat<T>& v2)
692 { return equivalent(v1, v2, 100*SGLimits<T>::epsilon()); }
693
694 #ifndef NDEBUG
695 template<typename T>
696 inline
697 bool
698 isNaN(const SGQuat<T>& v)
699 {
700   return SGMisc<T>::isNaN(v(0)) || SGMisc<T>::isNaN(v(1))
701     || SGMisc<T>::isNaN(v(2)) || SGMisc<T>::isNaN(v(3));
702 }
703 #endif
704
705 /// quaternion interpolation for t in [0,1] interpolate between src (=0)
706 /// and dst (=1)
707 template<typename T>
708 inline
709 SGQuat<T>
710 interpolate(T t, const SGQuat<T>& src, const SGQuat<T>& dst)
711 {
712   T cosPhi = dot(src, dst);
713   // need to take the shorter way ...
714   int signCosPhi = SGMisc<T>::sign(cosPhi);
715   // cosPhi must be corrected for that sign
716   cosPhi = fabs(cosPhi);
717
718   // first opportunity to fail - make sure acos will succeed later -
719   // result is correct
720   if (1 <= cosPhi)
721     return dst;
722
723   // now the half angle between the orientations
724   T o = acos(cosPhi);
725
726   // need the scales now, if the angle is very small, do linear interpolation
727   // to avoid instabilities
728   T scale0, scale1;
729   if (fabs(o) < SGLimits<T>::epsilon()) {
730     scale0 = 1 - t;
731     scale1 = t;
732   } else {
733     // note that we can give a positive lower bound for sin(o) here
734     T sino = sin(o);
735     T so = 1/sino;
736     scale0 = sin((1 - t)*o)*so;
737     scale1 = sin(t*o)*so;
738   }
739
740   return scale0*src + signCosPhi*scale1*dst;
741 }
742
743 /// Output to an ostream
744 template<typename char_type, typename traits_type, typename T>
745 inline
746 std::basic_ostream<char_type, traits_type>&
747 operator<<(std::basic_ostream<char_type, traits_type>& s, const SGQuat<T>& v)
748 { return s << "[ " << v(0) << ", " << v(1) << ", " << v(2) << ", " << v(3) << " ]"; }
749
750 inline
751 SGQuatf
752 toQuatf(const SGQuatd& v)
753 { return SGQuatf((float)v(0), (float)v(1), (float)v(2), (float)v(3)); }
754
755 inline
756 SGQuatd
757 toQuatd(const SGQuatf& v)
758 { return SGQuatd(v(0), v(1), v(2), v(3)); }
759
760 #endif