|
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- |
|
2 * This Source Code Form is subject to the terms of the Mozilla Public |
|
3 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
5 |
|
6 #ifndef GFX_QUATERNION_H |
|
7 #define GFX_QUATERNION_H |
|
8 |
|
9 #include "mozilla/gfx/BasePoint4D.h" |
|
10 #include "gfx3DMatrix.h" |
|
11 #include "nsAlgorithm.h" |
|
12 #include <algorithm> |
|
13 |
|
14 struct gfxQuaternion : public mozilla::gfx::BasePoint4D<gfxFloat, gfxQuaternion> { |
|
15 typedef mozilla::gfx::BasePoint4D<gfxFloat, gfxQuaternion> Super; |
|
16 |
|
17 gfxQuaternion() : Super() {} |
|
18 gfxQuaternion(gfxFloat aX, gfxFloat aY, gfxFloat aZ, gfxFloat aW) : Super(aX, aY, aZ, aW) {} |
|
19 |
|
20 gfxQuaternion(const gfx3DMatrix& aMatrix) { |
|
21 w = 0.5 * sqrt(std::max(1 + aMatrix[0][0] + aMatrix[1][1] + aMatrix[2][2], 0.0f)); |
|
22 x = 0.5 * sqrt(std::max(1 + aMatrix[0][0] - aMatrix[1][1] - aMatrix[2][2], 0.0f)); |
|
23 y = 0.5 * sqrt(std::max(1 - aMatrix[0][0] + aMatrix[1][1] - aMatrix[2][2], 0.0f)); |
|
24 z = 0.5 * sqrt(std::max(1 - aMatrix[0][0] - aMatrix[1][1] + aMatrix[2][2], 0.0f)); |
|
25 |
|
26 if(aMatrix[2][1] > aMatrix[1][2]) |
|
27 x = -x; |
|
28 if(aMatrix[0][2] > aMatrix[2][0]) |
|
29 y = -y; |
|
30 if(aMatrix[1][0] > aMatrix[0][1]) |
|
31 z = -z; |
|
32 } |
|
33 |
|
34 gfxQuaternion Slerp(const gfxQuaternion &aOther, gfxFloat aCoeff) { |
|
35 gfxFloat dot = mozilla::clamped(DotProduct(aOther), -1.0, 1.0); |
|
36 if (dot == 1.0) { |
|
37 return *this; |
|
38 } |
|
39 |
|
40 gfxFloat theta = acos(dot); |
|
41 gfxFloat rsintheta = 1/sqrt(1 - dot*dot); |
|
42 gfxFloat rightWeight = sin(aCoeff*theta)*rsintheta; |
|
43 |
|
44 gfxQuaternion left = *this; |
|
45 gfxQuaternion right = aOther; |
|
46 |
|
47 left *= cos(aCoeff*theta) - dot*rightWeight; |
|
48 right *= rightWeight; |
|
49 |
|
50 return left + right; |
|
51 } |
|
52 |
|
53 gfx3DMatrix ToMatrix() { |
|
54 gfx3DMatrix temp; |
|
55 |
|
56 temp[0][0] = 1 - 2 * (y * y + z * z); |
|
57 temp[0][1] = 2 * (x * y + w * z); |
|
58 temp[0][2] = 2 * (x * z - w * y); |
|
59 temp[1][0] = 2 * (x * y - w * z); |
|
60 temp[1][1] = 1 - 2 * (x * x + z * z); |
|
61 temp[1][2] = 2 * (y * z + w * x); |
|
62 temp[2][0] = 2 * (x * z + w * y); |
|
63 temp[2][1] = 2 * (y * z - w * x); |
|
64 temp[2][2] = 1 - 2 * (x * x + y * y); |
|
65 |
|
66 return temp; |
|
67 } |
|
68 |
|
69 }; |
|
70 |
|
71 #endif /* GFX_QUATERNION_H */ |