Browse Source

Template-ize some math.hpp functions.

tags/v1.1.6
Andrew Belt 5 years ago
parent
commit
7eb5017efd
1 changed files with 17 additions and 12 deletions
  1. +17
    -12
      include/math.hpp

+ 17
- 12
include/math.hpp View File

@@ -17,12 +17,14 @@ namespace math {
////////////////////

/** Returns true if `x` is odd. */
inline bool isEven(int x) {
template <typename T>
bool isEven(T x) {
return x % 2 == 0;
}

/** Returns true if `x` is odd. */
inline bool isOdd(int x) {
template <typename T>
bool isOdd(T x) {
return x % 2 != 0;
}

@@ -74,8 +76,9 @@ inline void eucDivMod(int a, int b, int* div, int* mod) {
}

/** Returns `floor(log_2(n))`, or 0 if `n == 1`. */
inline int log2(int n) {
int i = 0;
template <typename T>
T log2(T n) {
T i = 0;
while (n >>= 1) {
i++;
}
@@ -83,10 +86,19 @@ inline int log2(int n) {
}

/** Returns whether `n` is a power of 2. */
inline bool isPow2(int n) {
template <typename T>
bool isPow2(T n) {
return n > 0 && (n & (n - 1)) == 0;
}

/** Returns 1 for positive numbers, -1 for negative numbers, and 0 for zero.
See https://en.wikipedia.org/wiki/Sign_function.
*/
template <typename T>
T sgn(T x) {
return x > 0 ? 1 : (x < 0 ? -1 : 0);
}

////////////////////
// basic float functions
////////////////////
@@ -105,13 +117,6 @@ inline float clampSafe(float x, float a, float b) {
return (a <= b) ? clamp(x, a, b) : clamp(x, b, a);
}

/** Returns 1 for positive numbers, -1 for negative numbers, and 0 for zero.
See https://en.wikipedia.org/wiki/Sign_function.
*/
inline float sgn(float x) {
return x > 0.f ? 1.f : (x < 0.f ? -1.f : 0.f);
}

/** Converts -0.f to 0.f. Leaves all other values unchanged. */
inline float normalizeZero(float x) {
return x + 0.f;


Loading…
Cancel
Save