Skip to main content

voxel_framework/render/
mod.rs

1//! Rendering support for voxel chunks.
2//!
3//! Provides either a custom texture-array material ([`ChunkMaterial`]) or a
4//! shared `StandardMaterial` for vertex-colored voxels, depending on whether
5//! [`ChunkTextureArray`] is inserted before the plugin initialises.
6
7use bevy::asset::embedded_asset;
8use bevy::pbr::MaterialPlugin;
9use bevy::prelude::*;
10
11use crate::voxel::VoxelType;
12
13pub mod material;
14pub mod terrain;
15
16pub use material::ChunkMaterial;
17pub use material::ChunkMaterialConfig;
18pub use material::ChunkMaterialHandle;
19pub use material::ChunkRendered;
20pub use material::ChunkTextureArray;
21pub use material::build_texture_array;
22pub use material::chunk_aabb;
23pub use material::upgrade_to_texture_material;
24pub use terrain::{ChunkMaterialSection, TerrainMaterials};
25
26/// Plugin that sets up shared rendering resources for voxel chunks.
27///
28/// If [`ChunkTextureArray`] is present as a resource when the plugin builds,
29/// chunks will use the embedded WGSL shader with texture array support.
30/// Otherwise a shared `StandardMaterial` with vertex colors is used.
31pub struct RenderPlugin<V: VoxelType> {
32    _marker: std::marker::PhantomData<V>,
33}
34
35impl<V: VoxelType> RenderPlugin<V> {
36    /// Creates a new `RenderPlugin`.
37    pub fn new() -> Self {
38        Self {
39            _marker: std::marker::PhantomData,
40        }
41    }
42}
43
44impl<V: VoxelType> Default for RenderPlugin<V> {
45    fn default() -> Self {
46        Self::new()
47    }
48}
49
50impl<V: VoxelType> Plugin for RenderPlugin<V> {
51    fn build(&self, app: &mut App) {
52        // Embed the chunk WGSL shader into the binary.
53        // The resulting asset path is: embedded://voxel_framework/render/chunk.wgsl
54        embedded_asset!(app, "chunk.wgsl");
55
56        app.add_plugins(MaterialPlugin::<ChunkMaterial>::default());
57        app.init_resource::<ChunkMaterialHandle>();
58        app.init_resource::<ChunkMaterialConfig>();
59        app.init_resource::<TerrainMaterials>();
60        app.add_systems(Startup, material::setup_chunk_material);
61        app.add_systems(Update, material::upgrade_to_texture_material);
62    }
63}