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/// The array is wrapped in a `Box` to keep the struct's stack size to a single
27/// pointer (`8 bytes`) 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/// ## Coordinate bounds
46///
47/// Every method that takes `(x, y, z)` expects each coordinate in
48/// `[0, CHUNK_SIZE)` (i.e. `0..16`). Out-of-bounds access panics in debug
49/// builds via [`debug_assert`] inside [`Chunk::get_index`]. In release builds,
50/// out-of-bounds indices silently alias other voxels — callers must ensure
51/// correct inputs.
52///
53/// Use [`crate::chunk::world_to_local_coord`] to convert a world-space
54/// position to a valid `(x, y, z)` triple before calling `get` or `set`.
55///
56/// # See also
57///
58/// - [`crate::chunk`] — coordinate systems and conversion helpers.
59/// - [`crate::voxel::VoxelType`] — the trait `V` must implement.
60#[derive(Component, Clone, Debug)]
61pub struct Chunk<V: VoxelType> {
62 voxels: Box<[V; CHUNK_VOLUME]>,
63 /// Per-voxel state bytes — parallel array to `voxels`.
64 ///
65 /// Bits 0–2 encode the placement face; bits 3–7 are reserved for games.
66 /// All states are initialised to `0` (face = +X, conventional default).
67 pub states: Box<[u8; CHUNK_VOLUME]>,
68}
69
70/// Converts a world-space face normal to a placement-face state byte (bits 0–2).
71///
72/// | Normal | State |
73/// |--------|-------|
74/// | +X | 0 |
75/// | −X | 1 |
76/// | +Y | 2 |
77/// | −Y | 3 |
78/// | +Z | 4 |
79/// | −Z | 5 |
80/// | other | 6 |
81///
82/// The returned value is in `[0, 6]` and occupies only bits 0–2 so it can be
83/// OR-ed with the upper bits of an existing state byte without clobbering them.
84pub fn face_to_state(normal: bevy::math::IVec3) -> u8 {
85 match (normal.x, normal.y, normal.z) {
86 (1, 0, 0) => 0,
87 (-1, 0, 0) => 1,
88 (0, 1, 0) => 2,
89 (0, -1, 0) => 3,
90 (0, 0, 1) => 4,
91 (0, 0, -1) => 5,
92 _ => 6,
93 }
94}
95
96impl<V: VoxelType> Chunk<V> {
97 /// Creates a new chunk with every voxel initialized to [`VoxelType::air`]
98 /// and every state byte set to `0`.
99 ///
100 /// Allocates two [`CHUNK_VOLUME`]-element arrays on the heap.
101 pub fn new() -> Self {
102 Self {
103 voxels: Box::new([V::air(); CHUNK_VOLUME]),
104 states: Box::new([0u8; CHUNK_VOLUME]),
105 }
106 }
107
108 /// Computes the flat array index for the voxel at local coordinate `(x, y, z)`.
109 ///
110 /// The formula is `x * CHUNK_SIZE² + y * CHUNK_SIZE + z`, giving X-major
111 /// (row-major with X as the outermost dimension) storage order.
112 ///
113 /// Prefer calling [`Chunk::get`] or [`Chunk::set`] directly; this method is
114 /// public for use by the meshing and persistence systems that need to
115 /// iterate the flat array efficiently.
116 ///
117 /// # Panics
118 ///
119 /// Panics in **debug builds** if any coordinate is `>= CHUNK_SIZE`. In
120 /// release builds, the assertion is omitted for performance.
121 #[inline]
122 pub fn get_index(x: usize, y: usize, z: usize) -> usize {
123 debug_assert!(x < CHUNK_SIZE, "x={x} out of range");
124 debug_assert!(y < CHUNK_SIZE, "y={y} out of range");
125 debug_assert!(z < CHUNK_SIZE, "z={z} out of range");
126 x * CHUNK_SIZE * CHUNK_SIZE + y * CHUNK_SIZE + z
127 }
128
129 /// Returns a copy of the voxel at local coordinate `(x, y, z)`.
130 ///
131 /// Each coordinate must be in `[0, CHUNK_SIZE)`. The value is returned by
132 /// copy because [`VoxelType`] requires `Copy`.
133 ///
134 /// # Panics
135 ///
136 /// Panics in debug builds if any coordinate is out of bounds (see
137 /// [`Chunk::get_index`]).
138 #[inline]
139 pub fn get(&self, x: usize, y: usize, z: usize) -> V {
140 self.voxels[Self::get_index(x, y, z)]
141 }
142
143 /// Overwrites the voxel at local coordinate `(x, y, z)` with `voxel`.
144 ///
145 /// Each coordinate must be in `[0, CHUNK_SIZE)`. Use
146 /// [`VoxelType::air`] to clear a voxel back to empty.
147 ///
148 /// After calling this method on an already-spawned chunk entity, emit a
149 /// [`crate::world::ChunkModified`] event so that the mesh system
150 /// regenerates the chunk's geometry.
151 ///
152 /// # Panics
153 ///
154 /// Panics in debug builds if any coordinate is out of bounds (see
155 /// [`Chunk::get_index`]).
156 #[inline]
157 pub fn set(&mut self, x: usize, y: usize, z: usize, voxel: V) {
158 self.voxels[Self::get_index(x, y, z)] = voxel;
159 }
160
161 /// Returns the state byte for the voxel at local coordinate `(x, y, z)`.
162 ///
163 /// Bits 0–2 hold the placement face (see [`face_to_state`]); bits 3–7 are
164 /// available for game-specific use. Returns `0` for voxels that have never
165 /// been explicitly placed (e.g. generator-filled voxels).
166 ///
167 /// # Panics
168 ///
169 /// Panics in debug builds if any coordinate is out of bounds.
170 #[inline]
171 pub fn get_state(&self, x: usize, y: usize, z: usize) -> u8 {
172 self.states[Self::get_index(x, y, z)]
173 }
174
175 /// Overwrites the state byte for the voxel at local coordinate `(x, y, z)`.
176 ///
177 /// Games may set bits 3–7 freely. Bits 0–2 are normally written by the
178 /// placement system via [`face_to_state`].
179 ///
180 /// # Panics
181 ///
182 /// Panics in debug builds if any coordinate is out of bounds.
183 #[inline]
184 pub fn set_state(&mut self, x: usize, y: usize, z: usize, state: u8) {
185 self.states[Self::get_index(x, y, z)] = state;
186 }
187
188 /// Returns `true` if the voxel at local coordinate `(x, y, z)` is solid.
189 ///
190 /// Equivalent to `self.get(x, y, z).is_solid()`. Used by the meshing and
191 /// occlusion systems to test individual voxels without materializing the
192 /// full voxel value.
193 ///
194 /// # Panics
195 ///
196 /// Panics in debug builds if any coordinate is out of bounds.
197 #[inline]
198 pub fn is_solid_at(&self, x: usize, y: usize, z: usize) -> bool {
199 self.get(x, y, z).is_solid()
200 }
201
202 /// Returns `true` if every voxel in the chunk is solid.
203 ///
204 /// A fully solid chunk is opaque from all six faces and requires no
205 /// interior face geometry. The occlusion system uses this to skip mesh
206 /// generation for completely buried chunks.
207 ///
208 /// Runs in O([`CHUNK_VOLUME`]) time by scanning the flat array.
209 pub fn is_fully_solid(&self) -> bool {
210 self.voxels.iter().all(|v| v.is_solid())
211 }
212
213 /// Returns `true` if every voxel in the chunk is air (non-solid).
214 ///
215 /// An empty chunk produces no geometry. The streaming system uses this
216 /// to avoid spawning mesh entities for chunks that contain only air,
217 /// such as the open space above a terrain surface or inside a cave ceiling.
218 ///
219 /// Runs in O([`CHUNK_VOLUME`]) time by scanning the flat array.
220 pub fn is_empty(&self) -> bool {
221 self.voxels.iter().all(|v| !v.is_solid())
222 }
223
224 /// Extracts a 16x16 border slice for one of the six chunk faces.
225 ///
226 /// The returned array contains the voxels on the outermost layer in the
227 /// direction indicated by `face`:
228 ///
229 /// | Face | Direction | Fixed axis value |
230 /// |------|-----------|-----------------|
231 /// | 0 | +Y | y = 15 |
232 /// | 1 | -Y | y = 0 |
233 /// | 2 | +X | x = 15 |
234 /// | 3 | -X | x = 0 |
235 /// | 4 | +Z | z = 15 |
236 /// | 5 | -Z | z = 0 |
237 ///
238 /// The slice is packed in row-major order for the two varying axes.
239 ///
240 /// # Panics
241 ///
242 /// Panics if `face >= 6`.
243 pub fn border_slice(&self, face: usize) -> [V; CHUNK_SIZE * CHUNK_SIZE] {
244 let mut slice = [V::air(); CHUNK_SIZE * CHUNK_SIZE];
245 let last = CHUNK_SIZE - 1;
246
247 match face {
248 // +Y (y = 15): iterate x, z
249 0 => {
250 for x in 0..CHUNK_SIZE {
251 for z in 0..CHUNK_SIZE {
252 slice[x * CHUNK_SIZE + z] = self.get(x, last, z);
253 }
254 }
255 }
256 // -Y (y = 0): iterate x, z
257 1 => {
258 for x in 0..CHUNK_SIZE {
259 for z in 0..CHUNK_SIZE {
260 slice[x * CHUNK_SIZE + z] = self.get(x, 0, z);
261 }
262 }
263 }
264 // +X (x = 15): iterate y, z
265 2 => {
266 for y in 0..CHUNK_SIZE {
267 for z in 0..CHUNK_SIZE {
268 slice[y * CHUNK_SIZE + z] = self.get(last, y, z);
269 }
270 }
271 }
272 // -X (x = 0): iterate y, z
273 3 => {
274 for y in 0..CHUNK_SIZE {
275 for z in 0..CHUNK_SIZE {
276 slice[y * CHUNK_SIZE + z] = self.get(0, y, z);
277 }
278 }
279 }
280 // +Z (z = 15): iterate x, y
281 4 => {
282 for x in 0..CHUNK_SIZE {
283 for y in 0..CHUNK_SIZE {
284 slice[x * CHUNK_SIZE + y] = self.get(x, y, last);
285 }
286 }
287 }
288 // -Z (z = 0): iterate x, y
289 5 => {
290 for x in 0..CHUNK_SIZE {
291 for y in 0..CHUNK_SIZE {
292 slice[x * CHUNK_SIZE + y] = self.get(x, y, 0);
293 }
294 }
295 }
296 _ => panic!("invalid face index: {face} (must be 0..6)"),
297 }
298
299 slice
300 }
301}
302
303impl<V: VoxelType> Default for Chunk<V> {
304 fn default() -> Self {
305 Self::new()
306 }
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312 use crate::voxel::DefaultVoxel;
313
314 #[test]
315 fn new_chunk_is_all_air() {
316 let chunk = Chunk::<DefaultVoxel>::new();
317 for x in 0..CHUNK_SIZE {
318 for y in 0..CHUNK_SIZE {
319 for z in 0..CHUNK_SIZE {
320 assert_eq!(chunk.get(x, y, z), DefaultVoxel::Air);
321 }
322 }
323 }
324 }
325
326 #[test]
327 fn get_set_round_trip() {
328 let mut chunk = Chunk::<DefaultVoxel>::new();
329 chunk.set(3, 7, 11, DefaultVoxel::IronOre);
330 assert_eq!(chunk.get(3, 7, 11), DefaultVoxel::IronOre);
331
332 chunk.set(0, 0, 0, DefaultVoxel::RareMineral);
333 assert_eq!(chunk.get(0, 0, 0), DefaultVoxel::RareMineral);
334
335 chunk.set(15, 15, 15, DefaultVoxel::SiliconCrystal);
336 assert_eq!(chunk.get(15, 15, 15), DefaultVoxel::SiliconCrystal);
337 }
338
339 #[test]
340 fn is_fully_solid_on_filled_chunk() {
341 let mut chunk = Chunk::<DefaultVoxel>::new();
342 for x in 0..CHUNK_SIZE {
343 for y in 0..CHUNK_SIZE {
344 for z in 0..CHUNK_SIZE {
345 chunk.set(x, y, z, DefaultVoxel::Rock);
346 }
347 }
348 }
349 assert!(chunk.is_fully_solid());
350 assert!(!chunk.is_empty());
351 }
352
353 #[test]
354 fn is_empty_on_new_chunk() {
355 let chunk = Chunk::<DefaultVoxel>::new();
356 assert!(chunk.is_empty());
357 assert!(!chunk.is_fully_solid());
358 }
359
360 #[test]
361 fn border_slice_plus_y() {
362 let mut chunk = Chunk::<DefaultVoxel>::new();
363 // Fill the top face (y=15) with Rock
364 for x in 0..CHUNK_SIZE {
365 for z in 0..CHUNK_SIZE {
366 chunk.set(x, 15, z, DefaultVoxel::Rock);
367 }
368 }
369 let slice = chunk.border_slice(0); // +Y face
370 for v in &slice {
371 assert_eq!(*v, DefaultVoxel::Rock);
372 }
373 // -Y face should still be air
374 let bottom = chunk.border_slice(1);
375 for v in &bottom {
376 assert_eq!(*v, DefaultVoxel::Air);
377 }
378 }
379
380 #[test]
381 fn border_slice_specific_voxel() {
382 let mut chunk = Chunk::<DefaultVoxel>::new();
383 // Place a single voxel on the +X face at (15, 3, 7)
384 chunk.set(15, 3, 7, DefaultVoxel::IronOre);
385 let slice = chunk.border_slice(2); // +X face: iterate y, z
386 assert_eq!(slice[3 * CHUNK_SIZE + 7], DefaultVoxel::IronOre);
387 // All other entries on this face should be air
388 for y in 0..CHUNK_SIZE {
389 for z in 0..CHUNK_SIZE {
390 if y == 3 && z == 7 {
391 continue;
392 }
393 assert_eq!(slice[y * CHUNK_SIZE + z], DefaultVoxel::Air);
394 }
395 }
396 }
397}