Skip to main content

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