block-mesh

block-mesh 是 Rust 体素网格化的事实标准底层库,提供两种算法:极速但次优的面剔除,以及稍慢但最优的贪心合并。被 126+ 下游仓库使用。

基本信息

属性
仓库bonsairobo/block-mesh-rs
Crateblock-mesh (crates.io)
星标240★ / 29 分叉
下游使用126+ 仓库
许可MIT OR Apache-2.0

两种算法

算法速度输出质量代码
visible_block_faces~4000万 quad/秒(单核 i7 2.5GHz)次优(更多 quads)可见面提取
greedy_quads~3× 耗时最优(球形数据约 1/3 quads)贪心合并

实测命令:cd bench/ && cargo bench

Trait 系统

库要求为自定义体素类型实现以下 trait:

Voxel

trait Voxel {
    fn get_visibility(&self) -> VoxelVisibility;
}

VoxelVisibility 有三种变体:

  • Empty — 空体素,不渲染
  • Opaque — 不透明,阻挡背后面提取
  • Translucent — 半透明,需要特殊处理

MergeVoxel

用于 greedy meshing,决定两个体素面是否可以合并:

trait MergeVoxel {
    type MergeValue;
    type MergeValueFacingNeighbour;
    fn merge_value(&self) -> Self::MergeValue;
    fn merge_value_facing_neighbour(&self) -> Self::MergeValueFacingNeighbour;
}

坐标系统与形状

  • RIGHT_HANDED_Y_UP_CONFIG — 右手坐标系,Y 轴向上(与 Bevy 默认一致)
  • ndshape::ConstShape3u32<X, Y, Z> — 编译时 3D 数组形状
  • 建议使用 1-voxel padding(如 18³ 数组存储 16³ chunk)以避免边界断裂

典型使用模式

use block_mesh::ndshape::{ConstShape, ConstShape3u32};
use block_mesh::{greedy_quads, GreedyQuadsBuffer, MergeVoxel, Voxel, VoxelVisibility, RIGHT_HANDED_Y_UP_CONFIG};
 
#[derive(Clone, Copy, Eq, PartialEq)]
struct BoolVoxel(bool);
 
const EMPTY: BoolVoxel = BoolVoxel(false);
const FULL: BoolVoxel = BoolVoxel(true);
 
impl Voxel for BoolVoxel {
    fn get_visibility(&self) -> VoxelVisibility {
        if *self == EMPTY { VoxelVisibility::Empty } else { VoxelVisibility::Opaque }
    }
}
 
impl MergeVoxel for BoolVoxel {
    type MergeValue = Self;
    type MergeValueFacingNeighbour = Self;
    fn merge_value(&self) -> Self { *self }
    fn merge_value_facing_neighbour(&self) -> Self { *self }
}
 
type ChunkShape = ConstShape3u32<18, 18, 18>;
let mut voxels = [EMPTY; ChunkShape::SIZE as usize];
// ... 填充体素数据 ...
 
let mut buffer = GreedyQuadsBuffer::new(voxels.len());
greedy_quads(&voxels, &ChunkShape {}, [0; 3], [17; 3],
    &RIGHT_HANDED_Y_UP_CONFIG.faces, &mut buffer);

伴生库

block-mesh-bgm

基于二进制掩码的快速 greedy mesher,通过 bitwise 测试替换逐体素比较。提供与 block_mesh::greedy_quads 兼容的 API,设计目标是高性能与低开销。

选型建议

适用:需要完全控制体素 meshing 管线、自定义 chunk 系统、与 Bevy Meshlet 集成、或非 Bevy 框架使用。

不适用:快速原型验证、不想自己管理 chunk 生成/销毁逻辑 → 考虑 bevy_voxel_world

相关页面