1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
//! A shape type representing squares and rectangles used for drawing.
//!
//! # Examples
//!
//! You can create a [Rect] or square using [`Rect::new`] or [`Rect::square`]:
//!
//! ```
//! use pix_engine::prelude::*;
//!
//! let r = Rect::new(10, 20, 100, 200);
//! let s = Rect::square(10, 20, 100);
//! ```
//!
//! ...or by using the [rect!] or [square!] macros:
//!
//! ```
//! use pix_engine::prelude::*;
//!
//! let r = rect!(10, 20, 100, 200);
//! let s = square!(10, 20, 100);
//!
//! // using a point
//! let r = rect!([10, 20], 100, 200);
//! let r = rect!(point![10, 20], 100, 200);
//! let s = square!([10, 20], 100);
//! let s = square!(point![10, 20], 100);
//! ```
use crate::{error::Result, prelude::*};
use num_traits::{AsPrimitive, Bounded, NumCast};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::ops::{Add, Sub};
/// A `Rectangle` positioned at `(x, y)` with `width` and `height`. A square is a `Rectangle` where
/// `width` and `height` are equal.
///
/// Please see the [module-level documentation] for examples.
///
/// [module-level documentation]: crate::shape::rect
#[derive(Default, Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[repr(transparent)]
#[must_use]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Rect<T = i32>(pub(crate) [T; 4]);
/// Constructs a [Rect] at position `(x, y)` with `width` and `height`.
///
/// ```
/// # use pix_engine::prelude::*;
/// let p = point!(10, 20);
/// let r = rect!(p, 100, 200);
/// assert_eq!(r.x(), 10);
/// assert_eq!(r.y(), 20);
/// assert_eq!(r.width(), 100);
/// assert_eq!(r.height(), 200);
///
/// let r = rect!(10, 20, 100, 200);
/// assert_eq!(r.x(), 10);
/// assert_eq!(r.y(), 20);
/// assert_eq!(r.width(), 100);
/// assert_eq!(r.height(), 200);
/// ```
#[macro_export]
macro_rules! rect {
($p1:expr, $p2:expr$(,)?) => {
$crate::prelude::Rect::with_points($p1, $p2)
};
($p:expr, $width:expr, $height:expr$(,)?) => {
$crate::prelude::Rect::with_position($p, $width, $height)
};
($x:expr, $y:expr, $width:expr, $height:expr$(,)?) => {
$crate::prelude::Rect::new($x, $y, $width, $height)
};
}
/// Constructs a square [Rect] at position `(x, y)` with the same `width` and `height`.
///
/// ```
/// # use pix_engine::prelude::*;
/// let p = point!(10, 20);
/// let s = square!(p, 100);
/// assert_eq!(s.x(), 10);
/// assert_eq!(s.y(), 20);
/// assert_eq!(s.width(), 100);
/// assert_eq!(s.height(), 100);
///
/// let s = square!(10, 20, 100);
/// assert_eq!(s.x(), 10);
/// assert_eq!(s.y(), 20);
/// assert_eq!(s.width(), 100);
/// assert_eq!(s.height(), 100);
/// ```
#[macro_export]
macro_rules! square {
($p:expr, $size:expr$(,)?) => {{
$crate::prelude::Rect::square_with_position($p, $size)
}};
($x:expr, $y:expr, $size:expr$(,)?) => {
$crate::prelude::Rect::square($x, $y, $size)
};
}
impl<T> Rect<T> {
/// Constructs a `Rect` at position `(x, y)` with `width` and `height`.
pub const fn new(x: T, y: T, width: T, height: T) -> Self {
Self([x, y, width, height])
}
/// Constructs a square `Rect` at position `(x, y)` with `size`.
pub fn square(x: T, y: T, size: T) -> Self
where
T: Copy,
{
Self::new(x, y, size, size)
}
}
impl<T: Copy> Rect<T> {
/// Returns `Rect` coordinates as `[x, y, width, height]`.
///
/// # Example
///
/// ```
/// # use pix_engine::prelude::*;
/// let r = rect!(5, 10, 100, 100);
/// assert_eq!(r.coords(), [5, 10, 100, 100]);
/// ```
#[inline]
pub fn coords(&self) -> [T; 4] {
self.0
}
/// Returns `Rect` coordinates as a mutable slice `&mut [x, y, width, height]`.
///
/// # Example
///
/// ```
/// # use pix_engine::prelude::*;
/// let mut r = rect!(5, 10, 100, 100);
/// for p in r.coords_mut() {
/// *p += 5;
/// }
/// assert_eq!(r.coords(), [10, 15, 105, 105]);
/// ```
#[inline]
pub fn coords_mut(&mut self) -> &mut [T; 4] {
&mut self.0
}
/// Returns the `x-coordinate` of the rectangle.
#[inline]
pub fn x(&self) -> T {
self.0[0]
}
/// Sets the `x-coordinate` of the rectangle.
#[inline]
pub fn set_x(&mut self, x: T) {
self.0[0] = x;
}
/// Returns the `y-coordinate` of the rectangle.
#[inline]
pub fn y(&self) -> T {
self.0[1]
}
/// Sets the `y-coordinate` of the rectangle.
#[inline]
pub fn set_y(&mut self, y: T) {
self.0[1] = y;
}
/// Returns the `width` of the rectangle.
#[inline]
pub fn width(&self) -> T {
self.0[2]
}
/// Sets the `width` of the rectangle.
#[inline]
pub fn set_width(&mut self, width: T) {
self.0[2] = width;
}
/// Returns the `height` of the rectangle.
#[inline]
pub fn height(&self) -> T {
self.0[3]
}
/// Sets the `height` of the rectangle.
#[inline]
pub fn set_height(&mut self, height: T) {
self.0[3] = height;
}
}
impl<T: Num> Rect<T> {
/// Constructs a `Rect` at position [Point] with `width` and `height`.
pub fn with_position<P: Into<Point<T>>>(p: P, width: T, height: T) -> Self {
let p = p.into();
Self::new(p.x(), p.y(), width, height)
}
/// Constructs a square `Rect` at position [Point] with `size`.
pub fn square_with_position<P: Into<Point<T>>>(p: P, size: T) -> Self {
Self::with_position(p, size, size)
}
/// Constructs a `Rect` by providing top-left and bottom-right [Point]s.
///
/// # Panics
///
/// Panics if `p2 <= p1`.
///
/// # Example
///
/// ```
/// # use pix_engine::prelude::*;
/// let r = Rect::with_points([50, 50], [150, 150]);
/// assert_eq!(r.coords(), [50, 50, 100, 100]);
/// ```
pub fn with_points<P: Into<Point<T>>>(p1: P, p2: P) -> Self {
let p1 = p1.into();
let p2 = p2.into();
assert!(p2 > p1, "bottom-right point must be greater than top-right",);
let width = p2.x() - p1.x();
let height = p2.y() - p1.y();
Self::new(p1.x(), p1.y(), width, height)
}
/// Constructs a `Rect` centered at position `(x, y)` with `width` and `height`.
///
/// # Example
///
/// ```
/// # use pix_engine::prelude::*;
/// let r = Rect::from_center([50, 50], 100, 100);
/// assert_eq!(r.coords(), [0, 0, 100, 100]);
/// ```
pub fn from_center<P: Into<Point<T>>>(p: P, width: T, height: T) -> Self {
let p = p.into();
let two = T::one() + T::one();
Self::new(p.x() - width / two, p.y() - height / two, width, height)
}
/// Constructs a square `Rect` centered at position `(x, y)` with `size`.
///
/// # Example
///
/// ```
/// # use pix_engine::prelude::*;
/// let s = Rect::square_from_center([50, 50], 100);
/// assert_eq!(s.coords(), [0, 0, 100, 100]);
/// ```
pub fn square_from_center<P: Into<Point<T>>>(p: P, size: T) -> Self {
let p = p.into();
let two = T::one() + T::one();
let offset = size / two;
Self::new(p.x() - offset, p.y() - offset, size, size)
}
/// Returns the `size` of the rectangle as a `Point`.
#[inline]
pub fn size(&self) -> Point<T> {
point!(self.width(), self.height())
}
/// Reposition the the rectangle.
#[inline]
pub fn reposition(&self, x: T, y: T) -> Self {
Self::new(x, y, self.width(), self.height())
}
/// Resize the the rectangle.
#[inline]
pub fn resize(&self, width: T, height: T) -> Self {
Self::new(self.x(), self.y(), width, height)
}
/// Offsets a rectangle by shifting coordinates by given amount.
#[inline]
pub fn offset<P>(&self, offsets: P) -> Self
where
P: Into<Point<T>>,
{
let offsets = offsets.into();
let mut rect = *self;
for i in 0..=1 {
rect[i] += offsets[i];
}
rect
}
/// Offsets a rectangle's size by shifting coordinates by given amount.
#[inline]
pub fn offset_size<P>(&self, offsets: P) -> Self
where
P: Into<Point<T>>,
{
let offsets = offsets.into();
let mut rect = *self;
for i in 2..=3 {
rect[i] += offsets[i - 2];
}
rect
}
/// Grows a rectangle by a given size.
#[inline]
pub fn grow<P>(&self, offsets: P) -> Self
where
P: Into<Point<T>>,
{
let offsets = offsets.into();
let mut rect = *self;
for i in 0..=1 {
rect[i] -= offsets[i];
}
for i in 2..=3 {
rect[i] += (T::one() + T::one()) * offsets[i - 2];
}
rect
}
/// Shrinks a rectangle by a given size.
#[inline]
pub fn shrink<P>(&self, offsets: P) -> Self
where
P: Into<Point<T>>,
{
let offsets = offsets.into();
let mut rect = *self;
for i in 0..=1 {
rect[i] += offsets[i];
}
for i in 2..=3 {
rect[i] -= (T::one() + T::one()) * offsets[i - 2];
}
rect
}
/// Returns `Rect` as a [Vec].
///
/// # Example
///
/// ```
/// # use pix_engine::prelude::*;
/// let r = rect!(5, 10, 100, 100);
/// assert_eq!(r.to_vec(), vec![5, 10, 100, 100]);
/// ```
#[inline]
pub fn to_vec(self) -> Vec<T> {
self.0.to_vec()
}
/// Returns the horizontal position of the left edge.
#[inline]
pub fn left(&self) -> T {
self.x()
}
/// Set the horizontal position of the left edge.
#[inline]
pub fn set_left(&mut self, left: T) {
self.set_x(left);
}
/// Returns the horizontal position of the right edge.
#[inline]
pub fn right(&self) -> T {
self.x() + self.width()
}
/// Set the horizontal position of the right edge.
#[inline]
pub fn set_right(&mut self, right: T) {
self.set_x(right - self.width());
}
/// Returns the horizontal position of the top edge.
#[inline]
pub fn top(&self) -> T {
self.y()
}
/// Set the vertical position of the top edge.
#[inline]
pub fn set_top(&mut self, top: T) {
self.set_y(top);
}
/// Returns the vertical position of the bottom edge.
#[inline]
pub fn bottom(&self) -> T {
self.y() + self.height()
}
/// Set the vertical position of the bottom edge.
#[inline]
pub fn set_bottom(&mut self, bottom: T) {
self.set_y(bottom - self.height());
}
/// Returns the center position as [Point].
#[inline]
pub fn center(&self) -> Point<T> {
let two = T::one() + T::one();
point!(
self.x() + self.width() / two,
self.y() + self.height() / two
)
}
/// Returns the top-left position as [Point].
#[inline]
pub fn top_left(&self) -> Point<T> {
point!(self.left(), self.top())
}
/// Returns the top-right position as [Point].
#[inline]
pub fn top_right(&self) -> Point<T> {
point!(self.right(), self.top())
}
/// Returns the bottom-left position as [Point].
#[inline]
pub fn bottom_left(&self) -> Point<T> {
point!(self.left(), self.bottom())
}
/// Returns the bottom-right position as [Point].
#[inline]
pub fn bottom_right(&self) -> Point<T> {
point!(self.right(), self.bottom())
}
/// Returns the four [Point]s that compose this `Rect` as `[top_left, top_right, bottom_right,
/// bottom_left]`.
#[inline]
pub fn points(&self) -> [Point<T>; 4] {
[
self.top_left(),
self.top_right(),
self.bottom_right(),
self.bottom_left(),
]
}
/// Set position centered on a [Point].
#[inline]
pub fn center_on<P: Into<Point<T>>>(&mut self, p: P) {
let p = p.into();
let two = T::one() + T::one();
self.set_x(p.x() - self.width() / two);
self.set_y(p.y() - self.height() / two);
}
/// Returns the bounding box for a given rectangle rotated about a `center` by a given
/// `angle`. Passing `None` for `center` rotates about the top-left point of the rectangle.
#[inline]
pub fn rotated(&self, angle: f64, center: Option<Point<T>>) -> Self
where
T: Ord + Bounded + AsPrimitive<f64> + NumCast,
{
if angle == 0.0 {
return *self;
}
let sin_cos = angle.sin_cos();
// Determine rotated bounding box
let [cx, cy]: [f64; 2] = center.unwrap_or_else(|| self.center()).as_().coords();
let (sin, cos) = sin_cos;
let transformed_points = self.points().map(|p| {
let [x, y]: [f64; 2] = p.as_().coords();
point![
NumCast::from(((x - cx).mul_add(cos, cx) - (y - cy) * sin).round())
.unwrap_or_else(T::zero),
NumCast::from(((y - cy).mul_add(cos, (x - cx).mul_add(sin, cy))).round())
.unwrap_or_else(T::zero),
]
});
let (min_x, min_y) = transformed_points
.iter()
.fold((T::max_value(), T::max_value()), |(min_x, min_y), point| {
(min_x.min(point.x()), min_y.min(point.y()))
});
let (max_x, max_y) = transformed_points
.iter()
.fold((T::min_value(), T::min_value()), |(max_x, max_y), point| {
(max_x.max(point.x()), max_y.max(point.y()))
});
Self::with_points([min_x, min_y], [max_x, max_y])
}
}
impl<T: Num> Contains<Point<T>> for Rect<T> {
/// Returns whether this rectangle contains a given [Point].
fn contains(&self, p: Point<T>) -> bool {
p.x() >= self.left() && p.x() < self.right() && p.y() >= self.top() && p.y() < self.bottom()
}
}
impl<T: Num> Contains<Rect<T>> for Rect<T> {
/// Returns whether this rectangle completely contains another rectangle.
fn contains(&self, rect: Rect<T>) -> bool {
rect.left() >= self.left()
&& rect.right() < self.right()
&& rect.top() >= self.top()
&& rect.bottom() < self.bottom()
}
}
impl<T: Float> Intersects<Line<T>> for Rect<T> {
type Result = (Point<T>, T);
/// Returns the closest intersection point with a given line and distance along the line or
/// `None` if there is no intersection.
fn intersects(&self, line: Line<T>) -> Option<Self::Result> {
let left = line.intersects(line_![self.top_left(), self.bottom_left()]);
let right = line.intersects(line_![self.top_right(), self.bottom_right()]);
let top = line.intersects(line_![self.top_left(), self.top_right()]);
let bottom = line.intersects(line_![self.bottom_left(), self.bottom_right()]);
[left, right, top, bottom]
.iter()
.filter_map(|&p| p)
.fold(None, |closest, intersection| {
let closest_t = closest.map_or_else(T::infinity, |c| c.1);
let t = intersection.1;
if t < closest_t {
Some(intersection)
} else {
closest
}
})
}
}
impl<T: Num> Intersects<Rect<T>> for Rect<T> {
// FIXME: Provide a better intersection result
type Result = ();
/// Returns whether this rectangle intersects with another rectangle.
fn intersects(&self, rect: Rect<T>) -> Option<Self::Result> {
let tl = self.top_left();
let br = self.bottom_right();
let otl = rect.top_left();
let obr = rect.bottom_right();
// Both rectangle corner x and y values overlap ranges
if tl.x() < obr.x() && br.x() > otl.x() && tl.y() < otl.y() && br.y() > obr.y() {
Some(())
} else {
None
}
}
}
impl Draw for Rect<i32> {
/// Draw `Rect` to the current [`PixState`] canvas.
fn draw(&self, s: &mut PixState) -> Result<()> {
s.rect(*self)
}
}
impl<T: Copy> From<[T; 3]> for Rect<T> {
/// Converts `[T; 3]` into `Rect<T>`.
#[inline]
fn from([x, y, s]: [T; 3]) -> Self {
Self([x, y, s, s])
}
}
impl<T: Copy> From<&[T; 3]> for Rect<T> {
/// Converts `&[T; 3]` into `Rect<T>`.
#[inline]
fn from(&[x, y, s]: &[T; 3]) -> Self {
Self([x, y, s, s])
}
}
impl Add<Point<i32>> for Rect {
type Output = Self;
fn add(self, p: Point<i32>) -> Self::Output {
self.offset(p)
}
}
impl Sub<Point<i32>> for Rect {
type Output = Self;
fn sub(self, p: Point<i32>) -> Self::Output {
self.offset(-p)
}
}