Open Source Tomb Raider Engine
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

math.cpp 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*!
  2. *
  3. * \file src/math/math.cpp
  4. * \brief Vector and Matrix math
  5. *
  6. * \author Mongoose
  7. * \author xythobuz
  8. */
  9. #include <cstdlib>
  10. #include <cmath>
  11. #include <float.h>
  12. #include <algorithm>
  13. #include "global.h"
  14. #include "math/Vector3d.h"
  15. #include "math/Matrix.h"
  16. #include "math/math.h"
  17. bool equalEpsilon(float a, float b) {
  18. float epsilon = FLT_EPSILON;
  19. if (fabs(a - b) <= (std::max(fabs(a), fabs(b)) * epsilon))
  20. return true;
  21. return false;
  22. }
  23. int intersectionLinePolygon(float intersect[3],
  24. float p1[3], float p2[3], float polygon[3][3]) {
  25. assert(polygon != NULL);
  26. // float normal[3], a[3], b[3];
  27. Vector3d a, b, normal, pA, pB;
  28. float d, denominator, mu;
  29. pA = Vector3d(p1);
  30. pB = Vector3d(p2);
  31. // Find normal
  32. a = Vector3d(polygon[1]) - Vector3d(polygon[0]);
  33. b = Vector3d(polygon[2]) - Vector3d(polygon[0]);
  34. normal = Vector3d::cross(a, b);
  35. normal.normalize();
  36. // find D
  37. d = (normal.mVec[0] * polygon[0][0] -
  38. normal.mVec[1] * polygon[0][1] -
  39. normal.mVec[2] * polygon[0][2]);
  40. // line segment parallel to plane?
  41. a = pB - pA;
  42. denominator = Vector3d::dot(normal, a);
  43. if (denominator > 0.0)
  44. return 0;
  45. // Line segment contains intercept point?
  46. mu = -((d + Vector3d::dot(normal, pA)) / denominator);
  47. if (mu < 0.0 || mu > 1.0)
  48. return 0;
  49. b = pA + (a * mu);
  50. intersect[0] = b.mVec[0];
  51. intersect[1] = b.mVec[1];
  52. intersect[2] = b.mVec[2];
  53. // See if the intercept is bound by polygon by winding number
  54. // assume convex polygons here for sure
  55. double theta = Vector3d::dot(b - Vector3d(polygon[0]), normal); // b = intersect
  56. if (theta >= 90.0) // Yeah I know
  57. return 0;
  58. return 1;
  59. }
  60. float distance(const float a[3], const float b[3]) {
  61. return sqrtf(((b[0] - a[0]) * (b[0] - a[0])) +
  62. ((b[1] - a[1]) * (b[1] - a[1])) +
  63. ((b[2] - a[2]) * (b[2] - a[2])));
  64. }
  65. void midpoint(const float a[3], const float b[3], float mid[3]) {
  66. mid[0] = (a[0] + b[0]) / 2.0f;
  67. mid[1] = (a[1] + b[1]) / 2.0f;
  68. mid[2] = (a[2] + b[2]) / 2.0f;
  69. }
  70. float randomNum(float from, float to) {
  71. return from + ((to - from) * rand() / (RAND_MAX + 1.0f));
  72. }