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