use bevy::asset::RenderAssetUsages;
use bevy::math::bounding::Aabb3d;
use bevy::mesh::MeshVertexBufferLayoutRef;
use bevy::pbr::{Material, MaterialPipeline, MaterialPipelineKey, MeshPipelineKey};
use bevy::prelude::*;
use bevy::render::alpha::AlphaMode;
use bevy::render::render_resource::{
AsBindGroup, RenderPipelineDescriptor, SpecializedMeshPipelineError,
};
use bevy::shader::ShaderRef;
use crate::mesh::ATTRIBUTE_TEXTURE_LAYER;
#[derive(Asset, TypePath, AsBindGroup, Clone)]
pub struct ChunkMaterial {
#[texture(0, sample_type = "float", dimension = "2d_array")]
#[sampler(1)]
pub texture_array: Handle<Image>,
}
impl Material for ChunkMaterial {
fn vertex_shader() -> ShaderRef {
"embedded://voxel_framework/render/chunk.wgsl".into()
}
fn fragment_shader() -> ShaderRef {
"embedded://voxel_framework/render/chunk.wgsl".into()
}
fn specialize(
_pipeline: &MaterialPipeline,
descriptor: &mut RenderPipelineDescriptor,
layout: &MeshVertexBufferLayoutRef,
key: MaterialPipelineKey<Self>,
) -> Result<(), SpecializedMeshPipelineError> {
let is_prepass = key.mesh_key.intersects(
MeshPipelineKey::DEPTH_PREPASS
| MeshPipelineKey::NORMAL_PREPASS
| MeshPipelineKey::MOTION_VECTOR_PREPASS,
);
if is_prepass {
return Ok(());
}
let vertex_layout = layout.0.get_layout(&[
Mesh::ATTRIBUTE_POSITION.at_shader_location(0),
Mesh::ATTRIBUTE_NORMAL.at_shader_location(1),
Mesh::ATTRIBUTE_UV_0.at_shader_location(2),
Mesh::ATTRIBUTE_COLOR.at_shader_location(3),
ATTRIBUTE_TEXTURE_LAYER.at_shader_location(4),
])?;
descriptor.vertex.buffers = vec![vertex_layout];
Ok(())
}
}
#[derive(Resource)]
pub struct ChunkTextureArray {
pub handle: Handle<Image>,
}
#[derive(Resource, Default)]
pub struct ChunkMaterialHandle {
pub standard: Option<Handle<StandardMaterial>>,
pub custom: Option<Handle<ChunkMaterial>>,
}
#[derive(Resource, Clone, Debug)]
pub struct ChunkMaterialConfig {
pub base_color: Color,
pub alpha_mode: AlphaMode,
pub perceptual_roughness: f32,
pub metallic: f32,
pub reflectance: f32,
}
impl Default for ChunkMaterialConfig {
fn default() -> Self {
Self {
base_color: Color::WHITE,
alpha_mode: AlphaMode::Opaque,
perceptual_roughness: 0.9,
metallic: 0.0,
reflectance: 0.1,
}
}
}
#[derive(Component)]
pub struct ChunkRendered;
pub fn setup_chunk_material(
mut standard_materials: ResMut<Assets<StandardMaterial>>,
mut chunk_materials: ResMut<Assets<ChunkMaterial>>,
mut handle: ResMut<ChunkMaterialHandle>,
config: Res<ChunkMaterialConfig>,
texture_array: Option<Res<ChunkTextureArray>>,
) {
if let Some(tex) = texture_array {
let mat = ChunkMaterial {
texture_array: tex.handle.clone(),
};
handle.custom = Some(chunk_materials.add(mat));
} else {
let material = StandardMaterial {
base_color: config.base_color,
perceptual_roughness: config.perceptual_roughness,
metallic: config.metallic,
reflectance: config.reflectance,
alpha_mode: config.alpha_mode,
..default()
};
handle.standard = Some(standard_materials.add(material));
}
}
pub fn chunk_aabb() -> Aabb3d {
use bevy::math::Vec3A;
Aabb3d::new(Vec3A::splat(8.0), Vec3A::splat(8.0))
}
pub fn upgrade_to_texture_material(
mut commands: Commands,
mut chunk_materials: ResMut<Assets<ChunkMaterial>>,
mut handle: ResMut<ChunkMaterialHandle>,
texture_array: Option<Res<ChunkTextureArray>>,
rendered_chunks: Query<Entity, (With<ChunkRendered>, With<MeshMaterial3d<StandardMaterial>>)>,
) {
if handle.custom.is_some() {
return;
}
let Some(tex) = texture_array else {
return;
};
let mat = ChunkMaterial {
texture_array: tex.handle.clone(),
};
let mat_handle = chunk_materials.add(mat);
handle.custom = Some(mat_handle.clone());
for entity in &rendered_chunks {
commands
.entity(entity)
.remove::<MeshMaterial3d<StandardMaterial>>()
.insert(MeshMaterial3d(mat_handle.clone()));
}
eprintln!(
"voxel texture array active — {} chunk(s) upgraded to ChunkMaterial",
rendered_chunks.iter().count()
);
}
pub fn build_texture_array(images: &[Image]) -> Image {
assert!(
!images.is_empty(),
"build_texture_array: must provide at least one image"
);
let first = &images[0];
let width = first.width();
let height = first.height();
let format = first.texture_descriptor.format;
let layers = images.len() as u32;
for (i, img) in images.iter().enumerate() {
assert_eq!(img.width(), width, "image {i} width mismatch");
assert_eq!(img.height(), height, "image {i} height mismatch");
assert_eq!(
img.texture_descriptor.format, format,
"image {i} format mismatch"
);
}
let mut combined: Vec<u8> = Vec::new();
for img in images {
if let Some(data) = &img.data {
combined.extend_from_slice(data);
}
}
use bevy::render::render_resource::{
Extent3d, TextureDimension, TextureViewDescriptor, TextureViewDimension,
};
let size = Extent3d {
width,
height,
depth_or_array_layers: layers,
};
let mut array_image = Image::new(
size,
TextureDimension::D2,
combined,
format,
RenderAssetUsages::RENDER_WORLD,
);
array_image.texture_view_descriptor = Some(TextureViewDescriptor {
label: Some("chunk_texture_array_view"),
dimension: Some(TextureViewDimension::D2Array),
..Default::default()
});
array_image
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
chunk::Chunk,
mesh::generate_chunk_mesh,
voxel::{DefaultVoxel, VoxelType},
};
use bevy::mesh::VertexAttributeValues;
fn startup(config: ChunkMaterialConfig, texture: bool) -> App {
let mut app = App::new();
app.init_resource::<Assets<StandardMaterial>>()
.init_resource::<Assets<ChunkMaterial>>()
.init_resource::<ChunkMaterialHandle>()
.insert_resource(config)
.add_systems(Startup, setup_chunk_material);
if texture {
app.insert_resource(ChunkTextureArray {
handle: Handle::default(),
});
}
app.update();
app
}
#[test]
fn fallback_terrain_is_opaque_by_default() {
let app = startup(ChunkMaterialConfig::default(), false);
let handles = app.world().resource::<ChunkMaterialHandle>();
let materials = app.world().resource::<Assets<StandardMaterial>>();
let material = materials.get(handles.standard.as_ref().unwrap()).unwrap();
assert_eq!(material.alpha_mode, AlphaMode::Opaque);
assert!(handles.custom.is_none());
}
#[test]
fn default_palette_solids_are_opaque_and_air_has_no_geometry() {
for step in [1, 2] {
assert_eq!(
generate_chunk_mesh(&Chunk::<DefaultVoxel>::new(), step).count_vertices(),
0
);
for voxel in [
DefaultVoxel::Rock,
DefaultVoxel::IronOre,
DefaultVoxel::SiliconCrystal,
DefaultVoxel::RareMineral,
] {
assert_eq!(voxel.color()[3], 1.0);
let mut chunk = Chunk::new();
chunk.set(0, 0, 0, voxel);
let mesh = generate_chunk_mesh(&chunk, step);
assert!(mesh.count_vertices() > 0);
let Some(VertexAttributeValues::Float32x4(colors)) =
mesh.attribute(Mesh::ATTRIBUTE_COLOR)
else {
panic!("expected vertex colors")
};
assert!(colors.iter().all(|color| color[3] == 1.0));
}
}
}
#[test]
fn fallback_honors_explicit_alpha_and_pbr_configuration() {
for alpha_mode in [AlphaMode::Blend, AlphaMode::Mask(0.4)] {
let config = ChunkMaterialConfig {
base_color: Color::srgba(0.2, 0.3, 0.4, 0.5),
alpha_mode,
perceptual_roughness: 0.6,
metallic: 0.7,
reflectance: 0.8,
};
let app = startup(config.clone(), false);
let handles = app.world().resource::<ChunkMaterialHandle>();
let materials = app.world().resource::<Assets<StandardMaterial>>();
let material = materials.get(handles.standard.as_ref().unwrap()).unwrap();
assert_eq!(material.alpha_mode, alpha_mode);
assert_eq!(material.base_color, config.base_color);
assert_eq!(material.perceptual_roughness, config.perceptual_roughness);
assert_eq!(material.metallic, config.metallic);
assert_eq!(material.reflectance, config.reflectance);
}
}
#[test]
fn texture_array_ignores_fallback_alpha_policy() {
let app = startup(
ChunkMaterialConfig {
alpha_mode: AlphaMode::Blend,
..default()
},
true,
);
let handles = app.world().resource::<ChunkMaterialHandle>();
assert!(handles.standard.is_none());
let materials = app.world().resource::<Assets<ChunkMaterial>>();
let material = materials.get(handles.custom.as_ref().unwrap()).unwrap();
assert_eq!(material.alpha_mode(), AlphaMode::Opaque);
assert_eq!(material.texture_array, Handle::<Image>::default());
}
}