use bevy::mesh::Mesh;
use crate::chunk::{CHUNK_SIZE, Chunk};
use crate::voxel::{TerrainMaterialId, VoxelType};
use super::greedy::{Chamfer, FaceDir, build_material_meshes, build_mesh, super_voxel};
use super::{ChunkNeighbors, MeshConfig};
pub fn generate_chunk_mesh_with_neighbors<V: VoxelType>(
chunk: &Chunk<V>,
neighbors: &ChunkNeighbors<V>,
step: usize,
) -> Mesh {
crate::profile_span!("voxel::mesh::neighbor");
let face_visible =
|chunk: &Chunk<V>, x: usize, y: usize, z: usize, face: &FaceDir, step: usize| -> bool {
is_face_visible(chunk, neighbors, x, y, z, face, step)
};
build_mesh(chunk, step, &face_visible)
}
pub fn generate_chunk_material_meshes<V: VoxelType>(
chunk: &Chunk<V>,
neighbors: &ChunkNeighbors<V>,
step: usize,
) -> Vec<(TerrainMaterialId, Mesh)> {
generate_chunk_material_meshes_with_config(chunk, neighbors, step, &MeshConfig::default())
}
pub fn generate_chunk_material_meshes_with_config<V: VoxelType>(
chunk: &Chunk<V>,
neighbors: &ChunkNeighbors<V>,
step: usize,
config: &MeshConfig,
) -> Vec<(TerrainMaterialId, Mesh)> {
generate_chunk_material_meshes_with(chunk, neighbors, step, config, &|voxel: V| {
voxel.material()
})
}
pub(crate) fn generate_chunk_material_meshes_with<V: VoxelType, K: Copy + Ord>(
chunk: &Chunk<V>,
neighbors: &ChunkNeighbors<V>,
step: usize,
config: &MeshConfig,
material_of: &dyn Fn(V) -> K,
) -> Vec<(K, Mesh)> {
crate::profile_span!("voxel::mesh::neighbor");
let face_visible =
|chunk: &Chunk<V>, x: usize, y: usize, z: usize, face: &FaceDir, step: usize| -> bool {
is_face_visible(chunk, neighbors, x, y, z, face, step)
};
let sample = |coords: [i32; 3]| sample_voxel(chunk, neighbors, coords);
let chamfer = config.chamfer_width().map(|width| Chamfer {
width,
sample: &sample,
});
build_material_meshes(chunk, step, &face_visible, chamfer.as_ref(), material_of)
}
fn sample_voxel<V: VoxelType>(
chunk: &Chunk<V>,
neighbors: &ChunkNeighbors<V>,
coords: [i32; 3],
) -> Option<V> {
let size = CHUNK_SIZE as i32;
let mut outside = None;
for (axis, &coord) in coords.iter().enumerate() {
if coord < 0 || coord >= size {
if outside.is_some() || coord < -1 || coord > size {
return None;
}
outside = Some((axis, coord >= size));
}
}
let [x, y, z] = coords.map(|coord| coord.clamp(0, size - 1) as usize);
let Some((axis, positive)) = outside else {
return Some(chunk.get(x, y, z));
};
let (face_index, slice_index) = match axis {
1 => (if positive { 0 } else { 1 }, x * CHUNK_SIZE + z),
0 => (if positive { 2 } else { 3 }, y * CHUNK_SIZE + z),
_ => (if positive { 4 } else { 5 }, x * CHUNK_SIZE + y),
};
Some(match &neighbors.faces[face_index] {
Some(slice) => slice[slice_index],
None => V::air(),
})
}
#[inline]
fn is_face_visible<V: VoxelType>(
chunk: &Chunk<V>,
neighbors: &ChunkNeighbors<V>,
x: usize,
y: usize,
z: usize,
face: &FaceDir,
step: usize,
) -> bool {
let coords = [x, y, z];
let axis = face.axis;
let neighbor_on_axis = if face.positive {
coords[axis].wrapping_add(step)
} else {
coords[axis].wrapping_sub(step)
};
if neighbor_on_axis < CHUNK_SIZE {
let mut nc = [x, y, z];
nc[axis] = neighbor_on_axis;
let sv = super_voxel(chunk, nc[0], nc[1], nc[2], step);
return !sv.is_solid() || sv.color()[3] < 1.0;
}
let face_index = face_dir_to_index(face);
match &neighbors.faces[face_index] {
None => true, Some(slice) => {
let u_coord = coords[face.u_axis];
let v_coord = coords[face.v_axis];
for du in 0..step {
for dv in 0..step {
let u = u_coord + du;
let v = v_coord + dv;
if u >= CHUNK_SIZE || v >= CHUNK_SIZE {
return true; }
let slice_index = border_slice_index(face_index, u, v);
let neighbor = slice[slice_index];
if !neighbor.is_solid() || neighbor.color()[3] < 1.0 {
return true; }
}
}
false }
}
}
#[inline]
fn face_dir_to_index(face: &FaceDir) -> usize {
match (face.axis, face.positive) {
(1, true) => 0, (1, false) => 1, (0, true) => 2, (0, false) => 3, (2, true) => 4, (2, false) => 5, _ => unreachable!(),
}
}
#[inline]
fn border_slice_index(face_index: usize, u_coord: usize, v_coord: usize) -> usize {
match face_index {
0 | 1 => u_coord * CHUNK_SIZE + v_coord,
2 | 3 => v_coord * CHUNK_SIZE + u_coord,
4 | 5 => u_coord * CHUNK_SIZE + v_coord,
_ => unreachable!(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::voxel::DefaultVoxel;
const MAX: usize = CHUNK_SIZE - 1;
fn face_cases() -> [(usize, usize, (usize, usize, usize), (usize, usize, usize)); 6] {
[
(0, 1, (3, MAX, 7), (3, 0, 7)),
(1, 0, (3, 0, 7), (3, MAX, 7)),
(2, 3, (MAX, 3, 7), (0, 3, 7)),
(3, 2, (0, 3, 7), (MAX, 3, 7)),
(4, 5, (3, 7, MAX), (3, 7, 0)),
(5, 4, (3, 7, 0), (3, 7, MAX)),
]
}
fn single(cell: (usize, usize, usize)) -> Chunk<DefaultVoxel> {
let mut chunk = Chunk::new();
chunk.set(cell.0, cell.1, cell.2, DefaultVoxel::Rock);
chunk
}
fn mesh_vertices(
chunk: &Chunk<DefaultVoxel>,
face: usize,
slice_src: &Chunk<DefaultVoxel>,
opposite: usize,
) -> usize {
let mut neighbors = ChunkNeighbors::<DefaultVoxel>::default();
neighbors.faces[face] = Some(slice_src.border_slice(opposite));
generate_chunk_mesh_with_neighbors(chunk, &neighbors, 1).count_vertices()
}
#[test]
fn solid_neighbor_culls_the_touching_face_on_every_side() {
for (face, opposite, cell, touching) in face_cases() {
let vertices = mesh_vertices(&single(cell), face, &single(touching), opposite);
assert_eq!(
vertices, 20,
"face {face}: one of six quads (4 vertices) should be culled"
);
}
}
#[test]
fn neighbor_solid_at_a_different_cell_does_not_cull() {
for (face, opposite, cell, touching) in face_cases() {
let swapped = match face {
0 | 1 => (touching.2, touching.1, touching.0),
2 | 3 => (touching.0, touching.2, touching.1),
_ => (touching.1, touching.0, touching.2),
};
let vertices = mesh_vertices(&single(cell), face, &single(swapped), opposite);
assert_eq!(
vertices, 24,
"face {face}: misaligned neighbor must not cull"
);
}
}
#[test]
fn missing_or_empty_neighbor_keeps_all_faces() {
let chunk = single((0, 0, 0));
let none = ChunkNeighbors::<DefaultVoxel>::default();
assert_eq!(
generate_chunk_mesh_with_neighbors(&chunk, &none, 1).count_vertices(),
24
);
let empty = Chunk::<DefaultVoxel>::new();
assert_eq!(mesh_vertices(&chunk, 3, &empty, 2), 24);
}
use crate::mesh::test_voxel::{GLASS, TwoMaterialVoxel};
fn quad_count(mesh: &Mesh) -> usize {
mesh.count_vertices() / 4
}
#[test]
fn faces_are_split_into_one_mesh_per_material() {
let mut chunk = Chunk::<TwoMaterialVoxel>::new();
chunk.set(2, 2, 2, TwoMaterialVoxel::Stone);
chunk.set(8, 8, 8, TwoMaterialVoxel::Glass);
chunk.set(12, 8, 8, TwoMaterialVoxel::Glass);
let neighbors = ChunkNeighbors::default();
let meshes = generate_chunk_material_meshes(&chunk, &neighbors, 1);
let ids: Vec<_> = meshes.iter().map(|(id, _)| *id).collect();
assert_eq!(ids, vec![TerrainMaterialId::DEFAULT, GLASS]);
assert_eq!(quad_count(&meshes[0].1), 6);
assert_eq!(quad_count(&meshes[1].1), 12);
}
#[test]
fn material_meshes_hold_the_same_quads_as_the_single_mesh() {
let mut chunk = Chunk::<TwoMaterialVoxel>::new();
for x in 0..6 {
for z in 0..6 {
let voxel = if (x + z) % 3 == 0 {
TwoMaterialVoxel::Glass
} else {
TwoMaterialVoxel::Stone
};
chunk.set(x, 4, z, voxel);
}
}
let neighbors = ChunkNeighbors::default();
for step in [1, 2] {
let single = generate_chunk_mesh_with_neighbors(&chunk, &neighbors, step);
let split = generate_chunk_material_meshes(&chunk, &neighbors, step);
let total: usize = split.iter().map(|(_, mesh)| quad_count(mesh)).sum();
assert_eq!(total, quad_count(&single), "step {step}");
}
}
#[test]
fn a_material_without_visible_faces_has_no_mesh() {
let mut chunk = Chunk::<TwoMaterialVoxel>::new();
chunk.set(3, 3, 3, TwoMaterialVoxel::Glass);
let neighbors = ChunkNeighbors::default();
let meshes = generate_chunk_material_meshes(&chunk, &neighbors, 1);
assert_eq!(meshes.len(), 1);
assert_eq!(meshes[0].0, GLASS);
}
#[test]
fn empty_chunk_has_no_material_meshes() {
let chunk = Chunk::<TwoMaterialVoxel>::new();
let neighbors = ChunkNeighbors::default();
assert!(generate_chunk_material_meshes(&chunk, &neighbors, 1).is_empty());
}
#[test]
fn caller_routing_can_send_every_voxel_to_one_material() {
let mut chunk = Chunk::<TwoMaterialVoxel>::new();
chunk.set(2, 2, 2, TwoMaterialVoxel::Stone);
chunk.set(8, 8, 8, TwoMaterialVoxel::Glass);
let neighbors = ChunkNeighbors::default();
let meshes = generate_chunk_material_meshes_with(
&chunk,
&neighbors,
1,
&MeshConfig::default(),
&|_| TerrainMaterialId::DEFAULT,
);
assert_eq!(meshes.len(), 1);
assert_eq!(quad_count(&meshes[0].1), 12);
}
use bevy::mesh::{Indices, VertexAttributeValues};
use bevy::prelude::Vec3;
const CHAMFER: MeshConfig = MeshConfig {
edge_chamfer: Some(0.2),
};
fn chamfered(chunk: &Chunk<DefaultVoxel>, neighbors: &ChunkNeighbors<DefaultVoxel>) -> Mesh {
let mut meshes = generate_chunk_material_meshes_with_config(chunk, neighbors, 1, &CHAMFER);
assert_eq!(meshes.len(), 1);
meshes.remove(0).1
}
fn triangles(mesh: &Mesh) -> Vec<([Vec3; 3], Vec3)> {
let Some(VertexAttributeValues::Float32x3(positions)) =
mesh.attribute(Mesh::ATTRIBUTE_POSITION)
else {
panic!("positions");
};
let Some(VertexAttributeValues::Float32x3(normals)) =
mesh.attribute(Mesh::ATTRIBUTE_NORMAL)
else {
panic!("normals");
};
let Some(Indices::U32(indices)) = mesh.indices() else {
panic!("indices");
};
indices
.chunks(3)
.map(|tri| {
let corner = |i: u32| Vec3::from_array(positions[i as usize]);
(
[corner(tri[0]), corner(tri[1]), corner(tri[2])],
Vec3::from_array(normals[tri[0] as usize]),
)
})
.collect()
}
fn assert_closed(mesh: &Mesh) -> f32 {
let mut area = bevy::math::DVec3::ZERO;
let mut volume = 0.0f64;
for ([a, b, c], normal) in triangles(mesh) {
let cross = (b - a).cross(c - a);
assert!(
cross.length() == 0.0 || cross.normalize().dot(normal) > 0.99,
"triangle {a} {b} {c} does not face along its normal {normal}"
);
assert!((normal.length() - 1.0).abs() < 1e-4, "unit normal");
let (a, b, c) = (a.as_dvec3(), b.as_dvec3(), c.as_dvec3());
area += (b - a).cross(c - a) * 0.5;
volume += a.dot(b.cross(c)) / 6.0;
}
assert!(area.length() < 1e-3, "open surface: area vector sum {area}");
volume as f32
}
#[test]
fn no_chamfer_by_default() {
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(5, 5, 5, DefaultVoxel::Rock);
let neighbors = ChunkNeighbors::default();
let off = generate_chunk_material_meshes_with_config(
&chunk,
&neighbors,
1,
&MeshConfig::default(),
);
assert_eq!(off[0].1.count_vertices(), 24);
for width in [0.0, -0.3, f32::NAN] {
let config = MeshConfig {
edge_chamfer: Some(width),
};
let mesh = generate_chunk_material_meshes_with_config(&chunk, &neighbors, 1, &config);
assert_eq!(mesh[0].1.count_vertices(), 24, "width {width}");
}
}
#[test]
fn lone_voxel_is_chamfered_on_every_edge_and_stays_closed() {
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(5, 5, 5, DefaultVoxel::Rock);
let mesh = chamfered(&chunk, &ChunkNeighbors::default());
assert_eq!(mesh.count_vertices(), 6 * (4 + 4 * 4 + 4 * 4));
let volume = assert_closed(&mesh);
assert!(
volume < 1.0 && volume > 1.0 - 12.0 * 0.02,
"volume {volume}"
);
for ([a, b, c], _) in triangles(&mesh) {
for p in [a, b, c] {
assert!(p.min_element() >= 5.0 - 1e-5 && p.max_element() <= 6.0 + 1e-5);
}
}
}
#[test]
fn flat_seams_between_voxels_stay_merged() {
let mut chunk = Chunk::<DefaultVoxel>::new();
for x in 2..10 {
for z in 2..10 {
chunk.set(x, 4, z, DefaultVoxel::Rock);
}
}
let mesh = chamfered(&chunk, &ChunkNeighbors::default());
assert_eq!(mesh.count_vertices(), 6 * (4 + 4 * 4 + 4 * 4));
let volume = assert_closed(&mesh);
assert!(
volume < 64.0 - 1.2 && volume > 64.0 - 1.5,
"volume {volume}"
);
}
#[test]
fn chamfer_ending_against_another_voxel_is_capped() {
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(4, 4, 4, DefaultVoxel::Rock);
chunk.set(5, 4, 4, DefaultVoxel::Rock);
chunk.set(5, 5, 4, DefaultVoxel::Rock);
let mesh = chamfered(&chunk, &ChunkNeighbors::default());
let volume = assert_closed(&mesh);
assert!(volume < 3.0 && volume > 2.5, "volume {volume}");
}
#[test]
fn irregular_shapes_stay_closed() {
let mut chunk = Chunk::<DefaultVoxel>::new();
let mut count = 0;
for x in 1..15usize {
for y in 1..15usize {
for z in 1..15usize {
let hash = (x * 73_856_093) ^ (y * 19_349_663) ^ (z * 83_492_791);
if hash % 5 < 2 {
let voxel = if hash % 7 == 0 {
DefaultVoxel::IronOre
} else {
DefaultVoxel::Rock
};
chunk.set(x, y, z, voxel);
count += 1;
}
}
}
}
let mesh = chamfered(&chunk, &ChunkNeighbors::default());
let volume = assert_closed(&mesh);
assert!(volume < count as f32 && volume > count as f32 * 0.7);
}
#[test]
fn chamfer_reaches_the_chunk_border_and_stays_closed() {
let mut chunk = Chunk::<DefaultVoxel>::new();
for x in 0..CHUNK_SIZE {
for y in 0..CHUNK_SIZE {
for z in 0..CHUNK_SIZE {
chunk.set(x, y, z, DefaultVoxel::Rock);
}
}
}
let mesh = chamfered(&chunk, &ChunkNeighbors::default());
assert_eq!(mesh.count_vertices(), 6 * (4 + 4 * 4 + 4 * 4));
assert_closed(&mesh);
}
#[test]
fn edge_against_a_solid_neighbor_chunk_is_not_chamfered() {
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(5, 0, 5, DefaultVoxel::Rock);
let mut neighbors = ChunkNeighbors::default();
neighbors.faces[1] = Some([DefaultVoxel::Rock; CHUNK_SIZE * CHUNK_SIZE]);
let mesh = chamfered(&chunk, &neighbors);
assert_eq!(
mesh.count_vertices(),
(4 + 4 * 4 + 4 * 4) + 4 * (4 + 3 * 4 + 2 * 4 + 2 * 3)
);
for ([a, b, c], _) in triangles(&mesh) {
for p in [a, b, c] {
assert!(p.y >= 0.0);
}
}
}
#[test]
fn coarse_lod_is_not_chamfered() {
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(4, 4, 4, DefaultVoxel::Rock);
let neighbors = ChunkNeighbors::default();
let sharp = generate_chunk_mesh_with_neighbors(&chunk, &neighbors, 2);
let with_config =
generate_chunk_material_meshes_with_config(&chunk, &neighbors, 2, &CHAMFER);
assert_eq!(with_config[0].1.count_vertices(), sharp.count_vertices());
}
#[test]
fn chamfer_keeps_material_meshes_separate_and_closed_together() {
let mut chunk = Chunk::<TwoMaterialVoxel>::new();
chunk.set(4, 4, 4, TwoMaterialVoxel::Stone);
chunk.set(5, 4, 4, TwoMaterialVoxel::Glass);
let neighbors = ChunkNeighbors::default();
let meshes = generate_chunk_material_meshes_with_config(&chunk, &neighbors, 1, &CHAMFER);
assert_eq!(meshes.len(), 2);
let mut area = Vec3::ZERO;
for (_, mesh) in &meshes {
for ([a, b, c], _) in triangles(mesh) {
area += (b - a).cross(c - a) * 0.5;
}
}
assert!(area.length() < 1e-3, "area vector sum {area}");
}
use crate::mesh::ATTRIBUTE_FACE_EXPOSED;
fn exposed_by_vertex(mesh: &Mesh) -> Vec<([f32; 3], f32)> {
let Some(VertexAttributeValues::Float32x3(normals)) =
mesh.attribute(Mesh::ATTRIBUTE_NORMAL)
else {
panic!("normals");
};
let Some(VertexAttributeValues::Float32(exposed)) = mesh.attribute(ATTRIBUTE_FACE_EXPOSED)
else {
panic!("exposed attribute");
};
assert_eq!(normals.len(), exposed.len());
normals
.iter()
.copied()
.zip(exposed.iter().copied())
.collect()
}
#[test]
fn every_vertex_reports_no_exposed_face_by_default() {
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(5, 5, 5, DefaultVoxel::Rock);
let mesh = generate_chunk_mesh_with_neighbors(&chunk, &ChunkNeighbors::default(), 1);
let vertices = exposed_by_vertex(&mesh);
assert_eq!(vertices.len(), 24);
assert!(vertices.iter().all(|(_, exposed)| *exposed == 0.0));
}
#[test]
fn only_the_recorded_face_is_reported_as_exposed() {
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(5, 5, 5, DefaultVoxel::Rock);
chunk.set_exposed_faces(5, 5, 5, 1 << 2);
let mesh = generate_chunk_mesh_with_neighbors(&chunk, &ChunkNeighbors::default(), 1);
for (normal, exposed) in exposed_by_vertex(&mesh) {
let expected = if normal == [1.0, 0.0, 0.0] { 1.0 } else { 0.0 };
assert_eq!(exposed, expected, "normal {normal:?}");
}
}
#[test]
fn exposed_and_original_faces_do_not_merge() {
let mut chunk = Chunk::<DefaultVoxel>::new();
for x in 2..6 {
chunk.set(x, 5, 5, DefaultVoxel::Rock);
}
let neighbors = ChunkNeighbors::default();
let merged = generate_chunk_mesh_with_neighbors(&chunk, &neighbors, 1);
assert_eq!(merged.count_vertices(), 24);
chunk.set_exposed_faces(3, 5, 5, 1 << 0);
let split = generate_chunk_mesh_with_neighbors(&chunk, &neighbors, 1);
assert_eq!(split.count_vertices(), 24 + 8);
let fresh = exposed_by_vertex(&split)
.iter()
.filter(|(_, exposed)| *exposed == 1.0)
.count();
assert_eq!(fresh, 4);
}
#[test]
fn chamfer_vertices_carry_the_flag_of_their_face() {
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(5, 5, 5, DefaultVoxel::Rock);
chunk.set_exposed_faces(5, 5, 5, 1 << 0);
let mesh = chamfered(&chunk, &ChunkNeighbors::default());
let fresh = exposed_by_vertex(&mesh)
.iter()
.filter(|(_, exposed)| *exposed == 1.0)
.count();
assert_eq!(fresh, 4 + 4 * 4 + 4 * 4);
assert_closed(&mesh);
}
}