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
use crate::clipping::ClipMode::*;
use graphics_shapes::coord::Coord;
use graphics_shapes::prelude::{Circle, Rect};
use graphics_shapes::Shape;
use log::error;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::mem::swap;

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
enum ClipShape {
    Box(Rect),
    Round(Circle),
}

impl ClipShape {
    pub fn contains(&self, xy: (isize, isize)) -> bool {
        match self {
            ClipShape::Box(rect) => rect.contains(Coord::from(xy)),
            ClipShape::Round(circle) => circle.contains(Coord::from(xy)),
        }
    }
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
enum ClipElement {
    Add(ClipShape),
    Remove(ClipShape),
}

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
enum ClipMode {
    Nothing,
    Simple(ClipShape),
    Complex(Vec<ClipElement>),
    Custom(Vec<bool>),
}

/// Clip has four modes:
/// * Nothing - All pixels are valid
/// * Simple - Only pixels in the shape (rect or circle) are valid
/// * Custom - User provides a list of which pixels are valid
/// * Complex - A series of shapes adding and removing clip area
///
/// Complex starts with all pixels being valid
/// * use `add_*` to decrease the valid area
/// * use `remove_*` to increase the valid area
/// The last shape to touch a pixel determines it's validity
///
/// With complex mode a list of valid pixels is stored internally and each time the complex clip is updated the valid list is updated as well, if you're making a bulk edit call `set_auto_build_map(false)` first
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Clip {
    width: usize,
    height: usize,
    mode: ClipMode,
    old_mode: ClipMode,
    valid_pixel_map: Option<Vec<bool>>,
    old_valid_pixel_map: Option<Vec<bool>>,
    auto_build_map: bool,
}

impl Clip {
    pub fn new(width: usize, height: usize) -> Self {
        Self {
            width,
            height,
            mode: Nothing,
            old_mode: Nothing,
            valid_pixel_map: None,
            old_valid_pixel_map: None,
            auto_build_map: true,
        }
    }
}

impl Clip {
    pub fn is_nothing(&self) -> bool {
        matches!(&self.mode, Nothing)
    }

    pub fn is_simple(&self) -> bool {
        matches!(&self.mode, Simple(_))
    }

    pub fn is_complex(&self) -> bool {
        matches!(&self.mode, Complex(_))
    }

    pub fn is_custom(&self) -> bool {
        matches!(&self.mode, Custom(_))
    }

    pub fn set_auto_build_map(&mut self, auto_build_map: bool) {
        self.auto_build_map = auto_build_map;
    }
}

impl Clip {
    pub fn is_valid(&self, xy: (isize, isize)) -> bool {
        let i = xy.0 + xy.1 * (self.width as isize);
        let u = i.max(0) as usize;
        match &self.mode {
            Nothing => true,
            Simple(shape) => shape.contains(xy),
            Complex(_) => {
                if let Some(map) = &self.valid_pixel_map {
                    map[u]
                } else {
                    error!("Using complex clip but pixel map hasn't been built");
                    true
                }
            }
            Custom(map) => map[u],
        }
    }
}

impl Clip {
    fn store_current_mode(&mut self) {
        swap(&mut self.old_mode, &mut self.mode);
        swap(&mut self.old_valid_pixel_map, &mut self.valid_pixel_map);
        self.valid_pixel_map = None;
    }
}

impl Clip {
    /// Clears the clip so all pixels can be drawn to
    pub fn set_all_valid(&mut self) {
        self.store_current_mode();
        self.mode = Nothing;
    }

    /// Set the valid pixels to `rect`
    pub fn set_valid_rect(&mut self, rect: Rect) {
        self.store_current_mode();
        self.mode = Simple(ClipShape::Box(rect));
    }

    /// Set the valid pixels to `circle`
    pub fn set_valid_circle(&mut self, circle: Circle) {
        self.store_current_mode();
        self.mode = Simple(ClipShape::Round(circle));
    }

    /// Set the valid pixels to `pixel_map`
    pub fn custom(&mut self, pixel_map: Vec<bool>) {
        self.store_current_mode();
        self.mode = Custom(pixel_map);
    }

    pub fn get_pixel_map(&mut self) -> Vec<bool> {
        match &self.mode {
            Simple(_) | Nothing => self.build_pixel_map(),
            Complex(_) => {
                if let Some(map) = &self.valid_pixel_map {
                    map.clone()
                } else {
                    self.update_pixel_map();
                    self.valid_pixel_map.as_ref().unwrap().clone()
                }
            }
            Custom(map) => map.clone(),
        }
    }
}

impl Clip {
    fn swap_to_complex(&mut self) {
        if !self.is_complex() {
            self.store_current_mode();
            self.mode = Complex(vec![]);
        }
    }

    fn add(&mut self, element: ClipElement) {
        self.swap_to_complex();
        if let Complex(list) = &mut self.mode {
            list.push(element);
        }
        if self.auto_build_map {
            self.update_pixel_map();
        }
    }

    /// Set the mode to `complex` (clearing any other mode)
    /// Set any pixels in `rect` to valid
    pub fn add_rect(&mut self, rect: Rect) {
        self.add(ClipElement::Add(ClipShape::Box(rect)));
    }

    /// Set the mode to `complex` (clearing any other mode)
    /// Set any pixels in `rect` to invalid
    pub fn remove_rect(&mut self, rect: Rect) {
        self.add(ClipElement::Remove(ClipShape::Box(rect)));
    }

    /// Set the mode to `complex` (clearing any other mode)
    /// Set any pixels in `circle` to valid
    pub fn add_circle(&mut self, circle: Circle) {
        self.add(ClipElement::Add(ClipShape::Round(circle)));
    }

    /// Set the mode to `complex` (clearing any other mode)
    /// Set any pixels in `circle` to invalid
    pub fn remove_circle(&mut self, circle: Circle) {
        self.add(ClipElement::Remove(ClipShape::Round(circle)));
    }
}

impl Clip {
    pub fn update_pixel_map(&mut self) {
        if self.is_complex() {
            self.valid_pixel_map = Some(self.build_pixel_map())
        } else {
            self.valid_pixel_map = None;
        }
    }

    fn build_pixel_map(&self) -> Vec<bool> {
        match &self.mode {
            Nothing => vec![true; self.width * self.height],
            Simple(shape) => self.build_simple_map(shape),
            Complex(elements) => self.build_complex_map(elements),
            Custom(map) => map.clone(),
        }
    }

    fn build_simple_map(&self, shape: &ClipShape) -> Vec<bool> {
        let mut output = vec![false; self.width * self.height];
        for x in 0..self.width {
            for y in 0..self.height {
                let i = x + y * self.width;
                let contains = shape.contains((x as isize, y as isize));
                if contains {
                    output[i] = true;
                }
            }
        }
        output
    }

    fn build_complex_map(&self, elements: &[ClipElement]) -> Vec<bool> {
        let mut output = vec![true; self.width * self.height];
        for x in 0..self.width {
            for y in 0..self.height {
                let mut valid = true;
                for element in elements {
                    match element {
                        ClipElement::Add(shape) => {
                            if shape.contains((x as isize, y as isize)) {
                                valid = true;
                            }
                        }
                        ClipElement::Remove(shape) => {
                            if shape.contains((x as isize, y as isize)) {
                                valid = false;
                            }
                        }
                    }
                }
                let i = x + y * self.width;
                if i >= output.len() {
                    break;
                }
                output[x + y * self.width] = valid;
            }
        }
        output
    }
}

#[cfg(test)]
mod test {
    use crate::clipping::Clip;
    use graphics_shapes::rect::Rect;

    #[test]
    fn check_all_pixels_valid_for_none() {
        let mut clip = Clip::new(4, 4);
        assert_eq!(clip.get_pixel_map(), vec![true; 16]);
    }

    #[test]
    fn check_pixels_valid_for_square() {
        let mut clip = Clip::new(4, 4);
        clip.set_valid_rect(Rect::new((1, 1), (2, 2)));
        let expected = vec![
            false, false, false, false, false, true, true, false, false, true, true, false, false,
            false, false, false,
        ];
        assert_eq!(clip.get_pixel_map(), expected);
    }

    #[test]
    fn check_pixels_split_horz() {
        let mut clip = Clip::new(4, 4);
        clip.set_valid_rect(Rect::new((2, 0), (3, 3)));
        let expected = vec![
            false, false, true, true, false, false, true, true, false, false, true, true, false,
            false, true, true,
        ];
        assert_eq!(clip.get_pixel_map(), expected);
    }

    #[test]
    fn complex() {
        let mut clip = Clip::new(4, 4);

        clip.add_rect(Rect::new((0, 0), (3, 3))); //set all pixels to valid
        let expected = vec![true; 16];
        assert_eq!(clip.get_pixel_map(), expected);

        clip.remove_rect(Rect::new((2, 0), (3, 3))); //set right hand side to invalid
        let expected = vec![
            true, true, false, false, true, true, false, false, true, true, false, false, true,
            true, false, false,
        ];
        assert_eq!(clip.get_pixel_map(), expected);

        clip.add_rect(Rect::new((3, 0), (3, 3))); //set last column to valid
        let expected = vec![
            true, true, false, true, true, true, false, true, true, true, false, true, true, true,
            false, true,
        ];
        assert_eq!(clip.get_pixel_map(), expected);
    }
}