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 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 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 fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
210 self.update(|p| p.frustum_offset = *frustum_offset);
211 }
212
213 pub fn set_north_orientation(&mut self, orientation: NorthOrientation) {
214 self.update(|p| p.north_orientation = orientation);
215 }
216
217 #[must_use]
218 pub fn constrain_mode(&self) -> ConstrainMode {
219 self.view.params().constrain_mode
220 }
221
222 pub fn set_constrain_mode(&mut self, mode: ConstrainMode) {
223 self.update(|p| p.constrain_mode = mode);
224 }
225
226 pub fn set_viewport_mode(&mut self, mode: ViewportMode) {
227 self.update(|p| p.viewport_mode = mode);
228 }
229
230 pub fn set_center_clamped_to_ground(&mut self, clamped: bool) {
231 self.update(|p| p.center_clamped_to_ground = clamped);
232 }
233
234 pub fn set_globe_free_bearing(&mut self, free_bearing: bool) {
235 self.update(|p| p.globe_free_bearing = free_bearing);
236 }
237
238 pub fn set_padding(&mut self, padding: &EdgeInsets) {
239 self.update(|p| p.padding = *padding);
240 }
241
242 #[must_use]
246 pub 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 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 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 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 fn set_fov(&mut self, fov: f64) {
354 if fov.is_finite() {
355 self.update(|p| p.fov = fov);
356 }
357 }
358
359 pub 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 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 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 fn set_axonometric(&mut self, axonometric: bool) {
384 self.update(|p| p.axonometric = axonometric);
385 }
386
387 #[must_use]
393 pub 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 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 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 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 fn constrain_camera_and_zoom_to_bounds(&self, requested_camera: &mut CameraOptions, requested_zoom: &mut f64) {
473 if self.constrain_mode() != ConstrainMode::Screen || self.limits.bounds == LatLngBounds::default() {
474 return;
475 }
476
477 let view = &self.view;
478 let current_center = view.center(WrapMode::Unwrapped);
479 let center_lat_lng = requested_camera.center.unwrap_or(current_center);
480
481 let mut anchor_offset = Point::new(0.0, 0.0);
482 let requested_scale = zoom_scale(*requested_zoom);
483
484 if let Some(mut anchor) = requested_camera.anchor {
488 anchor.y = f64::from(view.size().height) - anchor.y;
489 let mut state = self.clone();
491 state.set_lat_lng_zoom(¤t_center, scale_zoom(requested_scale));
492 if let (Ok(anchor_lat_lng), Ok(screen_lat_lng)) = (
495 view.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped),
496 state.view.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped),
497 ) {
498 let lat_lng_coord = Projection::project(&anchor_lat_lng, requested_scale);
499 let anchor_coord = Projection::project(&screen_lat_lng, requested_scale);
500 anchor_offset = Point::new(lat_lng_coord.x - anchor_coord.x, lat_lng_coord.y - anchor_coord.y);
501 }
502 }
503
504 let current_bounds = self.limits.bounds;
505 let ne_bounds = Projection::project(¤t_bounds.northeast(), requested_scale);
506 let sw_bounds = Projection::project(¤t_bounds.southwest(), requested_scale);
507 let center = Projection::project(¢er_lat_lng, requested_scale);
508 let current_center = Projection::project(¤t_center, requested_scale);
509
510 let min_y = ne_bounds.y;
511 let max_y = sw_bounds.y;
512 let min_x = sw_bounds.x;
513 let max_x = ne_bounds.x;
514
515 let start_x = center.x;
516 let start_y = center.y;
517
518 let mut result_x = start_x;
519 let mut result_y = start_y;
520
521 let screen_width = view.size().width;
522 let screen_height = view.size().height;
523
524 let h2 = f64::from(screen_height) / 2.0;
525 if start_y - h2 + anchor_offset.y < min_y {
526 result_y = min_y + h2;
527 }
528 if start_y + anchor_offset.y + h2 > max_y {
529 result_y = max_y - h2;
530 }
531
532 let w2 = f64::from(screen_width) / 2.0;
533 if start_x + anchor_offset.x - w2 < min_x {
534 result_x = min_x + w2;
535 }
536 if start_x + anchor_offset.x + w2 > max_x {
537 result_x = max_x - w2;
538 }
539
540 let mut scale_y = 0.0;
541 if max_y - min_y < f64::from(screen_height) {
542 scale_y = f64::from(screen_height) / (max_y - min_y);
543 result_y = f64::midpoint(max_y, min_y);
544 }
545
546 let mut scale_x = 0.0;
547 if max_x - min_x < f64::from(screen_width) {
548 scale_x = f64::from(screen_width) / (max_x - min_x);
549 result_x = f64::midpoint(max_x, min_x);
550 }
551
552 let max_scale = if scale_x > scale_y { scale_x } else { scale_y };
553
554 if max_scale > 1.000_001 {
559 *requested_zoom += scale_zoom(max_scale);
560
561 if scale_y > scale_x {
562 result_x = current_center.x;
565 } else {
566 result_y = current_center.y;
569 }
570
571 if result_x * max_scale - w2 <= min_x * max_scale {
577 result_x = min_x * max_scale + w2;
578 result_x /= max_scale;
579 } else if result_x * max_scale + w2 >= max_x * max_scale {
580 result_x = max_x * max_scale - w2;
581 result_x /= max_scale;
582 }
583
584 if result_y * max_scale - h2 <= min_y * max_scale {
585 result_y = min_y * max_scale + h2;
586 result_y /= max_scale;
587 } else if result_y * max_scale + h2 >= max_y * max_scale {
588 result_y = max_y * max_scale - h2;
589 result_y /= max_scale;
590 }
591 }
592
593 if result_x != start_x || result_y != start_y {
594 requested_camera.anchor = None;
596 requested_camera.center =
598 Projection::unproject(&Point::new(result_x, result_y), requested_scale, WrapMode::Unwrapped).ok();
599 }
600 }
601
602 #[must_use]
607 pub fn min_zoom_for_screen_bounds(&self) -> Option<f64> {
608 if self.constrain_mode() != ConstrainMode::Screen || self.limits.bounds == LatLngBounds::default() {
609 return None;
610 }
611 let ne = Projection::project(&self.limits.bounds.northeast(), 1.0);
614 let sw = Projection::project(&self.limits.bounds.southwest(), 1.0);
615 let size = self.view.size();
616 let scale_x = f64::from(size.width) / (ne.x - sw.x);
617 let scale_y = f64::from(size.height) / (sw.y - ne.y);
618 Some(scale_zoom(f64::max(scale_x, scale_y)))
619 }
620
621 pub fn move_lat_lng(&mut self, lat_lng: &LatLng, anchor: &ScreenCoordinate) -> Result<(), Error> {
628 self.move_lat_lng_at(lat_lng, anchor, 0.0)
629 }
630
631 pub fn move_lat_lng_at(&mut self, lat_lng: &LatLng, anchor: &ScreenCoordinate, height: f64) -> Result<(), Error> {
639 let view = &self.view;
640 if view.is_globe() {
641 if let Some(center) =
642 VerticalPerspectiveProjection::center_for_location_at_point(view, lat_lng, anchor, height)
643 {
644 let target = self.constrained_center(¢er, view.zoom());
645 let zoom = view.zoom()
646 + VerticalPerspectiveProjection::zoom_adjustment(
647 view.center(WrapMode::Unwrapped).latitude(),
648 target.latitude(),
649 );
650 self.set_lat_lng_zoom(&target, zoom);
651 }
652 return Ok(());
653 }
654 let center = self.center_for_lat_lng_at(lat_lng, anchor, height)?;
655 let target = if self.limits.bounds == LatLngBounds::default() { center.wrapped() } else { center };
658 let zoom = self.view.zoom();
659 self.set_lat_lng_zoom(&target, zoom);
660 Ok(())
661 }
662
663 pub fn center_for_lat_lng_at(
674 &self,
675 lat_lng: &LatLng,
676 anchor: &ScreenCoordinate,
677 height: f64,
678 ) -> Result<LatLng, Error> {
679 let view = &self.view;
680 if view.is_globe() && !view.size().is_empty() {
681 return VerticalPerspectiveProjection::center_for_location_at_point(view, lat_lng, anchor, height)
682 .ok_or_else(|| Error::invalid_argument("no center holds the location at the point"));
683 }
684 let scale = view.scale();
685 let center_coord = Projection::project(&view.center(WrapMode::Unwrapped), scale);
686 let lat_lng_coord = Projection::project(lat_lng, scale);
687 let anchor_coord =
688 Projection::project(&view.screen_coordinate_to_lat_lng_at(anchor, height, WrapMode::Unwrapped)?, scale);
689 Projection::unproject(
690 &Point::new(
691 center_coord.x + lat_lng_coord.x - anchor_coord.x,
692 center_coord.y + lat_lng_coord.y - anchor_coord.y,
693 ),
694 scale,
695 WrapMode::Unwrapped,
696 )
697 }
698
699 pub fn set_lat_lng_zoom(&mut self, lat_lng: &LatLng, zoom: f64) {
700 if !zoom.is_finite() {
701 return;
702 }
703 let globe = self.view.is_globe();
704 let mut requested = *lat_lng;
705 if globe && self.limits.bounds != LatLngBounds::default() {
709 let turns =
710 ((self.limits.bounds.center().longitude() - lat_lng.longitude()) / constants::DEGREES_MAX).round();
711 requested = LatLng::saturating(
712 lat_lng.latitude(),
713 lat_lng.longitude() + turns * constants::DEGREES_MAX,
714 WrapMode::Unwrapped,
715 );
716 }
717 let mut constrained = self.limits.bounds.constrain(&requested);
718 if globe && self.limits.bounds == LatLngBounds::default() {
722 let current = self.view.center(WrapMode::Unwrapped).longitude();
723 if current.is_finite() {
724 let turns = ((current - constrained.longitude()) / constants::DEGREES_MAX).round();
725 constrained = LatLng::saturating(
726 constrained.latitude(),
727 constrained.longitude() + turns * constants::DEGREES_MAX,
728 WrapMode::Unwrapped,
729 );
730 }
731 }
732
733 let min_scale = if globe {
734 zoom_scale(self.min_zoom_at_latitude(constrained.latitude()))
735 } else {
736 self.constrained_min_scale()
737 };
738 let new_scale = mln_style::math::clamp_f64(zoom_scale(zoom), min_scale, self.max_scale());
739 let (x, y) = map_offset(&constrained, new_scale, globe);
740 if !x.is_finite() || !y.is_finite() {
742 return;
743 }
744 let (scale, x, y) = self.constrain(new_scale, x, y);
745 self.update(|p| {
746 p.scale = scale;
747 p.x = x;
748 p.y = y;
749 });
750 }
751
752 pub fn set_center_altitude(&mut self, alt_m: f64) {
755 if !alt_m.is_finite() {
756 return;
757 }
758 self.update(|p| p.center_altitude = alt_m);
759 }
760
761 pub fn set_terrain_min_elevation(&mut self, min_elevation: Option<f64>) {
766 if min_elevation.is_some_and(|min| !min.is_finite()) {
767 return;
768 }
769 self.update(|p| p.terrain_min_elevation = min_elevation);
770 }
771
772 pub fn raise_eye(&mut self, lift: f64) -> bool {
782 let view = &self.view;
783 if !lift.is_finite() || !view.is_valid() {
784 return false;
785 }
786 let distance = view.camera_to_center_distance();
789 let across = view.pitch().sin() * distance;
790 let up = view.pitch().cos() * distance + lift / Self::height_meters_per_pixel(view);
791 let raised = across.hypot(up);
792 if raised == 0.0 {
793 return false;
794 }
795 let pitch = mln_style::math::clamp_f64(across.atan2(up), self.limits.min_pitch, self.limits.max_pitch);
796 let zoom = view.zoom() + (distance / raised).log2();
797 let center = view.center(WrapMode::Unwrapped);
798 let before = *view.params();
799 self.set_pitch(pitch);
800 self.set_lat_lng_zoom(¢er, zoom);
801 *self.view.params() != before
802 }
803
804 pub fn recenter_on(&mut self, hit: &GroundHit) -> bool {
828 let view = &self.view;
829 if !view.is_valid() {
830 return false;
831 }
832 let recentered =
833 if view.is_globe() { Self::recentered_on_sphere(view, hit) } else { self.recentered_on_plane(hit) };
834 let Some((center, altitude, zoom)) = recentered else { return false };
835
836 let mut moved = self.clone();
837 moved.set_center_altitude(altitude);
838 moved.set_lat_lng_zoom(¢er, zoom);
839 let landed = moved.view.center(WrapMode::Unwrapped);
841 let mut on_screen = CameraOptions { center: Some(landed), ..CameraOptions::default() };
842 let mut screen_zoom = moved.view.zoom();
843 moved.constrain_camera_and_zoom_to_bounds(&mut on_screen, &mut screen_zoom);
844 let refused = (moved.view.zoom() - zoom).abs() > 1e-9
845 || (landed.latitude() - center.latitude()).abs() > 1e-9
846 || (landed.longitude() - center.longitude()).abs() > 1e-9
847 || on_screen.center != Some(landed)
848 || screen_zoom != moved.view.zoom();
849 if refused {
850 return false;
851 }
852 *self = moved;
853 true
854 }
855
856 fn recentered_on_plane(&self, hit: &GroundHit) -> Option<(LatLng, f64, f64)> {
859 let view = &self.view;
860 let eye = view.eye_position();
861 let forward = view.camera_pose().forward();
862 let latitude = hit.location(WrapMode::Unwrapped).latitude();
864 let meters = Projection::meters_per_pixel_at_latitude(latitude, 0.0) * TILE_SIZE_D;
865 let to_hit = DVec3::new((hit.world.x - eye.x) * meters, (hit.world.y - eye.y) * meters, hit.height - eye.z);
866 let distance = to_hit.dot(forward);
867 if !(distance.is_finite() && distance > 0.0) {
868 return None;
869 }
870 let world = Point::new(eye.x + forward.x * distance / meters, eye.y + forward.y * distance / meters);
871 let center = Projection::unproject(&world, 1.0 / TILE_SIZE_D, WrapMode::Unwrapped).ok()?;
872 let center = if self.limits.bounds == LatLngBounds::default() { center.wrapped() } else { center };
875 let zoom = scale_zoom(view.camera_to_center_distance() * meters / distance / TILE_SIZE_D);
876 Some((center, eye.z + forward.z * distance, zoom))
877 }
878
879 fn recentered_on_sphere(view: &View, hit: &GroundHit) -> Option<(LatLng, f64, f64)> {
883 let radius = |height: f64| 1.0 + height / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS;
884 let eye = view.globe_camera_position();
885 let center = VerticalPerspectiveProjection::surface_vector(&view.center(WrapMode::Unwrapped))
886 * radius(view.center_altitude());
887 let forward = (center - eye).normalize();
888 let target =
889 VerticalPerspectiveProjection::surface_vector(&hit.location(WrapMode::Unwrapped)) * radius(hit.height);
890 let distance = (target - eye).dot(forward);
891 if !(distance.is_finite() && distance > 0.0) {
892 return None;
893 }
894 let point = eye + forward * distance;
895 let length = point.length();
896 let location = VerticalPerspectiveProjection::surface_vector_to_lat_lng(point / length)?;
897 let location = view.lat_lng_near_center(&location);
898 let radius_at_zoom_0 =
899 VerticalPerspectiveProjection::globe_radius_pixels(Projection::world_size(1.0), location.latitude());
900 let zoom = scale_zoom(view.camera_to_center_distance() / distance / radius_at_zoom_0);
901 Some((location, (length - 1.0) * VerticalPerspectiveProjection::GLOBE_RADIUS_METERS, zoom))
902 }
903
904 fn height_meters_per_pixel(view: &View) -> f64 {
908 if view.is_globe() {
909 let latitude = view.center(WrapMode::Unwrapped).latitude();
910 VerticalPerspectiveProjection::GLOBE_RADIUS_METERS
911 / VerticalPerspectiveProjection::globe_radius_pixels(Projection::world_size(view.scale()), latitude)
912 } else {
913 view.meters_per_pixel()
914 }
915 }
916}
917
918#[cfg(test)]
919#[path = "transform_state_test.rs"]
920mod transform_state_test;