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`], [`effects::VoxelEffectsPlugin`], [`world::mining::MiningPlugin`], [`world::placement::PlacementPlugin`], [`player::PlayerPlugin`] |
39//! | Default Implementation | Replaceable UI/audio/visual defaults | [`ui::UiPlugin`], [`ui::VoxelHudPlugin`], [`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//! [`ui::VoxelHudPlugin`] is also explicit and remains outside [`ui::UiPlugin`]
57//! and the convenience bundles. Authors register domain-neutral presentation
58//! definitions, publish screen-ready values, and may schedule same-frame
59//! publishers in [`ui::HudSystemSet::Publish`]. The retained renderer preserves
60//! element identity and safely hides unresolved or unavailable asset inputs.
61//!
62//! ## The Chunk Pipeline
63//!
64//! The full data flow from viewer movement to rendered geometry:
65//!
66//! ```text
67//! ViewerPosition update
68//!        │
69//!        ▼
70//! WorldPlugin — streaming system
71//!   Computes which chunks are within the configured render distance.
72//!   Emits ChunkRequested events for chunks not yet loaded.
73//!        │
74//!        ▼
75//! GeneratorPlugin — async generation (AsyncComputeTaskPool)
76//!   Spawns a task per requested chunk. Each task calls
77//!   ChunkGenerator::generate(coord) → Chunk<V>.
78//!   When the task completes, inserts the Chunk<V> component and emits
79//!   ChunkModified so downstream systems are notified.
80//!        │
81//!        ▼
82//! MeshPlugin — greedy mesh generation
83//!   Reacts to ChunkModified. Iterates the chunk with a configurable LOD
84//!   step, runs the greedy meshing algorithm, and uploads a Bevy Mesh asset.
85//!        │
86//!        ▼
87//! RenderPlugin — PBR material + entity spawn
88//!   Attaches a shared chunk PBR material and a MeshBundle to the chunk
89//!   entity so Bevy's renderer picks it up on the next frame.
90//!        │
91//!        ▼
92//! OcclusionPlugin — neighbor-solid occlusion
93//!   Reacts to ChunkModified and hides chunks whose six face-adjacent
94//!   neighbours are all loaded and fully solid.
95//! ```
96//!
97//! ## Quick Start
98//!
99//! A minimal working world using the built-in asteroid generator:
100//!
101//! ```rust,no_run
102//! use bevy::prelude::*;
103//! use voxel_framework::{
104//!     VoxelPlugin,
105//!     generator::{GeneratorPlugin, GeneratorResource},
106//!     generator::asteroid::{AsteroidConfig, AsteroidGenerator},
107//!     voxel::DefaultVoxel,
108//! };
109//! use std::sync::Arc;
110//!
111//! App::new()
112//!     .add_plugins(DefaultPlugins)
113//!     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
114//!     .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
115//!     .insert_resource(GeneratorResource::<DefaultVoxel> {
116//!         generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
117//!     })
118//!     .run();
119//! ```
120//!
121//! Use explicit catalog plugins instead of [`VoxelPlugin`] when you want full
122//! control over engine, world data, gameplay, and presentation defaults.
123//!
124//! ## Extending the Framework
125//!
126//! To use a custom voxel palette, implement [`voxel::VoxelType`] on your own type and
127//! substitute it wherever the framework is generic over `V: VoxelType`:
128//!
129//! - [`generator::GeneratorPlugin::<YourVoxel>::new()`][`generator::GeneratorPlugin`]
130//! - [`mesh::MeshPlugin::<YourVoxel>::new()`][`mesh::MeshPlugin`]
131//! - [`render::RenderPlugin::<YourVoxel>::new()`][`render::RenderPlugin`]
132//!
133//! To drive generation, implement [`generator::ChunkGenerator`] and wrap it in
134//! a [`generator::GeneratorResource`].
135//!
136//! See [`prelude`] for the most commonly used re-exports.
137
138#![deny(rustdoc::broken_intra_doc_links)]
139
140pub mod audio;
141pub mod chunk;
142pub mod content;
143#[cfg(feature = "crafting")]
144pub mod crafting;
145pub mod effects;
146pub mod fragments;
147pub mod generator;
148#[cfg(feature = "items")]
149pub mod items;
150pub mod mesh;
151#[cfg(feature = "mobs")]
152pub mod mobs;
153pub mod noise;
154pub mod player;
155pub mod plugin_category;
156pub mod prelude;
157pub mod profile;
158pub mod render;
159pub mod settings;
160pub mod skybox;
161pub mod stats;
162pub mod ui;
163pub mod voxel;
164pub mod world;
165
166use bevy::prelude::*;
167
168use audio::SfxPlugin;
169use fragments::FragmentPlugin;
170#[cfg(feature = "items")]
171use items::hotbar::HotbarPlugin;
172use mesh::MeshPlugin;
173use render::RenderPlugin;
174use skybox::SkyboxPlugin;
175use ui::UiPlugin;
176use voxel::DefaultVoxel;
177use voxel::VoxelType;
178use world::loading::LoadingPlugin;
179use world::mining::MiningPlugin;
180use world::occlusion::OcclusionPlugin;
181use world::placement::PlacementPlugin;
182use world::{WorldConfigPlugin, WorldPlugin};
183
184/// Convenience bundle for the historical core voxel runtime.
185///
186/// `VoxelCorePlugin<V>` wires up the legacy core bundle — world streaming,
187/// chunk lifecycle, meshing, PBR rendering, neighbor-solid occlusion, mining,
188/// placement, and loading state — without the bundled presentation defaults
189/// from [`VoxelPlugin`].
190///
191/// In the plugin catalog taxonomy this type is a [`plugin_category::ConveniencePlugin`]:
192/// it composes stricter Engine and Gameplay plugins for compatibility and quick
193/// starts. New architecture should describe those individual plugins by their
194/// primary categories rather than treating this bundle as the whole model.
195///
196/// The generic parameter `V` selects the voxel type used by the rendering,
197/// meshing, and occlusion systems. Defaults to [`DefaultVoxel`] for backwards
198/// compatibility: `VoxelCorePlugin::default()` and
199/// `VoxelCorePlugin::<DefaultVoxel>::new()` are equivalent.
200///
201/// # Included systems
202///
203/// | Plugin | Responsibility |
204/// |--------|----------------|
205/// | [`WorldPlugin`] | [`world::ChunkManager`], [`world::systems::ViewerPosition`], chunk lifecycle events, and streaming |
206/// | [`WorldConfigPlugin`] | Inserts the [`world::WorldConfig`] resource |
207/// | `RenderPlugin<V>` | Shared chunk PBR material and entity spawn |
208/// | `MeshPlugin<V>` | Greedy mesh generation and chunk despawn |
209/// | `OcclusionPlugin<V>` | Neighbor-solid chunk occlusion |
210/// | [`world::mining::MiningPlugin`] | Gameplay primitive for voxel removal |
211/// | [`world::placement::PlacementPlugin`] | Gameplay primitive for voxel placement |
212/// | [`world::loading::LoadingPlugin`] | World loading state machine |
213///
214/// # Not included (opt-in)
215///
216/// - [`generator::GeneratorPlugin`] — requires the caller to supply a
217///   [`generator::GeneratorResource`].
218#[cfg_attr(
219    feature = "items",
220    doc = "- [`FragmentPlugin`], [`SkyboxPlugin`], [`SfxPlugin`], [`HotbarPlugin`], and [`UiPlugin`] — presentation/gameplay defaults included by [`VoxelPlugin`]."
221)]
222#[cfg_attr(
223    not(feature = "items"),
224    doc = "- [`FragmentPlugin`], [`SkyboxPlugin`], [`SfxPlugin`], and [`UiPlugin`] — presentation defaults included by [`VoxelPlugin`]. `HotbarPlugin` additionally requires the `items` feature."
225)]
226///
227/// # Example
228///
229/// ```rust,no_run
230/// use bevy::prelude::*;
231/// use voxel_framework::{VoxelCorePlugin, generator::{GeneratorPlugin, GeneratorResource}};
232/// use voxel_framework::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
233/// use voxel_framework::voxel::DefaultVoxel;
234/// use std::sync::Arc;
235///
236/// App::new()
237///     .add_plugins(DefaultPlugins)
238///     .add_plugins(VoxelCorePlugin::<DefaultVoxel>::new())
239///     .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
240///     .insert_resource(GeneratorResource::<DefaultVoxel> {
241///         generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
242///     })
243///     .run();
244/// ```
245///
246/// # See also
247///
248/// - [`VoxelPlugin`] — broader quick-start convenience bundle.
249pub struct VoxelCorePlugin<V: VoxelType = DefaultVoxel> {
250    _m: std::marker::PhantomData<V>,
251}
252
253impl<V: VoxelType> VoxelCorePlugin<V> {
254    /// Creates a new [`VoxelCorePlugin`] for voxel type `V`.
255    pub fn new() -> Self {
256        Self {
257            _m: std::marker::PhantomData,
258        }
259    }
260}
261
262impl<V: VoxelType> Default for VoxelCorePlugin<V> {
263    fn default() -> Self {
264        Self::new()
265    }
266}
267
268impl<V: VoxelType> Plugin for VoxelCorePlugin<V> {
269    fn build(&self, app: &mut App) {
270        app.add_plugins(WorldPlugin);
271        app.add_plugins(WorldConfigPlugin);
272        app.add_plugins(RenderPlugin::<V>::new());
273        app.add_plugins(MeshPlugin::<V>::new());
274        app.add_plugins(OcclusionPlugin::<V>::new());
275        app.add_plugins(MiningPlugin);
276        app.add_plugins(PlacementPlugin);
277        app.add_plugins(LoadingPlugin);
278    }
279}
280
281/// Quick-start convenience bundle for demos and prototypes.
282///
283/// `VoxelPlugin<V>` composes [`VoxelCorePlugin<V>`] with selected presentation
284/// and gameplay defaults. It is useful for examples, demos, and early
285/// prototyping, but it is not the architectural definition of the full
286/// framework. Production games should treat it as a convenience bundle and
287/// switch to explicit catalog plugins when they need finer control.
288///
289/// The generic parameter `V` selects the voxel type. Defaults to
290/// [`DefaultVoxel`] — `VoxelPlugin::default()` produces an asteroid-palette
291/// world, `VoxelPlugin::<DefaultTerrainVoxel>::new()` produces a terrain world.
292///
293/// # Included beyond [`VoxelCorePlugin`]
294///
295/// | Plugin | Responsibility |
296/// |--------|----------------|
297/// | [`FragmentPlugin`] | Floating voxel debris entities ejected on mining |
298/// | [`SkyboxPlugin`] | Procedural starfield and skybox rendering |
299/// | [`SfxPlugin`] | Positional audio effects for mining and placement |
300#[cfg_attr(
301    feature = "items",
302    doc = "| [`HotbarPlugin`] | Player hotbar, item switching, and held-item state |"
303)]
304#[cfg_attr(
305    not(feature = "items"),
306    doc = "| `HotbarPlugin` *(feature `items`)* | Player hotbar, item switching, and held-item state |"
307)]
308/// | [`UiPlugin`] | Crosshair, loading screen, and HUD overlays |
309///
310/// # Generator not included
311///
312/// [`generator::GeneratorPlugin`] is intentionally excluded because it requires
313/// the caller to supply a concrete [`generator::GeneratorResource`]. Always add
314/// it separately:
315///
316/// ```rust,no_run
317/// use bevy::prelude::*;
318/// use voxel_framework::{VoxelPlugin, generator::{GeneratorPlugin, GeneratorResource}};
319/// use voxel_framework::generator::terrain::{TerrainConfig, TerrainGenerator};
320/// use voxel_framework::voxel::DefaultTerrainVoxel;
321/// use std::sync::Arc;
322///
323/// App::new()
324///     .add_plugins(DefaultPlugins)
325///     .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
326///     .add_plugins(GeneratorPlugin::<DefaultTerrainVoxel>::new())
327///     .insert_resource(GeneratorResource::<DefaultTerrainVoxel> {
328///         generator: Arc::new(TerrainGenerator::new(TerrainConfig::default())),
329///     })
330///     .run();
331/// ```
332///
333/// # See also
334///
335/// - [`VoxelCorePlugin`] — narrower compatibility/convenience bundle.
336/// - [`prelude`] — commonly used re-exports for convenience imports.
337pub struct VoxelPlugin<V: VoxelType = DefaultVoxel> {
338    _m: std::marker::PhantomData<V>,
339}
340
341impl<V: VoxelType> VoxelPlugin<V> {
342    /// Creates a new [`VoxelPlugin`] for voxel type `V`.
343    pub fn new() -> Self {
344        Self {
345            _m: std::marker::PhantomData,
346        }
347    }
348}
349
350impl<V: VoxelType> Default for VoxelPlugin<V> {
351    fn default() -> Self {
352        Self::new()
353    }
354}
355
356impl<V: VoxelType> Plugin for VoxelPlugin<V> {
357    fn build(&self, app: &mut App) {
358        app.add_plugins(VoxelCorePlugin::<V>::new());
359        app.add_plugins(FragmentPlugin);
360        app.add_plugins(SkyboxPlugin);
361        app.add_plugins(SfxPlugin);
362        #[cfg(feature = "items")]
363        app.add_plugins(HotbarPlugin);
364        app.add_plugins(UiPlugin);
365    }
366}