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