Mesh resident block models with native culling and UV-aware merging

This commit is contained in:
Ludovic Marie
2026-10-06 22:30:16 +02:00
parent f5ba959cdc
commit a6966ab450
17 changed files with 1330 additions and 185 deletions
+28 -19
View File
@@ -30,12 +30,17 @@ use std::{
pub struct BakedFace {
pub quad: ModelQuad,
pub layer: u32,
pub opaque: bool,
}
pub struct BakedModel {
pub faces: Vec<BakedFace>,
pub cube: Option<[super::cube::CubeStyle; 6]>,
}
type VariantKey = (String, [u8; 3], bool);
pub struct StateModels {
choices: Vec<CompiledChoices>,
states: BTreeMap<BlockStateId, (usize, SelectedModels)>,
baked: BTreeMap<VariantKey, Vec<BakedFace>>,
baked: BTreeMap<VariantKey, BakedModel>,
}
fn key(variant: &Variant) -> VariantKey {
(variant.model.clone(), variant.rotations, variant.uv_lock)
@@ -159,14 +164,26 @@ impl StateModels {
let mut baked = BTreeMap::new();
for (name, turns, lock) in variants {
let model = library.resolve(&name)?;
let faces = bake_model_transformed(&model, BlockModelTransform::new(turns, lock))?.into_iter().map(|quad| {
if quad.material.force_translucent || quad.tint_index != -1 {
return Err("inspection gallery requires untinted opaque or binary-cutout materials".into());
}
let layer = sprites.insert(root, &quad.material.sprite)?;
Ok(BakedFace { quad, layer })
}).collect::<Result<_>>()?;
baked.insert((name, turns, lock), faces);
let faces: Vec<BakedFace> =
bake_model_transformed(&model, BlockModelTransform::new(turns, lock))?
.into_iter()
.map(|quad| {
if quad.material.force_translucent || quad.tint_index != -1 {
return Err(
"inspection gallery requires untinted opaque or binary-cutout materials"
.into(),
);
}
let layer = sprites.insert(root, &quad.material.sprite)?;
Ok(BakedFace {
quad,
layer,
opaque: sprites.opaque[layer as usize],
})
})
.collect::<Result<_>>()?;
let cube = super::cube::cube_styles(&faces);
baked.insert((name, turns, lock), BakedModel { faces, cube });
}
Ok(Self {
choices,
@@ -178,7 +195,7 @@ impl StateModels {
&self,
state: BlockStateId,
position: BlockPos,
) -> Result<Vec<(&Variant, &[BakedFace])>> {
) -> Result<Vec<(&Variant, &BakedModel)>> {
let (choice, selected) = self
.states
.get(&state)
@@ -190,15 +207,7 @@ impl StateModels {
self.choices[*choice].collect(selected, &mut random, &mut variants)?;
variants
.into_iter()
.map(|v| {
Ok((
v,
self.baked
.get(&key(v))
.ok_or("unbaked block model")?
.as_slice(),
))
})
.map(|v| Ok((v, self.baked.get(&key(v)).ok_or("unbaked block model")?)))
.collect()
}
}
+158
View File
@@ -0,0 +1,158 @@
//! Exact unit-cube faces eligible for repeated-texture greedy rectangles.
use super::catalog::BakedFace;
use horizon_assets::model::Direction;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CubeStyle {
pub layer: u32,
/// UV at spatial (u,v)=(0,0), then the two signed unit-axis derivatives.
pub uv: [i8; 6],
pub shade_bits: u32,
}
pub fn shade(face: &BakedFace) -> f32 {
match face
.quad
.shade_direction_override
.unwrap_or(face.quad.facing)
{
Direction::Down => 0.5,
Direction::Up => 1.0,
Direction::North | Direction::South => 0.8,
Direction::West | Direction::East => 0.6,
}
}
pub fn cube_styles(faces: &[BakedFace]) -> Option<[CubeStyle; 6]> {
if faces.len() != 6 {
return None;
}
let mut styles = [None; 6];
for face in faces {
if !face.opaque || face.quad.light_emission != 0 {
return None;
}
let q = &face.quad;
let direction = q.cull?;
if q.facing != direction || styles[direction as usize].is_some() {
return None;
}
let (axis, u, v) = match direction {
Direction::Down | Direction::Up => (1, 0, 2),
Direction::North | Direction::South => (2, 0, 1),
Direction::West | Direction::East => (0, 2, 1),
};
let plane = if (direction as usize).is_multiple_of(2) {
0.0
} else {
1.0
};
let mut uv = [None; 4];
for (p, texture) in q.positions.iter().zip(q.uv) {
if p[axis] != plane
|| ![p[u], p[v], texture[0], texture[1]]
.iter()
.all(|&x| x == 0.0 || x == 1.0)
{
return None;
}
let index = p[u] as usize + 2 * p[v] as usize;
if uv[index].replace(texture.map(|x| x as i8)).is_some() {
return None;
}
}
let [a, b, c, d] = uv.map(|v| v.unwrap());
let du = [b[0] - a[0], b[1] - a[1]];
let dv = [c[0] - a[0], c[1] - a[1]];
if d != [a[0] + du[0] + dv[0], a[1] + du[1] + dv[1]]
|| (du[0] * dv[1] - du[1] * dv[0]).abs() != 1
{
return None;
}
styles[direction as usize] = Some(CubeStyle {
layer: face.layer,
uv: [a[0], a[1], du[0], du[1], dv[0], dv[1]],
shade_bits: shade(face).to_bits(),
});
}
Some(styles.map(|v| v.unwrap()))
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_assets::{
bake::{BlockModelTransform, bake_model_transformed},
model::CuboidModel,
resolve::ModelLibrary,
};
use serde_json::json;
#[test]
fn projected_cube_uvs_match_baked_quarter_turns() {
let faces: serde_json::Map<String, serde_json::Value> = Direction::ALL
.into_iter()
.map(|d| {
(
d.name().to_owned(),
json!({"texture":"#all","cullface":d.name()}),
)
})
.collect();
let model = CuboidModel::from_json(&json!({"textures":{"all":"horizon:probe"},"elements":[{"from":[0,0,0],"to":[16,16,16],"faces":faces}]}).to_string()).unwrap();
let library = ModelLibrary::new([("horizon:cube".to_owned(), model)].into()).unwrap();
let model = library.resolve("horizon:cube").unwrap();
let mut eligible = 0;
for x in 0..4 {
for y in 0..4 {
for z in 0..4 {
for lock in [false, true] {
let faces: Vec<_> = bake_model_transformed(
&model,
BlockModelTransform::new([x, y, z], lock),
)
.unwrap()
.into_iter()
.map(|quad| BakedFace {
quad,
layer: 7,
opaque: true,
})
.collect();
let Some(styles) = cube_styles(&faces) else {
assert!(lock);
continue;
};
eligible += 1;
for face in &faces {
let direction = face.quad.cull.unwrap();
let (u, v) = match direction {
Direction::Down | Direction::Up => (0, 2),
Direction::North | Direction::South => (0, 1),
_ => (2, 1),
};
let style = styles[direction as usize];
let [a, b, c, d, e, f] = style.uv.map(f32::from);
for (p, uv) in face.quad.positions.iter().zip(face.quad.uv) {
assert_eq!([a + c * p[u] + e * p[v], b + d * p[u] + f * p[v]], uv);
}
}
}
}
}
}
assert!(eligible >= 64);
let mut faces: Vec<_> =
bake_model_transformed(&model, BlockModelTransform::new([0; 3], false))
.unwrap()
.into_iter()
.map(|quad| BakedFace {
quad,
layer: 0,
opaque: true,
})
.collect();
faces[0].opaque = false;
assert!(cube_styles(&faces).is_none());
faces[0].opaque = true;
faces[0].quad.positions[0][0] = 0.25;
assert!(cube_styles(&faces).is_none());
}
}