aboutsummaryrefslogtreecommitdiff
path: root/src/bitmap.rs
blob: ff41cb826921c6332f4128159a4b5831f32e4f84 (plain)
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
use std::{
    collections::HashSet,
    convert::{From, Into, TryFrom},
    ops::{Add, Sub},
};

use crate::lisp::{error::EvalError, expr::LispExpr};

#[derive(Debug)]
pub struct Pixmap<T> {
    pub width: u32,
    pub height: u32,
    pub data: Vec<T>,
}

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct MapPoint {
    pub x: u32,
    pub y: u32,
}

impl From<(u32, u32)> for MapPoint {
    fn from((x, y): (u32, u32)) -> MapPoint {
        MapPoint { x, y }
    }
}

impl TryFrom<(i32, i32)> for MapPoint {
    type Error = ();
    fn try_from((x, y): (i32, i32)) -> Result<Self, Self::Error> {
        if x < 0 || y < 0 {
            Err(())
        } else {
            Ok(MapPoint {
                x: x as u32,
                y: y as u32,
            })
        }
    }
}

impl TryFrom<(i64, i64)> for MapPoint {
    type Error = ();
    fn try_from((x, y): (i64, i64)) -> Result<Self, Self::Error> {
        if x < 0 || y < 0 {
            Err(())
        } else {
            Ok(MapPoint {
                x: x as u32,
                y: y as u32,
            })
        }
    }
}

impl Add for MapPoint {
    type Output = Self;
    fn add(self, rhs: Self) -> Self::Output {
        MapPoint {
            x: self.x.saturating_add(rhs.x),
            y: self.y.saturating_add(rhs.y),
        }
    }
}

impl Sub for MapPoint {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self::Output {
        MapPoint {
            x: self.x.saturating_sub(rhs.x),
            y: self.y.saturating_sub(rhs.y),
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Axis {
    X,
    Y,
}

impl TryFrom<&LispExpr> for Axis {
    type Error = EvalError;
    fn try_from(value: &LispExpr) -> Result<Self, Self::Error> {
        match value {
            LispExpr::Ident(id) => match id.as_ref() {
                "x" => Ok(Axis::X),
                "y" => Ok(Axis::Y),
                _ => Err(EvalError::TypeMismatch),
            },
            _ => Err(EvalError::TypeMismatch),
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub enum Quadrant {
    I,
    II,
    III,
    IV,
}

impl MapPoint {
    #[inline]
    pub fn scale(self, c: u32) -> MapPoint {
        MapPoint {
            x: self.x * c,
            y: self.y * c,
        }
    }

    #[inline]
    pub fn mirror_about(self, line: u32, axis: Axis) -> MapPoint {
        let MapPoint { x, y } = self;
        match axis {
            Axis::X => MapPoint {
                x,
                y: (2 * line).saturating_sub(y),
            },
            Axis::Y => MapPoint {
                x: (2 * line).saturating_sub(x),
                y,
            },
        }
    }

    #[inline]
    pub fn reflect(self, around: MapPoint) -> MapPoint {
        around.scale(2) - self
    }

    #[inline]
    pub fn quadrant(self, origin: MapPoint) -> Quadrant {
        match (self, origin) {
            _ if self.x >= origin.x && self.y >= origin.y => Quadrant::I,
            _ if self.x < origin.x && self.y >= origin.y => Quadrant::II,
            _ if self.x < origin.x && self.y < origin.y => Quadrant::III,
            _ if self.x >= origin.x && self.y < origin.y => Quadrant::IV,
            _ => unreachable!("unexpected quadrant!"),
        }
    }
}

impl<T> Pixmap<T>
where
    T: Copy + Clone + Default + PartialEq,
{
    pub fn new(width: u32, height: u32) -> Self {
        let data = vec![Default::default(); (width * height) as usize];
        Pixmap {
            width,
            height,
            data,
        }
    }

    pub fn new_with(width: u32, height: u32, data: Vec<T>) -> Self {
        Pixmap {
            width,
            height,
            data,
        }
    }

    pub fn contains<P: Into<MapPoint>>(&self, pt: P) -> bool {
        let MapPoint { x, y } = pt.into();
        x < self.width && y < self.height
    }

    pub fn idx<P: Into<MapPoint>>(&self, pt: P) -> usize {
        let MapPoint { x, y } = pt.into();
        (y * self.width + x) as usize
    }

    pub fn get<P: Into<MapPoint>>(&self, pt: P) -> T {
        let idx = self.idx(pt);
        self.data[idx]
    }

    pub fn set<P: Into<MapPoint>>(&mut self, pt: P, new_val: T) -> T {
        let pt = pt.into();
        let old_val = self.get(pt);
        let idx = self.idx(pt);
        self.data[idx] = new_val;
        old_val
    }

    pub fn get_circle<P: Into<MapPoint>>(
        &self,
        center: P,
        radius: u32,
        filled: bool,
    ) -> Vec<MapPoint> {
        let mut circle: Vec<(i64, i64)> = vec![];
        let MapPoint { x, y } = center.into();
        let x = x as i64;
        let y = y as i64;
        let (mut dx, mut dy, mut err) = (radius as i64, 0i64, 1 - radius as i64);
        while dx >= dy {
            circle.push((x + dx, y + dy));
            circle.push((x - dx, y + dy));
            circle.push((x + dx, y - dy));
            circle.push((x - dx, y - dy));
            circle.push((x + dy, y + dx));
            circle.push((x - dy, y + dx));
            circle.push((x + dy, y - dx));
            circle.push((x - dy, y - dx));
            if filled {
                circle.extend((x - dx.abs() + 1..x + dx.abs()).map(|x| (x, y + dy)));
                circle.extend((x - dx.abs() + 1..x + dx.abs()).map(|x| (x, y - dy)));
                circle.extend((x - dy.abs() + 1..x + dy.abs()).map(|x| (x, y + dx)));
                circle.extend((x - dy.abs() + 1..x + dy.abs()).map(|x| (x, y - dx)));
            }
            dy += 1;
            if err < 0 {
                err = err + 2 * dy + 1;
            } else {
                dx -= 1;
                err += 2 * (dy - dx) + 1;
            }
        }
        circle
            .into_iter()
            .flat_map(MapPoint::try_from)
            .filter(|&pt| self.contains(pt))
            .collect()
    }

    pub fn get_line<P: Into<MapPoint>>(&self, start: P, end: P) -> Vec<MapPoint> {
        let MapPoint { x: x1, y: y1 } = start.into();
        let MapPoint { x: x2, y: y2 } = end.into();
        let mut coordinates = vec![];
        let dx = abs_difference(x1, x2) as i64;
        let dy = abs_difference(y1, y2) as i64;
        let sx = {
            if x1 < x2 {
                1
            } else {
                -1
            }
        };
        let sy = {
            if y1 < y2 {
                1
            } else {
                -1
            }
        };
        let mut err: i64 = dx - dy;
        let mut current_x = x1 as i64;
        let mut current_y = y1 as i64;
        loop {
            coordinates.push((current_x, current_y));
            if current_x == x2 as i64 && current_y == y2 as i64 {
                break;
            }
            let e2 = 2 * err;
            if e2 > -dy {
                err -= dy;
                current_x += sx;
            }
            if e2 < dx {
                err += dx;
                current_y += sy;
            }
        }
        coordinates
            .into_iter()
            .flat_map(MapPoint::try_from)
            .filter(|&pt| self.contains(pt))
            .collect()
    }

    pub fn flood_fill(&mut self, start: MapPoint, target: T, replacement: T) -> Vec<MapPoint> {
        let mut queue = vec![start];
        let mut area = HashSet::new();
        loop {
            if queue.is_empty() {
                break area.drain().collect();
            } else {
                let last = queue.pop().unwrap();
                area.insert(last);
                [(1, 0), (0, 1), (-1, 0), (0, -1)]
                    .iter()
                    .filter_map(|(x, y)| {
                        MapPoint::try_from((last.x as i64 + x, last.y as i64 + y)).ok()
                    })
                    .filter(|&pt| {
                        self.contains(pt)
                            && self.get(pt) == target
                            && self.get(pt) != replacement
                            && !area.contains(&pt)
                    })
                    .for_each(|pt| queue.push(pt));
            }
        }
    }
}

impl Pixmap<bool> {
    pub fn invert(&mut self) {
        for px in self.data.iter_mut() {
            *px = !(*px);
        }
    }
}

pub fn abs_difference<T: Sub<Output = T> + Ord>(x: T, y: T) -> T {
    if x < y {
        y - x
    } else {
        x - y
    }
}

pub fn mirror_figure(figure: &[MapPoint], line: u32, axis: Axis) -> Vec<MapPoint> {
    figure
        .iter()
        .map(|pt| pt.mirror_about(line, axis))
        .collect()
}

pub fn reflect_figure(figure: &[MapPoint], around: MapPoint) -> Vec<MapPoint> {
    figure.iter().map(|pt| pt.reflect(around)).collect()
}

pub fn positive_angle_with_x(start: MapPoint, end: MapPoint) -> f64 {
    if end.x == start.x {
        return 90.;
    }
    let numer = (end.y as f64 - start.y as f64).abs();
    let denum = (end.x as f64 - start.x as f64).abs();
    (numer / denum).atan().to_degrees()
}

pub fn manhattan(
    MapPoint { x: sx, y: sy }: MapPoint,
    MapPoint { x: ex, y: ey, .. }: MapPoint,
) -> u32 {
    abs_difference(sx, ex) + abs_difference(sy, ey)
}