mln_engine/render/terrain/
ground.rs1use 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
24const DEPTH_FORMAT: TextureFormat = TextureFormat::Rgba8Unorm;
27
28const DEPTH_STENCIL: TextureFormat = TextureFormat::Depth24PlusStencil8;
32
33pub struct FrameGround {
36 elevation: Arc<TerrainElevation>,
37 depth: Option<SharedTexture>,
38}
39
40impl FrameGround {
41 pub(crate) fn new(elevation: Arc<TerrainElevation>, depth: Option<SharedTexture>) -> FrameGround {
44 FrameGround { elevation, depth }
45 }
46
47 pub(crate) fn elevation(&self) -> &Arc<TerrainElevation> {
49 &self.elevation
50 }
51
52 #[must_use]
54 pub fn tile(&self, tile: UnwrappedTileID) -> TileGround<'_> {
55 TileGround::new(&self.elevation, tile)
56 }
57
58 #[must_use]
62 pub fn depth(&self) -> Option<&SharedTexture> {
63 self.depth.as_ref()
64 }
65}
66
67#[must_use]
70pub fn point_center(a1: [i16; 2]) -> [i16; 2] {
71 a1.map(|value| value >> 1)
72}
73
74#[derive(Default)]
77pub struct GroundHeights(Option<(Weak<TerrainElevation>, TypedVertices<f32>)>);
78
79impl GroundHeights {
80 #[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 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#[must_use]
108pub fn height_attribute(heights: &SharedVertices) -> SharedAttribute {
109 SharedAttribute::new(heights.clone(), AttributeDataType::Float, 0, size_of::<f32>() as u32)
110}
111
112pub struct StandingDraw {
116 pub mesh: Mesh,
117 heights: GroundHeights,
118}
119
120impl StandingDraw {
121 #[must_use]
123 pub fn new(mesh: Mesh) -> Self {
124 StandingDraw { mesh, heights: GroundHeights::default() }
125 }
126
127 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#[derive(Default)]
158pub(crate) struct GroundDepth {
159 texture: Option<(SharedTexture, Size)>,
160 depth: Option<GpuTexture>,
162}
163
164impl GroundDepth {
165 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 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 pub(crate) fn clear(&mut self) {
223 self.texture = None;
224 self.depth = None;
225 }
226}