Skip to main content

mln_map/
map.rs

1// The map owns its style versions, its transform and its style loader. An
2// edit reacts in the call that makes it; the loader and the renderer report
3// through queues that the map drains in `process_events`.
4
5use std::rc::Rc;
6use std::sync::Arc;
7
8use geo_types::Geometry;
9use mln_map_types::{
10    AnimationOptions, BoundOptions, CameraDelta, CameraError, CameraOptions, CameraUpdate, MapDebugOptions, MapMode,
11    MapView, ProjectionMode, TileLodMode, TransformState, VerticalPerspectiveProjection, Viewport,
12};
13use mln_renderer::{
14    Registry, RendererEvent, RendererEvents, RenderingStats, UpdateParameters, UpdateReader, UpdateSlot,
15};
16use mln_storage::FileSource;
17#[cfg(not(target_family = "wasm"))]
18use mln_storage::{Loader, ResourceOptions};
19use mln_style::conversion::{Convertible, convert_source};
20use mln_style::{Edit, Source, Style, StyleRegistry};
21use mln_style_types::{ProjectionDefinition, ProjectionType};
22use mln_util::error::Error;
23use mln_util::event_queue::{EventQueue, Waker};
24use mln_util::geo::{EdgeInsets, LatLng, LatLngBounds, ScreenCoordinate, WrapMode};
25use mln_util::geometry::for_each_point;
26use mln_util::logging::{Event, Log};
27use mln_util::mat4::Mat4;
28use mln_util::pool::Pool;
29use mln_util::size::Size;
30use mln_util::subdivision_granularity::SubdivisionGranularitySetting;
31use mln_util::time::Instant;
32use mln_util::vectors::Vec3;
33
34use crate::feature_state::FeatureStateStore;
35use crate::map_event::{MapEvent, RenderFrameStatus};
36use crate::map_options::{MapOptions, UnusedStyleImagePolicy};
37use crate::map_snapshot::{CameraBounds, FreeCamera, MapSnapshot, TileSettings};
38use crate::rendering_stats_view::{RenderingStatsView, RenderingStatsViewOptions};
39use crate::style_loader::{LoadEvent, StyleLoader};
40use crate::transform::{CameraCommandId, CommandEnd, FrameClock, Transform, TransformEvent};
41
42/// Where a still image that [`Map::render_still`] asked for stands.
43#[derive(Debug, PartialEq)]
44enum StillImage {
45    None,
46    /// Waits for a complete frame.
47    Pending,
48    /// Ended, until [`Map::take_still_image`] takes it.
49    Ended(Result<(), Error>),
50}
51
52/// A map: its style, its camera, and the updates it publishes for its
53/// renderer.
54///
55/// The map publishes its state for a renderer in an update slot, which a
56/// renderer reads through [`update_reader`](Self::update_reader) and
57/// reports back to through [`renderer_events`](Self::renderer_events).
58/// The style is an `Arc<Style>` version: [`edit_style`](Self::edit_style)
59/// makes the next one and publishes it at once. The style's loader and the
60/// renderer report to the map through queues, which the map handles only
61/// in [`process_events`](Self::process_events) (which
62/// [`drain_events`](Self::drain_events) calls): an owner calls it once per
63/// phase, before the commands that should see what was reported, such as a
64/// camera command that should land after the style's default camera. What
65/// the map reports to its owner waits in another queue, for `drain_events`.
66/// An owner sets a waker ([`set_waker`](Self::set_waker)) that schedules
67/// those calls on its thread.
68pub struct Map {
69    updates: UpdateSlot,
70    transform: Transform,
71
72    mode: MapMode,
73    pixel_ratio: f32,
74    cross_source_collisions: bool,
75    fast_pfor_enabled: bool,
76    unused_style_image_policy: UnusedStyleImagePolicy,
77
78    debug_options: MapDebugOptions,
79    rendering_stats_view: Option<RenderingStatsView>,
80    /// The current version of the style.
81    style: Arc<Style>,
82    /// Loads the style's document, its sprites and its sources'
83    /// descriptions.
84    loader: StyleLoader,
85    /// The state of the sources' features, which each update carries.
86    feature_state: FeatureStateStore,
87
88    camera_mutated: bool,
89    /// How the map picks the tiles to load, as its snapshot reports it.
90    tile: TileSettings,
91    loading: bool,
92    renderer_fully_loaded: bool,
93    /// A still image that [`Map::render_still`] asked for, until it ends.
94    still_image: StillImage,
95    /// Counts the still image requests, so the renderer can tell a new one.
96    still_image_request_id: u64,
97
98    /// Grows with each change to the map's state.
99    generation: u64,
100
101    renderer_events: RendererEvents,
102    /// What the map reports to its owner.
103    events: EventQueue<MapEvent>,
104    /// The ends of the camera commands, for its owner.
105    command_ends: Vec<CommandEnd>,
106
107    /// Declared after `style`, so the style and its requests go first.
108    file_source: Option<Arc<dyn FileSource>>,
109    /// Where the map's background work runs.
110    pool: Pool,
111}
112
113impl Map {
114    /// A map with a [`Loader`] of its own for the default
115    /// `ResourceOptions`, whose background work runs on `pool`.
116    ///
117    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an empty `map_options.size`.
118    #[cfg(not(target_family = "wasm"))]
119    pub fn new(map_options: MapOptions, pool: &Pool) -> Result<Map, Error> {
120        Self::with_resource_options(map_options, &ResourceOptions::default(), pool)
121    }
122
123    /// A map with a [`Loader`] of its own for `resource_options`, on
124    /// `pool`.
125    #[cfg(not(target_family = "wasm"))]
126    pub fn with_resource_options(
127        map_options: MapOptions,
128        resource_options: &ResourceOptions,
129        pool: &Pool,
130    ) -> Result<Map, Error> {
131        let loader: Arc<dyn FileSource> = Arc::new(Loader::new(resource_options, pool));
132        Self::with_registry(loader, map_options, Arc::clone(Registry::with_builtins().style()), pool)
133    }
134
135    // gtests-core: the C++ tests' `MapAdapter` (test/include/mln/test/
136    // map_adapter.hpp): a map over a given file source.
137    /// A map whose resources come from `file_source`, on `pool`.
138    pub fn with_file_source(
139        file_source: Arc<dyn FileSource>,
140        map_options: MapOptions,
141        pool: &Pool,
142    ) -> Result<Map, Error> {
143        Self::with_registry(file_source, map_options, Arc::clone(Registry::with_builtins().style()), pool)
144    }
145
146    /// A map whose resources come from `file_source` and whose style parses
147    /// against `registry`, on `pool`. The other constructors
148    /// use the built-in registrations.
149    ///
150    /// The renderer that draws the map must be given a registry filled by
151    /// the same calls as `registry` ([`mln_renderer::Registry::style`]): it
152    /// finds a layer's type by name, and draws no layer whose type it lacks.
153    pub fn with_registry(
154        file_source: Arc<dyn FileSource>,
155        map_options: MapOptions,
156        registry: Arc<StyleRegistry>,
157        pool: &Pool,
158    ) -> Result<Map, Error> {
159        let events = EventQueue::new();
160        let renderer_events = RendererEvents::new();
161        let pixel_ratio = map_options.pixel_ratio;
162        let style = Arc::new(Style::new(registry));
163        let loader = StyleLoader::new(Some(Arc::clone(&file_source)), pool, pixel_ratio);
164        let mut transform = Transform::new(map_options.constrain_mode, map_options.viewport_mode);
165        transform.set_north_orientation(map_options.north_orientation);
166        let mut map = Map {
167            updates: UpdateSlot::new(),
168            transform,
169            mode: map_options.map_mode,
170            pixel_ratio,
171            cross_source_collisions: map_options.cross_source_collisions,
172            fast_pfor_enabled: map_options.fast_pfor_enabled,
173            unused_style_image_policy: map_options.unused_style_image_policy,
174            debug_options: MapDebugOptions::NO_DEBUG,
175            rendering_stats_view: None,
176            style,
177            loader,
178            feature_state: FeatureStateStore::default(),
179            camera_mutated: false,
180            tile: TileSettings {
181                // util::DEFAULT_PREFETCH_ZOOM_DELTA
182                prefetch_zoom_delta: 4,
183                lod_min_radius: 3.0,
184                lod_scale: 1.0,
185                lod_pitch_threshold: 60.0,
186                lod_zoom_shift: 0.0,
187                lod_mode: TileLodMode::Default,
188            },
189            loading: false,
190            renderer_fully_loaded: false,
191            still_image: StillImage::None,
192            still_image_request_id: 0,
193            generation: 1,
194            renderer_events,
195            events,
196            command_ends: Vec::new(),
197            file_source: Some(file_source),
198            pool: pool.clone(),
199        };
200        map.share_projection_with_transform();
201        map.transform.resize(map_options.size)?;
202        Ok(map)
203    }
204
205    /// Where the map's background work runs.
206    #[must_use]
207    pub fn pool(&self) -> &Pool {
208        &self.pool
209    }
210
211    // MARK: - Renderer
212
213    /// A reader of the updates that the map publishes for its renderer.
214    pub fn update_reader(&self) -> UpdateReader {
215        self.updates.reader()
216    }
217
218    /// The queue that the map's renderer reports its events to.
219    pub fn renderer_events(&self) -> RendererEvents {
220        self.renderer_events.clone()
221    }
222
223    /// Holds the map's updates back from its renderer until the matching
224    /// [`end_command_group`](Self::end_command_group), so the changes in
225    /// between show in the same frame. Groups nest, and the changes show
226    /// when the outermost group ends.
227    pub fn begin_command_group(&mut self) {
228        self.updates.begin_group();
229    }
230
231    /// Ends the group that [`begin_command_group`](Self::begin_command_group)
232    /// began. Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind)
233    /// when no group is open.
234    pub fn end_command_group(&mut self) -> Result<(), Error> {
235        self.updates.end_group()
236    }
237
238    /// How many command groups are open.
239    pub fn command_group_depth(&self) -> u32 {
240        self.updates.group_depth()
241    }
242
243    /// Holds the map's updates back from its renderer, as a command group
244    /// does, until [`release_updates`](Self::release_updates). The hold is
245    /// apart from the groups: it doesn't nest, and
246    /// [`command_group_depth`](Self::command_group_depth) doesn't count it.
247    pub fn hold_updates(&mut self) {
248        self.updates.hold();
249    }
250
251    /// Ends the hold that [`hold_updates`](Self::hold_updates) began. The
252    /// changes show unless a command group still holds them.
253    pub fn release_updates(&mut self) {
254        self.updates.release();
255    }
256
257    // MARK: - Events
258
259    /// Sets the waker that runs, on any thread, when the map has events to
260    /// handle or to drain. It must not call the map: it schedules a call of
261    /// [`drain_events`](Self::drain_events) or
262    /// [`process_events`](Self::process_events) on the map's thread, as by
263    /// posting to the owner's `Queue`.
264    pub fn set_waker(&mut self, waker: Option<Waker>) {
265        self.loader.set_waker(waker.clone());
266        self.renderer_events.set_waker(waker.clone());
267        self.events.set_waker(waker);
268    }
269
270    /// Whether the style or the renderer reported something that
271    /// [`process_events`](Self::process_events) hasn't handled. A report
272    /// counts once it is queued, though its waker may not have run yet.
273    #[must_use]
274    pub fn has_reports(&self) -> bool {
275        self.loader.has_replies() || !self.renderer_events.is_empty()
276    }
277
278    /// Sets a waker as [`set_waker`](Self::set_waker) does, that runs only
279    /// when the style or the renderer reports something for the map to
280    /// handle, which can come from any thread. The events that the map's own
281    /// calls report don't run it, for an owner that drains them after each
282    /// call.
283    pub fn set_reports_waker(&mut self, waker: Option<Waker>) {
284        self.loader.set_waker(waker.clone());
285        self.renderer_events.set_waker(waker);
286        self.events.set_waker(None);
287    }
288
289    /// Handles what the style and the renderer reported since the last
290    /// call: loads, frames, errors and missing images. The map's reactions,
291    /// such as an update for the renderer or a still image's callback, run
292    /// here, and its events wait for [`drain_events`](Self::drain_events).
293    pub fn process_events(&mut self) {
294        loop {
295            let replies = self.loader.take_replies();
296            let renderer_events = self.renderer_events.take();
297            if replies.is_empty() && renderer_events.is_empty() {
298                break;
299            }
300            for reply in replies {
301                let events = self.loader.on_reply(&self.style, reply);
302                self.handle_load_events(events);
303            }
304            for event in renderer_events {
305                self.handle_renderer_event(event);
306            }
307        }
308    }
309
310    /// Handles what the style and the renderer reported, as
311    /// [`process_events`](Self::process_events) does, and takes the map's
312    /// events, oldest first.
313    pub fn drain_events(&mut self) -> Vec<MapEvent> {
314        self.process_events();
315        self.forward_camera_events();
316        self.events.take()
317    }
318
319    fn emit(&mut self, event: MapEvent) {
320        self.forward_camera_events();
321        self.events.push(event);
322    }
323
324    /// Moves what the transform reported to the map's events, after the
325    /// events before it, and to its command ends.
326    fn forward_camera_events(&mut self) {
327        for event in self.transform.drain_events() {
328            match event {
329                TransformEvent::CameraWillChange(change) => self.events.push(MapEvent::CameraWillChange(change)),
330                TransformEvent::CameraIsChanging => self.events.push(MapEvent::CameraIsChanging),
331                TransformEvent::CameraDidChange(change) => self.events.push(MapEvent::CameraDidChange(change)),
332                TransformEvent::CommandEnded(end) => self.command_ends.push(end),
333            }
334        }
335    }
336
337    /// Drains the ends of the camera commands that ended since the last
338    /// call, oldest first: each command's end comes once, unless the map
339    /// drops while the command runs (see [`close_camera`](Self::close_camera)).
340    /// They come with the camera events of the same calls, which
341    /// [`drain_events`](Self::drain_events) takes. The map keeps its buffer
342    /// for the ends that come next.
343    pub fn drain_command_ends(&mut self) -> std::vec::Drain<'_, CommandEnd> {
344        self.forward_camera_events();
345        self.command_ends.drain(..)
346    }
347
348    /// Does what the loader's events ask, in their order.
349    fn handle_load_events(&mut self, events: Vec<LoadEvent>) {
350        for event in events {
351            match event {
352                LoadEvent::Loading => {
353                    self.changed();
354                    self.loading = true;
355                    self.renderer_fully_loaded = false;
356                    self.emit(MapEvent::LoadingStarted);
357                }
358                LoadEvent::Parsed(style) => {
359                    self.style = Arc::new(style);
360                    self.watch_sources();
361                    // A style that loads takes every source's feature state
362                    // with it.
363                    self.feature_state.clear();
364                    self.share_projection_with_transform();
365                    self.on_update();
366                }
367                LoadEvent::Loaded => {
368                    self.changed();
369                    if !self.camera_mutated {
370                        let camera = self.style.get_default_camera();
371                        self.jump_to(&camera);
372                    }
373                    self.emit(MapEvent::StyleLoaded);
374                }
375                LoadEvent::Failed(error) => self.emit(MapEvent::LoadingFailed(error)),
376                LoadEvent::ResourceError(error) => self.on_resource_error(error),
377                LoadEvent::SpriteRequested(sprite) => self.emit(MapEvent::SpriteRequested(sprite)),
378                LoadEvent::SpriteImages(sprite, images) => {
379                    // The update this publishes is for *-pattern properties.
380                    let _ = self.apply_loaded(Edit::AddImages(images));
381                    self.emit(MapEvent::SpriteLoaded(sprite));
382                }
383                LoadEvent::SpriteFailed(sprite, error) => {
384                    // Unblocks the tiles that wait for the sprite.
385                    self.on_update();
386                    self.emit(MapEvent::SpriteError(sprite, error));
387                }
388                LoadEvent::SourceDescribed { load, result: Err(error) } => {
389                    Log::error(Event::Style, format!("Failed to load source {}: {error}", load.id));
390                    self.on_resource_error(error);
391                }
392                LoadEvent::SourceDescribed { load, result: Ok(description) } => {
393                    let previous = self.style.get_source(&load.id).cloned();
394                    let edit = Edit::SetSourceDescription {
395                        id: load.id.to_string(),
396                        instance: load.instance,
397                        load: load.load,
398                        result: Ok(description),
399                    };
400                    if !self.apply_loaded_changes(edit) {
401                        // The source is loaded now, which the update says.
402                        self.on_update();
403                    }
404                    if let (Some(previous), Some(source)) = (previous, self.style.get_source(&load.id))
405                        && source.metadata_changed_from(&previous)
406                    {
407                        self.emit(MapEvent::SourceChanged { source_id: load.id.to_string() });
408                        self.on_update();
409                    }
410                }
411            }
412        }
413    }
414
415    /// Loads the descriptions of the sources whose loads the loader hasn't
416    /// seen, and gives the style the ones their types know without a fetch,
417    /// before the version is published.
418    fn watch_sources(&mut self) {
419        let edits = self.loader.watch_sources(&self.style);
420        if edits.is_empty() {
421            return;
422        }
423        let style = Arc::make_mut(&mut self.style);
424        for edit in edits {
425            // A description that the loader found for the version can't fail.
426            let _ = style.apply(edit);
427        }
428    }
429
430    fn handle_renderer_event(&mut self, event: RendererEvent) {
431        let continuous = self.mode == MapMode::Continuous;
432        match event {
433            RendererEvent::Invalidate => self.on_update(),
434            RendererEvent::ResourceError(error) => self.on_resource_error(error),
435            RendererEvent::RenderFrameStarted => {
436                if continuous {
437                    self.emit(MapEvent::RenderFrameStarted);
438                }
439            }
440            RendererEvent::RenderFrameFinished {
441                mode,
442                needs_repaint,
443                placement_changed,
444                still_image_request_id,
445                stats,
446            } => {
447                self.on_render_frame_finished(mode, needs_repaint, placement_changed, still_image_request_id, stats);
448            }
449            RendererEvent::RenderMapStarted => {
450                if continuous {
451                    self.emit(MapEvent::RenderMapStarted);
452                }
453            }
454            RendererEvent::RenderMapFinished => {
455                if continuous && self.loading {
456                    self.emit(MapEvent::RenderMapFinished(mln_renderer::RenderMode::Full));
457                    self.loading = false;
458                    self.emit(MapEvent::LoadingFinished);
459                }
460            }
461            RendererEvent::StyleImageMissing(id) => {
462                if self.style.get_image(&id).is_none() {
463                    self.emit(MapEvent::StyleImageMissing { id });
464                }
465                self.on_update();
466            }
467            RendererEvent::UnusedStyleImages(ids) => {
468                if self.unused_style_image_policy == UnusedStyleImagePolicy::Remove {
469                    for id in ids {
470                        if self.style.get_image(&id).is_some_and(|image| !image.keep_unused) {
471                            let _ = self.apply_loaded(Edit::RemoveImage(id));
472                        }
473                    }
474                }
475            }
476            RendererEvent::GlyphsRequested { font_stack, range } => {
477                self.emit(MapEvent::GlyphsRequested { font_stack, range });
478            }
479            RendererEvent::GlyphsLoaded { font_stack, range } => {
480                self.emit(MapEvent::GlyphsLoaded { font_stack, range });
481            }
482            RendererEvent::GlyphsError { font_stack, range, error } => {
483                self.emit(MapEvent::GlyphsError { font_stack, range, error });
484            }
485            RendererEvent::TileAction { op, id, source_id } => self.emit(MapEvent::TileAction { op, id, source_id }),
486            RendererEvent::RenderError(error) => self.emit(MapEvent::RenderError(error)),
487        }
488    }
489
490    /// Fails the still image being rendered.
491    fn on_resource_error(&mut self, error: Error) {
492        if self.mode != MapMode::Continuous && self.still_image == StillImage::Pending {
493            self.still_image = StillImage::Ended(Err(error));
494        }
495    }
496
497    fn on_render_frame_finished(
498        &mut self,
499        mode: mln_renderer::RenderMode,
500        needs_repaint: bool,
501        placement_changed: bool,
502        still_image_request_id: u64,
503        stats: Arc<RenderingStats>,
504    ) {
505        let fully_loaded = mode == mln_renderer::RenderMode::Full;
506        if std::mem::replace(&mut self.renderer_fully_loaded, fully_loaded) != fully_loaded {
507            self.changed();
508        }
509
510        if let Some(mut view) = self.rendering_stats_view.take() {
511            view.update(self, &stats);
512            self.rendering_stats_view = Some(view);
513        }
514
515        if self.mode == MapMode::Continuous {
516            self.emit(MapEvent::RenderFrameFinished(RenderFrameStatus {
517                mode,
518                needs_repaint,
519                placement_changed,
520                rendering_stats: stats,
521            }));
522
523            // A host on a frame clock has each frame sample the running
524            // animations (`sample_frame`), so a frame's report adds no update
525            // for them, which would only repeat the frame's camera.
526            let animating = self.transform.in_transition();
527            if needs_repaint || (animating && self.transform.frame_time().is_none()) {
528                self.on_update();
529            } else if !animating && self.renderer_fully_loaded {
530                self.emit(MapEvent::Idle);
531            }
532        } else if self.renderer_fully_loaded
533            && still_image_request_id == self.still_image_request_id
534            && self.still_image == StillImage::Pending
535        {
536            self.still_image = StillImage::Ended(Ok(()));
537        }
538    }
539
540    /// Records a change to the map's state.
541    fn changed(&mut self) {
542        self.generation += 1;
543    }
544
545    /// Counts a change to state that the map's owner keeps for the map, such
546    /// as which of its events a runtime reports, in the map's
547    /// [`generation`](Self::generation).
548    pub fn record_change(&mut self) {
549        self.changed();
550    }
551
552    /// Publishes an update of the map's state for the renderer.
553    fn on_update(&mut self) {
554        // Each update request comes from a change, so the generation grows
555        // even in still mode, where no update goes out.
556        self.changed();
557
558        // Don't load/render anything in still mode until explicitly requested.
559        if self.mode != MapMode::Continuous && self.still_image != StillImage::Pending {
560            return;
561        }
562
563        // Still modes have no clock: they show every transition as ended.
564        let time_point =
565            (self.mode == MapMode::Continuous).then(|| self.transform.frame_time().unwrap_or_else(Instant::now));
566
567        self.transform.update_transitions(time_point);
568        let projection = self.projection_at(self.transform.get_zoom());
569        self.transform.set_projection_definition(&projection);
570
571        let params = UpdateParameters {
572            style_loaded: self.style_loaded(),
573            mode: self.mode,
574            pixel_ratio: self.pixel_ratio,
575            debug_options: self.debug_options,
576            time_point,
577            transform_state: self.transform.get_state().clone(),
578            style: Arc::clone(&self.style),
579            sprite_loaded: self.loader.sprites_loaded(),
580            feature_states: self.feature_state.shared(),
581            file_source: self.file_source.clone(),
582            prefetch_zoom_delta: self.tile.prefetch_zoom_delta,
583            still_image_request: self.still_image == StillImage::Pending,
584            still_image_request_id: self.still_image_request_id,
585            cross_source_collisions: self.cross_source_collisions,
586            fast_pfor_enabled: self.fast_pfor_enabled,
587            tile_lod_min_radius: self.tile.lod_min_radius,
588            tile_lod_scale: self.tile.lod_scale,
589            tile_lod_pitch_threshold: mln_math::deg2rad(self.tile.lod_pitch_threshold),
590            tile_lod_zoom_shift: self.tile.lod_zoom_shift,
591            tile_lod_mode: self.tile.lod_mode,
592            subdivision_granularity: if self.mode == MapMode::Tile {
593                SubdivisionGranularitySetting::none()
594            } else {
595                self.style.get_projection().get_subdivision_granularity()
596            },
597        };
598
599        self.updates.publish(Arc::new(params));
600        self.forward_camera_events();
601    }
602
603    pub fn jump_to(&mut self, camera: &CameraOptions) {
604        self.camera_mutated = true;
605        // The style's projection decides how the camera is constrained, so it
606        // has to be in place first.
607        let zoom = camera.zoom.unwrap_or_else(|| self.transform.get_zoom());
608        let projection = self.projection_at(zoom);
609        self.transform.set_projection_definition(&projection);
610        self.transform.jump_to(camera);
611        self.on_update();
612    }
613
614    /// The style's projection at the zoom; always Mercator in tile mode,
615    /// whose tiles are Mercator tiles.
616    fn projection_at(&self, zoom: f64) -> ProjectionDefinition {
617        if self.mode == MapMode::Tile {
618            return ProjectionDefinition::new(ProjectionType::Mercator);
619        }
620        self.style.get_projection().evaluate(zoom as f32)
621    }
622
623    /// Gives the transform the style's current projection, which constrains
624    /// the target of an animation it starts. The style reports each change
625    /// to its projection, and the map calls this then.
626    fn share_projection_with_transform(&mut self) {
627        let projection = (self.mode != MapMode::Tile).then(|| Arc::clone(self.style.get_projection()));
628        self.transform.set_projection_for_zoom(Some(Rc::new(move |zoom: f64| match &projection {
629            Some(projection) => projection.evaluate(zoom as f32),
630            None => ProjectionDefinition::new(ProjectionType::Mercator),
631        })));
632    }
633
634    // MARK: - Still images
635
636    /// Asks for a still image: the map's renderer draws frames until one
637    /// has everything loaded, and [`take_still_image`](Self::take_still_image)
638    /// then reports it. Fails with
639    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) for a continuous map
640    /// and while another still image is on its way, and with the style's
641    /// error when it failed to load.
642    pub fn render_still(&mut self) -> Result<(), Error> {
643        if self.mode != MapMode::Static && self.mode != MapMode::Tile {
644            return Err(Error::invalid_state("Map is not in static or tile image render modes"));
645        }
646        if self.still_image == StillImage::Pending {
647            return Err(Error::invalid_state("Map is currently rendering an image"));
648        }
649        if let Some(error) = self.loader.last_error() {
650            return Err(error.clone());
651        }
652        self.still_image = StillImage::Pending;
653        self.still_image_request_id += 1;
654        self.on_update();
655        Ok(())
656    }
657
658    /// How the still image that [`render_still`](Self::render_still) asked
659    /// for ended, once it has: `Ok` once a complete frame rendered, or why
660    /// the image failed. The map handles its renderer's reports in
661    /// [`process_events`](Self::process_events), so call that first.
662    pub fn take_still_image(&mut self) -> Option<Result<(), Error>> {
663        match std::mem::replace(&mut self.still_image, StillImage::None) {
664            StillImage::Ended(result) => Some(result),
665            other => {
666                self.still_image = other;
667                None
668            }
669        }
670    }
671
672    /// The still image request that waits for a frame, as the
673    /// `still_image_request_id` of the updates that ask for it, or `None`
674    /// once it ended.
675    #[must_use]
676    pub fn pending_still_image(&self) -> Option<u64> {
677        (self.still_image == StillImage::Pending).then_some(self.still_image_request_id)
678    }
679
680    /// Triggers a repaint.
681    pub fn trigger_repaint(&mut self) {
682        self.on_update();
683    }
684
685    // MARK: - Feature state
686
687    /// Merges `state` into the state of the feature `feature_id` of the
688    /// source `source_id`, in its source layer `source_layer_id`: its keys
689    /// replace the same keys of the feature's state, and the other keys
690    /// stay. `None`, like the empty string, names no source layer.
691    ///
692    /// The map keeps the state until it is removed or a style loads, which
693    /// removes the state of every source, and sends it to the renderer with
694    /// its updates. Publishes an update when the state changes. Returns
695    /// whether it changed.
696    pub fn set_feature_state(
697        &mut self,
698        source_id: &str,
699        source_layer_id: Option<&str>,
700        feature_id: &str,
701        state: mln_style::expression::expression::FeatureState,
702    ) -> bool {
703        let changed = self.feature_state.set(source_id, source_layer_id.unwrap_or(""), feature_id, state);
704        if changed {
705            self.on_update();
706        }
707        changed
708    }
709
710    /// The state of the feature `feature_id` of the source `source_id`, in
711    /// its source layer `source_layer_id`, empty when it has none.
712    pub fn get_feature_state(
713        &self,
714        source_id: &str,
715        source_layer_id: Option<&str>,
716        feature_id: &str,
717    ) -> mln_style::expression::expression::FeatureState {
718        self.feature_state.get(source_id, source_layer_id.unwrap_or(""), feature_id)
719    }
720
721    /// Removes the state of the feature `feature_id` of the source
722    /// `source_id`, in its source layer `source_layer_id`: only its key
723    /// `state_key` when there is one, and that of every feature in the
724    /// source layer without `feature_id`. Publishes an update when the state
725    /// changes. Returns whether it changed.
726    pub fn remove_feature_state(
727        &mut self,
728        source_id: &str,
729        source_layer_id: Option<&str>,
730        feature_id: Option<&str>,
731        state_key: Option<&str>,
732    ) -> bool {
733        let changed = self.feature_state.remove(source_id, source_layer_id.unwrap_or(""), feature_id, state_key);
734        if changed {
735            self.on_update();
736        }
737        changed
738    }
739
740    /// Removes the state of every feature of the source `source_id`, as when
741    /// the source leaves the style. Publishes an update when the state
742    /// changes. Returns whether it changed.
743    pub fn remove_source_feature_state(&mut self, source_id: &str) -> bool {
744        let changed = self.feature_state.remove_source(source_id);
745        if changed {
746            self.on_update();
747        }
748        changed
749    }
750
751    // MARK: - Style
752
753    /// The map's style.
754    pub fn style(&self) -> &Arc<Style> {
755        &self.style
756    }
757
758    /// Edits the style: `edit` changes the next version of it, and the map
759    /// publishes that version for the renderer if anything changed. A
760    /// version that `edit` left as it was stays the same `Arc`, so it
761    /// publishes nothing. Returns what `edit` returns, and keeps what it
762    /// changed before it failed.
763    ///
764    /// Each source that the edit changed, rather than added or removed,
765    /// reports [`MapEvent::SourceChanged`].
766    pub fn edit_style<R, E>(&mut self, edit: impl FnOnce(&mut Style) -> Result<R, E>) -> Result<R, E> {
767        let before = Arc::clone(&self.style);
768        let result = edit(Arc::make_mut(&mut self.style));
769        let changed_sources = changed_sources(&before, &self.style);
770        if self.react_to_change(before) {
771            // A revalidated document no longer replaces the edited style.
772            self.loader.edited();
773        }
774        for source_id in changed_sources {
775            self.emit(MapEvent::SourceChanged { source_id });
776        }
777        result
778    }
779
780    /// As [`edit_style`](Self::edit_style), but fails with
781    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) ("style is not
782    /// loaded") until a style document parsed, and from the start of each
783    /// [`load_style_url`](Self::load_style_url) until its document parses:
784    /// the parse replaces the whole style, so an edit made before it would
785    /// be lost.
786    pub fn edit_loaded_style<R>(&mut self, edit: impl FnOnce(&mut Style) -> Result<R, Error>) -> Result<R, Error> {
787        if !self.loader.document_loaded() {
788            return Err(Error::invalid_state("style is not loaded"));
789        }
790        self.edit_style(edit)
791    }
792
793    /// Whether a style document parsed, and no
794    /// [`load_style_url`](Self::load_style_url) began since.
795    #[must_use]
796    pub fn style_document_loaded(&self) -> bool {
797        self.loader.document_loaded()
798    }
799
800    /// Makes an edit that the map itself causes, such as a sprite's images,
801    /// which doesn't count as an edit of the loaded document.
802    pub(crate) fn apply_loaded(&mut self, edit: Edit) -> Result<(), Error> {
803        let before = Arc::clone(&self.style);
804        let result = Arc::make_mut(&mut self.style).apply(edit);
805        self.react_to_change(before);
806        result
807    }
808
809    /// As [`apply_loaded`](Self::apply_loaded), for an edit that can't fail.
810    /// Returns whether it changed the style.
811    fn apply_loaded_changes(&mut self, edit: Edit) -> bool {
812        let before = Arc::clone(&self.style);
813        let _ = Arc::make_mut(&mut self.style).apply(edit);
814        self.react_to_change(before)
815    }
816
817    /// Reacts to the change from `before` to the current version: keeps
818    /// `before` when nothing changed, and otherwise starts the loads of new
819    /// sources, shares a new projection with the transform and publishes an
820    /// update. Returns whether anything changed.
821    fn react_to_change(&mut self, before: Arc<Style>) -> bool {
822        if before.is_same_version(&self.style) {
823            self.style = before;
824            return false;
825        }
826        if !Arc::ptr_eq(before.get_sources(), self.style.get_sources()) {
827            self.watch_sources();
828        }
829        if !Arc::ptr_eq(before.get_projection(), self.style.get_projection()) {
830            self.share_projection_with_transform();
831        }
832        self.on_update();
833        true
834    }
835
836    // MARK: - Sources
837
838    /// Adds `source` to the style, last, and starts loading its description.
839    /// Fails with [`ErrorKind::AlreadyExists`](mln_util::ErrorKind) if the
840    /// style has a source with its id.
841    pub fn add_source(&mut self, source: Source) -> Result<(), Error> {
842        self.edit_style(|style| style.apply(Edit::AddSource(source)))
843    }
844
845    /// Adds the [source](https://maplibre.org/maplibre-style-spec/sources/)
846    /// that `json` describes, with the ID `id`.
847    ///
848    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) while the
849    /// style isn't loaded, with `AlreadyExists` if the style has a source
850    /// named `id`, and with `InvalidArgument` if `json` isn't a valid source.
851    pub fn add_source_json(&mut self, id: &str, json: &str) -> Result<(), Error> {
852        if !self.loader.document_loaded() {
853            return Err(Error::invalid_state("style is not loaded"));
854        }
855        if self.style.get_source(id).is_some() {
856            return Err(Error::already_exists(format!("source \"{id}\" already exists")));
857        }
858        let value: serde_json::Value = serde_json::from_str(json)
859            .map_err(|error| Error::invalid_argument(format!("style source \"{id}\" is not valid JSON: {error}")))?;
860        let mut error = mln_style::conversion::Error::default();
861        let registry = Arc::clone(self.style.registry());
862        let Some(source) = convert_source(&Convertible::from(&value), &mut error, id, &registry) else {
863            return Err(Error::invalid_argument(format!("style source \"{id}\": {}", error.message)));
864        };
865        self.add_source(source)
866    }
867
868    /// Removes the source `id` from the style and gives it back, unless a
869    /// layer uses it, which logs a warning.
870    pub fn remove_source(&mut self, id: &str) -> Option<Source> {
871        if self.style.get_layers().any(|layer| layer.get_source_id() == id) {
872            Log::warning(Event::General, format!("Source '{id}' is in use, cannot remove"));
873            return None;
874        }
875        let source = self.style.get_source(id)?.clone();
876        self.edit_style(|style| style.apply(Edit::RemoveSource(id.to_owned()))).ok()?;
877        Some(source)
878    }
879
880    /// The style's source `id`.
881    #[must_use]
882    pub fn source(&self, id: &str) -> Option<&Source> {
883        self.style.get_source(id)
884    }
885
886    /// The style's sources, in the order they were added.
887    pub fn sources(&self) -> impl Iterator<Item = &Source> {
888        self.style.get_sources().iter()
889    }
890
891    /// Loads the style document `json`, which replaces the style, and
892    /// cancels a URL load. A document that doesn't parse leaves the style
893    /// as it was and reports [`MapEvent::LoadingFailed`].
894    pub fn load_style_json(&mut self, json: &str) {
895        let events = self.loader.load_json(self.style.registry(), json);
896        self.handle_load_events(events);
897    }
898
899    /// Fetches the style document at `url`, which replaces the style when it
900    /// arrives and parses. The style stays meanwhile, but isn't loaded.
901    pub fn load_style_url(&mut self, url: &str) {
902        let events = self.loader.load_url(url);
903        self.handle_load_events(events);
904    }
905
906    /// The URL of the style document, or `None` for a style loaded from
907    /// JSON or none at all.
908    #[must_use]
909    pub fn style_url(&self) -> Option<&str> {
910        self.loader.url()
911    }
912
913    /// Sets the font faces that every font stack falls back to after the
914    /// style's own, for the style documents that load after this call.
915    ///
916    /// `json` is an array of font files, each an object with a `url` and an
917    /// optional `unicode-range`, as in a font face of a style's `font-faces`.
918    /// It fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) if
919    /// `json` isn't such an array. Without a font-face shaper, the map ignores
920    /// them, as it ignores a style's `font-faces`.
921    pub fn set_fallback_font_faces(&mut self, json: &str) -> Result<(), Error> {
922        let faces = mln_style::parser::parse_fallback_font_faces(json)?;
923        self.set_fallback_font_face_list(faces);
924        Ok(())
925    }
926
927    /// [`set_fallback_font_faces`](Self::set_fallback_font_faces) with faces
928    /// an app has made, such as `FontFace::fallback(url, ranges).with_data(bytes)`
929    /// for a font file it holds in memory.
930    pub fn set_fallback_font_face_list(&mut self, faces: mln_text::glyph::FontFaces) {
931        self.loader.set_fallback_font_faces(Some(Arc::new(faces)));
932    }
933
934    /// The last error of a sprite or a source of the style since its load
935    /// began, which fails still images.
936    #[must_use]
937    pub fn last_style_error(&self) -> Option<&Error> {
938        self.loader.last_error()
939    }
940
941    #[cfg(test)]
942    pub(crate) fn style_loader(&self) -> &StyleLoader {
943        &self.loader
944    }
945
946    /// Whether the style document parsed, and its sprites and sources
947    /// loaded.
948    pub(crate) fn style_loaded(&self) -> bool {
949        self.loader.document_loaded() && self.loader.sprites_loaded() && self.loader.sources_loaded(&self.style)
950    }
951
952    // MARK: - Transitions
953
954    pub fn cancel_transitions(&mut self) {
955        self.transform.cancel_transitions();
956        self.on_update();
957    }
958
959    /// Cancels the commands whose [`AnimationOptions::transition_id`] equals
960    /// `transition_id`, and leaves the others running. Requests an update only
961    /// when a command ended.
962    pub fn cancel_transitions_with_id(&mut self, transition_id: u64) {
963        let ended = self.transform.cancel_transitions_with_id(transition_id);
964        if ended {
965            self.on_update();
966        }
967    }
968
969    /// Moves the camera relative to where it is, as a gesture does
970    /// (the C API's `mln_map_apply_camera_delta`): a pan, a zoom,
971    /// turn and tilt around an anchor, a gesture phase, and the momentum a
972    /// gesture's end continues with. See [`CameraDelta`]. Returns the
973    /// command, whose end [`drain_command_ends`](Self::drain_command_ends)
974    /// reports.
975    pub fn apply_camera_delta(&mut self, delta: &CameraDelta) -> Result<CameraCommandId, CameraError> {
976        let command = self.transform.apply_camera_delta(delta)?;
977        self.camera_mutated = true;
978        self.on_update();
979        Ok(command)
980    }
981
982    /// Moves the camera to absolute values, by a jump, an ease or a flight,
983    /// as a command or as part of a gesture (the C API's
984    /// `mln_map_update_camera`). See [`CameraUpdate`]. Returns the command,
985    /// whose end [`drain_command_ends`](Self::drain_command_ends) reports.
986    pub fn update_camera(&mut self, update: &CameraUpdate) -> CameraCommandId {
987        self.camera_mutated = true;
988        let command = self.transform.update_camera(update);
989        self.on_update();
990        command
991    }
992
993    /// Ends the running camera commands as closed, as when the map closes,
994    /// which [`drain_command_ends`](Self::drain_command_ends) reports. An
995    /// owner that waits for the commands' ends calls it before it drops the
996    /// map.
997    pub fn close_camera(&mut self) {
998        self.transform.close();
999        self.forward_camera_events();
1000    }
1001
1002    /// On the globe, let drags and zooms around a point turn the bearing so
1003    /// the planet keeps its orientation, for maps whose rotation gestures are
1004    /// enabled. Off, the default, they hold the bearing as GL JS does.
1005    pub fn set_globe_free_bearing(&mut self, free_bearing: bool) {
1006        if free_bearing != self.transform.is_globe_free_bearing() {
1007            self.transform.set_globe_free_bearing(free_bearing);
1008            self.changed();
1009        }
1010    }
1011
1012    /// Samples the camera's animations at the host's frame time, from now on,
1013    /// and starts new ones from it: call it at the start of each frame with
1014    /// `Instant::now()`, before rendering. One older than
1015    /// `STALE_FRAME_TIME` counts as
1016    /// unset, so commands made while the host isn't drawing start now. If an
1017    /// animation runs, the map updates for this frame at once. `None` goes
1018    /// back to sampling at `Instant::now()` whenever the map updates. Still
1019    /// images ignore it. See
1020    /// [`Transform::set_frame_time`](crate::transform::Transform::set_frame_time).
1021    pub fn set_frame_time(&mut self, time: Option<Instant>) {
1022        self.transform.set_frame_time(time);
1023        self.sample_frame();
1024    }
1025
1026    /// The clock that [`set_frame_time`](Self::set_frame_time) sets, for a
1027    /// host that sets it from the thread that draws, without updating the
1028    /// map. It then calls [`sample_frame`](Self::sample_frame) for each frame
1029    /// that an animation runs in.
1030    #[must_use]
1031    pub fn frame_clock(&self) -> FrameClock {
1032        self.transform.frame_clock()
1033    }
1034
1035    /// Updates the map for a frame at the frame clock's time, if an
1036    /// animation runs.
1037    pub fn sample_frame(&mut self) {
1038        if self.transform.in_transition() {
1039            self.on_update();
1040        }
1041    }
1042
1043    // MARK: - Camera
1044
1045    // query: the render-test runner's tile mode uses it.
1046    /// The bounds of the area the map shows from `camera`.
1047    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a camera whose
1048    /// corners have no `LatLng`.
1049    pub fn lat_lng_bounds_for_camera(&self, camera: &CameraOptions) -> Result<LatLngBounds, Error> {
1050        let mut shallow = Transform::from_state(self.transform.get_state().clone());
1051        let size = shallow.get_state().get_size();
1052
1053        shallow.jump_to(camera);
1054        if shallow.get_state().is_globe_rendering() {
1055            return globe_bounds(&shallow);
1056        }
1057        Ok(LatLngBounds::hull(
1058            shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(0.0, 0.0), WrapMode::Wrapped)?,
1059            shallow.screen_coordinate_to_lat_lng(
1060                &ScreenCoordinate::new(f64::from(size.width), f64::from(size.height)),
1061                WrapMode::Wrapped,
1062            )?,
1063        ))
1064    }
1065
1066    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a NaN or infinite
1067    /// point.
1068    pub fn move_by(&mut self, point: &ScreenCoordinate, animation: &AnimationOptions) -> Result<(), Error> {
1069        self.camera_mutated = true;
1070        self.transform.move_by(point, animation)?;
1071        self.on_update();
1072        Ok(())
1073    }
1074
1075    // gtests-core: cameraForLatLngBounds, cameraForLatLngs,
1076    // latLngBoundsForCameraUnwrapped (test/map/map.test.cpp).
1077    /// The camera that fits `bounds` in the view, inset by `padding`, at
1078    /// `bearing` and `pitch` (the current ones for `None`). Fails with
1079    /// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a center that has no
1080    /// `LatLng` (padding that pushes it to infinity).
1081    pub fn camera_for_lat_lng_bounds(
1082        &self,
1083        bounds: &LatLngBounds,
1084        padding: &EdgeInsets,
1085        bearing: Option<f64>,
1086        pitch: Option<f64>,
1087    ) -> Result<CameraOptions, Error> {
1088        self.camera_for_lat_lngs(
1089            &[bounds.northwest(), bounds.southwest(), bounds.southeast(), bounds.northeast()],
1090            padding,
1091            bearing,
1092            pitch,
1093        )
1094    }
1095
1096    /// The camera that fits every point of `lat_lngs` in the view, inset by
1097    /// `padding`, at `bearing` and `pitch` (the current ones for `None`).
1098    /// Fails as [`camera_for_lat_lng_bounds`](Self::camera_for_lat_lng_bounds)
1099    /// does.
1100    pub fn camera_for_lat_lngs(
1101        &self,
1102        lat_lngs: &[LatLng],
1103        padding: &EdgeInsets,
1104        bearing: Option<f64>,
1105        pitch: Option<f64>,
1106    ) -> Result<CameraOptions, Error> {
1107        if bearing.is_none() && pitch.is_none() {
1108            return camera_for_lat_lngs(lat_lngs, &self.transform, padding);
1109        }
1110
1111        let mut transform = Transform::from_state(self.transform.get_state().clone());
1112
1113        transform.jump_to(&CameraOptions { bearing, pitch, ..Default::default() });
1114
1115        Ok(CameraOptions {
1116            bearing: Some(mln_math::rad2deg(-transform.get_bearing())),
1117            pitch: Some(mln_math::rad2deg(transform.get_pitch())),
1118            ..camera_for_lat_lngs(lat_lngs, &transform, padding)?
1119        })
1120    }
1121
1122    /// The camera that fits every point of `geometry` (x longitude, y
1123    /// latitude), as [`camera_for_lat_lngs`](Self::camera_for_lat_lngs) fits
1124    /// them. Fails as that does, and with
1125    /// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a point with no
1126    /// `LatLng` (an infinite or NaN coordinate, or a latitude beyond ±90°).
1127    pub fn camera_for_geometry(
1128        &self,
1129        geometry: &Geometry<f64>,
1130        padding: &EdgeInsets,
1131        bearing: Option<f64>,
1132        pitch: Option<f64>,
1133    ) -> Result<CameraOptions, Error> {
1134        let mut points = Vec::new();
1135        for_each_point(geometry, &mut |point| points.push(*point));
1136        let lat_lngs = points.iter().map(|point| LatLng::new(point.y, point.x)).collect::<Result<Vec<_>, _>>()?;
1137        self.camera_for_lat_lngs(&lat_lngs, padding, bearing, pitch)
1138    }
1139
1140    /// The bounds of the area the map shows from `camera`, with the corners
1141    /// unwrapped toward the center, so that the bounds can cross the
1142    /// antimeridian. Fails as
1143    /// [`lat_lng_bounds_for_camera`](Self::lat_lng_bounds_for_camera) does.
1144    pub fn lat_lng_bounds_for_camera_unwrapped(&self, camera: &CameraOptions) -> Result<LatLngBounds, Error> {
1145        let mut shallow = Transform::from_state(self.transform.get_state().clone());
1146        let size = shallow.get_state().get_size();
1147
1148        shallow.jump_to(camera);
1149        if shallow.get_state().is_globe_rendering() {
1150            return globe_bounds(&shallow);
1151        }
1152        let width = f64::from(size.width);
1153        let height = f64::from(size.height);
1154        let mut nw = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(0.0, 0.0), WrapMode::Wrapped)?;
1155        let mut se = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(width, height), WrapMode::Wrapped)?;
1156        let mut ne = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(width, 0.0), WrapMode::Wrapped)?;
1157        let mut sw = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(0.0, height), WrapMode::Wrapped)?;
1158        let center = shallow
1159            .screen_coordinate_to_lat_lng(&ScreenCoordinate::new(width / 2.0, height / 2.0), WrapMode::Wrapped)?;
1160        nw.unwrap_for_shortest_path(&center);
1161        se.unwrap_for_shortest_path(&center);
1162        ne.unwrap_for_shortest_path(&center);
1163        sw.unwrap_for_shortest_path(&center);
1164        let mut bounds = LatLngBounds::hull(nw, se);
1165        bounds.extend(&ne);
1166        bounds.extend(&sw);
1167        bounds.extend(&center);
1168        Ok(bounds)
1169    }
1170
1171    // MARK: - Bounds
1172
1173    pub fn set_bounds(&mut self, options: &BoundOptions) -> Result<(), Error> {
1174        if *options != BoundOptions::default() {
1175            self.changed();
1176        }
1177        let mut change_camera = false;
1178        let mut camera_options = CameraOptions::default();
1179
1180        {
1181            let transform = &mut self.transform;
1182
1183            if let Some(bounds) = options.bounds {
1184                change_camera = true;
1185                transform.set_lat_lng_bounds(bounds)?;
1186            }
1187
1188            if let Some(min_zoom) = options.min_zoom {
1189                transform.set_min_zoom(min_zoom);
1190                // On the globe the lowest zoom falls with latitude; on
1191                // Mercator it is the minimum.
1192                let state = transform.get_state();
1193                let latitude_term = state.get_min_zoom_at_latitude(state.get_lat_lng(WrapMode::Unwrapped).latitude())
1194                    - state.get_min_zoom();
1195                let min_zoom = min_zoom + latitude_term;
1196                if transform.get_zoom() < min_zoom {
1197                    change_camera = true;
1198                    camera_options = CameraOptions { zoom: Some(min_zoom), ..camera_options };
1199                }
1200            }
1201
1202            if let Some(max_zoom) = options.max_zoom {
1203                transform.set_max_zoom(max_zoom);
1204                if transform.get_zoom() > max_zoom {
1205                    change_camera = true;
1206                    camera_options = CameraOptions { zoom: options.max_zoom, ..camera_options };
1207                }
1208            }
1209
1210            if let Some(max_pitch) = options.max_pitch {
1211                transform.set_max_pitch(max_pitch);
1212                if transform.get_pitch() > transform.get_state().get_max_pitch() {
1213                    change_camera = true;
1214                    camera_options = CameraOptions { pitch: options.max_pitch, ..camera_options };
1215                }
1216            }
1217
1218            if let Some(min_pitch) = options.min_pitch {
1219                transform.set_min_pitch(min_pitch);
1220                if transform.get_pitch() < transform.get_state().get_min_pitch() {
1221                    change_camera = true;
1222                    camera_options = CameraOptions { pitch: options.min_pitch, ..camera_options };
1223                }
1224            }
1225        }
1226
1227        if change_camera {
1228            self.jump_to(&camera_options);
1229        }
1230        Ok(())
1231    }
1232
1233    // MARK: - Map options
1234
1235    /// Sets how the map orients and constrains its view, every setting at
1236    /// once.
1237    pub fn set_viewport(&mut self, viewport: &Viewport) {
1238        let state = self.transform.get_state();
1239        let (orientation, constrain_mode, viewport_mode, frustum_offset) = (
1240            state.get_north_orientation(),
1241            state.get_constrain_mode(),
1242            state.get_viewport_mode(),
1243            state.get_frustum_offset(),
1244        );
1245        if viewport.north_orientation != orientation {
1246            self.transform.set_north_orientation(viewport.north_orientation);
1247        }
1248        if viewport.constrain_mode != constrain_mode {
1249            self.transform.set_constrain_mode(viewport.constrain_mode);
1250        }
1251        if viewport.viewport_mode != viewport_mode {
1252            self.transform.set_viewport_mode(viewport.viewport_mode);
1253        }
1254        if viewport.frustum_offset != frustum_offset {
1255            self.transform.set_frustum_offset(&viewport.frustum_offset);
1256        }
1257        self.on_update();
1258    }
1259
1260    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an empty size.
1261    pub fn set_size(&mut self, size: Size) -> Result<(), Error> {
1262        self.transform.resize(size)?;
1263        self.on_update();
1264        Ok(())
1265    }
1266
1267    /// Sets the map's pixel ratio: device pixels per logical pixel. The
1268    /// renderer draws the next frame at the new ratio and lays the loaded
1269    /// tiles out again without loading them, and the style loads its sprites
1270    /// again where the ratio picks their other resolution.
1271    ///
1272    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
1273    /// ratio that isn't finite and positive.
1274    pub fn set_pixel_ratio(&mut self, pixel_ratio: f32) -> Result<(), Error> {
1275        if !pixel_ratio.is_finite() || pixel_ratio <= 0.0 {
1276            return Err(Error::invalid_argument(format!("pixel ratio {pixel_ratio} isn't finite and positive")));
1277        }
1278        if pixel_ratio == self.pixel_ratio {
1279            return Ok(());
1280        }
1281        self.pixel_ratio = pixel_ratio;
1282        let events = self.loader.set_pixel_ratio(pixel_ratio);
1283        self.handle_load_events(events);
1284        self.on_update();
1285        Ok(())
1286    }
1287
1288    // MARK: - Projection mode
1289
1290    pub fn set_projection_mode(&mut self, options: &ProjectionMode) {
1291        self.transform.set_projection_mode(options);
1292        self.on_update();
1293    }
1294
1295    // MARK: - Transform
1296
1297    pub fn get_transform_state(&self) -> TransformState {
1298        self.transform.get_state().clone()
1299    }
1300
1301    // MARK: - Tile settings
1302
1303    /// Sets how the map picks the tiles to load, every setting at once, in
1304    /// the units that its snapshot reports them. Publishes an update when
1305    /// they change.
1306    pub fn set_tile_settings(&mut self, tile: &TileSettings) {
1307        if self.tile != *tile {
1308            self.tile = *tile;
1309            self.on_update();
1310        }
1311    }
1312
1313    // gtests-core: projection and prefetch zoom delta (test/map, test/api).
1314    // MARK: - Projection
1315
1316    pub fn pixel_for_lat_lng(&self, lat_lng: &LatLng) -> ScreenCoordinate {
1317        let transform = &self.transform;
1318        transform.lat_lng_to_screen_coordinate(&transform.get_state().lat_lng_near_center(lat_lng))
1319    }
1320
1321    /// The location under `pixel`. Fails with
1322    /// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a NaN or infinite pixel.
1323    pub fn lat_lng_for_pixel(&self, pixel: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
1324        self.transform.screen_coordinate_to_lat_lng(pixel, wrap_mode)
1325    }
1326
1327    /// Whether the globe hides a location from the camera; a Mercator map
1328    /// hides nothing.
1329    #[cfg(test)]
1330    pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
1331        self.transform.is_location_occluded(lat_lng)
1332    }
1333
1334    pub fn lat_lngs_for_pixels(
1335        &self,
1336        screen_coords: &[ScreenCoordinate],
1337        wrap_mode: WrapMode,
1338    ) -> Result<Vec<LatLng>, Error> {
1339        screen_coords.iter().map(|point| self.lat_lng_for_pixel(point, wrap_mode)).collect()
1340    }
1341
1342    /// Places the camera by its position and orientation, and cancels the
1343    /// running camera commands. A NaN position, or a NaN or zero-length
1344    /// orientation, is ignored; the position's height is clamped to the zoom
1345    /// range.
1346    pub fn set_free_camera_options(&mut self, camera: &mln_map_types::FreeCameraOptions) {
1347        self.transform.set_free_camera_options(camera);
1348        self.camera_mutated = true;
1349        self.on_update();
1350    }
1351
1352    // MARK: - Debug
1353
1354    pub fn set_debug(&mut self, debug_options: MapDebugOptions) {
1355        self.debug_options = debug_options;
1356        self.on_update();
1357    }
1358
1359    /// Shows the rendering stats of the last frames in the top right corner,
1360    /// with a symbol layer (and its source) that the view adds to the style
1361    /// and keeps there, even when the style is replaced. The text needs the
1362    /// style's glyphs. Disabling the view removes them.
1363    pub fn enable_rendering_stats_view(&mut self, value: bool) {
1364        if value != self.rendering_stats_view.is_some() {
1365            self.changed();
1366        }
1367        if value {
1368            if self.rendering_stats_view.is_some() {
1369                return;
1370            }
1371            let view = RenderingStatsView::new(RenderingStatsViewOptions::default());
1372            view.create(self);
1373            self.rendering_stats_view = Some(view);
1374        } else if let Some(view) = self.rendering_stats_view.take() {
1375            view.destroy(self);
1376        }
1377    }
1378
1379    /// Grows with each change to the map's state: each call that changes it,
1380    /// and each change that loading, rendering and animations make.
1381    pub fn generation(&self) -> u64 {
1382        self.generation
1383    }
1384
1385    /// Counts the updates that the map has published for its renderer.
1386    /// An update that a command group holds back counts when it shows.
1387    pub fn update_generation(&self) -> u64 {
1388        self.updates.generation()
1389    }
1390
1391    /// The generation of the update that shows the map's changes so far:
1392    /// [`update_generation`](Self::update_generation), or while a command
1393    /// group holds an update back, the one that the outermost group's end
1394    /// shows.
1395    pub fn pending_update_generation(&self) -> u64 {
1396        self.updates.pending_generation()
1397    }
1398
1399    /// Copies the map's state.
1400    pub fn snapshot(&self) -> MapSnapshot {
1401        let transform = &self.transform;
1402        let state = transform.get_state();
1403        let bounds = state.get_lat_lng_bounds();
1404        let free_camera = state.get_free_camera_options();
1405        MapSnapshot {
1406            generation: self.generation,
1407            update_generation: self.updates.generation(),
1408            debug: self.debug_options,
1409            fully_loaded: self.is_fully_loaded(),
1410            rendering_stats_view_enabled: self.rendering_stats_view.is_some(),
1411            gesture_in_progress: transform.is_gesture_in_progress(),
1412            transition_in_progress: transform.in_transition(),
1413            tile: self.tile,
1414            bounds: CameraBounds {
1415                bounds: (bounds != LatLngBounds::infinite()).then_some(bounds),
1416                min_zoom: state.get_min_zoom(),
1417                max_zoom: state.get_max_zoom(),
1418                min_pitch: mln_math::rad2deg(state.get_min_pitch()),
1419                max_pitch: mln_math::rad2deg(state.get_max_pitch()),
1420            },
1421            free_camera: FreeCamera {
1422                position: free_camera.position.unwrap_or_default(),
1423                orientation: free_camera.orientation.unwrap_or_default(),
1424            },
1425            view: MapView::from_state(state, f64::from(self.pixel_ratio)),
1426            globe_rendering: state.is_globe_rendering(),
1427            globe_free_bearing: transform.is_globe_free_bearing(),
1428        }
1429    }
1430
1431    fn is_fully_loaded(&self) -> bool {
1432        self.style_loaded() && self.renderer_fully_loaded
1433    }
1434
1435    /// Logs the style's sources and their state.
1436    pub fn dump_debug_logs(&self) {
1437        let rule = "-".repeat(80);
1438        Log::info(Event::General, &rule);
1439        Log::info(Event::General, format!("styleURL: {}", self.loader.url().unwrap_or_default()));
1440        for source in self.style.get_sources().iter() {
1441            Log::info(Event::General, format!("Source::id: {}", source.id()));
1442            Log::info(Event::General, format!("Source::loaded: {}", i32::from(self.loader.source_loaded(source.id()))));
1443        }
1444        Log::info(Event::General, &rule);
1445    }
1446}
1447
1448/// The ids of the sources that are in both `before` and `after`, as the same
1449/// instance, and changed from one to the other, in `after`'s order.
1450fn changed_sources(before: &Style, after: &Style) -> Vec<String> {
1451    let (old, new) = (before.get_sources(), after.get_sources());
1452    if Arc::ptr_eq(old, new) {
1453        return Vec::new();
1454    }
1455    new.iter()
1456        .filter(|source| {
1457            old.get(source.id()).is_some_and(|old| old.instance() == source.instance() && !Source::ptr_eq(old, source))
1458        })
1459        .map(|source| source.id().to_owned())
1460        .collect()
1461}
1462
1463// gtests-core: the free function `cameraForLatLngs(latLngs, transform,
1464// padding)` of map.cpp (Map::cameraForLatLngs and MapProjection use it).
1465pub(crate) fn camera_for_lat_lngs(
1466    lat_lngs: &[LatLng],
1467    transform: &Transform,
1468    padding: &EdgeInsets,
1469) -> Result<CameraOptions, Error> {
1470    if lat_lngs.is_empty() {
1471        return Ok(CameraOptions::default());
1472    }
1473    if transform.get_state().is_globe_rendering() {
1474        camera_for_lat_lngs_on_globe(lat_lngs, transform, padding)
1475    } else {
1476        camera_for_lat_lngs_on_screen(lat_lngs, transform, padding)
1477    }
1478}
1479
1480/// Fails as `Map::camera_for_lat_lngs` does.
1481fn camera_for_lat_lngs_on_screen(
1482    lat_lngs: &[LatLng],
1483    transform: &Transform,
1484    padding: &EdgeInsets,
1485) -> Result<CameraOptions, Error> {
1486    let size = transform.get_state().get_size();
1487    // Calculate the bounds of the possibly rotated shape with respect to the viewport.
1488    let mut ne_pixel = ScreenCoordinate::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
1489    let mut sw_pixel = ScreenCoordinate::new(f64::INFINITY, f64::INFINITY);
1490    for lat_lng in lat_lngs {
1491        let pixel = transform.lat_lng_to_screen_coordinate(lat_lng);
1492        // std::min / std::max
1493        sw_pixel.x = if pixel.x < sw_pixel.x { pixel.x } else { sw_pixel.x };
1494        ne_pixel.x = if ne_pixel.x < pixel.x { pixel.x } else { ne_pixel.x };
1495        sw_pixel.y = if pixel.y < sw_pixel.y { pixel.y } else { sw_pixel.y };
1496        ne_pixel.y = if ne_pixel.y < pixel.y { pixel.y } else { ne_pixel.y };
1497    }
1498    let width = ne_pixel.x - sw_pixel.x;
1499    let height = ne_pixel.y - sw_pixel.y;
1500
1501    // Calculate the zoom level.
1502    let mut min_scale = f64::INFINITY;
1503    if width > 0.0 || height > 0.0 {
1504        let mut scale_x = f64::from(size.width) / width;
1505        let mut scale_y = f64::from(size.height) / height;
1506        scale_x -= (padding.left() + padding.right()) / width;
1507        scale_y -= (padding.top() + padding.bottom()) / height;
1508        min_scale = mln_math::fmin(scale_x, scale_y);
1509    }
1510
1511    let mut zoom = transform.get_zoom();
1512    if min_scale > 0.0 {
1513        zoom = mln_math::clamp_f64(
1514            zoom + min_scale.log2(),
1515            transform.get_state().get_min_zoom(),
1516            transform.get_state().get_max_zoom(),
1517        );
1518    } else {
1519        Log::error(
1520            Event::General,
1521            "Unable to calculate appropriate zoom level for bounds. Vertical or horizontal padding is greater than \
1522             map's height or width.",
1523        );
1524    }
1525
1526    // Calculate the center point of a virtual bounds that is extended in all directions by padding.
1527    let center_pixel =
1528        ScreenCoordinate::new(f64::midpoint(ne_pixel.x, sw_pixel.x), f64::midpoint(ne_pixel.y, sw_pixel.y));
1529
1530    Ok(CameraOptions {
1531        center: Some(transform.screen_coordinate_to_lat_lng(&center_pixel, WrapMode::Wrapped)?),
1532        padding: Some(*padding),
1533        zoom: Some(zoom),
1534        ..Default::default()
1535    })
1536}
1537
1538/// GL JS `solveVectorScale`: how much to scale the globe for a surface point
1539/// to land on `target` along one clip axis, or nothing when the equation
1540/// degenerates. Zooming out also moves the camera along `to_center`, so the
1541/// point solved for is `vector * t + to_center * (1 - t)`.
1542fn globe_scale_for_clip_target(
1543    vector: &Vec3,
1544    to_center: &Vec3,
1545    projection: &Mat4,
1546    x_axis: bool,
1547    target: f64,
1548) -> Option<f64> {
1549    let column: [f64; 4] = if x_axis {
1550        [projection[0], projection[4], projection[8], projection[12]]
1551    } else {
1552        [projection[1], projection[5], projection[9], projection[13]]
1553    };
1554    let column_z: [f64; 4] = [projection[3], projection[7], projection[11], projection[15]];
1555
1556    let vector_dot = vector[0] * column[0] + vector[1] * column[1] + vector[2] * column[2];
1557    let vector_dot_z = vector[0] * column_z[0] + vector[1] * column_z[1] + vector[2] * column_z[2];
1558    let to_center_dot = to_center[0] * column[0] + to_center[1] * column[1] + to_center[2] * column[2];
1559    let to_center_dot_z = to_center[0] * column_z[0] + to_center[1] * column_z[1] + to_center[2] * column_z[2];
1560
1561    if to_center_dot + target * vector_dot_z == vector_dot + target * to_center_dot_z
1562        || column_z[3] * (vector_dot - to_center_dot)
1563            + column[3] * (to_center_dot_z - vector_dot_z)
1564            + vector_dot * to_center_dot_z
1565            == to_center_dot * vector_dot_z
1566    {
1567        return None;
1568    }
1569    Some(
1570        (to_center_dot + column[3] - target * to_center_dot_z - target * column_z[3])
1571            / (to_center_dot - vector_dot - target * to_center_dot_z + target * vector_dot_z),
1572    )
1573}
1574
1575fn keep_smallest_scale(smallest: &mut f64, candidate: Option<f64>) {
1576    if let Some(candidate) = candidate
1577        && candidate >= 0.0
1578        && candidate < *smallest
1579    {
1580        *smallest = candidate;
1581    }
1582}
1583
1584/// GL JS `VerticalPerspectiveCameraHelper.cameraForBoxAndBearing`: fit the
1585/// flat world first, then scale the globe until every corner and edge
1586/// midpoint of the bounds is inside the padded viewport, with no pitch.
1587/// Fails as `Map::camera_for_lat_lngs` does.
1588fn camera_for_lat_lngs_on_globe(
1589    lat_lngs: &[LatLng],
1590    transform: &Transform,
1591    padding: &EdgeInsets,
1592) -> Result<CameraOptions, Error> {
1593    let mut flat = Transform::from_state(transform.get_state().clone());
1594    flat.set_projection_definition(&ProjectionDefinition::new(ProjectionType::Mercator));
1595    flat.jump_to(&CameraOptions { pitch: Some(0.0), roll: Some(0.0), ..Default::default() });
1596    let fit = camera_for_lat_lngs_on_screen(lat_lngs, &flat, padding)?;
1597    let (Some(fit_center), Some(fit_zoom)) = (fit.center, fit.zoom) else {
1598        return Ok(fit);
1599    };
1600
1601    // Solve with the padding the returned camera is shown with.
1602    let mut globe = Transform::from_state(transform.get_state().clone());
1603    globe.jump_to(&CameraOptions {
1604        center: Some(fit_center),
1605        zoom: Some(fit_zoom),
1606        padding: Some(*padding),
1607        pitch: Some(0.0),
1608        roll: Some(0.0),
1609        ..Default::default()
1610    });
1611    let state = globe.get_state();
1612    let matrix = state.get_globe_view_projection_matrix();
1613    let size = state.get_size();
1614    let width = f64::from(size.width);
1615    let height = f64::from(size.height);
1616    let left = padding.left() / width * 2.0 - 1.0;
1617    let right = (width - padding.right()) / width * 2.0 - 1.0;
1618    let top = padding.top() / height * -2.0 + 1.0;
1619    let bottom = (height - padding.bottom()) / height * -2.0 + 1.0;
1620
1621    let mut bounds = LatLngBounds::empty();
1622    for lat_lng in lat_lngs {
1623        bounds.extend(lat_lng);
1624    }
1625    let west = bounds.west();
1626    let east = bounds.east();
1627    let north = bounds.north();
1628    let south = bounds.south();
1629    let mid_longitude = west + VerticalPerspectiveProjection::difference_of_angles_degrees(west, east) * 0.5;
1630    let mid_latitude = north + VerticalPerspectiveProjection::difference_of_angles_degrees(north, south) * 0.5;
1631    let samples = [
1632        LatLng::new(north, west)?,
1633        LatLng::new(north, east)?,
1634        LatLng::new(south, west)?,
1635        LatLng::new(south, east)?,
1636        LatLng::new(mid_latitude, east)?,
1637        LatLng::new(mid_latitude, west)?,
1638        LatLng::new(north, mid_longitude)?,
1639        LatLng::new(south, mid_longitude)?,
1640    ];
1641    let to_center = VerticalPerspectiveProjection::surface_vector(&fit_center);
1642
1643    let mut smallest = f64::INFINITY;
1644    for sample in &samples {
1645        let vector = VerticalPerspectiveProjection::surface_vector(sample);
1646        if left < 0.0 {
1647            keep_smallest_scale(&mut smallest, globe_scale_for_clip_target(&vector, &to_center, &matrix, true, left));
1648        }
1649        if right > 0.0 {
1650            keep_smallest_scale(&mut smallest, globe_scale_for_clip_target(&vector, &to_center, &matrix, true, right));
1651        }
1652        if top > 0.0 {
1653            keep_smallest_scale(&mut smallest, globe_scale_for_clip_target(&vector, &to_center, &matrix, false, top));
1654        }
1655        if bottom < 0.0 {
1656            keep_smallest_scale(
1657                &mut smallest,
1658                globe_scale_for_clip_target(&vector, &to_center, &matrix, false, bottom),
1659            );
1660        }
1661    }
1662    if !smallest.is_finite() || smallest == 0.0 {
1663        Log::warning(Event::General, "Unable to fit the bounds on the globe; keeping the flat fit.");
1664        return Ok(fit);
1665    }
1666    Ok(CameraOptions {
1667        zoom: Some(f64::min(globe.get_zoom() + state.scale_zoom(smallest), state.get_max_zoom())),
1668        ..fit
1669    })
1670}
1671
1672/// GL JS's globe bounds: the farthest of eight edge points on each side of
1673/// the center, where points off the planet fall on its horizon, widened to
1674/// every longitude when a pole is on screen.
1675/// Fails as `Map::lat_lng_bounds_for_camera` does.
1676fn globe_bounds(transform: &Transform) -> Result<LatLngBounds, Error> {
1677    let width = f64::from(transform.get_state().get_size().width);
1678    let height = f64::from(transform.get_state().get_size().height);
1679    let center = transform.get_lat_lng(WrapMode::Wrapped);
1680    let mut west = 0.0;
1681    let mut east = 0.0;
1682    let mut south = 0.0;
1683    let mut north = 0.0;
1684    for point in [
1685        ScreenCoordinate::new(0.0, 0.0),
1686        ScreenCoordinate::new(width / 2.0, 0.0),
1687        ScreenCoordinate::new(width, 0.0),
1688        ScreenCoordinate::new(width, height / 2.0),
1689        ScreenCoordinate::new(width, height),
1690        ScreenCoordinate::new(width / 2.0, height),
1691        ScreenCoordinate::new(0.0, height),
1692        ScreenCoordinate::new(0.0, height / 2.0),
1693    ] {
1694        let lat_lng = transform.screen_coordinate_to_lat_lng(&point, WrapMode::Wrapped)?;
1695        let longitude =
1696            VerticalPerspectiveProjection::difference_of_angles_degrees(center.longitude(), lat_lng.longitude());
1697        let latitude =
1698            VerticalPerspectiveProjection::difference_of_angles_degrees(center.latitude(), lat_lng.latitude());
1699        west = f64::min(west, longitude);
1700        east = f64::max(east, longitude);
1701        south = f64::min(south, latitude);
1702        north = f64::max(north, latitude);
1703    }
1704    west += center.longitude();
1705    east += center.longitude();
1706    south += center.latitude();
1707    north += center.latitude();
1708
1709    let on_screen = |pole: &LatLng| {
1710        // In front of the camera and inside its depth range, as GL JS's
1711        // isSurfacePointOnScreen asks.
1712        let (_, clip) = VerticalPerspectiveProjection::lat_lng_to_screen_coordinate(transform.get_state(), pole);
1713        if clip[3] <= 0.0 || (clip[2] / clip[3]).abs() >= 1.0 {
1714            return false;
1715        }
1716        let point = transform.lat_lng_to_screen_coordinate(pole);
1717        !transform.get_state().is_location_occluded(pole)
1718            && point.x > 0.0
1719            && point.x < width
1720            && point.y > 0.0
1721            && point.y < height
1722    };
1723    if on_screen(&LatLng::new(90.0, 0.0)?) {
1724        north = 90.0;
1725        west = -180.0;
1726        east = 180.0;
1727    }
1728    if on_screen(&LatLng::new(-90.0, 0.0)?) {
1729        south = -90.0;
1730        west = -180.0;
1731        east = 180.0;
1732    }
1733    Ok(LatLngBounds::hull(LatLng::new(south, west)?, LatLng::new(north, east)?))
1734}