region: correct the point-region distance2 calculation

This commit is contained in:
Danny Robson 2019-08-30 13:45:08 +10:00
parent 979deaa4aa
commit fd64ca6bce
2 changed files with 38 additions and 3 deletions

View File

@ -233,11 +233,12 @@ namespace cruft {
distance2 (region<S,T> r, point<S,T> p)
{
auto const clamped = cruft::max (
cruft::min (p, r.p + r.e),
r.p
r.p - p,
vector<S,T> (0),
p - (r.p + r.e)
);
return distance2 (r.p, clamped);
return sum (clamped * clamped);
}

View File

@ -102,5 +102,39 @@ main (int, char **)
tap.expect (success, "make_range(region2i)");
};
// test distance2 for points
{
struct {
cruft::region2f r;
cruft::point2f p;
float distance2;
char const *message;
} const TESTS[] = {
{
{ cruft::point2f { 1, 1 }, cruft::point2f { 3, 5 } },
{ 0, 0 },
2.f,
"origin to offset rect"
},
{
{ cruft::point2f { 1, 1 }, cruft::point2f { 3, 5 } },
{ 2, 2 },
0.f,
"point inside region"
},
{
{ cruft::point2f { 1, 1 }, cruft::point2f { 3, 5 } },
{ 4, 7 },
1 + 4,
"offset point to offset rect"
},
};
for (auto const &t: TESTS) {
auto const d2 = distance2 (t.r, t.p);
tap.expect_eq (d2, t.distance2, "region-point distance2: %!", t.message);
}
};
return tap.status ();
}