BsLineSegment3.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "BsLineSegment3.h"
  2. #include "BsRay.h"
  3. namespace BansheeEngine
  4. {
  5. LineSegment3::LineSegment3(const Vector3& start, const Vector3& end)
  6. :mStart(start), mEnd(end)
  7. {
  8. }
  9. std::pair<std::array<Vector3, 2>, float> LineSegment3::getNearestPoint(const Ray& ray) const
  10. {
  11. const Vector3& org = ray.getOrigin();
  12. const Vector3& dir = ray.getDirection();
  13. Vector3 segDir = mEnd - mStart;
  14. float segExtent = segDir.normalize() * 0.5f;
  15. Vector3 segCenter = mStart + segDir * segExtent;
  16. Vector3 diff = org - segCenter;
  17. float a01 = -dir.dot(segDir);
  18. float b0 = diff.dot(dir);
  19. float c = diff.dot(diff);
  20. float det = fabs(1.0f - a01*a01);
  21. float s0, s1;
  22. float sqrDistance;
  23. if (det > 0.0f) // Not parallel
  24. {
  25. float b1 = -diff.dot(segDir);
  26. s1 = a01 * b0 - b1;
  27. float extDet = segExtent * det;
  28. if (s1 >= -extDet)
  29. {
  30. if (s1 <= extDet) // Interior of the segment and interior of the ray are closest
  31. {
  32. float invDet = 1.0f / det;
  33. s0 = (a01*b1 - b0)*invDet;
  34. s1 *= invDet;
  35. sqrDistance = s0*(s0 + a01*s1 + 2.0f*b0) +
  36. s1*(a01*s0 + s1 + 2.0f*b1) + c;
  37. }
  38. else // Segment end and interior of the ray are closest
  39. {
  40. s1 = segExtent;
  41. s0 = -(a01*s1 + b0);
  42. sqrDistance = -s0*s0 + s1*(s1 + (2.0f)*b1) + c;
  43. }
  44. }
  45. else // Segment start and interior of the ray are closest
  46. {
  47. s1 = -segExtent;
  48. s0 = -(a01*s1 + b0);
  49. sqrDistance = -s0*s0 + s1*(s1 + (2.0f)*b1) + c;
  50. }
  51. }
  52. else // Parallel
  53. {
  54. s1 = 0;
  55. s0 = -b0;
  56. sqrDistance = b0*s0 + c;
  57. }
  58. if (sqrDistance < 0.0f)
  59. sqrDistance = 0.0f;
  60. float distance = std::sqrt(sqrDistance);
  61. std::array<Vector3, 2> nearestPoints;
  62. nearestPoints[0] = org + s0 * dir;
  63. nearestPoints[1] = segCenter + s1 * segDir;
  64. return std::make_pair(nearestPoints, distance);
  65. }
  66. }