helpler_funtions.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #pragma once
  2. #include <float.h>
  3. #include <stdbool.h>
  4. #include "math.h"
  5. #ifndef M_PI
  6. #define M_PI 3.14159265358979323846
  7. #endif
  8. static inline int sign(float val)
  9. {
  10. return (FLT_EPSILON < val) - (val < FLT_EPSILON);
  11. }
  12. static inline double wrap_double(double x, double low, double high)
  13. {
  14. if (low <= x && x < high)
  15. {
  16. return x;
  17. }
  18. const double range = high - low;
  19. const double inv_range = 1.0f / range;
  20. const double num_wraps = floor((x - low) * inv_range);
  21. return x - range * num_wraps;
  22. }
  23. static inline float wrap_float(float x, float low, float high)
  24. {
  25. if (low <= x && x < high)
  26. {
  27. return x;
  28. }
  29. const float range = high - low;
  30. const float inv_range = 1.0f / range;
  31. const float num_wraps = floorf((x - low) * inv_range);
  32. return x - range * num_wraps;
  33. }
  34. static inline float wrap_pi(float x)
  35. {
  36. return wrap_float(x, -M_PI, M_PI);
  37. }
  38. static inline float wrap_180(float x)
  39. {
  40. return wrap_float(x, -180.0f, 180.0f);
  41. }
  42. static inline float wrap_360(float x)
  43. {
  44. return wrap_float(x, 0.0f, 360.0f);
  45. }
  46. static inline float constrain_float(float x, float low, float high)
  47. {
  48. if (x < low)
  49. return low;
  50. else if (x > high)
  51. return high;
  52. else
  53. return x;
  54. }
  55. static inline float rad_to_deg(float rad)
  56. {
  57. return (rad * 180.0f / M_PI);
  58. }
  59. static inline float deg_to_rad(float deg)
  60. {
  61. return (deg * M_PI / 180.0f);
  62. }