diff --git a/geom/aabb.cpp b/geom/aabb.cpp index f74632ae..579f21db 100644 --- a/geom/aabb.cpp +++ b/geom/aabb.cpp @@ -9,6 +9,7 @@ #include "aabb.hpp" +#include "ops.hpp" #include "iostream.hpp" #include "../coord/iostream.hpp" @@ -35,6 +36,21 @@ aabb<3,float>::vertices (void) const noexcept } +/////////////////////////////////////////////////////////////////////////////// +/// Returns the squared minimum distance from the AABB to a point. +template +T cruft::geom::distance2 (aabb a, point b) +{ + auto const clamped = cruft::max ( + a.lo - b, + vector (0), + b - a.hi + ); + + return sum (clamped * clamped); +} + + /////////////////////////////////////////////////////////////////////////////// namespace cruft::debug { template @@ -60,8 +76,9 @@ cruft::geom::operator<< (std::ostream &os, cruft::geom::aabb b) #define INSTANTIATE_S_T(S,T) \ namespace cruft::geom { template struct aabb; } \ template bool cruft::debug::is_valid (const aabb&); \ -template std::ostream& cruft::geom::operator<< (std::ostream&, aabb); - +template std::ostream& cruft::geom::operator<< (std::ostream&, aabb); \ +template T cruft::geom::distance2 (point, aabb); \ +template T cruft::geom::distance2 (aabb, point); #define INSTANTIATE(T) \ INSTANTIATE_S_T(2,T) \ INSTANTIATE_S_T(3,T) diff --git a/geom/aabb.hpp b/geom/aabb.hpp index 94b5e7f5..f4d23728 100644 --- a/geom/aabb.hpp +++ b/geom/aabb.hpp @@ -192,6 +192,21 @@ namespace cruft::geom { { return a.inclusive (b); } + + + /////////////////////////////////////////////////////////////////////////// + /// Returns the squared minimum distance from the AABB to a point. + template + T distance2 (aabb a, point b); + + + //------------------------------------------------------------------------- + template + T + distance2 (point a, aabb b) + { + return distance2 (b, a); + } }