9
3

closest_point.inl 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /// @ref gtx_closest_point
  2. namespace glm
  3. {
  4. template<typename T, qualifier Q>
  5. GLM_FUNC_QUALIFIER vec<3, T, Q> closestPointOnLine
  6. (
  7. vec<3, T, Q> const& point,
  8. vec<3, T, Q> const& a,
  9. vec<3, T, Q> const& b
  10. )
  11. {
  12. T LineLength = distance(a, b);
  13. vec<3, T, Q> Vector = point - a;
  14. vec<3, T, Q> LineDirection = (b - a) / LineLength;
  15. // Project Vector to LineDirection to get the distance of point from a
  16. T Distance = dot(Vector, LineDirection);
  17. if(Distance <= T(0)) return a;
  18. if(Distance >= LineLength) return b;
  19. return a + LineDirection * Distance;
  20. }
  21. template<typename T, qualifier Q>
  22. GLM_FUNC_QUALIFIER vec<2, T, Q> closestPointOnLine
  23. (
  24. vec<2, T, Q> const& point,
  25. vec<2, T, Q> const& a,
  26. vec<2, T, Q> const& b
  27. )
  28. {
  29. T LineLength = distance(a, b);
  30. vec<2, T, Q> Vector = point - a;
  31. vec<2, T, Q> LineDirection = (b - a) / LineLength;
  32. // Project Vector to LineDirection to get the distance of point from a
  33. T Distance = dot(Vector, LineDirection);
  34. if(Distance <= T(0)) return a;
  35. if(Distance >= LineLength) return b;
  36. return a + LineDirection * Distance;
  37. }
  38. }//namespace glm