mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! Camera bounds fitting and visible-bounds queries for flat and globe views.

use glam::{DMat4, DVec3};
use mln_style::error::Error;
use mln_style::geo::{LatLng, LatLngBounds, WrapMode};
use mln_style::types::{ProjectionDefinition, ProjectionType};

use crate::camera::transform::Transform;
use crate::camera::{CameraOptions, VerticalPerspectiveProjection, scale_zoom, zoom_scale};
use crate::geo::projection::Projection;
use crate::geo::{EdgeInsets, ScreenCoordinate};
use crate::log_target;

/// The bounds of the area `transform` shows; when `unwrapped` is true, corners
/// are unwrapped toward the center so bounds can cross the antimeridian.
pub(crate) fn lat_lng_bounds_for_transform(transform: &Transform, unwrapped: bool) -> Result<LatLngBounds, Error> {
    let size = transform.state().view().size();
    if transform.state().view().is_globe() {
        return globe_bounds(transform);
    }
    if !transform.view().world().wraps() {
        return corner_bounds(transform);
    }
    let (width, height) = (f64::from(size.width), f64::from(size.height));
    let at = |x, y| transform.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(x, y), WrapMode::Wrapped);
    let mut nw = at(0.0, 0.0)?;
    let mut se = at(width, height)?;
    if !unwrapped {
        return Ok(LatLngBounds::hull(nw, se));
    }
    let mut ne = at(width, 0.0)?;
    let mut sw = at(0.0, height)?;
    let center = at(width / 2.0, height / 2.0)?;
    for corner in [&mut nw, &mut se, &mut ne, &mut sw] {
        corner.unwrap_for_shortest_path(&center);
    }
    let mut bounds = LatLngBounds::hull(nw, se);
    bounds.extend(&ne);
    bounds.extend(&sw);
    bounds.extend(&center);
    Ok(bounds)
}

/// The center and zoom that fit `bounds` in `transform`'s view inset by
/// `padding` and `margin`, at a zoom no higher than `max_zoom` or the
/// transform's limit.
pub(crate) fn camera_for_lat_lng_bounds(
    bounds: &LatLngBounds,
    transform: &Transform,
    padding: &EdgeInsets,
    margin: &EdgeInsets,
    max_zoom: f64,
) -> Result<CameraOptions, Error> {
    let view = transform.view();
    if view.is_globe() {
        let corners = [bounds.northwest(), bounds.southwest(), bounds.southeast(), bounds.northeast()];
        return camera_for_lat_lngs(&corners, transform, padding, margin, max_zoom);
    }
    let samples = view.world().lng_lat_box_samples(bounds);
    let pixels: Vec<ScreenCoordinate> =
        samples.points.iter().map(|point| transform.world_to_screen_coordinate(point)).collect();
    let bulge = samples.bulge * Projection::world_size(view.scale());
    camera_for_pixels(&pixels, bulge, transform, padding, margin, max_zoom)
}

/// The center and zoom that fit `lat_lngs`, as `transform` shows them,
/// inside the view inset by `padding` and `margin`, for a camera with
/// `padding`, at a zoom no higher than `max_zoom` or the transform's limit.
pub(crate) fn camera_for_lat_lngs(
    lat_lngs: &[LatLng],
    transform: &Transform,
    padding: &EdgeInsets,
    margin: &EdgeInsets,
    max_zoom: f64,
) -> Result<CameraOptions, Error> {
    if lat_lngs.is_empty() {
        return Ok(CameraOptions::default());
    }
    if transform.state().view().is_globe() {
        camera_for_lat_lngs_on_globe(lat_lngs, transform, padding, margin, max_zoom)
    } else {
        camera_for_lat_lngs_on_screen(lat_lngs, transform, padding, margin, max_zoom)
    }
}

/// `padding` and `margin` added together.
fn total_insets(padding: &EdgeInsets, margin: &EdgeInsets) -> EdgeInsets {
    EdgeInsets {
        top: padding.top + margin.top,
        left: padding.left + margin.left,
        bottom: padding.bottom + margin.bottom,
        right: padding.right + margin.right,
    }
}

/// Fails as `Map::camera_for_lat_lngs` does.
fn camera_for_lat_lngs_on_screen(
    lat_lngs: &[LatLng],
    transform: &Transform,
    padding: &EdgeInsets,
    margin: &EdgeInsets,
    max_zoom: f64,
) -> Result<CameraOptions, Error> {
    let pixels: Vec<ScreenCoordinate> =
        lat_lngs.iter().map(|lat_lng| transform.lat_lng_to_screen_coordinate(lat_lng)).collect();
    camera_for_pixels(&pixels, 0.0, transform, padding, margin, max_zoom)
}

/// The center and zoom that fit every point of `pixels`, screen points (y
/// down) of `transform`'s view, with `bulge` pixels around them, inside the
/// view inset by `padding` and `margin`, for a camera with `padding`, at a
/// zoom no higher than `max_zoom` or the transform's limit. Fails as
/// `Map::camera_for_lat_lngs` does.
fn camera_for_pixels(
    pixels: &[ScreenCoordinate],
    bulge: f64,
    transform: &Transform,
    padding: &EdgeInsets,
    margin: &EdgeInsets,
    max_zoom: f64,
) -> Result<CameraOptions, Error> {
    let size = transform.state().view().size();
    let insets = total_insets(padding, margin);
    // Calculate the bounds of the possibly rotated shape with respect to the viewport.
    let mut ne_pixel = ScreenCoordinate::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
    let mut sw_pixel = ScreenCoordinate::new(f64::INFINITY, f64::INFINITY);
    for &pixel in pixels {
        // A NaN pixel moves neither corner.
        sw_pixel.x = if pixel.x < sw_pixel.x { pixel.x } else { sw_pixel.x };
        ne_pixel.x = if ne_pixel.x < pixel.x { pixel.x } else { ne_pixel.x };
        sw_pixel.y = if pixel.y < sw_pixel.y { pixel.y } else { sw_pixel.y };
        ne_pixel.y = if ne_pixel.y < pixel.y { pixel.y } else { ne_pixel.y };
    }
    if bulge != 0.0 {
        sw_pixel = ScreenCoordinate::new(sw_pixel.x - bulge, sw_pixel.y - bulge);
        ne_pixel = ScreenCoordinate::new(ne_pixel.x + bulge, ne_pixel.y + bulge);
    }
    let width = ne_pixel.x - sw_pixel.x;
    let height = ne_pixel.y - sw_pixel.y;

    // Calculate the zoom level.
    let mut min_scale = f64::INFINITY;
    if width > 0.0 || height > 0.0 {
        let mut scale_x = f64::from(size.width) / width;
        let mut scale_y = f64::from(size.height) / height;
        scale_x -= (insets.left() + insets.right()) / width;
        scale_y -= (insets.top() + insets.bottom()) / height;
        min_scale = mln_style::math::fmin(scale_x, scale_y);
    }

    let current_zoom = transform.view().zoom();
    let mut zoom = current_zoom;
    if min_scale > 0.0 {
        zoom = mln_style::math::clamp_f64(
            f64::min(zoom + min_scale.log2(), max_zoom),
            transform.state().min_zoom(),
            transform.state().limits().max_zoom,
        );
    } else {
        tracing::error!(
            target: log_target::GENERAL,
            "Unable to calculate appropriate zoom level for bounds. Vertical or horizontal padding is greater than \
             map's height or width."
        );
    }

    // The camera centers inside its padding, so an uneven margin moves the
    // area's center off the camera's by half the difference, at the new zoom.
    let offset_scale = zoom_scale(current_zoom - zoom);
    let center_pixel = ScreenCoordinate::new(
        f64::midpoint(ne_pixel.x, sw_pixel.x) - (margin.left - margin.right) / 2.0 * offset_scale,
        f64::midpoint(ne_pixel.y, sw_pixel.y) - (margin.top - margin.bottom) / 2.0 * offset_scale,
    );

    Ok(CameraOptions {
        center: Some(transform.screen_coordinate_to_lat_lng(&center_pixel, WrapMode::Wrapped)?),
        zoom: Some(zoom),
        ..Default::default()
    })
}

/// How much to scale the globe for a surface point to land on `target` along
/// one clip axis, or nothing when the equation degenerates. Zooming out also
/// moves the camera along `to_center`, so the point solved for is `vector * t +
/// to_center * (1 - t)`.
fn globe_scale_for_clip_target(
    vector: DVec3,
    to_center: DVec3,
    projection: &DMat4,
    x_axis: bool,
    target: f64,
) -> Option<f64> {
    // The rows of the clip axis and of w.
    let column = projection.row(usize::from(!x_axis));
    let column_z = projection.row(3);

    let vector_dot = vector.dot(column.truncate());
    let vector_dot_z = vector.dot(column_z.truncate());
    let to_center_dot = to_center.dot(column.truncate());
    let to_center_dot_z = to_center.dot(column_z.truncate());

    if to_center_dot + target * vector_dot_z == vector_dot + target * to_center_dot_z
        || column_z[3] * (vector_dot - to_center_dot)
            + column[3] * (to_center_dot_z - vector_dot_z)
            + vector_dot * to_center_dot_z
            == to_center_dot * vector_dot_z
    {
        return None;
    }
    Some(
        (to_center_dot + column[3] - target * to_center_dot_z - target * column_z[3])
            / (to_center_dot - vector_dot - target * to_center_dot_z + target * vector_dot_z),
    )
}

fn keep_smallest_scale(smallest: &mut f64, candidate: Option<f64>) {
    if let Some(candidate) = candidate
        && candidate >= 0.0
        && candidate < *smallest
    {
        *smallest = candidate;
    }
}

/// The camera that fits `lat_lngs` on the globe: fit the flat world first,
/// then scale the globe until every corner and edge midpoint of their
/// bounds is inside the padded viewport, with no pitch.
/// Fails as `Map::camera_for_lat_lngs` does.
fn camera_for_lat_lngs_on_globe(
    lat_lngs: &[LatLng],
    transform: &Transform,
    padding: &EdgeInsets,
    margin: &EdgeInsets,
    max_zoom: f64,
) -> Result<CameraOptions, Error> {
    let mut flat = Transform::from_state(transform.state().clone());
    flat.set_projection(ProjectionDefinition::new(ProjectionType::Mercator).into());
    flat.jump_to(&CameraOptions { pitch: Some(0.0), roll: Some(0.0), ..Default::default() });
    let fit = camera_for_lat_lngs_on_screen(lat_lngs, &flat, padding, margin, max_zoom)?;
    let (Some(fit_center), Some(fit_zoom)) = (fit.center, fit.zoom) else {
        return Ok(fit);
    };

    // Solve with the padding the returned camera is shown with.
    let mut globe = Transform::from_state(transform.state().clone());
    globe.jump_to(&CameraOptions {
        center: Some(fit_center),
        zoom: Some(fit_zoom),
        padding: Some(*padding),
        pitch: Some(0.0),
        roll: Some(0.0),
        ..Default::default()
    });
    let state = globe.state();
    let matrix = state.view().globe_view_projection_matrix();
    let size = state.view().size();
    let width = f64::from(size.width);
    let height = f64::from(size.height);
    // The samples must land inside the padding and the margin.
    let insets = total_insets(padding, margin);
    let left = insets.left() / width * 2.0 - 1.0;
    let right = (width - insets.right()) / width * 2.0 - 1.0;
    let top = insets.top() / height * -2.0 + 1.0;
    let bottom = (height - insets.bottom()) / height * -2.0 + 1.0;

    let mut bounds = LatLngBounds::empty();
    for lat_lng in lat_lngs {
        bounds.extend(lat_lng);
    }
    let west = bounds.west();
    let east = bounds.east();
    let north = bounds.north();
    let south = bounds.south();
    let mid_longitude = west + VerticalPerspectiveProjection::difference_of_angles_degrees(west, east) * 0.5;
    let mid_latitude = north + VerticalPerspectiveProjection::difference_of_angles_degrees(north, south) * 0.5;
    let samples = [
        LatLng::new(north, west)?,
        LatLng::new(north, east)?,
        LatLng::new(south, west)?,
        LatLng::new(south, east)?,
        LatLng::new(mid_latitude, east)?,
        LatLng::new(mid_latitude, west)?,
        LatLng::new(north, mid_longitude)?,
        LatLng::new(south, mid_longitude)?,
    ];
    let to_center = VerticalPerspectiveProjection::surface_vector(&fit_center);

    let mut smallest = f64::INFINITY;
    for sample in &samples {
        let vector = VerticalPerspectiveProjection::surface_vector(sample);
        if left < 0.0 {
            keep_smallest_scale(&mut smallest, globe_scale_for_clip_target(vector, to_center, &matrix, true, left));
        }
        if right > 0.0 {
            keep_smallest_scale(&mut smallest, globe_scale_for_clip_target(vector, to_center, &matrix, true, right));
        }
        if top > 0.0 {
            keep_smallest_scale(&mut smallest, globe_scale_for_clip_target(vector, to_center, &matrix, false, top));
        }
        if bottom < 0.0 {
            keep_smallest_scale(&mut smallest, globe_scale_for_clip_target(vector, to_center, &matrix, false, bottom));
        }
    }
    if !smallest.is_finite() || smallest == 0.0 {
        tracing::warn!(target: log_target::GENERAL, "Unable to fit the bounds on the globe; keeping the flat fit.");
        return Ok(fit);
    }
    Ok(CameraOptions {
        zoom: Some(mln_style::math::clamp_f64(
            f64::min(globe.view().zoom() + scale_zoom(smallest), max_zoom),
            state.min_zoom(),
            state.limits().max_zoom,
        )),
        ..fit
    })
}

/// The bounds of the locations at the corners of `transform`'s view, for a
/// world that doesn't wrap, where north needn't be up and the view's
/// north-west corner needn't be the area's. Fails as
/// `Map::lat_lng_bounds_for_camera` does.
fn corner_bounds(transform: &Transform) -> Result<LatLngBounds, Error> {
    let size = transform.state().view().size();
    let (width, height) = (f64::from(size.width), f64::from(size.height));
    let at = |x: f64, y: f64| transform.screen_coordinate_to_lat_lng(&ScreenCoordinate::new(x, y), WrapMode::Unwrapped);
    let mut bounds = LatLngBounds::hull(at(0.0, 0.0)?, at(width, height)?);
    bounds.extend(&at(width, 0.0)?);
    bounds.extend(&at(0.0, height)?);
    Ok(bounds)
}

/// The bounds the globe shows: the farthest of eight edge points on each side
/// of the center, where points off the planet fall on its horizon, widened to
/// every longitude when a pole is on screen. Fails as
/// `Map::lat_lng_bounds_for_camera` does.
fn globe_bounds(transform: &Transform) -> Result<LatLngBounds, Error> {
    let width = f64::from(transform.state().view().size().width);
    let height = f64::from(transform.state().view().size().height);
    let center = transform.view().center(WrapMode::Wrapped);
    let mut west = 0.0;
    let mut east = 0.0;
    let mut south = 0.0;
    let mut north = 0.0;
    for point in [
        ScreenCoordinate::new(0.0, 0.0),
        ScreenCoordinate::new(width / 2.0, 0.0),
        ScreenCoordinate::new(width, 0.0),
        ScreenCoordinate::new(width, height / 2.0),
        ScreenCoordinate::new(width, height),
        ScreenCoordinate::new(width / 2.0, height),
        ScreenCoordinate::new(0.0, height),
        ScreenCoordinate::new(0.0, height / 2.0),
    ] {
        let lat_lng = transform.screen_coordinate_to_lat_lng(&point, WrapMode::Wrapped)?;
        let longitude =
            VerticalPerspectiveProjection::difference_of_angles_degrees(center.longitude(), lat_lng.longitude());
        let latitude =
            VerticalPerspectiveProjection::difference_of_angles_degrees(center.latitude(), lat_lng.latitude());
        west = f64::min(west, longitude);
        east = f64::max(east, longitude);
        south = f64::min(south, latitude);
        north = f64::max(north, latitude);
    }
    west += center.longitude();
    east += center.longitude();
    south += center.latitude();
    north += center.latitude();

    let on_screen = |pole: &LatLng| {
        // In front of the camera and inside its depth range.
        let (_, clip) =
            VerticalPerspectiveProjection::lat_lng_to_screen_coordinate(transform.state().view(), pole, 0.0);
        if clip[3] <= 0.0 || (clip[2] / clip[3]).abs() >= 1.0 {
            return false;
        }
        let point = transform.lat_lng_to_screen_coordinate(pole);
        !transform.state().view().is_location_occluded(pole)
            && point.x > 0.0
            && point.x < width
            && point.y > 0.0
            && point.y < height
    };
    if on_screen(&LatLng::new(90.0, 0.0)?) {
        north = 90.0;
        west = -180.0;
        east = 180.0;
    }
    if on_screen(&LatLng::new(-90.0, 0.0)?) {
        south = -90.0;
        west = -180.0;
        east = 180.0;
    }
    Ok(LatLngBounds::hull(LatLng::new(south, west)?, LatLng::new(north, east)?))
}