1use core::fmt;
8use core::ops::{BitOr, BitOrAssign};
9
10pub const MAX_COORD: i32 = 1 << 29;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
22pub struct Point {
23 pub x: i32,
25 pub y: i32,
27}
28
29impl Point {
30 #[must_use]
32 pub const fn new(x: i32, y: i32) -> Self {
33 Self { x, y }
34 }
35
36 #[must_use]
46 pub fn manhattan(self, other: Self) -> u64 {
47 abs_diff(self.x, other.x) + abs_diff(self.y, other.y)
48 }
49
50 #[must_use]
52 pub fn distance_squared(self, other: Self) -> u128 {
53 let dx = u128::from(abs_diff(self.x, other.x));
54 let dy = u128::from(abs_diff(self.y, other.y));
55
56 dx * dx + dy * dy
57 }
58
59 #[must_use]
61 pub fn coordinate(self, axis: Axis) -> i32 {
62 match axis {
63 Axis::X => self.x,
64 Axis::Y => self.y,
65 }
66 }
67
68 #[must_use]
70 pub fn is_in_range(self) -> bool {
71 self.x.unsigned_abs() <= MAX_COORD.unsigned_abs()
72 && self.y.unsigned_abs() <= MAX_COORD.unsigned_abs()
73 }
74}
75
76impl fmt::Display for Point {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 write!(f, "({}, {})", self.x, self.y)
79 }
80}
81
82#[must_use]
84pub(crate) fn abs_diff(a: i32, b: i32) -> u64 {
85 u64::from(a.abs_diff(b))
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
90pub enum Axis {
91 X,
93 Y,
95}
96
97impl Axis {
98 #[must_use]
100 pub const fn other(self) -> Self {
101 match self {
102 Self::X => Self::Y,
103 Self::Y => Self::X,
104 }
105 }
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
110pub enum Direction {
111 Right = 0,
113 Up = 1,
115 Left = 2,
117 Down = 3,
119}
120
121impl Direction {
122 pub const ALL: [Self; 4] = [Self::Right, Self::Up, Self::Left, Self::Down];
124
125 #[must_use]
127 pub const fn from_index(i: usize) -> Self {
128 Self::ALL[i % 4]
129 }
130
131 #[must_use]
133 pub const fn index(self) -> usize {
134 self as usize
135 }
136
137 #[must_use]
139 pub const fn reverse(self) -> Self {
140 Self::from_index(self.index() + 2)
141 }
142
143 #[must_use]
145 pub const fn left(self) -> Self {
146 Self::from_index(self.index() + 1)
147 }
148
149 #[must_use]
151 pub const fn right(self) -> Self {
152 Self::from_index(self.index() + 3)
153 }
154
155 #[must_use]
157 pub const fn axis(self) -> Axis {
158 match self {
159 Self::Right | Self::Left => Axis::X,
160 Self::Up | Self::Down => Axis::Y,
161 }
162 }
163
164 #[must_use]
166 pub const fn is_positive(self) -> bool {
167 matches!(self, Self::Right | Self::Up)
168 }
169
170 #[must_use]
172 pub const fn delta(self) -> (i32, i32) {
173 match self {
174 Self::Right => (1, 0),
175 Self::Up => (0, 1),
176 Self::Left => (-1, 0),
177 Self::Down => (0, -1),
178 }
179 }
180
181 #[must_use]
183 pub fn between(from: Point, to: Point) -> Option<Self> {
184 match (to.x.cmp(&from.x), to.y.cmp(&from.y)) {
185 (core::cmp::Ordering::Greater, core::cmp::Ordering::Equal) => Some(Self::Right),
186 (core::cmp::Ordering::Less, core::cmp::Ordering::Equal) => Some(Self::Left),
187 (core::cmp::Ordering::Equal, core::cmp::Ordering::Greater) => Some(Self::Up),
188 (core::cmp::Ordering::Equal, core::cmp::Ordering::Less) => Some(Self::Down),
189 _ => None,
190 }
191 }
192
193 #[must_use]
196 pub const fn turns_to(self, other: Self) -> u32 {
197 match (other.index() + 4 - self.index()) % 4 {
198 0 => 0,
199 2 => 2,
200 _ => 1,
201 }
202 }
203}
204
205#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
207pub struct DirSet(u8);
208
209impl DirSet {
210 pub const NONE: Self = Self(0);
212 pub const ALL: Self = Self(0b1111);
214 pub const RIGHT: Self = Self::only(Direction::Right);
216 pub const UP: Self = Self::only(Direction::Up);
218 pub const LEFT: Self = Self::only(Direction::Left);
220 pub const DOWN: Self = Self::only(Direction::Down);
222
223 #[must_use]
225 pub const fn only(dir: Direction) -> Self {
226 Self(1 << dir.index())
227 }
228
229 #[must_use]
231 pub const fn contains(self, dir: Direction) -> bool {
232 self.0 & (1 << dir.index()) != 0
233 }
234
235 #[must_use]
237 pub const fn is_empty(self) -> bool {
238 self.0 == 0
239 }
240
241 #[must_use]
243 pub fn reversed(self) -> Self {
244 self.iter().fold(Self::NONE, |set, dir| set | dir.reverse())
245 }
246
247 pub fn iter(self) -> impl Iterator<Item = Direction> {
249 Direction::ALL
250 .into_iter()
251 .filter(move |&d| self.contains(d))
252 }
253}
254
255impl BitOr for DirSet {
256 type Output = Self;
257
258 fn bitor(self, rhs: Self) -> Self {
259 Self(self.0 | rhs.0)
260 }
261}
262
263impl BitOr<Direction> for DirSet {
264 type Output = Self;
265
266 fn bitor(self, rhs: Direction) -> Self {
267 self | Self::only(rhs)
268 }
269}
270
271impl BitOrAssign for DirSet {
272 fn bitor_assign(&mut self, rhs: Self) {
273 self.0 |= rhs.0;
274 }
275}
276
277impl From<Direction> for DirSet {
278 fn from(dir: Direction) -> Self {
279 Self::only(dir)
280 }
281}
282
283impl fmt::Debug for DirSet {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285 f.debug_set().entries(self.iter()).finish()
286 }
287}
288
289#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
291pub enum Side {
292 Right,
294 Top,
296 Left,
298 Bottom,
300}
301
302impl Side {
303 pub const ALL: [Self; 4] = [Self::Right, Self::Top, Self::Left, Self::Bottom];
305
306 #[must_use]
308 pub const fn outward(self) -> Direction {
309 match self {
310 Self::Right => Direction::Right,
311 Self::Top => Direction::Up,
312 Self::Left => Direction::Left,
313 Self::Bottom => Direction::Down,
314 }
315 }
316}
317
318#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
322pub struct Rect {
323 pub min: Point,
325 pub max: Point,
327}
328
329impl Rect {
330 #[must_use]
347 pub fn new(x0: i32, y0: i32, x1: i32, y1: i32) -> Self {
348 Self::try_new(x0, y0, x1, y1).expect("a rectangle needs positive width and height")
349 }
350
351 #[must_use]
353 pub fn try_new(x0: i32, y0: i32, x1: i32, y1: i32) -> Option<Self> {
354 let min = Point::new(x0.min(x1), y0.min(y1));
355 let max = Point::new(x0.max(x1), y0.max(y1));
356
357 (min.x < max.x && min.y < max.y).then_some(Self { min, max })
358 }
359
360 #[must_use]
362 pub fn width(&self) -> u64 {
363 abs_diff(self.max.x, self.min.x)
364 }
365
366 #[must_use]
368 pub fn height(&self) -> u64 {
369 abs_diff(self.max.y, self.min.y)
370 }
371
372 #[must_use]
374 pub(crate) fn range(&self, axis: Axis) -> (i32, i32) {
375 (self.min.coordinate(axis), self.max.coordinate(axis))
376 }
377
378 #[must_use]
380 pub fn corners(&self) -> [Point; 4] {
381 [
382 self.min,
383 Point::new(self.max.x, self.min.y),
384 self.max,
385 Point::new(self.min.x, self.max.y),
386 ]
387 }
388
389 #[must_use]
391 pub fn center(&self) -> Point {
392 Point::new(
393 midpoint(self.min.x, self.max.x),
394 midpoint(self.min.y, self.max.y),
395 )
396 }
397
398 #[must_use]
400 pub fn interior_contains(&self, p: Point) -> bool {
401 self.min.x < p.x && p.x < self.max.x && self.min.y < p.y && p.y < self.max.y
402 }
403
404 #[must_use]
406 pub fn contains(&self, p: Point) -> bool {
407 self.min.x <= p.x && p.x <= self.max.x && self.min.y <= p.y && p.y <= self.max.y
408 }
409
410 #[must_use]
412 pub fn boundary_contains(&self, p: Point) -> bool {
413 self.contains(p) && !self.interior_contains(p)
414 }
415
416 #[must_use]
422 pub fn buffer(&self, amount: i32) -> Self {
423 Self::new(
424 self.min.x - amount,
425 self.min.y - amount,
426 self.max.x + amount,
427 self.max.y + amount,
428 )
429 }
430
431 #[must_use]
433 pub fn union(&self, other: &Self) -> Self {
434 Self {
435 min: Point::new(self.min.x.min(other.min.x), self.min.y.min(other.min.y)),
436 max: Point::new(self.max.x.max(other.max.x), self.max.y.max(other.max.y)),
437 }
438 }
439
440 #[must_use]
442 pub fn interiors_overlap(&self, other: &Self) -> bool {
443 self.min.x < other.max.x
444 && other.min.x < self.max.x
445 && self.min.y < other.max.y
446 && other.min.y < self.max.y
447 }
448
449 #[must_use]
453 pub fn blocks_segment(&self, a: Point, b: Point) -> bool {
454 let (lo, hi) = (
455 Point::new(a.x.min(b.x), a.y.min(b.y)),
456 Point::new(a.x.max(b.x), a.y.max(b.y)),
457 );
458 if lo.y == hi.y {
459 return self.min.y < lo.y
460 && lo.y < self.max.y
461 && lo.x < self.max.x
462 && self.min.x < hi.x;
463 }
464
465 self.min.x < lo.x && lo.x < self.max.x && lo.y < self.max.y && self.min.y < hi.y
466 }
467
468 #[must_use]
470 pub fn side_of(&self, p: Point) -> Option<Side> {
471 let on_x = p.x == self.min.x || p.x == self.max.x;
472 let on_y = p.y == self.min.y || p.y == self.max.y;
473 if !self.contains(p) || on_x == on_y {
474 return None;
475 }
476
477 Some(
478 match (p.x == self.max.x, p.x == self.min.x, p.y == self.max.y) {
479 (true, _, _) => Side::Right,
480 (_, true, _) => Side::Left,
481 (_, _, true) => Side::Top,
482 _ => Side::Bottom,
483 },
484 )
485 }
486}
487
488#[must_use]
490pub(crate) fn midpoint(a: i32, b: i32) -> i32 {
491 i32::try_from((i64::from(a) + i64::from(b)).div_euclid(2)).expect("between two i32")
492}
493
494#[cfg(test)]
495mod tests {
496 use super::*;
499
500 #[test]
502 fn turns_compose() {
503 for d in Direction::ALL {
504 assert_eq!(d.left().right(), d);
505 assert_eq!(d.left().left(), d.reverse());
506 assert_eq!(d.turns_to(d), 0);
507 assert_eq!(d.turns_to(d.left()), 1);
508 assert_eq!(d.turns_to(d.right()), 1);
509 assert_eq!(d.turns_to(d.reverse()), 2);
510 }
511
512 assert_eq!(Direction::Right.left(), Direction::Up);
513 }
514
515 #[test]
517 fn segment_blocking_uses_open_interior() {
518 let r = Rect::new(0, 0, 10, 10);
519 assert!(!r.blocks_segment(Point::new(-5, 0), Point::new(15, 0)));
520 assert!(!r.blocks_segment(Point::new(10, -5), Point::new(10, 15)));
521 assert!(r.blocks_segment(Point::new(-5, 5), Point::new(1, 5)));
522 assert!(!r.blocks_segment(Point::new(-5, 5), Point::new(0, 5)));
523 assert!(r.blocks_segment(Point::new(5, 20), Point::new(5, 9)));
524 }
525
526 #[test]
528 fn dirset_reverse() {
529 let set = DirSet::UP | Direction::Left;
530 assert_eq!(set.reversed(), DirSet::DOWN | Direction::Right);
531 assert_eq!(DirSet::ALL.iter().count(), 4);
532 }
533
534 #[test]
536 fn side_of_points() {
537 let r = Rect::new(0, 0, 10, 4);
538 assert_eq!(r.side_of(Point::new(10, 2)), Some(Side::Right));
539 assert_eq!(r.side_of(Point::new(3, 4)), Some(Side::Top));
540 assert_eq!(r.side_of(Point::new(0, 0)), None);
541 assert_eq!(r.side_of(Point::new(5, 2)), None);
542 }
543}