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