Skip to main content

blit_gui/
display_list.rs

1use alloc::vec::Vec;
2use core::{
3    any::TypeId,
4    hash::{BuildHasher, Hash, Hasher},
5};
6
7use blit::{FrameStore, FrameStoreMut, LogicalRect, PhysicalRect};
8
9use crate::style::BorderRadius;
10
11pub type DisplayHasher = <hashbrown::DefaultHashBuilder as BuildHasher>::Hasher;
12
13/// owned drawing inputs for a frame
14#[derive(Default)]
15pub struct DisplayList {
16    commands: Vec<Command>,
17    clips: Vec<Clip>,
18    store: FrameStore,
19}
20
21/// content comparison for recorded drawing inputs
22///
23/// equal values must hash identically
24/// resolve stored slices through their corresponding display lists
25pub trait Compare: 'static {
26    fn equal(a: &Self, left: &DisplayList, b: &Self, right: &DisplayList) -> bool;
27    fn hash(input: &Self, list: &DisplayList, state: &mut impl Hasher);
28}
29
30impl<T> Compare for T
31where
32    T: PartialEq + Hash + 'static,
33{
34    fn equal(a: &Self, _: &DisplayList, b: &Self, _: &DisplayList) -> bool {
35        a == b
36    }
37    fn hash(input: &Self, _: &DisplayList, state: &mut impl Hasher) {
38        Hash::hash(input, state);
39    }
40}
41
42impl DisplayList {
43    pub fn commands(&self) -> &[Command] {
44        &self.commands
45    }
46
47    pub fn clips(&self) -> &[Clip] {
48        &self.clips
49    }
50
51    pub fn store(&self) -> &FrameStore {
52        &self.store
53    }
54
55    pub fn store_mut(&mut self) -> FrameStoreMut<'_> {
56        self.store.as_mut()
57    }
58
59    /// records a drawing input
60    ///
61    /// use distinct input types for commands with different rendering behavior
62    #[inline]
63    pub fn push<T: Compare>(&mut self, area: LogicalRect, bounds: PhysicalRect, clip: u32, value: T) {
64        assert!(clip as usize <= self.clips.len(), "invalid paint clip");
65        let ops = const {
66            &Ops {
67                kind: TypeId::of::<T>(),
68                equal: |left, a, right, b| {
69                    // safety: equivalent checks both input types
70                    let a = unsafe { left.store.get::<T>(a) };
71                    let b = unsafe { right.store.get::<T>(b) };
72                    T::equal(a, left, b, right)
73                },
74                hash: |list, offset, state| {
75                    // safety: push pairs the input type and hash operation
76                    let value = unsafe { list.store.get::<T>(offset) };
77                    T::hash(value, list, state);
78                },
79            }
80        };
81        self.commands.push(Command {
82            area,
83            bounds,
84            clip,
85            offset: self.store.push(value),
86            ops,
87        });
88    }
89
90    /// returns the recorded value and its offset in the list's store
91    #[inline]
92    pub fn input<T: 'static>(&self, index: usize) -> (&T, u32) {
93        let command = &self.commands[index];
94        assert_eq!(command.ops.kind, TypeId::of::<T>(), "wrong command input type");
95        // safety: push stores the value of the checked type at this offset
96        (unsafe { self.store.get::<T>(command.offset) }, command.offset)
97    }
98
99    pub fn push_clip(&mut self, clip: Clip) -> u32 {
100        assert!(clip.parent as usize <= self.clips.len(), "invalid parent clip");
101        let index = u32::try_from(self.clips.len()).expect("too many paint clips");
102        let index = index.checked_add(1).expect("too many paint clips");
103        self.clips.push(clip);
104        index
105    }
106
107    pub fn hash(&self, index: usize, state: &mut DisplayHasher) {
108        let command = &self.commands[index];
109        let operations = command.ops;
110        operations.kind.hash(state);
111        let area = command.area;
112        [area.x, area.y, area.width, area.height]
113            .map(|value| if value == 0.0 { 0 } else { value.to_bits() })
114            .hash(state);
115        // safety: insertion pairs the operations with their recorded data
116        unsafe { (operations.hash)(self, command.offset, state) };
117    }
118
119    pub fn equivalent(&self, index: usize, other: &Self, other_index: usize) -> bool {
120        let left = &self.commands[index];
121        let right = &other.commands[other_index];
122        let operations = left.ops;
123        if left.area != right.area || left.bounds != right.bounds || operations.kind != right.ops.kind {
124            return false;
125        }
126        let mut clip = left.clip;
127        let mut other_clip = right.clip;
128        loop {
129            match (clip, other_clip) {
130                (0, 0) => break,
131                (0, _) | (_, 0) => return false,
132                _ => {}
133            }
134            let left = &self.clips[clip as usize - 1];
135            let right = &other.clips[other_clip as usize - 1];
136            if left.area != right.area || left.radius != right.radius {
137                return false;
138            }
139            clip = left.parent;
140            other_clip = right.parent;
141        }
142        // safety: the matching input types identify the representation at each offset
143        unsafe { (operations.equal)(self, left.offset, other, right.offset) }
144    }
145
146    pub fn clear(&mut self) {
147        self.commands.clear();
148        self.clips.clear();
149        self.store.clear();
150    }
151}
152
153pub struct Command {
154    /// logical layout area given to paint
155    pub area: LogicalRect,
156    /// physical pixels the command may touch
157    pub bounds: PhysicalRect,
158    pub clip: u32,
159    offset: u32,
160    ops: &'static Ops,
161}
162
163struct Ops {
164    kind: TypeId,
165    equal: unsafe fn(&DisplayList, u32, &DisplayList, u32) -> bool,
166    hash: unsafe fn(&DisplayList, u32, &mut DisplayHasher),
167}
168
169#[derive(Clone, Copy)]
170pub struct Clip {
171    pub parent: u32,
172    pub area: LogicalRect,
173    pub radius: BorderRadius,
174}