use crate::kurbo::{BezPath, Point, Rect, Shape, Vec2};
#[derive(Clone, Debug)]
pub struct Region {
rects: Vec<Rect>,
}
impl Region {
pub const EMPTY: Region = Region { rects: Vec::new() };
#[inline]
pub fn rects(&self) -> &[Rect] {
&self.rects
}
pub fn add_rect(&mut self, rect: Rect) {
if rect.area() > 0.0 {
self.rects.push(rect);
}
}
pub fn set_rect(&mut self, rect: Rect) {
self.clear();
self.add_rect(rect);
}
pub fn clear(&mut self) {
self.rects.clear();
}
pub fn bounding_box(&self) -> Rect {
if self.rects.is_empty() {
Rect::ZERO
} else {
self.rects[1..]
.iter()
.fold(self.rects[0], |r, s| r.union(*s))
}
}
#[doc(hidden)]
#[deprecated(since = "0.7.0", note = "Use bounding_box() instead")]
pub fn to_rect(&self) -> Rect {
self.bounding_box()
}
pub fn intersects(&self, rect: Rect) -> bool {
self.rects.iter().any(|r| r.intersect(rect).area() > 0.0)
}
pub fn contains(&self, point: Point) -> bool {
self.rects.iter().any(|r| r.contains(point))
}
pub fn is_empty(&self) -> bool {
self.rects.is_empty()
}
pub fn to_bez_path(&self) -> BezPath {
let mut ret = BezPath::new();
for rect in self.rects() {
ret.extend(rect.path_elements(0.0));
}
ret
}
pub fn union_with(&mut self, other: &Region) {
self.rects.extend_from_slice(&other.rects);
}
pub fn intersect_with(&mut self, rect: Rect) {
for r in &mut self.rects {
*r = r.intersect(rect);
}
self.rects.retain(|r| r.area() > 0.0)
}
}
impl std::ops::AddAssign<Vec2> for Region {
fn add_assign(&mut self, rhs: Vec2) {
for r in &mut self.rects {
*r = *r + rhs;
}
}
}
impl std::ops::SubAssign<Vec2> for Region {
fn sub_assign(&mut self, rhs: Vec2) {
for r in &mut self.rects {
*r = *r - rhs;
}
}
}
impl From<Rect> for Region {
fn from(rect: Rect) -> Region {
Region { rects: vec![rect] }
}
}