Skip to main content

mln_map/
map.rs

1// Ports include/mln/map/map.hpp and src/mln/map/map.cpp (the parts M1 runs).
2
3use std::cell::Ref;
4use std::rc::Rc;
5use std::sync::Arc;
6
7use mln_map_types::{
8    AnimationOptions, BoundOptions, CameraOptions, ConstrainMode, MapDebugOptions, MapMode, NorthOrientation,
9    ProjectionMode, TileLodMode, TransformState, ViewportMode,
10};
11use mln_renderer::{ExceptionPtr, RendererFrontend};
12use mln_storage::{ClientOptions, FileSource, FileSourceManager, FileSourceType, ResourceOptions};
13use mln_style::Style;
14use mln_util::exception::MisuseException;
15use mln_util::geo::{EdgeInsets, LatLng, LatLngBounds, ScreenCoordinate, WrapMode};
16use mln_util::size::Size;
17
18use crate::map_impl::{MapImpl, StillImageCallback, StillImageRequest, StyleMut};
19use crate::map_observer::MapObserver;
20use crate::map_options::MapOptions;
21
22pub struct Map {
23    impl_: Rc<MapImpl>,
24}
25
26impl Map {
27    /// `Map(RendererFrontend&, MapObserver&, const MapOptions&)` with the
28    /// default `ResourceOptions()` and `ClientOptions()`.
29    ///
30    /// C++ keeps a reference to the frontend; frontends are handles here
31    /// (`Clone` shares the same renderer), so the map keeps a clone.
32    pub fn new<F>(frontend: &F, observer: Rc<dyn MapObserver>, map_options: MapOptions) -> Map
33    where
34        F: RendererFrontend + Clone + 'static,
35    {
36        Self::with_resource_options(
37            frontend,
38            observer,
39            map_options,
40            &ResourceOptions::default(),
41            &ClientOptions::default(),
42        )
43    }
44
45    /// `Map(RendererFrontend&, MapObserver&, const MapOptions&, const
46    /// ResourceOptions&, const ClientOptions&)`: the file source is the
47    /// FileSourceManager's `ResourceLoader` for these options.
48    // TODO(port): ActionJournalOptions.
49    pub fn with_resource_options<F>(
50        frontend: &F,
51        observer: Rc<dyn MapObserver>,
52        map_options: MapOptions,
53        resource_options: &ResourceOptions,
54        client_options: &ClientOptions,
55    ) -> Map
56    where
57        F: RendererFrontend + Clone + 'static,
58    {
59        let file_source =
60            FileSourceManager::get().get_file_source(FileSourceType::ResourceLoader, resource_options, client_options);
61        Map { impl_: MapImpl::new(Box::new(frontend.clone()), observer, file_source, &map_options) }
62    }
63
64    // gtests-core: the C++ tests' `MapAdapter` (test/include/mln/test/
65    // map_adapter.hpp), i.e. `Map(std::make_unique<Map::Impl>(frontend,
66    // observer, fileSource, options))`: a map over a given file source.
67    /// `Map(std::unique_ptr<Impl>)` with `Impl(frontend, observer, fileSource, mapOptions)`.
68    pub fn with_file_source<F>(
69        frontend: &F,
70        observer: Rc<dyn MapObserver>,
71        file_source: Arc<dyn FileSource>,
72        map_options: MapOptions,
73    ) -> Map
74    where
75        F: RendererFrontend + Clone + 'static,
76    {
77        Map { impl_: MapImpl::new(Box::new(frontend.clone()), observer, Some(file_source), &map_options) }
78    }
79
80    /// `getClientOptions()`.
81    pub fn get_client_options(&self) -> ClientOptions {
82        match &self.impl_.file_source {
83            Some(file_source) => file_source.get_client_options(),
84            None => ClientOptions::default(),
85        }
86    }
87
88    /// Register a callback that will get called (on the render thread) when
89    /// all resources have been loaded and a complete render occurs.
90    pub fn render_still(&mut self, callback: StillImageCallback) {
91        let impl_ = &self.impl_;
92        if impl_.mode != MapMode::Static && impl_.mode != MapMode::Tile {
93            callback(Some(misuse("Map is not in static or tile image render modes")));
94            return;
95        }
96
97        if impl_.still_image_request.borrow().is_some() {
98            callback(Some(misuse("Map is currently rendering an image")));
99            return;
100        }
101
102        let last_error = impl_.style.borrow().impl_.get_last_error();
103        if let Some(error) = last_error {
104            callback(Some(error));
105            return;
106        }
107
108        *impl_.still_image_request.borrow_mut() = Some(StillImageRequest { callback });
109
110        impl_.on_update();
111    }
112
113    /// `renderStill(const CameraOptions&, MapDebugOptions, StillImageCallback)`.
114    pub fn render_still_with_camera(
115        &mut self,
116        camera: &CameraOptions,
117        debug_options: MapDebugOptions,
118        callback: StillImageCallback,
119    ) {
120        self.impl_.camera_mutated.set(true);
121        self.impl_.debug_options.set(debug_options);
122        self.impl_.transform.borrow_mut().jump_to(camera);
123        self.render_still(callback);
124    }
125
126    /// Triggers a repaint.
127    pub fn trigger_repaint(&mut self) {
128        self.impl_.on_update();
129    }
130
131    // MARK: - Style
132
133    /// `const style::Style& getStyle() const`.
134    pub fn get_style(&self) -> Ref<'_, Style> {
135        self.impl_.style.borrow()
136    }
137
138    /// `style::Style& getStyle()`: a guard that derefs to `&mut Style`; the
139    /// style's observer calls made through it reach the map when it drops.
140    pub fn get_style_mut(&mut self) -> StyleMut<'_> {
141        StyleMut::new(&self.impl_)
142    }
143
144    // TODO(port): setStyle(std::unique_ptr<style::Style>).
145
146    // MARK: - Transitions
147
148    pub fn cancel_transitions(&mut self) {
149        self.impl_.transform.borrow_mut().cancel_transitions();
150        self.impl_.on_update();
151    }
152
153    pub fn set_gesture_in_progress(&mut self, in_progress: bool) {
154        self.impl_.transform.borrow_mut().set_gesture_in_progress(in_progress);
155        self.impl_.on_update();
156    }
157
158    pub fn is_gesture_in_progress(&self) -> bool {
159        self.impl_.transform.borrow().is_gesture_in_progress()
160    }
161
162    pub fn is_rotating(&self) -> bool {
163        self.impl_.transform.borrow().is_rotating()
164    }
165
166    pub fn is_scaling(&self) -> bool {
167        self.impl_.transform.borrow().is_scaling()
168    }
169
170    pub fn is_panning(&self) -> bool {
171        self.impl_.transform.borrow().is_panning()
172    }
173
174    // MARK: - Camera
175
176    pub fn get_camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
177        self.impl_.transform.borrow().get_camera_options(padding)
178    }
179
180    pub fn jump_to(&mut self, camera: &CameraOptions) {
181        self.impl_.jump_to(camera);
182    }
183
184    // query: the render-test runner's tile mode uses it.
185    /// `latLngBoundsForCamera(camera)`.
186    pub fn lat_lng_bounds_for_camera(&self, camera: &CameraOptions) -> mln_util::geo::LatLngBounds {
187        let mut shallow = crate::transform::Transform::from_state(self.impl_.transform.borrow().get_state().clone());
188        let size = shallow.get_state().get_size();
189
190        shallow.jump_to(camera);
191        mln_util::geo::LatLngBounds::hull(
192            shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(0.0, 0.0), mln_util::geo::WrapMode::Wrapped),
193            shallow.screen_coordinate_to_lat_lng(
194                &ScreenCoordinate::new(f64::from(size.width), f64::from(size.height)),
195                mln_util::geo::WrapMode::Wrapped,
196            ),
197        )
198    }
199
200    pub fn ease_to(&mut self, camera: &CameraOptions, animation: &AnimationOptions) {
201        self.impl_.camera_mutated.set(true);
202        self.impl_.transform.borrow_mut().ease_to(camera, animation);
203        self.impl_.on_update();
204    }
205
206    pub fn fly_to(&mut self, camera: &CameraOptions, animation: &AnimationOptions) {
207        self.impl_.camera_mutated.set(true);
208        self.impl_.transform.borrow_mut().fly_to(camera, animation, false);
209        self.impl_.on_update();
210    }
211
212    pub fn move_by(&mut self, point: &ScreenCoordinate, animation: &AnimationOptions) {
213        self.impl_.camera_mutated.set(true);
214        self.impl_.transform.borrow_mut().move_by(point, animation);
215        self.impl_.on_update();
216    }
217
218    pub fn pitch_by(&mut self, pitch: f64, animation: &AnimationOptions) {
219        let current = mln_math::rad2deg(self.impl_.transform.borrow().get_pitch());
220        self.ease_to(&CameraOptions::default().with_pitch(Some(current - pitch)), animation);
221    }
222
223    pub fn scale_by(&mut self, scale: f64, anchor: Option<ScreenCoordinate>, animation: &AnimationOptions) {
224        let zoom = {
225            let transform = self.impl_.transform.borrow();
226            transform.get_zoom() + transform.get_state().scale_zoom(scale)
227        };
228        self.ease_to(&CameraOptions::default().with_zoom(Some(zoom)).with_anchor(anchor), animation);
229    }
230
231    pub fn rotate_by(&mut self, first: &ScreenCoordinate, second: &ScreenCoordinate, animation: &AnimationOptions) {
232        self.impl_.camera_mutated.set(true);
233        self.impl_.transform.borrow_mut().rotate_by(first, second, animation);
234        self.impl_.on_update();
235    }
236
237    // gtests-core: cameraForLatLngBounds, cameraForLatLngs,
238    // latLngBoundsForCameraUnwrapped (test/map/map.test.cpp).
239    /// `cameraForLatLngBounds(bounds, padding, bearing, pitch)`.
240    pub fn camera_for_lat_lng_bounds(
241        &self,
242        bounds: &LatLngBounds,
243        padding: &EdgeInsets,
244        bearing: Option<f64>,
245        pitch: Option<f64>,
246    ) -> CameraOptions {
247        self.camera_for_lat_lngs(
248            &[bounds.northwest(), bounds.southwest(), bounds.southeast(), bounds.northeast()],
249            padding,
250            bearing,
251            pitch,
252        )
253    }
254
255    /// `cameraForLatLngs(latLngs, padding, bearing, pitch)`.
256    pub fn camera_for_lat_lngs(
257        &self,
258        lat_lngs: &[LatLng],
259        padding: &EdgeInsets,
260        bearing: Option<f64>,
261        pitch: Option<f64>,
262    ) -> CameraOptions {
263        if bearing.is_none() && pitch.is_none() {
264            return camera_for_lat_lngs(lat_lngs, &self.impl_.transform.borrow(), padding);
265        }
266
267        let mut transform = crate::transform::Transform::from_state(self.impl_.transform.borrow().get_state().clone());
268
269        transform.jump_to(&CameraOptions::default().with_bearing(bearing).with_pitch(pitch));
270
271        camera_for_lat_lngs(lat_lngs, &transform, padding)
272            .with_bearing(Some(mln_math::rad2deg(-transform.get_bearing())))
273            .with_pitch(Some(mln_math::rad2deg(transform.get_pitch())))
274    }
275
276    // TODO(port): cameraForGeometry.
277
278    /// `latLngBoundsForCameraUnwrapped(camera)`.
279    pub fn lat_lng_bounds_for_camera_unwrapped(&self, camera: &CameraOptions) -> LatLngBounds {
280        let mut shallow = crate::transform::Transform::from_state(self.impl_.transform.borrow().get_state().clone());
281        let size = shallow.get_state().get_size();
282
283        shallow.jump_to(camera);
284        let width = f64::from(size.width);
285        let height = f64::from(size.height);
286        let mut nw = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(0.0, 0.0), WrapMode::Wrapped);
287        let mut se = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(width, height), WrapMode::Wrapped);
288        let mut ne = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(width, 0.0), WrapMode::Wrapped);
289        let mut sw = shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(0.0, height), WrapMode::Wrapped);
290        let center =
291            shallow.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(width / 2.0, height / 2.0), WrapMode::Wrapped);
292        nw.unwrap_for_shortest_path(&center);
293        se.unwrap_for_shortest_path(&center);
294        ne.unwrap_for_shortest_path(&center);
295        sw.unwrap_for_shortest_path(&center);
296        let mut bounds = LatLngBounds::hull(nw, se);
297        bounds.extend(&ne);
298        bounds.extend(&sw);
299        bounds.extend(&center);
300        bounds
301    }
302
303    // MARK: - Bounds
304
305    pub fn set_bounds(&mut self, options: &BoundOptions) -> Result<(), String> {
306        let mut change_camera = false;
307        let mut camera_options = CameraOptions::default();
308
309        {
310            let mut transform = self.impl_.transform.borrow_mut();
311
312            if let Some(bounds) = options.bounds {
313                change_camera = true;
314                transform.set_lat_lng_bounds(bounds)?;
315            }
316
317            if let Some(min_zoom) = options.min_zoom {
318                transform.set_min_zoom(min_zoom);
319                if transform.get_zoom() < min_zoom {
320                    change_camera = true;
321                    camera_options = camera_options.with_zoom(options.min_zoom);
322                }
323            }
324
325            if let Some(max_zoom) = options.max_zoom {
326                transform.set_max_zoom(max_zoom);
327                if transform.get_zoom() > max_zoom {
328                    change_camera = true;
329                    camera_options = camera_options.with_zoom(options.max_zoom);
330                }
331            }
332
333            if let Some(max_pitch) = options.max_pitch {
334                transform.set_max_pitch(max_pitch);
335                if transform.get_pitch() > transform.get_state().get_max_pitch() {
336                    change_camera = true;
337                    camera_options = camera_options.with_pitch(options.max_pitch);
338                }
339            }
340
341            if let Some(min_pitch) = options.min_pitch {
342                transform.set_min_pitch(min_pitch);
343                if transform.get_pitch() < transform.get_state().get_min_pitch() {
344                    change_camera = true;
345                    camera_options = camera_options.with_pitch(options.min_pitch);
346                }
347            }
348        }
349
350        if change_camera {
351            self.jump_to(&camera_options);
352        }
353        Ok(())
354    }
355
356    /// Returns the current map bound options. All optional fields in
357    /// BoundOptions are set.
358    pub fn get_bounds(&self) -> BoundOptions {
359        let transform = self.impl_.transform.borrow();
360        let state = transform.get_state();
361        BoundOptions::default()
362            .with_lat_lng_bounds(state.get_lat_lng_bounds())
363            .with_min_zoom(state.get_min_zoom())
364            .with_max_zoom(state.get_max_zoom())
365            .with_min_pitch(mln_math::rad2deg(state.get_min_pitch()))
366            .with_max_pitch(mln_math::rad2deg(state.get_max_pitch()))
367    }
368
369    // MARK: - Map options
370
371    pub fn set_north_orientation(&mut self, orientation: NorthOrientation) {
372        self.impl_.transform.borrow_mut().set_north_orientation(orientation);
373        self.impl_.on_update();
374    }
375
376    pub fn set_constrain_mode(&mut self, mode: ConstrainMode) {
377        self.impl_.transform.borrow_mut().set_constrain_mode(mode);
378        self.impl_.on_update();
379    }
380
381    pub fn set_viewport_mode(&mut self, mode: ViewportMode) {
382        self.impl_.transform.borrow_mut().set_viewport_mode(mode);
383        self.impl_.on_update();
384    }
385
386    /// C++ throws "failed to resize: size is empty"; the port returns it.
387    pub fn set_size(&mut self, size: Size) -> Result<(), String> {
388        self.impl_.transform.borrow_mut().resize(size)?;
389        self.impl_.on_update();
390        Ok(())
391    }
392
393    pub fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
394        self.impl_.transform.borrow_mut().set_frustum_offset(frustum_offset);
395        self.impl_.on_update();
396    }
397
398    pub fn get_frustum_offset(&self) -> EdgeInsets {
399        self.impl_.transform.borrow().get_frustum_offset()
400    }
401
402    pub fn get_map_options(&self) -> MapOptions {
403        let transform = self.impl_.transform.borrow();
404        let state = transform.get_state();
405        MapOptions::new()
406            .with_north_orientation(transform.get_north_orientation())
407            .with_map_mode(self.impl_.mode)
408            .with_constrain_mode(state.get_constrain_mode())
409            .with_viewport_mode(state.get_viewport_mode())
410            .with_cross_source_collisions(self.impl_.cross_source_collisions)
411            .with_size(state.get_size())
412            .with_pixel_ratio(self.impl_.pixel_ratio)
413    }
414
415    // MARK: - Projection mode
416
417    pub fn set_projection_mode(&mut self, options: &ProjectionMode) {
418        self.impl_.transform.borrow_mut().set_projection_mode(options);
419        self.impl_.on_update();
420    }
421
422    pub fn get_projection_mode(&self) -> ProjectionMode {
423        self.impl_.transform.borrow().get_projection_mode()
424    }
425
426    // MARK: - Transform
427
428    pub fn get_transform_state(&self) -> TransformState {
429        self.impl_.transform.borrow().get_state().clone()
430    }
431
432    // MARK: - Tile LOD
433
434    pub fn set_tile_lod_min_radius(&mut self, radius: f64) {
435        if self.impl_.tile_lod_min_radius.get() == radius {
436            return;
437        }
438        self.impl_.tile_lod_min_radius.set(radius);
439        self.impl_.on_update();
440    }
441
442    pub fn get_tile_lod_min_radius(&self) -> f64 {
443        self.impl_.tile_lod_min_radius.get()
444    }
445
446    pub fn set_tile_lod_scale(&mut self, scale: f64) {
447        if self.impl_.tile_lod_scale.get() == scale {
448            return;
449        }
450        self.impl_.tile_lod_scale.set(scale);
451        self.impl_.on_update();
452    }
453
454    pub fn get_tile_lod_scale(&self) -> f64 {
455        self.impl_.tile_lod_scale.get()
456    }
457
458    pub fn set_tile_lod_pitch_threshold(&mut self, threshold: f64) {
459        if self.impl_.tile_lod_pitch_threshold.get() == threshold {
460            return;
461        }
462        self.impl_.tile_lod_pitch_threshold.set(threshold);
463        self.impl_.on_update();
464    }
465
466    pub fn get_tile_lod_pitch_threshold(&self) -> f64 {
467        self.impl_.tile_lod_pitch_threshold.get()
468    }
469
470    pub fn set_tile_lod_zoom_shift(&mut self, shift: f64) {
471        if self.impl_.tile_lod_zoom_shift.get() == shift {
472            return;
473        }
474        self.impl_.tile_lod_zoom_shift.set(shift);
475        self.impl_.on_update();
476    }
477
478    pub fn get_tile_lod_zoom_shift(&self) -> f64 {
479        self.impl_.tile_lod_zoom_shift.get()
480    }
481
482    pub fn set_tile_lod_mode(&mut self, mode: TileLodMode) {
483        if self.impl_.tile_lod_mode.get() == mode {
484            return;
485        }
486        self.impl_.tile_lod_mode.set(mode);
487        self.impl_.on_update();
488    }
489
490    pub fn get_tile_lod_mode(&self) -> TileLodMode {
491        self.impl_.tile_lod_mode.get()
492    }
493
494    // gtests-core: projection and prefetch zoom delta (test/map, test/api).
495    // MARK: - Projection
496
497    /// `pixelForLatLng(latLng)`.
498    pub fn pixel_for_lat_lng(&self, lat_lng: &LatLng) -> ScreenCoordinate {
499        // If the center and point longitudes are not in the same side of the
500        // antimeridian, we unwrap the point longitude so it would be seen if
501        // e.g. the next antimeridian side is visible.
502        let transform = self.impl_.transform.borrow();
503        let mut unwrapped_lat_lng = lat_lng.wrapped();
504        unwrapped_lat_lng.unwrap_for_shortest_path(&transform.get_lat_lng(WrapMode::Wrapped));
505        transform.lat_lng_to_screen_coordinate(&unwrapped_lat_lng)
506    }
507
508    /// `latLngForPixel(pixel, wrapMode)`.
509    pub fn lat_lng_for_pixel(&self, pixel: &ScreenCoordinate, wrap_mode: WrapMode) -> LatLng {
510        self.impl_.transform.borrow().screen_coordinate_to_lat_lng(pixel, wrap_mode)
511    }
512
513    /// `pixelsForLatLngs(latLngs)`.
514    pub fn pixels_for_lat_lngs(&self, lat_lngs: &[LatLng]) -> Vec<ScreenCoordinate> {
515        lat_lngs.iter().map(|lat_lng| self.pixel_for_lat_lng(lat_lng)).collect()
516    }
517
518    /// `latLngsForPixels(screenCoords, wrapMode)`.
519    pub fn lat_lngs_for_pixels(&self, screen_coords: &[ScreenCoordinate], wrap_mode: WrapMode) -> Vec<LatLng> {
520        screen_coords.iter().map(|point| self.lat_lng_for_pixel(point, wrap_mode)).collect()
521    }
522
523    /// `setPrefetchZoomDelta(delta)`.
524    pub fn set_prefetch_zoom_delta(&mut self, delta: u8) {
525        if self.impl_.prefetch_zoom_delta.get() == delta {
526            return;
527        }
528        self.impl_.prefetch_zoom_delta.set(delta);
529        self.impl_.on_update();
530    }
531
532    /// `getPrefetchZoomDelta()`.
533    pub fn get_prefetch_zoom_delta(&self) -> u8 {
534        self.impl_.prefetch_zoom_delta.get()
535    }
536
537    /// `getFreeCameraOptions()`.
538    pub fn get_free_camera_options(&self) -> mln_map_types::FreeCameraOptions {
539        self.impl_.transform.borrow().get_free_camera_options()
540    }
541
542    // TODO(port): annotations, rendering stats view, setFreeCameraOptions,
543    // rendered features.
544
545    // MARK: - Debug
546
547    pub fn set_debug(&mut self, debug_options: MapDebugOptions) {
548        self.impl_.debug_options.set(debug_options);
549        self.impl_.on_update();
550    }
551
552    pub fn get_debug(&self) -> MapDebugOptions {
553        self.impl_.debug_options.get()
554    }
555
556    pub fn is_fully_loaded(&self) -> bool {
557        self.impl_.style.borrow().impl_.is_loaded() && self.impl_.renderer_fully_loaded.get()
558    }
559}
560
561fn misuse(message: &str) -> ExceptionPtr {
562    MisuseException::ptr(message)
563}
564
565// gtests-core: the free function `cameraForLatLngs(latLngs, transform,
566// padding)` of map.cpp (Map::cameraForLatLngs and MapProjection use it).
567pub(crate) fn camera_for_lat_lngs(
568    lat_lngs: &[LatLng],
569    transform: &crate::transform::Transform,
570    padding: &EdgeInsets,
571) -> CameraOptions {
572    if lat_lngs.is_empty() {
573        return CameraOptions::default();
574    }
575    let size = transform.get_state().get_size();
576    // Calculate the bounds of the possibly rotated shape with respect to the viewport.
577    let mut ne_pixel = ScreenCoordinate::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
578    let mut sw_pixel = ScreenCoordinate::new(f64::INFINITY, f64::INFINITY);
579    for lat_lng in lat_lngs {
580        let pixel = transform.lat_lng_to_screen_coordinate(lat_lng);
581        // std::min / std::max
582        sw_pixel.x = if pixel.x < sw_pixel.x { pixel.x } else { sw_pixel.x };
583        ne_pixel.x = if ne_pixel.x < pixel.x { pixel.x } else { ne_pixel.x };
584        sw_pixel.y = if pixel.y < sw_pixel.y { pixel.y } else { sw_pixel.y };
585        ne_pixel.y = if ne_pixel.y < pixel.y { pixel.y } else { ne_pixel.y };
586    }
587    let width = ne_pixel.x - sw_pixel.x;
588    let height = ne_pixel.y - sw_pixel.y;
589
590    // Calculate the zoom level.
591    let mut min_scale = f64::INFINITY;
592    if width > 0.0 || height > 0.0 {
593        let mut scale_x = f64::from(size.width) / width;
594        let mut scale_y = f64::from(size.height) / height;
595        scale_x -= (padding.left() + padding.right()) / width;
596        scale_y -= (padding.top() + padding.bottom()) / height;
597        min_scale = mln_math::min_f64(scale_x, scale_y);
598    }
599
600    let mut zoom = transform.get_zoom();
601    if min_scale > 0.0 {
602        zoom = mln_math::clamp_f64(
603            zoom + mln_math::log2(min_scale),
604            transform.get_state().get_min_zoom(),
605            transform.get_state().get_max_zoom(),
606        );
607    } else {
608        mln_util::logging::Log::error(
609            mln_util::logging::Event::General,
610            "Unable to calculate appropriate zoom level for bounds. Vertical or horizontal padding is greater than \
611             map's height or width.",
612        );
613    }
614
615    // Calculate the center point of a virtual bounds that is extended in all directions by padding.
616    let center_pixel = ScreenCoordinate::new((ne_pixel.x + sw_pixel.x) / 2.0, (ne_pixel.y + sw_pixel.y) / 2.0);
617
618    CameraOptions::default()
619        .with_center(Some(transform.screen_coordinate_to_lat_lng(&center_pixel, WrapMode::Wrapped)))
620        .with_padding(Some(*padding))
621        .with_zoom(Some(zoom))
622}