Browse Source

Utility function for clamping value in given limits.

vectorfields
Vladimír Vondruš 14 years ago
parent
commit
3558859cc6
  1. 6
      src/Math/Math.h
  2. 7
      src/Math/Test/MathTest.cpp
  3. 1
      src/Math/Test/MathTest.h

6
src/Math/Math.h

@ -19,6 +19,7 @@
#include <cmath> #include <cmath>
#include <type_traits> #include <type_traits>
#include <limits> #include <limits>
#include <algorithm>
#include "magnumVisibility.h" #include "magnumVisibility.h"
@ -129,6 +130,11 @@ template<class Integral, class FloatingPoint> inline constexpr typename std::ena
FloatingPoint(value*std::numeric_limits<Integral>::min())); FloatingPoint(value*std::numeric_limits<Integral>::min()));
} }
/** @brief Clamp value */
template<class T> inline T clamp(T value, T min, T max) {
return std::min(std::max(value, min), max);
}
/** /**
@brief Angle in degrees @brief Angle in degrees

7
src/Math/Test/MathTest.cpp

@ -28,6 +28,7 @@ MathTest::MathTest() {
&MathTest::degrad, &MathTest::degrad,
&MathTest::normalize, &MathTest::normalize,
&MathTest::denormalize, &MathTest::denormalize,
&MathTest::clamp,
&MathTest::pow, &MathTest::pow,
&MathTest::log); &MathTest::log);
} }
@ -96,6 +97,12 @@ void MathTest::denormalize() {
} }
} }
void MathTest::clamp() {
CORRADE_COMPARE(Math::clamp(0.5f, -1.0f, 5.0f), 0.5f);
CORRADE_COMPARE(Math::clamp(-1.6f, -1.0f, 5.0f), -1.0f);
CORRADE_COMPARE(Math::clamp(9.5f, -1.0f, 5.0f), 5.0f);
}
void MathTest::pow() { void MathTest::pow() {
CORRADE_COMPARE(Math::pow<10>(2ul), 1024ul); CORRADE_COMPARE(Math::pow<10>(2ul), 1024ul);
CORRADE_COMPARE(Math::pow<0>(3ul), 1ul); CORRADE_COMPARE(Math::pow<0>(3ul), 1ul);

1
src/Math/Test/MathTest.h

@ -27,6 +27,7 @@ class MathTest: public Corrade::TestSuite::Tester<MathTest> {
void degrad(); void degrad();
void normalize(); void normalize();
void denormalize(); void denormalize();
void clamp();
void pow(); void pow();
void log(); void log();
}; };

Loading…
Cancel
Save