Skip to main content

mln_engine/camera/
vertical_perspective_projection.rs

1use std::f64::consts::PI;
2
3use geometry::Point;
4use glam::dcamera::rh::proj::opengl::perspective;
5use glam::{DMat3, DMat4, DQuat, DVec3, DVec4, EulerRot, Vec3Swizzles, Vec4Swizzles};
6use mln_style::constants::{EXTENT, LATITUDE_MAX, TILE_SIZE_D};
7use mln_style::geo::{LatLng, WrapMode};
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
17/// How far from the polar axis a unit-sphere point can be and still be on its
18/// pole, with no longitude of its own: GL JS
19/// `sphereSurfacePointToCoordinates` gives it longitude 0.
20const POLE_AXIS_DISTANCE: f64 = 1e-6;
21
22fn rotate_x(v: DVec3, rad: f64) -> DVec3 {
23    DMat3::from_rotation_x(rad) * v
24}
25
26fn rotate_y(v: DVec3, rad: f64) -> DVec3 {
27    DMat3::from_rotation_y(rad) * v
28}
29
30fn rotate_z(v: DVec3, rad: f64) -> DVec3 {
31    DMat3::from_rotation_z(rad) * v
32}
33
34/// GL JS `VerticalPerspectiveTransform._isLineOfSightBlocked`: whether the
35/// planet stands between the camera and a point, both on the unit sphere's
36/// scale.
37fn line_of_sight_blocked(camera: DVec3, point: DVec3) -> bool {
38    let to_point = point - camera;
39    let length_sq = to_point.length_squared();
40    if length_sq == 0.0 {
41        return false;
42    }
43    let t = (-camera.dot(to_point) / length_sq).clamp(0.0, 1.0);
44    (camera + to_point * t).length_squared() < 1.0
45}
46
47/// The distance along a ray to where it first meets the unit sphere at the
48/// origin, by GL JS's numerically stable `raySphereIntersection`.
49fn ray_sphere_intersection(origin: DVec3, direction: DVec3) -> Option<f64> {
50    let origin_dot_direction = origin.dot(direction);
51    let inner = origin - direction * origin_dot_direction;
52    let discriminant = 1.0 - inner.length_squared();
53    // A NaN ray, from a NaN point, hits nothing.
54    if discriminant.is_nan() || discriminant < 0.0 {
55        return None;
56    }
57    let c = origin.length_squared() - 1.0;
58    let q = -origin_dot_direction + (if origin_dot_direction < 0.0 { 1.0 } else { -1.0 }) * discriminant.sqrt();
59    let t0 = c / q;
60    let t1 = q;
61    // Both behind the ray's origin, as for a ray into the sky past a nearby
62    // planet: no intersection.
63    if f64::max(t0, t1) < 0.0 {
64        return None;
65    }
66    Some(f64::min(t0, t1))
67}
68
69fn point_plane_signed_distance(plane: DVec4, point: DVec3) -> f64 {
70    plane.dot(point.extend(1.0))
71}
72
73fn ray_direction_from_pixel(view: &View, point: &ScreenCoordinate, inverse_view_projection: &DMat4) -> DVec3 {
74    let size = view.size();
75    let clip =
76        DVec3::new(point.x / f64::from(size.width) * 2.0 - 1.0, point.y / f64::from(size.height) * 2.0 - 1.0, 1.0);
77    (inverse_view_projection.project_point3(clip) - view.globe_camera_position()).normalize()
78}
79
80/// Angle to rotate the vector (x0, y0) onto the direction of (x1, y1).
81fn angle_to_rotate_between_vectors_2d(mut x0: f64, mut y0: f64, mut x1: f64, mut y1: f64) -> f64 {
82    let len0 = (x0 * x0 + y0 * y0).sqrt();
83    let len1 = (x1 * x1 + y1 * y1).sqrt();
84    x0 /= len0;
85    y0 /= len0;
86    x1 /= len1;
87    y1 /= len1;
88    let cross = x0 * y1 - x1 * y0;
89    let angle = (x0 * x1 + y0 * y1).clamp(-1.0, 1.0).acos();
90    if cross > 0.0 { angle } else { -angle }
91}
92
93fn distance_of_angles_radians(a: f64, b: f64) -> f64 {
94    let two_pi = 2.0 * PI;
95    // `%` on floats is C fmod.
96    let d = ((a - b) % two_pi + two_pi) % two_pi;
97    f64::min(d, two_pi - d)
98}
99
100/// The integral of 1 / cos(x): where the longitude gets to when the globe
101/// turns at a steady rate.
102fn integrate_secant(x: f64) -> f64 {
103    let half = 0.5 * x;
104    let sin = half.sin();
105    let cos = half.cos();
106    (sin + cos).ln() - (cos - sin).ln()
107}
108
109fn sign(value: f64) -> i32 {
110    i32::from(value > 0.0) - i32::from(value < 0.0)
111}
112
113/// The globe: tile geometry projected onto a unit sphere, viewed with a
114/// vertical perspective camera. Port of MapLibre GL JS
115/// `vertical_perspective_transform.ts`.
116#[derive(Clone, Copy, Debug, Default)]
117pub struct VerticalPerspectiveProjection;
118
119#[derive(Clone, Copy, Debug, PartialEq)]
120pub struct CenterAndBearing {
121    pub(crate) center: LatLng,
122    /// In degrees, with `CameraOptions`'s sign.
123    pub(crate) bearing: f64,
124}
125
126// GL JS vertical_perspective_camera_helper constants.
127const 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;
137// GL JS vertical_perspective_transform: how many times the view the area past
138// the Mercator range has grown to when the center is back on its edge.
139const 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    /// GL JS `earthRadius`, `GLOBE_RADIUS` in the shaders: the meters an
148    /// elevation is measured against.
149    pub const GLOBE_RADIUS_METERS: f64 = 6_371_008.8;
150
151    /// Globe radius in pixels at the given world size and center latitude, so
152    /// zoom means the same on both projections.
153    #[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    /// GL JS `planetScaleAtLatitude`: the cosine of the center latitude the
159    /// globe radius is divided by. Mercator ends at the edge of its range, so
160    /// past it the globe keeps its size there.
161    #[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    /// The unit-sphere position of a point in tile units.
167    #[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    /// The sine and cosine of the longitude, then of the latitude, of a point
174    /// in tile units. The longitude is 0 at the antimeridian, where Web
175    /// Mercator's X is 0, so the prime meridian is +Z.
176    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        // sin/cos of the latitude from the Mercator Y through the tangent
182        // half-angle identities, as the shaders do.
183        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    /// The center's distance from the planet's center, in radii: the camera
189    /// looks at the center raised by its altitude along its vertical, as the
190    /// globe raises any height.
191    fn center_radius(view: &View) -> f64 {
192        1.0 + view.center_altitude() / Self::GLOBE_RADIUS_METERS
193    }
194
195    /// The view-projection matrix that takes unit-sphere positions to clip
196    /// space. It draws the center, at its altitude, at the center of the
197    /// padded view. Its near plane is half a pixel from the eye, or the
198    /// terrain's ([`View::near_z`]) while terrain draws.
199    #[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        // Move the vanishing point to the center of the padded view.
214        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    /// The plane (as ax + by + cz + d) that separates the part of the
234    /// sea-level sphere the camera sees from the back of the globe.
235    #[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    /// Camera position in unit-sphere space, back from the center at its
257    /// altitude.
258    #[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    /// The location of a unit-sphere point, or `None` for a point that isn't
279    /// a number, as a degenerate camera's can be.
280    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    /// The Web Mercator point at zoom 0 under the unit-sphere point `point`,
292    /// in the world copy nearest the view's center, and its height in meters
293    /// above the sea-level sphere; `None` for a point that isn't a number.
294    /// Over the polar caps, past the latitudes that Web Mercator's square
295    /// holds, y is past 0 or 1, and at the poles infinite or far past.
296    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    /// The direction from the planet's center, as a unit-sphere point, of
304    /// where the ray through a screen pixel (y up, as `TransformState` takes
305    /// it) meets the sphere `height` meters above sea level; pixels off that
306    /// sphere snap to the nearest point on its horizon. It solves on the unit
307    /// sphere with the camera scaled by 1 / (1 + height / R), which at
308    /// height 0 is the sea-level sphere's math to the bit.
309    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        // The ray misses the sphere: take the nearest point on the horizon,
318        // the circle where the clipping plane cuts it.
319        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    /// Whether a screen pixel (y up) looks at the sphere `height` meters
343    /// above sea level rather than past it, from a camera outside it.
344    #[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    /// The location under a screen pixel (y up) on the sphere `height`
351    /// meters above sea level ([`Self::screen_coordinate_to_surface`]).
352    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    /// The screen point (y up) of a location `height` meters above sea level
363    /// on the globe, raised along its vertical, and its clip-space position.
364    #[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    /// The center that puts `lat_lng`, on the sphere `height` meters above
381    /// sea level, under `anchor` with the bearing unchanged, if one exists.
382    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        // GL JS `setLocationAtPoint`: solve the rotation that carries the
389        // surface point under the pixel onto the target. Turning the planet
390        // carries every sphere about its center with it, so the solve takes
391        // the direction of the point under the pixel on the sphere at
392        // `height`.
393        const LIMIT: f64 = PI * 0.5;
394        let center = view.center(WrapMode::Unwrapped);
395        let vec_to_pixel_current = Self::screen_coordinate_to_surface(view, anchor, height);
396        let vec_to_target = Self::surface_vector(lat_lng);
397
398        let rotated_pixel_vector = rotate_x(
399            rotate_y(vec_to_pixel_current, -mln_style::math::deg2rad(center.longitude())),
400            mln_style::math::deg2rad(center.latitude()),
401        );
402
403        let vec_to_target_xz_length_squared = vec_to_target.xz().length_squared();
404        let target_x_squared = rotated_pixel_vector.x * rotated_pixel_vector.x;
405        if vec_to_target_xz_length_squared < target_x_squared {
406            return None;
407        }
408
409        let intersection_a = (vec_to_target_xz_length_squared - target_x_squared).sqrt();
410        let intersection_b = -intersection_a;
411
412        let solve = |intersection: f64| {
413            let lng = angle_to_rotate_between_vectors_2d(
414                vec_to_target.x,
415                vec_to_target.z,
416                rotated_pixel_vector.x,
417                intersection,
418            );
419            let vec_to_target_lng = rotate_y(vec_to_target, -lng);
420            let lat = angle_to_rotate_between_vectors_2d(
421                vec_to_target_lng.y,
422                vec_to_target_lng.z,
423                rotated_pixel_vector.y,
424                rotated_pixel_vector.z,
425            );
426            (lng, lat)
427        };
428        let (lng_a, lat_a) = solve(intersection_a);
429        let (lng_b, lat_b) = solve(intersection_b);
430
431        let valid_a = (-LIMIT..=LIMIT).contains(&lat_a);
432        let valid_b = (-LIMIT..=LIMIT).contains(&lat_b);
433
434        let (lng, lat) = if valid_a && valid_b {
435            let center_lng = mln_style::math::deg2rad(center.longitude());
436            let center_lat = mln_style::math::deg2rad(center.latitude());
437            let distance_a =
438                distance_of_angles_radians(lng_a, center_lng) + distance_of_angles_radians(lat_a, center_lat);
439            let distance_b =
440                distance_of_angles_radians(lng_b, center_lng) + distance_of_angles_radians(lat_b, center_lat);
441            if distance_a < distance_b { (lng_a, lat_a) } else { (lng_b, lat_b) }
442        } else if valid_a {
443            (lng_a, lat_a)
444        } else if valid_b {
445            (lng_b, lat_b)
446        } else {
447            return None;
448        };
449        Some(LatLng::saturating(
450            (mln_style::math::rad2deg(lat)).clamp(-90.0, 90.0),
451            mln_style::math::rad2deg(lng),
452            WrapMode::Unwrapped,
453        ))
454    }
455
456    /// GL JS `handleMapControlsRollPitchBearingZoom`: after the zoom changed
457    /// by `zoom_delta`, move the center so that `zoom_location` stays under
458    /// `anchor`, exactly where that is well posed and by a damped heuristic
459    /// near the horizon, where a pixel is worth degrees of arc and the exact
460    /// solution jumps or does not exist. With `free_bearing` the planet turns
461    /// as one body instead and the bearing follows it, so near a pole, where
462    /// the longitude of the center swings, the view does not spin: the exact
463    /// part is the rotation that brings `zoom_location` back under `anchor`,
464    /// the heuristic part moves the center along the great circle towards
465    /// it. `zoom_location` stands on the sphere `height` meters above sea
466    /// level, which the exact part solves on.
467    pub(crate) fn zoom_around_point(
468        state: &mut TransformState,
469        anchor: &ScreenCoordinate,
470        zoom_location: &LatLng,
471        height: f64,
472        zoom_delta: f64,
473        free_bearing: bool,
474    ) {
475        if zoom_delta == 0.0 {
476            return;
477        }
478        let center = state.view().center(WrapMode::Unwrapped);
479        // A location on a pole has no longitude of its own, so the zoom keeps
480        // the center's meridian rather than turning the planet about the pole
481        // towards the longitude the location was given.
482        let on_pole = mln_style::math::deg2rad(zoom_location.latitude()).cos() <= POLE_AXIS_DISTANCE;
483        let d_lng_raw = if on_pole {
484            0.0
485        } else {
486            Self::difference_of_angles_degrees(center.longitude(), zoom_location.longitude())
487        };
488        let d_lng = d_lng_raw / ((d_lng_raw / 180.0).abs() + 1.0);
489        let d_lat = Self::difference_of_angles_degrees(center.latitude(), zoom_location.latitude());
490
491        // Slow the movement down when the anchor's ray passes far from the
492        // planet.
493        let ray_origin = camera_over_sphere(state.view(), height);
494        let ray_direction =
495            ray_direction_from_pixel(state.view(), anchor, &state.view().inverse_globe_view_projection_matrix());
496        let closest_point = ray_origin - ray_direction * ray_origin.dot(ray_direction);
497        let ray_distance_from_globe_center = closest_point.length();
498        let distance_factor =
499            (-f64::max(ray_distance_from_globe_center - 1.0 - RAY_SURFACE_DISTANCE_FOR_SLOWING_START, 0.0)
500                * SLOWING_MULTIPLIER)
501                .exp();
502        let interpolation_factor_horizon = remap_saturate(
503            ray_distance_from_globe_center,
504            INTERPOLATE_TO_HEURISTIC_START_HORIZON,
505            INTERPOLATE_TO_HEURISTIC_END_HORIZON,
506            0.0,
507            1.0,
508        );
509
510        // And when the globe is small on the viewport, where that is a
511        // stand-in for the anchor being near the horizon.
512        let size = state.view().size();
513        let radius = Self::globe_radius_pixels(Projection::world_size(state.view().scale()), center.latitude())
514            / f64::from(size.width.min(size.height));
515        let radius_factor =
516            remap_saturate(radius, SLOWING_RADIUS_START, SLOWING_RADIUS_STOP, 1.0, SLOWING_RADIUS_SLOW_FACTOR);
517        let slowing_factor = f64::min(distance_factor, 1.0 + (radius_factor - 1.0) * interpolation_factor_horizon);
518
519        let factor = (1.0 - 2.0f64.powf(-zoom_delta)) * slowing_factor;
520        if free_bearing {
521            zoom_turning_the_planet(state, anchor, zoom_location, height, factor, interpolation_factor_horizon);
522            return;
523        }
524        let heuristic_center = LatLng::saturating(
525            (center.latitude() + d_lat * factor).clamp(-90.0, 90.0),
526            center.longitude() + d_lng * factor,
527            WrapMode::Unwrapped,
528        );
529
530        let mut exact_center =
531            Self::center_for_location_at_point(state.view(), zoom_location, anchor, height).unwrap_or(center);
532        if on_pole {
533            exact_center = LatLng::saturating(exact_center.latitude(), center.longitude(), WrapMode::Unwrapped);
534        }
535
536        let interpolation_factor_longitude = remap_saturate(
537            d_lng_raw.abs(),
538            INTERPOLATE_TO_HEURISTIC_START_LNG,
539            INTERPOLATE_TO_HEURISTIC_END_LNG,
540            0.0,
541            1.0,
542        );
543        let heuristic_factor = f64::max(interpolation_factor_longitude, interpolation_factor_horizon)
544            .powf(INTERPOLATE_TO_HEURISTIC_EXPONENT);
545        let target = LatLng::saturating(
546            (exact_center.latitude()
547                + Self::difference_of_angles_degrees(exact_center.latitude(), heuristic_center.latitude())
548                    * heuristic_factor)
549                .clamp(-90.0, 90.0),
550            exact_center.longitude()
551                + Self::difference_of_angles_degrees(exact_center.longitude(), heuristic_center.longitude())
552                    * heuristic_factor,
553            WrapMode::Unwrapped,
554        );
555        let constrained = state.constrained_center(&target, state.view().zoom());
556        let zoom = state.view().zoom() + Self::zoom_adjustment(center.latitude(), constrained.latitude());
557        state.set_lat_lng_zoom(&constrained, zoom);
558    }
559
560    /// Zoom change that keeps the globe the same apparent size when the
561    /// center moves between latitudes.
562    #[must_use]
563    pub(crate) fn zoom_adjustment(from_latitude: f64, to_latitude: f64) -> f64 {
564        (Self::planet_scale(to_latitude) / Self::planet_scale(from_latitude)).log2()
565    }
566
567    /// GL JS `_getMaxLatitude`: how close to a pole the center can be at the
568    /// given zoom. Past the Mercator range there are no tiles, so the center
569    /// reaches the pole only while that area fits in the view, and eases back
570    /// to the edge of the range as the area outgrows the view.
571    pub(crate) fn max_latitude(view: &View, zoom: f64) -> f64 {
572        let area_radians = mln_style::math::deg2rad(90.0 - LATITUDE_MAX);
573        let area_pixels =
574            Self::globe_radius_pixels(Projection::world_size(2.0f64.powf(zoom)), LATITUDE_MAX) * area_radians;
575        let size = view.size();
576        let reach_pixels = f64::from(size.width.min(size.height)) / 2.0;
577        let center_pixels = f64::min(area_pixels, reach_pixels)
578            * remap_saturate(area_pixels, reach_pixels, reach_pixels * POLE_AREA_FADE_SCALE, 1.0, 0.0);
579        LATITUDE_MAX + mln_style::math::rad2deg(area_radians * center_pixels / area_pixels)
580    }
581
582    /// GL JS `computeGlobePanCenter`: the center after a pan of `offset`
583    /// pixels, turning the planet by degrees per pixel at the center's
584    /// latitude. The longitude is unwrapped and the latitude clamped to the
585    /// poles.
586    #[must_use]
587    pub(crate) fn pan_center(view: &View, offset: &ScreenCoordinate) -> LatLng {
588        // GL JS turns the pan by its bearing, which is the view's angle with the
589        // sign flipped.
590        let bearing = -view.angle();
591        let x = offset.x * bearing.cos() - offset.y * bearing.sin();
592        let y = offset.x * bearing.sin() + offset.y * bearing.cos();
593
594        let center = view.center(WrapMode::Unwrapped);
595        let latitude = center.latitude();
596        let inverse_scale = |lat: f64| 1.0 / Self::planet_scale(lat);
597        // Longitude speeds up towards the poles, where the planet is
598        // narrower, but as the globe zooms out from 7 to 3 the latitude it
599        // speeds up for is capped at 60°: GL JS's numbers.
600        let zoomed_out = ((7.0 - (view.zoom() + Self::zoom_adjustment(latitude, 0.0))) / 4.0).clamp(0.0, 1.0);
601        let longitude_speed =
602            interpolate(&inverse_scale(latitude), &inverse_scale(f64::min(latitude.abs(), 60.0)), zoomed_out);
603        let degrees_per_pixel =
604            360.0 / (2.0 * PI * Self::globe_radius_pixels(Projection::world_size(view.scale()), latitude));
605        LatLng::saturating(
606            (latitude + y * degrees_per_pixel).clamp(-90.0, 90.0),
607            center.longitude() - x * degrees_per_pixel * longitude_speed,
608            WrapMode::Unwrapped,
609        )
610    }
611
612    /// GL JS `versorSetLocationAtPoint` without the fixed bearing: the whole
613    /// rotation that brings the location under `point - pan_delta` under
614    /// `point` (both y up), so the grabbed location tracks the cursor exactly
615    /// and the bearing turns with the planet, over the poles too. The
616    /// location is on the sphere `height` meters above sea level. The
617    /// longitude stays unwrapped around the current center, the latitude is
618    /// not yet constrained.
619    #[must_use]
620    pub(crate) fn drag_camera(
621        view: &View,
622        point: &ScreenCoordinate,
623        pan_delta: &ScreenCoordinate,
624        height: f64,
625    ) -> CenterAndBearing {
626        center_and_bearing(
627            turned(
628                camera_orientation(view),
629                pan_surface_vector(view, &Point::new(point.x - pan_delta.x, point.y - pan_delta.y), height),
630                pan_surface_vector(view, point, height),
631            ),
632            &view.center(WrapMode::Unwrapped),
633        )
634    }
635
636    /// Where a fling of `offset` pixels (y up) ends with the bearing free:
637    /// the planet turns about the axis a drag in that direction at `center`
638    /// (y up) turns it about, by GL JS's degrees per pixel at the center's
639    /// latitude and short of half a turn, the orientation carried along. Its
640    /// axis is the sea-level sphere's, as its pace is.
641    #[must_use]
642    pub(crate) fn fling_camera(view: &View, center: &ScreenCoordinate, offset: &ScreenCoordinate) -> CenterAndBearing {
643        let lat_lng = view.center(WrapMode::Unwrapped);
644        let pixels = offset.x.hypot(offset.y);
645        if pixels == 0.0 {
646            return CenterAndBearing { center: lat_lng, bearing: -mln_style::math::rad2deg(view.angle()) };
647        }
648        let axis =
649            pan_surface_vector(view, &Point::new(center.x - offset.x / pixels, center.y - offset.y / pixels), 0.0)
650                .cross(pan_surface_vector(view, center, 0.0));
651        let degrees_per_pixel =
652            360.0 / (2.0 * PI * Self::globe_radius_pixels(Projection::world_size(view.scale()), lat_lng.latitude()));
653        center_and_bearing(
654            camera_orientation(view)
655                * rotation(axis, mln_style::math::deg2rad(f64::min(pixels * degrees_per_pixel, 179.5))),
656            &lat_lng,
657        )
658    }
659
660    /// The camera `t` of the way from one camera to another, the planet
661    /// turning about one axis.
662    #[must_use]
663    pub(crate) fn interpolate_camera(from: &CenterAndBearing, to: &CenterAndBearing, t: f64) -> CenterAndBearing {
664        center_and_bearing(
665            orientation_from_lat_lng_bearing(&from.center, from.bearing)
666                .slerp(orientation_from_lat_lng_bearing(&to.center, to.bearing), t),
667            &from.center,
668        )
669    }
670
671    /// GL JS `versorSetLocationAtPoint` with the bearing held, as a drag uses
672    /// it: the center after the one rotation that brings the location under
673    /// `point - pan_delta` back under `point` (both y up), on the sphere
674    /// `height` meters above sea level. Within 12 degrees of the pole's edge
675    /// the cursor turns a dial around the pole, and a swing over a pole stops
676    /// on it. The longitude stays unwrapped around the current center, the
677    /// latitude is not yet constrained.
678    #[must_use]
679    pub(crate) fn drag_center(
680        view: &View,
681        point: &ScreenCoordinate,
682        pan_delta: &ScreenCoordinate,
683        height: f64,
684    ) -> LatLng {
685        let center = view.center(WrapMode::Unwrapped);
686        // GL JS's bearing is the view's angle with the sign flipped.
687        let bearing = -mln_style::math::rad2deg(view.angle());
688        let swung = orientation_to_lat_lng_bearing(turned(
689            camera_orientation(view),
690            pan_surface_vector(view, &Point::new(point.x - pan_delta.x, point.y - pan_delta.y), height),
691            pan_surface_vector(view, point, height),
692        ));
693
694        // A swing over a pole turns the bearing around; with the bearing held,
695        // the center stops on that pole.
696        let latitude = if Self::difference_of_angles_degrees(bearing, swung.bearing).abs() <= 90.0 {
697            swung.latitude
698        } else if swung.latitude > 0.0 {
699            90.0
700        } else {
701            -90.0
702        };
703
704        // The swing's longitude is ill-conditioned near the pole, so within
705        // the last 12 degrees before the pole's edge the cursor turns a dial
706        // around the pole instead, blended in with a smoothstep and in full
707        // from the edge on. GL JS takes the sweep from the screen with y down.
708        let pole_latitude = if center.latitude() >= 0.0 { 90.0 } else { -90.0 };
709        let (pole, _) = Self::lat_lng_to_screen_coordinate(
710            view,
711            &LatLng::saturating(pole_latitude, 0.0, WrapMode::Unwrapped),
712            height,
713        );
714        let rx = point.x - pole.x;
715        let ry = pole.y - point.y;
716        let ramp = (1.0 - (LATITUDE_MAX - center.latitude().abs()) / DIAL_RAMP_DEGREES).clamp(0.0, 1.0);
717        let dial = ramp * ramp * (3.0 - 2.0 * ramp);
718        let d_lng_swing = mln_style::math::wrap(swung.longitude - center.longitude() + 180.0, 0.0, 360.0) - 180.0;
719        let mut d_lng_dial = 0.0;
720        if dial > 0.0 {
721            let radius_squared = f64::max(rx * rx + ry * ry, DIAL_MIN_RADIUS_PIXELS * DIAL_MIN_RADIUS_PIXELS);
722            let d_theta = (rx * -pan_delta.y - ry * pan_delta.x) / radius_squared;
723            d_lng_dial = (if pole_latitude > 0.0 { 1.0 } else { -1.0 }) * mln_style::math::rad2deg(d_theta);
724        }
725        LatLng::saturating(
726            latitude,
727            center.longitude() + (1.0 - dial) * d_lng_swing + dial * d_lng_dial,
728            WrapMode::Unwrapped,
729        )
730    }
731
732    /// The center that puts `location`, on the sphere `height` meters above
733    /// sea level, under `point` (y up) with the bearing held, where a drag
734    /// can hold a location exactly. Elsewhere `None`, and
735    /// [`Self::drag_center`] makes the step:
736    ///
737    /// - `point` is off the planet, or in the band at its edge where the
738    ///   drag eases off;
739    /// - the center is where the cursor turns the dial around a pole;
740    /// - no center puts `location` there, or the one that does turns more
741    ///   than `DRAG_HOLD_MAX_GAIN` times as far as the cursor moves, as for
742    ///   a location near a pole or a quarter turn of longitude from the
743    ///   center.
744    ///
745    /// The planet keeps its size on screen as the center changes latitude
746    /// ([`Self::zoom_adjustment`]), so the center holds `location` at the
747    /// adjusted zoom. The longitude stays unwrapped around the current
748    /// center, the latitude is not yet constrained.
749    #[must_use]
750    pub(crate) fn drag_center_holding(
751        view: &View,
752        location: &LatLng,
753        point: &ScreenCoordinate,
754        height: f64,
755    ) -> Option<LatLng> {
756        let center = view.center(WrapMode::Unwrapped);
757        if center.latitude().abs() > LATITUDE_MAX - DIAL_RAMP_DEGREES
758            || !Self::screen_coordinate_hits_globe(view, point, height)
759            || pan_falloff(view, point, height).is_some()
760        {
761            return None;
762        }
763        let held = Self::center_for_location_at_point(view, location, point, height)?;
764        // A pixel of cursor travel turns the center 1 / (cos(latitude) *
765        // cos(longitude from the center)) times as far as it does for a
766        // location at the center.
767        let gain = mln_style::math::deg2rad(location.latitude()).cos()
768            * mln_style::math::deg2rad(location.longitude() - held.longitude()).cos();
769        if gain.abs() * DRAG_HOLD_MAX_GAIN < 1.0 {
770            return None;
771        }
772        Some(LatLng::saturating(
773            held.latitude(),
774            center.longitude() + Self::difference_of_angles_degrees(center.longitude(), held.longitude()),
775            WrapMode::Unwrapped,
776        ))
777    }
778
779    /// The shorter signed way around from one angle to the other, in degrees.
780    #[must_use]
781    pub(crate) fn difference_of_angles_degrees(from: f64, to: f64) -> f64 {
782        let a = mln_style::math::wrap(from, 0.0, 360.0);
783        let b = mln_style::math::wrap(to, 0.0, 360.0);
784        let direct = b - a;
785        let around = if b > a { direct - 360.0 } else { direct + 360.0 };
786        if direct.abs() < around.abs() { direct } else { around }
787    }
788
789    /// Distance between two locations along the surface, in pixels at the
790    /// given world size and center latitude.
791    #[must_use]
792    pub(crate) fn surface_distance_pixels(world_size: f64, center_latitude: f64, a: &LatLng, b: &LatLng) -> f64 {
793        let radians = Self::surface_vector(a).dot(Self::surface_vector(b)).clamp(-1.0, 1.0).acos();
794        radians * Self::globe_radius_pixels(world_size, center_latitude)
795    }
796
797    /// The location `t` of the way from `start` to `start + delta`, the
798    /// longitude paced at 1 / cos(latitude) so the globe appears to turn at a
799    /// steady rate. The pace grows without bound towards the poles, so past
800    /// the Mercator range it keeps its value at the edge.
801    #[must_use]
802    pub(crate) fn interpolate_lat_lng(start: &LatLng, delta_latitude: f64, delta_longitude: f64, t: f64) -> LatLng {
803        let latitude = (start.latitude() + delta_latitude * t).clamp(-90.0, 90.0);
804        let start_latitude = start.latitude().clamp(-LATITUDE_MAX, LATITUDE_MAX);
805        let end_latitude = (start.latitude() + delta_latitude).clamp(-LATITUDE_MAX, LATITUDE_MAX);
806        if (end_latitude - start_latitude).abs() <= 1.0 {
807            return LatLng::saturating(latitude, start.longitude() + delta_longitude * t, WrapMode::Unwrapped);
808        }
809        let on_different_hemispheres = sign(end_latitude) != sign(start_latitude);
810        let sample_start = mln_style::math::deg2rad(if on_different_hemispheres {
811            -start_latitude.abs()
812        } else {
813            start_latitude.abs()
814        });
815        let sample_end = mln_style::math::deg2rad(end_latitude.abs());
816        let value_start = integrate_secant(sample_start);
817        let value_end = integrate_secant(sample_end);
818        let value_t = integrate_secant(sample_start + t * (sample_end - sample_start));
819        let longitude_t = (value_t - value_start) / (value_end - value_start);
820        LatLng::saturating(latitude, start.longitude() + delta_longitude * longitude_t, WrapMode::Unwrapped)
821    }
822}
823
824// GL JS globe_utils drag constants.
825const PAN_FALLOFF_BAND: f64 = 0.1;
826const DIAL_MIN_RADIUS_PIXELS: f64 = 20.0;
827const DIAL_RAMP_DEGREES: f64 = 12.0;
828const PAN_MAX_ANGLE: f64 = PI * 0.98;
829
830/// The most a held location may turn the center per pixel, relative to a
831/// location at the center, before the drag stops holding it exactly.
832const DRAG_HOLD_MAX_GAIN: f64 = 2.5;
833
834/// GL JS `orientationFromLngLatBearing`: the rotation by `-longitude` about
835/// x, then `-latitude` about y, then the bearing (in GL JS's sign) about z.
836fn orientation_from_lat_lng_bearing(center: &LatLng, bearing_degrees: f64) -> DQuat {
837    DQuat::from_euler(
838        EulerRot::ZYX,
839        mln_style::math::deg2rad(bearing_degrees),
840        mln_style::math::deg2rad(-center.latitude()),
841        mln_style::math::deg2rad(-center.longitude()),
842    )
843}
844
845struct Orientation {
846    latitude: f64,
847    longitude: f64,
848    bearing: f64,
849}
850
851/// GL JS `lngLatBearingFromOrientation`.
852fn orientation_to_lat_lng_bearing(q: DQuat) -> Orientation {
853    Orientation {
854        latitude: -mln_style::math::rad2deg((2.0 * (q.w * q.y - q.z * q.x)).clamp(-1.0, 1.0).asin()),
855        longitude: -mln_style::math::rad2deg(
856            (2.0 * (q.w * q.x + q.y * q.z)).atan2(1.0 - 2.0 * (q.x * q.x + q.y * q.y)),
857        ),
858        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))),
859    }
860}
861
862/// A drag's ray through a point in the falloff band of
863/// [`pan_surface_vector`], or past it.
864struct PanFalloff {
865    /// The direction from the planet's center to the camera.
866    toward_camera: DVec3,
867    /// The camera's distance from the planet's center, in radii of the
868    /// sphere the drag holds.
869    distance: f64,
870    /// The part of the ray's direction across `toward_camera`, and its
871    /// length.
872    lateral: DVec3,
873    lateral_length: f64,
874    /// The ray's angle from the line to the planet's center, and the angle
875    /// the band starts at.
876    angle: f64,
877    handover_angle: f64,
878}
879
880/// The falloff a drag towards `point` on the sphere `height` meters above sea
881/// level is in, if any: none while the ray is well inside that sphere's
882/// silhouette, where the drag aims at the point under `point`.
883fn pan_falloff(view: &View, point: &ScreenCoordinate, height: f64) -> Option<PanFalloff> {
884    let origin = camera_over_sphere(view, height);
885    let distance = origin.length();
886    if distance <= 1.0 {
887        return None;
888    }
889    let toward_camera = origin / distance;
890    let direction = ray_direction_from_pixel(view, point, &view.inverse_globe_view_projection_matrix());
891    let c = -direction.dot(toward_camera);
892    let lateral = direction + toward_camera * c;
893    let lateral_length = lateral.length();
894    if lateral_length < 1e-9 {
895        return None;
896    }
897    let angle = lateral_length.atan2(c);
898    let handover_angle = (1.0 / distance).asin() * (1.0 - PAN_FALLOFF_BAND);
899    (angle >= handover_angle).then_some(PanFalloff {
900        toward_camera,
901        distance,
902        lateral,
903        lateral_length,
904        angle,
905        handover_angle,
906    })
907}
908
909/// GL JS `panSurfaceLocation`: the direction of the point on the sphere
910/// `height` meters above sea level that a drag towards `point` aims at. Exact
911/// while the ray is well inside the silhouette, then eased off along a
912/// hyperbola that matches it in value and slope and saturates short of the
913/// far side, so the drag keeps going once the cursor leaves the planet.
914fn pan_surface_vector(view: &View, point: &ScreenCoordinate, height: f64) -> DVec3 {
915    let Some(PanFalloff { toward_camera: u, distance, lateral, lateral_length: s, angle, handover_angle }) =
916        pan_falloff(view, point, height)
917    else {
918        return VerticalPerspectiveProjection::screen_coordinate_to_surface(view, point, height);
919    };
920    let sin_handover = distance * handover_angle.sin();
921    let target_at_handover = sin_handover.clamp(-1.0, 1.0).asin() - handover_angle;
922    let slope_at_handover =
923        distance * handover_angle.cos() / f64::max(1.0 - sin_handover * sin_handover, 1e-12).sqrt() - 1.0;
924    let room = PAN_MAX_ANGLE - target_at_handover;
925    let excess = angle - handover_angle;
926    let target = (target_at_handover + room * (slope_at_handover * excess) / (room + slope_at_handover * excess))
927        .clamp(0.0, PAN_MAX_ANGLE);
928    (u * target.cos() + lateral * (target.sin() / s)).normalize()
929}
930
931/// The globe camera's position where the sphere `height` meters above sea
932/// level is the unit sphere: scaled by 1 / (1 + height / R), which at height
933/// 0 leaves it as it is, to the bit.
934fn camera_over_sphere(view: &View, height: f64) -> DVec3 {
935    view.globe_camera_position() / (1.0 + height / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS)
936}
937
938/// The globe camera's orientation; GL JS's bearing is the view's angle with the
939/// sign flipped.
940fn camera_orientation(view: &View) -> DQuat {
941    orientation_from_lat_lng_bearing(&view.center(WrapMode::Unwrapped), -mln_style::math::rad2deg(view.angle()))
942}
943
944/// The rotation about `axis` by `angle`, composed as GL JS's drag composes
945/// it: the axis is in the surface-vector frame and the orientation in the
946/// Euler frame, hence the swizzle.
947fn rotation(axis: DVec3, angle: f64) -> DQuat {
948    let l = axis.length();
949    if l == 0.0 {
950        return DQuat::IDENTITY;
951    }
952    let s = (angle / 2.0).sin();
953    DQuat::from_xyzw(axis.y / l * s, -axis.x / l * s, axis.z / l * s, (angle / 2.0).cos())
954}
955
956/// The orientation after the rotation that brings the surface location
957/// `from` to where `to` is.
958fn turned(orientation: DQuat, from: DVec3, to: DVec3) -> DQuat {
959    orientation * rotation(from.cross(to), from.dot(to).clamp(-1.0, 1.0).acos())
960}
961
962/// The point `t` of the way from one unit vector to another along the great
963/// circle.
964fn slerp_vec3(a: DVec3, b: DVec3, t: f64) -> DVec3 {
965    let angle = a.dot(b).clamp(-1.0, 1.0).acos();
966    if angle.sin() < 1e-9 {
967        return a;
968    }
969    a * (((1.0 - t) * angle).sin() / angle.sin()) + b * ((t * angle).sin() / angle.sin())
970}
971
972/// The center and bearing of an orientation, the longitude unwrapped around
973/// `center`.
974fn center_and_bearing(orientation: DQuat, center: &LatLng) -> CenterAndBearing {
975    let o = orientation_to_lat_lng_bearing(orientation);
976    CenterAndBearing {
977        center: LatLng::saturating(
978            o.latitude,
979            center.longitude()
980                + VerticalPerspectiveProjection::difference_of_angles_degrees(center.longitude(), o.longitude),
981            WrapMode::Unwrapped,
982        ),
983        bearing: o.bearing,
984    }
985}
986
987/// `zoom_around_point` with the bearing free. The exact part is the rotation
988/// that brings the zoom location back under the anchor; the heuristic part
989/// moves the center a `factor` of the way along the great circle towards it,
990/// the orientation carried along. They blend by GL JS's horizon factor alone:
991/// GL JS also blends by how far the location's longitude is from the
992/// center's, which the bearing-held solution needs near a pole and a rotation
993/// does not.
994fn zoom_turning_the_planet(
995    state: &mut TransformState,
996    anchor: &ScreenCoordinate,
997    zoom_location: &LatLng,
998    height: f64,
999    factor: f64,
1000    interpolation_factor_horizon: f64,
1001) {
1002    let center = state.view().center(WrapMode::Unwrapped);
1003    let orientation = camera_orientation(state.view());
1004    let location = VerticalPerspectiveProjection::surface_vector(zoom_location);
1005    let center_vector = VerticalPerspectiveProjection::surface_vector(&center);
1006    let exact = turned(orientation, location, pan_surface_vector(state.view(), anchor, height));
1007    let heuristic = turned(orientation, slerp_vec3(center_vector, location, factor), center_vector);
1008    let camera = center_and_bearing(
1009        exact.slerp(heuristic, interpolation_factor_horizon.powf(INTERPOLATE_TO_HEURISTIC_EXPONENT)),
1010        &center,
1011    );
1012    let constrained = state.constrained_center(&camera.center, state.view().zoom());
1013    let zoom =
1014        state.view().zoom() + VerticalPerspectiveProjection::zoom_adjustment(center.latitude(), constrained.latitude());
1015    state.set_lat_lng_zoom(&constrained, zoom);
1016    state.set_angle(-mln_style::math::deg2rad(camera.bearing));
1017}
1018
1019impl VerticalPerspectiveProjection {
1020    /// [`Projection::projection_data`](crate::camera::Projection::projection_data) on the globe.
1021    pub(crate) fn projection_data(view: &View, tile_id: &UnwrappedTileID, mercator_matrix: &DMat4) -> ProjectionData {
1022        // The middle of the tile; the shaders' `GLOBE_ANCHOR`.
1023        let middle = Point::new(f64::from(EXTENT) / 2.0, f64::from(EXTENT) / 2.0);
1024        ProjectionData {
1025            sphere_anchor: Self::tile_coordinates_to_sphere(&middle, tile_id),
1026            sphere_anchor_angles: Self::tile_coordinates_to_angles(&middle, tile_id),
1027            main_matrix: view.globe_view_projection_matrix(),
1028            tile_mercator_coords: mercator_tile_coords(tile_id),
1029            clipping_plane: view.globe_clipping_plane(),
1030            projection_transition: view.projection_transition(),
1031            fallback_matrix: *mercator_matrix,
1032            camera_position: view.globe_camera_position(),
1033            ..ProjectionData::default()
1034        }
1035    }
1036
1037    /// [`Projection::project_tile_point`](crate::camera::Projection::project_tile_point) on the globe.
1038    pub(crate) fn project_tile_point(
1039        data: &ProjectionData,
1040        tile_id: &UnwrappedTileID,
1041        point: &Point<f64>,
1042        elevation: f64,
1043    ) -> ProjectedTilePoint {
1044        let surface = Self::tile_coordinates_to_sphere(point, tile_id);
1045        let height_scale = 1.0 + elevation / Self::GLOBE_RADIUS_METERS;
1046        let sphere = surface * height_scale;
1047        let pos = data.main_matrix * sphere.extend(1.0);
1048        // GL JS: the horizon plane hides a point on the surface, and only the
1049        // planet itself hides a raised one.
1050        let occluded = if height_scale <= 1.0 {
1051            point_plane_signed_distance(data.clipping_plane, surface) < 0.0
1052        } else {
1053            line_of_sight_blocked(data.camera_position, sphere)
1054        };
1055        ProjectedTilePoint {
1056            point: Point::new(pos.x / pos.w, pos.y / pos.w),
1057            signed_distance_from_camera: pos.w,
1058            occluded,
1059        }
1060    }
1061
1062    /// [`Projection::drawn_tile_point`](crate::camera::Projection::drawn_tile_point) on the globe.
1063    pub(crate) fn drawn_tile_point(
1064        data: &ProjectionData,
1065        tile_id: &UnwrappedTileID,
1066        point: &Point<f64>,
1067        elevation: f64,
1068    ) -> ProjectedTilePoint {
1069        let globe = Self::project_tile_point(data, tile_id, point, elevation);
1070        let t = data.projection_transition;
1071        if t > 0.999 {
1072            return globe;
1073        }
1074        // The shaders' `interpolateProjection`: the sphere blended with
1075        // Mercator, the horizon clipping through the blended depth from a
1076        // fifth of the hand-over on. Raised geometry keeps its depth and the
1077        // globe hides it.
1078        let flat = data.fallback_matrix * DVec4::new(point.x, point.y, elevation, 1.0);
1079        let globe_w = globe.signed_distance_from_camera;
1080        let w = interpolate(&flat.w, &globe_w, t);
1081        let globeness = ((t - 0.2) / 0.8).clamp(0.0, 1.0);
1082        let mut occluded = globeness > 0.0 && globe.occluded;
1083        if elevation <= 0.0 {
1084            let surface = Self::tile_coordinates_to_sphere(point, tile_id);
1085            let clipping_z = 1.0 - point_plane_signed_distance(data.clipping_plane, surface);
1086            occluded = globeness * clipping_z * globe_w > w;
1087        }
1088        ProjectedTilePoint {
1089            point: Point::new(
1090                interpolate(&flat.x, &(globe.point.x * globe_w), t) / w,
1091                interpolate(&flat.y, &(globe.point.y * globe_w), t) / w,
1092            ),
1093            signed_distance_from_camera: w,
1094            occluded,
1095        }
1096    }
1097
1098    /// [`Projection::map_aligned_scale`](crate::camera::Projection::map_aligned_scale) on the globe.
1099    pub(crate) fn map_aligned_scale(view: &View) -> f64 {
1100        Self::planet_scale(view.center(WrapMode::Unwrapped).latitude())
1101    }
1102
1103    /// [`Projection::pixel_scale`](crate::camera::Projection::pixel_scale) on the globe.
1104    pub(crate) fn pixel_scale(view: &View) -> f64 {
1105        interpolate(
1106            &1.0,
1107            &(1.0 / Self::planet_scale(view.center(WrapMode::Unwrapped).latitude())),
1108            view.projection_transition(),
1109        )
1110    }
1111
1112    /// [`Projection::map_aligned_scale_at`](crate::camera::Projection::map_aligned_scale_at) on the globe.
1113    pub(crate) fn map_aligned_scale_at(view: &View, tile_anchor: &Point<f64>, tile_id: &UnwrappedTileID) -> f64 {
1114        let scale = 1.0 / (1u64 << tile_id.canonical.z) as f64;
1115        let mercator_y = tile_anchor.y / f64::from(EXTENT) * scale + f64::from(tile_id.canonical.y) * scale;
1116        let latitude = 2.0 * (PI - (mercator_y * PI * 2.0)).exp().atan() - PI * 0.5;
1117        interpolate(
1118            &1.0,
1119            &(Self::planet_scale(view.center(WrapMode::Unwrapped).latitude()) / latitude.cos()),
1120            view.projection_transition(),
1121        )
1122    }
1123}