Skip to main content

mln_engine/camera/
ground.rs

1//! Where a line of sight meets the ground a frame drew.
2
3use geometry::Point;
4use glam::{DVec2, DVec3};
5use mln_style::constants::{LATITUDE_MAX, TILE_SIZE_D};
6use mln_style::error::Error;
7use mln_style::geo::{LatLng, WrapMode};
8
9use crate::camera::vertical_perspective_projection::VerticalPerspectiveProjection;
10use crate::camera::{Elevation, View};
11use crate::geo::ScreenCoordinate;
12use crate::geo::projection::Projection;
13
14/// How far apart, in pixels at the zoom across the ground, a ray samples the
15/// ground, and the most samples it takes (GL JS's `raycastTerrain`).
16const STEP_PX: f64 = 4.0;
17const MAX_SAMPLES: u32 = 512;
18
19/// How near, in pixels at the zoom across the ground, bisection brings a
20/// hit, in at most [`MAX_BISECTIONS`] steps.
21const BISECTION_PX: f64 = 1e-3;
22const MAX_BISECTIONS: u32 = 40;
23
24/// How far above the surface a point still counts as on it, in meters.
25const HIT_EPSILON: f64 = 1e-6;
26
27/// How far, in meters, a ray looks past the snapshot's lowest and highest
28/// ground, which keeps the band open over flat ground.
29const BAND_PADDING: f64 = 10.0;
30
31/// A point of the ground a frame drew.
32#[derive(Clone, Copy, Debug, PartialEq)]
33pub struct GroundHit {
34    /// Its Web Mercator point at zoom 0 (from 0 to 1 across, y south), with
35    /// x in the world copy the view shows it in. On a globe's polar cap y is
36    /// past 0 or 1.
37    pub world: DVec2,
38    /// The height of the surface there, in meters with the terrain's
39    /// exaggeration ([`Elevation::surface_at`]).
40    pub height: f64,
41}
42
43impl GroundHit {
44    /// Its location, in the world copy of [`world`](Self::world) unless
45    /// `wrap_mode` wraps it.
46    #[must_use]
47    pub fn location(&self, wrap_mode: WrapMode) -> LatLng {
48        let world = Point::new(self.world.x, self.world.y);
49        // A finite point of the world always has a location.
50        Projection::unproject(&world, 1.0 / TILE_SIZE_D, wrap_mode).unwrap_or_default()
51    }
52}
53
54impl View {
55    /// Where the line of sight through `point`, measured from the bottom
56    /// edge (y up), first enters `ground` from above, between the near and
57    /// far planes; a line that starts under the ground finds where it next
58    /// enters it (GL JS's `raycastTerrain`). It samples the surface the
59    /// frame drew ([`Elevation::surface_at`]) every 4 pixels across the
60    /// ground within the band of its heights, at most 512 times, which a
61    /// long line spaces closer near the eye, and bisects the first step
62    /// that ends under the ground. On the globe the band lies between the
63    /// spheres of the lowest and highest heights and sea level, a point's
64    /// height is measured up its vertical from the sea-level sphere, and the
65    /// hit's [`world`](GroundHit::world) is in the world copy nearest the
66    /// view's center; past the Mercator range, where the globe closes its
67    /// poles at sea level, the ground is at sea level wherever the tile at
68    /// the range's edge below it drew. `None` where the line meets no drawn
69    /// ground, and while the view shows nothing.
70    #[must_use]
71    pub fn ground_under(&self, point: &ScreenCoordinate, ground: &dyn Elevation) -> Option<GroundHit> {
72        if self.is_globe() {
73            return self.ground_under_on_globe(point, ground);
74        }
75        let (near, far) = self.line_of_sight(point)?;
76        self.ground_along(near, far, ground)
77    }
78
79    /// The location that `point`, measured from the bottom edge (y up),
80    /// shows over terrain: where its line of sight first meets `ground`
81    /// ([`ground_under`](Self::ground_under)). Where it meets none, as in
82    /// the sky or past the ground drawn, the plane at the center's altitude
83    /// stands in for the ground, on the globe the sphere
84    /// ([`screen_coordinate_to_lat_lng_at`](Self::screen_coordinate_to_lat_lng_at)).
85    /// Fails as [`screen_coordinate_to_lat_lng`](Self::screen_coordinate_to_lat_lng).
86    pub fn screen_coordinate_to_lat_lng_on(
87        &self,
88        point: &ScreenCoordinate,
89        ground: &dyn Elevation,
90        wrap_mode: WrapMode,
91    ) -> Result<LatLng, Error> {
92        match self.ground_under(point, ground) {
93            Some(hit) => Ok(hit.location(wrap_mode)),
94            None => self.screen_coordinate_to_lat_lng_at(point, self.center_altitude(), wrap_mode),
95        }
96    }
97
98    /// The screen point (y up) of `lat_lng` standing on `ground`: at the
99    /// height the ground was drawn at there, read in the world copy nearest
100    /// the center, or at the center's altitude where none was drawn, the
101    /// height [`screen_coordinate_to_lat_lng_on`] falls back to. On the
102    /// globe, past the Mercator range, the ground stands at sea level, as
103    /// [`ground_under`](Self::ground_under) meets it.
104    ///
105    /// [`screen_coordinate_to_lat_lng_on`]: Self::screen_coordinate_to_lat_lng_on
106    #[must_use]
107    pub fn lat_lng_to_screen_coordinate_on(&self, lat_lng: &LatLng, ground: &dyn Elevation) -> ScreenCoordinate {
108        let height = self.drawn_height_at(lat_lng, ground);
109        self.lat_lng_to_screen_coordinate_at(lat_lng, height.unwrap_or_else(|| self.center_altitude()))
110    }
111
112    /// The height `ground` was drawn at, at `lat_lng`, read in the world
113    /// copy nearest the center: on the globe, past the Mercator range, the
114    /// sea-level polar caps. `None` where no ground was drawn there, though
115    /// the camera may stand on ground under its center that wasn't drawn
116    /// ([`Elevation::at`]).
117    #[must_use]
118    pub fn drawn_height_at(&self, lat_lng: &LatLng, ground: &dyn Elevation) -> Option<f64> {
119        let near = self.lat_lng_near_center(lat_lng);
120        if self.is_globe() && near.latitude().abs() > LATITUDE_MAX {
121            return Some(0.0);
122        }
123        let world = Projection::project(&near, 1.0 / TILE_SIZE_D);
124        ground.surface_at(DVec2::new(world.x, world.y))
125    }
126
127    /// [`ground_under`](Self::ground_under) on the globe, in unit-sphere
128    /// space.
129    fn ground_under_on_globe(&self, point: &ScreenCoordinate, ground: &dyn Elevation) -> Option<GroundHit> {
130        let size = self.size();
131        if size.is_empty() {
132            return None;
133        }
134        // The band holds sea level, where the globe closes its poles.
135        let (low, high) = ground.range()?;
136        let radius = |height: f64| 1.0 + height / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS;
137        let (low, high) = (radius(low.min(0.0) - BAND_PADDING), radius(high.max(0.0) + BAND_PADDING));
138
139        // The line of sight from the near plane to the far plane.
140        let inverse = self.inverse_globe_view_projection_matrix();
141        let ndc = DVec2::new(point.x / f64::from(size.width) * 2.0 - 1.0, point.y / f64::from(size.height) * 2.0 - 1.0);
142        let near = inverse.project_point3(ndc.extend(-1.0));
143        let along = inverse.project_point3(ndc.extend(1.0)) - near;
144        if !(near.is_finite() && along.is_finite()) {
145            return None;
146        }
147
148        // The stretch of it within the shell of the ground's heights: from
149        // where it enters the outer sphere, or the near plane inside it, to
150        // where it enters the inner sphere, or else leaves the outer one.
151        let (outer_in, outer_out) = sphere_crossings(near, along, high)?;
152        let start = outer_in.max(0.0);
153        let end = sphere_crossings(near, along, low).map_or(outer_out, |(inner_in, _)| inner_in).min(1.0);
154        if start >= end {
155            return None;
156        }
157
158        let point_at = |t: f64| near + along * t;
159        let sample = |t: f64| {
160            let world = VerticalPerspectiveProjection::sphere_point_to_world(self, point_at(t))?;
161            // A polar cap draws at sea level where the tile at the edge of
162            // Web Mercator's square below it drew.
163            let edge = DVec2::new(world.x, world.y.clamp(0.0, 1.0));
164            let surface = ground.surface_at(edge)?;
165            Some((world, if edge.y == world.y { surface } else { 0.0 }))
166        };
167        // The ground the band spans, from the directions of its ends.
168        let globe_radius = VerticalPerspectiveProjection::globe_radius_pixels(
169            Projection::world_size(self.scale()),
170            self.center(WrapMode::Unwrapped).latitude(),
171        );
172        let band_px = (point_at(start).normalize() - point_at(end).normalize()).length() * globe_radius;
173        march(start, end, band_px / STEP_PX, BISECTION_PX * (end - start) / band_px, sample)
174    }
175
176    /// Where the line from `near` to `far`, each a Web Mercator point at
177    /// zoom 0 (x in the world copy the view shows it in) and a height in
178    /// meters, first enters `ground` from above, as
179    /// [`ground_under`](Self::ground_under) finds it on a line of sight,
180    /// sampling every 4 pixels across the ground at the view's zoom. `None`
181    /// where the line meets no drawn ground.
182    #[must_use]
183    pub fn ground_along(&self, near: DVec3, far: DVec3, ground: &dyn Elevation) -> Option<GroundHit> {
184        let (low, high) = ground.range()?;
185        let (low, high) = (low - BAND_PADDING, high + BAND_PADDING);
186        let along = far - near;
187
188        // The stretch of the line within the band of the ground's heights.
189        let (start, end) = if along.z == 0.0 {
190            if near.z < low || near.z > high {
191                return None;
192            }
193            (0.0, 1.0)
194        } else {
195            let (to_high, to_low) = ((high - near.z) / along.z, (low - near.z) / along.z);
196            let (start, end) = (to_high.min(to_low).max(0.0), to_high.max(to_low).min(1.0));
197            if start > end {
198                return None;
199            }
200            (start, end)
201        };
202
203        let point_at = |t: f64| near + along * t;
204        let sample = |t: f64| {
205            let point = point_at(t);
206            Some((point, ground.surface_at(point.truncate())?))
207        };
208        let length_px = along.truncate().length() * Projection::world_size(self.scale());
209        march(start, end, length_px * (end - start) / STEP_PX, BISECTION_PX / length_px, sample)
210    }
211}
212
213/// Where a line, from `start` to `end` of its parameter, first enters the
214/// ground from above, or next enters it where it starts under it: `sample`
215/// gives the line's Web Mercator point at zoom 0 and height in meters at a
216/// parameter, with the surface's height there, or `None` where no ground
217/// was drawn. It samples the line `steps` times, at most 512, spaced closer
218/// toward `start` where it would take more, and bisects the first step that
219/// ends under the ground to within `tolerance` of the parameter.
220fn march(
221    start: f64,
222    end: f64,
223    steps: f64,
224    tolerance: f64,
225    sample: impl Fn(f64) -> Option<(DVec3, f64)>,
226) -> Option<GroundHit> {
227    let surface = |t: f64| sample(t).map(|(_, surface)| surface);
228    let below = |t: f64| sample(t).is_some_and(|(point, surface)| point.z <= surface + HIT_EPSILON);
229
230    let steps = steps.ceil();
231    let samples = steps.clamp(1.0, f64::from(MAX_SAMPLES)) as u32;
232    let capped = steps > f64::from(MAX_SAMPLES);
233    let at = |i: u32| {
234        let f = f64::from(i) / f64::from(samples);
235        start + (end - start) * if capped { f * f } else { f }
236    };
237
238    let mut above = !below(start);
239    let mut previous = start;
240    for i in 1..=samples {
241        let t = at(i);
242        if !above {
243            above = !below(t);
244        } else if below(t) {
245            let (mut lo, mut hi) = (previous, t);
246            // A line that runs straight down needs no bisection: its surface
247            // doesn't change along it.
248            for _ in 0..MAX_BISECTIONS {
249                if hi - lo <= tolerance {
250                    break;
251                }
252                let mid = f64::midpoint(lo, hi);
253                if below(mid) {
254                    hi = mid;
255                } else {
256                    lo = mid;
257                }
258            }
259            // `hi` is under drawn ground.
260            let height_at = |t: f64| sample(t).map_or(f64::NAN, |(point, _)| point.z);
261            let (t, height) =
262                refine(lo, hi, height_at, surface).unwrap_or_else(|| (hi, surface(hi).unwrap_or_default()));
263            let point = sample(t).map_or(DVec3::NAN, |(point, _)| point);
264            return Some(GroundHit { world: point.truncate(), height });
265        }
266        previous = t;
267    }
268    None
269}
270
271/// Where a line from `origin` along `along` crosses the sphere of `radius`
272/// about the planet's center, in units of `along`: where it goes in and
273/// where it comes out, `None` where it misses.
274fn sphere_crossings(origin: DVec3, along: DVec3, radius: f64) -> Option<(f64, f64)> {
275    let a = along.length_squared();
276    let b = origin.dot(along);
277    // The line's nearest point to the center, then the half chord either side
278    // of it, which stays exact where |origin| is near `radius`.
279    let nearest = -b / a;
280    let closest = origin + along * nearest;
281    let half_chord_sq = (radius * radius - closest.length_squared()) / a;
282    if half_chord_sq.is_nan() || half_chord_sq < 0.0 {
283        return None;
284    }
285    let half_chord = half_chord_sq.sqrt();
286    Some((nearest - half_chord, nearest + half_chord))
287}
288
289/// Where between `lo`, above the ground, and `hi`, under it, a line of
290/// heights `z` crosses the `surface`, taking both as straight between them,
291/// and the surface's height there; `None` where the surface isn't drawn at
292/// `lo` or where it would be.
293fn refine(lo: f64, hi: f64, z: impl Fn(f64) -> f64, surface: impl Fn(f64) -> Option<f64>) -> Option<(f64, f64)> {
294    let over_lo = z(lo) - surface(lo)?;
295    let over_hi = z(hi) - surface(hi)?;
296    let t = if over_lo > over_hi { (lo + over_lo * (hi - lo) / (over_lo - over_hi)).clamp(lo, hi) } else { hi };
297    Some((t, surface(t)?))
298}
299
300#[cfg(test)]
301#[path = "ground_test.rs"]
302mod ground_test;