summaryrefslogtreecommitdiffstats
path: root/walleng/src/draw.rs
blob: be2c66be72de082066103dae8a3eaa9799acc326 (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
// -*- coding: utf-8 -*-
//
// Copyright 2021-2023 Michael Büsch <m@bues.ch>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

use crate::vec2d::Vec2D;
use std::cmp::Ordering;

trait XY {
    fn to_xy(&self) -> (i32, i32);
}

impl XY for Vec2D {
    #[inline]
    fn to_xy(&self) -> (i32, i32) {
        (self.x().round() as i32, self.y().round() as i32)
    }
}

/// Line pixel iterator.
struct LineIter {
    bx: i32,
    by: i32,
    dx: i32,
    dy: i32,
    xinc: i32,
    yinc: i32,
    x: i32,
    y: i32,
    err: i32,
    done: bool,
}

impl LineIter {
    /// Line iterator, from a to b.
    #[inline]
    fn new(a: (i32, i32), b: (i32, i32)) -> LineIter {
        let dx = b.0 - a.0;
        let dy = b.1 - a.1;

        let (dx, xinc) = if dx < 0 { (-dx, -1) } else { (dx, 1) };
        let (dy, yinc) = if dy < 0 { (-dy, -1) } else { (dy, 1) };

        LineIter {
            bx: b.0,
            by: b.1,
            dx,
            dy,
            xinc,
            yinc,
            x: a.0,
            y: a.1,
            err: 0,
            done: false,
        }
    }
}

impl Iterator for LineIter {
    /// (x, y)
    type Item = (i32, i32);

    /// Next pixel.
    #[allow(clippy::collapsible_else_if)]
    fn next(&mut self) -> Option<Self::Item> {
        if !self.done {
            if self.dx >= self.dy {
                if self.x != self.bx {
                    let (x, y) = (self.x, self.y);
                    self.x += self.xinc;
                    self.err += self.dy * 2;
                    if self.err > self.dx {
                        self.y += self.yinc;
                        self.err -= self.dx * 2;
                    }
                    Some((x, y))
                } else {
                    self.done = true;
                    Some((self.x, self.y))
                }
            } else {
                if self.y != self.by {
                    let (x, y) = (self.x, self.y);
                    self.y += self.yinc;
                    self.err += self.dx * 2;
                    if self.err > self.dy {
                        self.x += self.xinc;
                        self.err -= self.dy * 2;
                    }
                    Some((x, y))
                } else {
                    self.done = true;
                    Some((self.x, self.y))
                }
            }
        } else {
            None
        }
    }
}

struct PathIter<const SIZE: usize> {
    points: [(i32, i32); SIZE],
    size: usize,
    index: usize,
    line: Option<LineIter>,
}

impl<const SIZE: usize> PathIter<SIZE> {
    #[inline]
    fn new() -> PathIter<SIZE> {
        PathIter {
            points: [(0, 0); SIZE],
            size: 0,
            index: 0,
            line: None,
        }
    }

    /// Add a new point to the path.
    #[inline]
    fn add(&mut self, p: (i32, i32)) {
        if self.size < SIZE {
            self.points[self.size] = p;
            self.size += 1;
        }
    }
}

impl<const SIZE: usize> Iterator for PathIter<SIZE> {
    /// (x, y)
    type Item = (i32, i32);

    fn next(&mut self) -> Option<Self::Item> {
        if self.size >= 2 {
            'a: loop {
                if self.index < self.size - 1 {
                    if let Some(ref mut line) = self.line {
                        if let Some((x, y)) = line.next() {
                            break 'a Some((x, y));
                        } else {
                            // Go to next section.
                            self.index += 1;
                            self.line = None;
                        }
                    } else {
                        // Next section.
                        self.line = Some(LineIter::new(
                            self.points[self.index],
                            self.points[self.index + 1],
                        ));
                    }
                } else {
                    // All sections done.
                    break 'a None;
                }
            }
        } else {
            // Not enough points to form a section.
            None
        }
    }
}

pub struct Draw<'a> {
    image: &'a mut [u32],
    width: usize,
    height: usize,
}

impl<'a> Draw<'a> {
    pub fn new(image: &'a mut [u32], width: usize, height: usize) -> Draw {
        assert!(width <= i32::MAX as usize);
        assert!(height <= i32::MAX as usize);
        Draw {
            image,
            width,
            height,
        }
    }

    #[inline]
    pub fn set_pixel(&mut self, x: i32, y: i32, color: u32) {
        if x >= 0 && (x as usize) < self.width && y >= 0 && (y as usize) < self.height {
            self.image[y as usize * self.width + x as usize] = color;
        }
    }

    pub fn draw_line(&mut self, coords: (&Vec2D, &Vec2D), color: u32) {
        for (x, y) in LineIter::new(coords.0.to_xy(), coords.1.to_xy()) {
            self.set_pixel(x, y, color);
        }
    }

    pub fn draw_horizontal_line(&mut self, point: (i32, i32), length: i32, color: u32) {
        let (mut x, y) = point;
        let mut length = length;

        if y < self.height as i32 && y >= 0 {
            if length < 0 {
                x += length;
                debug_assert!(length != i32::MIN);
                length = -length;
            }
            if x < 0 {
                length = (length + x).max(0);
                x = 0;
            }
            if x < self.width as i32 {
                length = length.min(self.width as i32 - x);

                let (x, y, length) = (x as usize, y as usize, length as usize);

                let offs = y * self.width + x;
                self.image[offs..offs + length].fill(color);
            }
        }
    }

    #[allow(dead_code)]
    pub fn draw_tetragon(&mut self, corners: (&Vec2D, &Vec2D, &Vec2D, &Vec2D), color: u32) {
        self.draw_line((corners.0, corners.1), color);
        self.draw_line((corners.1, corners.2), color);
        self.draw_line((corners.2, corners.3), color);
        self.draw_line((corners.3, corners.0), color);
    }

    /// Fill a convex tetragon.
    #[allow(dead_code)]
    pub fn fill_tetragon(&mut self, corners: (&Vec2D, &Vec2D, &Vec2D, &Vec2D), color: u32) {
        // Sort all points top to bottom (= along y axis).
        let mut ttb = [
            corners.0.to_xy(),
            corners.1.to_xy(),
            corners.2.to_xy(),
            corners.3.to_xy(),
        ];
        ttb.sort_unstable_by(|a, b| {
            if a.1 < b.1 || (a.1 == b.1 && a.0 < b.0) {
                Ordering::Less
            } else if a.1 > b.1 || (a.1 == b.1 && a.0 > b.0) {
                Ordering::Greater
            } else {
                Ordering::Equal
            }
        });

        // Construct the left hand side path.
        let mut a_path: PathIter<4> = PathIter::new();
        a_path.add(ttb[0]);
        if ttb[1].0 < ttb[3].0 {
            a_path.add(ttb[1]);
        }
        if ttb[2].0 < ttb[3].0 {
            a_path.add(ttb[2]);
        }
        a_path.add(ttb[3]);

        // Construct the right hand side path.
        let mut b_path: PathIter<4> = PathIter::new();
        b_path.add(ttb[0]);
        if ttb[1].0 >= ttb[3].0 {
            b_path.add(ttb[1]);
        }
        if ttb[2].0 >= ttb[3].0 {
            b_path.add(ttb[2]);
        }
        b_path.add(ttb[3]);

        // Draw all horizontal lines in the convex tetragon
        // confined by the vertical paths a_path and b_path.
        let mut prev_ay = i32::MIN;
        let (mut bx, mut by) = (i32::MIN, i32::MIN);
        'outer: loop {
            if let Some((ax, ay)) = a_path.next() {
                if ay != prev_ay {
                    prev_ay = ay;
                    'inner: loop {
                        if ay == by {
                            self.draw_horizontal_line((ax, ay), bx - ax, color);
                            break 'inner;
                        }
                        if let Some((x, y)) = b_path.next() {
                            bx = x;
                            by = y;
                        } else {
                            break 'outer;
                        }
                    }
                }
            } else {
                break 'outer;
            }
        }
    }
}

// vim: ts=4 sw=4 expandtab
bues.ch cgit interface