mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! The ground a frame drew, as the map's camera reads it.

use std::fmt;
use std::sync::Arc;

use glam::{DVec2, DVec3, Vec2};
use mln_style::bitmap::PremultipliedImage;
use mln_style::crs::WorldMapping;
use mln_style::geo::{LatLng, WrapMode};
use mln_style::geometry::Point;
use mln_style::hash::HashMap;
use mln_style::sort;
use mln_style::tile_id::CanonicalTileID;

use crate::camera::{Elevation, TileCoordinate, TileProjector, VerticalPerspectiveProjection, View};
use crate::geo::ScreenCoordinate;
use crate::render::terrain::cover::{TerrainCover, dem_contents, place_in, world_copy};
use crate::tile::dem::{self, DemCoords, DemUnpack};
use crate::tile::{OverscaledTileID, UnwrappedTileID};
use crate::tile_store::dem::DemContents;
use crate::tile_store::source_tiles::SourceTiles;

/// The DEM a terrain tile drew with.
struct DrawnDem {
    /// The DEM tile it read.
    id: OverscaledTileID,
    /// The DEM tile's bordered image, `dim + 2` texels a side.
    image: Arc<PremultipliedImage>,
    dim: u32,
    coords: DemCoords,
    /// The lowest and highest heights of the DEM tile's own pixels, in
    /// meters, not exaggerated.
    min: f32,
    max: f32,
}

/// A terrain tile as a frame drew it.
struct DrawnTile {
    id: OverscaledTileID,
    dem: Option<DrawnDem>,
    /// Whether the frame drew it: all but the tile under the center that
    /// the cover keeps undrawn ([`TerrainCover::center`]).
    drawn: bool,
}

/// The terrain's tiles as a frame drew them, with the DEM data each read,
/// sampled by the height rule the shaders follow, and the finest DEM data
/// loaded, which the map's camera stands on and keeps its eye above, the
/// same whichever camera drew the frame. It shares the DEM tiles' images, which
/// don't change once shared.
///
/// Outside the engine it is a read-only height lookup: through
/// [`Elevation`], or under a tile's points ([`TileGround`]).
pub struct TerrainElevation {
    /// Nearest the center first, then the tile under the center when none
    /// drew there ([`TerrainCover::center`]).
    tiles: Vec<DrawnTile>,
    /// The zoom levels of the drawn tiles, finest first.
    zooms: Vec<u8>,
    /// Where each drawn tile is in `tiles`, the first of its world copies,
    /// which all read the same DEM.
    index: HashMap<CanonicalTileID, usize>,
    /// Where each drawn tile is in `tiles`, by its world copy.
    copies: HashMap<UnwrappedTileID, usize>,
    /// [`Elevation::range`]'s.
    range: Option<(f64, f64)>,
    unpack: DemUnpack,
    exaggeration: f32,
    /// How the map's lng/lat maps to the world square the tiles are in.
    world: WorldMapping,
    /// The DEM tiles with data that the terrain's source held when this
    /// ground was made, drawn or not, by their id, and their zoom levels,
    /// finest first ([`Elevation::clearance_at`]).
    clearance: HashMap<CanonicalTileID, (Arc<PremultipliedImage>, u32)>,
    clearance_zooms: Vec<u8>,
}

impl fmt::Debug for TerrainElevation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TerrainElevation")
            .field("tiles", &self.tiles.len())
            .field("unpack", &self.unpack)
            .field("exaggeration", &self.exaggeration)
            .finish_non_exhaustive()
    }
}

/// The DEM that a tile of `cover` bound, as `dem`, the terrain source's
/// tiles, hold it.
fn drawn_dem(dem: Option<&SourceTiles>, bound: Option<(OverscaledTileID, DemCoords)>) -> Option<DrawnDem> {
    let (id, coords) = bound?;
    let data = dem_contents(dem?.tile(&id)?)?.dem();
    let dim = u32::try_from(data.dim).ok()?;
    let (min, max) = data.range();
    Some(DrawnDem { id, image: Arc::clone(data.shared_image()), dim, coords, min, max })
}

impl TerrainElevation {
    /// The ground of the tiles of `cover`, as they bound their DEM from
    /// `dem`, the terrain source's tiles, decoded by `unpack` and raised by
    /// `exaggeration`.
    pub(crate) fn new(
        cover: &TerrainCover,
        dem: Option<&SourceTiles>,
        unpack: DemUnpack,
        exaggeration: f32,
    ) -> TerrainElevation {
        let drawn = cover.tiles.iter().map(|tile| (tile, true));
        let tiles: Vec<DrawnTile> = drawn
            .chain(cover.center.iter().map(|tile| (tile, false)))
            .map(|(tile, drawn)| DrawnTile { id: tile.id, dem: drawn_dem(dem, tile.dem), drawn })
            .collect();
        TerrainElevation::of_drawn(tiles, unpack, exaggeration, cover.world.clone())
    }

    /// The ground of a frame that drew `tile` alone, over `dem`, the DEM
    /// of `dem_id`, the tile or one of its ancestors, raised by
    /// `exaggeration`.
    #[cfg(feature = "bench")]
    pub(crate) fn of_tile(
        tile: OverscaledTileID,
        dem_id: OverscaledTileID,
        dem: &crate::tile::dem_data::DEMData,
        exaggeration: f32,
    ) -> Self {
        let (min, max) = dem.range();
        let image = Arc::clone(dem.shared_image());
        let dim = u32::try_from(dem.dim).unwrap_or(0);
        let dz = tile.canonical.z.saturating_sub(dem_id.canonical.z);
        let (tiles, mask) = ((1u32 << dz) as f32, (1u32 << dz) - 1);
        let (x, y) = ((tile.canonical.x & mask) as f32, (tile.canonical.y & mask) as f32);
        let coords = DemCoords { scale: 1.0 / tiles, offset: [x / tiles, y / tiles] };
        let dem_tile = DrawnDem { id: dem_id, image, dim, coords, min, max };
        let tiles = vec![DrawnTile { id: tile, dem: Some(dem_tile), drawn: true }];
        TerrainElevation::of_drawn(tiles, DemUnpack::of(dem.encoding), exaggeration, WorldMapping::default())
    }

    /// The ground of `tiles`, nearest the center first, decoded by `unpack`
    /// and raised by `exaggeration`, in the world square of `world`.
    fn of_drawn(tiles: Vec<DrawnTile>, unpack: DemUnpack, exaggeration: f32, world: WorldMapping) -> TerrainElevation {
        let mut index = HashMap::default();
        let mut copies = HashMap::default();
        let mut zooms = Vec::new();
        let mut range: Option<(f64, f64)> = None;
        for (at, tile) in tiles.iter().enumerate().filter(|(_, tile)| tile.drawn) {
            index.entry(tile.id.canonical).or_insert(at);
            copies.insert(tile.id.to_unwrapped(), at);
            if !zooms.contains(&tile.id.canonical.z) {
                zooms.push(tile.id.canonical.z);
            }
            let (min, max) = tile.dem.as_ref().map_or((0.0, 0.0), |dem| {
                let (min, max) = (f64::from(dem.min * exaggeration), f64::from(dem.max * exaggeration));
                (min.min(max), min.max(max))
            });
            range = Some(range.map_or((min, max), |(low, high)| (low.min(min), high.max(max))));
        }
        sort::sort_by(&mut zooms, |a, b| b.cmp(a));
        let (clearance, clearance_zooms) = (HashMap::default(), Vec::new());
        TerrainElevation { tiles, zooms, index, copies, range, unpack, exaggeration, world, clearance, clearance_zooms }
    }

    /// This ground, with the DEM tiles with data that `dem`, the terrain's
    /// source's tiles, holds, drawn or not, for [`Elevation::clearance_at`].
    pub(crate) fn with_clearance(mut self, dem: Option<&SourceTiles>) -> TerrainElevation {
        for slot in dem.into_iter().flat_map(SourceTiles::slots) {
            let Some(data) = dem_contents(&slot.tile).map(DemContents::dem) else { continue };
            let Ok(dim) = u32::try_from(data.dim) else { continue };
            let id = slot.tile.id.canonical;
            self.clearance.entry(id).or_insert_with(|| (Arc::clone(data.shared_image()), dim));
            if !self.clearance_zooms.contains(&id.z) {
                self.clearance_zooms.push(id.z);
            }
        }
        sort::sort_by(&mut self.clearance_zooms, |a, b| b.cmp(a));
        self
    }

    /// The height at `world` of the finest DEM tile of the clearance's
    /// that has it.
    fn finest_height(&self, world: DVec2) -> Option<f64> {
        self.clearance_zooms.iter().find_map(|&z| {
            let tiles = 1u32 << z;
            let x = world_copy(world.x).1 * f64::from(tiles);
            let y = world.y.clamp(0.0, 1.0) * f64::from(tiles);
            let (column, row) = (x.floor().min(f64::from(tiles - 1)), y.floor().min(f64::from(tiles - 1)));
            let id = CanonicalTileID::new(z, column as u32, row as u32);
            let (image, dim) = self.clearance.get(&id)?;
            let uv = [(x - column) as f32, (y - row) as f32];
            Some(dem_height(image, *dim, DemCoords::OWN, uv, self.unpack, self.exaggeration))
        })
    }

    /// Whether `other` is the same ground: the same tiles, drawn or kept
    /// under the center, reading the same DEM images in the same places,
    /// decoded and raised alike.
    pub(crate) fn draws_as(&self, other: &TerrainElevation) -> bool {
        // A DEM image this holds can't be freed and its address reused, and
        // one that changes after it is shared is copied first, so equal
        // addresses are equal images.
        let same_dem =
            |a: &DrawnDem, b: &DrawnDem| a.id == b.id && a.coords == b.coords && Arc::ptr_eq(&a.image, &b.image);
        let same_tile = |a: &DrawnTile, b: &DrawnTile| {
            a.id == b.id
                && a.drawn == b.drawn
                && match (&a.dem, &b.dem) {
                    (None, None) => true,
                    (Some(a), Some(b)) => same_dem(a, b),
                    _ => false,
                }
        };
        self.unpack == other.unpack
            && self.exaggeration == other.exaggeration
            && self.world == other.world
            && self.tiles.len() == other.tiles.len()
            && self.tiles.iter().zip(&other.tiles).all(|(a, b)| same_tile(a, b))
    }

    /// The drawn tile at `world`, a Web Mercator point at zoom 0 whose y is
    /// within the world, and where in it, from 0 to 1 across, y down: the
    /// finest that has it ([`place_in`]'s, which puts a point on an edge
    /// between tiles in one of them). In `world`'s copy (`in_copy`), else in
    /// any copy: every world copy of a tile reads the same DEM.
    fn drawn_tile_at(&self, world: DVec2, in_copy: bool) -> Option<(&DrawnTile, [f32; 2])> {
        if !world.x.is_finite() {
            return None;
        }
        let (copy, x) = world_copy(world.x);
        // No tile is in a copy past the range of the wraps.
        let wrap = if in_copy { Some(i16::try_from(copy as i64).ok()?) } else { None };
        self.zooms.iter().find_map(|&z| {
            let tiles = f64::from(1u32 << z);
            let (u, v) = (x * tiles, world.y * tiles);
            // The world's bottom edge is in the last row's tiles.
            let (column, row) = (u.floor(), v.floor().min(tiles - 1.0));
            let canonical = CanonicalTileID::new(z, column as u32, row as u32);
            let at = match wrap {
                Some(wrap) => self.copies.get(&UnwrappedTileID::with_wrap(wrap, canonical)),
                None => self.index.get(&canonical),
            };
            Some((&self.tiles[*at?], [(u - column) as f32, (v - row) as f32]))
        })
    }

    /// The tile at `location`, and where in it: a drawn one, else the tile
    /// the cover keeps under the center. A world that doesn't wrap has no
    /// copies, and no ground outside its square.
    fn tile_at_location(&self, location: LatLng) -> Option<(&DrawnTile, [f32; 2])> {
        let world = self.world.world_from_lat_lng(&location);
        if !self.world.wraps() && (!(0.0..1.0).contains(&world.x) || !(0.0..=1.0).contains(&world.y)) {
            return None;
        }
        let world = DVec2::new(world.x, world.y.clamp(0.0, 1.0));
        self.drawn_tile_at(world, false).or_else(|| {
            let center = self.tiles.last().filter(|tile| !tile.drawn)?;
            let [u, v] = place_in(center.id.canonical, [world.x, world.y])?;
            Some((center, [u as f32, v as f32]))
        })
    }

    /// [`Elevation::at`] and [`Elevation::min_at`] as the tiles, scanned in
    /// order, give them, which the index must agree with.
    #[cfg(test)]
    pub(crate) fn scanned(&self, location: LatLng) -> (Option<f64>, Option<f64>) {
        let world = TileCoordinate::from_lat_lng(0.0, &location).p;
        let found = self.tiles.iter().find_map(|tile| {
            let [u, v] = place_in(tile.id.canonical, [world.x, world.y])?;
            Some((tile, [u as f32, v as f32]))
        });
        found.map_or((None, None), |(tile, uv)| (Some(self.height_of(tile, uv)), Some(self.min_of(tile))))
    }

    /// [`Elevation::surface_at`] as the drawn tiles of `world`'s copy,
    /// scanned in order, give it, which the index must agree with.
    #[cfg(test)]
    pub(crate) fn scanned_surface(&self, world: DVec2) -> Option<f64> {
        let copy = world_copy(world.x).0;
        let found = self.tiles.iter().filter(|tile| tile.drawn && f64::from(tile.id.wrap) == copy).find_map(|tile| {
            let [u, v] = place_in(tile.id.canonical, [world.x, world.y])?;
            Some((tile, [u as f32, v as f32]))
        });
        let (tile, uv) = found?;
        Some(self.height_of(tile, uv))
    }

    /// The height `tile` draws at `uv`: its DEM's, or sea level where it
    /// draws flat.
    fn height_of(&self, tile: &DrawnTile, uv: [f32; 2]) -> f64 {
        tile.dem.as_ref().map_or(0.0, |dem| self.height(dem, uv))
    }

    /// The lowest height of the DEM `tile` reads, 0 for none.
    fn min_of(&self, tile: &DrawnTile) -> f64 {
        tile.dem.as_ref().map_or(0.0, |dem| f64::from(dem.min * self.exaggeration))
    }

    /// The height that `dem` gives at `uv` by the height rule, in meters with
    /// the exaggeration.
    fn height(&self, dem: &DrawnDem, uv: [f32; 2]) -> f64 {
        dem_height(&dem.image, dem.dim, dem.coords, uv, self.unpack, self.exaggeration)
    }
}

/// The height, in meters raised by `exaggeration`, that the DEM of `dim`
/// pixels a side whose bordered image is `image` gives at `uv` through
/// `coords`, decoded by `unpack`: the height rule of `crate::tile::dem`, which
/// the shaders follow.
pub(crate) fn dem_height(
    image: &PremultipliedImage,
    dim: u32,
    coords: DemCoords,
    uv: [f32; 2],
    unpack: DemUnpack,
    exaggeration: f32,
) -> f64 {
    let stride = dim as usize + 2;
    let texel = |x: u32, y: u32| {
        let start = (y as usize * stride + x as usize) * 4;
        let texel: [u8; 4] = image.data[start..start + 4].try_into().unwrap_or_default();
        unpack.decode(texel)
    };
    f64::from(dem::sample(dim, coords, uv, texel) * exaggeration)
}

/// The ground under a tile's points, as a frame drew it: what the layers
/// whose points the CPU places, as symbols, stand on.
#[derive(Clone, Copy, Debug)]
pub struct TileGround<'a> {
    ground: &'a TerrainElevation,
    tile: UnwrappedTileID,
}

impl<'a> TileGround<'a> {
    /// The ground of `ground` under the points of `tile`.
    #[must_use]
    pub fn new(ground: &'a TerrainElevation, tile: UnwrappedTileID) -> Self {
        TileGround { ground, tile }
    }

    /// The height of the surface the frame drew at `point`, in `EXTENT`
    /// units of the tile, in meters with the exaggeration
    /// ([`Elevation::surface_at`]); 0 where none drew, as on flat ground. A
    /// point past the tile's edges reads the ground there.
    #[must_use]
    pub fn height(&self, point: Vec2) -> f32 {
        let tiles = f64::from(1u32 << self.tile.canonical.z);
        let extent = f64::from(mln_style::constants::EXTENT);
        let tile = DVec2::new(f64::from(self.tile.canonical.x), f64::from(self.tile.canonical.y));
        let world = (tile + point.as_dvec2() / extent) / tiles + DVec2::new(f64::from(self.tile.wrap), 0.0);
        self.ground.surface_at(world).unwrap_or(0.0) as f32
    }

    /// How much of what stands at `point`, in `EXTENT` units of the tile,
    /// `elevation` meters up, the ground in front of it leaves in `view`, as
    /// the shaders' `ground_visibility` fades it: 1 where it doesn't show,
    /// where no ground nearer the camera shows at its screen point, or where
    /// that point is outside the view, down to 0 where the nearest ground
    /// there is in front of it by their ramp of depth; where that leaves
    /// less than 0.95, averaged with the same test of the screen point 0.01
    /// clip units above. The line of sight is sampled every 4 pixels across
    /// the ground, at most 512 times, and the ground it first passes under
    /// found by bisection.
    #[must_use]
    pub fn visibility(&self, view: &View, point: Point<f64>, elevation: f64) -> f64 {
        let tile = self.tile;
        let projector = TileProjector::new(view, &tile);
        let drawn = projector.project_as_drawn(&point, elevation);
        let size = view.size();
        let (width, view_height) = (f64::from(size.width), f64::from(size.height));
        // Where the point draws on the screen, from its top left; clip
        // space's y goes up.
        let screen =
            ScreenCoordinate::new((drawn.point.x + 1.0) * width * 0.5, (1.0 - drawn.point.y) * view_height * 0.5);
        if drawn.occluded
            || drawn.signed_distance_from_camera <= 0.0
            || !(0.0..=width).contains(&screen.x)
            || !(0.0..=view_height).contains(&screen.y)
        {
            return 1.0;
        }

        // The line of sight, as a line from the point to the eye, or to where
        // the near plane cuts it, through Mercator's tile units and meters, or
        // through the globe's unit-sphere space; and its point at `t`, from 0
        // at the point to 1, as a point of the tile and a height.
        let extent = f64::from(mln_style::constants::EXTENT);
        let tiles = f64::from(1u32 << tile.canonical.z);
        let to_tile = |x: f64, y: f64| {
            [
                ((x - f64::from(tile.wrap)) * tiles - f64::from(tile.canonical.x)) * extent,
                (y * tiles - f64::from(tile.canonical.y)) * extent,
            ]
        };
        let point_x = (f64::from(tile.canonical.x) + point.x / extent) / tiles + f64::from(tile.wrap);
        let globe = view.is_globe();
        let (start, end) = if globe {
            let surface = VerticalPerspectiveProjection::tile_coordinates_to_sphere(&point, &tile);
            (
                surface * (1.0 + elevation / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS),
                view.globe_camera_position(),
            )
        } else {
            let Some((near, _)) = view.line_of_sight(&ScreenCoordinate::new(screen.x, view_height - screen.y)) else {
                return 1.0;
            };
            let [x, y] = to_tile(near.x, near.y);
            (DVec3::new(point.x, point.y, elevation), DVec3::new(x, y, near.z))
        };
        let at = |t: f64| {
            let q = start.lerp(end, t);
            if !globe {
                return ([q.x, q.y], q.z);
            }
            let (radius, n) = (q.length(), q.normalize());
            let location =
                LatLng::saturating(n.y.asin().to_degrees(), n.x.atan2(n.z).to_degrees(), WrapMode::Unwrapped);
            let p = TileCoordinate::from_lat_lng(0.0, &location).p;
            // In the world copy of the point.
            let x = p.x + (point_x - p.x).round();
            (to_tile(x, p.y), (radius - 1.0) * VerticalPerspectiveProjection::GLOBE_RADIUS_METERS)
        };
        let under = |t: f64| {
            let (point, ray) = at(t);
            f64::from(self.height(Vec2::new(point[0] as f32, point[1] as f32))) > ray
        };

        // The tile units that a logical pixel spans at the point.
        let pixels_to_tile_units = extent
            / (mln_style::constants::TILE_SIZE * 2f64.powf(view.zoom() - f64::from(tile.canonical.z)))
            * projector.map_aligned_scale_at(&point);
        let (eye, _) = at(1.0);
        let across = (eye[0] - point.x).hypot(eye[1] - point.y) / pixels_to_tile_units;
        let steps = (across / 4.0).ceil().clamp(1.0, 512.0) as u32;
        let Some(step) = (1..=steps).find(|&i| under(1.0 - f64::from(i) / f64::from(steps))) else {
            return 1.0;
        };
        let (mut above, mut below) =
            (1.0 - f64::from(step - 1) / f64::from(steps), 1.0 - f64::from(step) / f64::from(steps));
        for _ in 0..24 {
            let mid = f64::midpoint(above, below);
            if under(mid) { below = mid } else { above = mid }
        }
        let (ground, ray) = at(below);
        let ground = projector.project_as_drawn(&Point::new(ground[0], ground[1]), ray);

        // The shaders' `ground_depth_opacity` against the ground `distance`
        // from the camera, with its ramp's scale.
        let depth_opacity = |distance: f64| {
            let d = view_height / 25.0 * (1.0 / drawn.signed_distance_from_camera - 1.0 / distance) + 0.0001;
            1.0 - (-500.0 * d).clamp(0.0, 1.0)
        };
        let visibility = depth_opacity(ground.signed_distance_from_camera);
        if visibility > 0.95 {
            return 1.0;
        }
        // Partly hidden, averaged with the screen point 0.01 clip units
        // above, where the line of sight meets the nearest ground the frame
        // drew; 1 where that point is outside the view or meets none.
        let above = ScreenCoordinate::new(screen.x, view_height - screen.y + 0.005 * view_height);
        let hit = if above.y <= view_height { view.ground_under(&above, self.ground) } else { None };
        let above = match hit {
            Some(hit) => {
                // On the globe, in the world copy of the point.
                let x = if globe { hit.world.x + (point_x - hit.world.x).round() } else { hit.world.x };
                let [x, y] = to_tile(x, hit.world.y);
                depth_opacity(projector.project_as_drawn(&Point::new(x, y), hit.height).signed_distance_from_camera)
            }
            None => 1.0,
        };
        f64::midpoint(visibility, above)
    }
}

impl Elevation for TerrainElevation {
    fn at(&self, location: LatLng) -> Option<f64> {
        let (tile, uv) = self.tile_at_location(location)?;
        Some(self.height_of(tile, uv))
    }

    fn ground_at(&self, location: LatLng) -> Option<f64> {
        let world = self.world.world_from_lat_lng(&location);
        let inside = (self.world.wraps() || (0.0..1.0).contains(&world.x)) && (0.0..=1.0).contains(&world.y);
        inside.then(|| self.finest_height(DVec2::new(world.x, world.y))).flatten().or_else(|| self.at(location))
    }

    fn min_at(&self, location: LatLng) -> Option<f64> {
        let (tile, _) = self.tile_at_location(location)?;
        Some(self.min_of(tile))
    }

    fn surface_at(&self, world: DVec2) -> Option<f64> {
        if !(0.0..=1.0).contains(&world.y) {
            return None;
        }
        let (tile, uv) = self.drawn_tile_at(world, true)?;
        Some(self.height_of(tile, uv))
    }

    fn clearance_at(&self, world: DVec2) -> Option<f64> {
        // A world that doesn't wrap has no copies, and no ground outside
        // its square.
        if !(0.0..=1.0).contains(&world.y) || (!self.world.wraps() && !(0.0..1.0).contains(&world.x)) {
            return None;
        }
        // The drawn tile's DEM, where the clearance's tiles have none.
        self.finest_height(world).or_else(|| {
            let (tile, uv) = self.drawn_tile_at(world, true)?;
            tile.dem.as_ref().map(|dem| self.height(dem, uv))
        })
    }

    fn range(&self) -> Option<(f64, f64)> {
        self.range
    }
}

#[cfg(test)]
mod tests {
    use mln_style::tileset::RasterEncoding;

    use super::*;
    use crate::render::terrain::cover::{ElevationRanges, TerrainTile};

    /// A point in a world copy past the range of the tiles' wraps has no
    /// surface, though a tile of the last copy in range drew: no copy of
    /// the point's stands in for it.
    #[test]
    fn a_point_in_a_copy_past_the_wraps_has_no_surface() {
        let tile =
            |wrap: i16| TerrainTile { id: OverscaledTileID::new(0, wrap, CanonicalTileID::new(0, 0, 0)), dem: None };
        let cover = TerrainCover {
            source_id: "dem".to_owned(),
            tile_size: 512,
            tiles: vec![tile(i16::MAX), tile(i16::MIN)],
            center: None,
            dem_tiles: Vec::new(),
            ranges: ElevationRanges::default(),
            world: WorldMapping::default(),
        };
        let ground = TerrainElevation::new(&cover, None, DemUnpack::of(RasterEncoding::Terrarium), 1.0);
        for copy in [i16::MAX, i16::MIN] {
            assert_eq!(Some(0.0), ground.surface_at(DVec2::new(f64::from(copy) + 0.5, 0.5)), "copy {copy}");
        }
        for x in [f64::from(i16::MAX) + 1.5, 1e12, f64::from(i16::MIN) - 0.5, -1e12] {
            assert_eq!(None, ground.surface_at(DVec2::new(x, 0.5)), "x {x}");
        }
    }

    /// A tile drawn flat before any DEM loaded has a surface, at sea level,
    /// but no clearance.
    #[test]
    fn a_flat_tile_s_surface_is_not_loaded() {
        let tile = TerrainTile { id: OverscaledTileID::new(0, 0, CanonicalTileID::new(0, 0, 0)), dem: None };
        let cover = TerrainCover {
            source_id: "dem".to_owned(),
            tile_size: 512,
            tiles: vec![tile],
            center: None,
            dem_tiles: Vec::new(),
            ranges: ElevationRanges::default(),
            world: WorldMapping::default(),
        };
        let ground = TerrainElevation::new(&cover, None, DemUnpack::of(RasterEncoding::Terrarium), 1.0);
        let point = DVec2::new(0.5, 0.5);
        assert_eq!(Some(0.0), ground.surface_at(point));
        assert_eq!(None, ground.clearance_at(point));
    }

    /// The clearance reads the finest DEM data held at a point, though the
    /// tile drawn there drew flat.
    #[test]
    fn the_clearance_reads_the_finest_dem_held() {
        let tile = TerrainTile { id: OverscaledTileID::new(0, 0, CanonicalTileID::new(0, 0, 0)), dem: None };
        let cover = TerrainCover {
            source_id: "dem".to_owned(),
            tile_size: 512,
            tiles: vec![tile],
            center: None,
            dem_tiles: Vec::new(),
            ranges: ElevationRanges::default(),
            world: WorldMapping::default(),
        };
        let mut ground = TerrainElevation::new(&cover, None, DemUnpack::of(RasterEncoding::Terrarium), 1.0);
        // Terrarium heights everywhere in a DEM of 4 pixels a side.
        let dem = |[red, green]: [u8; 2]| {
            let texels = [red, green, 0, 255].repeat(6 * 6);
            (Arc::new(PremultipliedImage::from_vec(mln_style::size::Size::new(6, 6), texels)), 4)
        };
        ground.clearance.insert(CanonicalTileID::new(1, 0, 0), dem([131, 232]));
        ground.clearance.insert(CanonicalTileID::new(2, 0, 0), dem([135, 208]));
        ground.clearance_zooms = vec![2, 1];
        assert_eq!(Some(2000.0), ground.clearance_at(DVec2::new(0.1, 0.1)));
        assert_eq!(Some(1000.0), ground.clearance_at(DVec2::new(0.4, 0.4)));
        assert_eq!(None, ground.clearance_at(DVec2::new(0.6, 0.6)));
        assert_eq!(Some(0.0), ground.surface_at(DVec2::new(0.1, 0.1)));
        // In the finer tile, at about (0.08, 0.22) of the world.
        let location = LatLng::new(70.0, -150.0).unwrap();
        assert_eq!(Some(2000.0), ground.ground_at(location));
        assert_eq!(Some(0.0), ground.at(location));
    }
}