Skip to main content

concinnity_core/components/
voxel_chunk.rs

1// Voxel-chunk schema.
2
3use crate::ecs::PayloadLocator;
4use crate::ecs::asset_id::AssetId;
5use alloc::vec::Vec;
6
7/// A voxel grid that compiles into a single mesh.
8///
9/// A dense grid of blocks compiled into a single mesh at build time. Use one
10/// chunk per region of a voxel/Minecraft-style world; reference it from a
11/// [Prop](#prop)'s `mesh` field. Hidden faces between two solid blocks are
12/// dropped, so a fully filled chunk contributes zero triangles to its interior.
13///
14/// The palette must contain at least one entry whose [BlockType](#blocktype) has
15/// `solid: false` (typically named `air`); cells whose palette entry is
16/// non-solid emit no faces. Faces are only emitted between a solid block and
17/// either an empty neighbour or the outside of the chunk.
18#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
19#[serde(default)]
20pub struct VoxelChunk {
21    /// Asset identity; injected via `inject_name`. Not part of `args`.
22    #[serde(skip)]
23    pub asset_id: AssetId,
24    /// [BlockType](#blocktype) asset names. `blocks[i]` is an index into this list.
25    pub palette: Vec<AssetId>,
26    /// Chunk dimensions `[dx, dy, dz]` in blocks.
27    pub dim: [u32; 3],
28    /// World units per block edge.
29    pub block_size: f32,
30    /// Flat block array, length `dx*dy*dz`. Index = `x + y*dx + z*dx*dy`.
31    pub blocks: Vec<u32>,
32    /// Number of level-of-detail versions to generate, including the original.
33    /// `1` (the default) generates none.
34    pub lod_levels: u32,
35    /// Camera distances at which to switch to each lower-detail version; empty
36    /// lets the build choose defaults.
37    #[serde(default)]
38    pub lod_distances: Vec<f32>,
39    /// Injected at load time from the compiled blob payload.
40    #[serde(skip)]
41    pub locator: Option<PayloadLocator>,
42}
43
44impl Default for VoxelChunk {
45    fn default() -> Self {
46        Self {
47            asset_id: AssetId::default(),
48            palette: Vec::new(),
49            dim: [0, 0, 0],
50            block_size: 1.0,
51            blocks: Vec::new(),
52            lod_levels: 1,
53            lod_distances: Vec::new(),
54            locator: None,
55        }
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    #[test]
64    fn a_blank_chunk_is_empty_with_metre_sized_blocks() {
65        let c = VoxelChunk::default();
66        assert_eq!(c.dim, [0, 0, 0]);
67        assert_eq!(c.block_size, 1.0);
68        assert!(c.blocks.is_empty());
69        assert!(c.palette.is_empty());
70        assert_eq!(c.lod_levels, 1);
71        assert!(c.lod_distances.is_empty());
72        assert!(c.locator.is_none());
73    }
74
75    #[test]
76    fn an_authored_chunk_parses_and_round_trips_through_postcard() {
77        crate::test_support::install_resolvers();
78        let c: VoxelChunk = serde_json::from_str(
79            r#"{"palette":["air","stone"],"dim":[2,1,2],"block_size":0.5,
80                "blocks":[0,1,1,0],"lod_levels":2,"lod_distances":[16]}"#,
81        )
82        .unwrap();
83        assert_eq!(c.palette, [AssetId(3), AssetId(5)]);
84        // The block list indexes the palette, one entry per cell in `dim`.
85        assert_eq!(c.blocks.len() as u32, c.dim[0] * c.dim[1] * c.dim[2]);
86
87        let bytes = postcard::to_allocvec(&c).unwrap();
88        let back: VoxelChunk = postcard::from_bytes(&bytes).unwrap();
89        assert_eq!(back.dim, [2, 1, 2]);
90        assert_eq!(back.block_size, 0.5);
91        assert_eq!(back.blocks, [0, 1, 1, 0]);
92        assert_eq!(back.lod_levels, 2);
93        assert_eq!(back.lod_distances, [16.0]);
94        assert_eq!(back.asset_id, AssetId::default());
95    }
96}