Skip to main content

voxel_framework/generator/
mod.rs

1//! Procedural chunk generation trait, async pipeline, and Bevy plugin.
2//!
3//! # Architecture
4//!
5//! World generation is split across two systems that run every frame inside
6//! [`GeneratorSystems`]:
7//!
8//! 1. **[`chunk_request_system`]** — receives [`crate::world::ChunkLoadRequest`]
9//!    messages.  It clones the [`Arc`]-wrapped generator and offloads work to
10//!    Bevy's [`bevy::tasks::AsyncComputeTaskPool`], storing the returned
11//!    [`Task`] as a [`ChunkTask<V>`] component on a new entity. The task first
12//!    tries to restore the chunk from disk (when
13//!    [`crate::world::PersistenceConfig`] is present) and generates it
14//!    otherwise.
15//!
16//! 2. **[`chunk_task_poll_system`]** — polls every in-flight [`ChunkTask<V>`]
17//!    with a single non-blocking `poll_once`.  When a task resolves it removes
18//!    the task component, inserts the completed [`crate::chunk::Chunk<V>`], and
19//!    emits [`crate::world::ChunkModified`] so that the mesh system in
20//!    [`crate::mesh`] can build geometry on the same frame.
21//!
22//! # The `ChunkGenerator` contract
23//!
24//! Every implementation of [`ChunkGenerator<V>`] runs on a worker thread from
25//! `AsyncComputeTaskPool`.  It **must not** access the Bevy [`bevy::ecs::world::World`]
26//! or any `Res<T>` — the generator `Arc` is the only shared state it may touch.
27//! The trait bounds `Send + Sync + 'static` enforce this at compile time.
28//!
29//! # Wiring into a Bevy app
30//!
31//! ```rust,no_run
32//! use std::sync::Arc;
33//! use bevy::prelude::*;
34//! use voxel_framework::{
35//!     generator::{GeneratorPlugin, GeneratorResource},
36//!     mesh::MeshPlugin,
37//!     voxel::DefaultVoxel,
38//!     VoxelPlugin,
39//! };
40//! use voxel_framework::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
41//!
42//! App::new()
43//!     .add_plugins(DefaultPlugins)
44//!     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
45//!     .insert_resource(GeneratorResource::<DefaultVoxel> {
46//!         generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
47//!     })
48//!     .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
49//!     .add_plugins(MeshPlugin::<DefaultVoxel>::new())
50//!     .run();
51//! ```
52//!
53//! [`Arc`]: std::sync::Arc
54//! [`Task`]: bevy::tasks::Task
55
56pub mod asteroid;
57pub mod region;
58pub mod systems;
59pub mod terrain;
60
61pub use region::{MultiGenerator, MultiGeneratorPlugin, RegionGenerator};
62pub use systems::{ChunkTask, chunk_request_system, chunk_task_poll_system};
63
64use std::sync::Arc;
65
66use bevy::prelude::*;
67
68use crate::chunk::Chunk;
69use crate::voxel::VoxelType;
70
71/// System set label for the generator pipeline.
72///
73/// `chunk_mesh_system` uses `.after(GeneratorSystems)` to guarantee it reads
74/// `ChunkModified` messages emitted in the same frame by `chunk_task_poll_system`.
75#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
76pub struct GeneratorSystems;
77
78/// Contract for procedural chunk generation strategies.
79///
80/// An implementation receives an empty [`Chunk<V>`] and a chunk-grid coordinate,
81/// and fills the chunk with whatever voxel data the strategy produces.  The
82/// framework stores implementations behind an [`std::sync::Arc`] and calls
83/// [`ChunkGenerator::generate`] on worker threads from Bevy's
84/// [`bevy::tasks::AsyncComputeTaskPool`].
85///
86/// # Thread safety contract
87///
88/// `generate` is called from a **background thread** — never from the Bevy main
89/// thread.  Implementations **must not**:
90///
91/// - access any [`bevy::ecs::world::World`] data (queries, resources, etc.),
92/// - hold non-`Send` types, or
93/// - perform blocking I/O on the calling thread.
94///
95/// The `Send + Sync + 'static` bounds on the trait enforce these constraints at
96/// compile time.  Internal state may be freely read (shared references via
97/// `Arc`), but must not be mutated without interior synchronization.
98///
99/// # Coordinate space
100///
101/// `coord` is in **chunk-grid space**: each axis unit corresponds to
102/// `CHUNK_SIZE` world units.  Convert to world space with
103/// `coord.as_vec3() * CHUNK_SIZE as f32`.
104///
105/// # Examples
106///
107/// ```rust,no_run
108/// use bevy::math::IVec3;
109/// use voxel_framework::{
110///     chunk::Chunk,
111///     generator::ChunkGenerator,
112///     voxel::DefaultVoxel,
113/// };
114///
115/// struct FlatWorldGenerator {
116///     ground_level: i32,
117/// }
118///
119/// impl ChunkGenerator<DefaultVoxel> for FlatWorldGenerator {
120///     fn generate(&self, coord: IVec3, chunk: &mut Chunk<DefaultVoxel>) {
121///         // Fill voxels below ground_level with rock, leave the rest as air.
122///         if coord.y < self.ground_level {
123///             for x in 0..voxel_framework::chunk::CHUNK_SIZE {
124///                 for y in 0..voxel_framework::chunk::CHUNK_SIZE {
125///                     for z in 0..voxel_framework::chunk::CHUNK_SIZE {
126///                         chunk.set(x, y, z, DefaultVoxel::Rock);
127///                     }
128///                 }
129///             }
130///         }
131///     }
132/// }
133/// ```
134pub trait ChunkGenerator<V: VoxelType>: Send + Sync + 'static {
135    /// Fills `chunk` with voxel data for the chunk at `coord`.
136    ///
137    /// `coord` is in chunk-grid space; each unit equals `CHUNK_SIZE` world units.
138    ///
139    /// **Called on a background thread. Must not access the Bevy `World`.**
140    fn generate(&self, coord: IVec3, chunk: &mut Chunk<V>);
141}
142
143/// Bevy [`Resource`] that holds the active [`ChunkGenerator<V>`].
144///
145/// Insert this resource before adding [`GeneratorPlugin<V>`] to provide the
146/// generation strategy.  The inner [`std::sync::Arc`] is cloned cheaply into
147/// each async task so that the generator is shared without blocking or copying.
148///
149/// ```rust,no_run
150/// use std::sync::Arc;
151/// use bevy::prelude::*;
152/// use voxel_framework::{
153///     generator::GeneratorResource,
154///     voxel::DefaultVoxel,
155/// };
156/// use voxel_framework::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
157///
158/// fn main() {
159///     App::new()
160///         .insert_resource(GeneratorResource::<DefaultVoxel> {
161///             generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
162///         })
163///         // ... add other plugins ...
164///         .run();
165/// }
166/// ```
167#[derive(Resource)]
168pub struct GeneratorResource<V: VoxelType> {
169    /// The active chunk generator, shared across worker threads via [`std::sync::Arc`].
170    pub generator: Arc<dyn ChunkGenerator<V>>,
171}
172
173/// Bevy [`Plugin`] that registers the async chunk generation pipeline for
174/// voxel type `V`.
175///
176/// Adds two systems to the [`Update`] schedule inside [`GeneratorSystems`],
177/// chained so that poll results are available to downstream systems in the same
178/// frame:
179///
180/// 1. [`chunk_request_system`] — converts [`crate::world::ChunkLoadRequest`]
181///    messages into async tasks that restore from disk or generate.
182/// 2. [`chunk_task_poll_system`] — harvests completed tasks and attaches
183///    [`crate::chunk::Chunk<V>`] components.
184///
185/// [`GeneratorResource<V>`] must be inserted separately; the plugin does not
186/// require it at registration time (the system accepts it as `Option<Res<_>>`).
187pub struct GeneratorPlugin<V: VoxelType> {
188    _marker: std::marker::PhantomData<V>,
189}
190
191impl<V: VoxelType> GeneratorPlugin<V> {
192    /// Creates a new [`GeneratorPlugin`] for voxel type `V`.
193    pub fn new() -> Self {
194        Self {
195            _marker: std::marker::PhantomData,
196        }
197    }
198}
199
200impl<V: VoxelType> Default for GeneratorPlugin<V> {
201    fn default() -> Self {
202        Self::new()
203    }
204}
205
206impl<V: VoxelType> Plugin for GeneratorPlugin<V> {
207    fn build(&self, app: &mut App) {
208        app.add_systems(
209            Update,
210            (
211                systems::chunk_request_system::<V>,
212                systems::chunk_task_poll_system::<V>,
213            )
214                .chain()
215                .in_set(GeneratorSystems),
216        );
217    }
218}