diff --git a/crates/horizon-client/examples/block_particles_fixture.rs b/crates/horizon-client/examples/block_particles_fixture.rs new file mode 100644 index 000000000..e9c207a7e --- /dev/null +++ b/crates/horizon-client/examples/block_particles_fixture.rs @@ -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> { + 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(()) +} diff --git a/crates/horizon-client/examples/breaking_fixture.rs b/crates/horizon-client/examples/breaking_fixture.rs new file mode 100644 index 000000000..ec8f7a68b --- /dev/null +++ b/crates/horizon-client/examples/breaking_fixture.rs @@ -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> { + 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::>() + }) + .collect(); + serde_json::to_writer( + &mut output, + &json!({"case":row["case"],"translucent":translucent,"quads":quads}), + )?; + output.write_all(&[10])?; + } + output.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/examples/cloud_fixture.rs b/crates/horizon-client/examples/cloud_fixture.rs index 7c05f00af..e21f3386e 100644 --- a/crates/horizon-client/examples/cloud_fixture.rs +++ b/crates/horizon-client/examples/cloud_fixture.rs @@ -27,7 +27,7 @@ fn main() -> Result<(), Box> { cell(x, z, 0); } } - output.push_str("\n"); + output.push('\n'); } fs::write(&args[2], output)?; Ok(()) diff --git a/crates/horizon-client/src/blocks.rs b/crates/horizon-client/src/blocks.rs index d75680ea3..25a3033c3 100644 --- a/crates/horizon-client/src/blocks.rs +++ b/crates/horizon-client/src/blocks.rs @@ -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]>, /// `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> = HashMap::new(); - let mut shape = |v: &Value, fallback: &dyn Fn() -> Vec<[f32; 6]>| -> Arc<[[f32; 6]]> { + let mut shapes: HashMap> = 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 diff --git a/crates/horizon-client/src/breaking.rs b/crates/horizon-client/src/breaking.rs new file mode 100644 index 000000000..d8079236a --- /dev/null +++ b/crates/horizon-client/src/breaking.rs @@ -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) { + // 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()); + } +} diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index b15d34211..7c9558d42 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -15,6 +15,7 @@ struct Globals { end_portal_sprites: array, 2>, // x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000) time: vec4, + crumbling_sprite: vec4, } @group(0) @binding(0) var globals: Globals; @group(0) @binding(1) var atlas: texture_2d; @@ -44,7 +45,7 @@ struct Out { 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); // Celestial bodies, clouds, beacon beams and breaking cracks are unlit. - var c = select(color * lm, color, overlay == 2u || overlay == 4u || overlay == 6u || overlay == 11u); + 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 +103,9 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { @fragment fn fs_entity(in: Out) -> @location(0) vec4 { 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 diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1ff8942d7..7417f959d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -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,58 +4601,27 @@ impl Game<'_> { f64::from(m.pos[2]), ) - camera) .as_vec3(); - let corner = |x: f32, y: f32, z: f32| o + glam::Vec3::new(x, y, z); - 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 + 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() - .zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]) - .rev() - { - out.push(Vertex { - pos: v.to_array(), - uv, - layer: 11, - color: 0xFFFF_FFFF, - light: (15 * 16) | ((15 * 16) << 8), - }); + .any(|(_, model)| model.faces.iter().any(|f| f.translucent)); + for (_, model) in models { + horizon_client::breaking::geometry(model, origin, translucent, &mut out); } } } @@ -7257,7 +7221,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 @@ -7269,7 +7233,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() @@ -7413,6 +7377,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 diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 1953f3734..81bc468de 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -28,13 +28,14 @@ fn batch_entities( entities: &[Vertex], additive: &[Vertex], hand: &[Vertex], -) -> (Vec, [u32; 3]) { +) -> (Vec, [u32; 4]) { let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len()); - let mut counts = [0u32; 3]; - for (i, layer) in [0, 11, 4].into_iter().enumerate() { + 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, }; @@ -71,6 +72,7 @@ struct Globals { end_portal_sprites: [[f32; 4]; 2], /// x: vanilla's `GameTime` uniform; yzw unused. time: [f32; 4], + crumbling_sprite: [f32; 4], } pub type SectionKey = (i32, i32, i32); struct SectionGpu { @@ -136,6 +138,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. @@ -1815,6 +1819,7 @@ 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], }; self.queue @@ -1968,9 +1973,17 @@ impl Renderer { self.queue .write_buffer(&self.outline, 0, bytemuck::cast_slice(&lines)); } - let (combined, [entity_quads, crumbling_quads, cloud_quads]) = - batch_entities(frame.entities, frame.additive, frame.hand); - let world_quads = entity_quads + crumbling_quads + cloud_quads; + 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; @@ -2145,13 +2158,23 @@ 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) * 4) as i32, + ((entity_quads + crumbling_quads + translucent_crumbling_quads) * 4) as i32, 0..1, ); } @@ -2427,12 +2450,12 @@ mod tests { light: id, }; 4] }; - let entities: Vec<_> = [(0, 0), (4, 1), (11, 2), (7, 3), (4, 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, 2]); + assert_eq!(counts, [2, 1, 1, 2]); assert_eq!( vertices .as_chunks::<4>() @@ -2440,7 +2463,7 @@ mod tests { .iter() .map(|q| q[0].light) .collect::>(), - [0, 3, 2, 1, 4, 5, 6] + [0, 3, 2, 7, 1, 4, 5, 6] ); } #[test] diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 7dba33f7e..a2364079f 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -19,6 +19,7 @@ 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; diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index a52c34e5a..241eba3fe 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -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!( diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockParticlesOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockParticlesOracle.java new file mode 100644 index 000000000..47d6ceffe --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockParticlesOracle.java @@ -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 make(Class 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 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();var next=new ArrayList(); + 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(); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBreakingModelOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBreakingModelOracle.java new file mode 100644 index 000000000..2e4b6da8a --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBreakingModelOracle.java @@ -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> quads=new ArrayList<>(); + final List 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();var blocks=new HashSet(); + 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();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(); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java index b19a25705..bf576e130 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java @@ -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(); diff --git a/tools/test_block_particles_parity.py b/tools/test_block_particles_parity.py new file mode 100644 index 000000000..c4e191831 --- /dev/null +++ b/tools/test_block_particles_parity.py @@ -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() diff --git a/tools/test_breaking_model_parity.py b/tools/test_breaking_model_parity.py new file mode 100644 index 000000000..11e627d12 --- /dev/null +++ b/tools/test_breaking_model_parity.py @@ -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()