Browse Source

Math: added Vector::isZero().

pull/23/head
Vladimír Vondruš 13 years ago
parent
commit
5ff1020dcd
  1. 7
      src/Math/Test/VectorTest.cpp
  2. 16
      src/Math/TypeTraits.h
  3. 12
      src/Math/Vector.h

7
src/Math/Test/VectorTest.cpp

@ -62,6 +62,7 @@ class VectorTest: public Corrade::TestSuite::Tester {
void constructConversion();
void constructCopy();
void isZero();
void isNormalized();
void convert();
@ -109,6 +110,7 @@ VectorTest::VectorTest() {
&VectorTest::constructConversion,
&VectorTest::constructCopy,
&VectorTest::isZero,
&VectorTest::isNormalized,
&VectorTest::convert,
@ -198,6 +200,11 @@ void VectorTest::constructCopy() {
CORRADE_COMPARE(b, Vector4(1.0f, 3.5f, 4.0f, -2.7f));
}
void VectorTest::isZero() {
CORRADE_VERIFY(!Vector3(0.01f, 0.0f, 0.0f).isZero());
CORRADE_VERIFY(Vector3(0.0f, 0.0f, 0.0f).isZero());
}
void VectorTest::isNormalized() {
CORRADE_VERIFY(!Vector3(1.0f, 2.0f, -1.0f).isNormalized());
CORRADE_VERIFY(Vector3(0.0f, 1.0f, 0.0f).isNormalized());

16
src/Math/TypeTraits.h

@ -183,6 +183,14 @@ template<> struct TypeTraits<long double>: Implementation::TypeTraitsFloatingPoi
constexpr static long double epsilon() { return LONG_DOUBLE_EQUALITY_PRECISION; }
};
namespace Implementation {
/* Proper comparison should be with epsilon^2, but the value is not
representable in given precision. Comparing to epsilon instead. */
template<class T> inline bool isZeroSquared(T lengthSquared) {
return std::abs(lengthSquared) < TypeTraits<T>::epsilon();
}
/* Comparing squared length to 1 is not sufficient to compare within range
[1 - epsilon, 1 + epsilon], as e.g. Quaternion with dot() = 1 + 1e-7 when
converted to matrix has column vectors with dot() = 1 + 1e-6, which is just
@ -190,10 +198,10 @@ template<> struct TypeTraits<long double>: Implementation::TypeTraitsFloatingPoi
[1 - epsilon, 1 + epsilon] or dot() in range [1 - 2*epsilon + epsilon^2,
1 + 2*epsilon + epsilon^2]. Because epsilon^2 is way off machine precision,
it's omitted. */
namespace Implementation {
template<class T> inline bool isNormalizedSquared(T lengthSquared) {
return std::abs(lengthSquared - T(1)) < T(2)*TypeTraits<T>::epsilon();
}
template<class T> inline bool isNormalizedSquared(T lengthSquared) {
return std::abs(lengthSquared - T(1)) < T(2)*TypeTraits<T>::epsilon();
}
}
#endif

12
src/Math/Vector.h

@ -220,6 +220,18 @@ template<std::size_t size, class T> class Vector {
/** @brief Component-wise greater than */
BoolVector<size> operator>(const Vector<size, T>& other) const;
/**
* @brief Whether the vector is zero
*
* @f[
* |\boldsymbol a \cdot \boldsymbol a - 0| < \epsilon^2 \cong \epsilon
* @f]
* @see dot(), normalized()
*/
bool isZero() const {
return Implementation::isZeroSquared(dot());
}
/**
* @brief Whether the vector is normalized
*

Loading…
Cancel
Save