Merge pull request #51 from ludovic111/review-cosmic

Cosmic's camera, breaking, clouds and outline fixes (#42 + #47), integrated
This commit is contained in:
Ludovic Marie
2026-10-13 23:14:30 +02:00
committed by GitHub
20 changed files with 1353 additions and 270 deletions
@@ -0,0 +1,61 @@
//! Transport for ClientLevel shape-aware terrain-particle placement.
use horizon_client::{assets::Assets, blocks::BlockFacts, mesher::MeshTables, models, particles};
use horizon_core::random::{LegacyRandom, RandomSource};
use horizon_world::registry::BlockStateId;
use serde_json::{Value, json};
use std::{
fs,
io::{BufRead, BufReader, BufWriter, Write},
path::Path,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
let root = Path::new(&args[1]);
let assets = Assets::load(root)?;
let facts = BlockFacts::load(root, assets.registry)?;
let tables = MeshTables::new(
&assets,
&facts,
models::load_visibility(root, assets.registry)?,
)?;
let mut output = BufWriter::new(fs::File::create(&args[3])?);
for line in BufReader::new(fs::File::open(&args[2])?).lines() {
let row: Value = serde_json::from_str(&line?)?;
let state = BlockStateId(row["state"].as_u64().unwrap() as u32);
let pos: [i32; 3] = serde_json::from_value(row["pos"].clone())?;
let offset = if facts.get(state).outline_offset {
tables.offset(state, pos[0], pos[2]).unwrap_or([0.0; 3])
} else {
[0.0; 3]
};
let boxes: Vec<[f64; 6]> = facts
.get(state)
.outline
.iter()
.map(|b| std::array::from_fn(|i| b[i] + offset[i % 3]))
.collect();
let mut hits = Vec::new();
let mut next = Vec::new();
for face in [
[0, -1, 0],
[0, 1, 0],
[0, 0, -1],
[0, 0, 1],
[-1, 0, 0],
[1, 0, 0],
] {
let mut random = LegacyRandom::new(row["seed"].as_i64().unwrap());
hits.push(particles::breaking_position(&mut random, pos, face, &boxes));
next.push(random.next_long());
}
let mut destroy = Vec::new();
particles::destroy_positions(pos, &boxes, |p, _| destroy.push(p));
serde_json::to_writer(
&mut output,
&json!({"case":row["case"],"hits":hits,"next":next,"destroy":destroy}),
)?;
output.write_all(&[10])?;
}
output.flush()?;
Ok(())
}
@@ -0,0 +1,74 @@
//! Headless transport for real model-shaped breaking overlays.
use horizon_client::{
assets::Assets,
blocks::{BlockFacts, RenderShape},
breaking,
mesher::MeshTables,
models,
};
use horizon_core::position::BlockPos;
use horizon_world::registry::BlockStateId;
use serde_json::{Value, json};
use std::{
fs,
io::{BufRead, BufReader, BufWriter, Write},
path::Path,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
let root = Path::new(&args[1]);
let assets = Assets::load(root)?;
let facts = BlockFacts::load(root, assets.registry)?;
let tables = MeshTables::new(
&assets,
&facts,
models::load_visibility(root, assets.registry)?,
)?;
let mut output = BufWriter::new(fs::File::create(&args[3])?);
for line in BufReader::new(fs::File::open(&args[2])?).lines() {
let row: Value = serde_json::from_str(&line?)?;
let state = BlockStateId(row["state"].as_u64().unwrap() as u32);
let p: [i32; 3] = serde_json::from_value(row["pos"].clone())?;
let camera: [f64; 3] = serde_json::from_value(row["camera"].clone())?;
let mut vertices = Vec::new();
let mut translucent = false;
if facts.get(state).render_shape == RenderShape::Model {
let models = assets
.model_catalog
.collect(state, BlockPos::new(p[0], p[1], p[2]))?;
let offset = tables.offset(state, p[0], p[2]).unwrap_or([0.0; 3]);
let origin = (glam::DVec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2]))
- glam::DVec3::from(camera))
.as_vec3()
+ glam::DVec3::from(offset).as_vec3();
translucent = models
.iter()
.any(|(_, m)| m.faces.iter().any(|f| f.translucent));
for (_, m) in models {
breaking::geometry(m, origin, translucent, &mut vertices);
}
}
let quads: Vec<_> = vertices
.as_chunks::<4>()
.0
.iter()
.map(|q| {
q.iter()
.map(|v| {
assert_eq!(v.color, 0xffff_ffff);
assert_eq!(v.light, 240 | (240 << 8));
assert_eq!(v.layer, if translucent { 12 } else { 11 });
[v.pos[0], v.pos[1], v.pos[2], v.uv[0], v.uv[1]]
})
.collect::<Vec<_>>()
})
.collect();
serde_json::to_writer(
&mut output,
&json!({"case":row["case"],"translucent":translucent,"quads":quads}),
)?;
output.write_all(&[10])?;
}
output.flush()?;
Ok(())
}
@@ -0,0 +1,34 @@
//! CloudRenderer face selection and mesh traversal, without a GPU.
use horizon_client::clouds;
use std::{fmt::Write, fs};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
let mut output = String::new();
for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() {
let values: Vec<i32> = line
.split_whitespace()
.map(|v| v.parse().unwrap())
.collect();
let [kind, x, z, bottom, neighbors] = values.as_slice() else {
panic!("invalid case")
};
write!(output, "{case}")?;
let mut cell = |x, z, neighbors| {
let empty = std::array::from_fn(|i| neighbors & (1 << i) != 0);
for (direction, inside) in clouds::faces(clouds::face_mask(x, z, *bottom as f32, empty))
{
write!(output, " {x},{z},{direction},{}", u8::from(inside)).unwrap();
}
};
if *kind == 0 {
cell(*x, *z, *neighbors);
} else {
for (x, z) in clouds::cells(*x) {
cell(x, z, 0);
}
}
output.push('\n');
}
fs::write(&args[2], output)?;
Ok(())
}
+12 -8
View File
@@ -54,6 +54,8 @@ pub struct StateFacts {
pub waterlogged: bool,
/// `hasOffsetFunction`: the model is jittered per column.
pub random_offset: bool,
/// Whether the outline, not just the model, follows BlockState.getOffset.
pub outline_offset: bool,
/// `BlockState.isSolid()` (legacy solidity; fluid surfaces read it).
pub legacy_solid: bool,
/// `isFaceSturdy(.., SupportType.FULL)` by Direction ordinal.
@@ -62,8 +64,8 @@ pub struct StateFacts {
pub classes: Arc<[Arc<str>]>,
/// `getShape` (the outline used for picking) as boxes in block space,
/// without the random offset; and its edges as LevelRenderer draws them.
pub outline: Arc<[[f32; 6]]>,
pub outline_edges: Arc<[[f32; 6]]>,
pub outline: Arc<[[f64; 6]]>,
pub outline_edges: Arc<[[f64; 6]]>,
/// `getMapColor(..).id` (0 = NONE).
pub map_color: u8,
}
@@ -78,11 +80,11 @@ pub const MAP_COLORS: [u32; 62] = [
14200723, 8365974,
];
/// The 12 edges of the unit cube (outline data predating the export).
fn cube_edges() -> Vec<[f32; 6]> {
fn cube_edges() -> Vec<[f64; 6]> {
let mut edges = Vec::new();
for a in 0..3 {
for (u, v) in [(0., 0.), (1., 0.), (0., 1.), (1., 1.)] {
let mut from = [0.0f32; 3];
let mut from = [0.0f64; 3];
let (b, c) = ((a + 1) % 3, (a + 2) % 3);
from[b] = u;
from[c] = v;
@@ -147,8 +149,8 @@ impl BlockFacts {
.or_insert_with(|| Arc::from(s))
.clone()
};
let mut shapes: HashMap<String, Arc<[[f32; 6]]>> = HashMap::new();
let mut shape = |v: &Value, fallback: &dyn Fn() -> Vec<[f32; 6]>| -> Arc<[[f32; 6]]> {
let mut shapes: HashMap<String, Arc<[[f64; 6]]>> = HashMap::new();
let mut shape = |v: &Value, fallback: &dyn Fn() -> Vec<[f64; 6]>| -> Arc<[[f64; 6]]> {
let Some(list) = v.as_array() else {
return fallback().into();
};
@@ -158,8 +160,7 @@ impl BlockFacts {
list.iter()
.filter_map(|b| {
let b = b.as_array()?;
let n =
|i: usize| b.get(i).and_then(Value::as_f64).unwrap_or(0.0) as f32;
let n = |i: usize| b.get(i).and_then(Value::as_f64).unwrap_or(0.0);
Some([n(0), n(1), n(2), n(3), n(4), n(5)])
})
.collect()
@@ -263,6 +264,9 @@ impl BlockFacts {
fluid_falling,
waterlogged: prop("waterlogged") == Some("true"),
random_offset: flag("offset"),
outline_offset: entry["outline_offset"]
.as_bool()
.unwrap_or_else(|| flag("offset")),
legacy_solid: behaviour_states[index][1].as_u64().unwrap_or(0) & 1 != 0,
sturdy_full: (behaviour_states[index][0].as_u64().unwrap_or(0) & 63) as u8,
classes: classes
+108
View File
@@ -0,0 +1,108 @@
//! BlockModelFeatureRenderer breaking quads and SheetedDecalTextureGenerator UVs.
use crate::{camera::joml, mesher::Vertex, models::catalog::BakedModel};
use horizon_assets::model::Direction;
use std::f32::consts::{FRAC_PI_2, PI};
/// Project in model space: the inverse decal pose cancels the block translation/offset.
pub fn decal_uv([x, y, z]: [f32; 3], direction: Direction) -> [f32; 2] {
let sy = joml::sin(PI);
let cy = joml::cos_from_sin(sy, PI);
let sx = joml::sin(-FRAC_PI_2);
let cx = joml::cos_from_sin(sx, -FRAC_PI_2);
let p = [cy * x + sy * z, y, -sy * x + cy * z];
let p = [p[0], cx * p[1] - sx * p[2], sx * p[1] + cx * p[2]];
let (angle_x, angle_z) = match direction {
Direction::Down => (PI, 0.0),
Direction::Up => (0.0, 0.0),
Direction::North => (FRAC_PI_2, PI),
Direction::South => (FRAC_PI_2, 0.0),
Direction::West => (FRAC_PI_2, FRAC_PI_2),
Direction::East => (FRAC_PI_2, -FRAC_PI_2),
};
let p = joml::Quat::rotation_yxz(0.0, angle_x, angle_z).transform(p);
[-p[0], -p[1]]
}
pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: &mut Vec<Vertex>) {
// Vanilla visits all six cull groups and then the unculled faces, even beside solid neighbours.
for cull in Direction::ALL.map(Some).into_iter().chain([None]) {
for face in model.faces.iter().filter(|face| face.quad.cull == cull) {
for pos in face.quad.positions {
out.push(Vertex {
pos: (origin + glam::Vec3::from(pos)).to_array(),
uv: decal_uv(pos, face.quad.facing),
layer: if translucent { 12 } else { 11 },
color: 0xffff_ffff,
light: 240 | (240 << 8),
});
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::catalog::BakedFace;
use horizon_assets::{bake::ModelQuad, model::Material};
fn slab_top() -> BakedModel {
BakedModel {
ambient_occlusion: true,
cube: None,
faces: vec![BakedFace {
layer: 0,
opaque: true,
translucent: false,
quad: ModelQuad {
positions: [
[0.0, 0.5, 0.0],
[0.0, 0.5, 1.0],
[1.0, 0.5, 1.0],
[1.0, 0.5, 0.0],
],
uv: [[0.0; 2]; 4],
facing: Direction::Up,
cull: None,
material: Material {
sprite: "block/stone".into(),
force_translucent: false,
},
tint_index: -1,
shade_direction_override: None,
light_emission: 0,
},
}],
}
}
#[test]
fn slab_overlay_follows_baked_top_not_unit_cube() {
let model = slab_top();
let mut vertices = Vec::new();
geometry(&model, glam::Vec3::new(2.0, 3.0, 4.0), false, &mut vertices);
assert_eq!(vertices.len(), 4);
for (v, p) in vertices.iter().zip(model.faces[0].quad.positions) {
assert_eq!(v.pos, [p[0] + 2.0, p[1] + 3.0, p[2] + 4.0]);
assert_eq!(v.color, 0xffff_ffff);
}
}
#[test]
fn small_faces_use_projected_not_stretched_uvs() {
let a = decal_uv([0.0, 0.0, 0.0], Direction::North);
let b = decal_uv([0.0, 0.5, 0.0], Direction::North);
assert!(((b[1] - a[1]).abs() - 0.5).abs() < 1e-6);
}
#[test]
fn translucent_overlay_has_its_own_pass() {
let mut vertices = Vec::new();
geometry(&slab_top(), glam::Vec3::ZERO, true, &mut vertices);
assert!(vertices.iter().all(|v| v.layer == 12));
}
#[test]
fn empty_model_has_no_cube_overlay() {
let mut model = slab_top();
model.faces.clear();
let mut vertices = Vec::new();
geometry(&model, glam::Vec3::ZERO, false, &mut vertices);
assert!(vertices.is_empty());
}
}
+28
View File
@@ -288,6 +288,13 @@ pub mod joml {
}
use joml::{Mat4, Quat};
/// Camera-relative world view used by terrain, sky and the first-person hand.
pub fn view_matrix(yaw: f32, pitch: f32) -> glam::Mat4 {
// Vanilla uses the conjugate of Camera.rotation, not a world-up look-at.
let q = Quat::rotation_yxz(PI - yaw * DEG_TO_RAD, -pitch * DEG_TO_RAD, 0.0);
glam::Mat4::from_quat(glam::Quat::from_xyzw(-q.x, -q.y, -q.z, q.w))
}
/// `CameraType`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CameraType {
@@ -763,6 +770,27 @@ pub fn bob_matrix(state: &BobState, damage_tilt_strength: f64, bob_view_option:
mod tests {
use super::*;
#[test]
fn view_keeps_yaw_at_vertical_pitch_limits() {
for yaw in [0.0, 45.0, 90.0, 180.0, -90.0, 360.0] {
for pitch in [-90.0, -89.999, 0.0, 89.999, 90.0] {
let view = view_matrix(yaw, pitch);
let mut camera = Camera::default();
camera.set_rotation(yaw, pitch);
for (world, expected) in [
(camera.forwards, -glam::Vec3::Z),
(camera.up, glam::Vec3::Y),
(camera.left, -glam::Vec3::X),
] {
let got = view.transform_vector3(glam::Vec3::from(world));
assert!(
(got - expected).length() < 1e-5,
"yaw={yaw}, pitch={pitch}: {got:?} != {expected:?}"
);
}
}
}
}
#[test]
fn camera_eases_eye_height_and_fov() {
let mut camera = Camera::default();
camera.tick(Some(1.62), 1.0);
+81
View File
@@ -0,0 +1,81 @@
//! Fancy cloud face selection (`CloudRenderer.buildExtrudedCell`).
/// Direction order is DOWN, UP, NORTH, SOUTH, WEST, EAST; inward faces use bits 6..12.
pub fn face_mask(x: i32, z: i32, bottom: f32, empty: [bool; 4]) -> u16 {
let mut mask = 0;
if bottom <= 0.0 {
mask |= 1 << 1;
}
if bottom + 4.0 >= 0.0 {
mask |= 1;
}
for (i, visible) in [z > 0, z < 0, x > 0, x < 0].into_iter().enumerate() {
if empty[i] && visible {
mask |= 1 << (i + 2);
}
}
if x.abs() <= 1 && z.abs() <= 1 {
mask |= 63 << 6;
}
mask
}
/// Exterior faces first, then reversed interior faces, in vanilla emission order.
pub fn faces(mask: u16) -> impl Iterator<Item = (u8, bool)> {
[1, 0, 2, 3, 4, 5]
.into_iter()
.filter(move |d| mask & (1 << d) != 0)
.map(|d| (d, false))
.chain(
(0..6)
.filter(move |d| mask & (1 << (d + 6)) != 0)
.map(|d| (d, true)),
)
}
/// CloudRenderer builds cells in expanding Manhattan rings, nearest first.
pub fn cells(radius: i32) -> impl Iterator<Item = (i32, i32)> {
(0..=2 * radius).flat_map(move |ring| {
(-ring..=ring).flat_map(move |x| {
let z = ring - x.abs();
let visible = z <= radius && x * x + z * z <= radius * radius;
(visible && z != 0)
.then_some((x, -z))
.into_iter()
.chain(visible.then_some((x, z)))
})
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cells_are_nearest_first_and_unique() {
let cells: Vec<_> = cells(2).collect();
assert_eq!(cells[0], (0, 0));
assert_eq!(cells.len(), 13);
assert!(
cells
.windows(2)
.all(|w| w[0].0.abs() + w[0].1.abs() <= w[1].0.abs() + w[1].1.abs())
);
assert_eq!(
cells.iter().collect::<std::collections::HashSet<_>>().len(),
cells.len()
);
}
#[test]
fn only_camera_facing_exterior_faces() {
assert_eq!(face_mask(2, 2, 10.0, [true; 4]), 1 | 4 | 16);
assert_eq!(face_mask(-2, -2, -5.0, [true; 4]), 2 | 8 | 32);
assert_eq!(face_mask(2, 2, 0.0, [false; 4]), 3);
}
#[test]
fn connected_cells_have_no_exterior_walls() {
assert_eq!(face_mask(2, 2, 10.0, [false; 4]), 1);
}
#[test]
fn nearby_cells_keep_inward_faces_for_camera_inside_clouds() {
assert_eq!(face_mask(0, 0, 0.0, [false; 4]), 3 | (63 << 6));
}
}
+8 -2
View File
@@ -15,6 +15,9 @@ struct Globals {
end_portal_sprites: array<vec4<f32>, 2>,
// x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000)
time: vec4<f32>,
crumbling_sprite: vec4<f32>,
// Selection outline parameters (read by terrain.wgsl).
outline_params: vec4<f32>,
}
@group(0) @binding(0) var<uniform> globals: Globals;
@group(0) @binding(1) var atlas: texture_2d<f32>;
@@ -43,8 +46,8 @@ struct Out {
let l = vec2(f32(light.y), f32(light.x));
let lm = textureSampleLevel(lightmap, lightmap_sampler,
clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0);
// overlay 2: celestial bodies, 4: clouds; both use their vertex colour unlit.
var c = select(color * lm, color, overlay == 2u || overlay == 4u || overlay == 6u);
// Celestial bodies, clouds, beacon beams and breaking cracks are unlit.
var c = select(color * lm, color, overlay == 2u || overlay == 4u || overlay == 6u || overlay == 11u || overlay == 12u);
// Overlay 6 (beacon beams): the light bytes carry the sprite's v range.
out.wrap = vec2(f32(light.x | (light.y << 8u)), f32(light.z | (light.w << 8u))) / 65535.0;
// Hurt overlay (OverlayTexture red tint).
@@ -102,6 +105,9 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
@fragment fn fs_entity(in: Out) -> @location(0) vec4<f32> {
var uv = in.uv;
if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; }
if in.overlay == 11u || in.overlay == 12u {
uv = globals.crumbling_sprite.xy + fract(in.uv) * globals.crumbling_sprite.zw;
}
var color = textureSample(atlas, atlas_sampler, uv) * in.color;
if in.overlay == 9u || in.overlay == 10u {
// rendertype_end_portal: end_sky and PORTAL_LAYERS (15 for portals, 16
+128 -161
View File
@@ -908,7 +908,7 @@ impl Game<'_> {
fn outline_boxes(&self, pos: [i32; 3]) -> Vec<[f64; 6]> {
let state = self.world.block(pos[0], pos[1], pos[2]);
let f = self.res.facts.get(state);
let o = if f.random_offset {
let o = if f.outline_offset {
self.res
.context
.tables
@@ -924,7 +924,7 @@ impl Game<'_> {
];
f.outline
.iter()
.map(|b| std::array::from_fn(|i| base[i % 3] + f64::from(b[i])))
.map(|b| std::array::from_fn(|i| base[i % 3] + b[i]))
.collect()
}
/// Voxel traversal against non-air, non-fluid blocks, clipped against
@@ -1102,51 +1102,47 @@ impl Game<'_> {
};
Some((name, tint))
}
/// ParticleEngine.destroy: a 4x4x4 burst.
fn particle_shape(&self, pos: [i32; 3], state: BlockStateId) -> Vec<[f64; 6]> {
let f = self.res.facts.get(state);
let offset = if f.outline_offset {
self.res
.context
.tables
.offset(state, pos[0], pos[2])
.unwrap_or([0.0; 3])
} else {
[0.0; 3]
};
f.outline
.iter()
.map(|b| std::array::from_fn(|i| b[i] + offset[i % 3]))
.collect()
}
/// ClientLevel.addDestroyBlockEffect: a burst per outline box.
fn destroy_particles(&mut self, pos: [i32; 3], state: BlockStateId) {
let Some((sprite, tint)) = self.particle_sprite(state) else {
return;
};
for x in 0..4 {
for y in 0..4 {
for z in 0..4 {
let d = |i: i32| (f64::from(i) + 0.5) / 4.0;
let p = [
f64::from(pos[0]) + d(x),
f64::from(pos[1]) + d(y),
f64::from(pos[2]) + d(z),
];
let v = [d(x) - 0.5, d(y) - 0.5, d(z) - 0.5];
// LevelEventHandler (2001) runs on the client: its random, not the level's.
let particle =
Particle::terrain(self.particles.random(), p, v, sprite.clone(), tint);
self.particles.push(particle);
}
}
}
let boxes = self.particle_shape(pos, state);
horizon_client::particles::destroy_positions(pos, &boxes, |p, v| {
let particle = Particle::terrain(self.particles.random(), p, v, sprite.clone(), tint);
self.particles.push(particle);
});
}
/// ParticleEngine.crack: one crumb on the face being mined.
/// ClientLevel.addBreakingParticles: one crumb on the face being mined.
fn crack_particle(&mut self, pos: [i32; 3], face: [i32; 3], state: BlockStateId) {
let Some((sprite, tint)) = self.particle_sprite(state) else {
return;
};
// Client-side particles draw from the client random, not the level's.
let boxes = self.particle_shape(pos, state);
// Keep client effects separate from the authoritative world RNG.
let r = self.particles.random();
let mut p = [0.0; 3];
for i in 0..3 {
let base = f64::from(pos[i]);
p[i] = match face[i] {
1 => base + 1.0 + 0.1,
-1 => base - 0.1,
_ => base + 0.1 + r.next_double() * 0.8,
};
}
let Some(p) = horizon_client::particles::breaking_position(r, pos, face, &boxes) else {
return;
};
let mut particle = Particle::terrain(r, p, [0.0; 3], sprite, tint);
for c in &mut particle.velocity {
*c *= 0.2;
}
particle.velocity[1] = (particle.velocity[1] - 0.1) * 0.2 + 0.1;
particle.size *= 0.6;
particle.set_power(0.2);
particle.scale(0.6);
self.particles.push(particle);
}
fn spawn_item(
@@ -4595,10 +4591,9 @@ impl Game<'_> {
&& m.progress > 0.0
{
let stage = ((m.progress * 10.0) as u32).min(9);
if let Some(r) = atlas
if atlas
.sprites
.get(&format!("block/destroy_stage_{stage}"))
.copied()
.contains_key(&format!("block/destroy_stage_{stage}"))
{
let o = (glam::DVec3::new(
f64::from(m.pos[0]),
@@ -4606,64 +4601,27 @@ impl Game<'_> {
f64::from(m.pos[2]),
) - camera)
.as_vec3();
let e = 0.002;
let corner = |x: f32, y: f32, z: f32| {
o + glam::Vec3::new(
x * (1.0 + 2.0 * e) - e,
y * (1.0 + 2.0 * e) - e,
z * (1.0 + 2.0 * e) - e,
)
};
let faces = [
[
corner(0., 1., 0.),
corner(1., 1., 0.),
corner(1., 1., 1.),
corner(0., 1., 1.),
],
[
corner(0., 0., 1.),
corner(1., 0., 1.),
corner(1., 0., 0.),
corner(0., 0., 0.),
],
[
corner(0., 0., 0.),
corner(1., 0., 0.),
corner(1., 1., 0.),
corner(0., 1., 0.),
],
[
corner(1., 0., 1.),
corner(0., 0., 1.),
corner(0., 1., 1.),
corner(1., 1., 1.),
],
[
corner(0., 0., 1.),
corner(0., 0., 0.),
corner(0., 1., 0.),
corner(0., 1., 1.),
],
[
corner(1., 0., 0.),
corner(1., 0., 1.),
corner(1., 1., 1.),
corner(1., 1., 0.),
],
];
for f in faces {
for (v, uv) in
f.iter()
.zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]])
{
out.push(Vertex {
pos: v.to_array(),
uv,
layer: 0,
color: 0xB4FF_FFFF,
light: (15 * 16) | ((15 * 16) << 8),
});
let state = self.world.block(m.pos[0], m.pos[1], m.pos[2]);
if self.res.facts.get(state).render_shape
== horizon_client::blocks::RenderShape::Model
&& let Ok(models) = self
.res
.assets
.model_catalog
.collect(state, BlockPos::new(m.pos[0], m.pos[1], m.pos[2]))
{
let offset = self
.res
.context
.tables
.offset(state, m.pos[0], m.pos[2])
.unwrap_or([0.0; 3]);
let origin = o + glam::DVec3::from(offset).as_vec3();
let translucent = models
.iter()
.any(|(_, model)| model.faces.iter().any(|f| f.translucent));
for (_, model) in models {
horizon_client::breaking::geometry(model, origin, translucent, &mut out);
}
}
}
@@ -5079,69 +5037,74 @@ impl Game<'_> {
let z_in = (cloud_z - cell_z as f64 * 12.0) as f32;
let bottom = (cloud_height - camera.y) as f32;
let filled = |cx: i64, cz: i64| cells[(cz.rem_euclid(h) * w + cx.rem_euclid(w)) as usize];
let radius = (self.streaming.radius * 16 / 12 + 1) as i64;
let radius = (self.streaming.radius * 16 + 11) / 12;
let c = sky.cloud_color;
let color = |shade: f32| {
let ch = |v: f32| ((v * shade).clamp(0.0, 1.0) * 255.0) as u32;
ch(c[3].clamp(0.0, 1.0)) << 24 | ch(c[2]) << 16 | ch(c[1]) << 8 | ch(c[0])
};
let light = 240 | 240 << 8;
for dz in -radius..=radius {
for dx in -radius..=radius {
if dx * dx + dz * dz > radius * radius {
continue;
for (dx, dz) in horizon_client::clouds::cells(radius) {
let (dx, dz) = (i64::from(dx), i64::from(dz));
let (cx, cz) = (cell_x + dx, cell_z + dz);
if !filled(cx, cz) {
continue;
}
let x0 = dx as f32 * 12.0 - x_in;
let z0 = dz as f32 * 12.0 - z_in;
let (x1, z1, y0, y1) = (x0 + 12.0, z0 + 12.0, bottom, bottom + 4.0);
let mut quad = |p: [[f32; 3]; 4], shade: f32| {
for v in p {
// Overlay 4: clouds (unlit, faded by the cloud fog end).
out.push(Vertex {
pos: v,
uv,
layer: 4,
color: color(shade),
light,
});
}
let (cx, cz) = (cell_x + dx, cell_z + dz);
if !filled(cx, cz) {
continue;
}
let x0 = dx as f32 * 12.0 - x_in;
let z0 = dz as f32 * 12.0 - z_in;
let (x1, z1, y0, y1) = (x0 + 12.0, z0 + 12.0, bottom, bottom + 4.0);
let mut quad = |p: [[f32; 3]; 4], shade: f32| {
for v in p {
// Overlay 4: clouds (unlit, faded by the cloud fog end).
out.push(Vertex {
pos: v,
uv,
layer: 4,
color: color(shade),
light,
});
}
};
quad(
[[x0, y1, z0], [x0, y1, z1], [x1, y1, z1], [x1, y1, z0]],
1.0,
);
quad(
};
let faces = [
(
[[x1, y0, z0], [x1, y0, z1], [x0, y0, z1], [x0, y0, z0]],
0.7,
);
if !filled(cx, cz - 1) {
quad(
[[x0, y0, z0], [x0, y1, z0], [x1, y1, z0], [x1, y0, z0]],
0.8,
);
}
if !filled(cx, cz + 1) {
quad(
[[x1, y0, z1], [x1, y1, z1], [x0, y1, z1], [x0, y0, z1]],
0.8,
);
}
if !filled(cx - 1, cz) {
quad(
[[x0, y0, z1], [x0, y1, z1], [x0, y1, z0], [x0, y0, z0]],
0.9,
);
}
if !filled(cx + 1, cz) {
quad(
[[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]],
0.9,
);
}
),
(
[[x0, y1, z0], [x0, y1, z1], [x1, y1, z1], [x1, y1, z0]],
1.0,
),
(
[[x0, y0, z0], [x0, y1, z0], [x1, y1, z0], [x1, y0, z0]],
0.8,
),
(
[[x1, y0, z1], [x1, y1, z1], [x0, y1, z1], [x0, y0, z1]],
0.8,
),
(
[[x0, y0, z1], [x0, y1, z1], [x0, y1, z0], [x0, y0, z0]],
0.9,
),
(
[[x1, y0, z0], [x1, y1, z0], [x1, y1, z1], [x1, y0, z1]],
0.9,
),
];
let mask = horizon_client::clouds::face_mask(
dx as i32,
dz as i32,
bottom,
[
!filled(cx, cz - 1),
!filled(cx, cz + 1),
!filled(cx - 1, cz),
!filled(cx + 1, cz),
],
);
for (direction, inside) in horizon_client::clouds::faces(mask) {
let (p, shade) = faces[usize::from(direction)];
quad(if inside { [p[3], p[2], p[1], p[0]] } else { p }, shade);
}
}
}
@@ -6490,13 +6453,7 @@ impl Game<'_> {
0.0
};
let inverse_height = 1.0 - self.heights.interpolated(a)[0];
let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians());
let forward = glam::Vec3::new(
-yaw.sin() * pitch.cos(),
-pitch.sin(),
yaw.cos() * pitch.cos(),
);
let view = glam::Mat4::look_to_rh(glam::Vec3::ZERO, forward, glam::Vec3::Y);
let view = horizon_client::camera::view_matrix(self.yaw, self.pitch);
let to_world = view.inverse();
let eye = self.eye_position().unwrap_or_default();
let light = self.world.light(
@@ -7259,7 +7216,7 @@ impl Game<'_> {
.map(|h| {
let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]);
let f = self.res.facts.get(state);
let o = if f.random_offset {
let o = if f.outline_offset {
self.res
.context
.tables
@@ -7271,7 +7228,7 @@ impl Game<'_> {
let p = h.pos.map(f64::from);
f.outline_edges
.iter()
.map(|e| std::array::from_fn(|i| p[i % 3] + o[i % 3] + f64::from(e[i])))
.map(|e| std::array::from_fn(|i| p[i % 3] + o[i % 3] + e[i]))
.collect()
})
.unwrap_or_default()
@@ -7415,6 +7372,16 @@ impl Game<'_> {
border,
game_time: self.world.game_time as f32,
shader_game_time: ((self.world.game_time % 24000) as f32 + alpha as f32) / 24000.0,
crumbling_sprite: self
.mining
.as_ref()
.and_then(|m| {
self.res.atlas.sprites.get(&format!(
"block/destroy_stage_{}",
((m.progress * 10.0) as u32).min(9)
))
})
.map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]),
end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| {
self.res
.atlas
@@ -8429,7 +8396,7 @@ pub fn run() -> Result<()> {
(
w,
h,
px.as_chunks::<4>().0.iter().map(|p| p[3] > 0).collect(),
px.as_chunks::<4>().0.iter().map(|p| p[3] >= 10).collect(),
)
})
.unwrap_or((1, 1, vec![false])),
+268 -94
View File
@@ -13,6 +13,66 @@ use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Instant};
use wgpu::util::DeviceExt;
use winit::window::Window;
// RenderPipelines.CRUMBLING: dst * src + src * dst, alpha replaced.
const CRUMBLING_BLEND: wgpu::BlendState = wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Dst,
dst_factor: wgpu::BlendFactor::Src,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::REPLACE,
};
// Separate special materials without changing entity order or their overlays.
fn batch_entities(
entities: &[Vertex],
additive: &[Vertex],
hand: &[Vertex],
) -> (Vec<Vertex>, [u32; 4]) {
let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len());
let mut counts = [0u32; 4];
for (i, layer) in [0, 11, 12, 4].into_iter().enumerate() {
for quad in entities.as_chunks::<4>().0 {
let material = match quad[0].layer {
11 => 11,
12 => 12,
4 => 4,
_ => 0,
};
if material == layer {
combined.extend_from_slice(quad);
counts[i] += 1;
}
}
}
combined.extend_from_slice(additive);
combined.extend_from_slice(hand);
(combined, counts)
}
/// Window.getAppropriateLineWidth, in framebuffer pixels.
pub fn outline_width(width: u32) -> f32 {
2.5f32.max(width as f32 / 1920.0 * 2.5)
}
/// ScreenSize, stroke width and ProjectionType.PERSPECTIVE layering.
pub fn outline_params(width: u32, height: u32) -> [f32; 4] {
[
width as f32,
height.max(1) as f32,
outline_width(width),
1.0 - 1.0 / 4096.0,
]
}
/// Camera-relative segment endpoints; no shape expansion in vanilla 26.3.
pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6]> {
edges
.iter()
.map(|e| std::array::from_fn(|i| (e[i] - camera.to_array()[i % 3]) as f32))
.collect()
}
mod arena;
mod occlusion;
mod timing;
@@ -35,6 +95,10 @@ struct Globals {
end_portal_sprites: [[f32; 4]; 2],
/// x: vanilla's `GameTime` uniform; yzw unused.
time: [f32; 4],
/// Atlas rect of the current destroy stage (entity.wgsl).
crumbling_sprite: [f32; 4],
/// Framebuffer size, selection stroke width, perspective layering scale.
outline_params: [f32; 4],
}
pub type SectionKey = (i32, i32, i32);
struct SectionGpu {
@@ -100,6 +164,8 @@ pub struct Frame<'a> {
/// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png
/// (`rendertype_end_portal`'s Sampler0 and Sampler1).
pub end_portal_sprites: [[f32; 4]; 2],
/// Current destroy-stage sprite: projected UVs repeat inside this atlas rect.
pub crumbling_sprite: [f32; 4],
pub ticks: u64,
/// The darkness effect on the lightmap: the brightness it takes off the
/// gamma option and the pulsing scale subtracted from the light.
@@ -153,6 +219,8 @@ pub struct Renderer {
dark_disc: wgpu::RenderPipeline,
lines: wgpu::RenderPipeline,
entity_pipeline: wgpu::RenderPipeline,
crumbling_pipeline: wgpu::RenderPipeline,
cloud_pipeline: wgpu::RenderPipeline,
additive_pipeline: wgpu::RenderPipeline,
celestial_pipeline: wgpu::RenderPipeline,
celestial_buffer: wgpu::Buffer,
@@ -453,10 +521,10 @@ impl Renderer {
attributes: &instance_attributes,
}),
];
let line_attributes = wgpu::vertex_attr_array![0=>Float32x3];
let line_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x3];
let line_buffers = [Some(wgpu::VertexBufferLayout {
array_stride: 12,
step_mode: wgpu::VertexStepMode::Vertex,
array_stride: 24,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &line_attributes,
})];
let alpha_blend = wgpu::BlendState::ALPHA_BLENDING;
@@ -559,7 +627,7 @@ impl Renderer {
"vs_line",
"fs_line",
&line_buffers,
wgpu::PrimitiveTopology::LineList,
wgpu::PrimitiveTopology::TriangleStrip,
None,
false,
true,
@@ -808,40 +876,62 @@ impl Renderer {
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &vertex_attributes,
})];
let entity_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Entities"),
layout: Some(&entity_layout),
vertex: wgpu::VertexState {
module: &entity_shader,
entry_point: Some("vs_entity"),
compilation_options: Default::default(),
buffers: &entity_vertex,
let entity_pipeline = |label, cull_mode, depth_write, bias, blend| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&entity_layout),
vertex: wgpu::VertexState {
module: &entity_shader,
entry_point: Some("vs_entity"),
compilation_options: Default::default(),
buffers: &entity_vertex,
},
primitive: wgpu::PrimitiveState {
cull_mode,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(depth_write),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: Default::default(),
bias,
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &entity_shader,
entry_point: Some("fs_entity"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: config.format.remove_srgb_suffix(),
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
};
let crumbling_pipeline = entity_pipeline(
"Breaking cracks",
Some(wgpu::Face::Back),
false,
wgpu::DepthBiasState {
constant: -10,
slope_scale: -1.0,
clamp: 0.0,
},
primitive: wgpu::PrimitiveState {
cull_mode: None,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &entity_shader,
entry_point: Some("fs_entity"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: config.format.remove_srgb_suffix(),
blend: Some(alpha_blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
CRUMBLING_BLEND,
);
let cloud_pipeline = entity_pipeline(
"Clouds",
Some(wgpu::Face::Back),
true,
Default::default(),
alpha_blend,
);
let entity_pipeline =
entity_pipeline("Entities", None, true, Default::default(), alpha_blend);
// BlendFunction.LIGHTNING: src alpha, one; no depth writes.
let additive_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Additive entities"),
@@ -1204,6 +1294,8 @@ impl Renderer {
dark_disc,
lines,
entity_pipeline,
crumbling_pipeline,
cloud_pipeline,
additive_pipeline,
celestial_pipeline,
celestial_buffer,
@@ -1538,17 +1630,10 @@ impl Renderer {
}
fn projection(&self, fov_degrees: f32, yaw: f32, pitch: f32, bob: Mat4, distance: f32) -> Mat4 {
let aspect = self.config.width as f32 / self.config.height.max(1) as f32;
let (yaw, pitch) = (yaw.to_radians(), pitch.to_radians());
// Minecraft yaw: 0 = +Z (south), 90 = -X (west); pitch positive looks down.
let forward = Vec3::new(
-yaw.sin() * pitch.cos(),
-pitch.sin(),
yaw.cos() * pitch.cos(),
);
let far = (distance * 4.0).max(1024.0);
Mat4::perspective_rh(fov_degrees.to_radians(), aspect, 0.05, far)
* bob
* Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y)
* crate::camera::view_matrix(yaw, pitch)
}
fn update_lightmap(
&self,
@@ -1694,13 +1779,7 @@ impl Renderer {
);
let view_proj = self.view_projection(frame);
let aspect = self.config.width as f32 / self.config.height.max(1) as f32;
let (yaw, pitch) = (frame.yaw.to_radians(), frame.pitch.to_radians());
let forward = Vec3::new(
-yaw.sin() * pitch.cos(),
-pitch.sin(),
yaw.cos() * pitch.cos(),
);
let view = Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y);
let view = crate::camera::view_matrix(frame.yaw, frame.pitch);
let sun_angle = frame.sky.sun_angle.to_radians();
// Celestial bodies rotate around the X axis; angle 0 = noon.
let sun = Vec3::new(0.0, sun_angle.cos(), -sun_angle.sin());
@@ -1766,7 +1845,9 @@ impl Renderer {
0.0,
],
end_portal_sprites: frame.end_portal_sprites,
crumbling_sprite: frame.crumbling_sprite,
time: [frame.shader_game_time, 0.0, 0.0, 0.0],
outline_params: outline_params(self.config.width, self.config.height),
};
self.queue
.write_buffer(&self.globals, 0, bytemuck::bytes_of(&globals));
@@ -1891,45 +1972,22 @@ impl Renderer {
}
let outline_edges = frame.outline.len().min(MAX_OUTLINE_EDGES as usize);
if outline_edges > 0 {
// A hair outside the block, like vanilla's line depth offset.
let lines: Vec<[f32; 3]> = frame.outline[..outline_edges]
.iter()
.flat_map(|e| {
let center = [
(e[0] + e[3]) / 2.0,
(e[1] + e[4]) / 2.0,
(e[2] + e[5]) / 2.0,
];
let point = |i: usize| -> [f32; 3] {
std::array::from_fn(|a| {
let v = e[i + a];
let grow = if v < center[a] {
-0.002
} else if v > center[a] {
0.002
} else {
0.0
};
(v - [camera.x, camera.y, camera.z][a]) as f32 + grow
})
};
[point(0), point(3)]
})
.collect();
let lines = outline_vertices(&frame.outline[..outline_edges], camera);
self.queue
.write_buffer(&self.outline, 0, bytemuck::cast_slice(&lines));
}
let mut combined;
let all_entities: &[Vertex] = if frame.hand.is_empty() && frame.additive.is_empty() {
frame.entities
} else {
combined =
Vec::with_capacity(frame.entities.len() + frame.additive.len() + frame.hand.len());
combined.extend_from_slice(frame.entities);
combined.extend_from_slice(frame.additive);
combined.extend_from_slice(frame.hand);
&combined
};
let (
combined,
[
entity_quads,
crumbling_quads,
translucent_crumbling_quads,
cloud_quads,
],
) = batch_entities(frame.entities, frame.additive, frame.hand);
let world_quads =
entity_quads + crumbling_quads + translucent_crumbling_quads + cloud_quads;
let all_entities = &combined;
let hand_quads = (frame.hand.len() / 4) as u32;
let additive_quads = (frame.additive.len() / 4) as u32;
let entity_vertices = all_entities.len() as u64;
@@ -1954,9 +2012,8 @@ impl Renderer {
bytemuck::cast_slice(&frame.celestial[..celestial_vertices]),
);
}
let entity_quads = (entity_vertices / 4) as u32 - hand_quads - additive_quads;
if entity_quads + additive_quads + hand_quads > self.index_quads {
self.index_quads = (entity_quads + additive_quads + hand_quads).next_power_of_two();
if world_quads + additive_quads + hand_quads > self.index_quads {
self.index_quads = (world_quads + additive_quads + hand_quads).next_power_of_two();
self.indices = Self::quad_indices(&self.device, self.index_quads);
}
if let Some(b) = &frame.border {
@@ -2069,17 +2126,24 @@ impl Renderer {
pass.draw_indexed(0..entity_quads * 6, 0, 0..1);
pass.set_bind_group(0, &self.group, &[]);
}
if crumbling_quads > 0 {
pass.set_pipeline(&self.crumbling_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(0..crumbling_quads * 6, (entity_quads * 4) as i32, 0..1);
pass.set_bind_group(0, &self.group, &[]);
}
if additive_quads > 0 {
pass.set_pipeline(&self.additive_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(0..additive_quads * 6, (entity_quads * 4) as i32, 0..1);
pass.draw_indexed(0..additive_quads * 6, (world_quads * 4) as i32, 0..1);
pass.set_bind_group(0, &self.group, &[]);
}
if outline_edges > 0 {
pass.set_pipeline(&self.lines);
pass.set_vertex_buffer(0, self.outline.slice(..));
pass.draw(0..outline_edges as u32 * 2, 0..1);
pass.draw(0..4, 0..outline_edges as u32);
}
pass.set_pipeline(&self.translucent);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
@@ -2097,6 +2161,26 @@ impl Renderer {
}
pass.set_bind_group(0, &self.group, &[]);
}
if translucent_crumbling_quads > 0 {
pass.set_pipeline(&self.crumbling_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(
0..translucent_crumbling_quads * 6,
((entity_quads + crumbling_quads) * 4) as i32,
0..1,
);
}
if cloud_quads > 0 {
pass.set_pipeline(&self.cloud_pipeline);
pass.set_bind_group(0, &self.entity_group, &[]);
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(
0..cloud_quads * 6,
((entity_quads + crumbling_quads + translucent_crumbling_quads) * 4) as i32,
0..1,
);
}
}
if scaled.is_some() {
self.world_post.finish(&mut encoder, &view_target);
@@ -2130,7 +2214,7 @@ impl Renderer {
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
pass.draw_indexed(
0..hand_quads * 6,
((entity_quads + additive_quads) * 4) as i32,
((world_quads + additive_quads) * 4) as i32,
0..1,
);
}
@@ -2355,3 +2439,93 @@ fn frustum(m: Mat4) -> [Vec4; 6] {
];
planes.map(|p| p / p.truncate().length())
}
#[cfg(test)]
mod tests {
#[test]
fn special_material_batches_preserve_quad_order_and_offsets() {
let quad = |layer, id| {
[super::Vertex {
pos: [0.0; 3],
uv: [0.0; 2],
layer,
color: 0xffff_ffff,
light: id,
}; 4]
};
let entities: Vec<_> = [(0, 0), (4, 1), (11, 2), (7, 3), (4, 4), (12, 7)]
.into_iter()
.flat_map(|(layer, id)| quad(layer, id))
.collect();
let (vertices, counts) = super::batch_entities(&entities, &quad(3, 5), &quad(0, 6));
assert_eq!(counts, [2, 1, 1, 2]);
assert_eq!(
vertices
.as_chunks::<4>()
.0
.iter()
.map(|q| q[0].light)
.collect::<Vec<_>>(),
[0, 3, 2, 7, 1, 4, 5, 6]
);
}
#[test]
fn cracks_multiply_instead_of_covering_the_block() {
let blend = super::CRUMBLING_BLEND;
assert_eq!(blend.color.src_factor, wgpu::BlendFactor::Dst);
assert_eq!(blend.color.dst_factor, wgpu::BlendFactor::Src);
assert_eq!(blend.alpha.src_factor, wgpu::BlendFactor::One);
assert_eq!(blend.alpha.dst_factor, wgpu::BlendFactor::Zero);
}
#[test]
fn shader_globals_match_the_rust_layout() {
// terrain.wgsl and entity.wgsl bind the same buffer: same fields, same order.
let fields = |source: &str| -> Vec<String> {
let body = source.split("struct Globals {").nth(1).unwrap();
body[..body.find('}').unwrap()]
.lines()
.filter_map(|l| l.trim().split_once(':').map(|(name, _)| name.to_string()))
.filter(|name| !name.starts_with("//"))
.collect()
};
let terrain = fields(include_str!("terrain.wgsl"));
assert_eq!(terrain, fields(include_str!("entity.wgsl")));
let rust = fields(include_str!("gfx.rs"));
assert_eq!(terrain, rust);
}
#[test]
fn selection_outline_uses_vanilla_pixel_width() {
for width in [640, 1280, 1920] {
assert_eq!(super::outline_width(width), 2.5);
}
assert_eq!(super::outline_width(2560), 2560.0 / 1920.0 * 2.5);
assert_eq!(super::outline_width(3840), 5.0);
}
#[test]
fn selection_outline_has_vanilla_perspective_layering() {
assert_eq!(
super::outline_params(1280, 720),
[1280.0, 720.0, 2.5, 0.99975586]
);
assert_eq!(
super::outline_params(3840, 0),
[3840.0, 1.0, 5.0, 0.99975586]
);
}
#[test]
fn selection_outline_preserves_shape_edges_without_inflation() {
let edges = [[2.0, 97.5, 3.0, 3.0, 97.5, 3.0]];
assert_eq!(
super::outline_vertices(&edges, glam::DVec3::new(0.5, 98.62, 0.5)),
vec![[
1.5,
(97.5 - 98.62) as f32,
2.5,
2.5,
(97.5 - 98.62) as f32,
2.5
]]
);
assert!(super::outline_vertices(&[], glam::DVec3::ZERO).is_empty());
}
}
+2
View File
@@ -19,12 +19,14 @@ pub mod block_transform;
pub mod blocks;
pub mod border_render;
pub mod bossbar;
pub mod breaking;
pub mod brewing;
pub mod camera;
pub mod cauldron;
pub mod chat;
pub mod chunk;
pub mod clock;
pub mod clouds;
pub mod collisions;
pub mod command;
pub mod command_storage;
+133
View File
@@ -414,6 +414,64 @@ fn aabb_at(p: [f64; 3], w: f32, h: f32) -> Aabb {
Vec3::new(p[0] + w, p[1] + f64::from(h), p[2] + w),
)
}
/// ClientLevel.addBreakingParticles placement, using local outline boxes.
pub fn breaking_position(
random: &mut impl RandomSource,
pos: [i32; 3],
face: [i32; 3],
boxes: &[[f64; 6]],
) -> Option<[f64; 3]> {
let mut bounds = *boxes.first()?;
for b in &boxes[1..] {
for i in 0..3 {
bounds[i] = bounds[i].min(b[i]);
bounds[i + 3] = bounds[i + 3].max(b[i + 3]);
}
}
// Vanilla consumes all three doubles before replacing the hit-face coordinate.
let mut p = std::array::from_fn(|i| {
f64::from(pos[i])
+ random.next_double() * (bounds[i + 3] - bounds[i] - f64::from(0.2f32))
+ f64::from(0.1f32)
+ bounds[i]
});
for i in 0..3 {
match face[i] {
-1 => p[i] = f64::from(pos[i]) + bounds[i] - f64::from(0.1f32),
1 => p[i] = f64::from(pos[i]) + bounds[i + 3] + f64::from(0.1f32),
_ => {}
}
}
Some(p)
}
/// ClientLevel.addDestroyBlockEffect placement and pre-constructor velocities.
pub fn destroy_positions(
pos: [i32; 3],
boxes: &[[f64; 6]],
mut emit: impl FnMut([f64; 3], [f64; 3]),
) {
for b in boxes {
let widths: [f64; 3] = std::array::from_fn(|i| (b[i + 3] - b[i]).min(1.0));
let counts: [usize; 3] = widths.map(|w| ((w / 0.25).ceil() as usize).max(2));
for x in 0..counts[0] {
for y in 0..counts[1] {
for z in 0..counts[2] {
let cells = [x, y, z];
let relative: [f64; 3] =
std::array::from_fn(|i| (cells[i] as f64 + 0.5) / counts[i] as f64);
emit(
std::array::from_fn(|i| {
f64::from(pos[i]) + (relative[i] * widths[i] + b[i])
}),
relative.map(|v| v - 0.5),
);
}
}
}
}
}
impl Particle {
/// `Particle(level, x, y, z)` + `SingleQuadParticle` (no initial velocity).
fn at(random: &mut LegacyRandom, ty: ParticleType, p: [f64; 3]) -> Self {
@@ -2830,6 +2888,81 @@ fn lifetime_alpha(a: [f32; 4], age: i32, lifetime: i32, partial: f32) -> f32 {
mod tests {
use super::*;
#[test]
fn mining_particles_follow_slab_and_trapdoor_height() {
for height in [0.5, 3.0 / 16.0] {
let boxes = [[0.0, 0.0, 0.0, 1.0, height, 1.0]];
let p = breaking_position(&mut LegacyRandom::new(1), [2, 97, 3], [0, 1, 0], &boxes)
.unwrap();
assert_eq!(p[1], 97.0 + height + f64::from(0.1f32));
for seed in 0..128 {
let p = breaking_position(&mut LegacyRandom::new(seed), [0; 3], [0, 0, -1], &boxes)
.unwrap();
assert!(p[1] <= height, "crumb above shape: {p:?}");
}
}
}
#[test]
fn destroyed_slab_uses_its_shape_and_particle_density() {
let mut burst = Vec::new();
destroy_positions([0; 3], &[[0.0, 0.0, 0.0, 1.0, 0.5, 1.0]], |p, v| {
burst.push((p, v))
});
assert_eq!(burst.len(), 32);
assert!(burst.iter().all(|(p, _)| p[1] < 0.5));
assert_eq!(burst[0], ([0.125, 0.125, 0.125], [-0.375, -0.25, -0.375]));
}
#[test]
fn empty_outline_emits_no_terrain_particles_or_random_draws() {
let mut r = LegacyRandom::new(1);
assert_eq!(breaking_position(&mut r, [0; 3], [0, 1, 0], &[]), None);
assert_eq!(r.next_long(), LegacyRandom::new(1).next_long());
destroy_positions([0; 3], &[], |_, _| panic!("empty shape emitted a particle"));
}
#[test]
fn every_hit_face_consumes_three_position_draws() {
let boxes = [[0.25, 0.0, 0.25, 0.75, 0.5, 0.75]];
for face in [
[-1, 0, 0],
[1, 0, 0],
[0, -1, 0],
[0, 1, 0],
[0, 0, -1],
[0, 0, 1],
] {
let mut random = LegacyRandom::new(42);
let p = breaking_position(&mut random, [0; 3], face, &boxes).unwrap();
let i = face.iter().position(|v| *v != 0).unwrap();
let expected = if face[i] < 0 {
boxes[0][i] - f64::from(0.1f32)
} else {
boxes[0][i + 3] + f64::from(0.1f32)
};
assert_eq!(p[i], expected);
let mut reference = LegacyRandom::new(42);
for _ in 0..3 {
reference.next_double();
}
assert_eq!(random.next_long(), reference.next_long());
}
}
#[test]
fn multipart_destroy_burst_uses_each_box_and_caps_widths() {
let boxes = [
[0.0, 0.0, 0.0, 1.0, 0.5, 1.0],
[0.0, 0.5, 0.5, 1.0, 1.0, 1.0],
];
let mut burst = Vec::new();
destroy_positions([0; 3], &boxes, |p, v| burst.push((p, v)));
assert_eq!(burst.len(), 48);
assert_eq!(burst[32].0, [0.125, 0.625, 0.625]);
let mut tall = Vec::new();
destroy_positions([0; 3], &[[0.0, 0.0, 0.0, 1.0, 1.5, 1.0]], |p, _| {
tall.push(p)
});
assert_eq!(tall.len(), 64);
assert!(tall.iter().all(|p| p[1] < 1.0));
}
#[test]
fn particle_names_round_trip() {
for &ty in ParticleType::ALL {
assert_eq!(
+33 -4
View File
@@ -18,6 +18,9 @@ struct Globals {
end_portal_sprites: array<vec4<f32>, 2>,
// x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000)
time: vec4<f32>,
// Atlas rect of the current destroy stage (read by entity.wgsl).
crumbling_sprite: vec4<f32>,
outline_params: vec4<f32>,
}
@group(0) @binding(0) var<uniform> globals: Globals;
@group(0) @binding(1) var sprites: texture_2d_array<f32>;
@@ -173,10 +176,36 @@ fn sunrise_weight(d: vec3<f32>) -> f32 {
return vec4(sky_fog(vec3(0.0), dist), 1.0);
}
struct LineOut { @builtin(position) clip: vec4<f32> }
@vertex fn vs_line(@location(0) position: vec3<f32>) -> LineOut {
// rendertype_lines.vsh: screen-space stroke and camera-space depth separation.
fn outline_clip(vertex: u32, start: vec3<f32>, end: vec3<f32>) -> vec4<f32> {
let position = select(start, end, vertex >= 2u);
let normal = normalize(end - start);
let view_shrink = 1.0 - 1.0 / 256.0;
let line_start = globals.view_proj * vec4((position * globals.outline_params.w) * view_shrink, 1.0);
let line_end = globals.view_proj * vec4(((position + normal) * globals.outline_params.w) * view_shrink, 1.0);
let ndc1 = line_start.xyz / line_start.w;
let ndc2 = line_end.xyz / line_end.w;
let screen = globals.outline_params.xy;
let direction = normalize((ndc2.xy - ndc1.xy) * screen);
var offset = vec2(-direction.y, direction.x) * globals.outline_params.z / screen;
if offset.x < 0.0 { offset = -offset; }
if vertex % 2u != 0u { offset = -offset; }
return vec4((ndc1 + vec3(offset, 0.0)) * line_start.w, line_start.w);
}
struct LineOut {
@builtin(position) clip: vec4<f32>,
@location(0) spherical: f32,
@location(1) cylindrical: f32,
}
@vertex fn vs_line(@builtin(vertex_index) vertex: u32,
@location(0) start: vec3<f32>, @location(1) end: vec3<f32>) -> LineOut {
let position = select(start, end, vertex >= 2u);
var out: LineOut;
out.clip = globals.view_proj * vec4(position, 1.0);
out.clip = outline_clip(vertex, start, end);
out.spherical = length(position);
out.cylindrical = max(length(position.xz), abs(position.y));
return out;
}
@fragment fn fs_line() -> @location(0) vec4<f32> { return vec4(0.0, 0.0, 0.0, 0.4); }
@fragment fn fs_line(in: LineOut) -> @location(0) vec4<f32> {
return apply_fog(vec4(0.0, 0.0, 0.0, 0.4), in.spherical, in.cylindrical);
}
@@ -0,0 +1,85 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.blaze3d.platform.NativeImage;
import java.lang.reflect.*;
import java.nio.file.*;
import java.util.*;
import net.minecraft.SharedConstants;
import net.minecraft.client.Minecraft;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.particle.*;
import net.minecraft.client.renderer.block.BlockStateModelSet;
import net.minecraft.client.renderer.texture.*;
import net.minecraft.client.resources.metadata.animation.FrameSize;
import net.minecraft.client.resources.model.ModelManager;
import net.minecraft.client.resources.model.sprite.Material;
import net.minecraft.core.*;
import net.minecraft.resources.Identifier;
import net.minecraft.server.Bootstrap;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.state.BlockState;
/** Calls the real client mining and destruction methods; records positions at enqueue.
* Sprite/tint lookup is stubbed. Particle-local RNG and velocities are not compared. */
public final class VanillaBlockParticlesOracle {
private static final Gson JSON = new Gson();
private static Object unsafe;
private static Method allocate;
private static Field field(Class<?> type, String name) throws Exception {
var f=type.getDeclaredField(name);f.setAccessible(true);return f;
}
private static <T> T make(Class<T> type) throws Exception { return type.cast(allocate.invoke(unsafe,type)); }
private static final class Level0 extends ClientLevel {
BlockPos pos;BlockState state;
Level0() { super(null,null,null,null,0,0,null,false,0L,0); }
@Override public BlockState getBlockState(BlockPos p) { return p.equals(pos)?state:Blocks.AIR.defaultBlockState(); }
}
private static final class Sprite extends TextureAtlasSprite {
Sprite() { super(TextureAtlas.LOCATION_BLOCKS,new SpriteContents(Identifier.parse("minecraft:missingno"),new FrameSize(16,16),new NativeImage(16,16,true)),16,16,0,0,0); }
}
private static final class Models extends BlockStateModelSet {
private final Material.Baked material=new Material.Baked(new Sprite(),false);
Models() { super(Map.of(),null); }
@Override public Material.Baked getParticleMaterial(BlockState state) { return material; }
}
private static final class Recorder extends ParticleEngine {
final List<double[]> positions=new ArrayList<>();
final Field[] xyz;
Recorder(ClientLevel level) throws Exception {
super(level,null);xyz=new Field[]{field(Particle.class,"x"),field(Particle.class,"y"),field(Particle.class,"z")};
}
@Override public void add(Particle p) {
try { positions.add(new double[]{xyz[0].getDouble(p),xyz[1].getDouble(p),xyz[2].getDouble(p)}); }
catch (Exception e) { throw new RuntimeException(e); }
}
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();Bootstrap.bootStrap();
var u=Class.forName("sun.misc.Unsafe");unsafe=field(u,"theUnsafe").get(null);allocate=u.getMethod("allocateInstance",Class.class);
var mc=make(Minecraft.class);field(Minecraft.class,"instance").set(null,mc);
var manager=make(ModelManager.class);field(ModelManager.class,"blockStateModelSet").set(manager,new Models());
field(Minecraft.class,"modelManager").set(mc,manager);field(Minecraft.class,"blockColors").set(mc,new BlockColors());
var level=make(Level0.class);field(ClientLevel.class,"minecraft").set(level,mc);
var recorder=new Recorder(level);field(Minecraft.class,"particleEngine").set(mc,recorder);
var crack=ClientLevel.class.getDeclaredMethod("addBreakingParticles",BlockPos.class,Direction.class,BlockState.class);crack.setAccessible(true);
try (var output=Files.newBufferedWriter(Path.of(args[1]))) {
for (String line:Files.readAllLines(Path.of(args[0]))) {
var row=JsonParser.parseString(line).getAsJsonObject();var p=row.getAsJsonArray("pos");
level.pos=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt());level.state=Block.stateById(row.get("state").getAsInt());
var hits=new ArrayList<Object>();var next=new ArrayList<Long>();
for (var face:Direction.values()) {
var random=RandomSource.create(row.get("seed").getAsLong());field(Level.class,"random").set(level,random);recorder.positions.clear();
if (!level.state.getShape(level,level.pos).isEmpty()) crack.invoke(level,level.pos,face,level.state);
hits.add(recorder.positions.isEmpty()?null:recorder.positions.getFirst());next.add(random.nextLong());
if (recorder.positions.size()>1) throw new AssertionError("multiple mining particles");
}
recorder.positions.clear();level.addDestroyBlockEffect(level.pos,level.state);
output.write(JSON.toJson(Map.of("case",row.get("case").getAsInt(),"hits",hits,"next",next,"destroy",recorder.positions)));output.newLine();
}
}
}
}
@@ -0,0 +1,89 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.vertex.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import net.minecraft.SharedConstants;
import net.minecraft.client.resources.metadata.animation.FrameSize;
import net.minecraft.client.renderer.block.dispatch.*;
import net.minecraft.client.renderer.feature.BlockModelFeatureRenderer;
import net.minecraft.client.renderer.texture.*;
import net.minecraft.client.renderer.texture.atlas.*;
import net.minecraft.client.resources.model.sprite.MaterialBaker;
import net.minecraft.core.BlockPos;
import net.minecraft.resources.Identifier;
import net.minecraft.server.Bootstrap;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.RenderShape;
/** Real model selection, offset, BlockModelFeatureRenderer and sheeted decal projection. */
public final class VanillaBreakingModelOracle {
private static final Gson JSON=new Gson();
private static final class Recorder implements VertexConsumer {
final List<List<float[]>> quads=new ArrayList<>();
final List<float[]> pending=new ArrayList<>();
float[] vertex;
public VertexConsumer addVertex(float x,float y,float z) { vertex=new float[]{x,y,z,0,0};return this; }
public VertexConsumer setColor(int color) {
if (color!=-1) throw new AssertionError("decal is tinted");return this;
}
public VertexConsumer setColor(int r,int g,int b,int a) {
if (r!=255||g!=255||b!=255||a!=255) throw new AssertionError("decal is tinted");return this;
}
public VertexConsumer setUv(float u,float v) {
vertex[3]=u;vertex[4]=v;pending.add(vertex);
if (pending.size()==4) { quads.add(new ArrayList<>(pending));pending.clear(); }return this;
}
public VertexConsumer setUv3(float u,float v) { return this; }
public VertexConsumer setUv1(int u,int v) { return this; }
public VertexConsumer setUv2(int u,int v) {
if (u!=240||v!=240) throw new AssertionError("decal is not full bright");return this;
}
public VertexConsumer setNormal(float x,float y,float z) { return this; }
public VertexConsumer setLineWidth(float width) { return this; }
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();Bootstrap.bootStrap();
var rows=new ArrayList<JsonObject>();var blocks=new HashSet<Block>();
for (String line:Files.readAllLines(Path.of(args[0]))) {
var row=JsonParser.parseString(line).getAsJsonObject();rows.add(row);
blocks.add(Block.stateById(row.get("state").getAsInt()).getBlock());
}
// Reuse the existing oracle model baker rather than duplicating it.
String helper=VanillaSectionMeshOracle.class.getName();
var missingContents=new SpriteContents(Identifier.parse("minecraft:missingno"),new FrameSize(16,16),new NativeImage(16,16,true));
var spriteCtor=Class.forName(helper+"$Sprite").getDeclaredConstructor(SpriteContents.class,int.class,int.class);spriteCtor.setAccessible(true);
var missing=(TextureAtlasSprite)spriteCtor.newInstance(missingContents,1,0);
var atlas=new SpriteLoader.Preparations(16,16,0,missing,Map.of(),CompletableFuture.completedFuture(null));
var materialsCtor=Class.forName(helper+"$Materials").getDeclaredConstructor(SpriteLoader.Preparations.class);materialsCtor.setAccessible(true);
var materials=(MaterialBaker)materialsCtor.newInstance(atlas);
var modelsClass=Class.forName(helper+"$Models");
var modelsCtor=modelsClass.getDeclaredConstructor(Set.class,MaterialBaker.class);modelsCtor.setAccessible(true);
Object models=modelsCtor.newInstance(blocks,materials);
var getModel=modelsClass.getDeclaredMethod("get",net.minecraft.world.level.block.state.BlockState.class);getModel.setAccessible(true);
var put=BlockModelFeatureRenderer.class.getDeclaredMethod("putPartQuads",BlockStateModelPart.class,PoseStack.Pose.class,QuadInstance.class,int.class,int[].class,VertexConsumer.class);put.setAccessible(true);
try (var output=Files.newBufferedWriter(Path.of(args[1]))) {
for (var row:rows) {
var state=Block.stateById(row.get("state").getAsInt());var recorder=new Recorder();boolean translucent=false;
if (state.getRenderShape()==RenderShape.MODEL) {
var p=row.getAsJsonArray("pos");var camera=row.getAsJsonArray("camera");
var pos=new BlockPos(p.get(0).getAsInt(),p.get(1).getAsInt(),p.get(2).getAsInt());
var pose=new PoseStack();
pose.translate(pos.getX()-camera.get(0).getAsDouble(),pos.getY()-camera.get(1).getAsDouble(),pos.getZ()-camera.get(2).getAsDouble());
pose.translate(state.getOffset(pos));
var model=(BlockStateModel)getModel.invoke(models,state);translucent=model.hasMaterialFlag(1);
var parts=new ArrayList<BlockStateModelPart>();model.collectParts(RandomSource.create(state.getSeed(pos)),parts);
var instance=new QuadInstance();instance.setLightCoords(15728880);instance.setOverlayCoords(655360);
var buffer=new SheetedDecalTextureGenerator(recorder,pose.last(),1.0F);
for (var part:parts) put.invoke(null,part,pose.last(),instance,0,new int[0],buffer);
}
if (!recorder.pending.isEmpty()) throw new AssertionError("partial quad");
output.write(JSON.toJson(Map.of("case",row.get("case").getAsInt(),"translucent",translucent,"quads",recorder.quads)));output.newLine();
}
}
}
}
@@ -0,0 +1,52 @@
package dev.horizonlab.parity;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import net.minecraft.client.renderer.CloudRenderer;
/** Invoke the shipped mesh builder without constructing GPU resources. */
public final class VanillaCloudRenderOracle {
public static void main(String[] args) throws Exception {
Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
var field = unsafeClass.getDeclaredField("theUnsafe");
field.setAccessible(true);
Object renderer = unsafeClass.getMethod("allocateInstance", Class.class)
.invoke(field.get(null), CloudRenderer.class);
Class<?> relative = Class.forName("net.minecraft.client.renderer.CloudRenderer$RelativeCameraPos");
Object[] positions = relative.getEnumConstants(); // ABOVE, INSIDE, BELOW
var cell = CloudRenderer.class.getDeclaredMethod("buildExtrudedCell", relative, ByteBuffer.class, int.class, int.class, long.class);
var mesh = CloudRenderer.class.getDeclaredMethod("buildMesh", relative, ByteBuffer.class, int.class, int.class, boolean.class, int.class);
cell.setAccessible(true);
mesh.setAccessible(true);
var texture = CloudRenderer.class.getDeclaredField("texture");
texture.setAccessible(true);
texture.set(renderer, new CloudRenderer.TextureData(new long[]{0xfffffff0L}, 1, 1));
StringBuilder output = new StringBuilder();
int index = 0;
for (String line : Files.readAllLines(Path.of(args[0]))) {
String[] parts = line.split(" ");
int kind = Integer.parseInt(parts[0]), x = Integer.parseInt(parts[1]), z = Integer.parseInt(parts[2]);
int bottom = Integer.parseInt(parts[3]), neighbors = Integer.parseInt(parts[4]);
Object pos = positions[bottom > 0 ? 2 : bottom + 4 < 0 ? 0 : 1];
ByteBuffer buffer = ByteBuffer.allocate(100000);
if (kind == 0) {
long flags = ((neighbors & 1) != 0 ? 8 : 0) | ((neighbors & 2) != 0 ? 2 : 0)
| ((neighbors & 4) != 0 ? 1 : 0) | ((neighbors & 8) != 0 ? 4 : 0);
cell.invoke(renderer, pos, buffer, x, z, 0xfffffff0L | flags);
} else {
mesh.invoke(renderer, pos, buffer, 0, 0, true, x);
}
output.append(index++);
buffer.flip();
while (buffer.hasRemaining()) {
int cx = buffer.get(), cz = buffer.get(), flags = Byte.toUnsignedInt(buffer.get());
cx = (cx << 1) | ((flags & 128) >> 7);
cz = (cz << 1) | ((flags & 64) >> 6);
output.append(" ").append(cx).append(",").append(cz).append(",").append(flags & 7).append(",").append((flags & 16) == 0 ? 0 : 1);
}
output.append("\n");
}
Files.writeString(Path.of(args[1]), output);
}
}
@@ -11,6 +11,8 @@ import net.minecraft.server.Bootstrap;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.level.EmptyBlockGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.phys.shapes.BooleanOp;
import net.minecraft.world.phys.shapes.Shapes;
/**
* Original exporter of per-state gameplay facts read through vanilla's own accessors:
@@ -52,7 +54,12 @@ public final class VanillaGameplayFactsExporter {
// The outline (selection) shape without the random offset, as boxes
// for picking and as the edges LevelRenderer draws.
var offset = state.getOffset(BlockPos.ZERO);
var shape = state.getShape(level, BlockPos.ZERO).move(-offset.x, -offset.y, -offset.z);
var shape = state.getShape(level, BlockPos.ZERO);
// Some offset models (e.g. tall flowers) have an unshifted outline.
boolean outlineOffset = state.hasOffsetFunction() && Shapes.joinIsNotEmpty(
shape, state.getShape(level, new BlockPos(17, 0, 29)), BooleanOp.NOT_SAME);
o.addProperty("outline_offset", outlineOffset);
if (outlineOffset) shape = shape.move(-offset.x, -offset.y, -offset.z);
var boxes = new JsonArray();
for (var box : shape.toAabbs()) {
var b = new JsonArray();
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Compare terrain-particle placement with real vanilla ClientLevel effect methods."""
import itertools
import json
try:
from . import lab, oracle_harness as harness, test_model_baking_parity as baking, test_rust_parity as base, test_breaking_model_parity as breaking
except ImportError:
import lab, oracle_harness as harness, test_model_baking_parity as baking, test_rust_parity as base, test_breaking_model_parity as breaking
def main():
lock, jars, _ = base.verify_artifacts()
resources = lab.LOCAL / "horizon-client/26.3"
build = lab.LOCAL / "block-particles-parity"
build.mkdir(exist_ok=True)
paths = [lab.ROOT / p for p in ["tools/test_block_particles_parity.py", "tools/test_breaking_model_parity.py", "tools/oracle_harness.py", "tools/lab.py", "crates/horizon-client/src/particles.rs", "crates/horizon-client/src/game.rs", "crates/horizon-client/src/blocks.rs", "crates/horizon-client/src/mesher.rs", "crates/horizon-client/examples/block_particles_fixture.rs", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockParticlesOracle.java", "crates/horizon-core/src/random.rs", "Cargo.lock", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java"]]
tested = base.source_hashes(paths)
rows = [dict(case=i, seed=(-1 if i % 2 else 1) * i * 987654321, **row) for i, row in enumerate(breaking.cases(resources))]
rows[0]["seed"] = -(2**63)
rows[-1]["seed"] = 2**63 - 1
inputs = build / "inputs.jsonl"
inputs.write_text("".join(json.dumps(row)+"\n" for row in rows))
classes, dependencies, _ = harness.compile_oracle(build, "VanillaBlockParticlesOracle", jars, baking.client_libraries(), lock["minecraft"]["java_major"])
binary = harness.build_probe(build, "block_particles_fixture")
harness.run_logged([binary, resources, inputs, build / "rust.jsonl"], build, "rust")
harness.java_run(build, classes, dependencies, "VanillaBlockParticlesOracle", [inputs, build / "client.jsonl"], "client")
count = hits = burst = 0
max_error = 0.0
with (build / "client.jsonl").open() as native, (build / "rust.jsonl").open() as rust:
for v, r in itertools.zip_longest(native, rust):
assert v is not None and r is not None, "output length differs"
v, r = json.loads(v), json.loads(r)
assert v["case"] == r["case"], "case order differs"
assert v["next"] == r["next"], (rows[count], "position RNG consumption differs")
for key in ["hits", "destroy"]:
assert len(v[key]) == len(r[key]), (rows[count], key, "count", len(v[key]), len(r[key]))
for vp, rp in zip(v[key], r[key]):
if vp is None or rp is None:
assert vp == rp, (rows[count], key, "empty shape differs")
continue
assert len(vp) == len(rp) == 3
for expected, got in zip(vp, rp):
error = abs(expected-got)
max_error = max(max_error, error)
assert error <= 1e-10, (rows[count], key, expected, got, error)
if key == "hits": hits += 1
else: burst += 1
count += 1
assert count == len(rows)
base.ensure_sources_unchanged(paths, tested)
lab.write_json(build / "report.json", dict(cases=count, hits=hits, burst=burst, max_error=max_error, sources_sha256=tested, gameplay_facts_sha256=lab.digest(resources / "gameplay-facts.json", "sha256"), client_jar_sha256=lab.digest(jars["client"], "sha256"), scope="Actual ClientLevel mining and destruction enqueue positions/count/order, outline offsets, six hit faces, position RNG draws. Sprite/tint lookup is stubbed; particle-local RNG, velocities, ticks and complete framebuffer parity are not compared."))
print(f"{count:,} block-particle cases / {hits:,} mining crumbs / {burst:,} burst crumbs match vanilla; max error {max_error:g}")
if __name__ == "__main__":
main()
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Compare real model-shaped breaking geometry and projected UVs with vanilla 26.3."""
import json
import itertools
try:
from . import lab, oracle_harness as harness, test_model_baking_parity as baking, test_rust_parity as base, test_section_mesh_parity as mesh
except ImportError:
import lab, oracle_harness as harness, test_model_baking_parity as baking, test_rust_parity as base, test_section_mesh_parity as mesh
BLOCKS = ["stone", "oak_slab", "stone_slab", "oak_stairs", "stone_stairs", "oak_fence", "iron_bars", "glass_pane", "white_stained_glass_pane", "glass", "tinted_glass", "cobblestone_wall", "oak_fence_gate", "oak_trapdoor", "iron_trapdoor", "oak_door", "white_carpet", "moss_carpet", "pale_moss_carpet", "snow", "cake", "candle", "sea_pickle", "dandelion", "tall_grass", "bamboo", "torch", "wall_torch", "lantern", "chain", "end_rod", "lightning_rod", "lever", "stone_button", "repeater", "comparator", "farmland", "enchanting_table", "lectern", "scaffolding", "anvil", "brewing_stand", "hopper", "cauldron", "composter", "potted_fern", "lily_pad", "sunflower", "chest", "air", "water"]
def cases(resources):
states=mesh.States(resources)
ids=sorted({i for block in BLOCKS for i in states.by_name.get("minecraft:"+block, [])})
for state, (pos, camera) in itertools.product(ids, [([2,97,3],[.5,98.62,.5]), ([-23,11,-19],[-25.25,12.125,-15.5])]):
yield dict(state=state,pos=pos,camera=camera)
def canonical(quads):
result=[]
for quad in quads:
# Only cyclic rotation is allowed, so reversed winding cannot pass.
rotations=[quad[i:]+quad[:i] for i in range(4)]
result.append(min(rotations,key=lambda q:tuple(round(v/1e-4) for p in q for v in p[:3])))
return sorted(result,key=lambda q:tuple(round(v/1e-4) for p in q for v in p[:3]))
def main():
lock,jars,_=base.verify_artifacts();libraries=baking.client_libraries()
resources=lab.LOCAL/"horizon-client/26.3";build=lab.LOCAL/"breaking-model-parity";build.mkdir(exist_ok=True)
paths=[lab.ROOT/"tools/test_breaking_model_parity.py",lab.ROOT/"crates/horizon-client/src/breaking.rs",lab.ROOT/"crates/horizon-client/src/game.rs",lab.ROOT/"crates/horizon-client/src/gfx.rs",lab.ROOT/"crates/horizon-client/src/entity.wgsl",lab.ROOT/"crates/horizon-client/src/models/catalog.rs",lab.ROOT/"crates/horizon-client/src/mesher.rs",lab.ROOT/"crates/horizon-client/src/camera.rs",lab.ROOT/"crates/horizon-client/examples/breaking_fixture.rs",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBreakingModelOracle.java",lab.ROOT/"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSectionMeshOracle.java",lab.ROOT/"Cargo.lock"]
tested=base.source_hashes(paths)
rows=[dict(case=i,**row) for i,row in enumerate(cases(resources))]
inputs=build/"inputs.jsonl";inputs.write_text("".join(json.dumps(row)+"\n" for row in rows))
classes,dependencies,_=harness.compile_oracle(build,"VanillaBreakingModelOracle",jars,libraries,lock["minecraft"]["java_major"])
binary=harness.build_probe(build,"breaking_fixture")
harness.run_logged([binary,resources,inputs,build/"rust.jsonl"],build,"rust")
harness.java_run(build,classes,dependencies,"VanillaBreakingModelOracle",[inputs,build/"client.jsonl"],"client")
count=vertices=0;max_error=0.0
with (build/"client.jsonl").open() as native, (build/"rust.jsonl").open() as rust:
for v,r in itertools.zip_longest(native,rust):
assert v is not None and r is not None,"output length differs"
v,r=json.loads(v),json.loads(r)
assert v["case"]==r["case"],"case order differs"
assert v["translucent"]==r["translucent"],(rows[count],"wrong render phase",v["translucent"],r["translucent"])
vq,rq=canonical(v["quads"]),canonical(r["quads"])
assert len(vq)==len(rq),(rows[count],"quad count",len(vq),len(rq))
for a,b in zip(vq,rq):
for vp,rp in zip(a,b):
for axis,(expected,got) in enumerate(zip(vp,rp)):
error=abs(expected-got);max_error=max(max_error,error)
assert error<=1e-4,(rows[count],axis,expected,got,error)
vertices+=1
count+=1
assert count==len(rows);base.ensure_sources_unchanged(paths,tested)
lab.write_json(build/"report.json",dict(cases=count,vertices=vertices,max_error=max_error,sources_sha256=tested,client_jar_sha256=lab.digest(jars["client"],"sha256"),scope="Selected baked model quads, block offsets, winding, projected crack UVs, white/fullbright vertices and translucent phase. Not complete framebuffer or block-entity overlay parity."))
print(f"{count:,} breaking model cases / {vertices:,} vertices match vanilla; max error {max_error:g}")
if __name__=="__main__":
main()
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Compare fancy cloud exterior/interior faces and nearest-first mesh traversal with 26.3."""
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
def make_input(build):
cases = []
for x in (-130, -2, -1, 0, 1, 2, 130):
for z in (-130, -2, -1, 0, 1, 2, 130):
for bottom in (-5, -4, 0, 1):
for empty in range(16):
cases.append(f"0 {x} {z} {bottom} {empty}\n")
for radius in range(11):
for bottom in (-5, -4, 0, 1):
cases.append(f"1 {radius} 0 {bottom} 0\n")
inputs = build / "inputs.txt"
inputs.write_text("".join(cases))
return inputs, len(cases)
def main():
harness.differential("cloud-render-parity", "VanillaCloudRenderOracle", "cloud_fixture", make_input,
"Fancy cloud face culling, interior winding flags and mesh traversal; not full framebuffer parity.",
sources=[lab.ROOT / "crates/horizon-client/src/clouds.rs"])
if __name__ == "__main__":
main()