Skip to main content

gpui/
vn_effect_history.rs

1//! vue-native: the state of `[SkHistory]` effects, which a renderer keeps from
2//! frame to frame per [`crate::VnEffectDraw::history`] key: two textures the
3//! size of the drawn quad, one holding the last state while the other takes
4//! the next.
5
6use std::collections::HashMap;
7
8/// Bytes per history texel: RGBA, each a 16-bit float.
9pub const VN_HISTORY_TEXEL_BYTES: u64 = 8;
10/// A quad longer than this on a side, in device pixels, gets no history.
11pub const VN_HISTORY_MAX_SIDE: u32 = 4096;
12/// What the histories of one window may hold together, both textures counted.
13pub const VN_HISTORY_BUDGET_BYTES: u64 = 256 << 20;
14/// The shortest time between two steps of one history, so a simulation runs
15/// at about the same speed on a 60 Hz and a 144 Hz display.
16pub const VN_HISTORY_MIN_STEP_SECONDS: f32 = 1. / 75.;
17
18/// One renderer's histories; `T` is its texture handle.
19pub struct VnEffectHistories<T> {
20    entries: HashMap<u64, Entry<T>>,
21    bytes: u64,
22}
23
24struct Entry<T> {
25    size: (u32, u32),
26    textures: [T; 2],
27    /// The texture holding the last state.
28    read: usize,
29    last_step: f32,
30    used: bool,
31    stepped: bool,
32}
33
34/// One history in this frame.
35pub struct VnHistory<T> {
36    /// The state the effect reads, as the last step left it.
37    pub read: T,
38    /// The texture this frame's step writes, when the history steps.
39    pub write: Option<T>,
40    /// Both textures were just made and must be cleared to zero first.
41    pub fresh: bool,
42}
43
44impl<T> Default for VnEffectHistories<T> {
45    fn default() -> Self {
46        Self {
47            entries: HashMap::new(),
48            bytes: 0,
49        }
50    }
51}
52
53impl<T: Clone> VnEffectHistories<T> {
54    /// The history for `key` at `size`, made with `create` when it is new or
55    /// its size changed (which starts it over). None for key 0, a quad too
56    /// large, a full budget, or a texture `create` could not make.
57    pub fn prepare(
58        &mut self,
59        key: u64,
60        size: (u32, u32),
61        now: f32,
62        mut create: impl FnMut(u32, u32) -> Option<T>,
63    ) -> Option<VnHistory<T>> {
64        let (width, height) = size;
65        if key == 0 || width == 0 || height == 0 {
66            return None;
67        }
68        if width > VN_HISTORY_MAX_SIDE || height > VN_HISTORY_MAX_SIDE {
69            advisory(format!(
70                "an `[SkHistory]` effect on an element larger than {VN_HISTORY_MAX_SIDE} device \
71                 pixels on a side keeps no history; it reads zeros there"
72            ));
73            return None;
74        }
75        if self
76            .entries
77            .get(&key)
78            .is_some_and(|entry| entry.size != size)
79        {
80            self.remove(key);
81        }
82        let mut fresh = false;
83        if !self.entries.contains_key(&key) {
84            let cost = 2 * u64::from(width) * u64::from(height) * VN_HISTORY_TEXEL_BYTES;
85            if self.bytes + cost > VN_HISTORY_BUDGET_BYTES {
86                advisory(format!(
87                    "`[SkHistory]` effects in one window are limited to {} MiB of history; \
88                     the ones past it read zeros",
89                    VN_HISTORY_BUDGET_BYTES >> 20
90                ));
91                return None;
92            }
93            let textures = [create(width, height)?, create(width, height)?];
94            self.entries.insert(
95                key,
96                Entry {
97                    size,
98                    textures,
99                    read: 0,
100                    last_step: f32::NEG_INFINITY,
101                    used: false,
102                    stepped: false,
103                },
104            );
105            self.bytes += cost;
106            fresh = true;
107        }
108        let entry = self.entries.get_mut(&key)?;
109        entry.used = true;
110        let step = !entry.stepped
111            && (fresh
112                || now - entry.last_step >= VN_HISTORY_MIN_STEP_SECONDS
113                || now < entry.last_step);
114        if step {
115            entry.stepped = true;
116            entry.last_step = now;
117        }
118        Some(VnHistory {
119            read: entry.textures[entry.read].clone(),
120            write: step.then(|| entry.textures[1 - entry.read].clone()),
121            fresh,
122        })
123    }
124
125    /// Ends a frame: a history that stepped reads its new state from now on,
126    /// and one the frame did not draw is freed.
127    pub fn finish_frame(&mut self) {
128        let mut freed = 0;
129        self.entries.retain(|_, entry| {
130            if !entry.used {
131                freed +=
132                    2 * u64::from(entry.size.0) * u64::from(entry.size.1) * VN_HISTORY_TEXEL_BYTES;
133                return false;
134            }
135            if entry.stepped {
136                entry.read = 1 - entry.read;
137            }
138            entry.used = false;
139            entry.stepped = false;
140            true
141        });
142        self.bytes -= freed;
143    }
144
145    /// Drops every history (a lost device).
146    pub fn clear(&mut self) {
147        self.entries.clear();
148        self.bytes = 0;
149    }
150
151    /// The bytes the histories hold.
152    pub fn bytes(&self) -> u64 {
153        self.bytes
154    }
155
156    /// How many histories are held.
157    pub fn len(&self) -> usize {
158        self.entries.len()
159    }
160
161    /// Whether none is held.
162    pub fn is_empty(&self) -> bool {
163        self.entries.is_empty()
164    }
165
166    fn remove(&mut self, key: u64) {
167        if let Some(entry) = self.entries.remove(&key) {
168            self.bytes -=
169                2 * u64::from(entry.size.0) * u64::from(entry.size.1) * VN_HISTORY_TEXEL_BYTES;
170        }
171    }
172}
173
174fn advisory(message: String) {
175    use parking_lot::Mutex;
176    static SEEN: Mutex<Vec<String>> = Mutex::new(Vec::new());
177    let mut seen = SEEN.lock();
178    if seen.contains(&message) {
179        return;
180    }
181    log::warn!("{message}");
182    eprintln!("skathi: {message}");
183    seen.push(message);
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn a_history_ping_pongs_steps_at_most_at_the_step_rate_and_frees_when_not_drawn() {
192        let mut made = 0;
193        let mut histories = VnEffectHistories::default();
194        let mut create = |_, _| {
195            made += 1;
196            Some(made)
197        };
198        let first = histories.prepare(7, (4, 4), 1.0, &mut create).unwrap();
199        assert!(first.fresh);
200        assert_eq!((first.read, first.write), (1, Some(2)));
201        histories.finish_frame();
202
203        let soon = histories.prepare(7, (4, 4), 1.001, &mut create).unwrap();
204        assert_eq!(
205            (soon.read, soon.write),
206            (2, None),
207            "reads the step it wrote"
208        );
209        histories.finish_frame();
210
211        let later = histories.prepare(7, (4, 4), 1.1, &mut create).unwrap();
212        assert_eq!((later.read, later.write), (2, Some(1)));
213        histories.finish_frame();
214
215        let resized = histories.prepare(7, (5, 4), 1.2, &mut create).unwrap();
216        assert!(resized.fresh, "a new size starts over");
217        assert_eq!(histories.bytes(), 2 * 5 * 4 * VN_HISTORY_TEXEL_BYTES);
218        histories.finish_frame();
219
220        histories.finish_frame();
221        assert!(histories.is_empty(), "a frame without it frees it");
222        assert_eq!(histories.bytes(), 0);
223    }
224
225    #[test]
226    fn a_history_past_the_budget_or_the_side_limit_is_refused() {
227        let mut histories = VnEffectHistories::default();
228        let side = VN_HISTORY_MAX_SIDE;
229        assert!(
230            histories
231                .prepare(1, (side + 1, 1), 0., |_, _| Some(()))
232                .is_none()
233        );
234        assert!(
235            histories
236                .prepare(1, (side, side), 0., |_, _| Some(()))
237                .is_some()
238        );
239        assert!(
240            histories.prepare(2, (1, 1), 0., |_, _| Some(())).is_none(),
241            "a 4096² history fills the budget"
242        );
243        assert!(histories.prepare(0, (1, 1), 0., |_, _| Some(())).is_none());
244    }
245}