Skip to main content

mln_engine/image/
image_store.rs

1// The style's images, on the render thread, owned by the orchestrator. Tiles
2// don't register with it: a tile waiting for images asks it to `resolve`
3// them again after it changes (`revision`). An image missing once the sprite
4// loaded is asked for with `styleimagemissing`, and resolves as missing in
5// the next update, once the app has had its frame to add it.
6
7use std::sync::Arc;
8
9use mln_style::collections::{VecMap, VecSet};
10use mln_style::hash::{HashMap, HashSet};
11use mln_style::image::StyleImage;
12
13use crate::log_target;
14use crate::render::events::RendererEvent;
15
16/// How many bytes of the images an app adds for
17/// [`RendererEvent::StyleImageMissing`] the store holds before it asks for
18/// unused ones to go. An average sprite image is about 2 kB at pixel ratio
19/// 1, and 8 kB at 2.
20pub(crate) const DEFAULT_ON_DEMAND_IMAGES_CACHE_SIZE: usize = 100 * 8192;
21
22/// What a layout uses an image as.
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, mln_wire::Wire)]
24pub enum ImageType {
25    Icon,
26    Pattern,
27}
28
29/// Images by id.
30///
31/// A `VecMap` rather than a `HashMap`:
32/// `DynamicTextureAtlas::upload_icons_and_patterns` reserves atlas space in
33/// iteration order, and a `HashMap`'s order changes from process to process,
34/// which would move icons in the atlas and change rendered pixels between runs.
35pub(crate) type ImageMap = VecMap<String, Arc<StyleImage>>;
36
37/// The images that a layout uses, by id.
38pub(crate) type ImageDependencies = HashMap<String, ImageType>;
39
40/// One wait for images, across the resolves it takes.
41#[derive(Clone, Copy, Debug, Default)]
42pub(crate) struct ImageWait {
43    /// The update in which the wait found images missing and asked for them.
44    asked: Option<u64>,
45}
46
47/// What a tile's image dependencies resolved to. A requested image absent
48/// from both is missing.
49pub(crate) struct ResolvedImages {
50    pub(crate) icons: ImageMap,
51    pub(crate) patterns: ImageMap,
52}
53
54pub struct ImageStore {
55    /// Whether the sprite loaded: before, a missing image may still come
56    /// with it.
57    loaded: bool,
58    images: ImageMap,
59    /// The keys of `images`.
60    available_images: Arc<VecSet<String>>,
61    /// The images asked for with `styleimagemissing`, which the app may add
62    /// and the store asks it to remove once no tile uses them.
63    requested: VecSet<String>,
64    /// The bytes of the requested images the app added.
65    requested_images_cache_size: usize,
66    /// The update each image was last asked for in.
67    asked: VecMap<String, u64>,
68    /// The orchestrator's updates, counted.
69    update: u64,
70    /// Whether this update asked for an image.
71    asked_this_update: bool,
72    revision: u64,
73    /// What the store reported since the last `take_events`: the images it
74    /// asked the app for and the ones it asks the app to remove.
75    events: Vec<RendererEvent>,
76}
77
78impl Default for ImageStore {
79    fn default() -> Self {
80        ImageStore {
81            loaded: false,
82            images: ImageMap::new(),
83            available_images: Arc::default(),
84            requested: VecSet::new(),
85            requested_images_cache_size: 0,
86            asked: VecMap::new(),
87            update: 0,
88            asked_this_update: false,
89            revision: 0,
90            events: Vec::new(),
91        }
92    }
93}
94
95impl ImageStore {
96    /// What the store reported since the last call, oldest first.
97    pub(crate) fn take_events(&mut self) -> Vec<RendererEvent> {
98        std::mem::take(&mut self.events)
99    }
100
101    /// Changes whenever a resolve that waited could now give another answer.
102    pub(crate) fn revision(&self) -> u64 {
103        self.revision
104    }
105
106    /// Starts an update: the images asked for in the last one now resolve as
107    /// missing if the app didn't add them.
108    pub(crate) fn begin_update(&mut self) {
109        self.update += 1;
110        if std::mem::take(&mut self.asked_this_update) {
111            self.revision += 1;
112        }
113    }
114
115    pub(crate) fn set_loaded(&mut self, loaded: bool) {
116        if self.loaded != loaded {
117            self.loaded = loaded;
118            self.revision += 1;
119        }
120    }
121
122    pub(crate) fn is_loaded(&self) -> bool {
123        self.loaded
124    }
125
126    pub(crate) fn dump_debug_logs(&self) {
127        tracing::info!(target: log_target::GENERAL, "Images: loaded {}", self.is_loaded());
128    }
129
130    #[must_use]
131    pub fn image(&self, id: &str) -> Option<&Arc<StyleImage>> {
132        self.images.get(id)
133    }
134
135    pub(crate) fn available_images(&self) -> &Arc<VecSet<String>> {
136        &self.available_images
137    }
138
139    pub(crate) fn add_image(&mut self, image: Arc<StyleImage>) {
140        debug_assert!(!self.images.contains_key(&image.id));
141        if self.requested.contains(&image.id) {
142            self.requested_images_cache_size += image.image.bytes();
143        }
144        Arc::make_mut(&mut self.available_images).insert(image.id.clone());
145        self.images.entry(image.id.clone()).or_insert(image);
146        self.revision += 1;
147    }
148
149    /// Replaces an image; true when the tiles that use it need a relayout:
150    /// its size or SDF flag changed. Otherwise the atlas patches its bins.
151    pub(crate) fn update_image(&mut self, image: Arc<StyleImage>) -> bool {
152        let Some(old_image) = self.images.get(&image.id) else {
153            debug_assert!(false);
154            return false;
155        };
156        let size_changed = old_image.image.size != image.image.size;
157        let sdf_changed = old_image.sdf != image.sdf;
158        if size_changed && self.requested.contains(&image.id) {
159            self.requested_images_cache_size =
160                self.requested_images_cache_size - old_image.image.bytes() + image.image.bytes();
161        }
162        self.images.insert(image.id.clone(), image);
163        self.revision += 1;
164        size_changed || sdf_changed
165    }
166
167    pub(crate) fn remove_image(&mut self, id: &str) {
168        let Some(image) = self.images.remove(id) else {
169            debug_assert!(false);
170            return;
171        };
172        if self.requested.remove(id) {
173            self.requested_images_cache_size -= image.image.bytes();
174        }
175        Arc::make_mut(&mut self.available_images).remove(id);
176        self.revision += 1;
177    }
178
179    /// The images of `wants`, once each is there or known missing. Until
180    /// then `None`: before the sprite loads, a missing image may still come
181    /// with it; after, the store asks for it and waits an update for the app
182    /// to add it.
183    pub(crate) fn resolve(&mut self, wants: &ImageDependencies, wait: &mut ImageWait) -> Option<ResolvedImages> {
184        let mut missing: Vec<&String> = wants.keys().filter(|id| !self.images.contains_key(*id)).collect();
185        if !missing.is_empty() {
186            if !self.loaded {
187                return None;
188            }
189            match wait.asked {
190                // The app had its update to add them.
191                Some(asked) if asked < self.update => {}
192                Some(_) => return None,
193                None => {
194                    missing.sort_unstable();
195                    for id in missing {
196                        self.requested.insert(id.clone());
197                        // Once per update, however many tiles miss it.
198                        if self.asked.insert(id.clone(), self.update) != Some(self.update) {
199                            self.events.push(RendererEvent::StyleImageMissing(id.clone()));
200                        }
201                    }
202                    wait.asked = Some(self.update);
203                    self.asked_this_update = true;
204                    return None;
205                }
206            }
207        }
208
209        let mut resolved = ResolvedImages { icons: ImageMap::new(), patterns: ImageMap::new() };
210        for (id, kind) in wants {
211            if let Some(image) = self.images.get(id) {
212                let images = match kind {
213                    ImageType::Icon => &mut resolved.icons,
214                    ImageType::Pattern => &mut resolved.patterns,
215                };
216                images.insert(id.clone(), Arc::clone(image));
217            }
218        }
219        Some(resolved)
220    }
221
222    /// Asks the app to remove the requested images that it added and that
223    /// no tile uses: none of `used`.
224    pub(crate) fn reduce_memory_use(&mut self, used: &HashSet<String>) {
225        let unused: Vec<String> =
226            self.requested.iter().filter(|id| self.images.contains_key(*id) && !used.contains(*id)).cloned().collect();
227        if !unused.is_empty() {
228            self.events.push(RendererEvent::UnusedStyleImages(unused));
229        }
230    }
231
232    /// Whether the requested images the app added take more than
233    /// `DEFAULT_ON_DEMAND_IMAGES_CACHE_SIZE` bytes, so that
234    /// `reduce_memory_use` should run.
235    pub(crate) fn exceeds_cache_size_limit(&self) -> bool {
236        self.requested_images_cache_size > DEFAULT_ON_DEMAND_IMAGES_CACHE_SIZE
237    }
238
239    pub(crate) fn clear(&mut self) {
240        self.images.clear();
241        self.available_images = Arc::default();
242        self.requested.clear();
243        self.requested_images_cache_size = 0;
244        self.asked.clear();
245        self.loaded = false;
246        self.revision += 1;
247    }
248}
249
250#[cfg(test)]
251#[path = "image_store_test.rs"]
252mod tests;