point_segment_squared_distance.cpp 729 B

12345678910111213141516171819202122232425262728293031323334
  1. #include "point_segment_squared_distance.h"
  2. template < typename Kernel>
  3. IGL_INLINE void igl::copyleft::cgal::point_segment_squared_distance(
  4. const CGAL::Point_3<Kernel> & P1,
  5. const CGAL::Segment_3<Kernel> & S2,
  6. CGAL::Point_3<Kernel> & P2,
  7. typename Kernel::FT & d)
  8. {
  9. if(S2.is_degenerate())
  10. {
  11. P2 = S2.source();
  12. d = (P1-P2).squared_length();
  13. return;
  14. }
  15. // http://stackoverflow.com/a/1501725/148668
  16. const auto sqr_len = S2.squared_length();
  17. assert(sqr_len != 0);
  18. const auto & V = S1.source();
  19. const auto & W = S2.target();
  20. const auto t = (P1-V).dot(W-V)/sqr_len;
  21. if(t<0)
  22. {
  23. P2 = V;
  24. }else if(t>1)
  25. {
  26. P2 = W;
  27. }else
  28. {
  29. P2 = V + t*(W-V);
  30. }
  31. d = (P1-P2).squared_length();
  32. }