DistLineRay.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // David Eberly, Geometric Tools, Redmond WA 98052
  2. // Copyright (c) 1998-2020
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // https://www.boost.org/LICENSE_1_0.txt
  5. // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
  6. // Version: 4.0.2019.08.13
  7. #pragma once
  8. #include <Mathematics/DCPQuery.h>
  9. #include <Mathematics/Line.h>
  10. #include <Mathematics/Ray.h>
  11. namespace WwiseGTE
  12. {
  13. template <int N, typename Real>
  14. class DCPQuery<Real, Line<N, Real>, Ray<N, Real>>
  15. {
  16. public:
  17. struct Result
  18. {
  19. Real distance, sqrDistance;
  20. Real parameter[2];
  21. Vector<N, Real> closestPoint[2];
  22. };
  23. Result operator()(Line<N, Real> const& line, Ray<N, Real> const& ray)
  24. {
  25. Result result;
  26. Vector<N, Real> diff = line.origin - ray.origin;
  27. Real a01 = -Dot(line.direction, ray.direction);
  28. Real b0 = Dot(diff, line.direction);
  29. Real s0, s1;
  30. if (std::fabs(a01) < (Real)1)
  31. {
  32. Real b1 = -Dot(diff, ray.direction);
  33. s1 = a01 * b0 - b1;
  34. if (s1 >= (Real)0)
  35. {
  36. // Two interior points are closest, one on line and one
  37. // on ray.
  38. Real det = (Real)1 - a01 * a01;
  39. s0 = (a01 * b1 - b0) / det;
  40. s1 /= det;
  41. }
  42. else
  43. {
  44. // Origin of ray and interior point of line are closest.
  45. s0 = -b0;
  46. s1 = (Real)0;
  47. }
  48. }
  49. else
  50. {
  51. // Lines are parallel, closest pair with one point at ray
  52. // origin.
  53. s0 = -b0;
  54. s1 = (Real)0;
  55. }
  56. result.parameter[0] = s0;
  57. result.parameter[1] = s1;
  58. result.closestPoint[0] = line.origin + s0 * line.direction;
  59. result.closestPoint[1] = ray.origin + s1 * ray.direction;
  60. diff = result.closestPoint[0] - result.closestPoint[1];
  61. result.sqrDistance = Dot(diff, diff);
  62. result.distance = std::sqrt(result.sqrDistance);
  63. return result;
  64. }
  65. };
  66. // Template aliases for convenience.
  67. template <int N, typename Real>
  68. using DCPLineRay = DCPQuery<Real, Line<N, Real>, Ray<N, Real>>;
  69. template <typename Real>
  70. using DCPLine2Ray2 = DCPLineRay<2, Real>;
  71. template <typename Real>
  72. using DCPLine3Ray3 = DCPLineRay<3, Real>;
  73. }