voxel_framework/chunk/storage.rs
1//! The [`Chunk<V>`] data structure — a fixed-size, flat-array 3D voxel grid.
2
3use bevy::prelude::Component;
4
5use super::{CHUNK_SIZE, CHUNK_VOLUME};
6use crate::voxel::VoxelType;
7
8/// A 16×16×16 block of voxels — the fundamental unit of world storage.
9///
10/// `Chunk<V>` is a Bevy [`Component`] that holds all voxel data for one
11/// 16-voxel-per-axis region of the world. It is generic over any type
12/// implementing [`VoxelType`], so it works with [`crate::voxel::DefaultVoxel`]
13/// out of the box and with custom palettes without any changes to the framework.
14///
15/// ## Memory layout
16///
17/// Voxels are stored in a single heap-allocated array of length
18/// [`CHUNK_VOLUME`] (`4 096`), indexed in **X-major order**:
19///
20/// ```text
21/// flat_index = x * CHUNK_SIZE² + y * CHUNK_SIZE + z
22/// ```
23///
24/// This means a full row of Z-adjacent voxels is contiguous in memory —
25/// the layout the greedy meshing algorithm iterates most frequently.
26/// Both arrays are boxed, so the struct itself stays a few machine words
27/// regardless of `V`'s size.
28///
29/// ## Block states
30///
31/// Each voxel has a companion `u8` **state byte** stored in a parallel
32/// `states` array. The state byte is set automatically by the placement system
33/// to record which face the block was placed against (bits 0-2, see
34/// [`face_to_state`]):
35///
36/// | Bits | Meaning |
37/// |------|---------|
38/// | 0–2 | Placement face (0=+X, 1=−X, 2=+Y, 3=−Y, 4=+Z, 5=−Z, 6=unknown) |
39/// | 3–7 | Reserved for game-specific use |
40///
41/// Games may read and write state bytes freely via [`Chunk::get_state`] /
42/// [`Chunk::set_state`] for door open/close flags, liquid level, growth stage,
43/// or any other per-voxel metadata.
44///
45/// ## Unsaved changes
46///
47/// A chunk remembers whether its data changed since it was generated, loaded
48/// from disk or last saved (see [`Chunk::is_dirty`]). [`Chunk::set`] and
49/// [`Chunk::set_state`] set the flag when they change a value; the persistence
50/// systems save only dirty chunks and clear it. Writing the public `states`
51/// array directly is **not** tracked — call [`Chunk::mark_dirty`] afterwards.
52///
53/// ## Coordinate bounds
54///
55/// Every method that takes `(x, y, z)` expects each coordinate in
56/// `[0, CHUNK_SIZE)` (i.e. `0..16`). Out-of-bounds access panics in debug
57/// builds via [`debug_assert`] inside [`Chunk::get_index`]. In release builds,
58/// out-of-bounds indices silently alias other voxels — callers must ensure
59/// correct inputs.
60///
61/// Use [`crate::chunk::world_to_local_coord`] to convert a world-space
62/// position to a valid `(x, y, z)` triple before calling `get` or `set`.
63///
64/// # See also
65///
66/// - [`crate::chunk`] — coordinate systems and conversion helpers.
67/// - [`crate::voxel::VoxelType`] — the trait `V` must implement.
68#[derive(Component, Clone, Debug)]
69pub struct Chunk<V: VoxelType> {
70 voxels: Box<[V; CHUNK_VOLUME]>,
71 /// Per-voxel state bytes — parallel array to `voxels`.
72 ///
73 /// Bits 0–2 encode the placement face; bits 3–7 are reserved for games.
74 /// All states are initialised to `0` (face = +X, conventional default).
75 ///
76 /// Prefer [`Chunk::set_state`]: direct writes to this array do not mark
77 /// the chunk as modified (see [`Chunk::mark_dirty`]).
78 pub states: Box<[u8; CHUNK_VOLUME]>,
79 /// `true` when the data differs from what was generated, loaded or last
80 /// saved.
81 dirty: bool,
82}
83
84/// Converts a world-space face normal to a placement-face state byte (bits 0–2).
85///
86/// | Normal | State |
87/// |--------|-------|
88/// | +X | 0 |
89/// | −X | 1 |
90/// | +Y | 2 |
91/// | −Y | 3 |
92/// | +Z | 4 |
93/// | −Z | 5 |
94/// | other | 6 |
95///
96/// The returned value is in `[0, 6]` and occupies only bits 0–2 so it can be
97/// OR-ed with the upper bits of an existing state byte without clobbering them.
98pub fn face_to_state(normal: bevy::math::IVec3) -> u8 {
99 match (normal.x, normal.y, normal.z) {
100 (1, 0, 0) => 0,
101 (-1, 0, 0) => 1,
102 (0, 1, 0) => 2,
103 (0, -1, 0) => 3,
104 (0, 0, 1) => 4,
105 (0, 0, -1) => 5,
106 _ => 6,
107 }
108}
109
110impl<V: VoxelType> Chunk<V> {
111 /// Creates a new chunk with every voxel initialized to [`VoxelType::air`]
112 /// and every state byte set to `0`.
113 ///
114 /// Allocates two [`CHUNK_VOLUME`]-element arrays on the heap.
115 pub fn new() -> Self {
116 Self {
117 voxels: Box::new([V::air(); CHUNK_VOLUME]),
118 states: Box::new([0u8; CHUNK_VOLUME]),
119 dirty: false,
120 }
121 }
122
123 /// Returns `true` if the chunk has changes that were not saved.
124 ///
125 /// A chunk from [`Chunk::new`] is clean. [`Chunk::set`] and
126 /// [`Chunk::set_state`] mark it dirty when they change a value. The
127 /// generator pipeline hands out clean chunks, so freshly generated or
128 /// restored terrain is never written to disk until something edits it.
129 #[inline]
130 pub fn is_dirty(&self) -> bool {
131 self.dirty
132 }
133
134 /// Marks the chunk as matching its saved (or regenerable) form.
135 ///
136 /// Call this after saving a chunk yourself, or after filling a chunk whose
137 /// contents can be reproduced and therefore need not be saved.
138 #[inline]
139 pub fn mark_clean(&mut self) {
140 self.dirty = false;
141 }
142
143 /// Marks the chunk as having unsaved changes.
144 ///
145 /// Needed only after writing the public `states` array directly, which the
146 /// chunk cannot observe.
147 #[inline]
148 pub fn mark_dirty(&mut self) {
149 self.dirty = true;
150 }
151
152 /// Computes the flat array index for the voxel at local coordinate `(x, y, z)`.
153 ///
154 /// The formula is `x * CHUNK_SIZE² + y * CHUNK_SIZE + z`, giving X-major
155 /// (row-major with X as the outermost dimension) storage order.
156 ///
157 /// Prefer calling [`Chunk::get`] or [`Chunk::set`] directly; this method is
158 /// public for use by the meshing and persistence systems that need to
159 /// iterate the flat array efficiently.
160 ///
161 /// # Panics
162 ///
163 /// Panics in **debug builds** if any coordinate is `>= CHUNK_SIZE`. In
164 /// release builds, the assertion is omitted for performance.
165 #[inline]
166 pub fn get_index(x: usize, y: usize, z: usize) -> usize {
167 debug_assert!(x < CHUNK_SIZE, "x={x} out of range");
168 debug_assert!(y < CHUNK_SIZE, "y={y} out of range");
169 debug_assert!(z < CHUNK_SIZE, "z={z} out of range");
170 x * CHUNK_SIZE * CHUNK_SIZE + y * CHUNK_SIZE + z
171 }
172
173 /// Returns a copy of the voxel at local coordinate `(x, y, z)`.
174 ///
175 /// Each coordinate must be in `[0, CHUNK_SIZE)`. The value is returned by
176 /// copy because [`VoxelType`] requires `Copy`.
177 ///
178 /// # Panics
179 ///
180 /// Panics in debug builds if any coordinate is out of bounds (see
181 /// [`Chunk::get_index`]).
182 #[inline]
183 pub fn get(&self, x: usize, y: usize, z: usize) -> V {
184 self.voxels[Self::get_index(x, y, z)]
185 }
186
187 /// Overwrites the voxel at local coordinate `(x, y, z)` with `voxel`.
188 ///
189 /// Each coordinate must be in `[0, CHUNK_SIZE)`. Use
190 /// [`VoxelType::air`] to clear a voxel back to empty.
191 ///
192 /// After calling this method on an already-spawned chunk entity, emit a
193 /// [`crate::world::ChunkModified`] event so that the mesh system
194 /// regenerates the chunk's geometry.
195 ///
196 /// # Panics
197 ///
198 /// Panics in debug builds if any coordinate is out of bounds (see
199 /// [`Chunk::get_index`]).
200 #[inline]
201 pub fn set(&mut self, x: usize, y: usize, z: usize, voxel: V) {
202 let slot = &mut self.voxels[Self::get_index(x, y, z)];
203 if *slot != voxel {
204 *slot = voxel;
205 self.dirty = true;
206 }
207 }
208
209 /// Returns the state byte for the voxel at local coordinate `(x, y, z)`.
210 ///
211 /// Bits 0–2 hold the placement face (see [`face_to_state`]); bits 3–7 are
212 /// available for game-specific use. Returns `0` for voxels that have never
213 /// been explicitly placed (e.g. generator-filled voxels).
214 ///
215 /// # Panics
216 ///
217 /// Panics in debug builds if any coordinate is out of bounds.
218 #[inline]
219 pub fn get_state(&self, x: usize, y: usize, z: usize) -> u8 {
220 self.states[Self::get_index(x, y, z)]
221 }
222
223 /// Overwrites the state byte for the voxel at local coordinate `(x, y, z)`.
224 ///
225 /// Games may set bits 3–7 freely. Bits 0–2 are normally written by the
226 /// placement system via [`face_to_state`].
227 ///
228 /// # Panics
229 ///
230 /// Panics in debug builds if any coordinate is out of bounds.
231 #[inline]
232 pub fn set_state(&mut self, x: usize, y: usize, z: usize, state: u8) {
233 let slot = &mut self.states[Self::get_index(x, y, z)];
234 if *slot != state {
235 *slot = state;
236 self.dirty = true;
237 }
238 }
239
240 /// Returns `true` if the voxel at local coordinate `(x, y, z)` is solid.
241 ///
242 /// Equivalent to `self.get(x, y, z).is_solid()`. Used by the meshing and
243 /// occlusion systems to test individual voxels without materializing the
244 /// full voxel value.
245 ///
246 /// # Panics
247 ///
248 /// Panics in debug builds if any coordinate is out of bounds.
249 #[inline]
250 pub fn is_solid_at(&self, x: usize, y: usize, z: usize) -> bool {
251 self.get(x, y, z).is_solid()
252 }
253
254 /// Returns `true` if every voxel in the chunk is solid.
255 ///
256 /// A fully solid chunk is opaque from all six faces and requires no
257 /// interior face geometry. The occlusion system uses this to skip mesh
258 /// generation for completely buried chunks.
259 ///
260 /// Runs in O([`CHUNK_VOLUME`]) time by scanning the flat array.
261 pub fn is_fully_solid(&self) -> bool {
262 self.voxels.iter().all(|v| v.is_solid())
263 }
264
265 /// Returns `true` if every voxel in the chunk is air (non-solid).
266 ///
267 /// An empty chunk produces no geometry. The streaming system uses this
268 /// to avoid spawning mesh entities for chunks that contain only air,
269 /// such as the open space above a terrain surface or inside a cave ceiling.
270 ///
271 /// Runs in O([`CHUNK_VOLUME`]) time by scanning the flat array.
272 pub fn is_empty(&self) -> bool {
273 self.voxels.iter().all(|v| !v.is_solid())
274 }
275
276 /// Extracts a 16x16 border slice for one of the six chunk faces.
277 ///
278 /// The returned array contains the voxels on the outermost layer in the
279 /// direction indicated by `face`:
280 ///
281 /// | Face | Direction | Fixed axis value |
282 /// |------|-----------|-----------------|
283 /// | 0 | +Y | y = 15 |
284 /// | 1 | -Y | y = 0 |
285 /// | 2 | +X | x = 15 |
286 /// | 3 | -X | x = 0 |
287 /// | 4 | +Z | z = 15 |
288 /// | 5 | -Z | z = 0 |
289 ///
290 /// The slice is packed in row-major order for the two varying axes.
291 ///
292 /// # Panics
293 ///
294 /// Panics if `face >= 6`.
295 pub fn border_slice(&self, face: usize) -> [V; CHUNK_SIZE * CHUNK_SIZE] {
296 let mut slice = [V::air(); CHUNK_SIZE * CHUNK_SIZE];
297 let last = CHUNK_SIZE - 1;
298
299 match face {
300 // +Y (y = 15): iterate x, z
301 0 => {
302 for x in 0..CHUNK_SIZE {
303 for z in 0..CHUNK_SIZE {
304 slice[x * CHUNK_SIZE + z] = self.get(x, last, z);
305 }
306 }
307 }
308 // -Y (y = 0): iterate x, z
309 1 => {
310 for x in 0..CHUNK_SIZE {
311 for z in 0..CHUNK_SIZE {
312 slice[x * CHUNK_SIZE + z] = self.get(x, 0, z);
313 }
314 }
315 }
316 // +X (x = 15): iterate y, z
317 2 => {
318 for y in 0..CHUNK_SIZE {
319 for z in 0..CHUNK_SIZE {
320 slice[y * CHUNK_SIZE + z] = self.get(last, y, z);
321 }
322 }
323 }
324 // -X (x = 0): iterate y, z
325 3 => {
326 for y in 0..CHUNK_SIZE {
327 for z in 0..CHUNK_SIZE {
328 slice[y * CHUNK_SIZE + z] = self.get(0, y, z);
329 }
330 }
331 }
332 // +Z (z = 15): iterate x, y
333 4 => {
334 for x in 0..CHUNK_SIZE {
335 for y in 0..CHUNK_SIZE {
336 slice[x * CHUNK_SIZE + y] = self.get(x, y, last);
337 }
338 }
339 }
340 // -Z (z = 0): iterate x, y
341 5 => {
342 for x in 0..CHUNK_SIZE {
343 for y in 0..CHUNK_SIZE {
344 slice[x * CHUNK_SIZE + y] = self.get(x, y, 0);
345 }
346 }
347 }
348 _ => panic!("invalid face index: {face} (must be 0..6)"),
349 }
350
351 slice
352 }
353}
354
355impl<V: VoxelType> Default for Chunk<V> {
356 fn default() -> Self {
357 Self::new()
358 }
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364 use crate::voxel::DefaultVoxel;
365
366 #[test]
367 fn new_chunk_is_all_air() {
368 let chunk = Chunk::<DefaultVoxel>::new();
369 for x in 0..CHUNK_SIZE {
370 for y in 0..CHUNK_SIZE {
371 for z in 0..CHUNK_SIZE {
372 assert_eq!(chunk.get(x, y, z), DefaultVoxel::Air);
373 }
374 }
375 }
376 }
377
378 #[test]
379 fn new_chunk_is_clean() {
380 assert!(!Chunk::<DefaultVoxel>::new().is_dirty());
381 }
382
383 #[test]
384 fn changing_a_voxel_or_state_marks_the_chunk_dirty() {
385 let mut chunk = Chunk::<DefaultVoxel>::new();
386 chunk.set(1, 2, 3, DefaultVoxel::Rock);
387 assert!(chunk.is_dirty());
388
389 let mut chunk = Chunk::<DefaultVoxel>::new();
390 chunk.set_state(1, 2, 3, 5);
391 assert!(chunk.is_dirty());
392 }
393
394 #[test]
395 fn writing_the_same_value_keeps_the_chunk_clean() {
396 let mut chunk = Chunk::<DefaultVoxel>::new();
397 chunk.set(1, 2, 3, DefaultVoxel::Air);
398 chunk.set_state(1, 2, 3, 0);
399 assert!(!chunk.is_dirty());
400 }
401
402 #[test]
403 fn mark_clean_and_mark_dirty_override_the_flag() {
404 let mut chunk = Chunk::<DefaultVoxel>::new();
405 chunk.set(0, 0, 0, DefaultVoxel::Rock);
406 chunk.mark_clean();
407 assert!(!chunk.is_dirty());
408 // Still clean when the same value is written again.
409 chunk.set(0, 0, 0, DefaultVoxel::Rock);
410 assert!(!chunk.is_dirty());
411 chunk.mark_dirty();
412 assert!(chunk.is_dirty());
413 }
414
415 #[test]
416 fn get_set_round_trip() {
417 let mut chunk = Chunk::<DefaultVoxel>::new();
418 chunk.set(3, 7, 11, DefaultVoxel::IronOre);
419 assert_eq!(chunk.get(3, 7, 11), DefaultVoxel::IronOre);
420
421 chunk.set(0, 0, 0, DefaultVoxel::RareMineral);
422 assert_eq!(chunk.get(0, 0, 0), DefaultVoxel::RareMineral);
423
424 chunk.set(15, 15, 15, DefaultVoxel::SiliconCrystal);
425 assert_eq!(chunk.get(15, 15, 15), DefaultVoxel::SiliconCrystal);
426 }
427
428 #[test]
429 fn is_fully_solid_on_filled_chunk() {
430 let mut chunk = Chunk::<DefaultVoxel>::new();
431 for x in 0..CHUNK_SIZE {
432 for y in 0..CHUNK_SIZE {
433 for z in 0..CHUNK_SIZE {
434 chunk.set(x, y, z, DefaultVoxel::Rock);
435 }
436 }
437 }
438 assert!(chunk.is_fully_solid());
439 assert!(!chunk.is_empty());
440 }
441
442 #[test]
443 fn is_empty_on_new_chunk() {
444 let chunk = Chunk::<DefaultVoxel>::new();
445 assert!(chunk.is_empty());
446 assert!(!chunk.is_fully_solid());
447 }
448
449 #[test]
450 fn border_slice_plus_y() {
451 let mut chunk = Chunk::<DefaultVoxel>::new();
452 // Fill the top face (y=15) with Rock
453 for x in 0..CHUNK_SIZE {
454 for z in 0..CHUNK_SIZE {
455 chunk.set(x, 15, z, DefaultVoxel::Rock);
456 }
457 }
458 let slice = chunk.border_slice(0); // +Y face
459 for v in &slice {
460 assert_eq!(*v, DefaultVoxel::Rock);
461 }
462 // -Y face should still be air
463 let bottom = chunk.border_slice(1);
464 for v in &bottom {
465 assert_eq!(*v, DefaultVoxel::Air);
466 }
467 }
468
469 #[test]
470 fn border_slice_specific_voxel() {
471 let mut chunk = Chunk::<DefaultVoxel>::new();
472 // Place a single voxel on the +X face at (15, 3, 7)
473 chunk.set(15, 3, 7, DefaultVoxel::IronOre);
474 let slice = chunk.border_slice(2); // +X face: iterate y, z
475 assert_eq!(slice[3 * CHUNK_SIZE + 7], DefaultVoxel::IronOre);
476 // All other entries on this face should be air
477 for y in 0..CHUNK_SIZE {
478 for z in 0..CHUNK_SIZE {
479 if y == 3 && z == 7 {
480 continue;
481 }
482 assert_eq!(slice[y * CHUNK_SIZE + z], DefaultVoxel::Air);
483 }
484 }
485 }
486}