Skip to main content

gpui_base/plot/
path_cache.rs

1use std::hash::{DefaultHasher, Hash, Hasher};
2
3use gpui::{App, ElementId, Entity, Path, Pixels, Point, Window};
4
5/// A tessellated path reused across frames while its shape is unchanged.
6///
7/// A chart repaints on every frame it is on screen — a scrolling list moves
8/// it — and tessellating its strokes (Catmull-Rom curves, dashes) is the bulk
9/// of that work, while the vertices only depend on the projected points
10/// relative to the chart's origin. A plot keeps one cache per shape and paints
11/// through [`Line::paint_cached`](super::shape::Line::paint_cached) or
12/// [`Area::paint_cached`](super::shape::Area::paint_cached): the path is built
13/// once per shape key, at a zero origin, and moved to the frame's origin on
14/// every paint.
15#[derive(Default)]
16pub struct PathCache {
17    key: Option<u64>,
18    /// Built relative to a zero origin.
19    path: Option<Path>,
20}
21
22impl PathCache {
23    /// The path for `key` at `origin`. `build` runs only when the key or the
24    /// origin differs from the last call's; it must build at `origin`.
25    ///
26    /// A finished [`Path`] can no longer be moved, so a path is reused only
27    /// while the shape stays at the same origin.
28    pub fn get(
29        &mut self,
30        key: u64,
31        origin: Point<Pixels>,
32        build: impl FnOnce() -> Option<Path>,
33    ) -> Option<Path> {
34        let mut hasher = DefaultHasher::new();
35        key.hash(&mut hasher);
36        origin.x.as_f32().to_bits().hash(&mut hasher);
37        origin.y.as_f32().to_bits().hash(&mut hasher);
38        let key = hasher.finish();
39        if self.key != Some(key) {
40            self.path = build();
41            self.key = Some(key);
42        }
43        self.path.clone()
44    }
45
46    /// Whether the last [`Self::get`] reused the path built by an earlier one.
47    pub fn is_warm(&self) -> bool {
48        self.key.is_some()
49    }
50}
51
52/// The [`PathCache`]s of a plot that is rebuilt on every render, kept in the
53/// window's element state so they outlive the plot value.
54///
55/// Plots are plain values built by `render` and painted once, so a cache
56/// held by the plot would be empty every frame; this keeps them under the
57/// element id the plot paints in (plus `key`), for as long as the plot is
58/// painted on consecutive frames.
59///
60/// ```ignore
61/// fn paint(&mut self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
62///     let caches = PathCaches::for_paint("lines", window, cx);
63///     caches.update(cx, |caches, _| {
64///         for (ix, line) in lines.iter().enumerate() {
65///             line.paint_cached(&bounds, caches.slot(ix), window);
66///         }
67///     });
68/// }
69/// ```
70#[derive(Default)]
71pub struct PathCaches {
72    slots: Vec<PathCache>,
73}
74
75impl PathCaches {
76    /// The caches for the plot painting under the window's current element
77    /// id; `key` tells apart several groups of shapes in one plot.
78    pub fn for_paint(key: impl Into<ElementId>, window: &mut Window, cx: &mut App) -> Entity<Self> {
79        window.use_keyed_state(key, cx, |_, _| Self::default())
80    }
81
82    /// The `index`-th cache, created on first use. Paint each shape through
83    /// the same index every frame.
84    pub fn slot(&mut self, index: usize) -> &mut PathCache {
85        if self.slots.len() <= index {
86            self.slots.resize_with(index + 1, PathCache::default);
87        }
88        &mut self.slots[index]
89    }
90
91    /// Two caches for a shape that keeps a fill and a stroke, such as
92    /// [`Area::paint_cached`](super::shape::Area::paint_cached), at
93    /// `2 * index` and `2 * index + 1`.
94    pub fn slot_pair(&mut self, index: usize) -> (&mut PathCache, &mut PathCache) {
95        let first = 2 * index;
96        if self.slots.len() <= first + 1 {
97            self.slots.resize_with(first + 2, PathCache::default);
98        }
99        let (head, tail) = self.slots.split_at_mut(first + 1);
100        (&mut head[first], &mut tail[0])
101    }
102}
103
104/// A shape key from its projected points (origin-relative) and whatever else
105/// shapes the tessellation (stroke width, curve style, dash pattern).
106pub struct ShapeKey(DefaultHasher);
107
108impl ShapeKey {
109    pub fn new(extra: impl Hash) -> Self {
110        let mut hasher = DefaultHasher::new();
111        extra.hash(&mut hasher);
112        Self(hasher)
113    }
114
115    pub fn point(&mut self, point: Point<Pixels>) -> &mut Self {
116        point.x.as_f32().to_bits().hash(&mut self.0);
117        point.y.as_f32().to_bits().hash(&mut self.0);
118        self
119    }
120
121    pub fn f32(&mut self, value: f32) -> &mut Self {
122        value.to_bits().hash(&mut self.0);
123        self
124    }
125
126    pub fn finish(&self) -> u64 {
127        self.0.finish()
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use gpui::{PathBuilder, point, px};
135
136    fn diagonal() -> Option<Path> {
137        let mut builder = PathBuilder::stroke(px(2.));
138        builder.move_to(point(px(0.), px(0.)));
139        builder.line_to(point(px(10.), px(10.)));
140        builder.build().ok()
141    }
142
143    #[test]
144    fn builds_once_per_key_and_origin() {
145        let mut cache = PathCache::default();
146        let mut builds = 0;
147        let origin = point(px(100.), px(50.));
148        cache.get(1, origin, || {
149            builds += 1;
150            diagonal()
151        });
152        assert!(
153            cache
154                .get(1, origin, || {
155                    builds += 1;
156                    diagonal()
157                })
158                .is_some()
159        );
160        assert_eq!(builds, 1);
161
162        cache.get(1, point(px(200.), px(50.)), || {
163            builds += 1;
164            diagonal()
165        });
166        assert_eq!(builds, 2);
167
168        cache.get(2, point(px(200.), px(50.)), || {
169            builds += 1;
170            diagonal()
171        });
172        assert_eq!(builds, 3);
173    }
174
175    #[test]
176    fn keys_follow_points_and_extras() {
177        let a = ShapeKey::new(("linear", 1.0f32.to_bits()))
178            .point(point(px(1.), px(2.)))
179            .finish();
180        let same = ShapeKey::new(("linear", 1.0f32.to_bits()))
181            .point(point(px(1.), px(2.)))
182            .finish();
183        let moved = ShapeKey::new(("linear", 1.0f32.to_bits()))
184            .point(point(px(1.), px(3.)))
185            .finish();
186        let thicker = ShapeKey::new(("linear", 2.0f32.to_bits()))
187            .point(point(px(1.), px(2.)))
188            .finish();
189        assert_eq!(a, same);
190        assert_ne!(a, moved);
191        assert_ne!(a, thicker);
192    }
193}