From 2d30bd751cb964d9790025c5295763da632cf6a2 Mon Sep 17 00:00:00 2001 From: Emil Ernerfeldt Date: Mon, 4 Apr 2022 11:24:08 +0200 Subject: [PATCH] emath: add Rect::signed_distance_to_pos and Vec2::abs --- emath/src/rect.rs | 10 ++++++++++ emath/src/vec2.rs | 6 ++++++ 2 files changed, 16 insertions(+) diff --git a/emath/src/rect.rs b/emath/src/rect.rs index 4309345a..cfb92f0b 100644 --- a/emath/src/rect.rs +++ b/emath/src/rect.rs @@ -338,6 +338,16 @@ impl Rect { dx * dx + dy * dy } + /// Signed distance to the edge of the box. + /// + /// Negative inside the box. + pub fn signed_distance_to_pos(&self, pos: Pos2) -> f32 { + let edge_distances = (pos - self.center()).abs() - self.size() * 0.5; + let inside_dist = edge_distances.x.max(edge_distances.y).min(0.0); + let outside_dist = edge_distances.max(Vec2::ZERO).length(); + inside_dist + outside_dist + } + #[inline(always)] pub fn x_range(&self) -> RangeInclusive { self.min.x..=self.max.x diff --git a/emath/src/vec2.rs b/emath/src/vec2.rs index 35205d16..df7265f3 100644 --- a/emath/src/vec2.rs +++ b/emath/src/vec2.rs @@ -223,6 +223,12 @@ impl Vec2 { vec2(self.x.ceil(), self.y.ceil()) } + #[must_use] + #[inline] + pub fn abs(self) -> Self { + vec2(self.x.abs(), self.y.abs()) + } + /// True if all members are also finite. #[inline(always)] pub fn is_finite(self) -> bool {