From 37a5d6347e68ec618e307118ecb52f0ca219ed69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladim=C3=ADr=20Vondru=C5=A1?= Date: Mon, 6 Aug 2012 17:23:55 +0200 Subject: [PATCH] Vector::angle() now expects normalized vectors. --- src/Math/Test/CMakeLists.txt | 1 + src/Math/Test/VectorTest.cpp | 9 ++++++++- src/Math/Vector.h | 11 +++++++---- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/Math/Test/CMakeLists.txt b/src/Math/Test/CMakeLists.txt index d19e1d975..f71db4d9a 100644 --- a/src/Math/Test/CMakeLists.txt +++ b/src/Math/Test/CMakeLists.txt @@ -1,6 +1,7 @@ corrade_add_test2(MathMathTypeTraitsTest MathTypeTraitsTest.cpp) corrade_add_test2(MathVectorTest VectorTest.cpp) +set_target_properties(MathVectorTest PROPERTIES COMPILE_FLAGS -DCORRADE_GRACEFUL_ASSERT) corrade_add_test2(MathVector2Test Vector2Test.cpp) corrade_add_test2(MathVector3Test Vector3Test.cpp) corrade_add_test2(MathVector4Test Vector4Test.cpp) diff --git a/src/Math/Test/VectorTest.cpp b/src/Math/Test/VectorTest.cpp index 459084f44..109f50ca9 100644 --- a/src/Math/Test/VectorTest.cpp +++ b/src/Math/Test/VectorTest.cpp @@ -131,7 +131,14 @@ void VectorTest::product() { } void VectorTest::angle() { - CORRADE_COMPARE(Vector3::angle({2.0f, 3.0f, 4.0f}, {1.0f, -2.0f, 3.0f}), rad(1.162514f)); + ostringstream o; + Error::setOutput(&o); + /* Both vectors must be normalized, otherwise NaN is returned */ + CORRADE_COMPARE(Vector3::angle(Vector3(2.0f, 3.0f, 4.0f).normalized(), {1.0f, -2.0f, 3.0f}), numeric_limits::quiet_NaN()); + CORRADE_COMPARE(o.str(), "Math::Vector::angle(): vectors must be normalized!\n"); + CORRADE_COMPARE(Vector3::angle({2.0f, 3.0f, 4.0f}, Vector3(1.0f, -2.0f, 3.0f).normalized()), numeric_limits::quiet_NaN()); + + CORRADE_COMPARE(Vector3::angle(Vector3(2.0f, 3.0f, 4.0f).normalized(), Vector3(1.0f, -2.0f, 3.0f).normalized()), rad(1.162514f)); } void VectorTest::negative() { diff --git a/src/Math/Vector.h b/src/Math/Vector.h index 5e089d81f..622ee3e00 100644 --- a/src/Math/Vector.h +++ b/src/Math/Vector.h @@ -20,6 +20,7 @@ */ #include +#include #include #include "MathTypeTraits.h" @@ -82,16 +83,18 @@ template class Vector { } /** - * @brief Angle between vectors + * @brief Angle between normalized vectors * * @f[ * \phi = \frac{a \cdot b}{|a| \cdot |b|} * @f] - * - * @todo optimize - Assume the vectors are normalized? + * @attention If any of the parameters is not normalized (and + * assertions are enabled), returns NaN. */ inline static T angle(const Vector& a, const Vector& b) { - return std::acos(dot(a, b)/(a.length()*b.length())); + CORRADE_ASSERT(MathTypeTraits::equals(a.dot(), T(1)) && MathTypeTraits::equals(b.dot(), T(1)), + "Math::Vector::angle(): vectors must be normalized!", std::numeric_limits::quiet_NaN()); + return std::acos(dot(a, b)); } /** @brief Default constructor */