From 2be1ff3763eb044b609edafb83d6392b1c4cd204 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladim=C3=ADr=20Vondru=C5=A1?= Date: Fri, 27 Apr 2012 02:29:09 +0200 Subject: [PATCH] Added Vector::lengthSquared() function. The name is a little bit misleading, but it is for more efficient vector length comparisons. --- src/Math/Test/VectorTest.cpp | 4 ++++ src/Math/Test/VectorTest.h | 1 + src/Math/Vector.h | 18 +++++++++++++++++- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Math/Test/VectorTest.cpp b/src/Math/Test/VectorTest.cpp index 38f13c919..0726925ea 100644 --- a/src/Math/Test/VectorTest.cpp +++ b/src/Math/Test/VectorTest.cpp @@ -93,6 +93,10 @@ void VectorTest::length() { QCOMPARE(Vector4(1.0f, 2.0f, 3.0f, 4.0f).length(), 5.4772256f); } +void VectorTest::lengthSquared() { + QCOMPARE(Vector4(1.0f, 2.0f, 3.0f, 4.0f).lengthSquared(), 30.0f); +} + void VectorTest::normalized() { QVERIFY(Vector4(1.0f, 1.0f, 1.0f, 1.0f).normalized() == Vector4(0.5f, 0.5f, 0.5f, 0.5f)); } diff --git a/src/Math/Test/VectorTest.h b/src/Math/Test/VectorTest.h index 70c7222e3..143ea01a3 100644 --- a/src/Math/Test/VectorTest.h +++ b/src/Math/Test/VectorTest.h @@ -30,6 +30,7 @@ class VectorTest: public QObject { void multiplyDivide(); void addSubstract(); void length(); + void lengthSquared(); void normalized(); void product(); void angle(); diff --git a/src/Math/Vector.h b/src/Math/Vector.h index 66a88f8f7..11fa9da49 100644 --- a/src/Math/Vector.h +++ b/src/Math/Vector.h @@ -218,11 +218,27 @@ template class Vector { return out; } - /** @brief %Vector length */ + /** + * @brief %Vector length + * + * @see lengthSquared() + */ inline T length() const { return sqrt(dot(*this, *this)); } + /** + * @brief %Vector length squared + * + * More efficient than length() for comparing vector length with + * other values, because it doesn't compute the square root, just the + * dot product: @f$ a \cdot a < length \cdot length @f$ is faster + * than @f$ \sqrt{a \cdot a} < length @f$. + */ + inline T lengthSquared() const { + return dot(*this, *this); + } + /** @brief Normalized vector (of length 1) */ inline Vector normalized() const { return *this/length();