use geometry::Point;
use glam::{DVec2, DVec3};
use mln_style::constants::{LATITUDE_MAX, TILE_SIZE_D};
use mln_style::error::Error;
use mln_style::geo::{LatLng, WrapMode};
use crate::camera::vertical_perspective_projection::VerticalPerspectiveProjection;
use crate::camera::{Elevation, View};
use crate::geo::ScreenCoordinate;
use crate::geo::projection::Projection;
const STEP_PX: f64 = 4.0;
const MAX_SAMPLES: u32 = 512;
const BISECTION_PX: f64 = 1e-3;
const MAX_BISECTIONS: u32 = 40;
const HIT_EPSILON: f64 = 1e-6;
const BAND_PADDING: f64 = 10.0;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GroundHit {
pub world: DVec2,
pub height: f64,
}
impl GroundHit {
#[must_use]
pub fn location(&self, wrap_mode: WrapMode) -> LatLng {
let world = Point::new(self.world.x, self.world.y);
Projection::unproject(&world, 1.0 / TILE_SIZE_D, wrap_mode).unwrap_or_default()
}
}
impl View {
#[must_use]
pub fn ground_under(&self, point: &ScreenCoordinate, ground: &dyn Elevation) -> Option<GroundHit> {
if self.is_globe() {
return self.ground_under_on_globe(point, ground);
}
let (near, far) = self.line_of_sight(point)?;
self.ground_along(near, far, ground)
}
pub fn screen_coordinate_to_lat_lng_on(
&self,
point: &ScreenCoordinate,
ground: &dyn Elevation,
wrap_mode: WrapMode,
) -> Result<LatLng, Error> {
match self.ground_under(point, ground) {
Some(hit) => Ok(hit.location(wrap_mode)),
None => self.screen_coordinate_to_lat_lng_at(point, self.center_altitude(), wrap_mode),
}
}
#[must_use]
pub fn lat_lng_to_screen_coordinate_on(&self, lat_lng: &LatLng, ground: &dyn Elevation) -> ScreenCoordinate {
let height = self.drawn_height_at(lat_lng, ground);
self.lat_lng_to_screen_coordinate_at(lat_lng, height.unwrap_or_else(|| self.center_altitude()))
}
#[must_use]
pub fn drawn_height_at(&self, lat_lng: &LatLng, ground: &dyn Elevation) -> Option<f64> {
let near = self.lat_lng_near_center(lat_lng);
if self.is_globe() && near.latitude().abs() > LATITUDE_MAX {
return Some(0.0);
}
let world = Projection::project(&near, 1.0 / TILE_SIZE_D);
ground.surface_at(DVec2::new(world.x, world.y))
}
fn ground_under_on_globe(&self, point: &ScreenCoordinate, ground: &dyn Elevation) -> Option<GroundHit> {
let size = self.size();
if size.is_empty() {
return None;
}
let (low, high) = ground.range()?;
let radius = |height: f64| 1.0 + height / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS;
let (low, high) = (radius(low.min(0.0) - BAND_PADDING), radius(high.max(0.0) + BAND_PADDING));
let inverse = self.inverse_globe_view_projection_matrix();
let ndc = DVec2::new(point.x / f64::from(size.width) * 2.0 - 1.0, point.y / f64::from(size.height) * 2.0 - 1.0);
let near = inverse.project_point3(ndc.extend(-1.0));
let along = inverse.project_point3(ndc.extend(1.0)) - near;
if !(near.is_finite() && along.is_finite()) {
return None;
}
let (outer_in, outer_out) = sphere_crossings(near, along, high)?;
let start = outer_in.max(0.0);
let end = sphere_crossings(near, along, low).map_or(outer_out, |(inner_in, _)| inner_in).min(1.0);
if start >= end {
return None;
}
let point_at = |t: f64| near + along * t;
let sample = |t: f64| {
let world = VerticalPerspectiveProjection::sphere_point_to_world(self, point_at(t))?;
let edge = DVec2::new(world.x, world.y.clamp(0.0, 1.0));
let surface = ground.surface_at(edge)?;
Some((world, if edge.y == world.y { surface } else { 0.0 }))
};
let globe_radius = VerticalPerspectiveProjection::globe_radius_pixels(
Projection::world_size(self.scale()),
self.center(WrapMode::Unwrapped).latitude(),
);
let band_px = (point_at(start).normalize() - point_at(end).normalize()).length() * globe_radius;
march(start, end, band_px / STEP_PX, BISECTION_PX * (end - start) / band_px, sample)
}
#[must_use]
pub fn ground_along(&self, near: DVec3, far: DVec3, ground: &dyn Elevation) -> Option<GroundHit> {
let (low, high) = ground.range()?;
let (low, high) = (low - BAND_PADDING, high + BAND_PADDING);
let along = far - near;
let (start, end) = if along.z == 0.0 {
if near.z < low || near.z > high {
return None;
}
(0.0, 1.0)
} else {
let (to_high, to_low) = ((high - near.z) / along.z, (low - near.z) / along.z);
let (start, end) = (to_high.min(to_low).max(0.0), to_high.max(to_low).min(1.0));
if start > end {
return None;
}
(start, end)
};
let point_at = |t: f64| near + along * t;
let sample = |t: f64| {
let point = point_at(t);
Some((point, ground.surface_at(point.truncate())?))
};
let length_px = along.truncate().length() * Projection::world_size(self.scale());
march(start, end, length_px * (end - start) / STEP_PX, BISECTION_PX / length_px, sample)
}
}
fn march(
start: f64,
end: f64,
steps: f64,
tolerance: f64,
sample: impl Fn(f64) -> Option<(DVec3, f64)>,
) -> Option<GroundHit> {
let surface = |t: f64| sample(t).map(|(_, surface)| surface);
let below = |t: f64| sample(t).is_some_and(|(point, surface)| point.z <= surface + HIT_EPSILON);
let steps = steps.ceil();
let samples = steps.clamp(1.0, f64::from(MAX_SAMPLES)) as u32;
let capped = steps > f64::from(MAX_SAMPLES);
let at = |i: u32| {
let f = f64::from(i) / f64::from(samples);
start + (end - start) * if capped { f * f } else { f }
};
let mut above = !below(start);
let mut previous = start;
for i in 1..=samples {
let t = at(i);
if !above {
above = !below(t);
} else if below(t) {
let (mut lo, mut hi) = (previous, t);
for _ in 0..MAX_BISECTIONS {
if hi - lo <= tolerance {
break;
}
let mid = f64::midpoint(lo, hi);
if below(mid) {
hi = mid;
} else {
lo = mid;
}
}
let height_at = |t: f64| sample(t).map_or(f64::NAN, |(point, _)| point.z);
let (t, height) =
refine(lo, hi, height_at, surface).unwrap_or_else(|| (hi, surface(hi).unwrap_or_default()));
let point = sample(t).map_or(DVec3::NAN, |(point, _)| point);
return Some(GroundHit { world: point.truncate(), height });
}
previous = t;
}
None
}
fn sphere_crossings(origin: DVec3, along: DVec3, radius: f64) -> Option<(f64, f64)> {
let a = along.length_squared();
let b = origin.dot(along);
let nearest = -b / a;
let closest = origin + along * nearest;
let half_chord_sq = (radius * radius - closest.length_squared()) / a;
if half_chord_sq.is_nan() || half_chord_sq < 0.0 {
return None;
}
let half_chord = half_chord_sq.sqrt();
Some((nearest - half_chord, nearest + half_chord))
}
fn refine(lo: f64, hi: f64, z: impl Fn(f64) -> f64, surface: impl Fn(f64) -> Option<f64>) -> Option<(f64, f64)> {
let over_lo = z(lo) - surface(lo)?;
let over_hi = z(hi) - surface(hi)?;
let t = if over_lo > over_hi { (lo + over_lo * (hi - lo) / (over_lo - over_hi)).clamp(lo, hi) } else { hi };
Some((t, surface(t)?))
}
#[cfg(test)]
#[path = "ground_test.rs"]
mod ground_test;