Skip to main content

mln_engine/tile_store/
tile_lod.rs

1// The C++ `TileZoomFunction::operator()` is `TileZoomFunction::call`.
2
3use mln_style::math::deg2rad;
4
5/// The pitch at which Mercator's horizon reaches the top of the screen, in
6/// degrees.
7pub(crate) const MAX_MERCATOR_HORIZON_ANGLE_DEGREES: f64 = 89.25;
8
9const ASSUMED_MAX_FEATURE_HEIGHT_METERS: f64 = 500.0;
10const TILE_CULLING_HORIZON_ONSET_DEGREES: f64 = 15.0;
11
12fn integral_of_cos_x_by_p(p: f64, x1: f64, x2: f64) -> f64 {
13    const NUM_POINTS: i32 = 10;
14    let mut sum = 0.0;
15    let dx = (x2 - x1) / f64::from(NUM_POINTS);
16    for i in 0..NUM_POINTS {
17        let x = x1 + (f64::from(i) + 0.5) / f64::from(NUM_POINTS) * (x2 - x1);
18        sum += dx * x.cos().powf(p);
19    }
20    sum
21}
22
23/// The zoom each tile is loaded at when the view is pitched: finer for tiles
24/// nearer the camera, coarser toward the horizon, under a total tile budget.
25/// GL JS `createCalculateTileZoomFunction`, which GL JS applies to both
26/// projections (the Mercator cover uses it whenever terrain is present or the
27/// pitch passes 78.5 - fov/2 degrees).
28#[derive(Clone, Copy, Debug)]
29pub(crate) struct TileZoomFunction {
30    camera_vertical_fov: f64,
31    pitch_tile_loading_behavior: f64,
32    tile_count_pitch0: f64,
33    tile_count_max_min_ratio: f64,
34}
35
36impl TileZoomFunction {
37    pub(crate) const DEFAULT_MAX_ZOOM_LEVELS_ON_SCREEN: f64 = 9.314;
38    pub(crate) const DEFAULT_TILE_COUNT_MAX_MIN_RATIO: f64 = 3.0;
39
40    /// The terms that depend on the field of view alone are computed once
41    /// here, for a whole cover. (C++ defaults the last two arguments to
42    /// `DEFAULT_MAX_ZOOM_LEVELS_ON_SCREEN` and
43    /// `DEFAULT_TILE_COUNT_MAX_MIN_RATIO`.)
44    #[must_use]
45    pub(crate) fn new(
46        camera_vertical_fov_degrees: f64,
47        max_zoom_levels_on_screen: f64,
48        tile_count_max_min_ratio: f64,
49    ) -> Self {
50        let pitch_tile_loading_behavior = 2.0
51            * ((max_zoom_levels_on_screen - 1.0)
52                / (deg2rad(MAX_MERCATOR_HORIZON_ANGLE_DEGREES - camera_vertical_fov_degrees).cos()
53                    / deg2rad(MAX_MERCATOR_HORIZON_ANGLE_DEGREES).cos())
54                .log2()
55                - 1.0);
56        TileZoomFunction {
57            camera_vertical_fov: camera_vertical_fov_degrees,
58            pitch_tile_loading_behavior,
59            tile_count_pitch0: 2.0
60                * integral_of_cos_x_by_p(
61                    pitch_tile_loading_behavior - 1.0,
62                    0.0,
63                    deg2rad(camera_vertical_fov_degrees / 2.0),
64                ),
65            tile_count_max_min_ratio,
66        }
67    }
68
69    /// The zoom to load a tile at. Distances share one unit (GL JS uses
70    /// Mercator units at zoom 0). Returns an unrounded zoom.
71    #[must_use]
72    pub(crate) fn call(
73        &self,
74        requested_center_zoom: f64,
75        distance_to_tile_2d: f64,
76        distance_to_tile_z: f64,
77        distance_to_center_3d: f64,
78    ) -> f64 {
79        let center_pitch = f64::min(1.0, distance_to_tile_z / distance_to_center_3d).acos();
80        let highest_pitch = f64::min(
81            deg2rad(MAX_MERCATOR_HORIZON_ANGLE_DEGREES),
82            center_pitch + deg2rad(self.camera_vertical_fov / 2.0),
83        );
84        let lowest_pitch = f64::min(highest_pitch, center_pitch - deg2rad(self.camera_vertical_fov / 2.0));
85        let tile_count = integral_of_cos_x_by_p(self.pitch_tile_loading_behavior - 1.0, lowest_pitch, highest_pitch);
86        let this_tile_pitch = distance_to_tile_2d.atan2(distance_to_tile_z);
87        let distance_to_tile_3d = distance_to_tile_2d.hypot(distance_to_tile_z);
88        let mut desired = requested_center_zoom;
89        desired += (distance_to_center_3d
90            / distance_to_tile_3d
91            / f64::max(0.5, deg2rad(self.camera_vertical_fov / 2.0).cos()))
92        .log2();
93        desired += self.pitch_tile_loading_behavior * this_tile_pitch.cos().log2() / 2.0;
94        desired -= f64::max(1.0, tile_count / self.tile_count_pitch0 / self.tile_count_max_min_ratio).log2() / 2.0;
95        desired
96    }
97}
98
99/// Near the bottom of a steeply pitched view, tiles are culled with room for
100/// the tallest feature they might hold, so buildings do not vanish before
101/// their tile leaves the screen. GL JS `getElevationForTileCulling`:
102/// `center_elevation` is the terrain height under the map center and
103/// `max_content_elevation` the tallest content the style is known to hold;
104/// both are zero without terrain (C++ defaults them to 0).
105#[must_use]
106pub(crate) fn elevation_for_tile_culling(
107    pitch_degrees: f64,
108    fov_degrees: f64,
109    center_elevation: f64,
110    max_content_elevation: f64,
111) -> f64 {
112    let bottom_edge_degrees_above_horizontal = MAX_MERCATOR_HORIZON_ANGLE_DEGREES - pitch_degrees - fov_degrees / 2.0;
113    let proximity = (TILE_CULLING_HORIZON_ONSET_DEGREES - bottom_edge_degrees_above_horizontal)
114        / TILE_CULLING_HORIZON_ONSET_DEGREES;
115    let proximity_to_horizon = proximity.clamp(0.0, 1.0);
116    center_elevation + proximity_to_horizon * f64::max(ASSUMED_MAX_FEATURE_HEIGHT_METERS, max_content_elevation)
117}
118
119#[cfg(test)]
120mod tests {
121    use super::TileZoomFunction;
122
123    #[test]
124    fn level_camera_over_containing_tile_does_not_return_nan() {
125        let zoom = TileZoomFunction::new(
126            36.87,
127            TileZoomFunction::DEFAULT_MAX_ZOOM_LEVELS_ON_SCREEN,
128            TileZoomFunction::DEFAULT_TILE_COUNT_MAX_MIN_RATIO,
129        );
130        // At pitch = 90°, camera_coord.z == center_coord.z (distance_z == 0.0)
131        // on platforms whose trig leaves no residual, and the root tile contains
132        // the camera (distance_to_tile_2d == 0.0).
133        let desired = zoom.call(13.0, 0.0, 0.0, 1e-4);
134        assert!(!desired.is_nan() && desired >= 13.0, "desired zoom: {desired}");
135    }
136}
137
138#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
139#[repr(u8)]
140pub enum TileLodMode {
141    /// Default `TileLOD` algorithm
142    #[default]
143    Default,
144    /// Distance-based `TileLOD` algorithm
145    Distance,
146}