mln-rs-engine 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! The planes that the camera's moves solve on, or on the globe the
//! spheres. A move around an anchor, a drag, a pinch, a turn or a tilt,
//! whether a command, a gesture or a momentum makes it, holds the location
//! its pointer grabbed under the pointer, on the plane at the height of the
//! ground it grabbed: over terrain the drawn ground, which is what the
//! pointer is on, and on the flat map sea level. A move without an anchor,
//! or around one whose line of sight doesn't meet the ground, moves the map
//! on the plane or the sphere at the center's altitude, which keeps the
//! center where it draws.

use mln_style::error::Error;
use mln_style::geo::{LatLng, WrapMode};
use mln_style::geometry::Point;

use super::{Transform, flip_y};
use crate::camera::{VerticalPerspectiveProjection, View};
use crate::geo::ScreenCoordinate;

/// How near the view's center, in squared pixels, an anchor stands at it:
/// a move around it leaves the center where it is.
const NEAR_CENTER: f64 = 1e-2;

/// How far up from the center to the eye, as a share of the way, the plane
/// a move holds its grabbed ground on can stand. Ground higher up is so
/// near the eye that a pointer's move holding it would carry the camera
/// only a sliver as far, and a drag into a hill would all but stop.
const MAX_ANCHOR_RISE: f64 = 0.9;

/// The most ground pixels (at the view's zoom) a flat-map pan moves per screen
/// pixel along the camera's forward axis. Below this gain, a drag holds the
/// grabbed ground 1:1 under the pointer; approaching the horizon and into the
/// sky, the gain saturates smoothly here instead of blowing up toward infinity.
const MAX_PAN_VERTICAL_GAIN: f64 = 3.0;

/// The most ground pixels (at the view's zoom) a flat-map pan moves per screen
/// pixel across the horizon. Keeps horizontal panning 1:1 at the view center
/// at every pitch while capping sideways speed near and above the horizon.
const MAX_PAN_HORIZONTAL_GAIN: f64 = 2.0;

impl Transform {
    /// The height of the plane on which a move around `anchor` (y down)
    /// holds the ground the pointer grabbed under `grabbed`, the pointer
    /// before the move: the ground's height, but no higher than
    /// [`MAX_ANCHOR_RISE`] of the way up from the center to the eye, where
    /// higher ground slips from under the pointer as smoothly as it rises
    /// past that. On the globe the plane is the sphere at that height.
    ///
    /// `None`, for the plane at the center's altitude, where the pointer
    /// grabbed no ground ([`Self::grabbed_height`]), for a pivot (`grabbed`
    /// is `anchor`) at the view's center, and where the plane can't hold the
    /// anchor or the grabbed point ([`sees_plane`]), such as one above the
    /// horizon.
    pub(super) fn anchor_plane(&self, grabbed: &ScreenCoordinate, anchor: &ScreenCoordinate) -> Option<f64> {
        let view = self.view();
        let altitude = view.center_altitude();
        let ceiling = altitude + MAX_ANCHOR_RISE * (view.eye_position().z - altitude);
        let height = self.grabbed_height(grabbed)?.min(ceiling);
        let center = view.padding().center_in(view.size());
        // A pivot at the center leaves the center where it is.
        let pivot = grabbed == anchor && (anchor.x - center.x).powi(2) + (anchor.y - center.y).powi(2) < NEAR_CENTER;
        let sees = |point: &ScreenCoordinate| sees_plane(view, &flip_y(view, point), height);
        (!pivot && sees(anchor) && sees(grabbed)).then_some(height)
    }

    /// The height of the ground a move grabs under `grabbed` (y down): over
    /// terrain, the drawn ground that the point's line of sight meets, or
    /// `None` where it meets none or before any was drawn; on the flat map,
    /// sea level.
    pub(super) fn grabbed_height(&self, grabbed: &ScreenCoordinate) -> Option<f64> {
        let Some(terrain) = &self.terrain else { return Some(0.0) };
        let view = self.view();
        Some(view.ground_under(&flip_y(view, grabbed), terrain.elevation.as_deref()?)?.height)
    }

    /// Clamps a plane height below the camera eye by [`MAX_ANCHOR_RISE`] of the
    /// way up from the center to the eye.
    pub(super) fn clamp_anchor_height(&self, height: f64) -> f64 {
        let view = self.view();
        let altitude = view.center_altitude();
        let ceiling = altitude + MAX_ANCHOR_RISE * (view.eye_position().z - altitude);
        height.min(ceiling)
    }

    /// The height of the plane, or on the globe the sphere, on which a move
    /// around `anchor` (y down) holds the location the pointer grabbed under
    /// `grabbed` ([`Self::anchor_plane`]), or else the center's altitude.
    pub(super) fn anchor_height(&self, grabbed: &ScreenCoordinate, anchor: &ScreenCoordinate) -> f64 {
        self.anchor_plane(grabbed, anchor).unwrap_or(self.view().center_altitude())
    }

    /// The center that moves the location on the plane `height` meters
    /// above sea level under `from` to `to`, both screen points (y down),
    /// unwrapped.
    pub(super) fn center_moving_on_plane(
        &self,
        from: &ScreenCoordinate,
        to: &ScreenCoordinate,
        height: f64,
    ) -> Result<LatLng, Error> {
        let location = self.screen_coordinate_to_lat_lng_at(from, height, WrapMode::Unwrapped)?;
        self.state.center_for_lat_lng_at(&location, &flip_y(self.view(), to), height)
    }

    /// The center that pans the flat map on the plane `height` meters above
    /// sea level from `from` to `to` (both screen points, y down), unwrapped.
    ///
    /// While both endpoints lie in the well-conditioned perspective zone
    /// (vertical gain at most [`MAX_PAN_VERTICAL_GAIN`] and horizontal gain at
    /// most [`MAX_PAN_HORIZONTAL_GAIN`]) on the map surface, this matches
    /// [`Self::center_moving_on_plane`] so grabbed ground stays 1:1 under the
    /// pointer. Approaching the horizon and into the sky, both gains saturate
    /// smoothly with no discontinuity across the horizon and no sideways drift
    /// for vertical drags in the sky.
    pub(super) fn center_panning_on_plane(
        &self,
        from: &ScreenCoordinate,
        to: &ScreenCoordinate,
        height: f64,
    ) -> Result<LatLng, Error> {
        let view = self.view();
        let size = view.size();
        if !from.x.is_finite()
            || !from.y.is_finite()
            || !to.x.is_finite()
            || !to.y.is_finite()
            || size.is_empty()
            || view.params().axonometric
            || view.is_globe()
        {
            return self.center_moving_on_plane(from, to, height);
        }

        let pitch = view.pitch();
        let d = 0.5 * f64::from(size.height) / (view.perspective_fov() / 2.0).tan();
        let eye_height_px = (view.eye_position().z - height) / view.meters_per_pixel();
        let h0 = eye_height_px / d;

        // Express `from` and `to` in the unrolled camera screen frame about
        // the padded view center: `u` right along the horizon, `v` up toward
        // the horizon.
        let center = view.padding().center_in(size);
        let (sin_psi, cos_psi) = (view.roll() - view.north_orientation_angle()).sin_cos();
        let unrolled = |p: &ScreenCoordinate| {
            let sx = p.x - center.x;
            let sy = center.y - p.y;
            (sx * cos_psi + sy * sin_psi, -sx * sin_psi + sy * cos_psi)
        };
        let (u1, v1) = unrolled(from);
        let (u2, v2) = unrolled(to);

        let (sin_p, cos_p) = pitch.sin_cos();
        let (dx_ground, dy_ground) = if !h0.is_finite() || h0 <= 0.0 {
            (u2 - u1, (v2 - v1) * MAX_PAN_VERTICAL_GAIN)
        } else if sin_p.abs() < 1e-9 {
            if sees_plane(view, &flip_y(view, from), height) && sees_plane(view, &flip_y(view, to), height) {
                return self.center_moving_on_plane(from, to, height);
            }
            let scale = h0 / cos_p;
            ((u2 - u1) * scale, (v2 - v1) * scale)
        } else {
            let q = |v: f64| cos_p - (v / d) * sin_p;
            let (q1, q2) = (q(v1), q(v2));
            let q_y_min = (h0 / MAX_PAN_VERTICAL_GAIN).sqrt();
            let q_x_min = h0 / MAX_PAN_HORIZONTAL_GAIN;
            let q_exact_min = q_y_min.max(q_x_min);

            if q1 >= q_exact_min
                && q2 >= q_exact_min
                && sees_plane(view, &flip_y(view, from), height)
                && sees_plane(view, &flip_y(view, to), height)
            {
                return self.center_moving_on_plane(from, to, height);
            }

            // C^1 vertical potential: exact below `v_y0` (where `q == q_y_min`),
            // linear at `MAX_PAN_VERTICAL_GAIN` above `v_y0` across the horizon
            // and into the sky.
            let v_y0 = d * (cos_p - q_y_min) / sin_p;
            let y_at = |v: f64, qv: f64| {
                if qv >= q_y_min {
                    h0 * d / (sin_p * qv)
                } else {
                    h0 * d / (sin_p * q_y_min) + MAX_PAN_VERTICAL_GAIN * (v - v_y0)
                }
            };
            let dy = y_at(v2, q2) - y_at(v1, q1);

            // Horizontal gain caps smoothly at `MAX_PAN_HORIZONTAL_GAIN`.
            let gx = |qv: f64| h0 / qv.max(q_x_min);
            let dx_horiz = f64::midpoint(gx(q1), gx(q2)) * (u2 - u1);

            // C^1 perspective convergence potential: matches `h0 / q` in the
            // exact zone, tapers smoothly to zero slope at the horizon (`q == 0`),
            // and stays constant in the sky (`q <= 0`).
            let conv_at = |qv: f64| {
                if qv >= q_y_min {
                    h0 / qv
                } else if qv > 0.0 {
                    h0 / q_y_min + 0.5 * MAX_PAN_VERTICAL_GAIN * (q_y_min * q_y_min - qv * qv) / q_y_min
                } else {
                    1.5 * h0 / q_y_min
                }
            };
            let dx_conv = f64::midpoint(u1, u2) * (conv_at(q2) - conv_at(q1));

            (dx_horiz + dx_conv, dy)
        };

        // Shift the center by `-(dx_ground, dy_ground)` in the camera's ground
        // basis (world pixels: x east, y south).
        let (sin_a, cos_a) = view.angle().sin_cos();
        let world_dx = -dx_ground * cos_a + dy_ground * sin_a;
        let world_dy = dx_ground * sin_a + dy_ground * cos_a;

        let scale = view.scale();
        let world = view.world();
        let center_coord = world.project(&view.center(WrapMode::Unwrapped), scale);
        world.unproject(&Point::new(center_coord.x + world_dx, center_coord.y + world_dy), scale, WrapMode::Unwrapped)
    }
}

/// Whether a move can hold a location on the plane `height` meters above
/// sea level under `point` of `view`, measured from the bottom edge (y up):
/// whether the point's line of sight starts above the plane and descends to
/// meet it before the far plane, which the view fits to the horizon, at a
/// place with a location of its own ([`View::has_lat_lng_at`]), which past a
/// registered projection's edge it hasn't. It asks the line itself, which a
/// roll turns away from the screen's rows. On the globe the plane is the sphere
/// at that height, which the eye must be above and the line must meet. Never
/// while the view shows nothing.
pub(super) fn sees_plane(view: &View, point: &ScreenCoordinate, height: f64) -> bool {
    if view.is_globe() {
        let above =
            view.globe_camera_position().length() > 1.0 + height / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS;
        return above && VerticalPerspectiveProjection::screen_coordinate_hits_globe(view, point, height);
    }
    let Some((near, far)) = view.line_of_sight(point) else { return false };
    far.z < near.z && far.z <= height && height < near.z && view.has_lat_lng_at(point, height)
}