voxel-framework 0.13.1

A reusable voxel engine framework built on Bevy
Documentation
//! Terrain materials registered by the game and drawn per voxel type.
//!
//! "Material" here is the rendering material, the description of how a
//! surface responds to light, not the kind of voxel. A voxel type names its
//! material with [`VoxelType::material`](crate::voxel::VoxelType::material)
//! and the game registers what is drawn for each id in [`TerrainMaterials`].
//! The framework does not interpret a material; it only routes faces to it.

use std::collections::HashMap;

use bevy::pbr::Material;
use bevy::prelude::*;

use crate::voxel::TerrainMaterialId;

/// Adds the material component of one registered material to an entity.
type InsertMaterial = Box<dyn Fn(&mut EntityCommands) + Send + Sync>;

/// The rendering materials the game registered for its terrain, by
/// [`TerrainMaterialId`].
///
/// [`RenderPlugin`](super::RenderPlugin) initializes it empty. With nothing
/// registered every chunk is one mesh drawn with the shared chunk material,
/// as before. For each registered id, the faces of the voxel types whose
/// [`VoxelType::material`](crate::voxel::VoxelType::material) returns it are
/// drawn with the registered material instead, in a mesh of their own (a
/// child entity of the chunk marked with [`ChunkMaterialSection`]).
///
/// The material can be any Bevy [`Material`]: a `StandardMaterial` or a type
/// defined by the game. The game adds the `MaterialPlugin` of its own
/// material types; the framework only adds the handle to the entity.
///
/// Registering [`TerrainMaterialId::DEFAULT`] replaces the shared chunk
/// material for every voxel type that does not name another material.
///
/// Changing the registry while the game runs rebuilds the meshes of the
/// loaded chunks.
///
/// # Cost
///
/// Each registered material present in a chunk is one more mesh and one more
/// draw call for that chunk.
///
/// # Vertex data
///
/// Every terrain mesh carries position, normal, UV (0 to 1 across each merged
/// quad), vertex color (the voxel color in linear RGB, darkened by baked
/// ambient occlusion) and
/// [`ATTRIBUTE_TEXTURE_LAYER`](crate::mesh::ATTRIBUTE_TEXTURE_LAYER).
///
/// # Example
///
/// ```
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
///
/// const ICE: TerrainMaterialId = TerrainMaterialId(1);
///
/// fn register_terrain_materials(
///     mut terrain: ResMut<TerrainMaterials>,
///     mut materials: ResMut<Assets<StandardMaterial>>,
/// ) {
///     terrain.register(
///         ICE,
///         materials.add(StandardMaterial {
///             perceptual_roughness: 0.1,
///             ..default()
///         }),
///     );
/// }
/// ```
#[derive(Resource, Default)]
pub struct TerrainMaterials {
    entries: HashMap<TerrainMaterialId, InsertMaterial>,
}

impl TerrainMaterials {
    /// Registers the material drawn for `id`, replacing a previous one.
    pub fn register<M: Material>(
        &mut self,
        id: TerrainMaterialId,
        material: Handle<M>,
    ) -> &mut Self {
        self.entries.insert(
            id,
            Box::new(move |entity: &mut EntityCommands| {
                entity.insert(MeshMaterial3d(material.clone()));
            }),
        );
        self
    }

    /// Removes the material of `id`. Its faces go back to the shared chunk
    /// material. Returns whether a material was registered.
    pub fn unregister(&mut self, id: TerrainMaterialId) -> bool {
        self.entries.remove(&id).is_some()
    }

    /// Whether a material is registered for `id`.
    pub fn contains(&self, id: TerrainMaterialId) -> bool {
        self.entries.contains_key(&id)
    }

    /// The registered ids, sorted.
    pub fn ids(&self) -> Vec<TerrainMaterialId> {
        let mut ids: Vec<_> = self.entries.keys().copied().collect();
        ids.sort();
        ids
    }

    /// Whether nothing is registered.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Adds the material component of `id` to `entity`. Returns `false`, and
    /// adds nothing, when no material is registered for it.
    pub(crate) fn insert_material(
        &self,
        id: TerrainMaterialId,
        entity: &mut EntityCommands,
    ) -> bool {
        match self.entries.get(&id) {
            Some(insert) => {
                insert(entity);
                true
            }
            None => false,
        }
    }
}

/// Marks the child entity of a chunk that draws the faces of one registered
/// terrain material.
///
/// The mesh system spawns, updates and despawns these entities; a game reads
/// the component to find them. They follow the chunk: they are despawned with
/// it and hidden with it.
#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChunkMaterialSection {
    /// The material whose faces this entity draws.
    pub material: TerrainMaterialId,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn registry_tracks_registered_ids() {
        let mut terrain = TerrainMaterials::default();
        assert!(terrain.is_empty());

        terrain
            .register(TerrainMaterialId(4), Handle::<StandardMaterial>::default())
            .register(TerrainMaterialId(2), Handle::<StandardMaterial>::default());

        assert!(terrain.contains(TerrainMaterialId(2)));
        assert!(!terrain.contains(TerrainMaterialId::DEFAULT));
        assert_eq!(
            terrain.ids(),
            vec![TerrainMaterialId(2), TerrainMaterialId(4)]
        );
    }

    #[test]
    fn unregister_reports_whether_a_material_was_there() {
        let mut terrain = TerrainMaterials::default();
        terrain.register(TerrainMaterialId(1), Handle::<StandardMaterial>::default());

        assert!(terrain.unregister(TerrainMaterialId(1)));
        assert!(!terrain.unregister(TerrainMaterialId(1)));
        assert!(terrain.is_empty());
    }

    #[test]
    fn insert_material_adds_the_registered_material_component() {
        let mut world = World::new();
        let mut terrain = TerrainMaterials::default();
        let handle = Handle::<StandardMaterial>::default();
        terrain.register(TerrainMaterialId(1), handle.clone());
        let entity = world.spawn_empty().id();

        let mut commands = world.commands();
        let mut entity_commands = commands.entity(entity);
        assert!(terrain.insert_material(TerrainMaterialId(1), &mut entity_commands));
        assert!(!terrain.insert_material(TerrainMaterialId(9), &mut entity_commands));
        world.flush();

        assert_eq!(
            world.get::<MeshMaterial3d<StandardMaterial>>(entity),
            Some(&MeshMaterial3d(handle))
        );
    }
}