Skip to main content

egui/
layers.rs

1//! Handles paint layers, i.e. how things
2//! are sometimes painted behind or in front of other things.
3
4use crate::{Id, IdMap, Rect, epaint};
5use epaint::{ClippedShape, Shape, emath::TSTransform};
6
7/// Different layer categories
8#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
9#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
10pub enum Order {
11    /// Painted behind all floating windows
12    Background,
13
14    /// Normal moveable windows that you reorder by click
15    Middle,
16
17    /// Popups, menus etc that should always be painted on top of windows
18    /// Foreground objects can also have tooltips
19    Foreground,
20
21    /// Things floating on top of everything else, like tooltips.
22    /// You cannot interact with these.
23    Tooltip,
24
25    /// Debug layer, always painted last / on top
26    Debug,
27}
28
29impl Order {
30    const COUNT: usize = 5;
31    const ALL: [Self; Self::COUNT] = [
32        Self::Background,
33        Self::Middle,
34        Self::Foreground,
35        Self::Tooltip,
36        Self::Debug,
37    ];
38    pub const TOP: Self = Self::Debug;
39
40    #[inline(always)]
41    pub fn allow_interaction(&self) -> bool {
42        match self {
43            Self::Background | Self::Middle | Self::Foreground | Self::Tooltip | Self::Debug => {
44                true
45            }
46        }
47    }
48
49    /// Short and readable summary
50    pub fn short_debug_format(&self) -> &'static str {
51        match self {
52            Self::Background => "backg",
53            Self::Middle => "middl",
54            Self::Foreground => "foreg",
55            Self::Tooltip => "toolt",
56            Self::Debug => "debug",
57        }
58    }
59}
60
61/// An identifier for a paint layer.
62/// Also acts as an identifier for [`crate::Area`]:s.
63#[derive(Clone, Copy, Hash, Eq, PartialEq)]
64#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
65pub struct LayerId {
66    pub order: Order,
67    pub id: Id,
68}
69
70impl LayerId {
71    pub fn new(order: Order, id: Id) -> Self {
72        Self { order, id }
73    }
74
75    pub fn debug() -> Self {
76        Self {
77            order: Order::Debug,
78            id: Id::new("debug"),
79        }
80    }
81
82    pub fn background() -> Self {
83        Self {
84            order: Order::Background,
85            id: Id::new("background"),
86        }
87    }
88
89    /// Short and readable summary
90    pub fn short_debug_format(&self) -> String {
91        format!(
92            "{} {}",
93            self.order.short_debug_format(),
94            self.id.short_debug_format()
95        )
96    }
97}
98
99impl core::fmt::Debug for LayerId {
100    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
101        let Self { order, id } = self;
102        write!(f, "LayerId {{ {order:?} {id:?} }}")
103    }
104}
105
106/// A unique identifier of a specific [`Shape`] in a [`PaintList`].
107
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub struct ShapeIdx(pub usize);
110
111/// A list of [`Shape`]s paired with a clip rectangle.
112#[derive(Clone, Default)]
113pub struct PaintList(Vec<ClippedShape>);
114
115impl PaintList {
116    #[inline(always)]
117    pub fn is_empty(&self) -> bool {
118        self.0.is_empty()
119    }
120
121    pub fn next_idx(&self) -> ShapeIdx {
122        ShapeIdx(self.0.len())
123    }
124
125    /// Returns the index of the new [`Shape`] that can be used with `PaintList::set`.
126    #[inline(always)]
127    pub fn add(&mut self, clip_rect: Rect, shape: Shape) -> ShapeIdx {
128        let idx = self.next_idx();
129        self.0.push(ClippedShape { clip_rect, shape });
130        idx
131    }
132
133    pub fn extend<I: IntoIterator<Item = Shape>>(&mut self, clip_rect: Rect, shapes: I) {
134        self.0.extend(
135            shapes
136                .into_iter()
137                .map(|shape| ClippedShape { clip_rect, shape }),
138        );
139    }
140
141    /// Modify an existing [`Shape`].
142    ///
143    /// Sometimes you want to paint a frame behind some contents, but don't know how large the frame needs to be
144    /// until the contents have been added, and therefor also painted to the [`PaintList`].
145    ///
146    /// The solution is to allocate a [`Shape`] using `let idx = paint_list.add(cr, Shape::Noop);`
147    /// and then later setting it using `paint_list.set(idx, cr, frame);`.
148    #[inline(always)]
149    pub fn set(&mut self, idx: ShapeIdx, clip_rect: Rect, shape: Shape) {
150        if self.0.len() <= idx.0 {
151            log::warn!("Index {} is out of bounds for PaintList", idx.0);
152            return;
153        }
154
155        self.0[idx.0] = ClippedShape { clip_rect, shape };
156    }
157
158    /// Set the given shape to be empty (a `Shape::Noop`).
159    #[inline(always)]
160    pub fn reset_shape(&mut self, idx: ShapeIdx) {
161        self.0[idx.0].shape = Shape::Noop;
162    }
163
164    /// Mutate the shape at the given index, if any.
165    pub fn mutate_shape(&mut self, idx: ShapeIdx, f: impl FnOnce(&mut ClippedShape)) {
166        self.0.get_mut(idx.0).map(f);
167    }
168
169    /// Transform each [`Shape`] and clip rectangle by this much, in-place
170    pub fn transform(&mut self, transform: TSTransform) {
171        for ClippedShape { clip_rect, shape } in &mut self.0 {
172            *clip_rect = transform.mul_rect(*clip_rect);
173            shape.transform(transform);
174        }
175    }
176
177    /// Transform each [`Shape`] and clip rectangle in range by this much, in-place
178    pub fn transform_range(&mut self, start: ShapeIdx, end: ShapeIdx, transform: TSTransform) {
179        for ClippedShape { clip_rect, shape } in &mut self.0[start.0..end.0] {
180            *clip_rect = transform.mul_rect(*clip_rect);
181            shape.transform(transform);
182        }
183    }
184
185    /// Read-only access to all held shapes.
186    pub fn all_entries(&self) -> impl ExactSizeIterator<Item = &ClippedShape> {
187        self.0.iter()
188    }
189}
190
191/// This is where painted [`Shape`]s end up during a frame.
192#[derive(Clone, Default)]
193pub struct GraphicLayers([IdMap<PaintList>; Order::COUNT]);
194
195impl GraphicLayers {
196    /// Get or insert the [`PaintList`] for the given [`LayerId`].
197    pub fn entry(&mut self, layer_id: LayerId) -> &mut PaintList {
198        self.0[layer_id.order as usize]
199            .entry(layer_id.id)
200            .or_default()
201    }
202
203    /// Get the [`PaintList`] for the given [`LayerId`].
204    pub fn get(&self, layer_id: LayerId) -> Option<&PaintList> {
205        self.0[layer_id.order as usize].get(&layer_id.id)
206    }
207
208    /// Get the [`PaintList`] for the given [`LayerId`].
209    pub fn get_mut(&mut self, layer_id: LayerId) -> Option<&mut PaintList> {
210        self.0[layer_id.order as usize].get_mut(&layer_id.id)
211    }
212
213    pub fn drain(
214        &mut self,
215        area_order: &[LayerId],
216        to_global: &ahash::HashMap<LayerId, TSTransform>,
217    ) -> Vec<ClippedShape> {
218        profiling::function_scope!();
219
220        let mut all_shapes: Vec<_> = Default::default();
221
222        for &order in &Order::ALL {
223            let order_map = &mut self.0[order as usize];
224
225            // If a layer is empty at the start of the frame
226            // then nobody has added to it, and it is old and defunct.
227            // Free it to save memory:
228            order_map.retain(|_, list| !list.is_empty());
229
230            // First do the layers part of area_order:
231            for layer_id in area_order {
232                if layer_id.order == order
233                    && let Some(list) = order_map.get_mut(&layer_id.id)
234                {
235                    if let Some(to_global) = to_global.get(layer_id) {
236                        for clipped_shape in &mut list.0 {
237                            clipped_shape.transform(*to_global);
238                        }
239                    }
240                    all_shapes.append(&mut list.0);
241                }
242            }
243
244            // Also draw areas that are missing in `area_order`:
245            // NOTE: We don't think we end up here in normal situations.
246            // This is just a safety net in case we have some bug somewhere.
247            #[expect(clippy::iter_over_hash_type)]
248            for (id, list) in order_map {
249                let layer_id = LayerId::new(order, *id);
250
251                if let Some(to_global) = to_global.get(&layer_id) {
252                    for clipped_shape in &mut list.0 {
253                        clipped_shape.transform(*to_global);
254                    }
255                }
256
257                all_shapes.append(&mut list.0);
258            }
259        }
260
261        all_shapes
262    }
263}