Skip to main content

devpage_design/tiles/
plan.rs

1//! The frame plan: what a browser canvas shows each frame and which tiles
2//! it paints next, for whichever host carries it out — the GPU, painting
3//! each tile into a texture as it is asked, or the page on the CPU, asking
4//! a worker and keeping its bitmaps. The plan holds all of the state that
5//! decides it: the tiles held, least recently used dropped first past a
6//! cap, which damage made stale; the tiles asked for and not yet arrived,
7//! each under a ticket, and whether damage reached it meanwhile. A host
8//! keeps only the paintings, by ticket.
9//!
10//! **One budget rule**: at most a budget of tiles are in flight — asked for
11//! and not yet arrived. The GPU paints what it is asked for at once, so its
12//! budget is the tiles of a frame; the CPU's worker answers later, so a
13//! frame asks only for as many as have arrived since.
14
15use std::collections::HashMap;
16use std::sync::atomic::{AtomicU32, Ordering};
17
18use kurbo::Rect as KRect;
19
20use crate::scene::Theme;
21
22use super::*;
23
24/// What a host knows a painting by: given when a tile is asked for, never
25/// given again by any plan, so an answer for the design a canvas showed
26/// before matches nothing.
27pub type Ticket = u32;
28
29/// The most tiles a canvas holds: more than a 4K screen at a device pixel
30/// ratio of 2 shows, about 160, so a view never evicts its own.
31pub const CAP: usize = 384;
32
33/// The most tiles a canvas has in flight at once.
34pub const BUDGET: usize = 6;
35
36/// The next ticket; 0 is never given.
37static NEXT: AtomicU32 = AtomicU32::new(1);
38
39/// A tile asked for and not yet arrived.
40struct Asked {
41    /// The tile asked for — its theme, level, column and row — which damage
42    /// is checked against.
43    key: Key,
44    /// Damage reached it after it was asked for: what arrives is stale.
45    stale: bool,
46}
47
48/// One canvas's frame plan.
49pub struct Plan {
50    /// The tiles held, each by the ticket its painting arrived under.
51    held: Cache<Ticket>,
52    /// The tiles in flight, by ticket.
53    asked: HashMap<Ticket, Asked>,
54    /// The most tiles in flight at once.
55    budget: usize,
56    /// Paintings let go since the last frame.
57    evicted: Vec<Ticket>,
58}
59
60/// A frame's work: the paintings to draw, bottom first, each where it lands in
61/// the view, in device pixels; the tiles to paint next, each under its
62/// ticket; the paintings to free; and how many tiles of the view at its own
63/// level are missing or stale — 0 when the frame shows the view current.
64#[derive(Debug)]
65pub struct Work {
66    /// The paintings to draw, bottom first, each where it lands in the view, in
67    /// device pixels.
68    pub draw: Vec<(Ticket, KRect)>,
69    /// The tiles to paint next, each under its ticket.
70    pub request: Vec<(Ticket, Key)>,
71    /// The paintings to free: let go since the last frame, their tickets
72    /// never given again.
73    pub evict: Vec<Ticket>,
74    /// How many tiles of the view at its own level are missing or stale: 0 when
75    /// the frame shows the view current.
76    pub missing: usize,
77}
78
79/// What became of a painting that arrived.
80#[derive(Clone, Copy, PartialEq, Eq, Debug)]
81pub enum Arrival {
82    /// Its ticket isn't one in flight: the host frees it.
83    Dropped,
84    /// Held, current.
85    Current,
86    /// Held and shown, but damage reached its tile while it was painted: it
87    /// is asked for again.
88    Stale,
89}
90
91impl Plan {
92    /// A plan holding at most `cap` tiles, with at most `budget` in flight.
93    pub fn new(cap: usize, budget: usize) -> Plan {
94        Plan {
95            held: Cache::new(cap),
96            asked: HashMap::new(),
97            budget,
98            evicted: Vec::new(),
99        }
100    }
101
102    /// Marks stale every tile of `theme`, held or in flight, that overlaps
103    /// one of `rects` — in the design's coordinates, the drawing's top-left
104    /// at `origin` — at every level.
105    pub fn damage(&mut self, theme: Theme, origin: (f64, f64), rects: &[KRect]) {
106        self.held.damage(theme, origin, rects);
107        for asked in self.asked.values_mut() {
108            if asked.key.theme == theme && asked.key.overlaps(origin, rects) {
109                asked.stale = true;
110            }
111        }
112    }
113
114    /// Marks every tile of `theme`, held or in flight, stale.
115    pub fn damage_all(&mut self, theme: Theme) {
116        self.held.damage_all(theme);
117        for asked in self.asked.values_mut() {
118            if asked.key.theme == theme {
119                asked.stale = true;
120            }
121        }
122    }
123
124    /// The frame of `view` of the drawing `area` in `theme`, which `needed`
125    /// — the tiles the view needs at its own level, nearest its middle first
126    /// — makes current. Every held tile of the theme the view shows is
127    /// drawn, as a stand-in where it is stale or at another level; once a
128    /// zoom has `settled`, the missing and stale tiles are asked for in
129    /// `needed`'s order while fewer than the budget are in flight.
130    pub fn frame(
131        &mut self,
132        theme: Theme,
133        area: KRect,
134        view: &View,
135        needed: &[(u32, u32)],
136        settled: bool,
137    ) -> Work {
138        let level = Level::of(view.zoom);
139        let missing: Vec<Key> = needed
140            .iter()
141            .map(|&(col, row)| Key {
142                theme,
143                level,
144                col,
145                row,
146            })
147            // Each tile the view needs counts as used.
148            .filter(|k| self.held.get(k).is_none_or(|(_, stale)| stale))
149            .collect();
150        let mut draw: Vec<(Level, Ticket, KRect)> = self
151            .held
152            .iter()
153            .filter(|(k, _, _)| k.theme == theme)
154            .filter_map(|(k, &ticket, _)| Some((k.level, ticket, view.place(area, k)?)))
155            .collect();
156        draw.sort_by_key(|&(l, _, _)| (l == level, l.0));
157        let mut request = Vec::new();
158        if settled {
159            for &key in &missing {
160                if self.asked.len() >= self.budget {
161                    break;
162                }
163                if self.asked.values().any(|a| a.key == key) {
164                    continue;
165                }
166                let ticket = NEXT.fetch_add(1, Ordering::Relaxed);
167                self.asked.insert(ticket, Asked { key, stale: false });
168                request.push((ticket, key));
169            }
170        }
171        Work {
172            draw: draw.into_iter().map(|(_, t, r)| (t, r)).collect(),
173            request,
174            evict: std::mem::take(&mut self.evicted),
175            missing: missing.len(),
176        }
177    }
178
179    /// The painting asked for under `ticket` has arrived: held in place of
180    /// the tile's last, which is let go, as are the least recently used past
181    /// the cap — or dropped, when the ticket isn't one in flight.
182    pub fn arrived(&mut self, ticket: Ticket) -> Arrival {
183        let Some(Asked { key, stale }) = self.asked.remove(&ticket) else {
184            return Arrival::Dropped;
185        };
186        self.evicted.extend(self.held.remove(&key));
187        let dropped = self.held.insert(key, ticket, 1);
188        self.evicted.extend(dropped.into_iter().map(|(_, t)| t));
189        if stale {
190            self.held.damage_all_where(|k| *k == key);
191            Arrival::Stale
192        } else {
193            Arrival::Current
194        }
195    }
196
197    /// The tile asked for under `ticket` was painted as nothing — the scene
198    /// couldn't be drawn when it was asked of — so it is no longer in
199    /// flight, and is asked for again.
200    pub fn missed(&mut self, ticket: Ticket) {
201        self.asked.remove(&ticket);
202    }
203}
204
205#[cfg(test)]
206mod tests;