Skip to main content

fbsurface/
geom.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Pure geometry: sizes, rectangles and bounded rectangle sets.
24//!
25//! This module has no pixel knowledge and no allocation. Everything is
26//! `Copy`, which makes the types safe to pass across the framebuffer lock.
27//!
28//! The single clipping rule used by [`Canvas`](crate::Canvas) lives here:
29//! [`Rect::intersect`]. There is deliberately no other definition of "inside
30//! the screen" anywhere in the crate.
31
32/// Width and height of a surface, in pixels.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
34pub struct Dims {
35    pub w: u32,
36    pub h: u32,
37}
38
39impl Dims {
40    pub const ZERO: Self = Self { w: 0, h: 0 };
41
42    #[inline]
43    pub const fn new(w: u32, h: u32) -> Self {
44        Self { w, h }
45    }
46
47    #[inline]
48    pub const fn area(self) -> u64 {
49        self.w as u64 * self.h as u64
50    }
51
52    #[inline]
53    pub const fn is_empty(self) -> bool {
54        self.w == 0 || self.h == 0
55    }
56}
57
58/// An axis-aligned rectangle, in pixels.
59///
60/// An empty rectangle (`w == 0` or `h == 0`) is never drawable and is what
61/// clipping operations return when nothing remains.
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
63pub struct Rect {
64    pub x: u32,
65    pub y: u32,
66    pub w: u32,
67    pub h: u32,
68}
69
70impl Rect {
71    pub const EMPTY: Self = Self {
72        x: 0,
73        y: 0,
74        w: 0,
75        h: 0,
76    };
77
78    #[inline]
79    pub const fn new(x: u32, y: u32, w: u32, h: u32) -> Self {
80        Self { x, y, w, h }
81    }
82
83    #[inline]
84    pub const fn is_empty(self) -> bool {
85        self.w == 0 || self.h == 0
86    }
87
88    /// One past the last column. Saturates instead of wrapping, so a bogus
89    /// `x + w` can never turn into a rectangle on the other side of zero.
90    #[inline]
91    pub const fn right(self) -> u32 {
92        self.x.saturating_add(self.w)
93    }
94
95    /// One past the last row.
96    #[inline]
97    pub const fn bottom(self) -> u32 {
98        self.y.saturating_add(self.h)
99    }
100
101    #[inline]
102    pub const fn area(self) -> u64 {
103        self.w as u64 * self.h as u64
104    }
105
106    #[inline]
107    pub const fn contains_point(self, x: u32, y: u32) -> bool {
108        !self.is_empty() && x >= self.x && x < self.right() && y >= self.y && y < self.bottom()
109    }
110
111    #[inline]
112    pub const fn contains_rect(self, other: Rect) -> bool {
113        !other.is_empty()
114            && other.x >= self.x
115            && other.y >= self.y
116            && other.right() <= self.right()
117            && other.bottom() <= self.bottom()
118    }
119
120    /// The overlap of two rectangles (empty when they do not overlap).
121    #[inline]
122    pub const fn intersect(self, other: Rect) -> Rect {
123        if self.is_empty() || other.is_empty() {
124            return Rect::EMPTY;
125        }
126        let x0 = max_u32(self.x, other.x);
127        let y0 = max_u32(self.y, other.y);
128        let x1 = min_u32(self.right(), other.right());
129        let y1 = min_u32(self.bottom(), other.bottom());
130        if x1 <= x0 || y1 <= y0 {
131            Rect::EMPTY
132        } else {
133            Rect::new(x0, y0, x1 - x0, y1 - y0)
134        }
135    }
136
137    /// The smallest rectangle containing both. An empty operand is ignored.
138    #[inline]
139    pub const fn union(self, other: Rect) -> Rect {
140        if self.is_empty() {
141            return other;
142        }
143        if other.is_empty() {
144            return self;
145        }
146        let x0 = min_u32(self.x, other.x);
147        let y0 = min_u32(self.y, other.y);
148        let x1 = max_u32(self.right(), other.right());
149        let y1 = max_u32(self.bottom(), other.bottom());
150        Rect::new(x0, y0, x1 - x0, y1 - y0)
151    }
152
153    /// True when the two rectangles share a full edge (no overlap and no
154    /// gap). Used by [`RectSet`] to coalesce glyph rows without covering
155    /// clean pixels.
156    #[inline]
157    pub const fn is_adjacent(self, other: Rect) -> bool {
158        if self.is_empty() || other.is_empty() {
159            return false;
160        }
161        let same_rows = self.y == other.y && self.h == other.h;
162        let same_cols = self.x == other.x && self.w == other.w;
163        (same_rows && (self.right() == other.x || other.right() == self.x))
164            || (same_cols && (self.bottom() == other.y || other.bottom() == self.y))
165    }
166
167    /// Translate by a signed offset, saturating at the origin.
168    #[inline]
169    pub const fn offset(self, dx: i32, dy: i32) -> Rect {
170        let x = self.x as i64 + dx as i64;
171        let y = self.y as i64 + dy as i64;
172        Rect::new(
173            if x < 0 { 0 } else { x as u32 },
174            if y < 0 { 0 } else { y as u32 },
175            self.w,
176            self.h,
177        )
178    }
179}
180
181#[inline]
182const fn min_u32(a: u32, b: u32) -> u32 {
183    if a < b {
184        a
185    } else {
186        b
187    }
188}
189
190#[inline]
191const fn max_u32(a: u32, b: u32) -> u32 {
192    if a > b {
193        a
194    } else {
195        b
196    }
197}
198
199/// Default number of rectangles kept without merging.
200pub const DEFAULT_SET_CAPACITY: usize = 16;
201
202/// A fixed-capacity set of non-overlapping dirty rectangles.
203///
204/// Replacement for both `DirtyRectSet` and `Damage`. The rules are:
205///
206/// - overlapping or edge-adjacent rectangles are merged, transitively;
207/// - when the set is full, the new rectangle is merged into the existing one
208///   whose union grows the least, so a single far-away rect cannot drag the
209///   presented area to the corner of the screen;
210/// - insertion never allocates and never fails.
211#[derive(Clone, Copy, Debug)]
212pub struct RectSet<const N: usize = DEFAULT_SET_CAPACITY> {
213    rects: [Rect; N],
214    len: usize,
215}
216
217impl<const N: usize> Default for RectSet<N> {
218    fn default() -> Self {
219        Self::empty()
220    }
221}
222
223impl<const N: usize> RectSet<N> {
224    #[inline]
225    pub const fn empty() -> Self {
226        Self {
227            rects: [Rect::EMPTY; N],
228            len: 0,
229        }
230    }
231
232    /// Insert a rectangle. Empty rectangles are ignored.
233    pub fn include(&mut self, rect: Rect) {
234        if rect.is_empty() {
235            return;
236        }
237        let mut next = rect;
238
239        let mut idx = 0;
240        while idx < self.len {
241            let cur = self.rects[idx];
242            if cur.is_empty() {
243                idx += 1;
244                continue;
245            }
246            if !cur.intersect(next).is_empty() || cur.is_adjacent(next) {
247                next = cur.union(next);
248                // Swap-remove, then restart: the merged rectangle may now
249                // touch a rectangle that came before it.
250                self.rects[idx] = self.rects[self.len - 1];
251                self.rects[self.len - 1] = Rect::EMPTY;
252                self.len -= 1;
253                idx = 0;
254                continue;
255            }
256            idx += 1;
257        }
258
259        if self.len < N {
260            self.rects[self.len] = next;
261            self.len += 1;
262            return;
263        }
264
265        if N == 0 {
266            return;
267        }
268
269        let mut best = 0;
270        let mut best_cost = u64::MAX;
271        for i in 0..self.len {
272            let union = self.rects[i].union(next);
273            let cost = union.area().saturating_sub(self.rects[i].area());
274            if cost < best_cost {
275                best_cost = cost;
276                best = i;
277            }
278        }
279        self.rects[best] = self.rects[best].union(next);
280    }
281
282    /// Insert every rectangle of another set.
283    ///
284    /// The capacities may differ: this keeps callers such as the kernel
285    /// `Presenter` from silently depending on two constants staying equal.
286    pub fn include_set<const M: usize>(&mut self, other: &RectSet<M>) {
287        for r in other.iter() {
288            self.include(r);
289        }
290    }
291
292    #[inline]
293    pub fn clear(&mut self) {
294        self.len = 0;
295    }
296
297    #[inline]
298    pub fn is_empty(&self) -> bool {
299        self.iter().next().is_none()
300    }
301
302    #[inline]
303    pub fn len(&self) -> usize {
304        self.len
305    }
306
307    /// Number of slots still available before merging starts.
308    #[inline]
309    pub fn spare(&self) -> usize {
310        N.saturating_sub(self.len)
311    }
312
313    #[inline]
314    pub fn capacity(&self) -> usize {
315        N
316    }
317
318    pub fn iter(&self) -> RectSetIter<'_, N> {
319        RectSetIter { set: self, idx: 0 }
320    }
321
322    /// Bounding box of every rectangle, or [`Rect::EMPTY`].
323    pub fn bounds(&self) -> Rect {
324        let mut bounds = Rect::EMPTY;
325        for r in self.iter() {
326            bounds = bounds.union(r);
327        }
328        bounds
329    }
330
331    /// Sum of the areas. Adjacent rects are merged, so this does not
332    /// double-count the common case.
333    pub fn total_area(&self) -> u64 {
334        self.iter().map(Rect::area).sum()
335    }
336}
337
338impl<const N: usize> IntoIterator for RectSet<N> {
339    type Item = Rect;
340    type IntoIter = RectSetOwnedIter<N>;
341
342    fn into_iter(self) -> Self::IntoIter {
343        RectSetOwnedIter { set: self, idx: 0 }
344    }
345}
346
347impl<'a, const N: usize> IntoIterator for &'a RectSet<N> {
348    type Item = Rect;
349    type IntoIter = RectSetIter<'a, N>;
350
351    fn into_iter(self) -> Self::IntoIter {
352        self.iter()
353    }
354}
355
356pub struct RectSetIter<'a, const N: usize> {
357    set: &'a RectSet<N>,
358    idx: usize,
359}
360
361impl<const N: usize> Iterator for RectSetIter<'_, N> {
362    type Item = Rect;
363
364    fn next(&mut self) -> Option<Self::Item> {
365        while self.idx < self.set.len {
366            let r = self.set.rects[self.idx];
367            self.idx += 1;
368            if !r.is_empty() {
369                return Some(r);
370            }
371        }
372        None
373    }
374}
375
376pub struct RectSetOwnedIter<const N: usize> {
377    set: RectSet<N>,
378    idx: usize,
379}
380
381impl<const N: usize> Iterator for RectSetOwnedIter<N> {
382    type Item = Rect;
383
384    fn next(&mut self) -> Option<Self::Item> {
385        while self.idx < self.set.len {
386            let r = self.set.rects[self.idx];
387            self.idx += 1;
388            if !r.is_empty() {
389                return Some(r);
390            }
391        }
392        None
393    }
394}
395
396#[cfg(test)]
397mod tests {
398    use super::*;
399
400    #[test]
401    fn intersect_clips_both_axes() {
402        let screen = Rect::new(0, 0, 100, 50);
403        assert_eq!(
404            Rect::new(90, 40, 30, 30).intersect(screen),
405            Rect::new(90, 40, 10, 10)
406        );
407        assert_eq!(Rect::new(100, 0, 10, 10).intersect(screen), Rect::EMPTY);
408        assert_eq!(Rect::EMPTY.intersect(screen), Rect::EMPTY);
409    }
410
411    #[test]
412    fn intersect_saturates_on_overflow() {
413        let huge = Rect::new(u32::MAX - 1, 0, 100, 10);
414        assert_eq!(huge.right(), u32::MAX);
415        assert_eq!(huge.intersect(Rect::new(0, 0, 10, 10)), Rect::EMPTY);
416    }
417
418    #[test]
419    fn union_ignores_empty() {
420        let r = Rect::new(4, 4, 8, 8);
421        assert_eq!(r.union(Rect::EMPTY), r);
422        assert_eq!(Rect::EMPTY.union(r), r);
423        assert_eq!(Rect::new(0, 0, 2, 2).union(r), Rect::new(0, 0, 12, 12));
424    }
425
426    #[test]
427    fn adjacency_is_edge_only() {
428        let a = Rect::new(0, 0, 10, 10);
429        assert!(a.is_adjacent(Rect::new(10, 0, 5, 10)));
430        assert!(a.is_adjacent(Rect::new(0, 10, 10, 5)));
431        // Diagonal contact is not adjacency, and neither is a gap.
432        assert!(!a.is_adjacent(Rect::new(10, 10, 5, 5)));
433        assert!(!a.is_adjacent(Rect::new(11, 0, 5, 10)));
434        // Overlap is handled by intersect(), not adjacency.
435        assert!(!a.is_adjacent(Rect::new(5, 0, 10, 10)));
436    }
437
438    #[test]
439    fn set_merges_adjacent_rows() {
440        let mut set = RectSet::<4>::empty();
441        set.include(Rect::new(0, 0, 8, 8));
442        set.include(Rect::new(8, 0, 8, 8));
443        assert_eq!(set.len(), 1);
444        assert_eq!(set.iter().next(), Some(Rect::new(0, 0, 16, 8)));
445    }
446
447    #[test]
448    fn set_merges_transitively() {
449        let mut set = RectSet::<8>::empty();
450        set.include(Rect::new(0, 0, 10, 10));
451        set.include(Rect::new(30, 0, 10, 10));
452        // Bridges the two existing rects.
453        set.include(Rect::new(10, 0, 20, 10));
454        assert_eq!(set.len(), 1);
455        assert_eq!(set.iter().next(), Some(Rect::new(0, 0, 40, 10)));
456    }
457
458    #[test]
459    fn set_keeps_disjoint_rects_apart() {
460        let mut set = RectSet::<4>::empty();
461        set.include(Rect::new(0, 0, 4, 4));
462        set.include(Rect::new(20, 20, 4, 4));
463        assert_eq!(set.len(), 2);
464        assert_eq!(set.total_area(), 32);
465        assert_eq!(set.bounds(), Rect::new(0, 0, 24, 24));
466    }
467
468    #[test]
469    fn set_overflow_merges_cheapest() {
470        let mut set = RectSet::<2>::empty();
471        set.include(Rect::new(0, 0, 10, 10));
472        set.include(Rect::new(100, 0, 10, 10));
473        // Third rect sits next to the first one: it must merge there.
474        set.include(Rect::new(10, 0, 10, 10));
475        assert_eq!(set.len(), 2);
476        let mut rects: [Rect; 2] = [Rect::EMPTY; 2];
477        for (i, r) in set.iter().enumerate() {
478            rects[i] = r;
479        }
480        assert!(rects.contains(&Rect::new(0, 0, 20, 10)));
481        assert!(rects.contains(&Rect::new(100, 0, 10, 10)));
482    }
483
484    #[test]
485    fn set_ignores_empty_and_clears() {
486        let mut set = RectSet::<4>::empty();
487        set.include(Rect::EMPTY);
488        assert!(set.is_empty());
489        set.include(Rect::new(1, 2, 3, 4));
490        assert_eq!(set.len(), 1);
491        set.clear();
492        assert!(set.is_empty());
493        assert_eq!(set.bounds(), Rect::EMPTY);
494    }
495
496    #[test]
497    fn sets_with_different_capacities_merge() {
498        let mut dst = RectSet::<4>::empty();
499        let mut src = RectSet::<2>::empty();
500        src.include(Rect::new(0, 0, 4, 4));
501        src.include(Rect::new(8, 0, 4, 4));
502        dst.include_set(&src);
503        assert_eq!(dst.len(), 2);
504        dst.include_set(&RectSet::<8>::empty());
505        assert_eq!(dst.len(), 2);
506    }
507
508    #[test]
509    fn zero_capacity_set_never_panics() {
510        let mut set = RectSet::<0>::empty();
511        set.include(Rect::new(1, 2, 3, 4));
512        assert!(set.is_empty());
513    }
514}