ddnet/src/base/math.h

133 lines
2.2 KiB
C
Raw Normal View History

2010-11-20 10:37:14 +00:00
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#ifndef BASE_MATH_H
#define BASE_MATH_H
#include <algorithm>
#include <cmath>
#include <cstdlib>
2008-01-12 17:09:00 +00:00
using std::clamp;
constexpr float pi = 3.1415926535897932384626433f;
2020-08-19 20:47:09 +00:00
constexpr inline int round_to_int(float f)
{
2020-08-19 21:02:33 +00:00
return f > 0 ? (int)(f + 0.5f) : (int)(f - 0.5f);
}
2020-08-19 20:47:09 +00:00
constexpr inline int round_truncate(float f)
2019-04-24 20:47:03 +00:00
{
return (int)f;
}
template<typename T, typename TB>
2020-08-19 20:47:09 +00:00
constexpr inline T mix(const T a, const T b, TB amount)
{
return a + (b - a) * amount;
}
2008-01-12 17:09:00 +00:00
inline float random_float()
{
return rand() / (float)(RAND_MAX);
}
2008-01-12 17:09:00 +00:00
inline float random_angle()
{
return 2.0f * pi * (rand() / std::nextafter((float)RAND_MAX, std::numeric_limits<float>::max()));
}
constexpr int fxpscale = 1 << 10;
// float to fixed
constexpr inline int f2fx(float v)
{
return (int)(v * fxpscale);
}
constexpr inline float fx2f(int v)
{
return v / (float)fxpscale;
}
// int to fixed
constexpr inline int i2fx(int v)
2020-09-22 12:47:21 +00:00
{
return v * fxpscale;
2020-09-22 12:47:21 +00:00
}
constexpr inline int fx2i(int v)
2020-09-22 12:47:21 +00:00
{
return v / fxpscale;
2020-09-22 12:47:21 +00:00
}
class fxp
{
int value;
public:
void set(int v)
{
value = v;
}
int get() const
{
return value;
}
fxp &operator=(int v)
{
value = i2fx(v);
return *this;
}
fxp &operator=(float v)
{
value = f2fx(v);
return *this;
}
operator int() const
{
return fx2i(value);
}
operator float() const
{
return fx2f(value);
}
};
template<typename T>
constexpr inline T minimum(T a, T b)
{
return std::min(a, b);
}
template<typename T>
constexpr inline T minimum(T a, T b, T c)
{
return std::min(std::min(a, b), c);
}
template<typename T>
constexpr inline T maximum(T a, T b)
{
return std::max(a, b);
}
template<typename T>
constexpr inline T maximum(T a, T b, T c)
{
return std::max(std::max(a, b), c);
}
template<typename T>
constexpr inline T absolute(T a)
{
return a < T(0) ? -a : a;
}
template<typename T>
constexpr inline T in_range(T a, T lower, T upper)
{
return lower <= a && a <= upper;
}
template<typename T>
constexpr inline T in_range(T a, T upper)
{
return in_range(a, 0, upper);
}
#endif // BASE_MATH_H