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
use crate::general_math::rotate_points;
use crate::new_hash_set;
use crate::prelude::*;
use crate::shape_box::ShapeBox;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::ops::Div;

/// Rectangle
///
/// Must have flat edges, to rotate first convert to [Polygon] using [Rect::as_polygon()]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Rect {
    top_left: Coord,
    bottom_right: Coord,
}

impl IntersectsContains for Rect {}

impl Rect {
    #[must_use]
    pub fn new<P1: Into<Coord>, P2: Into<Coord>>(top_left: P1, bottom_right: P2) -> Self {
        Self {
            top_left: top_left.into(),
            bottom_right: bottom_right.into(),
        }
    }

    #[must_use]
    pub fn new_with_size<P: Into<Coord>>(start: P, width: usize, height: usize) -> Self {
        let top_left = start.into();
        let bottom_right = Coord {
            x: top_left.x + width as isize,
            y: top_left.y + height as isize,
        };
        Self {
            top_left,
            bottom_right,
        }
    }
}

impl Rect {
    #[must_use]
    pub fn width(&self) -> usize {
        (self.bottom_right.x - self.top_left.x).unsigned_abs()
    }

    #[must_use]
    pub fn height(&self) -> usize {
        (self.bottom_right.y - self.top_left.y).unsigned_abs()
    }

    #[inline]
    #[must_use]
    pub fn top_left(&self) -> Coord {
        self.top_left
    }

    #[inline]
    #[must_use]
    pub fn bottom_right(&self) -> Coord {
        self.bottom_right
    }

    #[inline]
    #[must_use]
    pub fn is_square(&self) -> bool {
        let diff = self.bottom_right - self.top_left;
        diff.x == diff.y
    }
}

impl Shape for Rect {
    fn from_points(points: &[Coord]) -> Self
    where
        Self: Sized,
    {
        Rect::new(points[0], points[1])
    }

    fn rebuild(&self, points: &[Coord]) -> Self
    where
        Self: Sized,
    {
        Rect::from_points(points)
    }

    fn contains(&self, point: Coord) -> bool {
        (self.left()..=self.right()).contains(&point.x)
            && (self.top()..=self.bottom()).contains(&point.y)
    }

    fn points(&self) -> Vec<Coord> {
        vec![self.top_left, self.bottom_right]
    }

    fn rotate_around(&self, degrees: isize, point: Coord) -> Self
    where
        Self: Sized,
    {
        let degrees = (degrees as f32 / 90.0).round() as isize;
        let points = rotate_points(point, &self.points(), degrees * 90);
        Self::from_points(&points)
    }

    fn center(&self) -> Coord {
        self.top_left.mid_point(self.bottom_right)
    }

    fn left(&self) -> isize {
        self.top_left.x.min(self.bottom_right.x)
    }

    fn right(&self) -> isize {
        self.top_left.x.max(self.bottom_right.x)
    }

    fn top(&self) -> isize {
        self.top_left.y.min(self.bottom_right.y)
    }

    fn bottom(&self) -> isize {
        self.top_left.y.max(self.bottom_right.y)
    }

    fn outline_pixels(&self) -> Vec<Coord> {
        let mut output = new_hash_set();

        let left = self.left();
        let right = self.right();
        let top = self.top();
        let bottom = self.bottom();

        for x in left..=right {
            output.insert(coord!(x, top));
            output.insert(coord!(x, bottom));
        }
        for y in top..=bottom {
            output.insert(coord!(left, y));
            output.insert(coord!(right, y));
        }

        output.into_iter().collect()
    }

    fn filled_pixels(&self) -> Vec<Coord> {
        let mut output = new_hash_set();

        let left = self.left();
        let right = self.right();
        let top = self.top();
        let bottom = self.bottom();

        for y in top..=bottom {
            for x in left..=right {
                output.insert(coord!(x, y));
            }
        }

        output.into_iter().collect()
    }

    fn to_shape_box(&self) -> ShapeBox {
        ShapeBox::Rect(self.clone())
    }
}

impl Rect {
    /// Create a circle around the center to the closest edge
    #[must_use]
    pub fn as_inner_circle(&self) -> Circle {
        let radius = self.width().div(2).min(self.height().div(2));
        Circle::new(self.center(), radius)
    }

    /// Create a circle around the center to the farthest edge
    #[must_use]
    pub fn as_outer_circle(&self) -> Circle {
        let radius = self.width().div(2).max(self.height().div(2));
        Circle::new(self.center(), radius)
    }

    /// Create two triangles
    #[must_use]
    pub fn as_triangles(&self) -> (Triangle, Triangle) {
        let top_right = coord!(self.right(), self.top());
        let bottom_left = coord!(self.left(), self.bottom());
        (
            Triangle::new(self.top_left(), top_right, bottom_left),
            Triangle::new(self.bottom_right(), top_right, bottom_left),
        )
    }

    /// Same shape but represented as four points/lines instead of two points
    #[must_use]
    pub fn as_polygon(&self) -> Polygon {
        let top_right = coord!(self.right(), self.top());
        let bottom_left = coord!(self.left(), self.bottom());
        Polygon::new(&[self.top_left, top_right, self.bottom_right, bottom_left])
    }

    #[must_use]
    pub fn as_outer_ellipse(&self) -> Ellipse {
        Ellipse::new(self.center(), self.width(), self.height())
    }

    #[must_use]
    pub fn as_lines(&self) -> [Line; 4] {
        [
            Line::new(self.top_left(), self.top_right()),
            Line::new(self.top_right(), self.bottom_right()),
            Line::new(self.bottom_right(), self.bottom_left()),
            Line::new(self.bottom_left(), self.top_left()),
        ]
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::test::check_points;

    mod rotation {
        use crate::rect::Rect;
        use crate::Shape;

        #[test]
        fn rotate_square_around_bottom_right_corner_90_degrees_twice() {
            let square = Rect::new((0, 0), (20, 20));
            let rotated = square.rotate_around(90, coord!(20, 20));

            assert_eq!(rotated.points(), coord_vec![(40, 0), (20, 20)]);

            let rotated_again = rotated.rotate_around(90, coord!(20, 20));

            assert_eq!(rotated_again.points(), coord_vec![(40, 40), (20, 20)])
        }

        #[test]
        fn rotate_rect_around_center_90_degrees() {
            let rect = Rect::new((0, 0), (40, 20));
            let rotated = rect.rotate(90);

            assert_eq!(rotated.points(), coord_vec![(30, -10), (10, 30)]);
        }
    }

    #[test]
    fn basic_outline() {
        let rect = Rect::new((0, 0), (4, 4));
        let points = rect.outline_pixels();
        check_points(
            &[
                (0, 0),
                (1, 0),
                (2, 0),
                (3, 0),
                (4, 0),
                (0, 1),
                (4, 1),
                (0, 2),
                (4, 2),
                (0, 3),
                (4, 3),
                (0, 4),
                (1, 4),
                (2, 4),
                (3, 4),
                (4, 4),
            ],
            &points,
        );
    }

    #[test]
    fn basic_filled() {
        let rect = Rect::new((3, 2), (6, 4));
        let points = rect.filled_pixels();
        check_points(
            &[
                (3, 2),
                (4, 2),
                (5, 2),
                (6, 2),
                (3, 3),
                (4, 3),
                (5, 3),
                (6, 3),
                (3, 4),
                (4, 4),
                (5, 4),
                (6, 4),
            ],
            &points,
        );
    }

    #[test]
    fn move_center() {
        let rect = Rect::new((100, 100), (120, 120));
        let moved = rect.move_center_to(coord!(50, 50));

        assert_eq!(rect.center(), coord!(110, 110));
        assert_eq!(moved.center(), coord!(50, 50));
    }
}