Skip to main content

concinnity_asset/
voxel_chunk.rs

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