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