Math.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #ifndef COREMATH_H
  2. #define COREMATH_H
  3. #include <math.h>
  4. #ifndef M_PI
  5. #define M_PI 3.14159265358979323846
  6. #endif
  7. #ifndef _GNU_SOURCE
  8. void sincosf(float a, float* s, float* c);
  9. #endif
  10. namespace Math {
  11. template<typename T>
  12. T interpolate(const T& a, const T& b, float f) {
  13. return a * (1.0f - f) + b * f;
  14. }
  15. template<typename T>
  16. int popCount(const T& t) {
  17. static constexpr int map[16] = {0, 1, 1, 2, 1, 2, 2, 3,
  18. 1, 2, 2, 3, 2, 3, 3, 4};
  19. int sum = 0;
  20. for(int i = 0; i < static_cast<int>(sizeof(T) * 8); i += 4) {
  21. sum += map[(t >> i) & 0xF];
  22. }
  23. return sum;
  24. }
  25. constexpr int roundUpLog2(int i) {
  26. if(i <= 0) {
  27. return 0;
  28. }
  29. int c = 1;
  30. while(((i - 1) >> c) > 0) {
  31. c++;
  32. }
  33. return c;
  34. }
  35. template<typename T>
  36. const T& min(const T& t) {
  37. return t;
  38. }
  39. template<typename T, typename... Args>
  40. const T& min(const T& t, Args&&... args) {
  41. const T& o = min(args...);
  42. return t < o ? t : o;
  43. }
  44. template<typename T>
  45. const T& max(const T& t) {
  46. return t;
  47. }
  48. template<typename T, typename... Args>
  49. const T& max(const T& t, Args&&... args) {
  50. const T& o = max(args...);
  51. return o < t ? t : o;
  52. }
  53. template<typename T>
  54. const T& clamp(const T& t, const T& borderA, const T& borderB) {
  55. const T& low = min(borderA, borderB);
  56. const T& high = max(borderA, borderB);
  57. return max(low, min(high, t));
  58. }
  59. }
  60. #endif