use std::mem::size_of;
use std::sync::{Arc, Weak};
use mln_gfx::gpu::{ColorAttachment, DepthStencilAttachment, Gpu, LoadOp, TargetFormats, TextureFormat};
use mln_gfx::texture2d::SamplerState;
use mln_gfx::types::{TextureFilterType, TextureWrapType};
use mln_gfx::{AttributeDataType, Rgba, Size};
use super::{TerrainElevation, TileGround};
use crate::draw::context::Context;
use crate::draw::objects::DrawObjects;
use crate::draw::resources::GpuTexture;
use crate::draw::store::SharedTexture;
use crate::draw::vertex_attribute::SharedAttribute;
use crate::draw::vertices::{SharedVertices, TypedVertices};
use crate::layer::layer_drawing::{DrawObjectsMut, TileObjects};
use crate::render::paint_parameters::OpenPass;
use crate::tile::UnwrappedTileID;
const DEPTH_FORMAT: TextureFormat = TextureFormat::Rgba8Unorm;
const DEPTH_STENCIL: TextureFormat = TextureFormat::Depth24PlusStencil8;
pub(crate) struct FrameGround {
elevation: Arc<TerrainElevation>,
depth: Option<SharedTexture>,
}
impl FrameGround {
pub(crate) fn new(elevation: Arc<TerrainElevation>, depth: Option<SharedTexture>) -> FrameGround {
FrameGround { elevation, depth }
}
pub(crate) fn elevation(&self) -> &Arc<TerrainElevation> {
&self.elevation
}
pub(crate) fn tile(&self, tile: UnwrappedTileID) -> TileGround<'_> {
TileGround::new(&self.elevation, tile)
}
pub(crate) fn depth(&self) -> Option<&SharedTexture> {
self.depth.as_ref()
}
}
pub(crate) fn point_center(a1: [i16; 2]) -> [i16; 2] {
a1.map(|value| value >> 1)
}
#[derive(Default)]
pub(crate) struct GroundHeights(Option<(Weak<TerrainElevation>, TypedVertices<f32>)>);
impl GroundHeights {
pub(crate) fn are_of(&self, ground: &FrameGround) -> bool {
self.0.as_ref().is_some_and(|(of, _)| Weak::ptr_eq(of, &Arc::downgrade(ground.elevation())))
}
pub(crate) fn write(
&mut self,
context: &mut Context,
ground: &FrameGround,
heights: &[f32],
) -> Option<SharedVertices> {
let of = Arc::downgrade(ground.elevation());
if let Some((_, vertices)) = &self.0
&& context.update_vertices(vertices, heights)
{
self.0 = Some((of, vertices.clone()));
return None;
}
let vertices = context.add_dynamic_vertices(heights);
let shared = vertices.shared().clone();
self.0 = Some((of, vertices));
Some(shared)
}
}
pub(crate) fn height_attribute(heights: &SharedVertices) -> SharedAttribute {
SharedAttribute::new(heights.clone(), AttributeDataType::Float, 0, size_of::<f32>() as u32)
}
pub(crate) struct StandingDraw {
pub(crate) objects: DrawObjects,
heights: GroundHeights,
}
impl StandingDraw {
pub(crate) fn new(objects: DrawObjects) -> Self {
StandingDraw { objects, heights: GroundHeights::default() }
}
pub(crate) fn stand(
&mut self,
context: &mut Context,
ground: Option<&FrameGround>,
tile: UnwrappedTileID,
name: &'static str,
centers: &[[i16; 2]],
) {
let Some(ground) = ground.filter(|ground| !self.heights.are_of(ground)) else {
return;
};
let tile_ground = ground.tile(tile);
let heights: Vec<f32> =
centers.iter().map(|&[x, y]| tile_ground.height(glam::Vec2::new(f32::from(x), f32::from(y)))).collect();
if let Some(vertices) = self.heights.write(context, ground, &heights) {
self.objects.vertex_attributes_mut().set_shared(name, height_attribute(&vertices));
}
}
}
impl TileObjects for StandingDraw {
type Part = ();
fn objects(&mut self, (): ()) -> Option<DrawObjectsMut<'_>> {
Some((&mut self.objects).into())
}
fn drop_bindings(&mut self) {
self.objects.drop_bindings();
}
}
#[derive(Default)]
pub(crate) struct GroundDepth {
texture: Option<(SharedTexture, Size)>,
depth: Option<GpuTexture>,
}
impl GroundDepth {
pub(crate) fn texture(&mut self, context: &mut Context, size: Size) -> SharedTexture {
match &self.texture {
Some((texture, made)) if *made == size => texture.clone(),
_ => {
let texture = context.add_texture_with(|texture| {
texture.set_size(size);
texture.set_format(DEPTH_FORMAT);
texture.set_render_target();
texture.set_sampler(SamplerState {
filter: TextureFilterType::Nearest,
wrap_u: TextureWrapType::Clamp,
wrap_v: TextureWrapType::Clamp,
..SamplerState::default()
});
});
self.depth = None;
self.texture.insert((texture, size)).0.clone()
}
}
}
pub(crate) fn pass(&mut self, gpu: &mut dyn Gpu, context: &mut Context) -> Option<OpenPass> {
let (texture, size) = self.texture.as_ref()?;
let made = context.create_texture(gpu, texture).and_then(|color| {
if self.depth.is_none() {
self.depth = Some(context.device().attachment(gpu, "ground depth", *size, DEPTH_STENCIL)?);
}
Ok(color)
});
let color = match made {
Ok(color) => color,
Err(error) => {
context.fail(format!("Making the ground's depth failed: {error}"));
return None;
}
};
Some(OpenPass {
label: "ground depth",
color: Some(ColorAttachment { texture: color, load: LoadOp::Clear(Rgba::new(0.0, 0.0, 0.0, 0.0)) }),
depth_stencil: self.depth.as_ref().map(|depth| DepthStencilAttachment {
texture: depth.id(),
depth: LoadOp::Clear(1.0),
stencil: LoadOp::Clear(0),
}),
size: *size,
targets: TargetFormats { color: Some(DEPTH_FORMAT), depth_stencil: Some(DEPTH_STENCIL) },
})
}
pub(crate) fn clear(&mut self) {
self.texture = None;
self.depth = None;
}
}