nvmath.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // This code is in the public domain -- [email protected]
  2. #ifndef NV_MATH_H
  3. #define NV_MATH_H
  4. #include <cmath>
  5. #include <float.h> // finite, isnan
  6. #include "nvcore/utils.h" // max, clamp
  7. #define NVMATH_API
  8. #define NVMATH_CLASS
  9. #define PI float(3.1415926535897932384626433833)
  10. #define NV_EPSILON (0.0001f)
  11. #define NV_NORMAL_EPSILON (0.001f)
  12. namespace nv
  13. {
  14. inline float toRadian(float degree) { return degree * (PI / 180.0f); }
  15. inline float toDegree(float radian) { return radian * (180.0f / PI); }
  16. // Robust floating point comparisons:
  17. // http://realtimecollisiondetection.net/blog/?p=89
  18. inline bool equal(const float f0, const float f1, const float epsilon = NV_EPSILON)
  19. {
  20. //return fabs(f0-f1) <= epsilon;
  21. return fabs(f0-f1) <= epsilon * max3(1.0f, fabsf(f0), fabsf(f1));
  22. }
  23. inline bool isZero(const float f, const float epsilon = NV_EPSILON)
  24. {
  25. return fabsf(f) <= epsilon;
  26. }
  27. inline bool isFinite(const float f)
  28. {
  29. #if defined(_MSC_VER) && _MSC_VER <= 1800
  30. (void)f;
  31. return true;
  32. #else
  33. return std::isfinite(f);
  34. #endif // defined(_MSC_VER) && _MSC_VER <= 1800
  35. }
  36. // Eliminates negative zeros from a float array.
  37. inline void floatCleanup(float * fp, int n)
  38. {
  39. for (int i = 0; i < n; i++) {
  40. //nvDebugCheck(isFinite(fp[i]));
  41. union { float f; uint32 i; } x = { fp[i] };
  42. if (x.i == 0x80000000) fp[i] = 0.0f;
  43. }
  44. }
  45. inline float saturate(float f) {
  46. return clamp(f, 0.0f, 1.0f);
  47. }
  48. }
  49. #endif // NV_MATH_H