Skip to main content

mln_engine/render/terrain/
ground.rs

1//! The ground that the layers that stand on terrain stand on, and hide
2//! behind, in a frame: the ground the frame's surface drew, which gives
3//! their points their heights ([`TileGround`]), and the depth of that
4//! ground, which the layers that hide behind it read.
5
6use std::mem::size_of;
7use std::sync::{Arc, Weak};
8
9use mln_gfx::gpu::{ColorAttachment, DepthStencilAttachment, Gpu, LoadOp, TargetFormats, TextureFormat};
10use mln_gfx::texture2d::SamplerState;
11use mln_gfx::types::{TextureFilterType, TextureWrapType};
12use mln_gfx::{AttributeDataType, Rgba, Size};
13
14use super::{TerrainElevation, TileGround};
15use crate::draw::context::Context;
16use crate::draw::objects::Mesh;
17use crate::draw::resources::GpuTexture;
18use crate::draw::store::SharedTexture;
19use crate::draw::vertex_attribute::SharedAttribute;
20use crate::draw::vertices::{SharedVertices, TypedVertices};
21use crate::render::paint_parameters::OpenPass;
22use crate::tile::UnwrappedTileID;
23
24/// The texel format of the ground's depth: an `f32`'s bits in RGBA8, which
25/// every backend draws into and reads in a vertex stage.
26const DEPTH_FORMAT: TextureFormat = TextureFormat::Rgba8Unorm;
27
28/// The format of the depth attachment the ground's pass tests, so that the
29/// nearest ground stays in its texture whatever order the tiles draw in:
30/// one every backend draws into, as the layer composite's.
31const DEPTH_STENCIL: TextureFormat = TextureFormat::Depth24PlusStencil8;
32
33/// The ground of a frame: the ground its surface drew, and, where a layer
34/// hides behind it, the texture of its depth.
35pub struct FrameGround {
36    elevation: Arc<TerrainElevation>,
37    depth: Option<SharedTexture>,
38}
39
40impl FrameGround {
41    /// The ground `elevation`, whose depth draws into `depth` where a layer
42    /// hides behind it.
43    pub(crate) fn new(elevation: Arc<TerrainElevation>, depth: Option<SharedTexture>) -> FrameGround {
44        FrameGround { elevation, depth }
45    }
46
47    /// The ground the frame drew, whose `Arc` stays the same while it does.
48    pub(crate) fn elevation(&self) -> &Arc<TerrainElevation> {
49        &self.elevation
50    }
51
52    /// The ground under the points of `tile`.
53    #[must_use]
54    pub fn tile(&self, tile: UnwrappedTileID) -> TileGround<'_> {
55        TileGround::new(&self.elevation, tile)
56    }
57
58    /// The texture of the ground's depth, where a layer hides behind it:
59    /// each pixel's eye distance, an `f32`'s bits, least significant byte
60    /// first, 0 where no ground drew.
61    #[must_use]
62    pub fn depth(&self) -> Option<&SharedTexture> {
63        self.depth.as_ref()
64    }
65}
66
67/// The center of the point of a vertex of a point's quad at `a1`, the
68/// point's position, doubled, plus the quad's corner (`add_point_quads`).
69#[must_use]
70pub fn point_center(a1: [i16; 2]) -> [i16; 2] {
71    a1.map(|value| value >> 1)
72}
73
74/// The heights of the ground under a draw's vertices, which an attribute or
75/// storage buffer of its reads, and the ground they are of.
76#[derive(Default)]
77pub struct GroundHeights(Option<(Weak<TerrainElevation>, TypedVertices<f32>)>);
78
79impl GroundHeights {
80    /// Whether they are of `ground`, which stays the frame's ground while
81    /// its `Arc` does.
82    #[must_use]
83    pub fn are_of(&self, ground: &FrameGround) -> bool {
84        self.0.as_ref().is_some_and(|(of, _)| Weak::ptr_eq(of, &Arc::downgrade(ground.elevation())))
85    }
86
87    /// Makes them `heights`, of `ground`, through `context`: written over
88    /// those they were where they fit, which their readers read still, else
89    /// in new vertices, which it returns for the readers to read.
90    pub fn write(&mut self, context: &mut Context, ground: &FrameGround, heights: &[f32]) -> Option<SharedVertices> {
91        let of = Arc::downgrade(ground.elevation());
92        if let Some((_, vertices)) = &self.0
93            && context.update_vertices(vertices, heights)
94        {
95            self.0 = Some((of, vertices.clone()));
96            return None;
97        }
98        let vertices = context.add_dynamic_vertices(heights);
99        let shared = vertices.shared().clone();
100        self.0 = Some((of, vertices));
101        Some(shared)
102    }
103}
104
105/// The attribute of a vertex that reads its height from `heights`, an `f32`
106/// a vertex.
107#[must_use]
108pub fn height_attribute(heights: &SharedVertices) -> SharedAttribute {
109    SharedAttribute::new(heights.clone(), AttributeDataType::Float, 0, size_of::<f32>() as u32)
110}
111
112/// A tile's draw whose points stand on the ground: its mesh, and the
113/// heights of the ground under its vertices, which an attribute of theirs
114/// reads.
115pub struct StandingDraw {
116    pub mesh: Mesh,
117    heights: GroundHeights,
118}
119
120impl StandingDraw {
121    /// The draw of `mesh`, which stands on no ground yet.
122    #[must_use]
123    pub fn new(mesh: Mesh) -> Self {
124        StandingDraw { mesh, heights: GroundHeights::default() }
125    }
126
127    /// Over `ground`, has the attribute `name` of the draw's vertices read the
128    /// heights of the ground under `centers`, the center of each vertex's
129    /// point in `tile`: those of the ground they were of while it stays the
130    /// frame's, else written again, through `context`.
131    pub fn stand(
132        &mut self,
133        context: &mut Context,
134        ground: Option<&FrameGround>,
135        tile: UnwrappedTileID,
136        name: &'static str,
137        centers: &[[i16; 2]],
138    ) {
139        let Some(ground) = ground.filter(|ground| !self.heights.are_of(ground)) else {
140            return;
141        };
142        let tile_ground = ground.tile(tile);
143        let heights: Vec<f32> =
144            centers.iter().map(|&[x, y]| tile_ground.height(glam::Vec2::new(f32::from(x), f32::from(y)))).collect();
145        if let Some(vertices) = self.heights.write(context, ground, &heights)
146            && let Some(attrs) = self.mesh.vertex_attributes_mut(context)
147        {
148            attrs.set_shared(name, height_attribute(&vertices));
149        }
150    }
151}
152
153/// The texture of the ground's depth, of the frame's size, the depth
154/// attachment it draws with, and the pass that draws it. The pass draws
155/// into neither of the frame's attachments, which a window's framebuffer
156/// can't share with other textures.
157#[derive(Default)]
158pub(crate) struct GroundDepth {
159    texture: Option<(SharedTexture, Size)>,
160    /// The depth the pass tests, made with it, of the texture's size.
161    depth: Option<GpuTexture>,
162}
163
164impl GroundDepth {
165    /// The texture of a frame of `size` device pixels, made in `context`'s
166    /// store when the frame's size changes.
167    pub(crate) fn texture(&mut self, context: &mut Context, size: Size) -> SharedTexture {
168        match &self.texture {
169            Some((texture, made)) if *made == size => texture.clone(),
170            _ => {
171                let texture = context.add_texture_with(|texture| {
172                    texture.set_size(size);
173                    texture.set_format(DEPTH_FORMAT);
174                    texture.set_render_target();
175                    texture.set_sampler(SamplerState {
176                        filter: TextureFilterType::Nearest,
177                        wrap_u: TextureWrapType::Clamp,
178                        wrap_v: TextureWrapType::Clamp,
179                        ..SamplerState::default()
180                    });
181                });
182                self.depth = None;
183                self.texture.insert((texture, size)).0.clone()
184            }
185        }
186    }
187
188    /// The pass that draws the ground into the texture, cleared to no
189    /// ground, testing a depth attachment of its own, cleared too. `None`
190    /// without a texture, or where making it through `gpu` failed, which
191    /// fails the frame.
192    pub(crate) fn pass(&mut self, gpu: &mut dyn Gpu, context: &mut Context) -> Option<OpenPass> {
193        let (texture, size) = self.texture.as_ref()?;
194        let made = context.create_texture(gpu, texture).and_then(|color| {
195            if self.depth.is_none() {
196                self.depth = Some(context.device().attachment(gpu, "ground depth", *size, DEPTH_STENCIL)?);
197            }
198            Ok(color)
199        });
200        let color = match made {
201            Ok(color) => color,
202            Err(error) => {
203                context.fail(format!("Making the ground's depth failed: {error}"));
204                return None;
205            }
206        };
207        Some(OpenPass {
208            label: "ground depth",
209            color: Some(ColorAttachment { texture: color, load: LoadOp::Clear(Rgba::new(0.0, 0.0, 0.0, 0.0)) }),
210            depth_stencil: self.depth.as_ref().map(|depth| DepthStencilAttachment {
211                texture: depth.id(),
212                depth: LoadOp::Clear(1.0),
213                stencil: LoadOp::Clear(0),
214            }),
215            size: *size,
216            targets: TargetFormats { color: Some(DEPTH_FORMAT), depth_stencil: Some(DEPTH_STENCIL) },
217        })
218    }
219
220    /// Drops the texture and its depth, in a frame that doesn't draw the
221    /// ground's depth.
222    pub(crate) fn clear(&mut self) {
223        self.texture = None;
224        self.depth = None;
225    }
226}