1use 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
14const STEP_PX: f64 = 4.0;
17const MAX_SAMPLES: u32 = 512;
18
19const BISECTION_PX: f64 = 1e-3;
22const MAX_BISECTIONS: u32 = 40;
23
24const HIT_EPSILON: f64 = 1e-6;
26
27const BAND_PADDING: f64 = 10.0;
30
31#[derive(Clone, Copy, Debug, PartialEq)]
33pub struct GroundHit {
34 pub world: DVec2,
38 pub height: f64,
41}
42
43impl GroundHit {
44 #[must_use]
47 pub fn location(&self, wrap_mode: WrapMode) -> LatLng {
48 let world = Point::new(self.world.x, self.world.y);
49 Projection::unproject(&world, 1.0 / TILE_SIZE_D, wrap_mode).unwrap_or_default()
51 }
52}
53
54impl View {
55 #[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 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 #[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 #[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 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 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 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 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 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 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 #[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 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
213fn 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 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 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
271fn sphere_crossings(origin: DVec3, along: DVec3, radius: f64) -> Option<(f64, f64)> {
275 let a = along.length_squared();
276 let b = origin.dot(along);
277 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
289fn 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;