Skip to main content

blit_gui/damage/
command.rs

1use alloc::{collections::VecDeque, vec::Vec};
2use core::ops::Range;
3
4use blit::{PhysicalRect, Scale2};
5
6use super::{DamageTracker, DisplayList};
7
8/// compares ordered command inputs and their clip chains
9#[derive(Default)]
10pub struct CommandDiff {
11    previous: DisplayList,
12    current: Vec<PhysicalRect>,
13    history: VecDeque<Vec<PhysicalRect>>,
14    damage: Vec<PhysicalRect>,
15    clips: Vec<PhysicalRect>,
16    screen: PhysicalRect,
17    max_age: u8,
18    initialized: bool,
19}
20
21impl DamageTracker for CommandDiff {
22    fn update(&mut self, input: &DisplayList, screen: PhysicalRect, scale: f32, buffer_age: u8) {
23        self.max_age = self.max_age.max(buffer_age).max(1);
24        self.current.clear();
25        if !self.initialized || self.screen != screen {
26            self.current.push(screen);
27            self.history.clear();
28            self.initialized = true;
29        } else {
30            let previous = &self.previous;
31            let mut start = 0;
32            let common = previous.commands().len().min(input.commands().len());
33            while start < common && previous.equivalent(start, input, start) {
34                start += 1;
35            }
36            let mut old_end = previous.commands().len();
37            let mut new_end = input.commands().len();
38            while old_end > start
39                && new_end > start
40                && (old_end > start + 1 || new_end > start + 1)
41                && previous.equivalent(old_end - 1, input, new_end - 1)
42            {
43                old_end -= 1;
44                new_end -= 1;
45            }
46            let mut old = start;
47            let mut new = start;
48            while old < old_end && new < new_end {
49                // the prefix already rejected the initial pair
50                if (old != start || new != start) && previous.equivalent(old, input, new) {
51                    old += 1;
52                    new += 1;
53                    continue;
54                }
55                let mut aligned = false;
56                for offset in 1..=8 {
57                    if new + offset < new_end && previous.equivalent(old, input, new + offset) {
58                        for index in new..new + offset {
59                            push_damage(&mut self.current, clipped_bounds(input, index, scale, screen));
60                        }
61                        new += offset + 1;
62                        old += 1;
63                        aligned = true;
64                        break;
65                    }
66                    if old + offset < old_end && previous.equivalent(old + offset, input, new) {
67                        for index in old..old + offset {
68                            push_damage(&mut self.current, clipped_bounds(previous, index, scale, screen));
69                        }
70                        old += offset + 1;
71                        new += 1;
72                        aligned = true;
73                        break;
74                    }
75                }
76                if aligned {
77                    continue;
78                }
79                let old_bounds = clipped_bounds(previous, old, scale, screen);
80                let new_bounds = clipped_bounds(input, new, scale, screen);
81                push_damage(&mut self.current, old_bounds);
82                if new_bounds != old_bounds {
83                    push_damage(&mut self.current, new_bounds);
84                }
85                old += 1;
86                new += 1;
87            }
88            for index in old..old_end {
89                push_damage(&mut self.current, clipped_bounds(previous, index, scale, screen));
90            }
91            for index in new..new_end {
92                push_damage(&mut self.current, clipped_bounds(input, index, scale, screen));
93            }
94        }
95        self.screen = screen;
96        self.damage.clear();
97        if buffer_age == 0 || self.history.len() < buffer_age.saturating_sub(1) as usize {
98            self.damage.push(screen);
99        } else {
100            self.damage.extend_from_slice(&self.current);
101            for damage in self.history.iter().take(buffer_age.saturating_sub(1) as usize) {
102                self.damage.extend_from_slice(damage);
103            }
104        }
105        self.clips.clear();
106        self.clips.push(screen);
107        for clip in input.clips() {
108            self.clips.push(
109                clip.area
110                    .to_physical(Scale2::uniform(scale))
111                    .intersection(self.clips[clip.parent as usize])
112                    .unwrap_or_default(),
113            );
114        }
115    }
116
117    fn invalidate(&mut self) {
118        self.initialized = false;
119    }
120
121    fn is_empty(&self) -> bool {
122        !self
123            .damage
124            .iter()
125            .any(|bounds| bounds.intersection(self.screen).is_some())
126    }
127
128    fn intersects(&self, bounds: PhysicalRect, clip: u32) -> bool {
129        let Some(bounds) = bounds.intersection(self.clips[clip as usize]) else {
130            return false;
131        };
132        self.damage.iter().any(|damage| bounds.intersection(*damage).is_some())
133    }
134
135    fn line_ranges(&self, line: i32, bounds: PhysicalRect, ranges: &mut Vec<Range<usize>>) -> i32 {
136        ranges.clear();
137        let mut next = bounds.y.saturating_add(bounds.height);
138        let Some(bounds) = bounds.intersection(self.screen) else {
139            return next;
140        };
141        if line < bounds.y || line >= bounds.y + bounds.height {
142            return next;
143        }
144        for damage in &self.damage {
145            let Some(damage) = damage.intersection(bounds) else {
146                continue;
147            };
148            if damage.y > line {
149                next = next.min(damage.y);
150            } else if line < damage.y + damage.height {
151                next = next.min(damage.y + damage.height);
152                ranges.push(damage.x as usize..(damage.x + damage.width) as usize);
153            }
154        }
155        ranges.sort_unstable_by_key(|range| range.start);
156        let mut count = 0;
157        for index in 0..ranges.len() {
158            if count > 0 && ranges[index].start <= ranges[count - 1].end {
159                ranges[count - 1].end = ranges[count - 1].end.max(ranges[index].end);
160            } else {
161                ranges[count] = ranges[index].clone();
162                count += 1;
163            }
164        }
165        ranges.truncate(count);
166        next
167    }
168
169    fn finish_frame(&mut self, rendered: &mut DisplayList) {
170        core::mem::swap(&mut self.previous, rendered);
171        self.history.push_front(core::mem::take(&mut self.current));
172        if self.history.len() >= self.max_age as usize {
173            self.current = self.history.pop_back().unwrap();
174        }
175    }
176}
177
178fn push_damage(damage: &mut Vec<PhysicalRect>, bounds: PhysicalRect) {
179    if bounds.width <= 0 || bounds.height <= 0 {
180        return;
181    }
182    if damage.len() == 32 {
183        for index in 0..16 {
184            damage[index] = damage[index * 2].union(damage[index * 2 + 1]);
185        }
186        damage.truncate(16);
187    }
188    damage.push(bounds);
189}
190
191fn clipped_bounds(list: &DisplayList, index: usize, scale: f32, screen: PhysicalRect) -> PhysicalRect {
192    let command = &list.commands()[index];
193    let mut bounds = command.bounds.intersection(screen);
194    let mut clip = command.clip;
195    while clip != 0 {
196        let parent = &list.clips()[clip as usize - 1];
197        bounds = bounds.and_then(|bounds| bounds.intersection(parent.area.to_physical(Scale2::uniform(scale))));
198        clip = parent.parent;
199    }
200    bounds.unwrap_or_default()
201}