point_triangle_squared_distance.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2016 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "point_triangle_squared_distance.h"
  9. template < typename Kernel>
  10. IGL_INLINE void point_triangle_squared_distance(
  11. const CGAL::Point_3<Kernel> & P1,
  12. const CGAL::Triangle_3<Kernel> & T2,
  13. CGAL::Point_3<Kernel> & P2,
  14. typename Kernel::FT & d)
  15. {
  16. assert(!T2.is_degenerate());
  17. if(T2.has_on(P1))
  18. {
  19. P2 = P1;
  20. d = 0;
  21. return;
  22. }
  23. const auto proj_1 = T2.supporting_plane().projection(P2);
  24. if(T2.has_on(proj_1))
  25. {
  26. P2 = proj_1;
  27. d = (proj_1-P1).squared_length();
  28. return;
  29. }
  30. // closest point must be on the boundary
  31. bool first = true;
  32. // loop over edges
  33. for(int i=0;i<3;i++)
  34. {
  35. CGAL::Point_3<Kernel> P2i;
  36. typename Kernel::FT di;
  37. const CGAL::Segment_3<Kernel> si( T2.vertex(i+1), T2.vertex(i+2));
  38. point_segment_squared_distance(P1,si,P2i,di);
  39. if(first || di < d)
  40. {
  41. first = false;
  42. d = di;
  43. P2 = P2i;
  44. }
  45. }
  46. }