Skip to main content

mln_map/
map_impl.rs

1// Ports src/mln/map/map_impl.hpp and src/mln/map/map_impl.cpp.
2//
3// C++ `Map::Impl` is at once the TransformObserver, the style::Observer and
4// the RendererObserver, and holds references to the frontend and the
5// MapObserver. The port keeps it in an `Rc` so the renderer can observe it
6// through a `Weak` (C++: a raw pointer), with the mutable state in
7// `Cell`/`RefCell`s:
8// - The TransformObserver part only forwards to the MapObserver, so the
9//   Transform gets a small forwarding object (`MapTransformObserver`).
10// - The style::Observer part is `MapStyleObserver`, holding a `Weak` to the
11//   Impl. The style calls it while the Map hands out `&mut Style` (inside
12//   `load_json`, layer mutations, ...), when the Impl can't read the style.
13//   Those calls are queued and replayed, in order, as soon as the mutable
14//   borrow ends (`StyleMut` drop). Calls made while the style is not
15//   borrowed mutably are handled immediately, as in C++.
16
17use std::cell::{Cell, RefCell, RefMut};
18use std::ops::{Deref, DerefMut};
19use std::rc::{Rc, Weak};
20use std::sync::Arc;
21
22use mln_actor::{TaggedScheduler, scheduler};
23use mln_map_types::{CameraOptions, MapDebugOptions, MapMode, TileLodMode};
24use mln_renderer::{ExceptionPtr, RenderMode, RendererFrontend, RendererObserver, UpdateParameters};
25use mln_storage::FileSource;
26use mln_style::Style;
27use mln_style::observer::{Observer as StyleObserver, SourceObserver};
28use mln_style::source::Source;
29use mln_style::sprite::Sprite;
30use mln_util::chrono::{Clock, TimePoint};
31use mln_util::exception::{NotFoundException, StyleLoadException, StyleParseException};
32use mln_util::identity::SimpleIdentity;
33
34use crate::map_observer::{CameraChangeMode, MapLoadError, MapObserver, RenderFrameStatus};
35use crate::map_options::MapOptions;
36use crate::transform::{Transform, TransformObserver};
37
38/// `Map::StillImageCallback`: called with `None` on success, or the error.
39pub type StillImageCallback = Box<dyn FnOnce(Option<ExceptionPtr>)>;
40
41/// `StillImageRequest`.
42pub struct StillImageRequest {
43    pub callback: StillImageCallback,
44}
45
46/// The TransformObserver half of `Map::Impl`.
47struct MapTransformObserver {
48    observer: Rc<dyn MapObserver>,
49}
50
51impl TransformObserver for MapTransformObserver {
52    fn on_camera_will_change(&self, mode: CameraChangeMode) {
53        self.observer.on_camera_will_change(mode);
54    }
55    fn on_camera_is_changing(&self) {
56        self.observer.on_camera_is_changing();
57    }
58    fn on_camera_did_change(&self, mode: CameraChangeMode) {
59        self.observer.on_camera_did_change(mode);
60    }
61}
62
63/// A style::Observer call, queued while the style is borrowed mutably.
64enum StyleEvent {
65    SourceChanged,
66    Update,
67    StyleLoading,
68    StyleLoaded,
69    StyleError(ExceptionPtr),
70    ResourceError(ExceptionPtr),
71    SpriteLoaded,
72    SpriteError,
73    SpriteRequested,
74    /// Port-only: a `Style::loadURL` response is waiting (see
75    /// `Observer::on_style_response`).
76    StyleResponse,
77}
78
79/// The style::Observer half of `Map::Impl`.
80struct MapStyleObserver {
81    map: Weak<MapImpl>,
82}
83
84impl MapStyleObserver {
85    fn dispatch(&self, event: StyleEvent) {
86        if let Some(map) = self.map.upgrade() {
87            map.on_style_event(event);
88        }
89    }
90}
91
92impl SourceObserver for MapStyleObserver {
93    fn on_source_changed(&self, _source: &dyn Source) {
94        self.dispatch(StyleEvent::SourceChanged);
95    }
96}
97
98impl StyleObserver for MapStyleObserver {
99    fn on_style_loading(&self) {
100        self.dispatch(StyleEvent::StyleLoading);
101    }
102    fn on_style_loaded(&self) {
103        self.dispatch(StyleEvent::StyleLoaded);
104    }
105    fn on_update(&self) {
106        self.dispatch(StyleEvent::Update);
107    }
108    fn on_style_error(&self, error: ExceptionPtr) {
109        self.dispatch(StyleEvent::StyleError(error));
110    }
111    fn on_resource_error(&self, error: ExceptionPtr) {
112        self.dispatch(StyleEvent::ResourceError(error));
113    }
114    fn on_sprite_loaded(&self, _sprite: Option<&Sprite>) {
115        self.dispatch(StyleEvent::SpriteLoaded);
116    }
117    fn on_sprite_error(&self, _sprite: Option<&Sprite>, _error: ExceptionPtr) {
118        self.dispatch(StyleEvent::SpriteError);
119    }
120    fn on_sprite_requested(&self, _sprite: Option<&Sprite>) {
121        self.dispatch(StyleEvent::SpriteRequested);
122    }
123    fn on_style_response(&self) {
124        self.dispatch(StyleEvent::StyleResponse);
125    }
126}
127
128pub struct MapImpl {
129    pub(crate) observer: Rc<dyn MapObserver>,
130    pub(crate) renderer_frontend: Box<dyn RendererFrontend>,
131    // TODO(port): std::unique_ptr<util::ActionJournal> actionJournal.
132    pub(crate) transform: RefCell<Transform>,
133
134    pub(crate) mode: MapMode,
135    pub(crate) pixel_ratio: f32,
136    pub(crate) cross_source_collisions: bool,
137    pub(crate) fast_pfor_enabled: bool,
138    pub(crate) capture_rendered_features: bool,
139
140    pub(crate) debug_options: Cell<MapDebugOptions>,
141    // TODO(port): renderingStatsView, lastFrameStats, annotationManager.
142    pub(crate) style: RefCell<Style>,
143    pending_style_events: RefCell<Vec<StyleEvent>>,
144
145    pub(crate) camera_mutated: Cell<bool>,
146
147    pub(crate) prefetch_zoom_delta: Cell<u8>,
148
149    pub(crate) loading: Cell<bool>,
150    pub(crate) renderer_fully_loaded: Cell<bool>,
151    pub(crate) still_image_request: RefCell<Option<StillImageRequest>>,
152
153    pub(crate) tile_lod_min_radius: Cell<f64>,
154    pub(crate) tile_lod_scale: Cell<f64>,
155    pub(crate) tile_lod_pitch_threshold: Cell<f64>,
156    pub(crate) tile_lod_zoom_shift: Cell<f64>,
157    pub(crate) tile_lod_mode: Cell<TileLodMode>,
158
159    /// `std::shared_ptr<FileSource> fileSource`. Declared after `style`:
160    /// C++ destroys members in reverse order, so the style (and its sprite
161    /// requests) goes first.
162    pub(crate) file_source: Option<Arc<dyn FileSource>>,
163}
164
165impl MapImpl {
166    /// `Map::Impl(RendererFrontend&, MapObserver&, std::shared_ptr<FileSource>, const MapOptions&)`.
167    pub fn new(
168        frontend: Box<dyn RendererFrontend>,
169        observer: Rc<dyn MapObserver>,
170        file_source: Option<Arc<dyn FileSource>>,
171        map_options: &MapOptions,
172    ) -> Rc<MapImpl> {
173        let transform_observer: Rc<dyn TransformObserver> =
174            Rc::new(MapTransformObserver { observer: observer.clone() });
175        let pixel_ratio = map_options.pixel_ratio();
176        // TODO(port): `frontend_.getThreadPool()` (RendererFrontend has no
177        // thread pool yet); the background pool with a fresh tag instead.
178        let thread_pool = TaggedScheduler::new(scheduler::get_background(), SimpleIdentity::new());
179        let map = Rc::new(MapImpl {
180            observer,
181            renderer_frontend: frontend,
182            transform: RefCell::new(Transform::new(
183                transform_observer,
184                map_options.constrain_mode(),
185                map_options.viewport_mode(),
186            )),
187            mode: map_options.map_mode(),
188            pixel_ratio,
189            cross_source_collisions: map_options.cross_source_collisions(),
190            fast_pfor_enabled: map_options.fast_pfor_enabled(),
191            capture_rendered_features: map_options.rendered_feature_info(),
192            debug_options: Cell::new(MapDebugOptions::NO_DEBUG),
193            style: RefCell::new(Style::with_file_source(file_source.clone(), pixel_ratio, thread_pool)),
194            pending_style_events: RefCell::new(Vec::new()),
195            camera_mutated: Cell::new(false),
196            // util::DEFAULT_PREFETCH_ZOOM_DELTA
197            prefetch_zoom_delta: Cell::new(4),
198            loading: Cell::new(false),
199            // C++ leaves `rendererFullyLoaded` uninitialized until the first
200            // frame or style load.
201            renderer_fully_loaded: Cell::new(false),
202            still_image_request: RefCell::new(None),
203            tile_lod_min_radius: Cell::new(3.0),
204            tile_lod_scale: Cell::new(1.0),
205            tile_lod_pitch_threshold: Cell::new((60.0 / 180.0) * std::f64::consts::PI),
206            tile_lod_zoom_shift: Cell::new(0.0),
207            tile_lod_mode: Cell::new(TileLodMode::Default),
208            file_source,
209        });
210        map.transform.borrow_mut().set_north_orientation(map_options.north_orientation());
211        let style_observer: Rc<dyn StyleObserver> = Rc::new(MapStyleObserver { map: Rc::downgrade(&map) });
212        map.style.borrow_mut().impl_.set_observer(Some(style_observer));
213        let weak: Weak<MapImpl> = Rc::downgrade(&map);
214        map.renderer_frontend.set_observer(weak);
215        // C++ throws from the constructor for an empty size; the Rust Map
216        // constructor is infallible (agreed interface), so this panics.
217        if let Err(e) = map.transform.borrow_mut().resize(map_options.size()) {
218            panic!("{e}");
219        }
220        map
221    }
222
223    // MARK: - style::Observer dispatch
224
225    fn on_style_event(&self, event: StyleEvent) {
226        if self.style.try_borrow().is_err() {
227            // The style is being mutated through a StyleMut; replay when it
228            // drops.
229            self.pending_style_events.borrow_mut().push(event);
230            return;
231        }
232        self.handle_style_event(event);
233    }
234
235    /// Replays the style::Observer calls queued while the style was
236    /// borrowed mutably.
237    pub(crate) fn process_pending_style_events(&self) {
238        loop {
239            let event = {
240                let mut pending = self.pending_style_events.borrow_mut();
241                if pending.is_empty() {
242                    break;
243                }
244                pending.remove(0)
245            };
246            self.handle_style_event(event);
247        }
248    }
249
250    fn handle_style_event(&self, event: StyleEvent) {
251        match event {
252            StyleEvent::SourceChanged => self.on_source_changed(),
253            StyleEvent::Update => self.on_update(),
254            StyleEvent::StyleLoading => self.on_style_loading(),
255            StyleEvent::StyleLoaded => self.on_style_loaded(),
256            StyleEvent::StyleError(error) => self.on_style_error(error),
257            StyleEvent::ResourceError(error) => RendererObserver::on_resource_error(self, error),
258            // TODO(port): MapObserver::onSpriteLoaded / onSpriteError /
259            // onSpriteRequested (and the action journal).
260            StyleEvent::SpriteLoaded | StyleEvent::SpriteError | StyleEvent::SpriteRequested => {}
261            // C++ parses inside the file source callback (the lambda in
262            // Style::Impl::loadURL); the observer calls the parse makes are
263            // queued while the style is borrowed and replayed here.
264            StyleEvent::StyleResponse => {
265                self.style.borrow_mut().impl_.process_style_responses();
266                self.process_pending_style_events();
267            }
268        }
269    }
270
271    // MARK: - Map::Impl StyleObserver
272
273    fn on_source_changed(&self) {
274        // TODO(port): observer.onSourceChanged(source).
275    }
276
277    pub fn on_update(&self) {
278        // Don't load/render anything in still mode until explicitly requested.
279        if self.mode != MapMode::Continuous && self.still_image_request.borrow().is_none() {
280            return;
281        }
282
283        let time_point = if self.mode == MapMode::Continuous { Clock::now() } else { TimePoint::max() };
284
285        self.transform.borrow_mut().update_transitions(time_point);
286
287        let params = {
288            let style = self.style.borrow();
289            let style_impl = &style.impl_;
290            UpdateParameters {
291                style_loaded: style_impl.is_loaded(),
292                mode: self.mode,
293                pixel_ratio: self.pixel_ratio,
294                debug_options: self.debug_options.get(),
295                time_point,
296                transform_state: self.transform.borrow().get_state().clone(),
297                glyph_url: style_impl.get_glyph_url().to_owned(),
298                font_faces: style_impl.get_font_faces(),
299                sprite_loaded: style_impl.are_sprites_loaded(),
300                transition_options: style_impl.get_transition_options(),
301                light: style_impl.get_light_impl(),
302                images: style_impl.get_image_impls(),
303                sources: style_impl.get_source_impls(),
304                layers: style_impl.get_layer_impls(),
305                global_state: Some(style_impl.get_global_state_shared()),
306                file_source: self.file_source.clone(),
307                prefetch_zoom_delta: self.prefetch_zoom_delta.get(),
308                still_image_request: self.still_image_request.borrow().is_some(),
309                cross_source_collisions: self.cross_source_collisions,
310                fast_pfor_enabled: self.fast_pfor_enabled,
311                capture_rendered_features: self.capture_rendered_features,
312                tile_lod_min_radius: self.tile_lod_min_radius.get(),
313                tile_lod_scale: self.tile_lod_scale.get(),
314                tile_lod_pitch_threshold: self.tile_lod_pitch_threshold.get(),
315                tile_lod_zoom_shift: self.tile_lod_zoom_shift.get(),
316                tile_lod_mode: self.tile_lod_mode.get(),
317            }
318        };
319
320        // `update` takes C++'s `std::shared_ptr<UpdateParameters>` as an `Arc`.
321        #[allow(clippy::arc_with_non_send_sync)]
322        self.renderer_frontend.update(Arc::new(params));
323    }
324
325    pub fn on_style_loading(&self) {
326        self.loading.set(true);
327        self.renderer_fully_loaded.set(false);
328        self.observer.on_will_start_loading_map();
329    }
330
331    pub fn on_style_loaded(&self) {
332        if !self.camera_mutated.get() {
333            let camera = self.style.borrow().get_default_camera();
334            self.jump_to(&camera);
335        }
336        // TODO(port): if (LayerManager::annotationsEnabled)
337        // annotationManager.onStyleLoaded() (see DEVIATIONS.md).
338
339        self.observer.on_did_finish_loading_style();
340
341        // TODO(port): logStyleDependencies (debug builds only).
342    }
343
344    pub fn on_style_error(&self, error: ExceptionPtr) {
345        let type_ = if error.downcast_ref::<StyleParseException>().is_some() {
346            MapLoadError::StyleParseError
347        } else if error.downcast_ref::<StyleLoadException>().is_some() {
348            MapLoadError::StyleLoadError
349        } else if error.downcast_ref::<NotFoundException>().is_some() {
350            MapLoadError::NotFoundError
351        } else {
352            MapLoadError::UnknownError
353        };
354        let description = error.to_string();
355
356        self.observer.on_did_fail_loading_map(type_, &description);
357    }
358
359    // MARK: - Map
360
361    pub fn jump_to(&self, camera: &CameraOptions) {
362        self.camera_mutated.set(true);
363        self.transform.borrow_mut().jump_to(camera);
364        self.on_update();
365    }
366}
367
368impl Drop for MapImpl {
369    fn drop(&mut self) {
370        // Explicitly reset the RendererFrontend first to ensure it releases
371        // all shared resources (AnnotationManager).
372        self.renderer_frontend.reset();
373    }
374}
375
376// MARK: - Map::Impl RendererObserver
377
378impl RendererObserver for MapImpl {
379    fn on_invalidate(&self) {
380        self.on_update();
381    }
382
383    fn on_resource_error(&self, error: ExceptionPtr) {
384        if self.mode != MapMode::Continuous {
385            let request = self.still_image_request.borrow_mut().take();
386            if let Some(request) = request {
387                (request.callback)(Some(error));
388            }
389        }
390    }
391
392    fn on_will_start_rendering_frame(&self) {
393        if self.mode == MapMode::Continuous {
394            self.observer.on_will_start_rendering_frame();
395        }
396    }
397
398    fn on_did_finish_rendering_frame(&self, render_mode: RenderMode, needs_repaint: bool, placement_changed: bool) {
399        self.renderer_fully_loaded.set(render_mode == RenderMode::Full);
400
401        // TODO(port): renderingStatsView->update(*style, *stats).
402
403        if self.mode == MapMode::Continuous {
404            let frame_status = RenderFrameStatus {
405                mode: match render_mode {
406                    RenderMode::Partial => crate::map_observer::RenderMode::Partial,
407                    RenderMode::Full => crate::map_observer::RenderMode::Full,
408                },
409                needs_repaint,
410                placement_changed,
411            };
412            self.observer.on_did_finish_rendering_frame(&frame_status);
413
414            if needs_repaint || self.transform.borrow().in_transition() {
415                self.on_update();
416            } else if self.renderer_fully_loaded.get() {
417                self.observer.on_did_become_idle();
418            }
419        } else if self.still_image_request.borrow().is_some() && self.renderer_fully_loaded.get() {
420            let request = self.still_image_request.borrow_mut().take();
421            if let Some(request) = request {
422                (request.callback)(None);
423            }
424        }
425    }
426
427    fn on_will_start_rendering_map(&self) {
428        if self.mode == MapMode::Continuous {
429            self.observer.on_will_start_rendering_map();
430        }
431    }
432
433    fn on_did_finish_rendering_map(&self) {
434        if self.mode == MapMode::Continuous && self.loading.get() {
435            self.observer.on_did_finish_rendering_map(crate::map_observer::RenderMode::Full);
436            if self.loading.get() {
437                self.loading.set(false);
438                self.observer.on_did_finish_loading_map();
439            }
440        }
441    }
442
443    fn on_style_image_missing(&self, id: &str, done: &mut dyn FnMut()) {
444        if self.style.borrow().get_image(id).is_none() {
445            self.observer.on_style_image_missing(id);
446        }
447
448        done();
449        self.on_update();
450    }
451
452    fn on_remove_unused_style_images(&self, unused_image_ids: &[String]) {
453        for unused_image_id in unused_image_ids {
454            if self.observer.on_can_remove_unused_style_image(unused_image_id) {
455                self.style.borrow_mut().remove_image(unused_image_id);
456                self.process_pending_style_events();
457            }
458        }
459    }
460
461    fn on_render_error(&self, error: ExceptionPtr) {
462        self.observer.on_render_error(error);
463    }
464}
465
466/// The `style::Style&` that `Map::getStyle()` returns, for mutation: derefs
467/// to `Style`; when it drops, the style::Observer calls the mutation made
468/// are delivered to the map (see the comment at the top of this file).
469pub struct StyleMut<'a> {
470    map: &'a MapImpl,
471    style: Option<RefMut<'a, Style>>,
472}
473
474impl<'a> StyleMut<'a> {
475    pub(crate) fn new(map: &'a MapImpl) -> Self {
476        StyleMut { map, style: Some(map.style.borrow_mut()) }
477    }
478}
479
480impl Deref for StyleMut<'_> {
481    type Target = Style;
482    fn deref(&self) -> &Style {
483        self.style.as_ref().expect("style")
484    }
485}
486
487impl DerefMut for StyleMut<'_> {
488    fn deref_mut(&mut self) -> &mut Style {
489        self.style.as_mut().expect("style")
490    }
491}
492
493impl Drop for StyleMut<'_> {
494    fn drop(&mut self) {
495        drop(self.style.take());
496        self.map.process_pending_style_events();
497    }
498}