1use std::f64::consts::PI;
2
3use glam::dcamera::rh::proj::opengl::perspective;
4use glam::{DMat3, DMat4, DQuat, DVec3, DVec4, EulerRot, Vec3Swizzles, Vec4Swizzles};
5use mln_style::constants::{EXTENT, LATITUDE_MAX, TILE_SIZE_D};
6use mln_style::geo::{LatLng, WrapMode};
7use mln_style::geometry::Point;
8use mln_style::interpolate::interpolate;
9
10use crate::camera::projection::{ProjectedTilePoint, ProjectionData, mercator_tile_coords};
11use crate::camera::transform_state::TransformState;
12use crate::camera::view::{NorthOrientation, View};
13use crate::geo::ScreenCoordinate;
14use crate::geo::projection::Projection;
15use crate::tile::UnwrappedTileID;
16
17const POLE_AXIS_DISTANCE: f64 = 1e-6;
20
21fn rotate_x(v: DVec3, rad: f64) -> DVec3 {
22 DMat3::from_rotation_x(rad) * v
23}
24
25fn rotate_y(v: DVec3, rad: f64) -> DVec3 {
26 DMat3::from_rotation_y(rad) * v
27}
28
29fn rotate_z(v: DVec3, rad: f64) -> DVec3 {
30 DMat3::from_rotation_z(rad) * v
31}
32
33fn line_of_sight_blocked(camera: DVec3, point: DVec3) -> bool {
36 let to_point = point - camera;
37 let length_sq = to_point.length_squared();
38 if length_sq == 0.0 {
39 return false;
40 }
41 let t = (-camera.dot(to_point) / length_sq).clamp(0.0, 1.0);
42 (camera + to_point * t).length_squared() < 1.0
43}
44
45fn ray_sphere_intersection(origin: DVec3, direction: DVec3) -> Option<f64> {
49 let origin_dot_direction = origin.dot(direction);
50 let inner = origin - direction * origin_dot_direction;
51 let discriminant = 1.0 - inner.length_squared();
52 if discriminant.is_nan() || discriminant < 0.0 {
54 return None;
55 }
56 let c = origin.length_squared() - 1.0;
57 let q = -origin_dot_direction + (if origin_dot_direction < 0.0 { 1.0 } else { -1.0 }) * discriminant.sqrt();
58 let t0 = c / q;
59 let t1 = q;
60 if f64::max(t0, t1) < 0.0 {
63 return None;
64 }
65 Some(f64::min(t0, t1))
66}
67
68fn point_plane_signed_distance(plane: DVec4, point: DVec3) -> f64 {
69 plane.dot(point.extend(1.0))
70}
71
72fn ray_direction_from_pixel(view: &View, point: &ScreenCoordinate, inverse_view_projection: &DMat4) -> DVec3 {
73 let size = view.size();
74 let clip =
75 DVec3::new(point.x / f64::from(size.width) * 2.0 - 1.0, point.y / f64::from(size.height) * 2.0 - 1.0, 1.0);
76 (inverse_view_projection.project_point3(clip) - view.globe_camera_position()).normalize()
77}
78
79fn angle_to_rotate_between_vectors_2d(mut x0: f64, mut y0: f64, mut x1: f64, mut y1: f64) -> f64 {
81 let len0 = (x0 * x0 + y0 * y0).sqrt();
82 let len1 = (x1 * x1 + y1 * y1).sqrt();
83 x0 /= len0;
84 y0 /= len0;
85 x1 /= len1;
86 y1 /= len1;
87 let cross = x0 * y1 - x1 * y0;
88 let angle = (x0 * x1 + y0 * y1).clamp(-1.0, 1.0).acos();
89 if cross > 0.0 { angle } else { -angle }
90}
91
92fn distance_of_angles_radians(a: f64, b: f64) -> f64 {
93 let two_pi = 2.0 * PI;
94 let d = ((a - b) % two_pi + two_pi) % two_pi;
96 f64::min(d, two_pi - d)
97}
98
99fn integrate_secant(x: f64) -> f64 {
102 let half = 0.5 * x;
103 let sin = half.sin();
104 let cos = half.cos();
105 (sin + cos).ln() - (cos - sin).ln()
106}
107
108fn sign(value: f64) -> i32 {
109 i32::from(value > 0.0) - i32::from(value < 0.0)
110}
111
112#[derive(Clone, Copy, Debug, Default)]
116pub struct VerticalPerspectiveProjection;
117
118#[derive(Clone, Copy, Debug, PartialEq)]
119pub struct CenterAndBearing {
120 pub(crate) center: LatLng,
121 pub(crate) bearing: f64,
123}
124
125const RAY_SURFACE_DISTANCE_FOR_SLOWING_START: f64 = 0.3;
128const SLOWING_MULTIPLIER: f64 = 0.5;
129const INTERPOLATE_TO_HEURISTIC_START_LNG: f64 = 45.0;
130const INTERPOLATE_TO_HEURISTIC_END_LNG: f64 = 85.0;
131const INTERPOLATE_TO_HEURISTIC_EXPONENT: f64 = 0.25;
132const INTERPOLATE_TO_HEURISTIC_START_HORIZON: f64 = 0.95;
133const INTERPOLATE_TO_HEURISTIC_END_HORIZON: f64 = 0.999;
134const SLOWING_RADIUS_START: f64 = 0.9;
135const SLOWING_RADIUS_STOP: f64 = 0.5;
136const SLOWING_RADIUS_SLOW_FACTOR: f64 = 0.25;
137const POLE_AREA_FADE_SCALE: f64 = 4.0;
140
141fn remap_saturate(value: f64, old_min: f64, old_max: f64, new_min: f64, new_max: f64) -> f64 {
142 let t = ((value - old_min) / (old_max - old_min)).clamp(0.0, 1.0);
143 new_min + (new_max - new_min) * t
144}
145
146impl VerticalPerspectiveProjection {
147 pub const GLOBE_RADIUS_METERS: f64 = 6_371_008.8;
150
151 #[must_use]
154 pub(crate) fn globe_radius_pixels(world_size: f64, center_latitude: f64) -> f64 {
155 world_size / (2.0 * PI) / Self::planet_scale(center_latitude)
156 }
157
158 #[must_use]
162 pub(crate) fn planet_scale(center_latitude: f64) -> f64 {
163 mln_style::math::deg2rad(f64::min(center_latitude.abs(), LATITUDE_MAX)).cos()
164 }
165
166 #[must_use]
168 pub fn tile_coordinates_to_sphere(tile_point: &Point<f64>, tile_id: &UnwrappedTileID) -> DVec3 {
169 let [sin_x, cos_x, sin_y, cos_y] = Self::tile_coordinates_to_angles(tile_point, tile_id).to_array();
170 DVec3::new(sin_x * cos_y, sin_y, cos_x * cos_y)
171 }
172
173 fn tile_coordinates_to_angles(tile_point: &Point<f64>, tile_id: &UnwrappedTileID) -> DVec4 {
177 let scale = 1.0 / (1u64 << tile_id.canonical.z) as f64;
178 let mercator_x = tile_point.x / f64::from(EXTENT) * scale + f64::from(tile_id.canonical.x) * scale;
179 let mercator_y = tile_point.y / f64::from(EXTENT) * scale + f64::from(tile_id.canonical.y) * scale;
180 let spherical_x = mercator_x * PI * 2.0 + PI;
181 let t = (PI - (mercator_y * PI * 2.0)).exp();
184 let t2 = t * t;
185 DVec4::new(spherical_x.sin(), spherical_x.cos(), (t2 - 1.0) / (t2 + 1.0), (2.0 * t) / (t2 + 1.0))
186 }
187
188 fn center_radius(view: &View) -> f64 {
192 1.0 + view.center_altitude() / Self::GLOBE_RADIUS_METERS
193 }
194
195 #[must_use]
200 pub(crate) fn globe_view_projection_matrix(view: &View, radius: f64) -> DMat4 {
201 let size = view.size();
202 let camera_to_center_distance = view.camera_to_center_distance();
203 let center = view.center(WrapMode::Unwrapped);
204 let near = if view.terrain_min_elevation().is_some() { view.near_z() } else { 0.5 };
205 let center_radius = Self::center_radius(view);
206
207 let mut projection = perspective(
208 view.perspective_fov(),
209 f64::from(size.width) / f64::from(size.height),
210 near,
211 camera_to_center_distance + radius * (center_radius + 1.0),
212 );
213 let offset = view.center_offset();
215 projection.z_axis.x = -offset.x * 2.0 / f64::from(size.width);
216 projection.z_axis.y = offset.y * 2.0 / f64::from(size.height);
217
218 if view.north_orientation() != NorthOrientation::Upwards {
219 projection *= DMat4::from_rotation_z(-view.north_orientation_angle());
220 }
221
222 projection
223 * DMat4::from_translation(DVec3::new(0.0, 0.0, -camera_to_center_distance))
224 * DMat4::from_rotation_z(view.roll())
225 * DMat4::from_rotation_x(-view.pitch())
226 * DMat4::from_rotation_z(-view.angle())
227 * DMat4::from_translation(DVec3::new(0.0, 0.0, -radius * center_radius))
228 * DMat4::from_rotation_x(mln_style::math::deg2rad(center.latitude()))
229 * DMat4::from_rotation_y(-mln_style::math::deg2rad(center.longitude()))
230 * DMat4::from_scale(DVec3::splat(radius))
231 }
232
233 #[must_use]
236 pub(crate) fn clipping_plane(view: &View, radius: f64) -> DVec4 {
237 let pitch = view.pitch();
238 let distance_camera_to_b = view.camera_to_center_distance() / radius;
239 let distance_camera_to_a = pitch.sin() * distance_camera_to_b;
240 let distance_a_to_c = pitch.cos() * distance_camera_to_b + Self::center_radius(view);
241 let distance_camera_to_c =
242 (distance_camera_to_a * distance_camera_to_a + distance_a_to_c * distance_a_to_c).sqrt();
243 let tangent_plane_distance_to_c = 1.0 / distance_camera_to_c;
244
245 let mut plane =
246 DVec3::new(0.0, -distance_camera_to_a / distance_camera_to_c, distance_a_to_c / distance_camera_to_c);
247
248 let center = view.center(WrapMode::Unwrapped);
249 plane = rotate_z(plane, view.angle());
250 plane = rotate_x(plane, -mln_style::math::deg2rad(center.latitude()));
251 plane = rotate_y(plane, mln_style::math::deg2rad(center.longitude()));
252
253 plane.extend(-tangent_plane_distance_to_c) / plane.length()
254 }
255
256 #[must_use]
259 pub(crate) fn camera_position(view: &View, radius: f64) -> DVec3 {
260 let center = view.center(WrapMode::Unwrapped);
261 let mut position = DVec3::new(0.0, 0.0, view.camera_to_center_distance() / radius);
262 position = rotate_z(position, -view.roll());
263 position = rotate_x(position, view.pitch());
264 position = rotate_z(position, view.angle());
265 position += DVec3::Z * Self::center_radius(view);
266 position = rotate_x(position, -mln_style::math::deg2rad(center.latitude()));
267 rotate_y(position, mln_style::math::deg2rad(center.longitude()))
268 }
269
270 #[must_use]
271 pub(crate) fn surface_vector(lat_lng: &LatLng) -> DVec3 {
272 let lng = mln_style::math::deg2rad(lat_lng.longitude());
273 let lat = mln_style::math::deg2rad(lat_lng.latitude());
274 let len = lat.cos();
275 DVec3::new(lng.sin() * len, lat.sin(), lng.cos() * len)
276 }
277
278 pub(crate) fn surface_vector_to_lat_lng(surface: DVec3) -> Option<LatLng> {
281 let latitude = mln_style::math::rad2deg(surface.y.clamp(-1.0, 1.0).asin());
282 let length_xz = surface.xz().length();
283 if length_xz <= POLE_AXIS_DISTANCE {
284 return LatLng::with_mode(latitude, 0.0, WrapMode::Unwrapped).ok();
285 }
286 let acos_z = (surface.z / length_xz).clamp(-1.0, 1.0).acos();
287 let longitude = mln_style::math::rad2deg(if surface.x > 0.0 { acos_z } else { -acos_z });
288 LatLng::with_mode(latitude, longitude, WrapMode::Wrapped).ok()
289 }
290
291 pub(crate) fn sphere_point_to_world(view: &View, point: DVec3) -> Option<DVec3> {
297 let length = point.length();
298 let location = view.lat_lng_near_center(&Self::surface_vector_to_lat_lng(point / length)?);
299 let offset = view.world().project_from_center(&location, 1.0 / TILE_SIZE_D);
300 Some(DVec3::new(0.5 + offset.x, 0.5 + offset.y, (length - 1.0) * Self::GLOBE_RADIUS_METERS))
301 }
302
303 pub(crate) fn screen_coordinate_to_surface(view: &View, point: &ScreenCoordinate, height: f64) -> DVec3 {
310 let origin = camera_over_sphere(view, height);
311 let direction = ray_direction_from_pixel(view, point, &view.inverse_globe_view_projection_matrix());
312
313 if let Some(t) = ray_sphere_intersection(origin, direction) {
314 return (origin + direction * t).normalize();
315 }
316
317 let plane = if height == 0.0 {
320 view.globe_clipping_plane()
321 } else {
322 let distance = origin.length();
323 (origin / distance).extend(-1.0 / distance)
324 };
325 let normal = plane.xyz();
326 let distance_to_intersection = -point_plane_signed_distance(plane, origin) / direction.dot(normal);
327
328 let plane_intersection = if distance_to_intersection > 0.0 {
329 origin + direction * distance_to_intersection
330 } else {
331 const MAX_RAY_LENGTH: f64 = 2.0;
332 let distant_point = origin + direction * MAX_RAY_LENGTH;
333 distant_point - normal * point_plane_signed_distance(plane, distant_point)
334 };
335
336 let horizon_center = normal * -plane.w;
337 let horizon_radius = f64::max(0.0, 1.0 - plane.w * plane.w).sqrt();
338 let relative = plane_intersection - horizon_center;
339 horizon_center + relative * (horizon_radius / relative.length())
340 }
341
342 #[must_use]
345 pub(crate) fn screen_coordinate_hits_globe(view: &View, point: &ScreenCoordinate, height: f64) -> bool {
346 let direction = ray_direction_from_pixel(view, point, &view.inverse_globe_view_projection_matrix());
347 ray_sphere_intersection(camera_over_sphere(view, height), direction).is_some()
348 }
349
350 pub(crate) fn screen_coordinate_to_lat_lng(
353 view: &View,
354 point: &ScreenCoordinate,
355 height: f64,
356 wrap_mode: WrapMode,
357 ) -> Option<LatLng> {
358 let lat_lng = Self::surface_vector_to_lat_lng(Self::screen_coordinate_to_surface(view, point, height))?;
359 Some(if wrap_mode == WrapMode::Wrapped { lat_lng.wrapped() } else { lat_lng })
360 }
361
362 #[must_use]
365 pub(crate) fn lat_lng_to_screen_coordinate(
366 view: &View,
367 lat_lng: &LatLng,
368 height: f64,
369 ) -> (ScreenCoordinate, DVec4) {
370 let sphere = Self::surface_vector(lat_lng) * (1.0 + height / Self::GLOBE_RADIUS_METERS);
371 let clip = view.globe_view_projection_matrix() * sphere.extend(1.0);
372 let size = view.size();
373 let point = Point::new(
374 (clip.x / clip.w * 0.5 + 0.5) * f64::from(size.width),
375 (clip.y / clip.w * 0.5 + 0.5) * f64::from(size.height),
376 );
377 (point, clip)
378 }
379
380 pub(crate) fn center_for_location_at_point(
383 view: &View,
384 lat_lng: &LatLng,
385 anchor: &ScreenCoordinate,
386 height: f64,
387 ) -> Option<LatLng> {
388 const LIMIT: f64 = PI * 0.5;
393 let center = view.center(WrapMode::Unwrapped);
394 let vec_to_pixel_current = Self::screen_coordinate_to_surface(view, anchor, height);
395 let vec_to_target = Self::surface_vector(lat_lng);
396
397 let rotated_pixel_vector = rotate_x(
398 rotate_y(vec_to_pixel_current, -mln_style::math::deg2rad(center.longitude())),
399 mln_style::math::deg2rad(center.latitude()),
400 );
401
402 let vec_to_target_xz_length_squared = vec_to_target.xz().length_squared();
403 let target_x_squared = rotated_pixel_vector.x * rotated_pixel_vector.x;
404 if vec_to_target_xz_length_squared < target_x_squared {
405 return None;
406 }
407
408 let intersection_a = (vec_to_target_xz_length_squared - target_x_squared).sqrt();
409 let intersection_b = -intersection_a;
410
411 let solve = |intersection: f64| {
412 let lng = angle_to_rotate_between_vectors_2d(
413 vec_to_target.x,
414 vec_to_target.z,
415 rotated_pixel_vector.x,
416 intersection,
417 );
418 let vec_to_target_lng = rotate_y(vec_to_target, -lng);
419 let lat = angle_to_rotate_between_vectors_2d(
420 vec_to_target_lng.y,
421 vec_to_target_lng.z,
422 rotated_pixel_vector.y,
423 rotated_pixel_vector.z,
424 );
425 (lng, lat)
426 };
427 let (lng_a, lat_a) = solve(intersection_a);
428 let (lng_b, lat_b) = solve(intersection_b);
429
430 let valid_a = (-LIMIT..=LIMIT).contains(&lat_a);
431 let valid_b = (-LIMIT..=LIMIT).contains(&lat_b);
432
433 let (lng, lat) = if valid_a && valid_b {
434 let center_lng = mln_style::math::deg2rad(center.longitude());
435 let center_lat = mln_style::math::deg2rad(center.latitude());
436 let distance_a =
437 distance_of_angles_radians(lng_a, center_lng) + distance_of_angles_radians(lat_a, center_lat);
438 let distance_b =
439 distance_of_angles_radians(lng_b, center_lng) + distance_of_angles_radians(lat_b, center_lat);
440 if distance_a < distance_b { (lng_a, lat_a) } else { (lng_b, lat_b) }
441 } else if valid_a {
442 (lng_a, lat_a)
443 } else if valid_b {
444 (lng_b, lat_b)
445 } else {
446 return None;
447 };
448 Some(LatLng::saturating(
449 (mln_style::math::rad2deg(lat)).clamp(-90.0, 90.0),
450 mln_style::math::rad2deg(lng),
451 WrapMode::Unwrapped,
452 ))
453 }
454
455 pub(crate) fn zoom_around_point(
466 state: &mut TransformState,
467 anchor: &ScreenCoordinate,
468 zoom_location: &LatLng,
469 height: f64,
470 zoom_delta: f64,
471 free_bearing: bool,
472 ) {
473 if zoom_delta == 0.0 {
474 return;
475 }
476 let center = state.view().center(WrapMode::Unwrapped);
477 let on_pole = mln_style::math::deg2rad(zoom_location.latitude()).cos() <= POLE_AXIS_DISTANCE;
481 let d_lng_raw = if on_pole {
482 0.0
483 } else {
484 Self::difference_of_angles_degrees(center.longitude(), zoom_location.longitude())
485 };
486 let d_lng = d_lng_raw / ((d_lng_raw / 180.0).abs() + 1.0);
487 let d_lat = Self::difference_of_angles_degrees(center.latitude(), zoom_location.latitude());
488
489 let ray_origin = camera_over_sphere(state.view(), height);
492 let ray_direction =
493 ray_direction_from_pixel(state.view(), anchor, &state.view().inverse_globe_view_projection_matrix());
494 let closest_point = ray_origin - ray_direction * ray_origin.dot(ray_direction);
495 let ray_distance_from_globe_center = closest_point.length();
496 let distance_factor =
497 (-f64::max(ray_distance_from_globe_center - 1.0 - RAY_SURFACE_DISTANCE_FOR_SLOWING_START, 0.0)
498 * SLOWING_MULTIPLIER)
499 .exp();
500 let interpolation_factor_horizon = remap_saturate(
501 ray_distance_from_globe_center,
502 INTERPOLATE_TO_HEURISTIC_START_HORIZON,
503 INTERPOLATE_TO_HEURISTIC_END_HORIZON,
504 0.0,
505 1.0,
506 );
507
508 let size = state.view().size();
511 let radius = Self::globe_radius_pixels(Projection::world_size(state.view().scale()), center.latitude())
512 / f64::from(size.width.min(size.height));
513 let radius_factor =
514 remap_saturate(radius, SLOWING_RADIUS_START, SLOWING_RADIUS_STOP, 1.0, SLOWING_RADIUS_SLOW_FACTOR);
515 let slowing_factor = f64::min(distance_factor, 1.0 + (radius_factor - 1.0) * interpolation_factor_horizon);
516
517 let factor = (1.0 - 2.0f64.powf(-zoom_delta)) * slowing_factor;
518 if free_bearing {
519 zoom_turning_the_planet(state, anchor, zoom_location, height, factor, interpolation_factor_horizon);
520 return;
521 }
522 let heuristic_center = LatLng::saturating(
523 (center.latitude() + d_lat * factor).clamp(-90.0, 90.0),
524 center.longitude() + d_lng * factor,
525 WrapMode::Unwrapped,
526 );
527
528 let mut exact_center =
529 Self::center_for_location_at_point(state.view(), zoom_location, anchor, height).unwrap_or(center);
530 if on_pole {
531 exact_center = LatLng::saturating(exact_center.latitude(), center.longitude(), WrapMode::Unwrapped);
532 }
533
534 let interpolation_factor_longitude = remap_saturate(
535 d_lng_raw.abs(),
536 INTERPOLATE_TO_HEURISTIC_START_LNG,
537 INTERPOLATE_TO_HEURISTIC_END_LNG,
538 0.0,
539 1.0,
540 );
541 let heuristic_factor = f64::max(interpolation_factor_longitude, interpolation_factor_horizon)
542 .powf(INTERPOLATE_TO_HEURISTIC_EXPONENT);
543 let target = LatLng::saturating(
544 (exact_center.latitude()
545 + Self::difference_of_angles_degrees(exact_center.latitude(), heuristic_center.latitude())
546 * heuristic_factor)
547 .clamp(-90.0, 90.0),
548 exact_center.longitude()
549 + Self::difference_of_angles_degrees(exact_center.longitude(), heuristic_center.longitude())
550 * heuristic_factor,
551 WrapMode::Unwrapped,
552 );
553 let constrained = state.constrained_center(&target, state.view().zoom());
554 let zoom = state.view().zoom() + Self::zoom_adjustment(center.latitude(), constrained.latitude());
555 state.set_lat_lng_zoom(&constrained, zoom);
556 }
557
558 #[must_use]
561 pub(crate) fn zoom_adjustment(from_latitude: f64, to_latitude: f64) -> f64 {
562 (Self::planet_scale(to_latitude) / Self::planet_scale(from_latitude)).log2()
563 }
564
565 pub(crate) fn max_latitude(view: &View, zoom: f64) -> f64 {
570 let area_radians = mln_style::math::deg2rad(90.0 - LATITUDE_MAX);
571 let area_pixels =
572 Self::globe_radius_pixels(Projection::world_size(2.0f64.powf(zoom)), LATITUDE_MAX) * area_radians;
573 let size = view.size();
574 let reach_pixels = f64::from(size.width.min(size.height)) / 2.0;
575 let center_pixels = f64::min(area_pixels, reach_pixels)
576 * remap_saturate(area_pixels, reach_pixels, reach_pixels * POLE_AREA_FADE_SCALE, 1.0, 0.0);
577 LATITUDE_MAX + mln_style::math::rad2deg(area_radians * center_pixels / area_pixels)
578 }
579
580 #[must_use]
585 pub(crate) fn pan_center(view: &View, offset: &ScreenCoordinate) -> LatLng {
586 let bearing = -view.angle();
589 let x = offset.x * bearing.cos() - offset.y * bearing.sin();
590 let y = offset.x * bearing.sin() + offset.y * bearing.cos();
591
592 let center = view.center(WrapMode::Unwrapped);
593 let latitude = center.latitude();
594 let inverse_scale = |lat: f64| 1.0 / Self::planet_scale(lat);
595 let zoomed_out = ((7.0 - (view.zoom() + Self::zoom_adjustment(latitude, 0.0))) / 4.0).clamp(0.0, 1.0);
600 let longitude_speed =
601 interpolate(&inverse_scale(latitude), &inverse_scale(f64::min(latitude.abs(), 60.0)), zoomed_out);
602 let degrees_per_pixel =
603 360.0 / (2.0 * PI * Self::globe_radius_pixels(Projection::world_size(view.scale()), latitude));
604 LatLng::saturating(
605 (latitude + y * degrees_per_pixel).clamp(-90.0, 90.0),
606 center.longitude() - x * degrees_per_pixel * longitude_speed,
607 WrapMode::Unwrapped,
608 )
609 }
610
611 #[must_use]
618 pub(crate) fn drag_camera(
619 view: &View,
620 point: &ScreenCoordinate,
621 pan_delta: &ScreenCoordinate,
622 height: f64,
623 ) -> CenterAndBearing {
624 center_and_bearing(
625 turned(
626 camera_orientation(view),
627 pan_surface_vector(view, &Point::new(point.x - pan_delta.x, point.y - pan_delta.y), height),
628 pan_surface_vector(view, point, height),
629 ),
630 &view.center(WrapMode::Unwrapped),
631 )
632 }
633
634 #[must_use]
640 pub(crate) fn fling_camera(view: &View, center: &ScreenCoordinate, offset: &ScreenCoordinate) -> CenterAndBearing {
641 let lat_lng = view.center(WrapMode::Unwrapped);
642 let pixels = offset.x.hypot(offset.y);
643 if pixels == 0.0 {
644 return CenterAndBearing { center: lat_lng, bearing: -mln_style::math::rad2deg(view.angle()) };
645 }
646 let axis =
647 pan_surface_vector(view, &Point::new(center.x - offset.x / pixels, center.y - offset.y / pixels), 0.0)
648 .cross(pan_surface_vector(view, center, 0.0));
649 let degrees_per_pixel =
650 360.0 / (2.0 * PI * Self::globe_radius_pixels(Projection::world_size(view.scale()), lat_lng.latitude()));
651 center_and_bearing(
652 camera_orientation(view)
653 * rotation(axis, mln_style::math::deg2rad(f64::min(pixels * degrees_per_pixel, 179.5))),
654 &lat_lng,
655 )
656 }
657
658 #[must_use]
661 pub(crate) fn interpolate_camera(from: &CenterAndBearing, to: &CenterAndBearing, t: f64) -> CenterAndBearing {
662 center_and_bearing(
663 orientation_from_lat_lng_bearing(&from.center, from.bearing)
664 .slerp(orientation_from_lat_lng_bearing(&to.center, to.bearing), t),
665 &from.center,
666 )
667 }
668
669 #[must_use]
676 pub(crate) fn drag_center(
677 view: &View,
678 point: &ScreenCoordinate,
679 pan_delta: &ScreenCoordinate,
680 height: f64,
681 ) -> LatLng {
682 let center = view.center(WrapMode::Unwrapped);
683 let bearing = -mln_style::math::rad2deg(view.angle());
685 let swung = orientation_to_lat_lng_bearing(turned(
686 camera_orientation(view),
687 pan_surface_vector(view, &Point::new(point.x - pan_delta.x, point.y - pan_delta.y), height),
688 pan_surface_vector(view, point, height),
689 ));
690
691 let latitude = if Self::difference_of_angles_degrees(bearing, swung.bearing).abs() <= 90.0 {
694 swung.latitude
695 } else if swung.latitude > 0.0 {
696 90.0
697 } else {
698 -90.0
699 };
700
701 let pole_latitude = if center.latitude() >= 0.0 { 90.0 } else { -90.0 };
706 let (pole, _) = Self::lat_lng_to_screen_coordinate(
707 view,
708 &LatLng::saturating(pole_latitude, 0.0, WrapMode::Unwrapped),
709 height,
710 );
711 let rx = point.x - pole.x;
712 let ry = pole.y - point.y;
713 let ramp = (1.0 - (LATITUDE_MAX - center.latitude().abs()) / DIAL_RAMP_DEGREES).clamp(0.0, 1.0);
714 let dial = ramp * ramp * (3.0 - 2.0 * ramp);
715 let d_lng_swing = mln_style::math::wrap(swung.longitude - center.longitude() + 180.0, 0.0, 360.0) - 180.0;
716 let mut d_lng_dial = 0.0;
717 if dial > 0.0 {
718 let radius_squared = f64::max(rx * rx + ry * ry, DIAL_MIN_RADIUS_PIXELS * DIAL_MIN_RADIUS_PIXELS);
719 let d_theta = (rx * -pan_delta.y - ry * pan_delta.x) / radius_squared;
720 d_lng_dial = (if pole_latitude > 0.0 { 1.0 } else { -1.0 }) * mln_style::math::rad2deg(d_theta);
721 }
722 LatLng::saturating(
723 latitude,
724 center.longitude() + (1.0 - dial) * d_lng_swing + dial * d_lng_dial,
725 WrapMode::Unwrapped,
726 )
727 }
728
729 #[must_use]
747 pub(crate) fn drag_center_holding(
748 view: &View,
749 location: &LatLng,
750 point: &ScreenCoordinate,
751 height: f64,
752 ) -> Option<LatLng> {
753 let center = view.center(WrapMode::Unwrapped);
754 if center.latitude().abs() > LATITUDE_MAX - DIAL_RAMP_DEGREES
755 || !Self::screen_coordinate_hits_globe(view, point, height)
756 || pan_falloff(view, point, height).is_some()
757 {
758 return None;
759 }
760 let held = Self::center_for_location_at_point(view, location, point, height)?;
761 let gain = mln_style::math::deg2rad(location.latitude()).cos()
765 * mln_style::math::deg2rad(location.longitude() - held.longitude()).cos();
766 if gain.abs() * DRAG_HOLD_MAX_GAIN < 1.0 {
767 return None;
768 }
769 Some(LatLng::saturating(
770 held.latitude(),
771 center.longitude() + Self::difference_of_angles_degrees(center.longitude(), held.longitude()),
772 WrapMode::Unwrapped,
773 ))
774 }
775
776 #[must_use]
778 pub(crate) fn difference_of_angles_degrees(from: f64, to: f64) -> f64 {
779 let a = mln_style::math::wrap(from, 0.0, 360.0);
780 let b = mln_style::math::wrap(to, 0.0, 360.0);
781 let direct = b - a;
782 let around = if b > a { direct - 360.0 } else { direct + 360.0 };
783 if direct.abs() < around.abs() { direct } else { around }
784 }
785
786 #[must_use]
789 pub(crate) fn surface_distance_pixels(world_size: f64, center_latitude: f64, a: &LatLng, b: &LatLng) -> f64 {
790 let radians = Self::surface_vector(a).dot(Self::surface_vector(b)).clamp(-1.0, 1.0).acos();
791 radians * Self::globe_radius_pixels(world_size, center_latitude)
792 }
793
794 #[must_use]
799 pub(crate) fn interpolate_lat_lng(start: &LatLng, delta_latitude: f64, delta_longitude: f64, t: f64) -> LatLng {
800 let latitude = (start.latitude() + delta_latitude * t).clamp(-90.0, 90.0);
801 let start_latitude = start.latitude().clamp(-LATITUDE_MAX, LATITUDE_MAX);
802 let end_latitude = (start.latitude() + delta_latitude).clamp(-LATITUDE_MAX, LATITUDE_MAX);
803 if (end_latitude - start_latitude).abs() <= 1.0 {
804 return LatLng::saturating(latitude, start.longitude() + delta_longitude * t, WrapMode::Unwrapped);
805 }
806 let on_different_hemispheres = sign(end_latitude) != sign(start_latitude);
807 let sample_start = mln_style::math::deg2rad(if on_different_hemispheres {
808 -start_latitude.abs()
809 } else {
810 start_latitude.abs()
811 });
812 let sample_end = mln_style::math::deg2rad(end_latitude.abs());
813 let value_start = integrate_secant(sample_start);
814 let value_end = integrate_secant(sample_end);
815 let value_t = integrate_secant(sample_start + t * (sample_end - sample_start));
816 let longitude_t = (value_t - value_start) / (value_end - value_start);
817 LatLng::saturating(latitude, start.longitude() + delta_longitude * longitude_t, WrapMode::Unwrapped)
818 }
819}
820
821const PAN_FALLOFF_BAND: f64 = 0.1;
824const DIAL_MIN_RADIUS_PIXELS: f64 = 20.0;
825const DIAL_RAMP_DEGREES: f64 = 12.0;
826const PAN_MAX_ANGLE: f64 = PI * 0.98;
827
828const DRAG_HOLD_MAX_GAIN: f64 = 2.5;
831
832fn orientation_from_lat_lng_bearing(center: &LatLng, bearing_degrees: f64) -> DQuat {
835 DQuat::from_euler(
836 EulerRot::ZYX,
837 mln_style::math::deg2rad(bearing_degrees),
838 mln_style::math::deg2rad(-center.latitude()),
839 mln_style::math::deg2rad(-center.longitude()),
840 )
841}
842
843struct Orientation {
844 latitude: f64,
845 longitude: f64,
846 bearing: f64,
847}
848
849fn orientation_to_lat_lng_bearing(q: DQuat) -> Orientation {
852 Orientation {
853 latitude: -mln_style::math::rad2deg((2.0 * (q.w * q.y - q.z * q.x)).clamp(-1.0, 1.0).asin()),
854 longitude: -mln_style::math::rad2deg(
855 (2.0 * (q.w * q.x + q.y * q.z)).atan2(1.0 - 2.0 * (q.x * q.x + q.y * q.y)),
856 ),
857 bearing: mln_style::math::rad2deg((2.0 * (q.w * q.z + q.x * q.y)).atan2(1.0 - 2.0 * (q.y * q.y + q.z * q.z))),
858 }
859}
860
861struct PanFalloff {
864 toward_camera: DVec3,
866 distance: f64,
869 lateral: DVec3,
872 lateral_length: f64,
873 angle: f64,
876 handover_angle: f64,
877}
878
879fn pan_falloff(view: &View, point: &ScreenCoordinate, height: f64) -> Option<PanFalloff> {
883 let origin = camera_over_sphere(view, height);
884 let distance = origin.length();
885 if distance <= 1.0 {
886 return None;
887 }
888 let toward_camera = origin / distance;
889 let direction = ray_direction_from_pixel(view, point, &view.inverse_globe_view_projection_matrix());
890 let c = -direction.dot(toward_camera);
891 let lateral = direction + toward_camera * c;
892 let lateral_length = lateral.length();
893 if lateral_length < 1e-9 {
894 return None;
895 }
896 let angle = lateral_length.atan2(c);
897 let handover_angle = (1.0 / distance).asin() * (1.0 - PAN_FALLOFF_BAND);
898 (angle >= handover_angle).then_some(PanFalloff {
899 toward_camera,
900 distance,
901 lateral,
902 lateral_length,
903 angle,
904 handover_angle,
905 })
906}
907
908fn pan_surface_vector(view: &View, point: &ScreenCoordinate, height: f64) -> DVec3 {
914 let Some(PanFalloff { toward_camera: u, distance, lateral, lateral_length: s, angle, handover_angle }) =
915 pan_falloff(view, point, height)
916 else {
917 return VerticalPerspectiveProjection::screen_coordinate_to_surface(view, point, height);
918 };
919 let sin_handover = distance * handover_angle.sin();
920 let target_at_handover = sin_handover.clamp(-1.0, 1.0).asin() - handover_angle;
921 let slope_at_handover =
922 distance * handover_angle.cos() / f64::max(1.0 - sin_handover * sin_handover, 1e-12).sqrt() - 1.0;
923 let room = PAN_MAX_ANGLE - target_at_handover;
924 let excess = angle - handover_angle;
925 let target = (target_at_handover + room * (slope_at_handover * excess) / (room + slope_at_handover * excess))
926 .clamp(0.0, PAN_MAX_ANGLE);
927 (u * target.cos() + lateral * (target.sin() / s)).normalize()
928}
929
930fn camera_over_sphere(view: &View, height: f64) -> DVec3 {
934 view.globe_camera_position() / (1.0 + height / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS)
935}
936
937fn camera_orientation(view: &View) -> DQuat {
940 orientation_from_lat_lng_bearing(&view.center(WrapMode::Unwrapped), -mln_style::math::rad2deg(view.angle()))
941}
942
943fn rotation(axis: DVec3, angle: f64) -> DQuat {
947 let l = axis.length();
948 if l == 0.0 {
949 return DQuat::IDENTITY;
950 }
951 let s = (angle / 2.0).sin();
952 DQuat::from_xyzw(axis.y / l * s, -axis.x / l * s, axis.z / l * s, (angle / 2.0).cos())
953}
954
955fn turned(orientation: DQuat, from: DVec3, to: DVec3) -> DQuat {
958 orientation * rotation(from.cross(to), from.dot(to).clamp(-1.0, 1.0).acos())
959}
960
961fn slerp_vec3(a: DVec3, b: DVec3, t: f64) -> DVec3 {
964 let angle = a.dot(b).clamp(-1.0, 1.0).acos();
965 if angle.sin() < 1e-9 {
966 return a;
967 }
968 a * (((1.0 - t) * angle).sin() / angle.sin()) + b * ((t * angle).sin() / angle.sin())
969}
970
971fn center_and_bearing(orientation: DQuat, center: &LatLng) -> CenterAndBearing {
974 let o = orientation_to_lat_lng_bearing(orientation);
975 CenterAndBearing {
976 center: LatLng::saturating(
977 o.latitude,
978 center.longitude()
979 + VerticalPerspectiveProjection::difference_of_angles_degrees(center.longitude(), o.longitude),
980 WrapMode::Unwrapped,
981 ),
982 bearing: o.bearing,
983 }
984}
985
986fn zoom_turning_the_planet(
994 state: &mut TransformState,
995 anchor: &ScreenCoordinate,
996 zoom_location: &LatLng,
997 height: f64,
998 factor: f64,
999 interpolation_factor_horizon: f64,
1000) {
1001 let center = state.view().center(WrapMode::Unwrapped);
1002 let orientation = camera_orientation(state.view());
1003 let location = VerticalPerspectiveProjection::surface_vector(zoom_location);
1004 let center_vector = VerticalPerspectiveProjection::surface_vector(¢er);
1005 let exact = turned(orientation, location, pan_surface_vector(state.view(), anchor, height));
1006 let heuristic = turned(orientation, slerp_vec3(center_vector, location, factor), center_vector);
1007 let camera = center_and_bearing(
1008 exact.slerp(heuristic, interpolation_factor_horizon.powf(INTERPOLATE_TO_HEURISTIC_EXPONENT)),
1009 ¢er,
1010 );
1011 let constrained = state.constrained_center(&camera.center, state.view().zoom());
1012 let zoom =
1013 state.view().zoom() + VerticalPerspectiveProjection::zoom_adjustment(center.latitude(), constrained.latitude());
1014 state.set_lat_lng_zoom(&constrained, zoom);
1015 state.set_angle(-mln_style::math::deg2rad(camera.bearing));
1016}
1017
1018impl VerticalPerspectiveProjection {
1019 pub(crate) fn projection_data(view: &View, tile_id: &UnwrappedTileID, mercator_matrix: &DMat4) -> ProjectionData {
1021 let middle = Point::new(f64::from(EXTENT) / 2.0, f64::from(EXTENT) / 2.0);
1023 ProjectionData {
1024 sphere_anchor: Self::tile_coordinates_to_sphere(&middle, tile_id),
1025 sphere_anchor_angles: Self::tile_coordinates_to_angles(&middle, tile_id),
1026 main_matrix: view.globe_view_projection_matrix(),
1027 tile_mercator_coords: mercator_tile_coords(tile_id),
1028 clipping_plane: view.globe_clipping_plane(),
1029 projection_transition: view.projection_transition(),
1030 fallback_matrix: *mercator_matrix,
1031 camera_position: view.globe_camera_position(),
1032 ..ProjectionData::default()
1033 }
1034 }
1035
1036 pub(crate) fn project_tile_point(
1038 data: &ProjectionData,
1039 tile_id: &UnwrappedTileID,
1040 point: &Point<f64>,
1041 elevation: f64,
1042 ) -> ProjectedTilePoint {
1043 let surface = Self::tile_coordinates_to_sphere(point, tile_id);
1044 let height_scale = 1.0 + elevation / Self::GLOBE_RADIUS_METERS;
1045 let sphere = surface * height_scale;
1046 let pos = data.main_matrix * sphere.extend(1.0);
1047 let occluded = if height_scale <= 1.0 {
1050 point_plane_signed_distance(data.clipping_plane, surface) < 0.0
1051 } else {
1052 line_of_sight_blocked(data.camera_position, sphere)
1053 };
1054 ProjectedTilePoint {
1055 point: Point::new(pos.x / pos.w, pos.y / pos.w),
1056 signed_distance_from_camera: pos.w,
1057 occluded,
1058 }
1059 }
1060
1061 pub(crate) fn drawn_tile_point(
1063 data: &ProjectionData,
1064 tile_id: &UnwrappedTileID,
1065 point: &Point<f64>,
1066 elevation: f64,
1067 ) -> ProjectedTilePoint {
1068 let globe = Self::project_tile_point(data, tile_id, point, elevation);
1069 let t = data.projection_transition;
1070 if t > 0.999 {
1071 return globe;
1072 }
1073 let flat = data.fallback_matrix * DVec4::new(point.x, point.y, elevation, 1.0);
1078 let globe_w = globe.signed_distance_from_camera;
1079 let w = interpolate(&flat.w, &globe_w, t);
1080 let globeness = ((t - 0.2) / 0.8).clamp(0.0, 1.0);
1081 let mut occluded = globeness > 0.0 && globe.occluded;
1082 if elevation <= 0.0 {
1083 let surface = Self::tile_coordinates_to_sphere(point, tile_id);
1084 let clipping_z = 1.0 - point_plane_signed_distance(data.clipping_plane, surface);
1085 occluded = globeness * clipping_z * globe_w > w;
1086 }
1087 ProjectedTilePoint {
1088 point: Point::new(
1089 interpolate(&flat.x, &(globe.point.x * globe_w), t) / w,
1090 interpolate(&flat.y, &(globe.point.y * globe_w), t) / w,
1091 ),
1092 signed_distance_from_camera: w,
1093 occluded,
1094 }
1095 }
1096
1097 pub(crate) fn map_aligned_scale(view: &View) -> f64 {
1099 Self::planet_scale(view.center(WrapMode::Unwrapped).latitude())
1100 }
1101
1102 pub(crate) fn pixel_scale(view: &View) -> f64 {
1104 interpolate(
1105 &1.0,
1106 &(1.0 / Self::planet_scale(view.center(WrapMode::Unwrapped).latitude())),
1107 view.projection_transition(),
1108 )
1109 }
1110
1111 pub(crate) fn map_aligned_scale_at(view: &View, tile_anchor: &Point<f64>, tile_id: &UnwrappedTileID) -> f64 {
1113 let scale = 1.0 / (1u64 << tile_id.canonical.z) as f64;
1114 let mercator_y = tile_anchor.y / f64::from(EXTENT) * scale + f64::from(tile_id.canonical.y) * scale;
1115 let latitude = 2.0 * (PI - (mercator_y * PI * 2.0)).exp().atan() - PI * 0.5;
1116 interpolate(
1117 &1.0,
1118 &(Self::planet_scale(view.center(WrapMode::Unwrapped).latitude()) / latitude.cos()),
1119 view.projection_transition(),
1120 )
1121 }
1122}