use glam::Vec2;
use super::Corners;
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct Rect {
pub position: Vec2,
pub size: Vec2,
}
impl Rect {
pub const fn new(position: Vec2, size: Vec2) -> Self {
Self { position, size }
}
pub const fn from_position(position: Vec2) -> Self {
Self {
position,
size: Vec2::ZERO,
}
}
pub const fn from_size(size: Vec2) -> Self {
Self {
position: Vec2::ZERO,
size,
}
}
pub fn contains_point(&self, point: Vec2) -> bool {
point.cmpge(self.position).all() && point.cmple(self.position + self.size).all()
}
pub fn intersects_rect(&self, other: Rect) -> bool {
self.position.x < other.position.x + other.size.x
&& self.position.x + self.size.x > other.position.x
&& self.position.y < other.position.y + other.size.y
&& self.position.y + self.size.y > other.position.y
}
pub fn width(&self) -> f32 {
self.size.x
}
pub fn height(&self) -> f32 {
self.size.y
}
pub fn x(&self) -> f32 {
self.position.x
}
pub fn y(&self) -> f32 {
self.position.y
}
pub fn corners(&self) -> Corners<Vec2> {
Corners {
top_left: self.position,
top_right: self.position + Vec2::new(self.size.x, 0.0),
bottom_left: self.position + Vec2::new(0.0, self.size.y),
bottom_right: self.position + self.size,
}
}
}
impl From<Vec2> for Rect {
fn from(size: Vec2) -> Self {
Self::from_size(size)
}
}
impl From<(Vec2, Vec2)> for Rect {
fn from((position, size): (Vec2, Vec2)) -> Self {
Self { position, size }
}
}
impl From<(f32, f32, f32, f32)> for Rect {
fn from((x, y, width, height): (f32, f32, f32, f32)) -> Self {
Self {
position: Vec2::new(x, y),
size: Vec2::new(width, height),
}
}
}
impl From<[f32; 4]> for Rect {
fn from([x, y, width, height]: [f32; 4]) -> Self {
Self {
position: Vec2::new(x, y),
size: Vec2::new(width, height),
}
}
}
impl From<Rect> for (Vec2, Vec2) {
fn from(rect: Rect) -> Self {
(rect.position, rect.size)
}
}
impl From<Rect> for (f32, f32, f32, f32) {
fn from(rect: Rect) -> Self {
(rect.position.x, rect.position.y, rect.size.x, rect.size.y)
}
}
impl From<Rect> for [f32; 4] {
fn from(rect: Rect) -> Self {
[rect.position.x, rect.position.y, rect.size.x, rect.size.y]
}
}