1use std::fmt;
2
3use crate::{Div, Mul, NumExt as _, Pos2, Rangef, Rot2, Vec2, lerp, pos2, vec2};
4use std::ops::{BitOr, BitOrAssign};
5
6#[repr(C)]
22#[derive(Clone, Copy, Eq, PartialEq)]
23#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
24#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
25pub struct Rect {
26 pub min: Pos2,
28
29 pub max: Pos2,
31}
32
33impl Rect {
34 pub const EVERYTHING: Self = Self {
36 min: pos2(-f32::INFINITY, -f32::INFINITY),
37 max: pos2(f32::INFINITY, f32::INFINITY),
38 };
39
40 pub const NOTHING: Self = Self {
56 min: pos2(f32::INFINITY, f32::INFINITY),
57 max: pos2(-f32::INFINITY, -f32::INFINITY),
58 };
59
60 pub const NAN: Self = Self {
62 min: pos2(f32::NAN, f32::NAN),
63 max: pos2(f32::NAN, f32::NAN),
64 };
65
66 pub const ZERO: Self = Self {
68 min: Pos2::ZERO,
69 max: Pos2::ZERO,
70 };
71
72 #[inline(always)]
73 pub const fn from_min_max(min: Pos2, max: Pos2) -> Self {
74 Self { min, max }
75 }
76
77 #[inline(always)]
79 pub fn from_min_size(min: Pos2, size: Vec2) -> Self {
80 Self {
81 min,
82 max: min + size,
83 }
84 }
85
86 #[inline(always)]
87 pub fn from_center_size(center: Pos2, size: Vec2) -> Self {
88 Self {
89 min: center - size * 0.5,
90 max: center + size * 0.5,
91 }
92 }
93
94 #[inline(always)]
95 pub fn from_x_y_ranges(x_range: impl Into<Rangef>, y_range: impl Into<Rangef>) -> Self {
96 let x_range = x_range.into();
97 let y_range = y_range.into();
98 Self {
99 min: pos2(x_range.min, y_range.min),
100 max: pos2(x_range.max, y_range.max),
101 }
102 }
103
104 #[inline]
106 pub fn from_two_pos(a: Pos2, b: Pos2) -> Self {
107 Self {
108 min: pos2(a.x.min(b.x), a.y.min(b.y)),
109 max: pos2(a.x.max(b.x), a.y.max(b.y)),
110 }
111 }
112
113 #[inline]
115 pub fn from_pos(point: Pos2) -> Self {
116 Self {
117 min: point,
118 max: point,
119 }
120 }
121
122 pub fn from_points(points: &[Pos2]) -> Self {
124 let mut rect = Self::NOTHING;
125 for &p in points {
126 rect.extend_with(p);
127 }
128 rect
129 }
130
131 #[inline]
133 pub fn everything_right_of(left_x: f32) -> Self {
134 let mut rect = Self::EVERYTHING;
135 rect.set_left(left_x);
136 rect
137 }
138
139 #[inline]
141 pub fn everything_left_of(right_x: f32) -> Self {
142 let mut rect = Self::EVERYTHING;
143 rect.set_right(right_x);
144 rect
145 }
146
147 #[inline]
149 pub fn everything_below(top_y: f32) -> Self {
150 let mut rect = Self::EVERYTHING;
151 rect.set_top(top_y);
152 rect
153 }
154
155 #[inline]
157 pub fn everything_above(bottom_y: f32) -> Self {
158 let mut rect = Self::EVERYTHING;
159 rect.set_bottom(bottom_y);
160 rect
161 }
162
163 #[must_use]
164 #[inline]
165 pub fn with_min_x(mut self, min_x: f32) -> Self {
166 self.min.x = min_x;
167 self
168 }
169
170 #[must_use]
171 #[inline]
172 pub fn with_min_y(mut self, min_y: f32) -> Self {
173 self.min.y = min_y;
174 self
175 }
176
177 #[must_use]
178 #[inline]
179 pub fn with_max_x(mut self, max_x: f32) -> Self {
180 self.max.x = max_x;
181 self
182 }
183
184 #[must_use]
185 #[inline]
186 pub fn with_max_y(mut self, max_y: f32) -> Self {
187 self.max.y = max_y;
188 self
189 }
190
191 #[must_use]
193 pub fn expand(self, amnt: f32) -> Self {
194 self.expand2(Vec2::splat(amnt))
195 }
196
197 #[must_use]
199 pub fn expand2(self, amnt: Vec2) -> Self {
200 Self::from_min_max(self.min - amnt, self.max + amnt)
201 }
202
203 #[must_use]
205 pub fn scale_from_center(self, scale_factor: f32) -> Self {
206 self.scale_from_center2(Vec2::splat(scale_factor))
207 }
208
209 #[must_use]
211 pub fn scale_from_center2(self, scale_factor: Vec2) -> Self {
212 Self::from_center_size(self.center(), self.size() * scale_factor)
213 }
214
215 #[must_use]
217 pub fn shrink(self, amnt: f32) -> Self {
218 self.shrink2(Vec2::splat(amnt))
219 }
220
221 #[must_use]
223 pub fn shrink2(self, amnt: Vec2) -> Self {
224 Self::from_min_max(self.min + amnt, self.max - amnt)
225 }
226
227 #[must_use]
228 #[inline]
229 pub fn translate(self, amnt: Vec2) -> Self {
230 Self::from_min_size(self.min + amnt, self.size())
231 }
232
233 #[must_use]
235 #[inline]
236 pub fn rotate_bb(self, rot: Rot2) -> Self {
237 let a = rot * self.left_top().to_vec2();
238 let b = rot * self.right_top().to_vec2();
239 let c = rot * self.left_bottom().to_vec2();
240 let d = rot * self.right_bottom().to_vec2();
241
242 Self::from_min_max(
243 a.min(b).min(c).min(d).to_pos2(),
244 a.max(b).max(c).max(d).to_pos2(),
245 )
246 }
247
248 #[must_use]
249 #[inline]
250 pub fn intersects(self, other: Self) -> bool {
251 self.min.x <= other.max.x
252 && other.min.x <= self.max.x
253 && self.min.y <= other.max.y
254 && other.min.y <= self.max.y
255 }
256
257 pub fn set_width(&mut self, w: f32) {
259 self.max.x = self.min.x + w;
260 }
261
262 pub fn set_height(&mut self, h: f32) {
264 self.max.y = self.min.y + h;
265 }
266
267 pub fn set_center(&mut self, center: Pos2) {
269 *self = self.translate(center - self.center());
270 }
271
272 #[must_use]
273 #[inline(always)]
274 pub fn contains(&self, p: Pos2) -> bool {
275 self.min.x <= p.x && p.x <= self.max.x && self.min.y <= p.y && p.y <= self.max.y
276 }
277
278 #[must_use]
279 pub fn contains_rect(&self, other: Self) -> bool {
280 self.contains(other.min) && self.contains(other.max)
281 }
282
283 #[must_use]
286 pub fn clamp(&self, p: Pos2) -> Pos2 {
287 p.clamp(self.min, self.max)
288 }
289
290 #[inline(always)]
291 pub fn extend_with(&mut self, p: Pos2) {
292 self.min = self.min.min(p);
293 self.max = self.max.max(p);
294 }
295
296 #[inline(always)]
297 pub fn extend_with_x(&mut self, x: f32) {
299 self.min.x = self.min.x.min(x);
300 self.max.x = self.max.x.max(x);
301 }
302
303 #[inline(always)]
304 pub fn extend_with_y(&mut self, y: f32) {
306 self.min.y = self.min.y.min(y);
307 self.max.y = self.max.y.max(y);
308 }
309
310 #[inline(always)]
313 #[must_use]
314 pub fn union(self, other: Self) -> Self {
315 Self {
316 min: self.min.min(other.min),
317 max: self.max.max(other.max),
318 }
319 }
320
321 #[inline]
323 #[must_use]
324 pub fn intersect(self, other: Self) -> Self {
325 Self {
326 min: self.min.max(other.min),
327 max: self.max.min(other.max),
328 }
329 }
330
331 #[inline(always)]
332 pub fn center(&self) -> Pos2 {
333 Pos2 {
334 x: (self.min.x + self.max.x) / 2.0,
335 y: (self.min.y + self.max.y) / 2.0,
336 }
337 }
338
339 #[inline(always)]
341 pub fn size(&self) -> Vec2 {
342 self.max - self.min
343 }
344
345 #[inline(always)]
347 pub fn width(&self) -> f32 {
348 self.max.x - self.min.x
349 }
350
351 #[inline(always)]
353 pub fn height(&self) -> f32 {
354 self.max.y - self.min.y
355 }
356
357 pub fn aspect_ratio(&self) -> f32 {
363 self.width() / self.height()
364 }
365
366 pub fn square_proportions(&self) -> Vec2 {
370 let w = self.width();
371 let h = self.height();
372 if w > h {
373 vec2(w / h, 1.0)
374 } else {
375 vec2(1.0, h / w)
376 }
377 }
378
379 #[inline(always)]
381 pub fn area(&self) -> f32 {
382 self.width().at_least(0.0) * self.height().at_least(0.0)
383 }
384
385 #[inline]
391 pub fn distance_to_pos(&self, pos: Pos2) -> f32 {
392 self.distance_sq_to_pos(pos).sqrt()
393 }
394
395 #[inline]
401 pub fn distance_sq_to_pos(&self, pos: Pos2) -> f32 {
402 if self.is_negative() {
403 return f32::INFINITY;
404 }
405
406 let dx = if self.min.x > pos.x {
407 self.min.x - pos.x
408 } else if pos.x > self.max.x {
409 pos.x - self.max.x
410 } else {
411 0.0
412 };
413
414 let dy = if self.min.y > pos.y {
415 self.min.y - pos.y
416 } else if pos.y > self.max.y {
417 pos.y - self.max.y
418 } else {
419 0.0
420 };
421
422 dx * dx + dy * dy
423 }
424
425 pub fn signed_distance_to_pos(&self, pos: Pos2) -> f32 {
439 if self.is_negative() {
440 return f32::INFINITY;
441 }
442
443 let edge_distances = (pos - self.center()).abs() - self.size() * 0.5;
444 let inside_dist = edge_distances.max_elem().min(0.0);
445 let outside_dist = edge_distances.max(Vec2::ZERO).length();
446 inside_dist + outside_dist
447 }
448
449 #[inline]
452 pub fn lerp_inside(&self, t: Vec2) -> Pos2 {
453 Pos2 {
454 x: lerp(self.min.x..=self.max.x, t.x),
455 y: lerp(self.min.y..=self.max.y, t.y),
456 }
457 }
458
459 #[inline]
461 pub fn lerp_towards(&self, other: &Self, t: f32) -> Self {
462 Self {
463 min: self.min.lerp(other.min, t),
464 max: self.max.lerp(other.max, t),
465 }
466 }
467
468 #[inline(always)]
469 pub fn x_range(&self) -> Rangef {
470 Rangef::new(self.min.x, self.max.x)
471 }
472
473 #[inline(always)]
474 pub fn y_range(&self) -> Rangef {
475 Rangef::new(self.min.y, self.max.y)
476 }
477
478 #[inline(always)]
479 pub fn bottom_up_range(&self) -> Rangef {
480 Rangef::new(self.max.y, self.min.y)
481 }
482
483 #[inline(always)]
485 pub fn is_negative(&self) -> bool {
486 self.max.x < self.min.x || self.max.y < self.min.y
487 }
488
489 #[inline(always)]
491 pub fn is_positive(&self) -> bool {
492 self.min.x < self.max.x && self.min.y < self.max.y
493 }
494
495 #[inline(always)]
497 pub fn is_finite(&self) -> bool {
498 self.min.is_finite() && self.max.is_finite()
499 }
500
501 #[inline(always)]
503 pub fn any_nan(self) -> bool {
504 self.min.any_nan() || self.max.any_nan()
505 }
506}
507
508impl Rect {
510 #[inline(always)]
512 pub fn left(&self) -> f32 {
513 self.min.x
514 }
515
516 #[inline(always)]
518 pub fn left_mut(&mut self) -> &mut f32 {
519 &mut self.min.x
520 }
521
522 #[inline(always)]
524 pub fn set_left(&mut self, x: f32) {
525 self.min.x = x;
526 }
527
528 #[inline(always)]
530 pub fn right(&self) -> f32 {
531 self.max.x
532 }
533
534 #[inline(always)]
536 pub fn right_mut(&mut self) -> &mut f32 {
537 &mut self.max.x
538 }
539
540 #[inline(always)]
542 pub fn set_right(&mut self, x: f32) {
543 self.max.x = x;
544 }
545
546 #[inline(always)]
548 pub fn top(&self) -> f32 {
549 self.min.y
550 }
551
552 #[inline(always)]
554 pub fn top_mut(&mut self) -> &mut f32 {
555 &mut self.min.y
556 }
557
558 #[inline(always)]
560 pub fn set_top(&mut self, y: f32) {
561 self.min.y = y;
562 }
563
564 #[inline(always)]
566 pub fn bottom(&self) -> f32 {
567 self.max.y
568 }
569
570 #[inline(always)]
572 pub fn bottom_mut(&mut self) -> &mut f32 {
573 &mut self.max.y
574 }
575
576 #[inline(always)]
578 pub fn set_bottom(&mut self, y: f32) {
579 self.max.y = y;
580 }
581
582 #[inline(always)]
583 #[doc(alias = "top_left")]
584 pub fn left_top(&self) -> Pos2 {
585 pos2(self.left(), self.top())
586 }
587
588 #[inline(always)]
589 pub fn center_top(&self) -> Pos2 {
590 pos2(self.center().x, self.top())
591 }
592
593 #[inline(always)]
594 #[doc(alias = "top_right")]
595 pub fn right_top(&self) -> Pos2 {
596 pos2(self.right(), self.top())
597 }
598
599 #[inline(always)]
600 pub fn left_center(&self) -> Pos2 {
601 pos2(self.left(), self.center().y)
602 }
603
604 #[inline(always)]
605 pub fn right_center(&self) -> Pos2 {
606 pos2(self.right(), self.center().y)
607 }
608
609 #[inline(always)]
610 #[doc(alias = "bottom_left")]
611 pub fn left_bottom(&self) -> Pos2 {
612 pos2(self.left(), self.bottom())
613 }
614
615 #[inline(always)]
616 pub fn center_bottom(&self) -> Pos2 {
617 pos2(self.center().x, self.bottom())
618 }
619
620 #[inline(always)]
621 #[doc(alias = "bottom_right")]
622 pub fn right_bottom(&self) -> Pos2 {
623 pos2(self.right(), self.bottom())
624 }
625
626 pub fn split_left_right_at_fraction(&self, t: f32) -> (Self, Self) {
628 self.split_left_right_at_x(lerp(self.min.x..=self.max.x, t))
629 }
630
631 pub fn split_left_right_at_x(&self, split_x: f32) -> (Self, Self) {
633 let left = Self::from_min_max(self.min, Pos2::new(split_x, self.max.y));
634 let right = Self::from_min_max(Pos2::new(split_x, self.min.y), self.max);
635 (left, right)
636 }
637
638 pub fn split_top_bottom_at_fraction(&self, t: f32) -> (Self, Self) {
640 self.split_top_bottom_at_y(lerp(self.min.y..=self.max.y, t))
641 }
642
643 pub fn split_top_bottom_at_y(&self, split_y: f32) -> (Self, Self) {
645 let top = Self::from_min_max(self.min, Pos2::new(self.max.x, split_y));
646 let bottom = Self::from_min_max(Pos2::new(self.min.x, split_y), self.max);
647 (top, bottom)
648 }
649}
650
651impl Rect {
652 pub fn intersects_ray(&self, o: Pos2, d: Vec2) -> bool {
656 debug_assert!(
657 d.is_normalized(),
658 "Debug assert: expected normalized direction, but `d` has length {}",
659 d.length()
660 );
661
662 let mut tmin = -f32::INFINITY;
663 let mut tmax = f32::INFINITY;
664
665 if d.x != 0.0 {
666 let tx1 = (self.min.x - o.x) / d.x;
667 let tx2 = (self.max.x - o.x) / d.x;
668
669 tmin = tmin.max(tx1.min(tx2));
670 tmax = tmax.min(tx1.max(tx2));
671 }
672
673 if d.y != 0.0 {
674 let ty1 = (self.min.y - o.y) / d.y;
675 let ty2 = (self.max.y - o.y) / d.y;
676
677 tmin = tmin.max(ty1.min(ty2));
678 tmax = tmax.min(ty1.max(ty2));
679 }
680
681 0.0 <= tmax && tmin <= tmax
682 }
683
684 pub fn intersects_ray_from_center(&self, d: Vec2) -> Pos2 {
688 debug_assert!(
689 d.is_normalized(),
690 "expected normalized direction, but `d` has length {}",
691 d.length()
692 );
693
694 let mut tmin = f32::NEG_INFINITY;
695 let mut tmax = f32::INFINITY;
696
697 for i in 0..2 {
698 let inv_d = 1.0 / -d[i];
699 let mut t0 = (self.min[i] - self.center()[i]) * inv_d;
700 let mut t1 = (self.max[i] - self.center()[i]) * inv_d;
701
702 if inv_d < 0.0 {
703 std::mem::swap(&mut t0, &mut t1);
704 }
705
706 tmin = tmin.max(t0);
707 tmax = tmax.min(t1);
708 }
709
710 let t = tmax.min(tmin);
711 self.center() + t * -d
712 }
713}
714
715impl fmt::Debug for Rect {
716 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
717 if let Some(precision) = f.precision() {
718 write!(f, "[{1:.0$?} - {2:.0$?}]", precision, self.min, self.max)
719 } else {
720 write!(f, "[{:?} - {:?}]", self.min, self.max)
721 }
722 }
723}
724
725impl fmt::Display for Rect {
726 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
727 f.write_str("[")?;
728 self.min.fmt(f)?;
729 f.write_str(" - ")?;
730 self.max.fmt(f)?;
731 f.write_str("]")?;
732 Ok(())
733 }
734}
735
736impl From<[Pos2; 2]> for Rect {
738 #[inline]
739 fn from([min, max]: [Pos2; 2]) -> Self {
740 Self { min, max }
741 }
742}
743
744impl Mul<f32> for Rect {
745 type Output = Self;
746
747 #[inline]
748 fn mul(self, factor: f32) -> Self {
749 Self {
750 min: self.min * factor,
751 max: self.max * factor,
752 }
753 }
754}
755
756impl Mul<Rect> for f32 {
757 type Output = Rect;
758
759 #[inline]
760 fn mul(self, vec: Rect) -> Rect {
761 Rect {
762 min: self * vec.min,
763 max: self * vec.max,
764 }
765 }
766}
767
768impl Div<f32> for Rect {
769 type Output = Self;
770
771 #[inline]
772 fn div(self, factor: f32) -> Self {
773 Self {
774 min: self.min / factor,
775 max: self.max / factor,
776 }
777 }
778}
779
780impl BitOr for Rect {
781 type Output = Self;
782
783 #[inline]
784 fn bitor(self, other: Self) -> Self {
785 self.union(other)
786 }
787}
788
789impl BitOrAssign for Rect {
790 #[inline]
791 fn bitor_assign(&mut self, other: Self) {
792 *self = self.union(other);
793 }
794}
795
796#[cfg(test)]
797mod tests {
798 use super::*;
799
800 #[test]
801 fn test_rect() {
802 let r = Rect::from_min_max(pos2(10.0, 10.0), pos2(20.0, 20.0));
803 assert_eq!(r.distance_sq_to_pos(pos2(15.0, 15.0)), 0.0);
804 assert_eq!(r.distance_sq_to_pos(pos2(10.0, 15.0)), 0.0);
805 assert_eq!(r.distance_sq_to_pos(pos2(10.0, 10.0)), 0.0);
806
807 assert_eq!(r.distance_sq_to_pos(pos2(5.0, 15.0)), 25.0); assert_eq!(r.distance_sq_to_pos(pos2(25.0, 15.0)), 25.0); assert_eq!(r.distance_sq_to_pos(pos2(15.0, 5.0)), 25.0); assert_eq!(r.distance_sq_to_pos(pos2(15.0, 25.0)), 25.0); assert_eq!(r.distance_sq_to_pos(pos2(25.0, 5.0)), 50.0); }
813
814 #[test]
815 fn scale_rect() {
816 let c = pos2(100.0, 50.0);
817 let r = Rect::from_center_size(c, vec2(30.0, 60.0));
818
819 assert_eq!(
820 r.scale_from_center(2.0),
821 Rect::from_center_size(c, vec2(60.0, 120.0))
822 );
823 assert_eq!(
824 r.scale_from_center(0.5),
825 Rect::from_center_size(c, vec2(15.0, 30.0))
826 );
827 assert_eq!(
828 r.scale_from_center2(vec2(2.0, 3.0)),
829 Rect::from_center_size(c, vec2(60.0, 180.0))
830 );
831 }
832
833 #[test]
834 fn test_ray_intersection() {
835 let rect = Rect::from_min_max(pos2(1.0, 1.0), pos2(3.0, 3.0));
836
837 println!("Righward ray from left:");
838 assert!(rect.intersects_ray(pos2(0.0, 2.0), Vec2::RIGHT));
839
840 println!("Righward ray from center:");
841 assert!(rect.intersects_ray(pos2(2.0, 2.0), Vec2::RIGHT));
842
843 println!("Righward ray from right:");
844 assert!(!rect.intersects_ray(pos2(4.0, 2.0), Vec2::RIGHT));
845
846 println!("Leftward ray from left:");
847 assert!(!rect.intersects_ray(pos2(0.0, 2.0), Vec2::LEFT));
848
849 println!("Leftward ray from center:");
850 assert!(rect.intersects_ray(pos2(2.0, 2.0), Vec2::LEFT));
851
852 println!("Leftward ray from right:");
853 assert!(rect.intersects_ray(pos2(4.0, 2.0), Vec2::LEFT));
854 }
855
856 #[test]
857 fn test_ray_from_center_intersection() {
858 let rect = Rect::from_min_max(pos2(1.0, 1.0), pos2(3.0, 3.0));
859
860 assert_eq!(
861 rect.intersects_ray_from_center(Vec2::RIGHT),
862 pos2(3.0, 2.0),
863 "rightward ray"
864 );
865
866 assert_eq!(
867 rect.intersects_ray_from_center(Vec2::UP),
868 pos2(2.0, 1.0),
869 "upward ray"
870 );
871
872 assert_eq!(
873 rect.intersects_ray_from_center(Vec2::LEFT),
874 pos2(1.0, 2.0),
875 "leftward ray"
876 );
877
878 assert_eq!(
879 rect.intersects_ray_from_center(Vec2::DOWN),
880 pos2(2.0, 3.0),
881 "downward ray"
882 );
883
884 assert_eq!(
885 rect.intersects_ray_from_center((Vec2::LEFT + Vec2::DOWN).normalized()),
886 pos2(1.0, 3.0),
887 "bottom-left corner ray"
888 );
889
890 assert_eq!(
891 rect.intersects_ray_from_center((Vec2::LEFT + Vec2::UP).normalized()),
892 pos2(1.0, 1.0),
893 "top-left corner ray"
894 );
895
896 assert_eq!(
897 rect.intersects_ray_from_center((Vec2::RIGHT + Vec2::DOWN).normalized()),
898 pos2(3.0, 3.0),
899 "bottom-right corner ray"
900 );
901
902 assert_eq!(
903 rect.intersects_ray_from_center((Vec2::RIGHT + Vec2::UP).normalized()),
904 pos2(3.0, 1.0),
905 "top-right corner ray"
906 );
907 }
908}