Skip to main content

qualia_core_db/container_10d/
voxel_section.rs

1//! Section 22 (`VOX0`): 3D Sparse Voxel Octree / DAG Lattice Section.
2//!
3//! Encodes volumetric underground strata, cavities, root networks, and CSG excavations
4//! using a 16-byte cache-friendly Directed Acyclic Graph (`Vox0DagNode`).
5//!
6//! # 16-Byte POD Binary Layout (`Vox0DagNode`)
7//!
8//! | Offset | Type | Field | Description |
9//! |---|---|---|---|
10//! | `0x00` | `u8` | `child_mask` | Valid child octant presence bitmask (8 bits) |
11//! | `0x01` | `u8` | `leaf_mask` | Octants terminating as leaves (8 bits) |
12//! | `0x02` | `u8` | `primary_material_lut` | Majority constituent LUT index (0..255) |
13//! | `0x03` | `u8` | `secondary_material_lut` | Secondary constituent LUT index (0..255) |
14//! | `0x04` | `u32` | `child_ptr_or_density` | SVO index to child cluster, or packed density |
15//! | `0x08` | `[i8; 2]` | `normal_oct_snorm8` | Octahedral encoded surface normal vector |
16//! | `0x0A` | `u8` | `moisture_u8` | Volumetric water saturation Sw (0..255) |
17//! | `0x0B` | `u8` | `compaction_u8` | Overburden compaction / hardness metric |
18//! | `0x0C` | `u16` | `node_crc16` | Integrity checksum over bytes 0..11 |
19//! | `0x0E` | `[u8; 2]` | `_reserved` | Explicit zero padding to 16 bytes |
20
21use bytemuck::{bytes_of, cast_slice, Pod, Zeroable};
22
23pub const VOXEL_SECTION_VERSION: u16 = 1;
24pub const VOXEL_MINI_HEADER_SIZE: usize = 64;
25pub const VOX0_NODE_SIZE: usize = 16;
26pub const MAGIC_VOX0: [u8; 4] = *b"VOX0";
27
28pub const FLAG_VOXEL_COMPACT_DAG: u16 = 1 << 0;
29pub const FLAG_VOXEL_HAS_EXCAVATIONS: u16 = 1 << 1;
30
31/// 64-Byte POD Mini Header for SectionType::VoxelLattice (22).
32#[repr(C)]
33#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
34pub struct VoxelSectionMiniHeader {
35    /// 4B: ASCII magic bytes "VOX0".
36    pub magic: [u8; 4],
37    /// 2B: Section version (1).
38    pub version: u16,
39    /// 2B: Feature flags (e.g. compact DAG vs octree).
40    pub flags: u16,
41    /// 4B: Total count of 16-byte Vox0DagNode records.
42    pub node_count: u32,
43    /// 4B: Stride of each node record in bytes (16).
44    pub stride: u32,
45    /// 4B: Array index of the root node.
46    pub root_node_index: u32,
47    /// 2B: Maximum tree depth.
48    pub max_depth: u16,
49    /// 2B: Explicit padding.
50    pub _pad: u16,
51    /// 12B: Minimum spatial bounding box in local millimeters.
52    pub aabb_min: [f32; 3],
53    /// 12B: Maximum spatial bounding box in local millimeters.
54    pub aabb_max: [f32; 3],
55    /// 4B: Leaf voxel spatial resolution in millimeters.
56    pub voxel_resolution_mm: f32,
57    /// 12B: Reserved padding to reach 64 bytes.
58    pub _reserved: [u8; 12],
59}
60
61impl Default for VoxelSectionMiniHeader {
62    fn default() -> Self {
63        Self {
64            magic: MAGIC_VOX0,
65            version: VOXEL_SECTION_VERSION,
66            flags: 0,
67            node_count: 0,
68            stride: VOX0_NODE_SIZE as u32,
69            root_node_index: 0,
70            max_depth: 8,
71            _pad: 0,
72            aabb_min: [-32000.0, -32000.0, -10000.0],
73            aabb_max: [32000.0, 32000.0, 10000.0],
74            voxel_resolution_mm: 250.0, // 25cm default leaf voxel
75            _reserved: [0; 12],
76        }
77    }
78}
79
80/// 16-Byte POD Node Record for Sparse Voxel Octrees and DAGs.
81#[repr(C, align(16))]
82#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
83pub struct Vox0DagNode {
84    /// 1B: Valid octant child bitmask (bits 0..7).
85    pub child_mask: u8,
86    /// 1B: Bitmask of octants that terminate as solid leaves (bits 0..7).
87    pub leaf_mask: u8,
88    /// 1B: Primary constituent LUT index (0..255).
89    pub primary_material_lut: u8,
90    /// 1B: Secondary constituent LUT index (0..255).
91    pub secondary_material_lut: u8,
92    /// 4B: Child pointer into node array (when non-leaf) or packed density.
93    pub child_ptr_or_density: u32,
94    /// 2B: Octahedrally-encoded surface normal vector.
95    pub normal_oct_snorm8: [i8; 2],
96    /// 1B: Volumetric moisture saturation Sw (0..255 maps to 0..100%).
97    pub moisture_u8: u8,
98    /// 1B: Soil compaction / hardness metric (0..255).
99    pub compaction_u8: u8,
100    /// 2B: CRC-16 checksum of bytes 0..11.
101    pub node_crc16: u16,
102    /// 2B: Explicit zero padding to 16 bytes.
103    pub _reserved: [u8; 2],
104}
105
106impl Default for Vox0DagNode {
107    fn default() -> Self {
108        Self {
109            child_mask: 0,
110            leaf_mask: 0xFF, // Solid leaf by default
111            primary_material_lut: 1, // Topsoil default
112            secondary_material_lut: 1,
113            child_ptr_or_density: 0,
114            normal_oct_snorm8: [0, 127], // Up vector
115            moisture_u8: 128,
116            compaction_u8: 100,
117            node_crc16: 0,
118            _reserved: [0; 2],
119        }
120    }
121}
122
123impl Vox0DagNode {
124    /// Returns true if the child octant (0..7) exists in the lattice.
125    #[inline]
126    pub fn has_child(&self, octant: usize) -> bool {
127        (self.child_mask & (1 << (octant & 7))) != 0
128    }
129
130    /// Returns true if the child octant (0..7) terminates as a leaf.
131    #[inline]
132    pub fn is_leaf(&self, octant: usize) -> bool {
133        (self.leaf_mask & (1 << (octant & 7))) != 0
134    }
135
136    /// Compute simple CRC-16 (IBM polynomial 0xA001) over bytes 0..11.
137    #[inline]
138    pub fn compute_crc16(&self) -> u16 {
139        let bytes: &[u8; VOX0_NODE_SIZE] = bytemuck::cast_ref(self);
140        let mut crc = 0xFFFFu16;
141        for &b in &bytes[..12] {
142            crc ^= b as u16;
143            for _ in 0..8 {
144                if (crc & 1) != 0 {
145                    crc = (crc >> 1) ^ 0xA001;
146                } else {
147                    crc >>= 1;
148                }
149            }
150        }
151        crc
152    }
153
154    /// Update `node_crc16` with the computed checksum.
155    #[inline]
156    pub fn update_crc(&mut self) {
157        self.node_crc16 = self.compute_crc16();
158    }
159
160    /// Validate the CRC-16 of this node.
161    #[inline]
162    pub fn validate(&self) -> bool {
163        self.node_crc16 == self.compute_crc16()
164    }
165}
166
167/// Errors during voxel section encode/decode.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub enum VoxelSectionError {
170    BufferTooSmall { required: usize, provided: usize },
171    InvalidMagic,
172    UnsupportedVersion(u16),
173    InvalidStride(u32),
174    NodeCountOverflow,
175    MisalignedBuffer,
176}
177
178/// Encode a voxel section into a caller-supplied fixed slice without heap allocation.
179pub fn encode_voxel_section(
180    header: &VoxelSectionMiniHeader,
181    nodes: &[Vox0DagNode],
182    out: &mut [u8],
183) -> Result<usize, VoxelSectionError> {
184    let required_len = VOXEL_MINI_HEADER_SIZE + nodes.len() * VOX0_NODE_SIZE;
185    if out.len() < required_len {
186        return Err(VoxelSectionError::BufferTooSmall {
187            required: required_len,
188            provided: out.len(),
189        });
190    }
191
192    let mut header_copy = *header;
193    header_copy.magic = MAGIC_VOX0;
194    header_copy.version = VOXEL_SECTION_VERSION;
195    header_copy.node_count = nodes.len() as u32;
196    header_copy.stride = VOX0_NODE_SIZE as u32;
197
198    out[..VOXEL_MINI_HEADER_SIZE].copy_from_slice(bytes_of(&header_copy));
199    let nodes_bytes: &[u8] = cast_slice(nodes);
200    out[VOXEL_MINI_HEADER_SIZE..required_len].copy_from_slice(nodes_bytes);
201
202    Ok(required_len)
203}
204
205/// Zero-copy parse a voxel section from a byte slice.
206pub fn parse_voxel_section(
207    bytes: &[u8],
208) -> Result<(&VoxelSectionMiniHeader, &[Vox0DagNode]), VoxelSectionError> {
209    if bytes.len() < VOXEL_MINI_HEADER_SIZE {
210        return Err(VoxelSectionError::BufferTooSmall {
211            required: VOXEL_MINI_HEADER_SIZE,
212            provided: bytes.len(),
213        });
214    }
215
216    let (header_bytes, payload) = bytes.split_at(VOXEL_MINI_HEADER_SIZE);
217    let header: &VoxelSectionMiniHeader = bytemuck::try_from_bytes(header_bytes)
218        .map_err(|_| VoxelSectionError::MisalignedBuffer)?;
219
220    if header.magic != MAGIC_VOX0 {
221        return Err(VoxelSectionError::InvalidMagic);
222    }
223    if header.version != VOXEL_SECTION_VERSION {
224        return Err(VoxelSectionError::UnsupportedVersion(header.version));
225    }
226    if header.stride != VOX0_NODE_SIZE as u32 {
227        return Err(VoxelSectionError::InvalidStride(header.stride));
228    }
229
230    let expected_payload_len = header.node_count as usize * VOX0_NODE_SIZE;
231    if payload.len() < expected_payload_len {
232        return Err(VoxelSectionError::BufferTooSmall {
233            required: expected_payload_len,
234            provided: payload.len(),
235        });
236    }
237
238    let nodes: &[Vox0DagNode] = bytemuck::try_cast_slice(&payload[..expected_payload_len])
239        .map_err(|_| VoxelSectionError::MisalignedBuffer)?;
240
241    Ok((header, nodes))
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    #[test]
249    fn test_vox0_dag_node_size_and_alignment() {
250        assert_eq!(
251            std::mem::size_of::<Vox0DagNode>(),
252            16,
253            "Vox0DagNode must be exactly 16 bytes"
254        );
255        assert_eq!(
256            std::mem::align_of::<Vox0DagNode>(),
257            16,
258            "Vox0DagNode must have 16-byte alignment"
259        );
260    }
261
262    #[test]
263    fn test_voxel_section_mini_header_size() {
264        assert_eq!(
265            std::mem::size_of::<VoxelSectionMiniHeader>(),
266            64,
267            "VoxelSectionMiniHeader must be exactly 64 bytes"
268        );
269    }
270
271    #[test]
272    fn test_voxel_section_encode_decode_roundtrip() {
273        let mut header = VoxelSectionMiniHeader::default();
274        header.voxel_resolution_mm = 125.0;
275
276        let mut node1 = Vox0DagNode::default();
277        node1.child_mask = 0b0000_1111;
278        node1.primary_material_lut = 2; // Clay
279        node1.update_crc();
280        assert!(node1.validate());
281
282        let mut node2 = Vox0DagNode::default();
283        node2.child_mask = 0b1111_0000;
284        node2.primary_material_lut = 5; // Basalt
285        node2.update_crc();
286        assert!(node2.validate());
287
288        let nodes = [node1, node2];
289        #[repr(align(64))]
290        struct AlignedBuffer([u8; 256]);
291        let mut buffer = AlignedBuffer([0u8; 256]);
292
293        let written = encode_voxel_section(&header, &nodes, &mut buffer.0).expect("encode succeeds");
294        assert_eq!(written, 64 + 32);
295
296        let (parsed_header, parsed_nodes) =
297            parse_voxel_section(&buffer.0[..written]).expect("parse succeeds");
298
299        assert_eq!(parsed_header.magic, MAGIC_VOX0);
300        assert_eq!(parsed_header.node_count, 2);
301        assert_eq!(parsed_header.voxel_resolution_mm, 125.0);
302        assert_eq!(parsed_nodes.len(), 2);
303        assert_eq!(parsed_nodes[0].primary_material_lut, 2);
304        assert_eq!(parsed_nodes[1].primary_material_lut, 5);
305        assert!(parsed_nodes[0].validate());
306        assert!(parsed_nodes[1].validate());
307    }
308
309    #[test]
310    fn test_voxel_section_error_handling() {
311        let header = VoxelSectionMiniHeader::default();
312        let nodes = [Vox0DagNode::default()];
313        let mut small_buf = [0u8; 32]; // Less than 64B header
314
315        // Buffer too small for encode
316        assert!(matches!(
317            encode_voxel_section(&header, &nodes, &mut small_buf),
318            Err(VoxelSectionError::BufferTooSmall { .. })
319        ));
320
321        // Buffer too small for parse
322        assert!(matches!(
323            parse_voxel_section(&small_buf),
324            Err(VoxelSectionError::BufferTooSmall { .. })
325        ));
326
327        // Corrupted magic with aligned buffer
328        #[repr(align(64))]
329        struct AlignedBuffer([u8; 128]);
330        let mut valid_buf = AlignedBuffer([0u8; 128]);
331        let written = encode_voxel_section(&header, &nodes, &mut valid_buf.0).unwrap();
332        valid_buf.0[0] = b'X'; // Corrupt magic "XOX0"
333        assert!(matches!(
334            parse_voxel_section(&valid_buf.0[..written]),
335            Err(VoxelSectionError::InvalidMagic)
336        ));
337    }
338}