From 8e93520bd64e9daefea6e42a13d4b76fba6bf000 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladim=C3=ADr=20Vondru=C5=A1?= Date: Sun, 6 Jan 2013 15:40:28 +0100 Subject: [PATCH] Math: converting Quaternion to rotation matrix. --- src/Math/Quaternion.h | 20 ++++++++++++++++++++ src/Math/Test/MathQuaternionTest.cpp | 11 +++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/Math/Quaternion.h b/src/Math/Quaternion.h index 5cdcb9dbe..81f0a7a88 100644 --- a/src/Math/Quaternion.h +++ b/src/Math/Quaternion.h @@ -25,6 +25,7 @@ #include "Math/Math.h" #include "Math/MathTypeTraits.h" +#include "Math/Matrix.h" #include "Math/Vector3.h" namespace Magnum { namespace Math { @@ -92,6 +93,25 @@ template class Quaternion { return _vector/std::sqrt(1-pow<2>(_scalar)); } + /** + * @brief Convert quaternion to rotation matrix + * + * @see Matrix4::from(const Matrix<3, T>&, const Vector3&) + */ + Matrix<3, T> matrix() const { + return { /* Column-major! */ + T(1) - 2*pow<2>(_vector.y()) - 2*pow<2>(_vector.z()), + 2*_vector.x()*_vector.y() + 2*_vector.z()*_scalar, + 2*_vector.x()*_vector.z() - 2*_vector.y()*_scalar, + 2*_vector.x()*_vector.y() - 2*_vector.z()*_scalar, + T(1) - 2*pow<2>(_vector.x()) - 2*pow<2>(_vector.z()), + 2*_vector.y()*_vector.z() + 2*_vector.x()*_scalar, + 2*_vector.x()*_vector.z() + 2*_vector.y()*_scalar, + 2*_vector.y()*_vector.z() - 2*_vector.x()*_scalar, + T(1) - 2*pow<2>(_vector.x()) - 2*pow<2>(_vector.y()) + }; + } + /** * @brief Multiply with scalar and assign * diff --git a/src/Math/Test/MathQuaternionTest.cpp b/src/Math/Test/MathQuaternionTest.cpp index 1b8a351eb..fe2360964 100644 --- a/src/Math/Test/MathQuaternionTest.cpp +++ b/src/Math/Test/MathQuaternionTest.cpp @@ -17,6 +17,7 @@ #include #include "Math/Constants.h" +#include "Math/Matrix4.h" #include "Math/Quaternion.h" namespace Magnum { namespace Math { namespace Test { @@ -34,6 +35,7 @@ class QuaternionTest: public Corrade::TestSuite::Tester { void inverted(); void invertedNormalized(); void rotation(); + void matrix(); void debug(); }; @@ -51,6 +53,7 @@ QuaternionTest::QuaternionTest() { &QuaternionTest::inverted, &QuaternionTest::invertedNormalized, &QuaternionTest::rotation, + &QuaternionTest::matrix, &QuaternionTest::debug); } @@ -132,6 +135,14 @@ void QuaternionTest::rotation() { CORRADE_COMPARE(q2.rotationAxis(), -axis); } +void QuaternionTest::matrix() { + float angle = deg(37.0f); + Vector3 axis(1.0f/Constants::sqrt3()); + Quaternion q = Quaternion::fromRotation(angle, axis); + Matrix<3, float> expected = Matrix4::rotation(angle, axis).rotationScaling(); + CORRADE_COMPARE(q.matrix(), expected); +} + void QuaternionTest::debug() { std::ostringstream o;