Skip to main content

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    /// Per-voxel record of faces uncovered by edits, one bit per face.
80    /// Allocated on the first recorded face.
81    exposed: Option<Box<[u8; CHUNK_VOLUME]>>,
82    /// `true` when the data differs from what was generated, loaded or last
83    /// saved.
84    dirty: bool,
85}
86
87/// Converts a world-space face normal to a placement-face state byte (bits 0–2).
88///
89/// | Normal | State |
90/// |--------|-------|
91/// | +X     | 0     |
92/// | −X     | 1     |
93/// | +Y     | 2     |
94/// | −Y     | 3     |
95/// | +Z     | 4     |
96/// | −Z     | 5     |
97/// | other  | 6     |
98///
99/// The returned value is in `[0, 6]` and occupies only bits 0–2 so it can be
100/// OR-ed with the upper bits of an existing state byte without clobbering them.
101pub fn face_to_state(normal: bevy::math::IVec3) -> u8 {
102    match (normal.x, normal.y, normal.z) {
103        (1, 0, 0) => 0,
104        (-1, 0, 0) => 1,
105        (0, 1, 0) => 2,
106        (0, -1, 0) => 3,
107        (0, 0, 1) => 4,
108        (0, 0, -1) => 5,
109        _ => 6,
110    }
111}
112
113impl<V: VoxelType> Chunk<V> {
114    /// Creates a new chunk with every voxel initialized to [`VoxelType::air`]
115    /// and every state byte set to `0`.
116    ///
117    /// Allocates two [`CHUNK_VOLUME`]-element arrays on the heap.
118    pub fn new() -> Self {
119        Self {
120            voxels: Box::new([V::air(); CHUNK_VOLUME]),
121            states: Box::new([0u8; CHUNK_VOLUME]),
122            exposed: None,
123            dirty: false,
124        }
125    }
126
127    /// Returns `true` if the chunk has changes that were not saved.
128    ///
129    /// A chunk from [`Chunk::new`] is clean. [`Chunk::set`] and
130    /// [`Chunk::set_state`] mark it dirty when they change a value. The
131    /// generator pipeline hands out clean chunks, so freshly generated or
132    /// restored terrain is never written to disk until something edits it.
133    #[inline]
134    pub fn is_dirty(&self) -> bool {
135        self.dirty
136    }
137
138    /// Marks the chunk as matching its saved (or regenerable) form.
139    ///
140    /// Call this after saving a chunk yourself, or after filling a chunk whose
141    /// contents can be reproduced and therefore need not be saved.
142    #[inline]
143    pub fn mark_clean(&mut self) {
144        self.dirty = false;
145    }
146
147    /// Marks the chunk as having unsaved changes.
148    ///
149    /// Needed only after writing the public `states` array directly, which the
150    /// chunk cannot observe.
151    #[inline]
152    pub fn mark_dirty(&mut self) {
153        self.dirty = true;
154    }
155
156    /// Computes the flat array index for the voxel at local coordinate `(x, y, z)`.
157    ///
158    /// The formula is `x * CHUNK_SIZE² + y * CHUNK_SIZE + z`, giving X-major
159    /// (row-major with X as the outermost dimension) storage order.
160    ///
161    /// Prefer calling [`Chunk::get`] or [`Chunk::set`] directly; this method is
162    /// public for use by the meshing and persistence systems that need to
163    /// iterate the flat array efficiently.
164    ///
165    /// # Panics
166    ///
167    /// Panics in **debug builds** if any coordinate is `>= CHUNK_SIZE`. In
168    /// release builds, the assertion is omitted for performance.
169    #[inline]
170    pub fn get_index(x: usize, y: usize, z: usize) -> usize {
171        debug_assert!(x < CHUNK_SIZE, "x={x} out of range");
172        debug_assert!(y < CHUNK_SIZE, "y={y} out of range");
173        debug_assert!(z < CHUNK_SIZE, "z={z} out of range");
174        x * CHUNK_SIZE * CHUNK_SIZE + y * CHUNK_SIZE + z
175    }
176
177    /// Returns a copy of the voxel at local coordinate `(x, y, z)`.
178    ///
179    /// Each coordinate must be in `[0, CHUNK_SIZE)`. The value is returned by
180    /// copy because [`VoxelType`] requires `Copy`.
181    ///
182    /// # Panics
183    ///
184    /// Panics in debug builds if any coordinate is out of bounds (see
185    /// [`Chunk::get_index`]).
186    #[inline]
187    pub fn get(&self, x: usize, y: usize, z: usize) -> V {
188        self.voxels[Self::get_index(x, y, z)]
189    }
190
191    /// Overwrites the voxel at local coordinate `(x, y, z)` with `voxel`.
192    ///
193    /// Each coordinate must be in `[0, CHUNK_SIZE)`. Use
194    /// [`VoxelType::air`] to clear a voxel back to empty.
195    ///
196    /// After calling this method on an already-spawned chunk entity, emit a
197    /// [`crate::world::ChunkModified`] event so that the mesh system
198    /// regenerates the chunk's geometry.
199    ///
200    /// # Panics
201    ///
202    /// Panics in debug builds if any coordinate is out of bounds (see
203    /// [`Chunk::get_index`]).
204    #[inline]
205    pub fn set(&mut self, x: usize, y: usize, z: usize, voxel: V) {
206        let slot = &mut self.voxels[Self::get_index(x, y, z)];
207        if *slot != voxel {
208            *slot = voxel;
209            self.dirty = true;
210        }
211    }
212
213    /// Returns the state byte for the voxel at local coordinate `(x, y, z)`.
214    ///
215    /// Bits 0–2 hold the placement face (see [`face_to_state`]); bits 3–7 are
216    /// available for game-specific use.  Returns `0` for voxels that have never
217    /// been explicitly placed (e.g. generator-filled voxels).
218    ///
219    /// # Panics
220    ///
221    /// Panics in debug builds if any coordinate is out of bounds.
222    #[inline]
223    pub fn get_state(&self, x: usize, y: usize, z: usize) -> u8 {
224        self.states[Self::get_index(x, y, z)]
225    }
226
227    /// Overwrites the state byte for the voxel at local coordinate `(x, y, z)`.
228    ///
229    /// Games may set bits 3–7 freely. Bits 0–2 are normally written by the
230    /// placement system via [`face_to_state`].
231    ///
232    /// # Panics
233    ///
234    /// Panics in debug builds if any coordinate is out of bounds.
235    #[inline]
236    pub fn set_state(&mut self, x: usize, y: usize, z: usize, state: u8) {
237        let slot = &mut self.states[Self::get_index(x, y, z)];
238        if *slot != state {
239            *slot = state;
240            self.dirty = true;
241        }
242    }
243
244    /// The faces of the voxel at `(x, y, z)` that were uncovered by an edit
245    /// since the chunk was generated: one bit per face, bit `i` for face
246    /// index `i` (`0` = +Y, `1` = -Y, `2` = +X, `3` = -X, `4` = +Z, `5` = -Z,
247    /// as in [`VoxelType::texture_layer`]).
248    ///
249    /// A generated chunk has no exposed faces. The record is filled by the
250    /// edit functions of [`crate::world`] (mining, placement, `set_voxel_at`)
251    /// through [`crate::world::record_voxel_edit`]; [`Chunk::set`] alone does
252    /// not touch it, which is what keeps generation out of the record. The
253    /// mesher reports it per face in
254    /// [`ATTRIBUTE_FACE_EXPOSED`](crate::mesh::ATTRIBUTE_FACE_EXPOSED), and it
255    /// is saved with the chunk.
256    #[inline]
257    pub fn exposed_faces(&self, x: usize, y: usize, z: usize) -> u8 {
258        match &self.exposed {
259            Some(exposed) => exposed[Self::get_index(x, y, z)],
260            None => 0,
261        }
262    }
263
264    /// Overwrites the exposed-face bits of the voxel at `(x, y, z)`. Bits
265    /// above the six faces are ignored. Marks the chunk dirty when the value
266    /// changes.
267    pub fn set_exposed_faces(&mut self, x: usize, y: usize, z: usize, faces: u8) {
268        let faces = faces & 0b11_1111;
269        if self.exposed_faces(x, y, z) == faces {
270            return;
271        }
272        let exposed = self
273            .exposed
274            .get_or_insert_with(|| Box::new([0; CHUNK_VOLUME]));
275        exposed[Self::get_index(x, y, z)] = faces;
276        self.dirty = true;
277    }
278
279    /// Whether any face of the chunk is recorded as uncovered by an edit.
280    pub fn has_exposed_faces(&self) -> bool {
281        self.exposed
282            .as_ref()
283            .is_some_and(|exposed| exposed.iter().any(|faces| *faces != 0))
284    }
285
286    /// Forgets every exposed face. Marks the chunk dirty when there was one.
287    pub fn clear_exposed_faces(&mut self) {
288        if self.has_exposed_faces() {
289            self.dirty = true;
290        }
291        self.exposed = None;
292    }
293
294    /// Returns `true` if the voxel at local coordinate `(x, y, z)` is solid.
295    ///
296    /// Equivalent to `self.get(x, y, z).is_solid()`. Used by the meshing and
297    /// occlusion systems to test individual voxels without materializing the
298    /// full voxel value.
299    ///
300    /// # Panics
301    ///
302    /// Panics in debug builds if any coordinate is out of bounds.
303    #[inline]
304    pub fn is_solid_at(&self, x: usize, y: usize, z: usize) -> bool {
305        self.get(x, y, z).is_solid()
306    }
307
308    /// Returns `true` if every voxel in the chunk is solid.
309    ///
310    /// A fully solid chunk is opaque from all six faces and requires no
311    /// interior face geometry. The occlusion system uses this to skip mesh
312    /// generation for completely buried chunks.
313    ///
314    /// Runs in O([`CHUNK_VOLUME`]) time by scanning the flat array.
315    pub fn is_fully_solid(&self) -> bool {
316        self.voxels.iter().all(|v| v.is_solid())
317    }
318
319    /// Returns `true` if every voxel in the chunk is air (non-solid).
320    ///
321    /// An empty chunk produces no geometry. The streaming system uses this
322    /// to avoid spawning mesh entities for chunks that contain only air,
323    /// such as the open space above a terrain surface or inside a cave ceiling.
324    ///
325    /// Runs in O([`CHUNK_VOLUME`]) time by scanning the flat array.
326    pub fn is_empty(&self) -> bool {
327        self.voxels.iter().all(|v| !v.is_solid())
328    }
329
330    /// Extracts a 16x16 border slice for one of the six chunk faces.
331    ///
332    /// The returned array contains the voxels on the outermost layer in the
333    /// direction indicated by `face`:
334    ///
335    /// | Face | Direction | Fixed axis value |
336    /// |------|-----------|-----------------|
337    /// | 0    | +Y        | y = 15          |
338    /// | 1    | -Y        | y = 0           |
339    /// | 2    | +X        | x = 15          |
340    /// | 3    | -X        | x = 0           |
341    /// | 4    | +Z        | z = 15          |
342    /// | 5    | -Z        | z = 0           |
343    ///
344    /// The slice is packed in row-major order for the two varying axes.
345    ///
346    /// # Panics
347    ///
348    /// Panics if `face >= 6`.
349    pub fn border_slice(&self, face: usize) -> [V; CHUNK_SIZE * CHUNK_SIZE] {
350        let mut slice = [V::air(); CHUNK_SIZE * CHUNK_SIZE];
351        let last = CHUNK_SIZE - 1;
352
353        match face {
354            // +Y (y = 15): iterate x, z
355            0 => {
356                for x in 0..CHUNK_SIZE {
357                    for z in 0..CHUNK_SIZE {
358                        slice[x * CHUNK_SIZE + z] = self.get(x, last, z);
359                    }
360                }
361            }
362            // -Y (y = 0): iterate x, z
363            1 => {
364                for x in 0..CHUNK_SIZE {
365                    for z in 0..CHUNK_SIZE {
366                        slice[x * CHUNK_SIZE + z] = self.get(x, 0, z);
367                    }
368                }
369            }
370            // +X (x = 15): iterate y, z
371            2 => {
372                for y in 0..CHUNK_SIZE {
373                    for z in 0..CHUNK_SIZE {
374                        slice[y * CHUNK_SIZE + z] = self.get(last, y, z);
375                    }
376                }
377            }
378            // -X (x = 0): iterate y, z
379            3 => {
380                for y in 0..CHUNK_SIZE {
381                    for z in 0..CHUNK_SIZE {
382                        slice[y * CHUNK_SIZE + z] = self.get(0, y, z);
383                    }
384                }
385            }
386            // +Z (z = 15): iterate x, y
387            4 => {
388                for x in 0..CHUNK_SIZE {
389                    for y in 0..CHUNK_SIZE {
390                        slice[x * CHUNK_SIZE + y] = self.get(x, y, last);
391                    }
392                }
393            }
394            // -Z (z = 0): iterate x, y
395            5 => {
396                for x in 0..CHUNK_SIZE {
397                    for y in 0..CHUNK_SIZE {
398                        slice[x * CHUNK_SIZE + y] = self.get(x, y, 0);
399                    }
400                }
401            }
402            _ => panic!("invalid face index: {face} (must be 0..6)"),
403        }
404
405        slice
406    }
407}
408
409impl<V: VoxelType> Default for Chunk<V> {
410    fn default() -> Self {
411        Self::new()
412    }
413}
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418    use crate::voxel::DefaultVoxel;
419
420    #[test]
421    fn new_chunk_is_all_air() {
422        let chunk = Chunk::<DefaultVoxel>::new();
423        for x in 0..CHUNK_SIZE {
424            for y in 0..CHUNK_SIZE {
425                for z in 0..CHUNK_SIZE {
426                    assert_eq!(chunk.get(x, y, z), DefaultVoxel::Air);
427                }
428            }
429        }
430    }
431
432    #[test]
433    fn new_chunk_is_clean() {
434        assert!(!Chunk::<DefaultVoxel>::new().is_dirty());
435    }
436
437    #[test]
438    fn changing_a_voxel_or_state_marks_the_chunk_dirty() {
439        let mut chunk = Chunk::<DefaultVoxel>::new();
440        chunk.set(1, 2, 3, DefaultVoxel::Rock);
441        assert!(chunk.is_dirty());
442
443        let mut chunk = Chunk::<DefaultVoxel>::new();
444        chunk.set_state(1, 2, 3, 5);
445        assert!(chunk.is_dirty());
446    }
447
448    #[test]
449    fn writing_the_same_value_keeps_the_chunk_clean() {
450        let mut chunk = Chunk::<DefaultVoxel>::new();
451        chunk.set(1, 2, 3, DefaultVoxel::Air);
452        chunk.set_state(1, 2, 3, 0);
453        assert!(!chunk.is_dirty());
454    }
455
456    #[test]
457    fn mark_clean_and_mark_dirty_override_the_flag() {
458        let mut chunk = Chunk::<DefaultVoxel>::new();
459        chunk.set(0, 0, 0, DefaultVoxel::Rock);
460        chunk.mark_clean();
461        assert!(!chunk.is_dirty());
462        // Still clean when the same value is written again.
463        chunk.set(0, 0, 0, DefaultVoxel::Rock);
464        assert!(!chunk.is_dirty());
465        chunk.mark_dirty();
466        assert!(chunk.is_dirty());
467    }
468
469    #[test]
470    fn get_set_round_trip() {
471        let mut chunk = Chunk::<DefaultVoxel>::new();
472        chunk.set(3, 7, 11, DefaultVoxel::IronOre);
473        assert_eq!(chunk.get(3, 7, 11), DefaultVoxel::IronOre);
474
475        chunk.set(0, 0, 0, DefaultVoxel::RareMineral);
476        assert_eq!(chunk.get(0, 0, 0), DefaultVoxel::RareMineral);
477
478        chunk.set(15, 15, 15, DefaultVoxel::SiliconCrystal);
479        assert_eq!(chunk.get(15, 15, 15), DefaultVoxel::SiliconCrystal);
480    }
481
482    #[test]
483    fn is_fully_solid_on_filled_chunk() {
484        let mut chunk = Chunk::<DefaultVoxel>::new();
485        for x in 0..CHUNK_SIZE {
486            for y in 0..CHUNK_SIZE {
487                for z in 0..CHUNK_SIZE {
488                    chunk.set(x, y, z, DefaultVoxel::Rock);
489                }
490            }
491        }
492        assert!(chunk.is_fully_solid());
493        assert!(!chunk.is_empty());
494    }
495
496    #[test]
497    fn is_empty_on_new_chunk() {
498        let chunk = Chunk::<DefaultVoxel>::new();
499        assert!(chunk.is_empty());
500        assert!(!chunk.is_fully_solid());
501    }
502
503    #[test]
504    fn border_slice_plus_y() {
505        let mut chunk = Chunk::<DefaultVoxel>::new();
506        // Fill the top face (y=15) with Rock
507        for x in 0..CHUNK_SIZE {
508            for z in 0..CHUNK_SIZE {
509                chunk.set(x, 15, z, DefaultVoxel::Rock);
510            }
511        }
512        let slice = chunk.border_slice(0); // +Y face
513        for v in &slice {
514            assert_eq!(*v, DefaultVoxel::Rock);
515        }
516        // -Y face should still be air
517        let bottom = chunk.border_slice(1);
518        for v in &bottom {
519            assert_eq!(*v, DefaultVoxel::Air);
520        }
521    }
522
523    #[test]
524    fn border_slice_specific_voxel() {
525        let mut chunk = Chunk::<DefaultVoxel>::new();
526        // Place a single voxel on the +X face at (15, 3, 7)
527        chunk.set(15, 3, 7, DefaultVoxel::IronOre);
528        let slice = chunk.border_slice(2); // +X face: iterate y, z
529        assert_eq!(slice[3 * CHUNK_SIZE + 7], DefaultVoxel::IronOre);
530        // All other entries on this face should be air
531        for y in 0..CHUNK_SIZE {
532            for z in 0..CHUNK_SIZE {
533                if y == 3 && z == 7 {
534                    continue;
535                }
536                assert_eq!(slice[y * CHUNK_SIZE + z], DefaultVoxel::Air);
537            }
538        }
539    }
540}