qualia_core_db/container_10d/
voxel_section.rs1use 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#[repr(C)]
33#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
34pub struct VoxelSectionMiniHeader {
35 pub magic: [u8; 4],
37 pub version: u16,
39 pub flags: u16,
41 pub node_count: u32,
43 pub stride: u32,
45 pub root_node_index: u32,
47 pub max_depth: u16,
49 pub _pad: u16,
51 pub aabb_min: [f32; 3],
53 pub aabb_max: [f32; 3],
55 pub voxel_resolution_mm: f32,
57 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, _reserved: [0; 12],
76 }
77 }
78}
79
80#[repr(C, align(16))]
82#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
83pub struct Vox0DagNode {
84 pub child_mask: u8,
86 pub leaf_mask: u8,
88 pub primary_material_lut: u8,
90 pub secondary_material_lut: u8,
92 pub child_ptr_or_density: u32,
94 pub normal_oct_snorm8: [i8; 2],
96 pub moisture_u8: u8,
98 pub compaction_u8: u8,
100 pub node_crc16: u16,
102 pub _reserved: [u8; 2],
104}
105
106impl Default for Vox0DagNode {
107 fn default() -> Self {
108 Self {
109 child_mask: 0,
110 leaf_mask: 0xFF, primary_material_lut: 1, secondary_material_lut: 1,
113 child_ptr_or_density: 0,
114 normal_oct_snorm8: [0, 127], moisture_u8: 128,
116 compaction_u8: 100,
117 node_crc16: 0,
118 _reserved: [0; 2],
119 }
120 }
121}
122
123impl Vox0DagNode {
124 #[inline]
126 pub fn has_child(&self, octant: usize) -> bool {
127 (self.child_mask & (1 << (octant & 7))) != 0
128 }
129
130 #[inline]
132 pub fn is_leaf(&self, octant: usize) -> bool {
133 (self.leaf_mask & (1 << (octant & 7))) != 0
134 }
135
136 #[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 #[inline]
156 pub fn update_crc(&mut self) {
157 self.node_crc16 = self.compute_crc16();
158 }
159
160 #[inline]
162 pub fn validate(&self) -> bool {
163 self.node_crc16 == self.compute_crc16()
164 }
165}
166
167#[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
178pub 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
205pub 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; 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; 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]; assert!(matches!(
317 encode_voxel_section(&header, &nodes, &mut small_buf),
318 Err(VoxelSectionError::BufferTooSmall { .. })
319 ));
320
321 assert!(matches!(
323 parse_voxel_section(&small_buf),
324 Err(VoxelSectionError::BufferTooSmall { .. })
325 ));
326
327 #[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'; assert!(matches!(
334 parse_voxel_section(&valid_buf.0[..written]),
335 Err(VoxelSectionError::InvalidMagic)
336 ));
337 }
338}