1use std::f64::consts::PI;
2
3use constants::TILE_SIZE_D;
4use geometry::Point;
5use glam::{DQuat, DVec3};
6use mln_style::constants;
7use mln_style::error::Error;
8use mln_style::geo::{LatLng, LatLngBounds, WrapMode};
9use mln_style::size::Size;
10use mln_style::types::ProjectionDefinition;
11
12use crate::camera::camera::{CameraOptions, FreeCameraOptions};
13use crate::camera::camera_limits::CameraLimits;
14use crate::camera::camera_pose::CameraPose;
15use crate::camera::ground::GroundHit;
16use crate::camera::mode::{ConstrainMode, ViewportMode};
17use crate::camera::vertical_perspective_projection::VerticalPerspectiveProjection;
18use crate::camera::view::{
19 NorthOrientation, View, ViewParams, map_offset, max_mercator_horizon_angle, scale_zoom, zoom_scale,
20};
21use crate::geo::constants::M2PI;
22use crate::geo::projection::Projection;
23use crate::geo::{EdgeInsets, ScreenCoordinate};
24
25fn lat_lng_from_mercator(mercator_coordinate: Point<f64>, wrap_mode: WrapMode) -> Result<LatLng, Error> {
26 LatLng::with_mode(
27 mln_style::math::rad2deg(2.0 * (PI - mercator_coordinate.y * 2.0 * PI).exp().atan() - (PI / 2.0)),
28 mercator_coordinate.x * 360.0 - 180.0,
29 wrap_mode,
30 )
31}
32
33#[derive(Clone, Debug, PartialEq)]
38pub struct TransformState {
39 view: View,
40 limits: CameraLimits,
41}
42
43impl Default for TransformState {
44 fn default() -> Self {
45 TransformState::new(ConstrainMode::HeightOnly, ViewportMode::Default)
46 }
47}
48
49impl TransformState {
50 #[must_use]
51 pub(crate) fn new(constrain_mode: ConstrainMode, viewport_mode: ViewportMode) -> Self {
52 TransformState {
53 view: View::new(ViewParams::new(constrain_mode, viewport_mode)),
54 limits: CameraLimits::default(),
55 }
56 }
57
58 pub(crate) fn from_parts(params: ViewParams, limits: CameraLimits) -> Self {
60 let mut state = TransformState { view: View::new(params), limits };
61 state.update(|_| ());
62 state
63 }
64
65 #[must_use]
67 pub fn view(&self) -> &View {
68 &self.view
69 }
70
71 fn update(&mut self, change: impl FnOnce(&mut ViewParams)) {
74 let mut params = *self.view.params();
75 change(&mut params);
76 params.center_wrap = if params.projection_transition > 0.0 && self.limits.bounds == LatLngBounds::default() {
77 WrapMode::Wrapped
78 } else {
79 WrapMode::Unwrapped
80 };
81 if params != *self.view.params() {
82 self.view = View::new(params);
83 }
84 }
85
86 pub fn set_projection_definition(&mut self, definition: &ProjectionDefinition) {
89 let transition = definition.transition_state();
90 let previous = self.view.projection_transition();
91 self.update(|p| {
92 p.projection_definition = *definition;
93 p.projection_transition = transition;
94 });
95 let leaves_globe = transition == 0.0 && previous > 0.0;
99 if leaves_globe && !self.view.size().is_empty() {
100 let wrap_mode =
101 if self.limits.bounds == LatLngBounds::default() { WrapMode::Wrapped } else { WrapMode::Unwrapped };
102 let center = self.view.center(wrap_mode);
103 let zoom = self.view.zoom();
104 self.set_lat_lng_zoom(¢er, zoom);
105 }
106 }
107
108 fn update_state_from_camera(&mut self, camera: &CameraPose) {
111 let position = camera.position;
112 let DVec3 { x: dx, y: dy, z: dz } = camera.forward();
113
114 let (new_roll, mut new_pitch, new_bearing) = camera.orientation_angles();
115 new_pitch = mln_style::math::clamp_f64(new_pitch, self.limits.min_pitch, self.limits.max_pitch);
116
117 let center_distance = self.view.camera_to_center_distance();
120 let zoom;
121 let travel;
122 if dz < -1.0e-9 && position.z > 1.0e-9 && new_pitch <= max_mercator_horizon_angle() {
123 zoom = (center_distance / (position.z / new_pitch.cos() * TILE_SIZE_D)).log2();
124 travel = -position.z / dz;
125 } else {
126 zoom = 14.0;
127 let new_scale = mln_style::math::clamp_f64(2.0f64.powf(zoom), self.min_scale(), self.max_scale());
128 travel = center_distance / new_scale / TILE_SIZE_D;
129 }
130
131 let mercator_point = Point::new(position.x + dx * travel, position.y + dy * travel);
132 let Ok(center) = lat_lng_from_mercator(mercator_point, WrapMode::Unwrapped) else {
133 return;
134 };
135 let zoom = f64::min(zoom, self.limits.max_zoom);
136 self.set_lat_lng_zoom(¢er, zoom);
137
138 let mercator_z = position.z + dz * travel;
139 let alt_m = mercator_z
140 * Projection::meters_per_pixel_at_latitude(self.view.center(WrapMode::Unwrapped).latitude(), 0.0)
141 * TILE_SIZE_D;
142 self.set_center_altitude(alt_m);
143 self.set_angle(new_bearing);
144 self.set_pitch(new_pitch);
145 self.set_roll(new_roll);
146 }
147
148 fn constrained_camera_position(&self, position: DVec3) -> Option<DVec3> {
151 if position.is_nan() {
152 return None;
153 }
154 let max_world_size = Projection::world_size(2.0f64.powf(self.limits.max_zoom));
155 let min_world_size = Projection::world_size(2.0f64.powf(self.min_zoom()));
156 let dist_to_center = self.view.camera_to_center_distance();
157 Some(DVec3::new(
158 position.x,
159 position.y,
160 mln_style::math::clamp_f64(position.z, dist_to_center / max_world_size, dist_to_center / min_world_size),
161 ))
162 }
163
164 fn constrained_camera_orientation(orientation: DQuat) -> Option<DQuat> {
168 if orientation.is_nan() || orientation.length() == 0.0 {
169 return None;
170 }
171 let unit_quat = orientation.normalize();
172 CameraPose::orientation_from_frame(unit_quat * DVec3::NEG_Z, unit_quat * DVec3::NEG_Y)
173 }
174
175 pub(crate) fn set_free_camera_options(&mut self, options: &FreeCameraOptions) {
176 if !self.is_valid() {
177 return;
178 }
179
180 let mut camera = self.view.camera_pose();
181 let mut changed = false;
182 if let Some(orientation) = options.orientation
183 && orientation != camera.orientation
184 && let Some(orientation) = Self::constrained_camera_orientation(orientation)
185 {
186 camera.orientation = orientation;
187 changed = true;
188 }
189
190 if let Some(position) = options.position
191 && position != camera.position
192 && let Some(position) = self.constrained_camera_position(position)
193 {
194 camera.position = position;
195 changed = true;
196 }
197
198 if changed {
199 self.update_state_from_camera(&camera);
200 }
201 }
202
203 pub fn set_size(&mut self, size: Size) {
206 self.update(|p| p.size = size);
207 }
208
209 pub(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
210 self.update(|p| p.frustum_offset = *frustum_offset);
211 }
212
213 pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
214 self.update(|p| p.north_orientation = orientation);
215 }
216
217 #[must_use]
218 pub(crate) fn constrain_mode(&self) -> ConstrainMode {
219 self.view.params().constrain_mode
220 }
221
222 pub(crate) fn set_constrain_mode(&mut self, mode: ConstrainMode) {
223 self.update(|p| p.constrain_mode = mode);
224 }
225
226 pub(crate) fn set_viewport_mode(&mut self, mode: ViewportMode) {
227 self.update(|p| p.viewport_mode = mode);
228 }
229
230 pub(crate) fn set_center_clamped_to_ground(&mut self, clamped: bool) {
231 self.update(|p| p.center_clamped_to_ground = clamped);
232 }
233
234 pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
235 self.update(|p| p.globe_free_bearing = free_bearing);
236 }
237
238 pub(crate) fn set_padding(&mut self, padding: &EdgeInsets) {
239 self.update(|p| p.padding = *padding);
240 }
241
242 #[must_use]
246 pub(crate) fn camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
247 let mut camera = self.view.camera();
248 if let Some(padding) = padding {
249 camera.padding = padding;
250 }
251 CameraOptions::from(camera)
252 }
253
254 #[must_use]
260 pub(crate) fn min_zoom_at_latitude(&self, latitude: f64) -> f64 {
261 self.min_zoom_at_latitude_with(latitude, self.view.is_globe())
262 }
263
264 #[must_use]
267 pub(crate) fn min_zoom_at_latitude_with(&self, latitude: f64, globe: bool) -> f64 {
268 if !globe {
269 return self.min_zoom();
270 }
271 scale_zoom(self.min_scale()) + VerticalPerspectiveProjection::zoom_adjustment(0.0, latitude)
274 }
275
276 #[must_use]
279 pub(crate) fn constrained_center(&self, lat_lng: &LatLng, zoom: f64) -> LatLng {
280 if self.constrain_mode() == ConstrainMode::None || !self.view.is_globe() {
281 return *lat_lng;
282 }
283 let max_latitude = VerticalPerspectiveProjection::max_latitude(
284 &self.view,
285 mln_style::math::clamp_f64(zoom, self.min_zoom_at_latitude(lat_lng.latitude()), self.limits.max_zoom),
286 );
287 LatLng::saturating(
288 mln_style::math::clamp_f64(lat_lng.latitude(), -max_latitude, max_latitude),
289 lat_lng.longitude(),
290 WrapMode::Unwrapped,
291 )
292 }
293
294 #[must_use]
298 pub fn limits(&self) -> &CameraLimits {
299 &self.limits
300 }
301
302 pub fn set_limits(&mut self, limits: CameraLimits) -> Result<(), Error> {
307 let limits = limits.validated()?;
308 let least_scale = self.constrain(zoom_scale(limits.min_zoom), self.view.x(), self.view.y()).0;
310 if zoom_scale(limits.max_zoom) < least_scale {
311 return Err(Error::invalid_argument("the maximum zoom must be at least the least zoom the view allows"));
312 }
313 let bounds_changed = limits.bounds != self.limits.bounds;
314 self.limits = limits;
315 if bounds_changed {
316 let lat_lng = self.view.center(WrapMode::Unwrapped);
317 let zoom = self.view.zoom();
318 self.set_lat_lng_zoom(&lat_lng, zoom);
319 self.update(|_| ());
320 }
321 Ok(())
322 }
323
324 fn min_scale(&self) -> f64 {
325 zoom_scale(self.limits.min_zoom)
326 }
327
328 fn max_scale(&self) -> f64 {
329 zoom_scale(self.limits.max_zoom)
330 }
331
332 #[must_use]
335 pub fn min_zoom(&self) -> f64 {
336 scale_zoom(self.constrained_min_scale())
337 }
338
339 fn constrained_min_scale(&self) -> f64 {
340 self.constrain(self.min_scale(), self.view.x(), self.view.y()).0
341 }
342
343 pub fn set_angle(&mut self, angle: f64) {
348 if angle.is_finite() {
349 self.update(|p| p.angle = angle);
350 }
351 }
352
353 pub(crate) fn set_fov(&mut self, fov: f64) {
354 if fov.is_finite() {
355 self.update(|p| p.fov = fov);
356 }
357 }
358
359 pub(crate) fn set_roll(&mut self, roll: f64) {
360 if roll.is_finite() {
361 self.update(|p| p.roll = roll);
362 }
363 }
364
365 pub fn set_pitch(&mut self, pitch: f64) {
366 if pitch.is_finite() {
367 self.update(|p| p.pitch = pitch);
368 }
369 }
370
371 pub(crate) fn set_x_skew(&mut self, skew: f64) {
372 if skew.is_finite() {
373 self.update(|p| p.x_skew = skew);
374 }
375 }
376
377 pub(crate) fn set_y_skew(&mut self, skew: f64) {
378 if skew.is_finite() {
379 self.update(|p| p.y_skew = skew);
380 }
381 }
382
383 pub(crate) fn set_axonometric(&mut self, axonometric: bool) {
384 self.update(|p| p.axonometric = axonometric);
385 }
386
387 #[must_use]
393 pub(crate) fn is_valid(&self) -> bool {
394 let scale = self.view.scale();
395 self.view.is_valid()
396 && (if self.view.is_globe() { scale > 0.0 } else { scale >= self.min_scale() })
397 && scale <= self.max_scale()
398 }
399
400 fn rotated_north(&self) -> bool {
403 matches!(self.view.north_orientation(), NorthOrientation::Leftwards | NorthOrientation::Rightwards)
404 }
405
406 #[must_use]
410 pub(crate) fn constrain_screen(&self, scale: f64) -> (f64, Option<LatLng>) {
411 if self.constrain_mode() != ConstrainMode::Screen {
412 return (scale, None);
413 }
414 let mut zoom = scale_zoom(scale);
415 let mut options = CameraOptions::default();
416 self.constrain_camera_and_zoom_to_bounds(&mut options, &mut zoom);
417 (zoom_scale(zoom), options.center)
418 }
419
420 #[must_use]
423 pub(crate) fn constrain(&self, mut scale: f64, mut x: f64, mut y: f64) -> (f64, f64, f64) {
424 let constrain_mode = self.constrain_mode();
425 if constrain_mode == ConstrainMode::None || constrain_mode == ConstrainMode::Screen {
426 return (scale, x, y);
427 }
428
429 if self.view.is_globe() {
432 let max_latitude = VerticalPerspectiveProjection::max_latitude(&self.view, scale_zoom(scale));
433 let max_y = Projection::world_size(scale) / M2PI * mln_style::math::deg2rad(max_latitude).tan().asinh();
434 y = mln_style::math::clamp_f64(y, -max_y, max_y);
435 return (scale, x, y);
436 }
437
438 let size = self.view.size();
439 let width = f64::from(size.width);
440 let height = f64::from(size.height);
441
442 let ratio_y = (if self.rotated_north() { width } else { height }) / TILE_SIZE_D;
445 scale = mln_style::math::fmax(scale, ratio_y);
446
447 let max_y = (scale * TILE_SIZE_D - (if self.rotated_north() { width } else { height })) / 2.0;
449 y = f64::max(-max_y, f64::min(y, max_y));
450
451 if constrain_mode == ConstrainMode::WidthAndHeight {
452 let max_x = (scale * TILE_SIZE_D - (if self.rotated_north() { height } else { width })) / 2.0;
454 x = f64::max(-max_x, f64::min(x, max_x));
455 }
456 (scale, x, y)
457 }
458
459 pub(crate) fn constrain_position(&mut self, scale: f64) {
462 let (scale, x, y) = self.constrain(scale, self.view.x(), self.view.y());
463 if scale.is_finite() && x.is_finite() && y.is_finite() {
464 self.update(|p| {
465 p.scale = scale;
466 p.x = x;
467 p.y = y;
468 });
469 }
470 }
471
472 pub(crate) fn constrain_camera_and_zoom_to_bounds(
473 &self,
474 requested_camera: &mut CameraOptions,
475 requested_zoom: &mut f64,
476 ) {
477 if self.constrain_mode() != ConstrainMode::Screen || self.limits.bounds == LatLngBounds::default() {
478 return;
479 }
480
481 let view = &self.view;
482 let current_center = view.center(WrapMode::Unwrapped);
483 let center_lat_lng = requested_camera.center.unwrap_or(current_center);
484
485 let mut anchor_offset = Point::new(0.0, 0.0);
486 let requested_scale = zoom_scale(*requested_zoom);
487
488 if let Some(mut anchor) = requested_camera.anchor {
492 anchor.y = f64::from(view.size().height) - anchor.y;
493 let mut state = self.clone();
495 state.set_lat_lng_zoom(¤t_center, scale_zoom(requested_scale));
496 if let (Ok(anchor_lat_lng), Ok(screen_lat_lng)) = (
499 view.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped),
500 state.view.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped),
501 ) {
502 let lat_lng_coord = Projection::project(&anchor_lat_lng, requested_scale);
503 let anchor_coord = Projection::project(&screen_lat_lng, requested_scale);
504 anchor_offset = Point::new(lat_lng_coord.x - anchor_coord.x, lat_lng_coord.y - anchor_coord.y);
505 }
506 }
507
508 let current_bounds = self.limits.bounds;
509 let ne_bounds = Projection::project(¤t_bounds.northeast(), requested_scale);
510 let sw_bounds = Projection::project(¤t_bounds.southwest(), requested_scale);
511 let center = Projection::project(¢er_lat_lng, requested_scale);
512 let current_center = Projection::project(¤t_center, requested_scale);
513
514 let min_y = ne_bounds.y;
515 let max_y = sw_bounds.y;
516 let min_x = sw_bounds.x;
517 let max_x = ne_bounds.x;
518
519 let start_x = center.x;
520 let start_y = center.y;
521
522 let mut result_x = start_x;
523 let mut result_y = start_y;
524
525 let screen_width = view.size().width;
526 let screen_height = view.size().height;
527
528 let h2 = f64::from(screen_height) / 2.0;
529 if start_y - h2 + anchor_offset.y < min_y {
530 result_y = min_y + h2;
531 }
532 if start_y + anchor_offset.y + h2 > max_y {
533 result_y = max_y - h2;
534 }
535
536 let w2 = f64::from(screen_width) / 2.0;
537 if start_x + anchor_offset.x - w2 < min_x {
538 result_x = min_x + w2;
539 }
540 if start_x + anchor_offset.x + w2 > max_x {
541 result_x = max_x - w2;
542 }
543
544 let mut scale_y = 0.0;
545 if max_y - min_y < f64::from(screen_height) {
546 scale_y = f64::from(screen_height) / (max_y - min_y);
547 result_y = f64::midpoint(max_y, min_y);
548 }
549
550 let mut scale_x = 0.0;
551 if max_x - min_x < f64::from(screen_width) {
552 scale_x = f64::from(screen_width) / (max_x - min_x);
553 result_x = f64::midpoint(max_x, min_x);
554 }
555
556 let max_scale = if scale_x > scale_y { scale_x } else { scale_y };
557
558 if max_scale > 1.000_001 {
563 *requested_zoom += scale_zoom(max_scale);
564
565 if scale_y > scale_x {
566 result_x = current_center.x;
569 } else {
570 result_y = current_center.y;
573 }
574
575 if result_x * max_scale - w2 <= min_x * max_scale {
581 result_x = min_x * max_scale + w2;
582 result_x /= max_scale;
583 } else if result_x * max_scale + w2 >= max_x * max_scale {
584 result_x = max_x * max_scale - w2;
585 result_x /= max_scale;
586 }
587
588 if result_y * max_scale - h2 <= min_y * max_scale {
589 result_y = min_y * max_scale + h2;
590 result_y /= max_scale;
591 } else if result_y * max_scale + h2 >= max_y * max_scale {
592 result_y = max_y * max_scale - h2;
593 result_y /= max_scale;
594 }
595 }
596
597 if result_x != start_x || result_y != start_y {
598 requested_camera.anchor = None;
600 requested_camera.center =
602 Projection::unproject(&Point::new(result_x, result_y), requested_scale, WrapMode::Unwrapped).ok();
603 }
604 }
605
606 #[must_use]
611 pub(crate) fn min_zoom_for_screen_bounds(&self) -> Option<f64> {
612 if self.constrain_mode() != ConstrainMode::Screen || self.limits.bounds == LatLngBounds::default() {
613 return None;
614 }
615 let ne = Projection::project(&self.limits.bounds.northeast(), 1.0);
618 let sw = Projection::project(&self.limits.bounds.southwest(), 1.0);
619 let size = self.view.size();
620 let scale_x = f64::from(size.width) / (ne.x - sw.x);
621 let scale_y = f64::from(size.height) / (sw.y - ne.y);
622 Some(scale_zoom(f64::max(scale_x, scale_y)))
623 }
624
625 #[cfg(test)]
632 pub(crate) fn move_lat_lng(&mut self, lat_lng: &LatLng, anchor: &ScreenCoordinate) -> Result<(), Error> {
633 self.move_lat_lng_at(lat_lng, anchor, 0.0)
634 }
635
636 pub(crate) fn move_lat_lng_at(
644 &mut self,
645 lat_lng: &LatLng,
646 anchor: &ScreenCoordinate,
647 height: f64,
648 ) -> Result<(), Error> {
649 let view = &self.view;
650 if view.is_globe() {
651 if let Some(center) =
652 VerticalPerspectiveProjection::center_for_location_at_point(view, lat_lng, anchor, height)
653 {
654 let target = self.constrained_center(¢er, view.zoom());
655 let zoom = view.zoom()
656 + VerticalPerspectiveProjection::zoom_adjustment(
657 view.center(WrapMode::Unwrapped).latitude(),
658 target.latitude(),
659 );
660 self.set_lat_lng_zoom(&target, zoom);
661 }
662 return Ok(());
663 }
664 let center = self.center_for_lat_lng_at(lat_lng, anchor, height)?;
665 let target = if self.limits.bounds == LatLngBounds::default() { center.wrapped() } else { center };
668 let zoom = self.view.zoom();
669 self.set_lat_lng_zoom(&target, zoom);
670 Ok(())
671 }
672
673 pub(crate) fn center_for_lat_lng_at(
684 &self,
685 lat_lng: &LatLng,
686 anchor: &ScreenCoordinate,
687 height: f64,
688 ) -> Result<LatLng, Error> {
689 let view = &self.view;
690 if view.is_globe() && !view.size().is_empty() {
691 return VerticalPerspectiveProjection::center_for_location_at_point(view, lat_lng, anchor, height)
692 .ok_or_else(|| Error::invalid_argument("no center holds the location at the point"));
693 }
694 let scale = view.scale();
695 let center_coord = Projection::project(&view.center(WrapMode::Unwrapped), scale);
696 let lat_lng_coord = Projection::project(lat_lng, scale);
697 let anchor_coord =
698 Projection::project(&view.screen_coordinate_to_lat_lng_at(anchor, height, WrapMode::Unwrapped)?, scale);
699 Projection::unproject(
700 &Point::new(
701 center_coord.x + lat_lng_coord.x - anchor_coord.x,
702 center_coord.y + lat_lng_coord.y - anchor_coord.y,
703 ),
704 scale,
705 WrapMode::Unwrapped,
706 )
707 }
708
709 pub fn set_lat_lng_zoom(&mut self, lat_lng: &LatLng, zoom: f64) {
710 if !zoom.is_finite() {
711 return;
712 }
713 let globe = self.view.is_globe();
714 let mut requested = *lat_lng;
715 if globe && self.limits.bounds != LatLngBounds::default() {
719 let turns =
720 ((self.limits.bounds.center().longitude() - lat_lng.longitude()) / constants::DEGREES_MAX).round();
721 requested = LatLng::saturating(
722 lat_lng.latitude(),
723 lat_lng.longitude() + turns * constants::DEGREES_MAX,
724 WrapMode::Unwrapped,
725 );
726 }
727 let mut constrained = self.limits.bounds.constrain(&requested);
728 if globe && self.limits.bounds == LatLngBounds::default() {
732 let current = self.view.center(WrapMode::Unwrapped).longitude();
733 if current.is_finite() {
734 let turns = ((current - constrained.longitude()) / constants::DEGREES_MAX).round();
735 constrained = LatLng::saturating(
736 constrained.latitude(),
737 constrained.longitude() + turns * constants::DEGREES_MAX,
738 WrapMode::Unwrapped,
739 );
740 }
741 }
742
743 let min_scale = if globe {
744 zoom_scale(self.min_zoom_at_latitude(constrained.latitude()))
745 } else {
746 self.constrained_min_scale()
747 };
748 let new_scale = mln_style::math::clamp_f64(zoom_scale(zoom), min_scale, self.max_scale());
749 let (x, y) = map_offset(&constrained, new_scale, globe);
750 if !x.is_finite() || !y.is_finite() {
752 return;
753 }
754 let (scale, x, y) = self.constrain(new_scale, x, y);
755 self.update(|p| {
756 p.scale = scale;
757 p.x = x;
758 p.y = y;
759 });
760 }
761
762 pub(crate) fn set_center_altitude(&mut self, alt_m: f64) {
765 if !alt_m.is_finite() {
766 return;
767 }
768 self.update(|p| p.center_altitude = alt_m);
769 }
770
771 pub(crate) fn set_terrain_min_elevation(&mut self, min_elevation: Option<f64>) {
776 if min_elevation.is_some_and(|min| !min.is_finite()) {
777 return;
778 }
779 self.update(|p| p.terrain_min_elevation = min_elevation);
780 }
781
782 pub(crate) fn raise_eye(&mut self, lift: f64) -> bool {
792 let view = &self.view;
793 if !lift.is_finite() || !view.is_valid() {
794 return false;
795 }
796 let distance = view.camera_to_center_distance();
799 let across = view.pitch().sin() * distance;
800 let up = view.pitch().cos() * distance + lift / Self::height_meters_per_pixel(view);
801 let raised = across.hypot(up);
802 if raised == 0.0 {
803 return false;
804 }
805 let pitch = mln_style::math::clamp_f64(across.atan2(up), self.limits.min_pitch, self.limits.max_pitch);
806 let zoom = view.zoom() + (distance / raised).log2();
807 let center = view.center(WrapMode::Unwrapped);
808 let before = *view.params();
809 self.set_pitch(pitch);
810 self.set_lat_lng_zoom(¢er, zoom);
811 *self.view.params() != before
812 }
813
814 pub(crate) fn recenter_on(&mut self, hit: &GroundHit) -> bool {
838 let view = &self.view;
839 if !view.is_valid() {
840 return false;
841 }
842 let recentered =
843 if view.is_globe() { Self::recentered_on_sphere(view, hit) } else { self.recentered_on_plane(hit) };
844 let Some((center, altitude, zoom)) = recentered else { return false };
845
846 let mut moved = self.clone();
847 moved.set_center_altitude(altitude);
848 moved.set_lat_lng_zoom(¢er, zoom);
849 let landed = moved.view.center(WrapMode::Unwrapped);
851 let mut on_screen = CameraOptions { center: Some(landed), ..CameraOptions::default() };
852 let mut screen_zoom = moved.view.zoom();
853 moved.constrain_camera_and_zoom_to_bounds(&mut on_screen, &mut screen_zoom);
854 let refused = (moved.view.zoom() - zoom).abs() > 1e-9
855 || (landed.latitude() - center.latitude()).abs() > 1e-9
856 || (landed.longitude() - center.longitude()).abs() > 1e-9
857 || on_screen.center != Some(landed)
858 || screen_zoom != moved.view.zoom();
859 if refused {
860 return false;
861 }
862 *self = moved;
863 true
864 }
865
866 fn recentered_on_plane(&self, hit: &GroundHit) -> Option<(LatLng, f64, f64)> {
869 let view = &self.view;
870 let eye = view.eye_position();
871 let forward = view.camera_pose().forward();
872 let latitude = hit.location(WrapMode::Unwrapped).latitude();
874 let meters = Projection::meters_per_pixel_at_latitude(latitude, 0.0) * TILE_SIZE_D;
875 let to_hit = DVec3::new((hit.world.x - eye.x) * meters, (hit.world.y - eye.y) * meters, hit.height - eye.z);
876 let distance = to_hit.dot(forward);
877 if !(distance.is_finite() && distance > 0.0) {
878 return None;
879 }
880 let world = Point::new(eye.x + forward.x * distance / meters, eye.y + forward.y * distance / meters);
881 let center = Projection::unproject(&world, 1.0 / TILE_SIZE_D, WrapMode::Unwrapped).ok()?;
882 let center = if self.limits.bounds == LatLngBounds::default() { center.wrapped() } else { center };
885 let zoom = scale_zoom(view.camera_to_center_distance() * meters / distance / TILE_SIZE_D);
886 Some((center, eye.z + forward.z * distance, zoom))
887 }
888
889 fn recentered_on_sphere(view: &View, hit: &GroundHit) -> Option<(LatLng, f64, f64)> {
893 let radius = |height: f64| 1.0 + height / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS;
894 let eye = view.globe_camera_position();
895 let center = VerticalPerspectiveProjection::surface_vector(&view.center(WrapMode::Unwrapped))
896 * radius(view.center_altitude());
897 let forward = (center - eye).normalize();
898 let target =
899 VerticalPerspectiveProjection::surface_vector(&hit.location(WrapMode::Unwrapped)) * radius(hit.height);
900 let distance = (target - eye).dot(forward);
901 if !(distance.is_finite() && distance > 0.0) {
902 return None;
903 }
904 let point = eye + forward * distance;
905 let length = point.length();
906 let location = VerticalPerspectiveProjection::surface_vector_to_lat_lng(point / length)?;
907 let location = view.lat_lng_near_center(&location);
908 let radius_at_zoom_0 =
909 VerticalPerspectiveProjection::globe_radius_pixels(Projection::world_size(1.0), location.latitude());
910 let zoom = scale_zoom(view.camera_to_center_distance() / distance / radius_at_zoom_0);
911 Some((location, (length - 1.0) * VerticalPerspectiveProjection::GLOBE_RADIUS_METERS, zoom))
912 }
913
914 fn height_meters_per_pixel(view: &View) -> f64 {
918 if view.is_globe() {
919 let latitude = view.center(WrapMode::Unwrapped).latitude();
920 VerticalPerspectiveProjection::GLOBE_RADIUS_METERS
921 / VerticalPerspectiveProjection::globe_radius_pixels(Projection::world_size(view.scale()), latitude)
922 } else {
923 view.meters_per_pixel()
924 }
925 }
926}
927
928#[cfg(test)]
929#[path = "transform_state_test.rs"]
930mod transform_state_test;