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;
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)
46 }
47}
48
49impl TransformState {
50 #[must_use]
51 pub(crate) fn new(constrain_mode: ConstrainMode) -> Self {
52 TransformState { view: View::new(ViewParams::new(constrain_mode)), limits: CameraLimits::default() }
53 }
54
55 pub(crate) fn from_parts(params: ViewParams, limits: CameraLimits) -> Self {
57 let mut state = TransformState { view: View::new(params), limits };
58 state.update(|_| ());
59 state
60 }
61
62 #[must_use]
64 pub fn view(&self) -> &View {
65 &self.view
66 }
67
68 fn update(&mut self, change: impl FnOnce(&mut ViewParams)) {
71 let mut params = *self.view.params();
72 change(&mut params);
73 params.center_wrap = if params.projection_transition > 0.0 && self.limits.bounds == LatLngBounds::default() {
74 WrapMode::Wrapped
75 } else {
76 WrapMode::Unwrapped
77 };
78 if params != *self.view.params() {
79 self.view = View::new(params);
80 }
81 }
82
83 pub fn set_projection_definition(&mut self, definition: &ProjectionDefinition) {
86 let transition = definition.transition_state();
87 let previous = self.view.projection_transition();
88 self.update(|p| {
89 p.projection_definition = *definition;
90 p.projection_transition = transition;
91 });
92 let leaves_globe = transition == 0.0 && previous > 0.0;
96 if leaves_globe && !self.view.size().is_empty() {
97 let wrap_mode =
98 if self.limits.bounds == LatLngBounds::default() { WrapMode::Wrapped } else { WrapMode::Unwrapped };
99 let center = self.view.center(wrap_mode);
100 let zoom = self.view.zoom();
101 self.set_lat_lng_zoom(¢er, zoom);
102 }
103 }
104
105 fn update_state_from_camera(&mut self, camera: &CameraPose) {
108 let position = camera.position;
109 let DVec3 { x: dx, y: dy, z: dz } = camera.forward();
110
111 let (new_roll, mut new_pitch, new_bearing) = camera.orientation_angles();
112 new_pitch = mln_style::math::clamp_f64(new_pitch, self.limits.min_pitch, self.limits.max_pitch);
113
114 let center_distance = self.view.camera_to_center_distance();
117 let zoom;
118 let travel;
119 if dz < -1.0e-9 && position.z > 1.0e-9 && new_pitch <= max_mercator_horizon_angle() {
120 zoom = (center_distance / (position.z / new_pitch.cos() * TILE_SIZE_D)).log2();
121 travel = -position.z / dz;
122 } else {
123 zoom = 14.0;
124 let new_scale = mln_style::math::clamp_f64(2.0f64.powf(zoom), self.min_scale(), self.max_scale());
125 travel = center_distance / new_scale / TILE_SIZE_D;
126 }
127
128 let mercator_point = Point::new(position.x + dx * travel, position.y + dy * travel);
129 let Ok(center) = lat_lng_from_mercator(mercator_point, WrapMode::Unwrapped) else {
130 return;
131 };
132 let zoom = f64::min(zoom, self.limits.max_zoom);
133 self.set_lat_lng_zoom(¢er, zoom);
134
135 let mercator_z = position.z + dz * travel;
136 let alt_m = mercator_z
137 * Projection::meters_per_pixel_at_latitude(self.view.center(WrapMode::Unwrapped).latitude(), 0.0)
138 * TILE_SIZE_D;
139 self.set_center_altitude(alt_m);
140 self.set_angle(new_bearing);
141 self.set_pitch(new_pitch);
142 self.set_roll(new_roll);
143 }
144
145 fn constrained_camera_position(&self, position: DVec3) -> Option<DVec3> {
148 if position.is_nan() {
149 return None;
150 }
151 let max_world_size = Projection::world_size(2.0f64.powf(self.limits.max_zoom));
152 let min_world_size = Projection::world_size(2.0f64.powf(self.min_zoom()));
153 let dist_to_center = self.view.camera_to_center_distance();
154 Some(DVec3::new(
155 position.x,
156 position.y,
157 mln_style::math::clamp_f64(position.z, dist_to_center / max_world_size, dist_to_center / min_world_size),
158 ))
159 }
160
161 fn constrained_camera_orientation(orientation: DQuat) -> Option<DQuat> {
165 if orientation.is_nan() || orientation.length() == 0.0 {
166 return None;
167 }
168 let unit_quat = orientation.normalize();
169 CameraPose::orientation_from_frame(unit_quat * DVec3::NEG_Z, unit_quat * DVec3::NEG_Y)
170 }
171
172 pub(crate) fn set_free_camera_options(&mut self, options: &FreeCameraOptions) {
173 if !self.is_valid() {
174 return;
175 }
176
177 let mut camera = self.view.camera_pose();
178 let mut changed = false;
179 if let Some(orientation) = options.orientation
180 && orientation != camera.orientation
181 && let Some(orientation) = Self::constrained_camera_orientation(orientation)
182 {
183 camera.orientation = orientation;
184 changed = true;
185 }
186
187 if let Some(position) = options.position
188 && position != camera.position
189 && let Some(position) = self.constrained_camera_position(position)
190 {
191 camera.position = position;
192 changed = true;
193 }
194
195 if changed {
196 self.update_state_from_camera(&camera);
197 }
198 }
199
200 pub fn set_size(&mut self, size: Size) {
203 self.update(|p| p.size = size);
204 }
205
206 pub(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
207 self.update(|p| p.frustum_offset = *frustum_offset);
208 }
209
210 pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
211 self.update(|p| p.north_orientation = orientation);
212 }
213
214 #[must_use]
215 pub(crate) fn constrain_mode(&self) -> ConstrainMode {
216 self.view.params().constrain_mode
217 }
218
219 pub(crate) fn set_constrain_mode(&mut self, mode: ConstrainMode) {
220 self.update(|p| p.constrain_mode = mode);
221 }
222
223 pub(crate) fn set_center_clamped_to_ground(&mut self, clamped: bool) {
224 self.update(|p| p.center_clamped_to_ground = clamped);
225 }
226
227 pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
228 self.update(|p| p.globe_free_bearing = free_bearing);
229 }
230
231 pub(crate) fn set_padding(&mut self, padding: &EdgeInsets) {
232 self.update(|p| p.padding = *padding);
233 }
234
235 #[must_use]
239 pub(crate) fn camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
240 let mut camera = self.view.camera();
241 if let Some(padding) = padding {
242 camera.padding = padding;
243 }
244 CameraOptions::from(camera)
245 }
246
247 #[must_use]
253 pub(crate) fn min_zoom_at_latitude(&self, latitude: f64) -> f64 {
254 self.min_zoom_at_latitude_with(latitude, self.view.is_globe())
255 }
256
257 #[must_use]
260 pub(crate) fn min_zoom_at_latitude_with(&self, latitude: f64, globe: bool) -> f64 {
261 if !globe {
262 return self.min_zoom();
263 }
264 scale_zoom(self.min_scale()) + VerticalPerspectiveProjection::zoom_adjustment(0.0, latitude)
267 }
268
269 #[must_use]
272 pub(crate) fn constrained_center(&self, lat_lng: &LatLng, zoom: f64) -> LatLng {
273 if self.constrain_mode() == ConstrainMode::None || !self.view.is_globe() {
274 return *lat_lng;
275 }
276 let max_latitude = VerticalPerspectiveProjection::max_latitude(
277 &self.view,
278 mln_style::math::clamp_f64(zoom, self.min_zoom_at_latitude(lat_lng.latitude()), self.limits.max_zoom),
279 );
280 LatLng::saturating(
281 mln_style::math::clamp_f64(lat_lng.latitude(), -max_latitude, max_latitude),
282 lat_lng.longitude(),
283 WrapMode::Unwrapped,
284 )
285 }
286
287 #[must_use]
291 pub fn limits(&self) -> &CameraLimits {
292 &self.limits
293 }
294
295 pub fn set_limits(&mut self, limits: CameraLimits) -> Result<(), Error> {
300 let limits = limits.validated()?;
301 let least_scale = self.constrain(zoom_scale(limits.min_zoom), self.view.x(), self.view.y()).0;
303 if zoom_scale(limits.max_zoom) < least_scale {
304 return Err(Error::invalid_argument("the maximum zoom must be at least the least zoom the view allows"));
305 }
306 let bounds_changed = limits.bounds != self.limits.bounds;
307 self.limits = limits;
308 if bounds_changed {
309 let lat_lng = self.view.center(WrapMode::Unwrapped);
310 let zoom = self.view.zoom();
311 self.set_lat_lng_zoom(&lat_lng, zoom);
312 self.update(|_| ());
313 }
314 Ok(())
315 }
316
317 fn min_scale(&self) -> f64 {
318 zoom_scale(self.limits.min_zoom)
319 }
320
321 fn max_scale(&self) -> f64 {
322 zoom_scale(self.limits.max_zoom)
323 }
324
325 #[must_use]
328 pub fn min_zoom(&self) -> f64 {
329 scale_zoom(self.constrained_min_scale())
330 }
331
332 fn constrained_min_scale(&self) -> f64 {
333 self.constrain(self.min_scale(), self.view.x(), self.view.y()).0
334 }
335
336 pub fn set_angle(&mut self, angle: f64) {
341 if angle.is_finite() {
342 self.update(|p| p.angle = angle);
343 }
344 }
345
346 pub(crate) fn set_fov(&mut self, fov: f64) {
347 if fov.is_finite() {
348 self.update(|p| p.fov = fov);
349 }
350 }
351
352 pub(crate) fn set_roll(&mut self, roll: f64) {
353 if roll.is_finite() {
354 self.update(|p| p.roll = roll);
355 }
356 }
357
358 pub fn set_pitch(&mut self, pitch: f64) {
359 if pitch.is_finite() {
360 self.update(|p| p.pitch = pitch);
361 }
362 }
363
364 pub(crate) fn set_x_skew(&mut self, skew: f64) {
365 if skew.is_finite() {
366 self.update(|p| p.x_skew = skew);
367 }
368 }
369
370 pub(crate) fn set_y_skew(&mut self, skew: f64) {
371 if skew.is_finite() {
372 self.update(|p| p.y_skew = skew);
373 }
374 }
375
376 pub(crate) fn set_axonometric(&mut self, axonometric: bool) {
377 self.update(|p| p.axonometric = axonometric);
378 }
379
380 #[must_use]
386 pub(crate) fn is_valid(&self) -> bool {
387 let scale = self.view.scale();
388 self.view.is_valid()
389 && (if self.view.is_globe() { scale > 0.0 } else { scale >= self.min_scale() })
390 && scale <= self.max_scale()
391 }
392
393 fn rotated_north(&self) -> bool {
396 matches!(self.view.north_orientation(), NorthOrientation::Leftwards | NorthOrientation::Rightwards)
397 }
398
399 #[must_use]
403 pub(crate) fn constrain_screen(&self, scale: f64) -> (f64, Option<LatLng>) {
404 if self.constrain_mode() != ConstrainMode::Screen {
405 return (scale, None);
406 }
407 let mut zoom = scale_zoom(scale);
408 let mut options = CameraOptions::default();
409 self.constrain_camera_and_zoom_to_bounds(&mut options, &mut zoom);
410 (zoom_scale(zoom), options.center)
411 }
412
413 #[must_use]
416 pub(crate) fn constrain(&self, mut scale: f64, mut x: f64, mut y: f64) -> (f64, f64, f64) {
417 let constrain_mode = self.constrain_mode();
418 if constrain_mode == ConstrainMode::None || constrain_mode == ConstrainMode::Screen {
419 return (scale, x, y);
420 }
421
422 if self.view.is_globe() {
425 let max_latitude = VerticalPerspectiveProjection::max_latitude(&self.view, scale_zoom(scale));
426 let max_y = Projection::world_size(scale) / M2PI * mln_style::math::deg2rad(max_latitude).tan().asinh();
427 y = mln_style::math::clamp_f64(y, -max_y, max_y);
428 return (scale, x, y);
429 }
430
431 let size = self.view.size();
432 let width = f64::from(size.width);
433 let height = f64::from(size.height);
434
435 let ratio_y = (if self.rotated_north() { width } else { height }) / TILE_SIZE_D;
438 scale = mln_style::math::fmax(scale, ratio_y);
439
440 let max_y = (scale * TILE_SIZE_D - (if self.rotated_north() { width } else { height })) / 2.0;
442 y = f64::max(-max_y, f64::min(y, max_y));
443
444 if constrain_mode == ConstrainMode::WidthAndHeight {
445 let max_x = (scale * TILE_SIZE_D - (if self.rotated_north() { height } else { width })) / 2.0;
447 x = f64::max(-max_x, f64::min(x, max_x));
448 }
449 (scale, x, y)
450 }
451
452 pub(crate) fn constrain_position(&mut self, scale: f64) {
455 let (scale, x, y) = self.constrain(scale, self.view.x(), self.view.y());
456 if scale.is_finite() && x.is_finite() && y.is_finite() {
457 self.update(|p| {
458 p.scale = scale;
459 p.x = x;
460 p.y = y;
461 });
462 }
463 }
464
465 pub(crate) fn constrain_camera_and_zoom_to_bounds(
466 &self,
467 requested_camera: &mut CameraOptions,
468 requested_zoom: &mut f64,
469 ) {
470 if self.constrain_mode() != ConstrainMode::Screen || self.limits.bounds == LatLngBounds::default() {
471 return;
472 }
473
474 let view = &self.view;
475 let current_center = view.center(WrapMode::Unwrapped);
476 let center_lat_lng = requested_camera.center.unwrap_or(current_center);
477
478 let mut anchor_offset = Point::new(0.0, 0.0);
479 let requested_scale = zoom_scale(*requested_zoom);
480
481 if let Some(mut anchor) = requested_camera.anchor {
485 anchor.y = f64::from(view.size().height) - anchor.y;
486 let mut state = self.clone();
488 state.set_lat_lng_zoom(¤t_center, scale_zoom(requested_scale));
489 if let (Ok(anchor_lat_lng), Ok(screen_lat_lng)) = (
492 view.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped),
493 state.view.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped),
494 ) {
495 let lat_lng_coord = Projection::project(&anchor_lat_lng, requested_scale);
496 let anchor_coord = Projection::project(&screen_lat_lng, requested_scale);
497 anchor_offset = Point::new(lat_lng_coord.x - anchor_coord.x, lat_lng_coord.y - anchor_coord.y);
498 }
499 }
500
501 let current_bounds = self.limits.bounds;
502 let ne_bounds = Projection::project(¤t_bounds.northeast(), requested_scale);
503 let sw_bounds = Projection::project(¤t_bounds.southwest(), requested_scale);
504 let center = Projection::project(¢er_lat_lng, requested_scale);
505 let current_center = Projection::project(¤t_center, requested_scale);
506
507 let min_y = ne_bounds.y;
508 let max_y = sw_bounds.y;
509 let min_x = sw_bounds.x;
510 let max_x = ne_bounds.x;
511
512 let start_x = center.x;
513 let start_y = center.y;
514
515 let mut result_x = start_x;
516 let mut result_y = start_y;
517
518 let screen_width = view.size().width;
519 let screen_height = view.size().height;
520
521 let h2 = f64::from(screen_height) / 2.0;
522 if start_y - h2 + anchor_offset.y < min_y {
523 result_y = min_y + h2;
524 }
525 if start_y + anchor_offset.y + h2 > max_y {
526 result_y = max_y - h2;
527 }
528
529 let w2 = f64::from(screen_width) / 2.0;
530 if start_x + anchor_offset.x - w2 < min_x {
531 result_x = min_x + w2;
532 }
533 if start_x + anchor_offset.x + w2 > max_x {
534 result_x = max_x - w2;
535 }
536
537 let mut scale_y = 0.0;
538 if max_y - min_y < f64::from(screen_height) {
539 scale_y = f64::from(screen_height) / (max_y - min_y);
540 result_y = f64::midpoint(max_y, min_y);
541 }
542
543 let mut scale_x = 0.0;
544 if max_x - min_x < f64::from(screen_width) {
545 scale_x = f64::from(screen_width) / (max_x - min_x);
546 result_x = f64::midpoint(max_x, min_x);
547 }
548
549 let max_scale = if scale_x > scale_y { scale_x } else { scale_y };
550
551 if max_scale > 1.000_001 {
556 *requested_zoom += scale_zoom(max_scale);
557
558 if scale_y > scale_x {
559 result_x = current_center.x;
562 } else {
563 result_y = current_center.y;
566 }
567
568 if result_x * max_scale - w2 <= min_x * max_scale {
574 result_x = min_x * max_scale + w2;
575 result_x /= max_scale;
576 } else if result_x * max_scale + w2 >= max_x * max_scale {
577 result_x = max_x * max_scale - w2;
578 result_x /= max_scale;
579 }
580
581 if result_y * max_scale - h2 <= min_y * max_scale {
582 result_y = min_y * max_scale + h2;
583 result_y /= max_scale;
584 } else if result_y * max_scale + h2 >= max_y * max_scale {
585 result_y = max_y * max_scale - h2;
586 result_y /= max_scale;
587 }
588 }
589
590 if result_x != start_x || result_y != start_y {
591 requested_camera.anchor = None;
593 requested_camera.center =
595 Projection::unproject(&Point::new(result_x, result_y), requested_scale, WrapMode::Unwrapped).ok();
596 }
597 }
598
599 #[must_use]
604 pub(crate) fn min_zoom_for_screen_bounds(&self) -> Option<f64> {
605 if self.constrain_mode() != ConstrainMode::Screen || self.limits.bounds == LatLngBounds::default() {
606 return None;
607 }
608 let ne = Projection::project(&self.limits.bounds.northeast(), 1.0);
611 let sw = Projection::project(&self.limits.bounds.southwest(), 1.0);
612 let size = self.view.size();
613 let scale_x = f64::from(size.width) / (ne.x - sw.x);
614 let scale_y = f64::from(size.height) / (sw.y - ne.y);
615 Some(scale_zoom(f64::max(scale_x, scale_y)))
616 }
617
618 #[cfg(test)]
625 pub(crate) fn move_lat_lng(&mut self, lat_lng: &LatLng, anchor: &ScreenCoordinate) -> Result<(), Error> {
626 self.move_lat_lng_at(lat_lng, anchor, 0.0)
627 }
628
629 pub(crate) fn move_lat_lng_at(
637 &mut self,
638 lat_lng: &LatLng,
639 anchor: &ScreenCoordinate,
640 height: f64,
641 ) -> Result<(), Error> {
642 let view = &self.view;
643 if view.is_globe() {
644 if let Some(center) =
645 VerticalPerspectiveProjection::center_for_location_at_point(view, lat_lng, anchor, height)
646 {
647 let target = self.constrained_center(¢er, view.zoom());
648 let zoom = view.zoom()
649 + VerticalPerspectiveProjection::zoom_adjustment(
650 view.center(WrapMode::Unwrapped).latitude(),
651 target.latitude(),
652 );
653 self.set_lat_lng_zoom(&target, zoom);
654 }
655 return Ok(());
656 }
657 let center = self.center_for_lat_lng_at(lat_lng, anchor, height)?;
658 let target = if self.limits.bounds == LatLngBounds::default() { center.wrapped() } else { center };
661 let zoom = self.view.zoom();
662 self.set_lat_lng_zoom(&target, zoom);
663 Ok(())
664 }
665
666 pub(crate) fn center_for_lat_lng_at(
677 &self,
678 lat_lng: &LatLng,
679 anchor: &ScreenCoordinate,
680 height: f64,
681 ) -> Result<LatLng, Error> {
682 let view = &self.view;
683 if view.is_globe() && !view.size().is_empty() {
684 return VerticalPerspectiveProjection::center_for_location_at_point(view, lat_lng, anchor, height)
685 .ok_or_else(|| Error::invalid_argument("no center holds the location at the point"));
686 }
687 let scale = view.scale();
688 let center_coord = Projection::project(&view.center(WrapMode::Unwrapped), scale);
689 let lat_lng_coord = Projection::project(lat_lng, scale);
690 let anchor_coord =
691 Projection::project(&view.screen_coordinate_to_lat_lng_at(anchor, height, WrapMode::Unwrapped)?, scale);
692 Projection::unproject(
693 &Point::new(
694 center_coord.x + lat_lng_coord.x - anchor_coord.x,
695 center_coord.y + lat_lng_coord.y - anchor_coord.y,
696 ),
697 scale,
698 WrapMode::Unwrapped,
699 )
700 }
701
702 pub fn set_lat_lng_zoom(&mut self, lat_lng: &LatLng, zoom: f64) {
703 if !zoom.is_finite() {
704 return;
705 }
706 let globe = self.view.is_globe();
707 let mut requested = *lat_lng;
708 if globe && self.limits.bounds != LatLngBounds::default() {
712 let turns =
713 ((self.limits.bounds.center().longitude() - lat_lng.longitude()) / constants::DEGREES_MAX).round();
714 requested = LatLng::saturating(
715 lat_lng.latitude(),
716 lat_lng.longitude() + turns * constants::DEGREES_MAX,
717 WrapMode::Unwrapped,
718 );
719 }
720 let mut constrained = self.limits.bounds.constrain(&requested);
721 if globe && self.limits.bounds == LatLngBounds::default() {
725 let current = self.view.center(WrapMode::Unwrapped).longitude();
726 if current.is_finite() {
727 let turns = ((current - constrained.longitude()) / constants::DEGREES_MAX).round();
728 constrained = LatLng::saturating(
729 constrained.latitude(),
730 constrained.longitude() + turns * constants::DEGREES_MAX,
731 WrapMode::Unwrapped,
732 );
733 }
734 }
735
736 let min_scale = if globe {
737 zoom_scale(self.min_zoom_at_latitude(constrained.latitude()))
738 } else {
739 self.constrained_min_scale()
740 };
741 let new_scale = mln_style::math::clamp_f64(zoom_scale(zoom), min_scale, self.max_scale());
742 let (x, y) = map_offset(&constrained, new_scale, globe);
743 if !x.is_finite() || !y.is_finite() {
745 return;
746 }
747 let (scale, x, y) = self.constrain(new_scale, x, y);
748 self.update(|p| {
749 p.scale = scale;
750 p.x = x;
751 p.y = y;
752 });
753 }
754
755 pub(crate) fn set_center_altitude(&mut self, alt_m: f64) {
758 if !alt_m.is_finite() {
759 return;
760 }
761 self.update(|p| p.center_altitude = alt_m);
762 }
763
764 pub(crate) fn set_terrain_min_elevation(&mut self, min_elevation: Option<f64>) {
769 if min_elevation.is_some_and(|min| !min.is_finite()) {
770 return;
771 }
772 self.update(|p| p.terrain_min_elevation = min_elevation);
773 }
774
775 pub(crate) fn raise_eye(&mut self, lift: f64) -> bool {
785 let view = &self.view;
786 if !lift.is_finite() || !view.is_valid() {
787 return false;
788 }
789 let distance = view.camera_to_center_distance();
792 let across = view.pitch().sin() * distance;
793 let up = view.pitch().cos() * distance + lift / Self::height_meters_per_pixel(view);
794 let raised = across.hypot(up);
795 if raised == 0.0 {
796 return false;
797 }
798 let pitch = mln_style::math::clamp_f64(across.atan2(up), self.limits.min_pitch, self.limits.max_pitch);
799 let zoom = view.zoom() + (distance / raised).log2();
800 let center = view.center(WrapMode::Unwrapped);
801 let before = *view.params();
802 self.set_pitch(pitch);
803 self.set_lat_lng_zoom(¢er, zoom);
804 *self.view.params() != before
805 }
806
807 pub(crate) fn recenter_on(&mut self, hit: &GroundHit) -> bool {
831 let view = &self.view;
832 if !view.is_valid() {
833 return false;
834 }
835 let recentered =
836 if view.is_globe() { Self::recentered_on_sphere(view, hit) } else { self.recentered_on_plane(hit) };
837 let Some((center, altitude, zoom)) = recentered else { return false };
838
839 let mut moved = self.clone();
840 moved.set_center_altitude(altitude);
841 moved.set_lat_lng_zoom(¢er, zoom);
842 let landed = moved.view.center(WrapMode::Unwrapped);
844 let mut on_screen = CameraOptions { center: Some(landed), ..CameraOptions::default() };
845 let mut screen_zoom = moved.view.zoom();
846 moved.constrain_camera_and_zoom_to_bounds(&mut on_screen, &mut screen_zoom);
847 let refused = (moved.view.zoom() - zoom).abs() > 1e-9
848 || (landed.latitude() - center.latitude()).abs() > 1e-9
849 || (landed.longitude() - center.longitude()).abs() > 1e-9
850 || on_screen.center != Some(landed)
851 || screen_zoom != moved.view.zoom();
852 if refused {
853 return false;
854 }
855 *self = moved;
856 true
857 }
858
859 fn recentered_on_plane(&self, hit: &GroundHit) -> Option<(LatLng, f64, f64)> {
862 let view = &self.view;
863 let eye = view.eye_position();
864 let forward = view.camera_pose().forward();
865 let latitude = hit.location(WrapMode::Unwrapped).latitude();
867 let meters = Projection::meters_per_pixel_at_latitude(latitude, 0.0) * TILE_SIZE_D;
868 let to_hit = DVec3::new((hit.world.x - eye.x) * meters, (hit.world.y - eye.y) * meters, hit.height - eye.z);
869 let distance = to_hit.dot(forward);
870 if !(distance.is_finite() && distance > 0.0) {
871 return None;
872 }
873 let world = Point::new(eye.x + forward.x * distance / meters, eye.y + forward.y * distance / meters);
874 let center = Projection::unproject(&world, 1.0 / TILE_SIZE_D, WrapMode::Unwrapped).ok()?;
875 let center = if self.limits.bounds == LatLngBounds::default() { center.wrapped() } else { center };
878 let zoom = scale_zoom(view.camera_to_center_distance() * meters / distance / TILE_SIZE_D);
879 Some((center, eye.z + forward.z * distance, zoom))
880 }
881
882 fn recentered_on_sphere(view: &View, hit: &GroundHit) -> Option<(LatLng, f64, f64)> {
886 let radius = |height: f64| 1.0 + height / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS;
887 let eye = view.globe_camera_position();
888 let center = VerticalPerspectiveProjection::surface_vector(&view.center(WrapMode::Unwrapped))
889 * radius(view.center_altitude());
890 let forward = (center - eye).normalize();
891 let target =
892 VerticalPerspectiveProjection::surface_vector(&hit.location(WrapMode::Unwrapped)) * radius(hit.height);
893 let distance = (target - eye).dot(forward);
894 if !(distance.is_finite() && distance > 0.0) {
895 return None;
896 }
897 let point = eye + forward * distance;
898 let length = point.length();
899 let location = VerticalPerspectiveProjection::surface_vector_to_lat_lng(point / length)?;
900 let location = view.lat_lng_near_center(&location);
901 let radius_at_zoom_0 =
902 VerticalPerspectiveProjection::globe_radius_pixels(Projection::world_size(1.0), location.latitude());
903 let zoom = scale_zoom(view.camera_to_center_distance() / distance / radius_at_zoom_0);
904 Some((location, (length - 1.0) * VerticalPerspectiveProjection::GLOBE_RADIUS_METERS, zoom))
905 }
906
907 fn height_meters_per_pixel(view: &View) -> f64 {
911 if view.is_globe() {
912 let latitude = view.center(WrapMode::Unwrapped).latitude();
913 VerticalPerspectiveProjection::GLOBE_RADIUS_METERS
914 / VerticalPerspectiveProjection::globe_radius_pixels(Projection::world_size(view.scale()), latitude)
915 } else {
916 view.meters_per_pixel()
917 }
918 }
919}
920
921#[cfg(test)]
922#[path = "transform_state_test.rs"]
923mod transform_state_test;