From a66e5c6dabd745738b4184583400bc757e2b97a4 Mon Sep 17 00:00:00 2001 From: Sam Hocevar Date: Sat, 17 May 2014 12:09:56 +0000 Subject: [PATCH] geometry: implement point-to-segment distance function. --- src/lol/math/geometry.h | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/lol/math/geometry.h b/src/lol/math/geometry.h index 1636a0d7..05cf712b 100644 --- a/src/lol/math/geometry.h +++ b/src/lol/math/geometry.h @@ -314,24 +314,34 @@ PlaneIntersection TestPointVsPlane(const TV &point, const TV &plane_p, const TV return PlaneIntersection::Plane; } -//Project points functions -//Plane +/* Project point on plane */ template -TV ProjectPointOnPlane(TV const &proj_point, TV const &plane_point, TV const &plane_normal) +TV ProjectPointOnPlane(TV const &p, TV const &origin, TV const &normal) { - return proj_point - dot(proj_point - plane_point, plane_normal) * plane_normal; + return p - dot(p - origin, normal) * normal; } -//Line + +/* Project point on line */ +template +TV ProjectPointOnRay(TV const &p, TV const &origin, TV const &direction) +{ + return origin + direction * dot(p - origin, direction); +} + +/* Distance from point to plane */ template -TV ProjectPointOnRay(TV const &proj_point, TV const &ray_point, TV const &ray_dir) +float PointDistToPlane(TV const &p, TV const &origin, TV const &normal) { - return ray_point + ray_dir * dot(proj_point - ray_point, ray_dir); + return abs(dot(p - origin, normal)); } -//Point dist to plane + +/* Distance from point to segment */ template -float PointDistToPlane(TV const &proj_point, TV const &plane_point, TV const &plane_normal) +float PointDistToSegment(TV const &p, TV const &a, TV const &b) { - return abs(dot(proj_point - plane_point, plane_normal)); + float d2 = sqlength(b - a); + float u = d2 ? dot(p - a, b - a) / d2 : 0.0f; + return distance(p, mix(a, b, clamp(u, 0.0f, 1.0f))); } } /* namespace lol */