Skip to main content

voxel_framework/
lib.rs

1//! # voxel-framework
2//!
3//! A reusable voxel engine library built on [Bevy](https://bevyengine.org/),
4//! providing all the infrastructure needed to build voxel-based games and
5//! simulations: chunk storage, procedural generation, greedy meshing, world
6//! streaming, PBR rendering, and player interaction.
7//!
8//! ## Overview
9//!
10//! The framework is built around three core abstractions:
11//!
12//! - **[`voxel::VoxelType`]** — a trait that every voxel palette must implement.
13//!   It describes whether a voxel is solid, what color it renders as, and how
14//!   it serializes to and from a single byte for persistence. The built-in
15//!   [`voxel::DefaultVoxel`] palette covers five material types (Air, Rock,
16//!   IronOre, SiliconCrystal, RareMineral) and is ready to use out of the box.
17//!
18//! - **[`chunk::Chunk<V>`]** — the fundamental storage unit. A 16×16×16 flat
19//!   array of voxels stored on the heap. All generation, meshing, and I/O
20//!   operate on chunks identified by a [`chunk::ChunkCoord`] (an `IVec3`
21//!   where one unit equals `CHUNK_SIZE` world-space units).
22//!
23//! - **[`generator::ChunkGenerator`]** — an async-safe trait implemented by
24//!   procedural generators. Generators run on a Bevy `AsyncComputeTaskPool`
25//!   thread and produce fully populated [`chunk::Chunk<V>`] values, which are
26//!   then handed back to the main world for meshing and insertion.
27//!
28//! ## Plugin Catalog Architecture
29//!
30//! `voxel-framework` exposes a flat catalog of Bevy plugins grouped by
31//! responsibility. Game crates compose the plugins they need instead of
32//! depending on a hidden monolithic game plugin:
33//!
34//! | Category | Purpose | Examples |
35//! |----------|---------|----------|
36//! | Engine | Foundation for streamable/renderable voxel worlds | [`world::WorldPlugin`], [`mesh::MeshPlugin`], [`render::RenderPlugin`] |
37//! | World Data | Chunk sources, generation, persistence, lifecycle data | [`generator::GeneratorPlugin`], [`world::PersistencePlugin`] |
38//! | Gameplay | Reusable rules and interactions | [`content::VoxelContentPlugin`], [`stats::VoxelStatsPlugin`], [`world::mining::MiningPlugin`], [`world::placement::PlacementPlugin`], [`player::PlayerPlugin`] |
39//! | Default Implementation | Replaceable UI/audio/visual defaults | [`ui::UiPlugin`], [`skybox::SkyboxPlugin`], [`audio::DefaultAudioPlugin`] |
40//! | Convenience | Compatibility bundles, input adapters, recipes, prototyping helpers | [`VoxelCorePlugin`], [`VoxelPlugin`] |
41//!
42//! These categories are also represented by marker traits in
43//! [`plugin_category`]. They are documentation and API classification tools;
44//! Bevy composition still uses the normal [`Plugin`] trait.
45//!
46//! [`VoxelCorePlugin`] and [`VoxelPlugin`] remain available as convenience
47//! bundles for compatibility and quick starts, but they are not the primary
48//! architecture. New domain behavior should normally be modeled as an explicit
49//! Engine, World Data, Gameplay, or Default Implementation plugin.
50//!
51//! [`generator::GeneratorPlugin`] is always **opt-in** because it is generic
52//! over `V: VoxelType` and requires the caller to supply a
53//! [`generator::GeneratorResource`] holding a concrete generator. Add it
54//! separately after either a bundle or explicit engine plugins.
55//!
56//! ## The Chunk Pipeline
57//!
58//! The full data flow from viewer movement to rendered geometry:
59//!
60//! ```text
61//! ViewerPosition update
62//!        │
63//!        ▼
64//! WorldPlugin — streaming system
65//!   Computes which chunks are within the configured render distance.
66//!   Emits ChunkRequested events for chunks not yet loaded.
67//!        │
68//!        ▼
69//! GeneratorPlugin — async generation (AsyncComputeTaskPool)
70//!   Spawns a task per requested chunk. Each task calls
71//!   ChunkGenerator::generate(coord) → Chunk<V>.
72//!   When the task completes, inserts the Chunk<V> component and emits
73//!   ChunkModified so downstream systems are notified.
74//!        │
75//!        ▼
76//! MeshPlugin — greedy mesh generation
77//!   Reacts to ChunkModified. Iterates the chunk with a configurable LOD
78//!   step, runs the greedy meshing algorithm, and uploads a Bevy Mesh asset.
79//!        │
80//!        ▼
81//! RenderPlugin — PBR material + entity spawn
82//!   Attaches a shared chunk PBR material and a MeshBundle to the chunk
83//!   entity so Bevy's renderer picks it up on the next frame.
84//!        │
85//!        ▼
86//! OcclusionPlugin — neighbor-solid occlusion
87//!   Reacts to ChunkModified and hides chunks whose six face-adjacent
88//!   neighbours are all loaded and fully solid.
89//! ```
90//!
91//! ## Quick Start
92//!
93//! A minimal working world using the built-in asteroid generator:
94//!
95//! ```rust,no_run
96//! use bevy::prelude::*;
97//! use voxel_framework::{
98//!     VoxelPlugin,
99//!     generator::{GeneratorPlugin, GeneratorResource},
100//!     generator::asteroid::{AsteroidConfig, AsteroidGenerator},
101//!     voxel::DefaultVoxel,
102//! };
103//! use std::sync::Arc;
104//!
105//! App::new()
106//!     .add_plugins(DefaultPlugins)
107//!     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
108//!     .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
109//!     .insert_resource(GeneratorResource::<DefaultVoxel> {
110//!         generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
111//!     })
112//!     .run();
113//! ```
114//!
115//! Use explicit catalog plugins instead of [`VoxelPlugin`] when you want full
116//! control over engine, world data, gameplay, and presentation defaults.
117//!
118//! ## Extending the Framework
119//!
120//! To use a custom voxel palette, implement [`voxel::VoxelType`] on your own type and
121//! substitute it wherever the framework is generic over `V: VoxelType`:
122//!
123//! - [`generator::GeneratorPlugin::<YourVoxel>::new()`][`generator::GeneratorPlugin`]
124//! - [`mesh::MeshPlugin::<YourVoxel>::new()`][`mesh::MeshPlugin`]
125//! - [`render::RenderPlugin::<YourVoxel>::new()`][`render::RenderPlugin`]
126//!
127//! To drive generation, implement [`generator::ChunkGenerator`] and wrap it in
128//! a [`generator::GeneratorResource`].
129//!
130//! See [`prelude`] for the most commonly used re-exports.
131
132#![deny(rustdoc::broken_intra_doc_links)]
133
134pub mod audio;
135pub mod chunk;
136pub mod content;
137#[cfg(feature = "crafting")]
138pub mod crafting;
139pub mod fragments;
140pub mod generator;
141#[cfg(feature = "items")]
142pub mod items;
143pub mod mesh;
144#[cfg(feature = "mobs")]
145pub mod mobs;
146pub mod noise;
147pub mod player;
148pub mod plugin_category;
149pub mod prelude;
150pub mod profile;
151pub mod render;
152pub mod settings;
153pub mod skybox;
154pub mod stats;
155pub mod ui;
156pub mod voxel;
157pub mod world;
158
159use bevy::prelude::*;
160
161use audio::SfxPlugin;
162use fragments::FragmentPlugin;
163#[cfg(feature = "items")]
164use items::hotbar::HotbarPlugin;
165use mesh::MeshPlugin;
166use render::RenderPlugin;
167use skybox::SkyboxPlugin;
168use ui::UiPlugin;
169use voxel::DefaultVoxel;
170use voxel::VoxelType;
171use world::loading::LoadingPlugin;
172use world::mining::MiningPlugin;
173use world::occlusion::OcclusionPlugin;
174use world::placement::PlacementPlugin;
175use world::{WorldConfigPlugin, WorldPlugin};
176
177/// Convenience bundle for the historical core voxel runtime.
178///
179/// `VoxelCorePlugin<V>` wires up the legacy core bundle — world streaming,
180/// chunk lifecycle, meshing, PBR rendering, neighbor-solid occlusion, mining,
181/// placement, and loading state — without the bundled presentation defaults
182/// from [`VoxelPlugin`].
183///
184/// In the plugin catalog taxonomy this type is a [`plugin_category::ConveniencePlugin`]:
185/// it composes stricter Engine and Gameplay plugins for compatibility and quick
186/// starts. New architecture should describe those individual plugins by their
187/// primary categories rather than treating this bundle as the whole model.
188///
189/// The generic parameter `V` selects the voxel type used by the rendering,
190/// meshing, and occlusion systems. Defaults to [`DefaultVoxel`] for backwards
191/// compatibility: `VoxelCorePlugin::default()` and
192/// `VoxelCorePlugin::<DefaultVoxel>::new()` are equivalent.
193///
194/// # Included systems
195///
196/// | Plugin | Responsibility |
197/// |--------|----------------|
198/// | [`WorldPlugin`] | [`world::ChunkManager`], [`world::systems::ViewerPosition`], chunk lifecycle events, and streaming |
199/// | [`WorldConfigPlugin`] | Inserts the [`world::WorldConfig`] resource |
200/// | `RenderPlugin<V>` | Shared chunk PBR material and entity spawn |
201/// | `MeshPlugin<V>` | Greedy mesh generation and chunk despawn |
202/// | `OcclusionPlugin<V>` | Neighbor-solid chunk occlusion |
203/// | [`world::mining::MiningPlugin`] | Gameplay primitive for voxel removal |
204/// | [`world::placement::PlacementPlugin`] | Gameplay primitive for voxel placement |
205/// | [`world::loading::LoadingPlugin`] | World loading state machine |
206///
207/// # Not included (opt-in)
208///
209/// - [`generator::GeneratorPlugin`] — requires the caller to supply a
210///   [`generator::GeneratorResource`].
211/// - [`FragmentPlugin`], [`SkyboxPlugin`], [`SfxPlugin`], [`HotbarPlugin`],
212///   [`UiPlugin`] — presentation/gameplay defaults included by [`VoxelPlugin`].
213///
214/// # Example
215///
216/// ```rust,no_run
217/// use bevy::prelude::*;
218/// use voxel_framework::{VoxelCorePlugin, generator::{GeneratorPlugin, GeneratorResource}};
219/// use voxel_framework::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
220/// use voxel_framework::voxel::DefaultVoxel;
221/// use std::sync::Arc;
222///
223/// App::new()
224///     .add_plugins(DefaultPlugins)
225///     .add_plugins(VoxelCorePlugin::<DefaultVoxel>::new())
226///     .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
227///     .insert_resource(GeneratorResource::<DefaultVoxel> {
228///         generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
229///     })
230///     .run();
231/// ```
232///
233/// # See also
234///
235/// - [`VoxelPlugin`] — broader quick-start convenience bundle.
236pub struct VoxelCorePlugin<V: VoxelType = DefaultVoxel> {
237    _m: std::marker::PhantomData<V>,
238}
239
240impl<V: VoxelType> VoxelCorePlugin<V> {
241    /// Creates a new [`VoxelCorePlugin`] for voxel type `V`.
242    pub fn new() -> Self {
243        Self {
244            _m: std::marker::PhantomData,
245        }
246    }
247}
248
249impl<V: VoxelType> Default for VoxelCorePlugin<V> {
250    fn default() -> Self {
251        Self::new()
252    }
253}
254
255impl<V: VoxelType> Plugin for VoxelCorePlugin<V> {
256    fn build(&self, app: &mut App) {
257        app.add_plugins(WorldPlugin);
258        app.add_plugins(WorldConfigPlugin);
259        app.add_plugins(RenderPlugin::<V>::new());
260        app.add_plugins(MeshPlugin::<V>::new());
261        app.add_plugins(OcclusionPlugin::<V>::new());
262        app.add_plugins(MiningPlugin);
263        app.add_plugins(PlacementPlugin);
264        app.add_plugins(LoadingPlugin);
265    }
266}
267
268/// Quick-start convenience bundle for demos and prototypes.
269///
270/// `VoxelPlugin<V>` composes [`VoxelCorePlugin<V>`] with selected presentation
271/// and gameplay defaults. It is useful for examples, demos, and early
272/// prototyping, but it is not the architectural definition of the full
273/// framework. Production games should treat it as a convenience bundle and
274/// switch to explicit catalog plugins when they need finer control.
275///
276/// The generic parameter `V` selects the voxel type. Defaults to
277/// [`DefaultVoxel`] — `VoxelPlugin::default()` produces an asteroid-palette
278/// world, `VoxelPlugin::<DefaultTerrainVoxel>::new()` produces a terrain world.
279///
280/// # Included beyond [`VoxelCorePlugin`]
281///
282/// | Plugin | Responsibility |
283/// |--------|----------------|
284/// | [`FragmentPlugin`] | Floating voxel debris entities ejected on mining |
285/// | [`SkyboxPlugin`] | Procedural starfield and skybox rendering |
286/// | [`SfxPlugin`] | Positional audio effects for mining and placement |
287/// | [`HotbarPlugin`] | Player hotbar, item switching, and held-item state |
288/// | [`UiPlugin`] | Crosshair, loading screen, and HUD overlays |
289///
290/// # Generator not included
291///
292/// [`generator::GeneratorPlugin`] is intentionally excluded because it requires
293/// the caller to supply a concrete [`generator::GeneratorResource`]. Always add
294/// it separately:
295///
296/// ```rust,no_run
297/// use bevy::prelude::*;
298/// use voxel_framework::{VoxelPlugin, generator::{GeneratorPlugin, GeneratorResource}};
299/// use voxel_framework::generator::terrain::{TerrainConfig, TerrainGenerator};
300/// use voxel_framework::voxel::DefaultTerrainVoxel;
301/// use std::sync::Arc;
302///
303/// App::new()
304///     .add_plugins(DefaultPlugins)
305///     .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
306///     .add_plugins(GeneratorPlugin::<DefaultTerrainVoxel>::new())
307///     .insert_resource(GeneratorResource::<DefaultTerrainVoxel> {
308///         generator: Arc::new(TerrainGenerator::new(TerrainConfig::default())),
309///     })
310///     .run();
311/// ```
312///
313/// # See also
314///
315/// - [`VoxelCorePlugin`] — narrower compatibility/convenience bundle.
316/// - [`prelude`] — commonly used re-exports for convenience imports.
317pub struct VoxelPlugin<V: VoxelType = DefaultVoxel> {
318    _m: std::marker::PhantomData<V>,
319}
320
321impl<V: VoxelType> VoxelPlugin<V> {
322    /// Creates a new [`VoxelPlugin`] for voxel type `V`.
323    pub fn new() -> Self {
324        Self {
325            _m: std::marker::PhantomData,
326        }
327    }
328}
329
330impl<V: VoxelType> Default for VoxelPlugin<V> {
331    fn default() -> Self {
332        Self::new()
333    }
334}
335
336impl<V: VoxelType> Plugin for VoxelPlugin<V> {
337    fn build(&self, app: &mut App) {
338        app.add_plugins(VoxelCorePlugin::<V>::new());
339        app.add_plugins(FragmentPlugin);
340        app.add_plugins(SkyboxPlugin);
341        app.add_plugins(SfxPlugin);
342        #[cfg(feature = "items")]
343        app.add_plugins(HotbarPlugin);
344        app.add_plugins(UiPlugin);
345    }
346}