]> git.lizzy.rs Git - mt_client.git/blobdiff - src/gfx/map.rs
Mesh data queue
[mt_client.git] / src / gfx / map.rs
index dbedb77b60a248caa5380b512973c2c48c078f3f..dfc41be615a7acb469fdd90ce92f71e16aa005b5 100644 (file)
@@ -1,17 +1,63 @@
+mod atlas;
+mod mesh;
+
 use super::{media::MediaMgr, state::State, util::MatrixUniform};
+use atlas::create_atlas;
 use cgmath::{prelude::*, Matrix4, Point3, Vector3};
+use mesh::{create_mesh, MeshData};
 use mt_net::{MapBlock, NodeDef};
-use rand::Rng;
-use std::{collections::HashMap, ops::Range};
+use serde::{Deserialize, Serialize};
+use std::{
+    collections::HashMap,
+    ops::DerefMut,
+    sync::{Arc, Mutex},
+};
 use wgpu::util::DeviceExt;
 
+#[derive(Serialize, Deserialize, PartialEq, Eq, Copy, Clone, Debug)]
+#[serde(rename_all = "snake_case")]
+pub enum LeavesMode {
+    Opaque,
+    Simple,
+    Fancy,
+}
+
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
+pub struct MapRenderSettings {
+    pub leaves: LeavesMode,
+    pub opaque_liquids: bool,
+}
+
+impl Default for MapRenderSettings {
+    fn default() -> Self {
+        Self {
+            leaves: LeavesMode::Fancy,
+            opaque_liquids: false,
+        }
+    }
+}
+
+struct AtlasSlice {
+    cube_tex_coords: [[[f32; 2]; 6]; 6],
+}
+
+struct MeshMakeInfo {
+    // i optimized the shit out of these
+    textures: Vec<AtlasSlice>,
+    nodes: [Option<Box<NodeDef>>; u16::MAX as usize + 1],
+}
+
+type MeshQueue = HashMap<Point3<i16>, MeshData>;
+
 pub struct MapRender {
     pipeline: wgpu::RenderPipeline,
-    textures: HashMap<String, [Range<f32>; 2]>,
-    nodes: HashMap<u16, NodeDef>,
     atlas: wgpu::BindGroup,
     model: wgpu::BindGroupLayout,
-    blocks: HashMap<[i16; 3], BlockMesh>,
+    blocks: HashMap<[i16; 3], BlockModel>,
+    mesh_make_info: Arc<MeshMakeInfo>,
+    mesh_data_buffer: Mutex<usize>,
+    queue_consume: MeshQueue,
+    queue_produce: Arc<Mutex<MeshQueue>>,
 }
 
 #[repr(C)]
@@ -38,7 +84,41 @@ impl Vertex {
 struct BlockMesh {
     vertex_buffer: wgpu::Buffer,
     num_vertices: u32,
-    model: MatrixUniform,
+}
+
+impl BlockMesh {
+    fn new(state: &State, vertices: &[Vertex]) -> Option<Self> {
+        if vertices.is_empty() {
+            return None;
+        }
+
+        Some(BlockMesh {
+            vertex_buffer: state
+                .device
+                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
+                    label: Some("mapblock.vertex_buffer"),
+                    contents: bytemuck::cast_slice(vertices),
+                    usage: wgpu::BufferUsages::VERTEX,
+                }),
+            num_vertices: vertices.len() as u32,
+        })
+    }
+
+    fn render<'a>(&'a self, pass: &mut wgpu::RenderPass<'a>, transform: &'a MatrixUniform) {
+        pass.set_bind_group(2, &transform.bind_group, &[]);
+        pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
+        pass.draw(0..self.num_vertices, 0..1);
+    }
+}
+
+struct BlockModel {
+    mesh: Option<BlockMesh>,
+    mesh_blend: Option<BlockMesh>,
+    transform: MatrixUniform,
+}
+
+fn block_float_pos(pos: Vector3<i16>) -> Vector3<f32> {
+    pos.cast::<f32>().unwrap() * 16.0
 }
 
 impl MapRender {
@@ -47,202 +127,92 @@ impl MapRender {
         pass.set_bind_group(0, &self.atlas, &[]);
         pass.set_bind_group(1, &state.camera_uniform.bind_group, &[]);
 
-        for mesh in self.blocks.values() {
-            pass.set_bind_group(2, &mesh.model.bind_group, &[]);
-            pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
-            pass.draw(0..mesh.num_vertices, 0..1);
+        struct BlendEntry<'a> {
+            dist: f32,
+            index: usize,
+            mesh: &'a BlockMesh,
+            transform: &'a MatrixUniform,
         }
-    }
 
-    pub fn add_block(&mut self, state: &mut State, pos: Point3<i16>, block: Box<MapBlock>) {
-        let mut vertices = Vec::with_capacity(10000);
-        for (index, content) in block.param_0.iter().enumerate() {
-            let def = match self.nodes.get(content) {
-                Some(x) => x,
-                None => continue,
-            };
-
-            use lerp::Lerp;
-            use mt_net::{DrawType, Param1Type};
-            use std::array::from_fn as array;
-
-            match def.draw_type {
-                DrawType::Cube | DrawType::AllFaces | DrawType::AllFacesOpt => {
-                    let light = match def.param1_type {
-                        Param1Type::Light => {
-                            println!("{}", block.param_1[index]);
-
-                            block.param_1[index] as f32 / 15.0
-                        }
-                        _ => 1.0,
-                    };
-
-                    let pos: [i16; 3] = array(|i| ((index >> (4 * i)) & 0xf) as i16);
-                    for (f, face) in CUBE.iter().enumerate() {
-                        let dir = FACE_DIR[f];
-                        let npos: [i16; 3] = array(|i| dir[i] + pos[i]);
-                        if npos.iter().all(|x| (0..16).contains(x)) {
-                            let nindex = npos[0] | (npos[1] << 4) | (npos[2] << 8);
-
-                            if let Some(ndef) = self.nodes.get(&block.param_0[nindex as usize]) {
-                                if ndef.draw_type == DrawType::Cube {
-                                    continue;
-                                }
-                            }
-                        }
-
-                        let tile = &def.tiles[f];
-                        let rect = self.textures.get(&tile.texture).unwrap();
-
-                        for vertex in face.iter() {
-                            /*println!(
-                                "{:?} {:?} {:?} {:?}",
-                                (vertex.1[0], vertex.1[1]),
-                                (rect[0].start, rect[1].start),
-                                (rect[0].end, rect[1].end),
-                                (
-                                    vertex.1[0].lerp(rect[0].start, rect[0].end),
-                                    vertex.1[1].lerp(rect[1].start, rect[1].end)
-                                )
-                            );*/
-                            vertices.push(Vertex {
-                                pos: array(|i| pos[i] as f32 - 8.5 + vertex.0[i]),
-                                tex_coords: array(|i| rect[i].start.lerp(rect[i].end, vertex.1[i])),
-                                light,
-                            })
-                        }
-                    }
-                }
-                DrawType::None => {}
-                _ => {
-                    // TODO
-                }
-            }
-        }
+        let mut blend = Vec::new();
 
-        self.blocks.insert(
-            pos.into(),
-            BlockMesh {
-                vertex_buffer: state
-                    .device
-                    .create_buffer_init(&wgpu::util::BufferInitDescriptor {
-                        label: Some("mapblock.vertex_buffer"),
-                        contents: bytemuck::cast_slice(&vertices),
-                        usage: wgpu::BufferUsages::VERTEX,
-                    }),
-                num_vertices: vertices.len() as u32,
-                model: MatrixUniform::new(
-                    &state.device,
-                    &self.model,
-                    Matrix4::from_translation(
-                        pos.cast::<f32>().unwrap().to_vec() * 16.0 + Vector3::new(8.5, 8.5, 8.5),
-                    ),
-                    "mapblock",
-                    false,
-                ),
-            },
-        );
-    }
+        for (index, (pos, model)) in self.blocks.iter().enumerate() {
+            if let Some(mesh) = &model.mesh {
+                mesh.render(pass, &model.transform);
+            }
 
-    pub fn new(state: &mut State, media: &MediaMgr, nodes: HashMap<u16, NodeDef>) -> Self {
-        let mut rng = rand::thread_rng();
-        let mut atlas_map = HashMap::new();
-        let mut atlas_alloc = guillotiere::SimpleAtlasAllocator::new(guillotiere::size2(1, 1));
-
-        for node in nodes.values() {
-            let tiles = node
-                .tiles
-                .iter()
-                .chain(node.overlay_tiles.iter())
-                .chain(node.special_tiles.iter());
-
-            let load_texture = |texture: &str| {
-                let payload = media
-                    .get(texture)
-                    .ok_or_else(|| format!("texture not found: {texture}"))?;
-
-                image::load_from_memory(payload)
-                    .or_else(|_| {
-                        image::load_from_memory_with_format(payload, image::ImageFormat::Tga)
-                    })
-                    .map_err(|e| format!("failed to load texture {texture}: {e}"))
-                    .map(|x| image::imageops::flip_vertical(&x))
-            };
-
-            let mut make_texture = |texture: &str| {
-                texture
-                    .split('^')
-                    .map(|part| match load_texture(part) {
-                        Ok(v) => v,
-                        Err(e) => {
-                            if !texture.is_empty() && !texture.contains('[') {
-                                eprintln!("{e}");
-                            }
-
-                            let mut img = image::RgbImage::new(1, 1);
-                            rng.fill(&mut img.get_pixel_mut(0, 0).0);
-
-                            image::DynamicImage::from(img).to_rgba8()
-                        }
-                    })
-                    .reduce(|mut base, top| {
-                        image::imageops::overlay(&mut base, &top, 0, 0);
-                        base
-                    })
-                    .unwrap()
-            };
-
-            for tile in tiles {
-                atlas_map.entry(tile.texture.clone()).or_insert_with(|| {
-                    let img = make_texture(&tile.texture);
-
-                    let dimensions = img.dimensions();
-                    let size = guillotiere::size2(dimensions.0 as i32, dimensions.1 as i32);
-
-                    loop {
-                        match atlas_alloc.allocate(size) {
-                            None => {
-                                let mut atlas_size = atlas_alloc.size();
-                                atlas_size.width *= 2;
-                                atlas_size.height *= 2;
-                                atlas_alloc.grow(atlas_size);
-                            }
-                            Some(v) => return (img, v),
-                        }
-                    }
+            if let Some(mesh) = &model.mesh_blend {
+                blend.push(BlendEntry {
+                    index,
+                    dist: (block_float_pos(Vector3::from(*pos))
+                        - Vector3::from(state.camera.position))
+                    .magnitude(),
+                    mesh,
+                    transform: &model.transform,
                 });
             }
         }
 
-        let atlas_size = atlas_alloc.size();
-        let mut atlas = image::RgbaImage::new(atlas_size.width as u32, atlas_size.height as u32);
+        blend.sort_unstable_by(|a, b| {
+            a.dist
+                .partial_cmp(&b.dist)
+                .unwrap_or(std::cmp::Ordering::Equal)
+                .then_with(|| a.index.cmp(&b.index))
+        });
 
-        let textures = atlas_map
-            .into_iter()
-            .map(|(name, (img, rect))| {
-                let w = atlas_size.width as f32;
-                let h = atlas_size.height as f32;
+        for entry in blend {
+            entry.mesh.render(pass, entry.transform);
+        }
+    }
+
+    pub fn update(&mut self, state: &mut State) {
+        std::mem::swap(
+            self.queue_produce.lock().unwrap().deref_mut(),
+            &mut self.queue_consume,
+        );
+        for (pos, data) in self.queue_consume.drain() {
+            self.blocks.insert(
+                pos.into(),
+                BlockModel {
+                    mesh: BlockMesh::new(state, &data.vertices),
+                    mesh_blend: BlockMesh::new(state, &data.vertices_blend),
+                    transform: MatrixUniform::new(
+                        &state.device,
+                        &self.model,
+                        Matrix4::from_translation(
+                            block_float_pos(pos.to_vec()) + Vector3::new(8.5, 8.5, 8.5),
+                        ),
+                        "mapblock",
+                        false,
+                    ),
+                },
+            );
+        }
+    }
 
-                let x = (rect.min.x as f32 / w)..(rect.max.x as f32 / w);
-                let y = (rect.min.y as f32 / h)..(rect.max.y as f32 / h);
+    pub fn add_block(&self, pos: Point3<i16>, block: Box<MapBlock>) {
+        let (pos, data) = create_mesh(
+            &mut self.mesh_data_buffer.lock().unwrap(),
+            self.mesh_make_info.clone(),
+            &Default::default(),
+            pos,
+            block,
+        );
 
-                use image::GenericImage;
-                atlas
-                    .copy_from(&img, rect.min.x as u32, rect.min.y as u32)
-                    .unwrap();
+        self.queue_produce.lock().unwrap().insert(pos, data);
+    }
 
-                (name, [x, y])
-            })
-            .collect();
+    pub fn new(state: &mut State, media: &MediaMgr, mut nodes: HashMap<u16, NodeDef>) -> Self {
+        let (atlas_img, atlas_slices) = create_atlas(&mut nodes, media);
 
-        let size = wgpu::Extent3d {
-            width: atlas_size.width as u32,
-            height: atlas_size.height as u32,
+        let atlas_size = wgpu::Extent3d {
+            width: atlas_img.width(),
+            height: atlas_img.height(),
             depth_or_array_layers: 1,
         };
 
         let atlas_texture = state.device.create_texture(&wgpu::TextureDescriptor {
-            size,
+            size: atlas_size,
             mip_level_count: 1,
             sample_count: 1,
             dimension: wgpu::TextureDimension::D2,
@@ -259,13 +229,13 @@ impl MapRender {
                 origin: wgpu::Origin3d::ZERO,
                 aspect: wgpu::TextureAspect::All,
             },
-            &atlas,
+            &atlas_img,
             wgpu::ImageDataLayout {
                 offset: 0,
-                bytes_per_row: std::num::NonZeroU32::new(4 * atlas_size.width as u32),
-                rows_per_image: std::num::NonZeroU32::new(atlas_size.height as u32),
+                bytes_per_row: std::num::NonZeroU32::new(4 * atlas_img.width()),
+                rows_per_image: std::num::NonZeroU32::new(atlas_img.height()),
             },
-            size,
+            atlas_size,
         );
 
         let atlas_view = atlas_texture.create_view(&wgpu::TextureViewDescriptor::default());
@@ -386,11 +356,16 @@ impl MapRender {
 
         Self {
             pipeline,
-            nodes,
-            textures,
+            mesh_make_info: Arc::new(MeshMakeInfo {
+                nodes: std::array::from_fn(|i| nodes.get(&(i as u16)).cloned().map(Box::new)),
+                textures: atlas_slices,
+            }),
+            mesh_data_buffer: Mutex::new(0),
             atlas: atlas_bind_group,
             model: model_bind_group_layout,
             blocks: HashMap::new(),
+            queue_consume: HashMap::new(),
+            queue_produce: Arc::new(Mutex::new(HashMap::new())),
         }
     }
 }
@@ -446,13 +421,3 @@ const CUBE: [[([f32; 3], [f32; 2]); 6]; 6] = [
                ([-0.5,  0.5, -0.5], [ 0.0,  1.0]),
        ],
 ];
-
-#[rustfmt::skip]
-const FACE_DIR: [[i16; 3]; 6] = [
-       [ 0,  1,  0],
-       [ 0, -1,  0],
-       [ 1,  0,  0],
-       [-1,  0,  0],
-       [ 0,  0,  1],
-       [ 0,  0, -1],
-];