Skip to main content

mln_engine/render/terrain/
mod.rs

1//! 3D terrain: the style's `terrain` drawn as a surface raised by a
2//! raster-dem source, with the layers that drape over it drawn into
3//! textures that the surface samples.
4//!
5//! Terrain draws once the style's terrain names a raster-dem source whose
6//! tileset has loaded, outside tile mode, on every projection, on a backend
7//! that makes its shader ([`RenderTerrain::make_shader`]). A frame without
8//! terrain takes none of the steps below, which [`RenderTerrain`] runs for
9//! each frame:
10//!
11//! 1. **Update**, before the sources update ([`RenderTerrain::update`]):
12//!    terrain tiles cover the view ([`TerrainCover`]), culled by the DEM's
13//!    elevation ranges ([`ElevationRanges`]), and the terrain's source keeps
14//!    the DEM tiles they read loaded. Every source covers the view the same
15//!    way.
16//! 2. **Bind**, once the sources have updated ([`RenderTerrain::bind`]):
17//!    each tile binds its DEM, and the ground the tiles draw
18//!    ([`TerrainElevation`]) goes to the map, whose camera stands on it.
19//! 3. **Encode**: the layers that drape draw nothing into the frame, but
20//!    into the drapes of their stack ([`DrapeStacks`], [`Drapes`]); the
21//!    surface makes a draw per tile and stack, which reads the DEM textures
22//!    ([`RenderTerrain::update_dems`], [`RenderTerrain::update_draws`]).
23//!    The layers that stand on terrain stand on the frame's ground
24//!    ([`FrameGround`], [`RenderTerrain::update_ground`]): their points'
25//!    heights are the ground's under them ([`TileGround`]).
26//! 4. **Ground**: before the frame's passes, where layers hide behind the
27//!    ground, the surface draws its depth into the ground's depth texture
28//!    ([`RenderTerrain::render_ground`]), which they read.
29//! 5. **Drapes**: before the frame's pass, the drapes whose layers draw
30//!    from something new draw into their textures; the others keep theirs
31//!    ([`RenderTerrain::render_drapes`]).
32//! 6. **Surface**: the frame's pass draws each stack's surface where the
33//!    stack's first layer draws, and between the stacks the layers that
34//!    don't drape, flat ([`RenderTerrain::render`]). The surface of a
35//!    hillshade's own stack shades its slopes with the frame's lights
36//!    ([`SurfaceLight`]), and the sky's fog covers it ([`terrain_fog`]).
37
38mod cover;
39mod dem_textures;
40mod drapes;
41mod draws;
42mod elevation;
43mod fog;
44pub(crate) mod glsl;
45pub(crate) mod glsl_es;
46mod ground;
47mod mesh;
48pub(crate) mod msl;
49pub mod programs;
50mod stacks;
51pub mod ubo;
52pub(crate) mod wgsl;
53
54use std::rc::Rc;
55use std::sync::Arc;
56
57pub(crate) use cover::{ElevationRanges, TerrainCover};
58#[cfg(test)]
59pub(crate) use cover::{REMEMBERED_RANGES, TerrainTile, terrain_tile_size};
60pub(crate) use drapes::Drapes;
61pub use elevation::{TerrainElevation, TileGround};
62pub(crate) use fog::terrain_fog;
63pub use ground::{FrameGround, GroundHeights, StandingDraw, height_attribute, point_center};
64use mln_gfx::gpu::Gpu;
65use mln_style::hash::HashMap;
66use mln_style::layer::SourceKind;
67use mln_style::tile_id::CanonicalTileID;
68use mln_style::tileset::RasterEncoding;
69pub(crate) use stacks::{DrapeStacks, Draped};
70
71use crate::draw::context::Context;
72use crate::draw::store::SharedTexture;
73use crate::geo::constants;
74use crate::layer::layer_drawing::ChangedBuckets;
75use crate::map::{MapMode, TerrainSkirtLength};
76use crate::render::events::RendererEvent;
77use crate::render::paint_parameters::PaintParameters;
78use crate::render::terrain::cover::dem_contents;
79use crate::render::terrain::dem_textures::DemTextures;
80use crate::render::terrain::draws::TerrainDraws;
81use crate::render::terrain::ground::GroundDepth;
82use crate::render::terrain::ubo::{HillshadeEvaluatedPropsUBO, HillshadeTilePropsUBO, TerrainFog, TerrainProps};
83use crate::render::update_parameters::UpdateParameters;
84use crate::tile::OverscaledTileID;
85use crate::tile::dem::DemUnpack;
86use crate::tile_store::source_tiles::SourceTiles;
87
88/// How far the skirts of terrain tiles reach down at `zoom`, in meters, or
89/// `None` for no skirts. `Auto` is a fifth of a tile's width at the
90/// equator, as GL JS's `getSkirtLength`.
91fn skirt_length(length: TerrainSkirtLength, zoom: f64) -> Option<f64> {
92    match length {
93        TerrainSkirtLength::Auto => Some(constants::M2PI * constants::EARTH_RADIUS_M / zoom.max(0.0).exp2() / 5.0),
94        TerrainSkirtLength::None => None,
95    }
96}
97
98/// How the terrain's surface draws in a frame: how its DEM decodes, its
99/// exaggeration and its skirts.
100#[derive(Clone, Copy, Debug, Default, PartialEq)]
101pub(crate) struct Surface {
102    /// How the surface stands, the first members of its uniform block.
103    pub(crate) props: TerrainProps,
104    /// Whether the tiles have skirts.
105    pub(crate) skirts: bool,
106}
107
108impl Surface {
109    /// The surface of a DEM of `encoding`, raised by `exaggeration`, with
110    /// skirts of `skirt_length` meters, or none.
111    fn new(encoding: RasterEncoding, exaggeration: f32, skirt_length: Option<f64>) -> Surface {
112        let unpack = DemUnpack::of(encoding);
113        let props = TerrainProps {
114            unpack: unpack.weights_and_base(),
115            unpack_scale: unpack.scale,
116            exaggeration,
117            skirt_length: skirt_length.unwrap_or(0.0) as f32,
118        };
119        Surface { props, skirts: skirt_length.is_some() }
120    }
121
122    /// How the DEM decodes.
123    fn unpack(&self) -> DemUnpack {
124        let [r, g, b, base] = self.props.unpack;
125        DemUnpack { weights: [r, g, b], base, scale: self.props.unpack_scale }
126    }
127}
128
129/// The shading that the surface adds to a stack's drapes, which hold a
130/// hillshade's slopes, as the hillshade's own draws would shade them: so
131/// that a hillshade lit from the viewport keeps its drapes as the map
132/// turns, while its light stays where the viewport puts it.
133#[derive(Clone, Copy, Debug, Default, PartialEq)]
134pub struct SurfaceLight {
135    /// The hillshade's lights, turned by the frame's bearing.
136    pub props: HillshadeEvaluatedPropsUBO,
137    /// The hillshade's values of a tile, but for its latitudes, which are
138    /// each terrain tile's.
139    pub tile: HillshadeTilePropsUBO,
140}
141
142/// The textures of the DEM tiles that the frame's terrain tiles read, which
143/// their draws bind.
144pub(crate) struct DemBindings {
145    /// The texture of each DEM tile, with its width in pixels.
146    textures: HashMap<CanonicalTileID, (SharedTexture, u32)>,
147    /// A transparent 1×1 texture, of flat ground and of a drape that holds
148    /// nothing.
149    flat: SharedTexture,
150}
151
152impl DemBindings {
153    /// The texture of the DEM tile `dem`, with its width in pixels, if a
154    /// tile reads it.
155    pub(crate) fn dem(&self, dem: &OverscaledTileID) -> Option<(&SharedTexture, u32)> {
156        self.textures.get(&dem.canonical).map(|(texture, dim)| (texture, *dim))
157    }
158
159    /// A transparent 1×1 texture.
160    pub(crate) fn flat(&self) -> &SharedTexture {
161        &self.flat
162    }
163}
164
165/// The terrain of the frames the renderer draws: whether it draws, the
166/// tiles that cover the view, their drapes and their draws.
167#[derive(Default)]
168pub(crate) struct RenderTerrain {
169    cover: Option<TerrainCover>,
170    /// How the surface of the cover draws.
171    surface: Surface,
172    drapes: Drapes,
173    draws: TerrainDraws,
174    /// The ground the last update's cover drew, as the renderer last told
175    /// the map; `None` while terrain doesn't draw.
176    elevation: Option<Arc<TerrainElevation>>,
177    /// The textures of the DEM tiles the frame's draws read.
178    dem_textures: DemTextures,
179    /// What the frame's draws bind of them; `None` without terrain.
180    dems: Option<DemBindings>,
181    /// The texture of the ground's depth, while the frame draws it.
182    ground_depth: GroundDepth,
183    /// The most bytes the drapes hold, the map's
184    /// [`TerrainOptions::drape_memory_limit`], or `None` for no limit.
185    ///
186    /// [`TerrainOptions::drape_memory_limit`]: crate::map::TerrainOptions::drape_memory_limit
187    drape_memory_limit: Option<u64>,
188}
189
190impl RenderTerrain {
191    /// Brings the terrain to `parameters`, before the sources update: checks
192    /// whether it draws, takes in the elevation ranges of the DEM tiles that
193    /// have loaded, which the last cover's ranges remember, covers the view
194    /// with its tiles and lists the DEM tiles they read. `dem` finds the
195    /// tiles of a source by its id. Returns the cover while terrain draws;
196    /// its tiles bind their DEM in [`bind`]. While terrain doesn't draw, it
197    /// remembers no ranges. Terrain doesn't draw on a backend that failed to
198    /// make its shader ([`make_shader`]): the map draws flat.
199    ///
200    /// [`bind`]: Self::bind
201    /// [`make_shader`]: Self::make_shader
202    pub(crate) fn update<'a>(
203        &mut self,
204        parameters: &UpdateParameters,
205        dem: impl FnOnce(&str) -> Option<&'a SourceTiles>,
206    ) -> Option<&TerrainCover> {
207        let mut ranges = self.cover.take().map(|cover| cover.ranges).unwrap_or_default();
208        let style = &parameters.style;
209        let terrain = style.get_terrain()?;
210        if parameters.mode == MapMode::Tile || self.draws.failed() {
211            return None;
212        }
213        // Terrain draws only once its source's tiles have a cover, and not
214        // at all from a source whose tiles aren't raster-dem.
215        let dem = dem(&terrain.source).filter(|dem| dem.info.kind == SourceKind::RasterDem)?;
216        let cover = dem.info.cover?;
217
218        let skirt_length = skirt_length(parameters.terrain.skirt_length, parameters.view.zoom());
219        self.surface = Surface::new(dem.info.dem_encoding, terrain.exaggeration, skirt_length);
220        self.drape_memory_limit = parameters.terrain.drape_memory_limit;
221
222        let dem_zooms = cover.zoom_range;
223        ranges.update(dem, dem_zooms, f64::from(terrain.exaggeration));
224        let tile_size = cover.tile_size;
225        let view = &parameters.view;
226        self.cover = Some(TerrainCover::new(view, &terrain.source, tile_size, dem_zooms, ranges));
227        self.cover.as_ref()
228    }
229
230    /// Makes the surface's shader on `gpu` in `context` for the update of
231    /// `parameters`, before [`update`], if its style has terrain. A backend
232    /// that fails to make it draws no terrain until the shaders are made
233    /// again ([`release_shaders`]).
234    ///
235    /// [`update`]: Self::update
236    /// [`release_shaders`]: Self::release_shaders
237    pub(crate) fn make_shader(&mut self, gpu: &mut dyn Gpu, context: &mut Context, parameters: &UpdateParameters) {
238        if parameters.style.get_terrain().is_some() && parameters.mode != MapMode::Tile {
239            self.draws.shaders(gpu, context, &parameters.view);
240        }
241    }
242
243    /// Binds each terrain tile's DEM, once the sources have updated, from
244    /// the tiles of the terrain's source that `dem` finds by its id. A
245    /// frame's bindings are of the DEM tiles it has, so that a frame that
246    /// has loaded draws each tile with its own.
247    ///
248    /// Returns whether the frame is grounded: whether the update
249    /// ([`UpdateParameters::elevation`]) carries the ground the tiles now
250    /// draw, the same `Arc`, or neither has one, as while terrain doesn't
251    /// draw. Otherwise it tells the map of its current ground in `events`
252    /// ([`RendererEvent::TerrainElevation`]), before the frame finishes.
253    /// The ground keeps its `Arc` while the tiles, the DEM data they read and
254    /// how it decodes stay the same.
255    pub(crate) fn bind<'a>(
256        &mut self,
257        dem: impl FnOnce(&str) -> Option<&'a SourceTiles>,
258        parameters: &UpdateParameters,
259        events: &mut Vec<RendererEvent>,
260    ) -> bool {
261        let seen = parameters.elevation.as_deref();
262        let Some(cover) = &mut self.cover else {
263            if self.elevation.take().is_some() || seen.is_some() {
264                events.push(RendererEvent::TerrainElevation(None));
265            }
266            return seen.is_none();
267        };
268        let tiles = dem(&cover.source_id);
269        cover.bind(tiles);
270        let ground = TerrainElevation::new(cover, tiles, self.surface.unpack(), self.surface.props.exaggeration);
271        let drawn = match &mut self.elevation {
272            Some(drawn) if drawn.draws_as(&ground) => drawn,
273            slot => slot.insert(Arc::new(ground)),
274        };
275        let grounded = seen.is_some_and(|seen| std::ptr::addr_eq(seen, Arc::as_ptr(drawn)));
276        if !grounded {
277            events.push(RendererEvent::TerrainElevation(Some(Arc::<TerrainElevation>::clone(drawn))));
278        }
279        grounded
280    }
281
282    /// The ground the last update's cover drew, while terrain draws.
283    pub(crate) fn ground(&self) -> Option<&Arc<TerrainElevation>> {
284        self.elevation.as_ref()
285    }
286
287    /// The ground of the frame of the last update, where it has terrain and
288    /// a layer `stands` on it: the ground its cover drew ([`ground`]), and,
289    /// where a layer `hides` behind it, the texture of its depth, which the
290    /// frame draws first ([`render_ground`]). Drops the ground's depth
291    /// otherwise.
292    ///
293    /// [`ground`]: Self::ground
294    /// [`render_ground`]: Self::render_ground
295    pub(crate) fn update_ground(
296        &mut self,
297        parameters: &mut PaintParameters<'_>,
298        stands: bool,
299        hides: bool,
300    ) -> Option<Rc<FrameGround>> {
301        let elevation = self.elevation.clone().filter(|_| stands && self.cover.is_some());
302        let depth = elevation
303            .as_ref()
304            .filter(|_| hides)
305            .map(|_| self.ground_depth.texture(parameters.context, parameters.renderable_size));
306        if depth.is_none() {
307            self.ground_depth.clear();
308        }
309        Some(Rc::new(FrameGround::new(elevation?, depth)))
310    }
311
312    /// The drapes of the last frame.
313    #[cfg(test)]
314    pub(crate) fn drapes(&self) -> &Drapes {
315        &self.drapes
316    }
317
318    /// How the surface of the last update's cover draws.
319    #[cfg(test)]
320    pub(crate) fn surface(&self) -> Surface {
321        self.surface
322    }
323
324    /// The cover of the last update, while terrain draws: [`update`]'s.
325    ///
326    /// [`update`]: Self::update
327    pub(crate) fn cover(&self) -> Option<&TerrainCover> {
328        self.cover.as_ref()
329    }
330
331    /// Makes, in the encode, the textures of the DEM tiles of the terrain's
332    /// source, which `dem` finds by its id, that the tiles of the last
333    /// update's cover read, for the surface's draws; drops them in a frame
334    /// without terrain.
335    pub(crate) fn update_dems<'a>(
336        &mut self,
337        parameters: &mut PaintParameters<'_>,
338        dem: impl FnOnce(&str) -> Option<&'a SourceTiles>,
339    ) {
340        let Some(cover) = &self.cover else {
341            self.dem_textures = DemTextures::default();
342            self.dems = None;
343            return;
344        };
345        let context = &mut *parameters.context;
346        let tiles = dem(&cover.source_id);
347        let mut textures = HashMap::default();
348        for (id, _) in cover.tiles.iter().filter_map(|tile| tile.dem) {
349            if textures.contains_key(&id.canonical) {
350                continue;
351            }
352            if let Some(dem) = tiles.and_then(|tiles| dem_contents(tiles.tile(&id)?)) {
353                let dim = u32::try_from(dem.dem().dim).unwrap_or(0);
354                textures.insert(id.canonical, (self.dem_textures.texture(context, dem), dim));
355            }
356        }
357        self.dem_textures.finish_frame();
358        let flat = self.dem_textures.flat(context);
359        self.dems = Some(DemBindings { textures, flat });
360    }
361
362    /// Starts the encode's update of the drapes of the frame of the last
363    /// update, of `stacks` stacks of draped layers, whose layers then make
364    /// their draws in them ([`Drapes::update_layer`]); `None`, dropping the
365    /// drapes, for a frame that doesn't draw terrain or no stack.
366    pub(crate) fn begin_drapes(&mut self, parameters: &mut PaintParameters<'_>, stacks: usize) -> Option<&mut Drapes> {
367        let Some(cover) = self.cover.as_ref().filter(|_| stacks > 0) else {
368            self.drapes = Drapes::default();
369            return None;
370        };
371        let max_texture_size = parameters.context.caps().max_texture_size;
372        self.drapes.begin(
373            parameters.view,
374            cover,
375            stacks,
376            (self.drape_memory_limit.unwrap_or(u64::MAX), max_texture_size),
377        );
378        Some(&mut self.drapes)
379    }
380
381    /// Makes the draws of the frame of the last update, a set for each stack
382    /// of the drapes the encode began ([`begin_drapes`]), which read the DEM
383    /// textures of the frame ([`update_dems`]), sample their stack's drapes,
384    /// shade them with the stack's light of `stacks`, if it has one, and
385    /// cover them with `fog`, and, if `depth_first`, draws of the surface's
386    /// depth alone ([`render_depth`]), and, if `ground`, draws of the
387    /// ground's depth into its texture ([`render_ground`]). Without either,
388    /// which a frame without terrain has neither of, it makes no draws, and
389    /// drops what the draws hold.
390    ///
391    /// [`begin_drapes`]: Self::begin_drapes
392    /// [`update_dems`]: Self::update_dems
393    /// [`render_depth`]: Self::render_depth
394    /// [`render_ground`]: Self::render_ground
395    pub(crate) fn update_draws(
396        &mut self,
397        gpu: &mut dyn Gpu,
398        parameters: &mut PaintParameters<'_>,
399        stacks: &DrapeStacks,
400        fog: TerrainFog,
401        (depth_first, ground): (bool, bool),
402    ) {
403        let cover = self.cover.as_ref().zip(self.dems.as_ref());
404        self.draws.update(gpu, parameters, cover, (self.surface, fog), (&self.drapes, stacks), (depth_first, ground));
405    }
406
407    /// Makes the drapes that show the buckets in `changed`, which changed,
408    /// draw again.
409    pub(crate) fn mark_changed(&mut self, changed: &ChangedBuckets) {
410        self.drapes.mark_changed(changed);
411    }
412
413    /// Makes every drape draw again in the next frame, for a change that
414    /// their keys don't tell: the style's images, or a frame that failed.
415    pub(crate) fn redraw_drapes(&mut self) {
416        self.drapes.redraw();
417    }
418
419    /// Drops the drapes once the map's center crossed the antimeridian: the
420    /// tiles are the same ones under new ids, and the next frame draws their
421    /// drapes again.
422    pub(crate) fn handle_wrap_jump(&mut self) {
423        self.drapes = Drapes::default();
424    }
425
426    /// Uploads the GPU objects of the frame's draws.
427    pub(crate) fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) {
428        self.draws.upload(gpu, context);
429    }
430
431    /// Uploads the drapes' draws and makes what they draw with, through
432    /// `gpu`, the context of `parameters`, the frame's.
433    pub(crate) fn upload_drapes(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
434        self.drapes.upload(gpu, parameters);
435    }
436
437    /// Draws the drapes into their textures, outside any pass, before the
438    /// frame's passes, whose surface samples them.
439    pub(crate) fn render_drapes(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
440        self.drapes.render(gpu, parameters);
441    }
442
443    /// Counts in the rendering stats of `context` what the drapes hold once
444    /// a frame has drawn ([`Drapes::count`]).
445    pub(crate) fn count(&self, context: &mut Context) {
446        self.drapes.count(context);
447    }
448
449    /// Draws the surface of `stack`, which samples the stack's drapes, into
450    /// the open pass of `gpu`, the context's.
451    pub(crate) fn render(&mut self, stack: usize, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
452        self.draws.render(stack, gpu, parameters);
453    }
454
455    /// Draws the ground's depth, where the frame has a ground that a layer
456    /// hides behind ([`update_ground`]), in a pass of its own before the
457    /// frame's passes, into its texture.
458    ///
459    /// [`update_ground`]: Self::update_ground
460    pub(crate) fn render_ground(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
461        if !self.draws.draws_ground() {
462            return;
463        }
464        let Some(pass) = self.ground_depth.pass(gpu, parameters.context) else {
465            return;
466        };
467        if let Err(error) = parameters.begin_pass(gpu, pass) {
468            parameters.context.fail(format!("Beginning the ground's pass failed: {error}"));
469            return;
470        }
471        self.draws.render_ground(gpu, parameters);
472        if let Err(error) = parameters.end_pass(gpu) {
473            parameters.context.fail(format!("Ending the ground's pass failed: {error}"));
474        }
475    }
476
477    /// Draws the surface's depth alone into the open pass of `gpu`, the
478    /// context's, where the frame's draws have it, so that the 3D layers
479    /// that draw before the first stack's surface stand behind the ground.
480    pub(crate) fn render_depth(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
481        self.draws.render_depth(gpu, parameters);
482    }
483
484    /// Drops all it made from the map's data, for the renderer's
485    /// `clear_data`: the cover and the elevation ranges it remembers, the
486    /// drapes and the layers' drawings in them, the draws and the DEM
487    /// textures. If it had told the map of the ground, it tells it in
488    /// `events` that the ground is gone.
489    pub(crate) fn clear_data(&mut self, events: &mut Vec<RendererEvent>) {
490        if self.elevation.is_some() {
491            events.push(RendererEvent::TerrainElevation(None));
492        }
493        *self = RenderTerrain::default();
494    }
495
496    /// Drops the draws and the drapes, which hold the renderer's shaders,
497    /// and the DEM textures; the next frame makes them again.
498    pub(crate) fn release_shaders(&mut self) {
499        self.drapes = Drapes::default();
500        self.draws = TerrainDraws::default();
501        self.dem_textures = DemTextures::default();
502        self.dems = None;
503        self.ground_depth.clear();
504    }
505}