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