diff --git a/crates/horizon-client/examples/block_entity_anim_fixture.rs b/crates/horizon-client/examples/block_entity_anim_fixture.rs new file mode 100644 index 000000000..3347a8104 --- /dev/null +++ b/crates/horizon-client/examples/block_entity_anim_fixture.rs @@ -0,0 +1,455 @@ +//! Headless transport for the block-entity animation parity gate: replays each +//! scripted case (block, neighbourhood, entities, block events, game times) +//! through `horizon_client::block_entity_anim` and prints the same lines as +//! `VanillaBlockEntityAnimOracle`: the block entity's fields, the level calls +//! its tick made and the render state the renderer derives from `BlockAnim`. +#![forbid(unsafe_code)] +use horizon_client::{ + assets::Assets, + block_entity_anim::{ + Bell, BellEntity, BlockEntityAnims, ChestLid, Conduit, ConduitTarget, DIRECTIONS, + PotWobble, Shulker, ShulkerStatus, Skull, WobbleStyle, chest_lid_x_rot, direction_index, + }, + block_entity_render::BlockEntityRenderer, + blocks::{BlockFacts, Fluid}, + items::Items, +}; +use horizon_core::random::LegacyRandom; +use horizon_world::registry::{BlockRegistry, BlockStateId}; +use serde_json::Value; +use std::{ + collections::HashMap, + fmt::Write as _, + fs, + io::{BufWriter, Write}, + path::PathBuf, +}; +type Result = std::result::Result>; + +fn f(v: f32) -> String { + format!("{:08x}", v.to_bits()) +} +fn d(v: f64) -> String { + format!("{:016x}", v.to_bits()) +} +fn bx(b: [f64; 6]) -> String { + b.map(d).join(" ") +} + +fn find_state(registry: &BlockRegistry, spec: &str) -> Option { + let (name, props) = match spec.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (spec, ""), + }; + let wanted: Vec<(&str, &str)> = props + .split(',') + .filter(|p| !p.is_empty()) + .filter_map(|p| p.split_once('=')) + .collect(); + let default = registry.state(registry.default_state(name)?)?.clone(); + (0..registry.len() as u32).find(|&id| { + registry.state(BlockStateId(id)).is_some_and(|s| { + s.name == name + && s.properties.iter().all(|(k, v)| { + wanted + .iter() + .find(|(wk, _)| wk == k) + .map_or(default.properties.get(k) == Some(v), |(_, wv)| wv == v) + }) + }) + }) +} + +fn prop<'a>(spec: &'a str, key: &str) -> Option<&'a str> { + let props = spec.split_once('[')?.1.trim_end_matches(']'); + props + .split(',') + .filter_map(|p| p.split_once('=')) + .find(|(k, _)| *k == key) + .map(|(_, v)| v) +} + +fn offset(key: &str) -> [i32; 3] { + let mut it = key.split(',').map(|v| v.parse::().unwrap_or(0)); + [ + it.next().unwrap_or(0), + it.next().unwrap_or(0), + it.next().unwrap_or(0), + ] +} + +fn mob(e: &Value) -> BellEntity { + let p = |i: usize| e["pos"][i].as_f64().unwrap_or(0.0); + BellEntity { + position: [p(0), p(1), p(2)], + alive: e["alive"].as_bool().unwrap_or(true) && !e["removed"].as_bool().unwrap_or(false), + raider: e["raider"].as_bool().unwrap_or(false), + } +} + +fn lid_text(l: Option<&ChestLid>) -> String { + l.map_or("-".to_owned(), |l| { + format!("{} {} {}", l.should_be_open, f(l.openness), f(l.o_openness)) + }) +} + +/// The case's players: feet positions and whether each is a spectator. +fn players(v: &Value) -> Vec<([f64; 3], bool)> { + v.as_array() + .into_iter() + .flatten() + .map(|p| { + let c = |i: usize| p["pos"][i].as_f64().unwrap_or(0.0); + ( + [c(0), c(1), c(2)], + p["spectator"].as_bool().unwrap_or(false), + ) + }) + .collect() +} + +fn status(s: ShulkerStatus) -> &'static str { + match s { + ShulkerStatus::Closed => "CLOSED", + ShulkerStatus::Opening => "OPENING", + ShulkerStatus::Opened => "OPENED", + ShulkerStatus::Closing => "CLOSING", + } +} + +fn main() -> Result<()> { + let args: Vec = std::env::args_os().skip(1).map(PathBuf::from).collect(); + let [root, inputs, output] = args.as_slice() else { + return Err("usage: block_entity_anim_fixture RESOURCES INPUTS OUTPUT".into()); + }; + let assets = Assets::load(root)?; + let registry = assets.registry; + let facts = BlockFacts::load(root, registry)?; + let renderer = BlockEntityRenderer::load(root, registry)?; + let tags = Items::tags_only(root)?; + let frames = tags + .block_tags + .get("minecraft:conduit_effect_block") + .cloned() + .unwrap_or_default(); + let mut out = BufWriter::new(fs::File::create(output)?); + for line in fs::read_to_string(inputs)? + .lines() + .filter(|l| !l.is_empty()) + { + let case: Value = serde_json::from_str(line)?; + writeln!(out, "case {}", case["name"].as_str().unwrap_or_default())?; + let block = case["block"].as_str().unwrap_or_default().to_owned(); + let int = |v: &Value| v.as_i64().unwrap_or(0) as i32; + let pos = [ + int(&case["pos"][0]), + int(&case["pos"][1]), + int(&case["pos"][2]), + ]; + // The neighbourhood as block states (conduits). + let mut blocks: HashMap<[i32; 3], String> = HashMap::new(); + blocks.insert(pos, block.clone()); + let place = |blocks: &mut HashMap<[i32; 3], String>, set: &Value| { + for (k, v) in set.as_object().into_iter().flatten() { + let o = offset(k); + blocks.insert( + [pos[0] + o[0], pos[1] + o[1], pos[2] + o[2]], + v.as_str().unwrap_or_default().to_owned(), + ); + } + }; + place(&mut blocks, &case["world"]); + let entities: Vec = case["entities"] + .as_array() + .into_iter() + .flatten() + .map(mob) + .collect(); + let target = case.get("target").map(|t| { + let e = mob(t); + ConduitTarget { + position: e.position, + eye_y: e.position[1] + f64::from(t["eye"].as_f64().unwrap_or(0.0) as f32), + width: t["width"].as_f64().unwrap_or(0.0) as f32, + height: t["height"].as_f64().unwrap_or(0.0) as f32, + } + }); + let mut random = LegacyRandom::new(case["seed"].as_i64().unwrap_or(0)); + let name = block.split('[').next().unwrap_or_default().to_owned(); + let mut anims = BlockEntityAnims::default(); + let partner = case["partner"].as_str().map(|k| { + let o = offset(k); + [pos[0] + o[0], pos[1] + o[1], pos[2] + o[2]] + }); + let mut gamers = players(&case["players"]); + if name == "minecraft:enchanting_table" { + anims.book_random = LegacyRandom::new(case["seed"].as_i64().unwrap_or(0)); + } + let facing = prop(&block, "facing") + .and_then(direction_index) + .unwrap_or(1); + let mut text = String::new(); + for step in case["steps"].as_array().into_iter().flatten() { + let time = step["time"].as_i64().unwrap_or(0); + let partial = step["partial"].as_f64().unwrap_or(0.0) as f32; + let mut log = String::new(); + place(&mut blocks, &step["set"]); + let event = step["event"].as_array().map(|e| (int(&e[0]), int(&e[1]))); + text.clear(); + if step.get("players").is_some() { + gamers = players(&step["players"]); + } + if name.ends_with("chest") { + let lid = anims.chests.entry(pos).or_default(); + if let Some((a, b)) = event { + let handled = lid.trigger_event(a, b); + let _ = write!(log, " event {handled}"); + } + if let Some(other) = partner { + let lid = anims.chests.entry(other).or_default(); + if let Some(e) = step["partnerEvent"].as_array() { + let handled = lid.trigger_event(int(&e[0]), int(&e[1])); + let _ = write!(log, " partner event {handled}"); + } + } + // lidAnimateTick: this chest, then the other half. + if let Some(l) = anims.chests.get_mut(&pos) { + l.tick(); + } + if let Some(l) = partner.and_then(|p| anims.chests.get_mut(&p)) { + l.tick(); + } + let state_at = |p: [i32; 3]| { + find_state( + registry, + blocks.get(&p).map_or("minecraft:air", String::as_str), + ) + .unwrap_or(0) + }; + let (open, _) = renderer + .chest_openness_of(pos, state_at(pos), &state_at, &|p| anims.lid(p, partial)); + let _ = write!( + text, + "{} partner {} render {} {}", + lid_text(anims.chests.get(&pos)), + partner.map_or("none".to_owned(), |p| lid_text(anims.chests.get(&p))), + f(open), + f(chest_lid_x_rot(open)) + ); + } else if name == "minecraft:enchanting_table" { + let feet: Vec<[f64; 3]> = gamers + .iter() + .filter(|(_, spectator)| !spectator) + .map(|(p, _)| *p) + .collect(); + let BlockEntityAnims { + books, book_random, .. + } = &mut anims; + books.entry(pos).or_default().tick(pos, &feet, book_random); + let b = anims.books[&pos]; + let r = anims + .block_anim(pos, time, partial, Default::default()) + .book + .render(partial); + let _ = write!( + text, + "{} {} {} {} {} {} {} {} {} {} render {} {} {} {} book {} {} {}", + b.time, + f(b.flip), + f(b.o_flip), + f(b.flip_t), + f(b.flip_a), + f(b.open), + f(b.o_open), + f(b.rot), + f(b.o_rot), + f(b.t_rot), + f(r.flip), + f(r.open), + f(r.time), + f(r.y_rot), + f(r.openness), + f(r.page_flip1), + f(r.page_flip2) + ); + } else if name.ends_with("shulker_box") { + let s = anims.shulkers.entry(pos).or_insert_with(Shulker::default); + if let Some((a, b)) = event { + let handled = s.trigger_event(a, b); + let _ = write!(log, " event {handled}"); + } + let tick = s.tick(pos, facing); + for _ in 0..tick.neighbor_updates { + log.push_str(" neighbors"); + } + if let Some(b) = tick.push { + let _ = write!(log, " push {}", bx(b)); + } + let (count, st) = (s.open_count, s.status); + let a = anims.block_anim(pos, time, partial, Default::default()); + // ShulkerBoxRenderer: getProgress(partial). + let (progress, old) = a.shulker; + let render = old + partial * (progress - old); + let s = &anims.shulkers[&pos]; + let _ = write!( + text, + "{} {} {} {} render {}", + status(st), + count, + f(s.progress), + f(s.progress_old), + f(render) + ); + } else if name == "minecraft:bell" { + let b = anims.bells.entry(pos).or_insert_with(Bell::default); + if let Some((e0, e1)) = event { + let handled = b.trigger_event(e0, e1, time, || { + let inflated = [ + f64::from(pos[0]) - 48.0, + f64::from(pos[1]) - 48.0, + f64::from(pos[2]) - 48.0, + f64::from(pos[0]) + 1.0 + 48.0, + f64::from(pos[1]) + 1.0 + 48.0, + f64::from(pos[2]) + 1.0 + 48.0, + ]; + let _ = write!(log, " gather {}", bx(inflated)); + (0..entities.len() as u64) + .filter(|&i| { + let p = entities[i as usize].position; + (0..3).all(|a| p[a] >= inflated[a] && p[a] < inflated[a + 3]) + }) + .collect() + }); + let _ = write!(log, " event {handled}"); + } + if !step["noTick"].as_bool().unwrap_or(false) { + let tick = b.tick(pos, |h| entities.get(h as usize).copied()); + if tick.resonate { + log.push_str(" sound minecraft:block.bell.resonate"); + } + if let Some((particles, _)) = tick.ended { + for (p, color) in particles { + let _ = write!( + log, + " particle minecraft:entity_effect {color} {} {} {} {} {} {}", + d(p[0]), + d(p[1]), + d(p[2]), + d(0.0), + d(0.0), + d(0.0) + ); + } + } + } + let b = &anims.bells[&pos]; + let a = anims.block_anim(pos, time, partial, Default::default()); + let dir = |d: Option<&str>| d.map_or("null".to_owned(), str::to_owned); + let _ = write!( + text, + "{} {} {} {} {} {} render {} {}", + b.ticks, + b.shaking, + dir(b.click_direction.map(|d| DIRECTIONS[usize::from(d)])), + b.resonating, + b.resonation_ticks, + b.last_ring_timestamp, + f(a.bell_ticks as f32 + partial), + dir(a.bell_shake) + ); + } else if name == "minecraft:conduit" { + let c = anims.conduits.entry(pos).or_insert_with(Conduit::default); + let state_of = |p: [i32; 3]| -> Option { + find_state( + registry, + blocks.get(&p).map_or("minecraft:air", String::as_str), + ) + }; + let is_water = |p: [i32; 3]| { + state_of(p).is_some_and(|s| facts.get(BlockStateId(s)).fluid == Fluid::Water) + }; + let is_frame = |p: [i32; 3]| { + let spec = blocks.get(&p).map_or("minecraft:air", String::as_str); + frames.contains(spec.split('[').next().unwrap_or_default()) + }; + let particles = c.client_tick(pos, time, is_water, is_frame, target, &mut random); + for (p, v) in particles { + let _ = write!( + log, + " particle minecraft:nautilus {} {} {} {} {} {}", + d(p[0]), + d(p[1]), + d(p[2]), + d(v[0]), + d(v[1]), + d(v[2]) + ); + } + let c = &anims.conduits[&pos]; + let a = anims.block_anim(pos, time, partial, Default::default()); + // ConduitRenderer.extractRenderState as block_entity_render derives it. + let (ticks, active, hunting, raw) = a.conduit; + let rotation = (raw + if active { partial } else { 0.0 }) * -0.0375; + let _ = write!( + text, + "{} {} {} {} {} render {} {} {} {} {}", + c.tick_count, + c.is_active, + c.is_hunting, + f(c.active_rotation), + c.effect_blocks.len(), + active, + f(rotation), + f(ticks as f32 + partial), + ticks / 66 % 3, + hunting + ); + } else if name.ends_with("_head") || name.ends_with("_skull") { + let now = step["state"].as_str().unwrap_or(&block); + let s = anims.skulls.entry(pos).or_insert_with(Skull::default); + s.tick(prop(now, "powered") == Some("true")); + let s = anims.skulls[&pos]; + let a = anims.block_anim(pos, time, partial, Default::default()); + // block_entity_render: count + partial while animating. + let (animating, count) = a.skull; + let render = count as f32 + if animating { partial } else { 0.0 }; + let _ = write!( + text, + "{} {} render {}", + s.animating, + s.tick_count, + f(render) + ); + } else if name == "minecraft:decorated_pot" { + let w = anims.pots.entry(pos).or_insert_with(PotWobble::default); + if let Some((e0, e1)) = event { + let handled = w.trigger_event(e0, e1, time); + let _ = write!(log, " event {handled}"); + } + let w = anims.pots[&pos]; + let a = anims.block_anim(pos, time, partial, Default::default()); + let (style, progress) = match a.wobble { + Some((true, p)) => ("POSITIVE", p), + Some((false, p)) => ("null", p), + None => ("null", 0.0), + }; + let _ = write!( + text, + "{} {} render {} {}", + w.started_at, + match w.style { + Some(WobbleStyle::Positive) => "POSITIVE", + Some(WobbleStyle::Negative) => "NEGATIVE", + None => "null", + }, + f(progress), + style + ); + } else { + text = format!("unsupported {block}"); + } + writeln!(out, "{text} |{log}")?; + } + } + Ok(()) +} diff --git a/crates/horizon-client/examples/block_entity_render_fixture.rs b/crates/horizon-client/examples/block_entity_render_fixture.rs index 1770c0c89..aa4a14a58 100644 --- a/crates/horizon-client/examples/block_entity_render_fixture.rs +++ b/crates/horizon-client/examples/block_entity_render_fixture.rs @@ -7,6 +7,7 @@ use glam::{DVec3, Mat4, Quat, Vec3}; use horizon_client::{ assets::Assets, banner::{self, Banners}, + block_entity_anim::EnchantingBook, block_entity_render::{ BlockAnim, BlockEntityRenderer, END_GATEWAY_LAYER, END_PORTAL_LAYER, Scene, TextCall, }, @@ -115,7 +116,7 @@ fn main() -> Result<()> { }; let assets = Assets::load(root)?; let registry = assets.registry; - let mut renderer = BlockEntityRenderer::load(root, registry)?; + let renderer = BlockEntityRenderer::load(root, registry)?; let atlas = HudAtlas::build(root)?; let banners = Banners::load(root); let (sprites, names, grid) = fake_sprites(textures)?; @@ -217,13 +218,22 @@ fn main() -> Result<()> { BlockStateId(neighbour), )?; } - if let Some(book) = case.get("book") { - renderer.set_book( - pos, - int(&book["time"]), - ["flip", "oFlip", "open", "oOpen", "rot", "oRot"].map(|k| float(&book[k])), - ); - } + let book = case + .get("book") + .map_or_else(EnchantingBook::default, |book| { + let [flip, o_flip, open, o_open, rot, o_rot] = + ["flip", "oFlip", "open", "oOpen", "rot", "oRot"].map(|k| float(&book[k])); + EnchantingBook { + time: int(&book["time"]), + flip, + o_flip, + open, + o_open, + rot, + o_rot, + ..EnchantingBook::default() + } + }); let sign = case.get("sign").map(|s| { let mut data = SignData { hanging: block.contains("hanging"), @@ -267,6 +277,7 @@ fn main() -> Result<()> { wobble: case["wobble"] .as_array() .map(|w| (w[0].as_str() == Some("POSITIVE"), float(&w[1]))), + book, gateway: ( case["gateway"]["age"].as_i64().unwrap_or(0), int(&case["gateway"]["cooldown"]), diff --git a/crates/horizon-client/src/block_entity_anim.rs b/crates/horizon-client/src/block_entity_anim.rs new file mode 100644 index 000000000..70a57cc64 --- /dev/null +++ b/crates/horizon-client/src/block_entity_anim.rs @@ -0,0 +1,905 @@ +//! Client-ticked block-entity animation state, as vanilla's block entities +//! keep it: `ChestLidController` (chests, trapped and copper chests, ender +//! chests), `EnchantingTableBlockEntity.bookAnimationTick`, +//! `ShulkerBoxBlockEntity` (open count, animation status, progress), +//! `BellBlockEntity` (ring ticks, shake direction, resonation), +//! `ConduitBlockEntity.clientTick` (tick count, shape check, rotation, +//! hunting, nautilus particles), `SkullBlockEntity.animation` (powered dragon +//! and piglin heads) and `DecoratedPotBlockEntity` wobbles. +//! +//! [`BlockEntityAnims`] holds the state per position and turns it into the +//! renderer's [`BlockAnim`]. Its tick methods take what the level answers +//! (blocks, entities, game time) as closures, so the parity fixture can drive +//! them with scripted inputs (`tools/test_block_entity_anim_parity.py`). +use crate::block_entity_render::BlockAnim; +use horizon_core::{ + geometry::trig::{self, Mth}, + random::{LegacyRandom, RandomSource}, +}; +use std::collections::HashMap; + +/// `Direction` names by `get3DDataValue`. +pub const DIRECTIONS: [&str; 6] = ["down", "up", "north", "south", "west", "east"]; + +fn step(direction: u8) -> [i32; 3] { + match direction { + 0 => [0, -1, 0], + 1 => [0, 1, 0], + 2 => [0, 0, -1], + 3 => [0, 0, 1], + 4 => [-1, 0, 0], + _ => [1, 0, 0], + } +} + +/// `Direction.from3DDataValue`: `BY_3D_DATA[Mth.abs(data % 6)]`. +pub fn from_3d_data_value(data: i32) -> u8 { + (data % 6).unsigned_abs() as u8 +} + +/// The 3D data value of a direction name. +pub fn direction_index(name: &str) -> Option { + DIRECTIONS.iter().position(|d| *d == name).map(|i| i as u8) +} + +/// `ChestLidController`, shared by `ChestBlockEntity` (chests, trapped and +/// copper chests) and `EnderChestBlockEntity`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ChestLid { + pub should_be_open: bool, + pub openness: f32, + pub o_openness: f32, +} + +impl ChestLid { + /// `triggerEvent(1, openCount)`: the lid opens while anyone has it open. + pub fn trigger_event(&mut self, b0: i32, b1: i32) -> bool { + if b0 == 1 { + self.should_be_open = b1 > 0; + true + } else { + false + } + } + /// `tickLid` (the client ticker `lidAnimateTick`). + pub fn tick(&mut self) { + self.o_openness = self.openness; + if !self.should_be_open && self.openness > 0.0 { + self.openness = (self.openness - 0.1).max(0.0); + } else if self.should_be_open && self.openness < 1.0 { + self.openness = (self.openness + 0.1).min(1.0); + } + } + /// `getOpenness(a)`: `Mth.lerp(a, oOpenness, openness)`. + pub fn get_openness(&self, a: f32) -> f32 { + self.o_openness + a * (self.openness - self.o_openness) + } +} + +/// `ChestBlock.opennessCombiner`: a double chest opens as far as its more +/// open half (`Math.max(first, second)`, first being the `right` half). +pub fn combined_openness(first: f32, second: Option) -> f32 { + match second { + Some(second) => java_max(first, second), + None => first, + } +} + +/// `Math.max(float, float)`. +fn java_max(a: f32, b: f32) -> f32 { + if a.is_nan() { + a + } else if a == 0.0 && b == 0.0 && a.to_bits() != b.to_bits() { + 0.0 + } else if a >= b { + a + } else { + b + } +} + +/// `ChestRenderer.submit` and `ChestModel.setupAnim`: the lid and lock +/// `xRot` for a render-state openness. +pub fn chest_lid_x_rot(open: f32) -> f32 { + let open = 1.0 - open; + let open = 1.0 - open * open * open; + -(open * std::f32::consts::FRAC_PI_2) +} + +/// `EnchantingTableBlockEntity` book fields. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct EnchantingBook { + pub time: i32, + pub flip: f32, + pub o_flip: f32, + pub flip_t: f32, + pub flip_a: f32, + pub open: f32, + pub o_open: f32, + pub rot: f32, + pub o_rot: f32, + pub t_rot: f32, +} + +/// The `while (a >= PI) a -= 2PI; while (a < -PI) a += 2PI` loops. +fn wrap_pi(mut a: f32) -> f32 { + use std::f32::consts::PI; + while a >= PI { + a -= 2.0 * PI; + } + while a < -PI { + a += 2.0 * PI; + } + a +} + +/// `Mth.floor(float)`. +fn mth_floor(v: f32) -> i32 { + let i = v as i32; + if v < i as f32 { i - 1 } else { i } +} + +/// `Mth.frac(float)`. +pub fn mth_frac(v: f32) -> f32 { + v - mth_floor(v) as f32 +} + +/// `EnchantTableRenderState` (`EnchantTableRenderer.extractRenderState`) and +/// the `BookModel.State` its `submit` builds. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct BookRender { + pub flip: f32, + pub open: f32, + pub time: f32, + pub y_rot: f32, + /// `BookModel.State.forAnimation`: openness, pageFlip1, pageFlip2. + pub openness: f32, + pub page_flip1: f32, + pub page_flip2: f32, +} + +impl EnchantingBook { + /// `bookAnimationTick`. `players` are the feet positions of the level's + /// non-spectator players (`getNearestPlayer(centre, 3.0, false)`); + /// `random` is the block entity class's shared static `RANDOM`. + pub fn tick(&mut self, pos: [i32; 3], players: &[[f64; 3]], random: &mut impl RandomSource) { + self.o_open = self.open; + self.o_rot = self.rot; + let c = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + let mut best = -1.0; + let mut nearest = None; + for p in players { + let (dx, dy, dz) = (p[0] - c[0], p[1] - c[1], p[2] - c[2]); + let dist = dx * dx + dy * dy + dz * dz; + if dist < 9.0 && (best == -1.0 || dist < best) { + best = dist; + nearest = Some(*p); + } + } + if let Some(p) = nearest { + let xd = p[0] - c[0]; + let zd = p[2] - c[2]; + self.t_rot = trig::atan2(zd, xd) as f32; + self.open += 0.1; + if self.open < 0.5 || random.next_int_bound(40).unwrap_or(1) == 0 { + let old = self.flip_t; + loop { + let a = random.next_int_bound(4).unwrap_or(0); + let b = random.next_int_bound(4).unwrap_or(0); + self.flip_t += (a - b) as f32; + if old != self.flip_t { + break; + } + } + } + } else { + self.t_rot += 0.02; + self.open -= 0.1; + } + self.rot = wrap_pi(self.rot); + self.t_rot = wrap_pi(self.t_rot); + let dir = wrap_pi(self.t_rot - self.rot); + self.rot += dir * 0.4; + self.open = self.open.clamp(0.0, 1.0); + self.time += 1; + self.o_flip = self.flip; + let diff = ((self.flip_t - self.flip) * 0.4).clamp(-0.2, 0.2); + self.flip_a += (diff - self.flip_a) * 0.9; + self.flip += self.flip_a; + } + /// `EnchantTableRenderer.extractRenderState` and the book state of its + /// `submit`. + pub fn render(&self, a: f32) -> BookRender { + let flip = self.o_flip + a * (self.flip - self.o_flip); + let open = self.o_open + a * (self.open - self.o_open); + let time = self.time as f32 + a; + let y_rot = self.o_rot + wrap_pi(self.rot - self.o_rot) * a; + let ff1 = mth_frac(flip + 0.25) * 1.6 - 0.3; + let ff2 = mth_frac(flip + 0.75) * 1.6 - 0.3; + BookRender { + flip, + open, + time, + y_rot, + openness: ((time * 0.02).msin() * 0.1 + 1.25) * open, + page_flip1: ff1.clamp(0.0, 1.0), + page_flip2: ff2.clamp(0.0, 1.0), + } + } +} + +/// `ShulkerBoxBlockEntity.AnimationStatus`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ShulkerStatus { + #[default] + Closed, + Opening, + Opened, + Closing, +} + +/// `ShulkerBoxBlockEntity` lid state. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Shulker { + pub open_count: i32, + pub status: ShulkerStatus, + pub progress: f32, + pub progress_old: f32, +} + +/// Side effects of one [`Shulker::tick`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ShulkerTick { + /// `doNeighborUpdates` calls (shape and neighbour updates around the box). + pub neighbor_updates: u32, + /// `moveCollidedEntities`: the swept lid box (min x, y, z, max x, y, z); + /// entities in it move out along the facing. + pub push: Option<[f64; 6]>, +} + +/// `Shulker.getProgressDeltaAabb(size, direction, from, to, position)`. +pub fn progress_delta_aabb( + size: f32, + direction: u8, + from: f32, + to: f32, + position: [f64; 3], +) -> [f64; 6] { + let size_d = f64::from(size); + let mut b = [ + -size_d * 0.5, + 0.0, + -size_d * 0.5, + size_d * 0.5, + size_d, + size_d * 0.5, + ]; + let max = f64::from(from.max(to)); + let min = f64::from(from.min(to)); + let s = step(direction); + for axis in 0..3 { + // expandTowards + let a = f64::from(s[axis]) * max * size_d; + if a < 0.0 { + b[axis] += a; + } else if a > 0.0 { + b[axis + 3] += a; + } + } + for axis in 0..3 { + // contract + let a = -f64::from(s[axis]) * (1.0 + min) * size_d; + if a < 0.0 { + b[axis] -= a; + } else if a > 0.0 { + b[axis + 3] -= a; + } + } + // new AABB keeps min <= max; then move to the position. + let mut out = [0.0; 6]; + for axis in 0..3 { + out[axis] = b[axis].min(b[axis + 3]) + position[axis]; + out[axis + 3] = b[axis].max(b[axis + 3]) + position[axis]; + } + out +} + +impl Shulker { + /// `triggerEvent(1, openCount)`. + pub fn trigger_event(&mut self, b0: i32, b1: i32) -> bool { + if b0 != 1 { + return false; + } + self.open_count = b1; + if b1 == 0 { + self.status = ShulkerStatus::Closing; + } + if b1 == 1 { + self.status = ShulkerStatus::Opening; + } + true + } + /// `startOpen`/`stopOpen` for a non-spectator user: the new open count to + /// send as block event 1, and whether this was the first opener (open) or + /// the last closer (close), which play the sound and game event. + pub fn start_open(&mut self) -> (i32, bool) { + if self.open_count < 0 { + self.open_count = 0; + } + self.open_count += 1; + (self.open_count, self.open_count == 1) + } + pub fn stop_open(&mut self) -> (i32, bool) { + self.open_count -= 1; + (self.open_count, self.open_count <= 0) + } + /// `updateAnimation` (`ShulkerBoxBlockEntity.tick`); `facing` is the + /// block's facing as a 3D data value. + pub fn tick(&mut self, pos: [i32; 3], facing: u8) -> ShulkerTick { + let mut out = ShulkerTick::default(); + self.progress_old = self.progress; + match self.status { + ShulkerStatus::Closed => self.progress = 0.0, + ShulkerStatus::Opening => { + self.progress += 0.1; + if self.progress_old == 0.0 { + out.neighbor_updates += 1; + } + if self.progress >= 1.0 { + self.status = ShulkerStatus::Opened; + self.progress = 1.0; + out.neighbor_updates += 1; + } + let bottom = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + out.push = Some(progress_delta_aabb( + 1.0, + facing, + self.progress_old, + self.progress, + bottom, + )); + } + ShulkerStatus::Opened => self.progress = 1.0, + ShulkerStatus::Closing => { + self.progress -= 0.1; + if self.progress_old == 1.0 { + out.neighbor_updates += 1; + } + if self.progress <= 0.0 { + self.status = ShulkerStatus::Closed; + self.progress = 0.0; + out.neighbor_updates += 1; + } + } + } + out + } + /// `getProgress(a)`: `Mth.lerp(a, progressOld, progress)`. + pub fn get_progress(&self, a: f32) -> f32 { + self.progress_old + a * (self.progress - self.progress_old) + } + /// `ShulkerBoxBlock.canOpen`: a closed box only opens when its lid has room + /// (`level.noCollision` of the half-block lid box, deflated by 1e-6). + pub fn lid_box(pos: [i32; 3], facing: u8) -> [f64; 6] { + let bottom = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + let mut b = progress_delta_aabb(1.0, facing, 0.0, 0.5, bottom); + for axis in 0..3 { + b[axis] += 1.0e-6; + b[axis + 3] -= 1.0e-6; + } + b + } +} + +/// What the bell's tick asks about an entity it gathered when rung. +#[derive(Clone, Copy, Debug)] +pub struct BellEntity { + pub position: [f64; 3], + /// `isAlive() && !isRemoved()`. + pub alive: bool, + /// In `EntityTypeTags.RAIDERS`. + pub raider: bool, +} + +/// `BellBlockEntity`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Bell { + pub ticks: i32, + pub shaking: bool, + /// `clickDirection` as a 3D data value. + pub click_direction: Option, + pub last_ring_timestamp: i64, + /// `nearbyEntities`: the living entities around the bell when it was last + /// gathered, as caller-defined handles. + pub nearby: Option>, + pub resonating: bool, + pub resonation_ticks: i32, +} + +/// Side effects of one [`Bell::tick`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BellTick { + /// Resonation started: `BELL_RESONATE` (played by the server). + pub resonate: bool, + /// Resonation ended (`ResonationEndAction`): the client's + /// `showBellParticles` entity-effect particles (position and colour) and + /// the server's `makeRaidersGlow` targets. + pub ended: Option<(Vec<([f64; 3], i32)>, Vec)>, +} + +fn closer_to_center_than(pos: [i32; 3], p: [f64; 3], distance: f64) -> bool { + let dx = f64::from(pos[0]) + 0.5 - p[0]; + let dy = f64::from(pos[1]) + 0.5 - p[1]; + let dz = f64::from(pos[2]) + 0.5 - p[2]; + dx * dx + dy * dy + dz * dz < distance * distance +} + +impl Bell { + /// `triggerEvent(1, direction)`. `gather` lists the living entities whose + /// position is inside the bell's block box inflated by 48 + /// (`updateEntities`, refreshed at most every 60 ticks). + pub fn trigger_event( + &mut self, + b0: i32, + b1: i32, + game_time: i64, + gather: impl FnOnce() -> Vec, + ) -> bool { + if b0 != 1 { + return false; + } + if game_time > self.last_ring_timestamp + 60 || self.nearby.is_none() { + self.last_ring_timestamp = game_time; + self.nearby = Some(gather()); + } + self.resonation_ticks = 0; + self.click_direction = Some(from_3d_data_value(b1)); + self.ticks = 0; + self.shaking = true; + true + } + /// `BellBlockEntity.tick` with the client's resonation end action. + pub fn tick(&mut self, pos: [i32; 3], entity: impl Fn(u64) -> Option) -> BellTick { + let mut out = BellTick::default(); + if self.shaking { + self.ticks += 1; + } + if self.ticks >= 50 { + self.shaking = false; + self.ticks = 0; + } + let nearby = self.nearby.clone().unwrap_or_default(); + let raider_in = |e: &BellEntity, distance: f64| { + e.alive && closer_to_center_than(pos, e.position, distance) && e.raider + }; + if self.ticks >= 5 + && self.resonation_ticks == 0 + && nearby + .iter() + .filter_map(|&h| entity(h)) + .any(|e| raider_in(&e, 32.0)) + { + self.resonating = true; + out.resonate = true; + } + if self.resonating { + if self.resonation_ticks < 40 { + self.resonation_ticks += 1; + } else { + // showBellParticles / makeRaidersGlow. + let mut color = 16_700_985; + let views: Vec<(u64, BellEntity)> = nearby + .iter() + .filter_map(|&h| Some((h, entity(h)?))) + .collect(); + let count = views + .iter() + .filter(|(_, e)| closer_to_center_than(pos, e.position, 48.0)) + .count() as i32; + let per = ((count - 21) / -2).clamp(3, 15); + let mut particles = Vec::new(); + let mut glow = Vec::new(); + for (h, e) in &views { + if !raider_in(e, 48.0) { + continue; + } + glow.push(*h); + let (bx, bz) = (f64::from(pos[0]), f64::from(pos[2])); + let dist = ((e.position[0] - bx) * (e.position[0] - bx) + + (e.position[2] - bz) * (e.position[2] - bz)) + .sqrt(); + let x3 = bx + f64::from(0.5f32) + 1.0 / dist * (e.position[0] - bx); + let z3 = bz + f64::from(0.5f32) + 1.0 / dist * (e.position[2] - bz); + for _ in 0..per { + color += 5; + particles.push(([x3, f64::from(pos[1]) + 0.5, z3], color)); + } + } + out.ended = Some((particles, glow)); + self.resonating = false; + } + } + out + } +} + +/// The conduit's `destroyTarget` as the client sees it. +#[derive(Clone, Copy, Debug)] +pub struct ConduitTarget { + pub position: [f64; 3], + pub eye_y: f64, + pub width: f32, + pub height: f32, +} + +/// `ConduitBlockEntity` (client side). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Conduit { + pub tick_count: i32, + pub active_rotation: f32, + pub is_active: bool, + pub is_hunting: bool, + pub effect_blocks: Vec<[i32; 3]>, +} + +/// One nautilus particle: position and velocity. +pub type Particle = ([f64; 3], [f64; 3]); + +impl Conduit { + /// `updateShape`: water all around, then the frame blocks + /// (`BlockTags.CONDUIT_EFFECT_BLOCK`) in the three 5x5 rings. + fn update_shape( + &mut self, + pos: [i32; 3], + is_water: &impl Fn([i32; 3]) -> bool, + is_frame: &impl Fn([i32; 3]) -> bool, + ) -> bool { + self.effect_blocks.clear(); + for ox in -1..=1 { + for oy in -1..=1 { + for oz in -1..=1 { + if !is_water([pos[0] + ox, pos[1] + oy, pos[2] + oz]) { + return false; + } + } + } + } + for ox in -2i32..=2 { + for oy in -2i32..=2 { + for oz in -2i32..=2 { + let (ax, ay, az) = (ox.abs(), oy.abs(), oz.abs()); + if (ax > 1 || ay > 1 || az > 1) + && (ox == 0 && (ay == 2 || az == 2) + || oy == 0 && (ax == 2 || az == 2) + || oz == 0 && (ax == 2 || ay == 2)) + { + let p = [pos[0] + ox, pos[1] + oy, pos[2] + oz]; + if is_frame(p) { + self.effect_blocks.push(p); + } + } + } + } + } + self.effect_blocks.len() >= 16 + } + /// `ConduitBlockEntity.clientTick`: returns the nautilus particles of + /// `animationTick`, drawn from the client level's random. + pub fn client_tick( + &mut self, + pos: [i32; 3], + game_time: i64, + is_water: impl Fn([i32; 3]) -> bool, + is_frame: impl Fn([i32; 3]) -> bool, + target: Option, + random: &mut impl RandomSource, + ) -> Vec { + self.tick_count += 1; + if game_time % 40 == 0 { + self.is_active = self.update_shape(pos, &is_water, &is_frame); + self.is_hunting = self.effect_blocks.len() >= 42; + } + let particles = self.animation_tick(pos, target, random); + if self.is_active { + self.active_rotation += 1.0; + } + particles + } + fn animation_tick( + &self, + pos: [i32; 3], + target: Option, + random: &mut impl RandomSource, + ) -> Vec { + let mut out = Vec::new(); + let hh = f64::from(((self.tick_count + 35) as f32 * 0.1).msin() / 2.0 + 0.5); + let hh = (hh * hh + hh) * f64::from(0.3f32); + let end = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 1.5 + hh, + f64::from(pos[2]) + 0.5, + ]; + for p in &self.effect_blocks { + if random.next_int_bound(50).unwrap_or(1) == 0 { + let dx = -0.5 + random.next_float() + (p[0] - pos[0]) as f32; + let dy = -2.0 + random.next_float() + (p[1] - pos[1]) as f32; + let dz = -0.5 + random.next_float() + (p[2] - pos[2]) as f32; + out.push((end, [f64::from(dx), f64::from(dy), f64::from(dz)])); + } + } + if let Some(t) = target { + let randx = (-0.5 + random.next_float()) * (3.0 + t.width); + let randy = -1.0 + random.next_float() * t.height; + let randz = (-0.5 + random.next_float()) * (3.0 + t.width); + out.push(( + [t.position[0], t.eye_y, t.position[2]], + [f64::from(randx), f64::from(randy), f64::from(randz)], + )); + } + out + } +} + +/// `SkullBlockEntity` animation (client ticker of dragon and piglin heads). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Skull { + pub animating: bool, + pub tick_count: i32, +} +impl Skull { + /// `SkullBlockEntity.animation`. + pub fn tick(&mut self, powered: bool) { + if powered { + self.animating = true; + self.tick_count += 1; + } else { + self.animating = false; + } + } + /// `getAnimation(a)`. + pub fn get_animation(&self, a: f32) -> f32 { + if self.animating { + self.tick_count as f32 + a + } else { + self.tick_count as f32 + } + } +} + +/// `DecoratedPotBlockEntity.WobbleStyle`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WobbleStyle { + Positive, + Negative, +} +impl WobbleStyle { + pub fn duration(self) -> i32 { + match self { + Self::Positive => 7, + Self::Negative => 10, + } + } +} + +/// `DecoratedPotBlockEntity` wobble fields. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct PotWobble { + pub started_at: i64, + pub style: Option, +} +impl PotWobble { + /// `triggerEvent(1, style)`. + pub fn trigger_event(&mut self, event: i32, data: i32, game_time: i64) -> bool { + if event == 1 && (0..2).contains(&data) { + self.started_at = game_time; + self.style = Some(if data == 0 { + WobbleStyle::Positive + } else { + WobbleStyle::Negative + }); + true + } else { + false + } + } + /// `DecoratedPotRenderer.extractRenderState`'s `wobbleProgress`. + pub fn progress(&self, game_time: i64, partial: f32) -> f32 { + match self.style { + Some(style) => { + ((game_time - self.started_at) as f32 + partial) / style.duration() as f32 + } + None => 0.0, + } + } +} + +/// The client ticker a block entity runs (`getTicker` on a client level), +/// or [`Ticker::Pot`] for decorated pots, which keep wobble state unticked. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ticker { + /// `ChestBlockEntity` / `EnderChestBlockEntity.lidAnimateTick`. + Lid, + /// `EnchantingTableBlockEntity.bookAnimationTick`. + Book, + /// `ShulkerBoxBlockEntity.tick`, with the box's facing. + Shulker { + facing: u8, + }, + /// `BellBlockEntity.clientTick`. + Bell, + /// `ConduitBlockEntity.clientTick`. + Conduit, + /// `SkullBlockEntity.animation` (dragon and piglin heads only). + Skull { + powered: bool, + }, + Pot, +} + +/// The [`Ticker`] of a block state, by block name and property lookup. +pub fn ticker(name: &str, prop: impl Fn(&str) -> Option) -> Option { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + let unwaxed = name.strip_prefix("waxed_").unwrap_or(name); + Some(match unwaxed { + "chest" + | "trapped_chest" + | "ender_chest" + | "copper_chest" + | "exposed_copper_chest" + | "weathered_copper_chest" + | "oxidized_copper_chest" => Ticker::Lid, + "enchanting_table" => Ticker::Book, + "bell" => Ticker::Bell, + "conduit" => Ticker::Conduit, + "decorated_pot" => Ticker::Pot, + "dragon_head" | "dragon_wall_head" | "piglin_head" | "piglin_wall_head" => Ticker::Skull { + powered: prop("powered").as_deref() == Some("true"), + }, + n if n.ends_with("shulker_box") => Ticker::Shulker { + facing: prop("facing") + .as_deref() + .and_then(direction_index) + .unwrap_or(1), + }, + _ => return None, + }) +} + +/// The animated block entities of a level, by position. +#[derive(Clone, Debug)] +pub struct BlockEntityAnims { + pub chests: HashMap<[i32; 3], ChestLid>, + pub books: HashMap<[i32; 3], EnchantingBook>, + /// `EnchantingTableBlockEntity.RANDOM`, shared by every table. + pub book_random: LegacyRandom, + pub shulkers: HashMap<[i32; 3], Shulker>, + pub bells: HashMap<[i32; 3], Bell>, + pub conduits: HashMap<[i32; 3], Conduit>, + pub skulls: HashMap<[i32; 3], Skull>, + pub pots: HashMap<[i32; 3], PotWobble>, + /// The client level's random (conduit particles). + pub random: LegacyRandom, + /// [`Ticker`] by block state id (see [`BlockEntityAnims::classify`]). + pub kinds: Vec>, +} +impl Default for BlockEntityAnims { + fn default() -> Self { + Self { + chests: HashMap::new(), + books: HashMap::new(), + book_random: LegacyRandom::new(0x626f6f6b), + shulkers: HashMap::new(), + bells: HashMap::new(), + conduits: HashMap::new(), + skulls: HashMap::new(), + pots: HashMap::new(), + random: LegacyRandom::new(0x6c6576656c), + kinds: Vec::new(), + } + } +} +impl BlockEntityAnims { + /// Fills [`Self::kinds`] for every state of the registry. + pub fn classify(&mut self, registry: &horizon_world::registry::BlockRegistry) { + self.kinds = (0..registry.len() as u32) + .map(|id| { + registry + .state(horizon_world::registry::BlockStateId(id)) + .and_then(|s| ticker(&s.name, |k| s.properties.get(k).cloned())) + }) + .collect(); + } + /// The ticker of a block state. + pub fn ticker(&self, state: u32) -> Option { + self.kinds.get(state as usize).copied().flatten() + } + /// Drops the state of block entities that are gone or changed kind: + /// `present` maps the loaded block entities to their tickers. + pub fn retain_present(&mut self, present: &HashMap<[i32; 3], Ticker>) { + let is = |p: &[i32; 3], f: fn(&Ticker) -> bool| present.get(p).is_some_and(f); + self.chests.retain(|p, _| is(p, |t| *t == Ticker::Lid)); + self.books.retain(|p, _| is(p, |t| *t == Ticker::Book)); + self.shulkers + .retain(|p, _| is(p, |t| matches!(t, Ticker::Shulker { .. }))); + self.bells.retain(|p, _| is(p, |t| *t == Ticker::Bell)); + self.conduits + .retain(|p, _| is(p, |t| *t == Ticker::Conduit)); + self.skulls + .retain(|p, _| is(p, |t| matches!(t, Ticker::Skull { .. }))); + self.pots.retain(|p, _| is(p, |t| *t == Ticker::Pot)); + } + /// Drops the state of positions whose block entity is gone. + pub fn retain(&mut self, keep: impl Fn([i32; 3]) -> bool) { + self.chests.retain(|p, _| keep(*p)); + self.books.retain(|p, _| keep(*p)); + self.shulkers.retain(|p, _| keep(*p)); + self.bells.retain(|p, _| keep(*p)); + self.conduits.retain(|p, _| keep(*p)); + self.skulls.retain(|p, _| keep(*p)); + self.pots.retain(|p, _| keep(*p)); + } + /// `getOpenNess(partial)` of the chest or ender chest at `pos`. + pub fn lid(&self, pos: [i32; 3], partial: f32) -> f32 { + self.chests + .get(&pos) + .map_or(0.0, |l| l.get_openness(partial)) + } + /// The renderer's view of the block entity at `pos`; `sherds` are the + /// pot's decorations (back, left, right, front), when it is a pot. + pub fn block_anim( + &self, + pos: [i32; 3], + game_time: i64, + partial: f32, + sherds: [Option; 4], + ) -> BlockAnim { + let mut anim = BlockAnim { + sherds, + // End gateway ages and cooldowns are not tracked on the client yet: + // gateways render settled (no beam). + gateway: (i64::MAX, 0), + ..BlockAnim::default() + }; + if let Some(b) = self.books.get(&pos) { + anim.book = *b; + } + if let Some(s) = self.shulkers.get(&pos) { + anim.shulker = (s.progress, s.progress_old); + } + if let Some(b) = self.bells.get(&pos) { + anim.bell_ticks = b.ticks; + anim.bell_shake = b + .shaking + .then_some(b.click_direction) + .flatten() + .map(|d| DIRECTIONS[usize::from(d)]); + } + if let Some(c) = self.conduits.get(&pos) { + anim.conduit = (c.tick_count, c.is_active, c.is_hunting, c.active_rotation); + } + if let Some(s) = self.skulls.get(&pos) { + anim.skull = (s.animating, s.tick_count); + } + if let Some(w) = self.pots.get(&pos) + && w.style.is_some() + { + // extractRenderState never copies lastWobbleStyle into the render + // state, so DecoratedPotRenderer.submit always takes the + // non-POSITIVE branch (with the style's own duration). + anim.wobble = Some((false, w.progress(game_time, partial))); + } + anim + } +} diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 1619ccba5..7380bb75e 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -7,10 +7,9 @@ //! the block plus `minecraft_mix_light` with the level's two diffuse lights. use crate::{hud::Rect, mesher::Vertex, world::World}; use glam::{DVec3, Mat4, Quat, Vec3}; -use horizon_core::geometry::Direction; -use horizon_core::{ - geometry::trig::{self, Mth}, - random::{LegacyRandom, RandomSource}, +use horizon_core::geometry::{ + Direction, + trig::{self, Mth}, }; use horizon_world::{ block_render::FaceVisibility, @@ -260,6 +259,8 @@ enum SkullType { enum Kind { None, Chest { + /// The block (`neighbourState.is(state.getBlock())`). + block: String, texture: &'static str, part: ChestPart, y_rot: f32, @@ -333,6 +334,7 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Kind { ChestPart::Right => Some(step(opposite(clockwise(facing)))), }; Kind::Chest { + block: name.to_owned(), texture: match part { ChestPart::Single => texture, ChestPart::Left => left, @@ -524,72 +526,6 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Kind { Kind::None } -/// `EnchantingTableBlockEntity` book animation state. -#[derive(Clone, Copy, Default)] -struct Book { - time: i32, - flip: f32, - o_flip: f32, - flip_t: f32, - flip_a: f32, - open: f32, - o_open: f32, - rot: f32, - o_rot: f32, - t_rot: f32, -} -fn wrap(mut a: f32) -> f32 { - while a >= PI { - a -= 2.0 * PI; - } - while a < -PI { - a += 2.0 * PI; - } - a -} -impl Book { - /// `EnchantingTableBlockEntity.bookAnimationTick`. - fn tick(&mut self, pos: [i32; 3], player: Option<[f64; 3]>, random: &mut LegacyRandom) { - self.o_open = self.open; - self.o_rot = self.rot; - let c = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ]; - let near = player.filter(|p| { - (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2) < 9.0 - }); - if let Some(p) = near { - self.t_rot = (p[2] - c[2]).atan2(p[0] - c[0]) as f32; - self.open += 0.1; - if self.open < 0.5 || random.next_int_bound(40).unwrap_or(1) == 0 { - let old = self.flip_t; - loop { - let a = random.next_int_bound(4).unwrap_or(0); - let b = random.next_int_bound(4).unwrap_or(0); - self.flip_t += (a - b) as f32; - if old != self.flip_t { - break; - } - } - } - } else { - self.t_rot += 0.02; - self.open -= 0.1; - } - self.rot = wrap(self.rot); - self.t_rot = wrap(self.t_rot); - let dir = wrap(self.t_rot - self.rot); - self.rot += dir * 0.4; - self.open = self.open.clamp(0.0, 1.0); - self.time += 1; - self.o_flip = self.flip; - let diff = ((self.flip_t - self.flip) * 0.4).clamp(-0.2, 0.2); - self.flip_a += (diff - self.flip_a) * 0.9; - self.flip += self.flip_a; - } -} /// `BookModel.setupAnim` for `BookModel.State(openness, pageFlip1, pageFlip2)`. fn book_pose(openness: f32, flip1: f32, flip2: f32) -> impl Fn(&str, &mut [f32; 9]) { move |name, p| match name { @@ -749,6 +685,8 @@ pub struct BlockAnim { pub sherds: [Option; 4], /// `DecoratedPotRenderState` wobble style (positive) and progress. pub wobble: Option<(bool, f32)>, + /// `EnchantingTableBlockEntity` book fields. + pub book: crate::block_entity_anim::EnchantingBook, /// `TheEndGatewayBlockEntity` age and teleportCooldown. pub gateway: (i64, i32), } @@ -797,8 +735,6 @@ pub struct Scene<'a> { pub struct BlockEntityRenderer { models: HashMap<&'static str, ModelPart>, kinds: Vec, - books: HashMap<[i32; 3], Book>, - random: LegacyRandom, /// Item id to its `PROVIDES_POTTERY_PATTERN` side texture (`Sheets.DECORATED_POT_MAPPER`). pot_patterns: HashMap, /// `Block.shouldRenderFace` for End gateway faces (its occlusion pair cache needs a lock). @@ -893,8 +829,6 @@ impl BlockEntityRenderer { Self { models, kinds, - books: HashMap::new(), - random: LegacyRandom::new(0x5EED_B00C), pot_patterns: HashMap::new(), visibility: None, } @@ -909,24 +843,6 @@ impl BlockEntityRenderer { fn kind(&self, state: u32) -> &Kind { self.kinds.get(state as usize).unwrap_or(&Kind::None) } - /// Client-side block-entity ticks (enchanting-table books). - pub fn tick<'a>( - &mut self, - blocks: impl Iterator, - player: Option<[f64; 3]>, - ) { - let mut seen = Vec::new(); - for (pos, state) in blocks { - if matches!(self.kind(*state), Kind::EnchantingTable) { - seen.push(*pos); - } - } - self.books.retain(|p, _| seen.contains(p)); - for pos in seen { - let book = self.books.entry(pos).or_default(); - book.tick(pos, player, &mut self.random); - } - } pub fn render<'a>( &self, scene: &Scene, @@ -980,21 +896,65 @@ impl BlockEntityRenderer { pub fn renders(&self, state: u32) -> bool { !matches!(self.kind(state), Kind::None) } - /// Sets an enchanting table's book fields (`EnchantingTableBlockEntity`): - /// time, flip, oFlip, open, oOpen, rot, oRot. - pub fn set_book(&mut self, pos: [i32; 3], time: i32, fields: [f32; 6]) { - let [flip, o_flip, open, o_open, rot, o_rot] = fields; - let book = self.books.entry(pos).or_default(); - *book = Book { - time, - flip, - o_flip, - open, - o_open, - rot, - o_rot, - ..*book + /// `ChestRenderer.extractRenderState`'s openness for the chest of `state` + /// at `pos`: `ChestBlock.combine` (`DoubleBlockCombiner.combineWithNeigbour`) + /// pairs a double half with its neighbour only when that is the same + /// block, the other half and faces the same way; `opennessCombiner` then + /// takes the more open of both. Also returns the paired half's position. + /// `lid` is `getOpenNess(partial)` at a position; non-chests give 0. + pub fn chest_openness_of( + &self, + pos: [i32; 3], + state: u32, + block_at: &dyn Fn([i32; 3]) -> u32, + lid: &dyn Fn([i32; 3]) -> f32, + ) -> (f32, Option<[i32; 3]>) { + self.chest_openness(pos, self.kind(state), block_at, lid) + } + fn chest_openness( + &self, + pos: [i32; 3], + kind: &Kind, + block_at: &dyn Fn([i32; 3]) -> u32, + lid: &dyn Fn([i32; 3]) -> f32, + ) -> (f32, Option<[i32; 3]>) { + let Kind::Chest { + block, + part, + y_rot, + double_with, + .. + } = kind + else { + return (0.0, None); }; + let open = lid(pos); + let Some(d) = double_with else { + return (open, None); + }; + let other = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; + match self.kind(block_at(other)) { + Kind::Chest { + block: other_block, + part: other_part, + y_rot: other_y_rot, + .. + } if other_block == block + && *other_part != ChestPart::Single + && other_part != part + && other_y_rot == y_rot => + { + let other_open = lid(other); + // The right half is the first. + let open = if *part == ChestPart::Right { + crate::block_entity_anim::combined_openness(open, Some(other_open)) + } else { + crate::block_entity_anim::combined_openness(other_open, Some(open)) + }; + (open, Some(other)) + } + _ => (open, None), + } } /// One block entity of `state` drawn under `base` (minecart contents). pub fn render_state( @@ -1089,7 +1049,7 @@ impl BlockEntityRenderer { texture, part, y_rot, - double_with, + .. } => { let model = match part { ChestPart::Single => "chest", @@ -1099,22 +1059,24 @@ impl BlockEntityRenderer { let (Some(model), Some(_)) = (self.models.get(model), sprite(texture)) else { return; }; - // ChestBlock.opennessCombiner / BrightnessCombiner: both halves. - let mut open = (scene.lid)(pos); + let (open, other) = self.chest_openness( + pos, + kind, + &|p| scene.world.block(p[0], p[1], p[2]).0, + scene.lid, + ); + // BrightnessCombiner: the brighter of both halves, per channel. let mut packed = packed; - if let Some(d) = double_with { - let other = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; - open = open.max((scene.lid)(other)); + if let Some(other) = other { let l = scene.world.light(other[0], other[1], other[2]); packed = (packed >> 4).max(l >> 4) << 4 | (packed & 15).max(l & 15); } - let open = 1.0 - (1.0 - open).powi(3); let m = base * around( Mat4::from_rotation_y((-y_rot).to_radians()), Vec3::new(0.5, 0.0, 0.5), ); - let lid = -(open * PI / 2.0); + let lid = crate::block_entity_anim::chest_lid_x_rot(open); let adjust = move |name: &str, p: &mut [f32; 9]| { if name == "lid" || name == "lock" { p[3] = lid; @@ -1459,21 +1421,18 @@ impl BlockEntityRenderer { ) else { return; }; - let b = self.books.get(&pos).copied().unwrap_or_default(); - let a = scene.partial; - let flip = b.o_flip + (b.flip - b.o_flip) * a; - let open = b.o_open + (b.open - b.o_open) * a; - let time = b.time as f32 + a; - let y_rot = b.o_rot + wrap(b.rot - b.o_rot) * a; + // EnchantTableRenderer.extractRenderState and submit. + let b = (scene.anim)(pos).book.render(scene.partial); let m = base * Mat4::from_translation(Vec3::new(0.5, 0.75, 0.5)) - * Mat4::from_translation(Vec3::new(0.0, 0.1 + (time * 0.1).msin() * 0.01, 0.0)) - * Mat4::from_rotation_y(-y_rot) + * Mat4::from_translation(Vec3::new( + 0.0, + 0.1 + (b.time * 0.1).msin() * 0.01, + 0.0, + )) + * Mat4::from_rotation_y(-b.y_rot) * Mat4::from_rotation_z(80f32.to_radians()); - let ff1 = (frac(flip + 0.25) * 1.6 - 0.3).clamp(0.0, 1.0); - let ff2 = (frac(flip + 0.75) * 1.6 - 0.3).clamp(0.0, 1.0); - // BookModel.State.forAnimation. - let openness = ((time * 0.02).msin() * 0.1 + 1.25) * open; + let (openness, ff1, ff2) = (b.openness, b.page_flip1, b.page_flip2); draw_part(model, "root", m, &book_pose(openness, ff1, ff2), paint, out); } Kind::Lectern { y_rot } => { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0e7f55c43..e7b1a14a6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -6,6 +6,7 @@ mod allays; mod armor_stands; mod banners; mod beacon; +mod block_entity_anims; mod blockctl; mod boats; mod books; @@ -612,7 +613,8 @@ struct Game<'a> { raiding: raids::Raiding, attack_ticks: u32, last_hurt_by_player: HashSet, - chest_open: HashMap<(i32, i32, i32), (f32, f32)>, + /// Client-ticked block-entity animation state (`game/block_entity_anims.rs`). + be_anims: horizon_client::block_entity_anim::BlockEntityAnims, /// Item being used (eaten): hotbar slot and ticks used. using: Option<(usize, u32)>, /// Camera.oldFovModifier / fovModifier. @@ -1592,6 +1594,9 @@ impl Game<'_> { state, kind: "shrieker_respond", } => self.shrieker_block_event(pos, state), + LevelEvent::BlockEntityEvent { pos, a, b, .. } => { + self.block_entity_event([pos.x, pos.y, pos.z], a, b) + } LevelEvent::GrowTree { .. } | LevelEvent::PlaceFeature { .. } | LevelEvent::BlockEvent { .. } => {} @@ -1616,6 +1621,7 @@ impl Game<'_> { self.craft_size = 3; } else if &*name == "minecraft:ender_chest" { self.open_ender_chest(key); + self.container_opener_event(key, true); let at = [ f64::from(key.0) + 0.5, f64::from(key.1) + 0.5, @@ -1628,9 +1634,12 @@ impl Game<'_> { self.world.block_entities.entry(key).or_insert_with(|| { BlockEntity::for_block(&name).unwrap_or(BlockEntity::Chest(Vec::new())) }); + } else if storage::is_shulker_box(&name) && !self.shulker_can_open(pos) { + // ShulkerBoxBlock.canOpen: the lid has no room; nothing opens. } else if let Some(entity) = BlockEntity::for_block(&name) { self.world.block_entities.entry(key).or_insert(entity); self.container = Some(key); + self.container_opener_event(key, true); self.post_block_game_event( "minecraft:container_open", [key.0, key.1, key.2], @@ -1867,6 +1876,7 @@ impl Game<'_> { let name = facts.name.clone(); self.release_contents(pos, entity, &name); if self.container == Some((pos[0], pos[1], pos[2])) { + self.container_opener_event((pos[0], pos[1], pos[2]), false); self.container = None; self.screen = Screen::Playing; } @@ -2756,17 +2766,10 @@ impl Game<'_> { self.tick_sculk()?; self.tick_brewing_stands()?; } - if let Some(r) = &self.renderer { - let eye = self.player.as_ref().map(|p| { - [ - p.position.x, - p.position.y + f64::from(self.eye), - p.position.z, - ] - }); - self.res.block_entity_render.tick(r.block_entities(), eye); - } if running { + // ClientLevel.tickBlockEntities (not while paused or frozen): + // chest lids, books, shulker boxes, bells, conduits, heads. + self.tick_block_entity_anims(); self.tick_particles(); } if self.right && self.use_delay == 0 && self.screen == Screen::Playing { @@ -3477,6 +3480,7 @@ impl Game<'_> { } self.craft_size = 2; if let Some(key) = self.container.take() { + self.container_opener_event(key, false); self.post_block_game_event( "minecraft:container_close", [key.0, key.1, key.2], @@ -4122,14 +4126,8 @@ impl Game<'_> { } // Block entities (BlockEntityRenderers): chests, shulker boxes, banners, skulls... if let Some(r) = &self.renderer { - let lid = |p: [i32; 3]| { - let (prev, cur) = self - .chest_open - .get(&(p[0], p[1], p[2])) - .copied() - .unwrap_or((0.0, 0.0)); - prev + (cur - prev) * alpha as f32 - }; + let lid = |p: [i32; 3]| self.chest_lid(p, alpha as f32); + let anim = |p: [i32; 3]| self.block_anim(p, alpha as f32); let (view_yaw, view_pitch) = if self.camera_type == perspective::CameraType::ThirdPersonFront { (self.yaw + 180.0, -self.pitch) @@ -4145,12 +4143,7 @@ impl Game<'_> { -view_pitch.to_radians(), 0.0, ), - // The client does not track End gateway ages and cooldowns yet: - // gateways render as settled (no beam). - anim: &|_| horizon_client::block_entity_render::BlockAnim { - gateway: (i64::MAX, 0), - ..Default::default() - }, + anim: &anim, texts: None, partial: alpha as f32, game_time: self.world.game_time, @@ -4616,20 +4609,6 @@ impl Game<'_> { self.tick_jukeboxes(); self.tick_beacons(); self.tick_creaking_hearts()?; - // ChestLidController: 0.1 per tick towards open/closed. - if let Some(key) = self.container { - self.chest_open.entry(key).or_insert((0.0, 0.0)); - } - let open = self.container; - self.chest_open.retain(|k, (prev, cur)| { - *prev = *cur; - *cur = if Some(*k) == open { - (*cur + 0.1).min(1.0) - } else { - (*cur - 0.1).max(0.0) - }; - *cur > 0.0 || *prev > 0.0 - }); let mut lit_changes = Vec::new(); for (pos, entity) in self.world.block_entities.iter_mut() { if let BlockEntity::Furnace(f) = entity @@ -5014,6 +4993,11 @@ impl Game<'_> { self.restore_effects(); self.mining = None; self.container = None; + let kinds = std::mem::take(&mut self.be_anims.kinds); + self.be_anims = horizon_client::block_entity_anim::BlockEntityAnims { + kinds, + ..Default::default() + }; self.carried = None; self.using = None; self.screen = Screen::Playing; @@ -8056,7 +8040,11 @@ pub fn run() -> Result<()> { raiding: Default::default(), attack_ticks: 100, last_hurt_by_player: HashSet::new(), - chest_open: HashMap::new(), + be_anims: { + let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); + anims.classify(registry_owner.registry); + anims + }, using: None, view: Default::default(), limiter: horizon_client::window::FramerateLimiter::new(0), diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs new file mode 100644 index 000000000..d1597a7a3 --- /dev/null +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -0,0 +1,291 @@ +//! The client side of animated block entities (`horizon_client::block_entity_anim`): +//! their client tickers (`Level.tickBlockEntities` on the client level) and +//! the block events that drive them (`ClientboundBlockEventPacket` reaching +//! `BlockEntity.triggerEvent`). The renderer reads the resulting state through +//! [`Game::block_anim`] and [`Game::chest_lid`]. +use super::Game; +use horizon_client::{ + block_entity_anim::{BellEntity, Shulker, ShulkerStatus, Ticker}, + block_entity_render::BlockAnim, + collisions::{SceneCollisions, no_collision_empty}, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::geometry::{Aabb, Vec3}; +use std::collections::HashMap; + +/// The handle of the local player among a bell's gathered entities. +const PLAYER: u64 = u64::MAX; + +impl Game<'_> { + /// `BlockEntity.triggerEvent(a, b)` on the client copy of the block entity at `pos`. + pub(super) fn block_entity_event(&mut self, pos: [i32; 3], a: i32, b: i32) { + let state = self.world.block(pos[0], pos[1], pos[2]).0; + let time = self.world.game_time; + match self.be_anims.ticker(state) { + Some(Ticker::Lid) => { + self.be_anims + .chests + .entry(pos) + .or_default() + .trigger_event(a, b); + } + Some(Ticker::Shulker { .. }) => { + self.be_anims + .shulkers + .entry(pos) + .or_default() + .trigger_event(a, b); + } + Some(Ticker::Bell) => { + let gathered = self.bell_gather(pos); + self.be_anims + .bells + .entry(pos) + .or_default() + .trigger_event(a, b, time, || gathered); + } + Some(Ticker::Pot) => { + self.be_anims + .pots + .entry(pos) + .or_default() + .trigger_event(a, b, time); + } + _ => {} + } + } + /// A player opened (`open`) or closed the container at `key`: the opener + /// count block event (`ContainerOpenersCounter` / `ShulkerBoxBlockEntity` + /// `startOpen`/`stopOpen`) for chests, ender chests and shulker boxes, + /// on both halves of a double chest (`CompoundContainer`). + pub(super) fn container_opener_event(&mut self, key: (i32, i32, i32), open: bool) { + // Spectators never count as openers. + if self.spectator() { + return; + } + let pos = [key.0, key.1, key.2]; + let state = self.world.block(pos[0], pos[1], pos[2]).0; + match self.be_anims.ticker(state) { + Some(Ticker::Lid) => { + let count = i32::from(open); + self.block_entity_event(pos, 1, count); + if let Some(other) = self.chest_other_half(key) { + self.block_entity_event([other.0, other.1, other.2], 1, count); + } + } + Some(Ticker::Shulker { .. }) => { + let shulker = self.be_anims.shulkers.entry(pos).or_default(); + let (count, _) = if open { + shulker.start_open() + } else { + shulker.stop_open() + }; + self.block_entity_event(pos, 1, count); + } + _ => {} + } + } + /// `BellBlockEntity.updateEntities`: the living entities whose bounding + /// box meets the bell's block box inflated by 48. + fn bell_gather(&self, pos: [i32; 3]) -> Vec { + let area = Aabb::new( + Vec3::new( + f64::from(pos[0]) - 48.0, + f64::from(pos[1]) - 48.0, + f64::from(pos[2]) - 48.0, + ), + Vec3::new( + f64::from(pos[0]) + 49.0, + f64::from(pos[1]) + 49.0, + f64::from(pos[2]) + 49.0, + ), + ); + let mut out = Vec::new(); + if self + .player_view() + .is_some_and(|p| p.bounds.intersects(area)) + { + out.push(PLAYER); + } + for m in &self.mobs { + if !m.removed && m.bounds().intersects(area) { + out.push(u64::from(m.id)); + } + } + out + } + /// `ShulkerBoxBlock.canOpen`: a closed box opens only when its lid has + /// room to rise (`level.noCollision` of the half-open lid box). + pub(super) fn shulker_can_open(&self, pos: [i32; 3]) -> bool { + let state = self.world.block(pos[0], pos[1], pos[2]).0; + let Some(Ticker::Shulker { facing }) = self.be_anims.ticker(state) else { + return true; + }; + let closed = self + .be_anims + .shulkers + .get(&pos) + .is_none_or(|s| s.status == ShulkerStatus::Closed); + if !closed { + return true; + } + let b = Shulker::lid_box(pos, facing); + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + }; + no_collision_empty( + &mut scene, + Aabb::new(Vec3::new(b[0], b[1], b[2]), Vec3::new(b[3], b[4], b[5])), + ) + } + /// The client tickers of the loaded animated block entities, once per + /// client tick (`ClientLevel.tickBlockEntities`). + pub(super) fn tick_block_entity_anims(&mut self) { + let Some(r) = &self.renderer else { + return; + }; + let present: HashMap<[i32; 3], Ticker> = r + .block_entities() + .filter_map(|(p, s)| Some((*p, self.be_anims.ticker(*s)?))) + .collect(); + self.be_anims.retain_present(&present); + let players: Vec<[f64; 3]> = match &self.player { + Some(p) if !self.spectator() => vec![[p.position.x, p.position.y, p.position.z]], + _ => Vec::new(), + }; + let raiders = self + .res + .stations + .enchantments + .entity_tags + .get("minecraft:raiders") + .cloned() + .unwrap_or_default(); + let frames = self + .res + .items + .block_tags + .get("minecraft:conduit_effect_block") + .cloned() + .unwrap_or_default(); + let mut positions: Vec<([i32; 3], Ticker)> = present.into_iter().collect(); + positions.sort_unstable_by_key(|(p, _)| *p); + for (pos, ticker) in positions { + match ticker { + Ticker::Lid => self.be_anims.chests.entry(pos).or_default().tick(), + Ticker::Book => { + let anims = &mut self.be_anims; + anims + .books + .entry(pos) + .or_default() + .tick(pos, &players, &mut anims.book_random); + } + Ticker::Shulker { facing } => { + // The lid's push of entities in its way (moveCollidedEntities) + // and the neighbour updates are left to the level. + self.be_anims + .shulkers + .entry(pos) + .or_default() + .tick(pos, facing); + } + Ticker::Skull { powered } => { + self.be_anims.skulls.entry(pos).or_default().tick(powered); + } + Ticker::Bell => { + let player = self.player_view().map(|p| BellEntity { + position: [p.position.x, p.position.y, p.position.z], + alive: p.alive, + raider: false, + }); + let mobs = &self.mobs; + let entity = |h: u64| { + if h == PLAYER { + return player; + } + let m = mobs.iter().find(|m| u64::from(m.id) == h)?; + Some(BellEntity { + position: [m.position.x, m.position.y, m.position.z], + alive: m.alive() && !m.removed, + raider: raiders.contains(&m.kind.id), + }) + }; + let tick = self + .be_anims + .bells + .entry(pos) + .or_default() + .tick(pos, entity); + let centre = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + if tick.resonate { + // The server's copy plays the resonance for everyone. + self.audio + .play("minecraft:block.bell.resonate", Some(centre), 1.0, 1.0); + } + if let Some((particles, glow)) = tick.ended { + for (p, color) in particles { + // ColorParticleOption.create(ENTITY_EFFECT, color): ARGB. + let c = color as u32; + let channel = |shift: u32| ((c >> shift) & 255) as f32 / 255.0; + let options = ParticleOptions { + color: [channel(16), channel(8), channel(0), channel(24)], + ..ParticleOptions::simple(ParticleType::EntityEffect) + }; + self.particles.add(&options, p, [0.0; 3]); + } + // makeRaidersGlow. + for m in self.mobs.iter_mut() { + if glow.contains(&u64::from(m.id)) { + m.add_effect("minecraft:glowing", 60, 0); + } + } + } + } + Ticker::Conduit => { + let world = &self.world; + let facts = &self.res.facts; + let registry = self.res.assets.registry; + let is_water = |p: [i32; 3]| { + facts.get(world.block(p[0], p[1], p[2])).fluid + == horizon_client::blocks::Fluid::Water + }; + let is_frame = |p: [i32; 3]| { + registry + .state(world.block(p[0], p[1], p[2])) + .is_some_and(|s| frames.contains(&s.name)) + }; + let time = world.game_time; + let anims = &mut self.be_anims; + let particles = anims.conduits.entry(pos).or_default().client_tick( + pos, + time, + is_water, + is_frame, + None, + self.particles.random(), + ); + let nautilus = ParticleOptions::simple(ParticleType::Nautilus); + for (p, v) in particles { + self.particles.add(&nautilus, p, v); + } + } + Ticker::Pot => {} + } + } + } + /// The renderer's view of the block entity at `pos`. + pub(super) fn block_anim(&self, pos: [i32; 3], partial: f32) -> BlockAnim { + self.be_anims + .block_anim(pos, self.world.game_time, partial, Default::default()) + } + /// `ChestLidController.getOpenness(partial)` at `pos`. + pub(super) fn chest_lid(&self, pos: [i32; 3], partial: f32) -> f32 { + self.be_anims.lid(pos, partial) + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 53685eeb2..874cecf9f 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -11,6 +11,7 @@ pub mod audio; pub mod auto_jump; pub mod banner; pub mod biome; +pub mod block_entity_anim; pub mod block_entity_nbt; pub mod block_entity_render; pub mod block_transform; diff --git a/crates/horizon-world/examples/block_update_fixture.rs b/crates/horizon-world/examples/block_update_fixture.rs index 9590c90bb..6d0fd2680 100644 --- a/crates/horizon-world/examples/block_update_fixture.rs +++ b/crates/horizon-world/examples/block_update_fixture.rs @@ -367,6 +367,8 @@ fn main() -> Result<(), Box> { LevelEvent::BlockEvent { kind, .. } => { let _ = writeln!(result, "X {kind}"); } + // The client copy of a bell's ring: no level change. + LevelEvent::BlockEntityEvent { .. } => {} LevelEvent::GrowTree { .. } => { let _ = writeln!(result, "X grow_tree"); } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 5192ea0aa..1c9e670fc 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -259,6 +259,16 @@ pub enum LevelEvent { state: BlockStateId, kind: &'static str, }, + /// A queued block event that reached a block entity + /// (`BaseEntityBlock.triggerEvent`): the client's copy runs + /// `BlockEntity.triggerEvent(a, b)` (`ClientboundBlockEventPacket`), as + /// for a bell's ring (event 1, the struck direction). + BlockEntityEvent { + pos: BlockPos, + state: BlockStateId, + a: i32, + b: i32, + }, /// A player-side effect of [`Behaviours::use_without_item`]. Player { pos: BlockPos, diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index 299959e0b..fa5b7989c 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -114,6 +114,13 @@ impl Sim<'_, L> { } else if data.is(super::classes::Class::Note) { self.note_trigger_event(pos, state); true + } else if data.is(super::classes::Class::Bell) { + // BellBlockEntity.triggerEvent handles event 1; the server + // broadcasts handled events to the clients. + if a == 1 { + self.emit(LevelEvent::BlockEntityEvent { pos, state, a, b }); + } + a == 1 } else { false } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java new file mode 100644 index 000000000..5c8c899db --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockEntityAnimOracle.java @@ -0,0 +1,362 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import java.util.function.Predicate; +import net.minecraft.client.model.object.book.BookModel; +import net.minecraft.client.model.object.chest.ChestModel; +import net.minecraft.client.renderer.blockentity.*; +import net.minecraft.client.renderer.blockentity.state.*; +import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.core.*; +import net.minecraft.core.particles.ColorParticleOption; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.particles.ParticleTypes; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.sounds.SoundSource; +import net.minecraft.util.RandomSource; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.entity.*; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.phys.*; + +/** + * Original oracle for the client-ticked animation state of chests and ender + * chests (ChestLidController), enchanting table books, shulker boxes, bells, + * conduits, skulls and decorated pots. Each case builds the real + * vanilla block entity on a stand-in client level (scripted blocks, entities, + * game time and a seeded LegacyRandomSource), then per step applies the + * scripted block event (triggerEvent), runs the block entity's own client + * ticker (lidAnimateTick, bookAnimationTick with the class's static RANDOM + * reseeded, ShulkerBoxBlockEntity.tick, BellBlockEntity.clientTick, + * ConduitBlockEntity.clientTick, SkullBlockEntity.animation; pots have none) + * and runs the real renderer's extractRenderState at the step's partial tick. + * It prints the block entity's fields, the level calls the tick made + * (neighbour updates, entity queries, sounds, particles) and the render state. + * + * Usage: VanillaBlockEntityAnimOracle inputs.jsonl output.txt + */ +public final class VanillaBlockEntityAnimOracle { + static Object unsafe; + static Method allocate, putObject, objectFieldOffset; + + @SuppressWarnings("unchecked") + static T make(Class type) throws Exception { return (T) allocate.invoke(unsafe, type); } + + static void put(Object target, Class owner, String name, Object value) throws Exception { + Field f = owner.getDeclaredField(name); + long offset = (long) objectFieldOffset.invoke(unsafe, f); + putObject.invoke(unsafe, target, offset, value); + } + + static Field field(Class owner, String name) throws Exception { + Field f = owner.getDeclaredField(name); + f.setAccessible(true); + return f; + } + + static String f(float v) { return String.format("%08x", Float.floatToRawIntBits(v)); } + static String d(double v) { return String.format("%016x", Double.doubleToRawLongBits(v)); } + static String box(AABB b) { return d(b.minX) + " " + d(b.minY) + " " + d(b.minZ) + " " + d(b.maxX) + " " + d(b.maxY) + " " + d(b.maxZ); } + + static BlockState parse(String s) throws Exception { + return BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, s, false).blockState(); + } + + /** A living entity the case places: a Pillager whose type field says raider or not. */ + static final class Mob extends net.minecraft.world.entity.monster.illager.Pillager { + boolean living; + Mob() { super(null, null); } + @Override public boolean isAlive() { return !this.isRemoved() && this.living; } + } + + /** A player the case places: position and game mode (spectators are skipped). */ + static final class Gamer extends Player { + GameType mode; + Gamer() { super(null, null); } + @Override public GameType gameMode() { return mode; } + @Override public net.minecraft.world.item.component.ResolvableProfile getProfile() { return null; } + } + + static Gamer gamer(JsonObject e) throws Exception { + Gamer g = make(Gamer.class); + g.mode = e.has("spectator") && e.get("spectator").getAsBoolean() ? GameType.SPECTATOR : GameType.SURVIVAL; + var p = e.getAsJsonArray("pos"); + put(g, Entity.class, "position", new Vec3(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble())); + return g; + } + + /** The stand-in client level. */ + static final class World extends Level { + World() { super(null, null, null, null, false, false, 0L, 0); } + long time; + Map blocks = new HashMap<>(); + List mobs = new ArrayList<>(); + List gamers = new ArrayList<>(); + Map entities = new HashMap<>(); + RandomSource random; + StringBuilder log = new StringBuilder(); + + @Override public long getGameTime() { return time; } + @Override public boolean isClientSide() { return true; } + @Override public BlockState getBlockState(BlockPos p) { return blocks.getOrDefault(p.immutable(), Blocks.AIR.defaultBlockState()); } + @Override public FluidState getFluidState(BlockPos p) { return getBlockState(p).getFluidState(); } + @Override public int getBrightness(LightLayer layer, BlockPos p) { return 0; } + @Override public RandomSource getRandom() { return random; } + @Override public BlockEntity getBlockEntity(BlockPos p) { return entities.get(p.immutable()); } + @Override public void updateNeighborsAt(BlockPos p, Block block) { log.append(" neighbors"); } + @Override public void neighborShapeChanged(Direction dir, BlockPos p, BlockPos from, BlockState state, int flags, int limit) {} + @Override public List getEntities(Entity except, AABB bb) { log.append(" push ").append(box(bb)); return List.of(); } + @SuppressWarnings("unchecked") + @Override public List getEntitiesOfClass(Class type, AABB bb, Predicate selector) { + log.append(" gather ").append(box(bb)); + List out = new ArrayList<>(); + for (Mob m : mobs) if (type.isInstance(m) && bb.contains(m.position())) out.add((T) m); + return out; + } + @Override public void playSound(Entity except, BlockPos p, SoundEvent s, SoundSource source, float volume, float pitch) { + log.append(" sound ").append(BuiltInRegistries.SOUND_EVENT.getKey(s)); + } + @Override public void addParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) { + log.append(" particle ").append(BuiltInRegistries.PARTICLE_TYPE.getKey(o.getType())); + if (o instanceof ColorParticleOption c) { + try { log.append(" ").append(field(ColorParticleOption.class, "color").getInt(c)); } catch (Exception e) { throw new RuntimeException(e); } + } + log.append(" ").append(d(x)).append(" ").append(d(y)).append(" ").append(d(z)) + .append(" ").append(d(xd)).append(" ").append(d(yd)).append(" ").append(d(zd)); + } +@Override public net.minecraft.world.clock.ClockManager clockManager(){throw new UnsupportedOperationException();} +@Override public void destroyBlockProgress(int p0,net.minecraft.core.BlockPos p1,int p2){throw new UnsupportedOperationException();} +@Override public java.util.Collection dragonParts(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes(){throw new UnsupportedOperationException();} +@Override public void explode(net.minecraft.world.entity.Entity p0,net.minecraft.world.damagesource.DamageSource p1,net.minecraft.world.level.ExplosionDamageCalculator p2,double p3,double p4,double p5,float p6,boolean p7,net.minecraft.world.level.Level.ExplosionInteraction p8,net.minecraft.core.particles.ParticleOptions p9,net.minecraft.core.particles.ParticleOptions p10,net.minecraft.util.random.WeightedList p11,net.minecraft.core.Holder p12){throw new UnsupportedOperationException();} +@Override public void gameEvent(net.minecraft.core.Holder p0,net.minecraft.world.phys.Vec3 p1,net.minecraft.world.level.gameevent.GameEvent.Context p2){throw new UnsupportedOperationException();} +@Override public java.lang.String gatherChunkSourceStats(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.ticks.LevelTickAccess getBlockTicks(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.level.chunk.ChunkSource getChunkSource(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.level.entity.LevelEntityGetter getEntities(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.entity.Entity getEntity(int p0){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.ticks.LevelTickAccess getFluidTicks(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.level.saveddata.maps.MapItemSavedData getMapData(net.minecraft.world.level.saveddata.maps.MapId p0){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.level.storage.LevelData.RespawnData getRespawnData(){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.scores.Scoreboard getScoreboard(){throw new UnsupportedOperationException();} +@Override public int getSeaLevel(){throw new UnsupportedOperationException();} +@Override public net.minecraft.core.Holder getUncachedNoiseBiome(int p0,int p1,int p2){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.level.border.WorldBorder getWorldBorder(){throw new UnsupportedOperationException();} +@Override public void levelEvent(net.minecraft.world.entity.Entity p0,int p1,net.minecraft.core.BlockPos p2,int p3){throw new UnsupportedOperationException();} +@Override public void playSeededSound(net.minecraft.world.entity.Entity p0,net.minecraft.world.entity.Entity p1,net.minecraft.core.Holder p2,net.minecraft.sounds.SoundSource p3,float p4,float p5,long p6){throw new UnsupportedOperationException();} +@Override public void playSeededSound(net.minecraft.world.entity.Entity p0,double p1,double p2,double p3,net.minecraft.core.Holder p4,net.minecraft.sounds.SoundSource p5,float p6,float p7,long p8){throw new UnsupportedOperationException();} +@Override public java.util.List players(){return gamers;} +@Override public net.minecraft.world.item.crafting.RecipeAccess recipeAccess(){throw new UnsupportedOperationException();} +@Override public void sendBlockUpdated(net.minecraft.core.BlockPos p0,net.minecraft.world.level.block.state.BlockState p1,net.minecraft.world.level.block.state.BlockState p2,int p3){throw new UnsupportedOperationException();} +@Override public void setRespawnData(net.minecraft.world.level.storage.LevelData.RespawnData p0){throw new UnsupportedOperationException();} +@Override public net.minecraft.world.TickRateManager tickRateManager(){throw new UnsupportedOperationException();} + } + + static Mob mob(JsonObject e, World world) throws Exception { + Mob m = make(Mob.class); + m.living = !e.has("alive") || e.get("alive").getAsBoolean(); + put(m, Entity.class, "type", e.has("raider") && e.get("raider").getAsBoolean() ? EntityTypes.PILLAGER : EntityTypes.COW); + var p = e.getAsJsonArray("pos"); + put(m, Entity.class, "position", new Vec3(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble())); + if (e.has("removed") && e.get("removed").getAsBoolean()) put(m, Entity.class, "removalReason", Entity.RemovalReason.KILLED); + if (e.has("width")) { + put(m, Entity.class, "dimensions", EntityDimensions.scalable(e.get("width").getAsFloat(), e.get("height").getAsFloat())); + Field eye = field(Entity.class, "eyeHeight"); + eye.setFloat(m, e.get("eye").getAsFloat()); + } + return m; + } + + static ChestModel CHEST_MODEL; + + static void tickLid(World world, BlockEntity e) { + if (e instanceof ChestBlockEntity c) ChestBlockEntity.lidAnimateTick(world, c.getBlockPos(), c.getBlockState(), c); + else if (e instanceof EnderChestBlockEntity c) EnderChestBlockEntity.lidAnimateTick(world, c.getBlockPos(), c.getBlockState(), c); + } + + static String lid(BlockEntity e) throws Exception { + if (!(e instanceof ChestBlockEntity) && !(e instanceof EnderChestBlockEntity)) return "-"; + Class owner = e instanceof ChestBlockEntity ? ChestBlockEntity.class : EnderChestBlockEntity.class; + Object lid = field(owner, "chestLidController").get(e); + return field(ChestLidController.class, "shouldBeOpen").getBoolean(lid) + + " " + f(field(ChestLidController.class, "openness").getFloat(lid)) + + " " + f(field(ChestLidController.class, "oOpenness").getFloat(lid)); + } + + static String run(JsonObject c) throws Exception { + World world = make(World.class); + world.blocks = new HashMap<>(); + world.mobs = new ArrayList<>(); + world.gamers = new ArrayList<>(); + world.entities = new HashMap<>(); + world.log = new StringBuilder(); + world.random = RandomSource.create(c.has("seed") ? c.get("seed").getAsLong() : 0L); + var pa = c.getAsJsonArray("pos"); + BlockPos pos = new BlockPos(pa.get(0).getAsInt(), pa.get(1).getAsInt(), pa.get(2).getAsInt()); + BlockState state = parse(c.get("block").getAsString()); + world.blocks.put(pos, state); + if (c.has("world")) { + for (var e : c.getAsJsonObject("world").entrySet()) { + String[] xyz = e.getKey().split(","); + world.blocks.put(pos.offset(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]), Integer.parseInt(xyz[2])), parse(e.getValue().getAsString())); + } + } + if (c.has("entities")) for (var e : c.getAsJsonArray("entities")) world.mobs.add(mob(e.getAsJsonObject(), world)); + var be = ((EntityBlock) state.getBlock()).newBlockEntity(pos, state); + be.setLevel(world); + world.entities.put(pos, be); + // The other half of a double chest (or whatever block sits there). + BlockEntity partner = null; + if (c.has("partner")) { + String[] xyz = c.get("partner").getAsString().split(","); + BlockPos at = pos.offset(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]), Integer.parseInt(xyz[2])); + BlockState there = world.getBlockState(at); + if (there.getBlock() instanceof EntityBlock eb) { + partner = eb.newBlockEntity(at, there); + partner.setLevel(world); + world.entities.put(at, partner); + } + } + if (c.has("players")) for (var e : c.getAsJsonArray("players")) world.gamers.add(gamer(e.getAsJsonObject())); + if (be instanceof EnchantingTableBlockEntity) { + ((RandomSource) field(EnchantingTableBlockEntity.class, "RANDOM").get(null)).setSeed(c.get("seed").getAsLong()); + } + if (c.has("target") && be instanceof ConduitBlockEntity) { + put(be, ConduitBlockEntity.class, "destroyTarget", EntityReference.of(mob(c.getAsJsonObject("target"), world))); + } + StringBuilder out = new StringBuilder(); + for (var stepElement : c.getAsJsonArray("steps")) { + var step = stepElement.getAsJsonObject(); + world.time = step.get("time").getAsLong(); + world.log.setLength(0); + if (step.has("set")) { + for (var e : step.getAsJsonObject("set").entrySet()) { + String[] xyz = e.getKey().split(","); + world.blocks.put(pos.offset(Integer.parseInt(xyz[0]), Integer.parseInt(xyz[1]), Integer.parseInt(xyz[2])), parse(e.getValue().getAsString())); + } + } + if (step.has("players")) { + world.gamers.clear(); + for (var e : step.getAsJsonArray("players")) world.gamers.add(gamer(e.getAsJsonObject())); + } + if (step.has("event")) { + var ev = step.getAsJsonArray("event"); + boolean handled = be.triggerEvent(ev.get(0).getAsInt(), ev.get(1).getAsInt()); + world.log.append(" event ").append(handled); + } + if (step.has("partnerEvent") && partner != null) { + var ev = step.getAsJsonArray("partnerEvent"); + boolean handled = partner.triggerEvent(ev.get(0).getAsInt(), ev.get(1).getAsInt()); + world.log.append(" partner event ").append(handled); + } + float partial = step.get("partial").getAsFloat(); + String fields; + if (be instanceof ChestBlockEntity || be instanceof EnderChestBlockEntity) { + tickLid(world, be); + if (partner != null) tickLid(world, partner); + ChestRenderer renderer = make(ChestRenderer.class); + var r = new net.minecraft.client.renderer.blockentity.state.ChestRenderState(); + @SuppressWarnings({"unchecked", "rawtypes"}) + ChestRenderer raw = renderer; + raw.extractRenderState(be, r, partial, Vec3.ZERO, null); + float open = r.open; + // ChestRenderer.submit, then ChestModel.setupAnim. + open = 1.0F - open; + open = 1.0F - open * open * open; + CHEST_MODEL.setupAnim(open); + fields = lid(be) + " partner " + (partner == null ? "none" : lid(partner)) + + " render " + f(r.open) + " " + f(((net.minecraft.client.model.geom.ModelPart) field(ChestModel.class, "lid").get(CHEST_MODEL)).xRot); + } else if (be instanceof EnchantingTableBlockEntity t) { + EnchantingTableBlockEntity.bookAnimationTick(world, pos, state, t); + var r = new net.minecraft.client.renderer.blockentity.state.EnchantTableRenderState(); + make(EnchantTableRenderer.class).extractRenderState(t, r, partial, Vec3.ZERO, null); + // EnchantTableRenderer.submit's book state. + float ff1 = Mth.frac(r.flip + 0.25F) * 1.6F - 0.3F; + float ff2 = Mth.frac(r.flip + 0.75F) * 1.6F - 0.3F; + var book = BookModel.State.forAnimation(r.time, Mth.clamp(ff1, 0.0F, 1.0F), Mth.clamp(ff2, 0.0F, 1.0F), r.open); + fields = t.time + " " + f(t.flip) + " " + f(t.oFlip) + " " + f(t.flipT) + " " + f(t.flipA) + + " " + f(t.open) + " " + f(t.oOpen) + " " + f(t.rot) + " " + f(t.oRot) + " " + f(t.tRot) + + " render " + f(r.flip) + " " + f(r.open) + " " + f(r.time) + " " + f(r.yRot) + + " book " + f(book.openness()) + " " + f(book.pageFlip1()) + " " + f(book.pageFlip2()); + } else if (be instanceof ShulkerBoxBlockEntity s) { + ShulkerBoxBlockEntity.tick(world, pos, state, s); + var r = make(ShulkerBoxRenderer.class).createRenderState(); + make(ShulkerBoxRenderer.class).extractRenderState(s, r, partial, Vec3.ZERO, null); + fields = s.getAnimationStatus() + " " + field(ShulkerBoxBlockEntity.class, "openCount").getInt(s) + + " " + f(field(ShulkerBoxBlockEntity.class, "progress").getFloat(s)) + + " " + f(field(ShulkerBoxBlockEntity.class, "progressOld").getFloat(s)) + + " render " + f(r.progress); + } else if (be instanceof BellBlockEntity b) { + if (!step.has("noTick")) BellBlockEntity.clientTick(world, pos, state, b); + var r = make(BellRenderer.class).createRenderState(); + make(BellRenderer.class).extractRenderState(b, r, partial, Vec3.ZERO, null); + fields = b.ticks + " " + b.shaking + " " + b.clickDirection + + " " + field(BellBlockEntity.class, "resonating").getBoolean(b) + + " " + field(BellBlockEntity.class, "resonationTicks").getInt(b) + + " " + field(BellBlockEntity.class, "lastRingTimestamp").getLong(b) + + " render " + f(r.ticks) + " " + r.shakeDirection; + } else if (be instanceof ConduitBlockEntity k) { + ConduitBlockEntity.clientTick(world, pos, state, k); + var r = make(ConduitRenderer.class).createRenderState(); + make(ConduitRenderer.class).extractRenderState(k, r, partial, Vec3.ZERO, null); + @SuppressWarnings("unchecked") + var effect = (List) field(ConduitBlockEntity.class, "effectBlocks").get(k); + fields = k.tickCount + " " + k.isActive() + " " + k.isHunting() + + " " + f(field(ConduitBlockEntity.class, "activeRotation").getFloat(k)) + " " + effect.size() + + " render " + r.isActive + " " + f(r.activeRotation) + " " + f(r.animTime) + " " + r.animationPhase + " " + r.isHunting; + } else if (be instanceof SkullBlockEntity k) { + BlockState now = step.has("state") ? parse(step.get("state").getAsString()) : state; + SkullBlockEntity.animation(world, pos, now, k); + fields = field(SkullBlockEntity.class, "isAnimating").getBoolean(k) + + " " + field(SkullBlockEntity.class, "animationTickCount").getInt(k) + + " render " + f(k.getAnimation(partial)); + } else if (be instanceof DecoratedPotBlockEntity p) { + var r = make(DecoratedPotRenderer.class).createRenderState(); + make(DecoratedPotRenderer.class).extractRenderState(p, r, partial, Vec3.ZERO, null); + fields = p.wobbleStartedAtTick + " " + p.lastWobbleStyle + + " render " + f(r.wobbleProgress) + " " + r.wobbleStyle; + } else { + throw new IllegalArgumentException("no animation for " + be); + } + out.append(fields).append(" |").append(world.log).append('\n'); + } + return out.toString(); + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var allocator = Class.forName("sun.misc.Unsafe"); + var theUnsafe = allocator.getDeclaredField("theUnsafe"); + theUnsafe.setAccessible(true); + unsafe = theUnsafe.get(null); + allocate = allocator.getMethod("allocateInstance", Class.class); + putObject = allocator.getMethod("putObject", Object.class, long.class, Object.class); + objectFieldOffset = allocator.getMethod("objectFieldOffset", Field.class); + CHEST_MODEL = new ChestModel(ChestModel.createSingleBodyLayer().bakeRoot()); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + var c = JsonParser.parseString(line).getAsJsonObject(); + String result; + try { + result = run(c); + } catch (Throwable t) { + result = "error " + t + "\n"; + } + out.print("case " + c.get("name").getAsString() + "\n" + result); + } + } + } +} diff --git a/tools/test_block_entity_anim_parity.py b/tools/test_block_entity_anim_parity.py new file mode 100755 index 000000000..0e85d978a --- /dev/null +++ b/tools/test_block_entity_anim_parity.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python3 +"""Compare client-ticked block-entity animation with the vanilla 26.3 block entities. + +The Java oracle (VanillaBlockEntityAnimOracle) builds each case's real vanilla +block entity (chest, trapped/copper chest and the other half of a double chest, +ender chest, enchanting table, shulker box, bell, conduit, dragon/piglin head, +decorated pot) +on a stand-in client level, then per scripted step applies the block event +(triggerEvent), runs the entity's own client ticker and the renderer's +extractRenderState, printing the fields, the level calls the tick made +(neighbour updates, entity pushes/queries, sounds, particles) and the render +state. `examples/block_entity_anim_fixture` replays the steps through +`horizon_client::block_entity_anim` and derives the render state from the +`BlockAnim` Horizon's renderer reads. Lines must match exactly (floats as bits). + + test_block_entity_anim_parity.py [--filter SUBSTRING] [--detail N] +""" +import argparse +import json +import os +import random +import subprocess +import sys + +try: + from . import lab, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab, test_rust_parity as base, test_model_baking_parity as baking + +PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' +HORIZONTAL = ['north', 'south', 'west', 'east'] +ALL = ['down', 'up'] + HORIZONTAL +FRAME = ['minecraft:prismarine', 'minecraft:prismarine_bricks', 'minecraft:sea_lantern', 'minecraft:dark_prismarine'] +WATERY = ['minecraft:water', 'minecraft:water[level=3]', 'minecraft:bubble_column', 'minecraft:seagrass', + 'minecraft:kelp_plant', 'minecraft:oak_slab[waterlogged=true]', 'minecraft:oak_stairs[waterlogged=true]'] +CHESTS = ['chest', 'trapped_chest', 'copper_chest', 'exposed_copper_chest', 'waxed_oxidized_copper_chest'] +CLOCKWISE = {'north': 'east', 'east': 'south', 'south': 'west', 'west': 'north'} +STEP = {'north': (0, 0, -1), 'south': (0, 0, 1), 'west': (-1, 0, 0), 'east': (1, 0, 0)} +DRY = ['minecraft:air', 'minecraft:stone', 'minecraft:lava', 'minecraft:oak_slab', 'minecraft:ice'] + + +def frame_offsets(): + out = [] + for ox in range(-2, 3): + for oy in range(-2, 3): + for oz in range(-2, 3): + ax, ay, az = abs(ox), abs(oy), abs(oz) + if (ax > 1 or ay > 1 or az > 1) and (ox == 0 and (ay == 2 or az == 2) or oy == 0 and (ax == 2 or az == 2) + or oz == 0 and (ax == 2 or ay == 2)): + out.append((ox, oy, oz)) + return out + + +def cases(): + rng = random.Random(0x414e494d) + out = [] + + def pos(): + return [rng.randint(-3000, 3000), rng.randint(-60, 300), rng.randint(-3000, 3000)] + + def add(kind, block, steps, **extra): + case = {'name': f'{kind}-{len(out)}', 'block': block, 'pos': pos(), 'steps': steps} + case.update(extra) + out.append(case) + + def times(n, start=None, gaps=(1,)): + t = rng.randint(-100, 10 ** 7) if start is None else start + result = [] + for _ in range(n): + result.append(t) + t += rng.choice(gaps) + return result + + # Shulker boxes: players open and close (open counts from startOpen/stopOpen), other events ignored. + for i in range(48): + color = rng.choice(['', 'white_', 'purple_', 'black_']) + block = f'minecraft:{color}shulker_box[facing={rng.choice(ALL)}]' + steps, count = [], 0 + for t in times(rng.randint(20, 70)): + step = {'time': t, 'partial': round(rng.random(), 4)} + r = rng.random() + if r < 0.12: + count = max(count, 0) + 1 + step['event'] = [1, count] + elif r < 0.22: + count -= 1 + step['event'] = [1, count] + elif r < 0.25: + step['event'] = [rng.choice([0, 2, 1]), rng.randint(-2, 3)] + steps.append(step) + add('shulker', block, steps) + + # Bells: rings from any side (and odd data values), raiders and other mobs nearby. + for i in range(40): + attach = rng.choice(['floor', 'ceiling', 'single_wall', 'double_wall']) + block = f'minecraft:bell[attachment={attach},facing={rng.choice(HORIZONTAL)}]' + p = pos() + entities = [] + for _ in range(rng.choice([0, 1, 2, 5, 12, 25])): + # Multiples of 1/1024: serde_json parses other decimals approximately (1 ulp off). + spread = rng.choice([10, 33, 50, 70]) + entities.append({'pos': [p[k] + 0.5 + round(rng.uniform(-spread, spread) * 1024) / 1024 for k in range(3)], + 'raider': rng.random() < 0.5, 'alive': rng.random() < 0.85, 'removed': rng.random() < 0.08}) + steps = [] + start = rng.randint(-50, 10 ** 6) + for k, t in enumerate(times(rng.randint(60, 180), start)): + step = {'time': t, 'partial': round(rng.random(), 4)} + if (k == 2 or rng.random() < 0.05) and k < 150: + step['event'] = [1 if rng.random() < 0.93 else 2, rng.choice([0, 1, 2, 3, 4, 5, 2, 3, 4, 5, 7, -3, 11])] + steps.append(step) + case = {'name': f'bell-{len(out)}', 'block': block, 'pos': p, 'steps': steps, 'entities': entities} + out.append(case) + + # Conduits: water around, prismarine frames of various sizes, frames changing over time. + rings = frame_offsets() + for i in range(36): + world = {} + water = rng.random() + for ox in range(-1, 2): + for oy in range(-1, 2): + for oz in range(-1, 2): + if (ox, oy, oz) != (0, 0, 0): + world[f'{ox},{oy},{oz}'] = rng.choice(WATERY) if rng.random() < 0.97 or water < 0.5 else rng.choice(DRY) + size = rng.choice([0, 10, 15, 16, 20, 30, 41, 42, 42]) + for o in rng.sample(rings, size): + world['%d,%d,%d' % o] = rng.choice(FRAME) + steps = [] + for t in times(rng.randint(60, 140), gaps=(1, 1, 1, 2, 7)): + step = {'time': t, 'partial': round(rng.random(), 4)} + if rng.random() < 0.04: + o = rng.choice(rings) + step['set'] = {'%d,%d,%d' % o: rng.choice(FRAME + DRY)} + steps.append(step) + waterlogged = 'true' if rng.random() < 0.9 else 'false' + extra = {'world': world, 'seed': rng.randint(0, 2 ** 40)} + if rng.random() < 0.3: + extra['target'] = {'pos': [round(rng.uniform(-8, 8) * 1024) / 1024 for _ in range(3)], 'width': round(rng.uniform(0.3, 2), 3), + 'height': round(rng.uniform(0.5, 3), 3), 'eye': round(rng.uniform(0.2, 2.5), 3)} + add('conduit', f'minecraft:conduit[waterlogged={waterlogged}]', steps, **extra) + + # Dragon and piglin heads powered on and off. + for i in range(24): + head = rng.choice(['dragon', 'piglin']) + wall = rng.random() < 0.5 + prop = f'facing={rng.choice(HORIZONTAL)}' if wall else f'rotation={rng.randint(0, 15)}' + name = f'minecraft:{head}_wall_head' if wall else f'minecraft:{head}_head' + powered = rng.random() < 0.5 + steps = [] + for t in times(rng.randint(20, 90)): + if rng.random() < 0.1: + powered = not powered + steps.append({'time': t, 'partial': round(rng.random(), 4), + 'state': f'{name}[{prop},powered={str(powered).lower()}]'}) + add('skull', f'{name}[{prop},powered=false]', steps) + + # Decorated pots wobbling (insert: POSITIVE, fail: NEGATIVE) and invalid events. + for i in range(24): + steps = [] + for t in times(rng.randint(20, 60), gaps=(0, 1, 1, 1, 3)): + step = {'time': t, 'partial': round(rng.random(), 4)} + if rng.random() < 0.15: + step['event'] = [rng.choice([1, 1, 1, 2]), rng.choice([0, 1, 0, 1, 2, -1])] + steps.append(step) + add('pot', f'minecraft:decorated_pot[facing={rng.choice(HORIZONTAL)}]', steps) + # Chests and ender chests: open counts from block event 1 (both halves of + # a double chest), other events ignored; the neighbour a double half + # connects to may be its other half or not (wrong block, type, facing). + for i in range(48): + facing = rng.choice(HORIZONTAL) + partner = None + world = {} + if rng.random() < 0.2: + block = f'minecraft:ender_chest[facing={facing}]' + else: + name = rng.choice(CHESTS) + kind = rng.choice(['single', 'left', 'right', 'left', 'right']) + block = f'minecraft:{name}[facing={facing},type={kind}]' + if kind != 'single': + connected = CLOCKWISE[facing] if kind == 'left' else [d for d, c in CLOCKWISE.items() if c == facing][0] + other_kind = 'right' if kind == 'left' else 'left' + other_name, other_facing, r = name, facing, rng.random() + if r < 0.1: + other_kind = kind + elif r < 0.2: + other_facing = rng.choice([d for d in HORIZONTAL if d != facing]) + elif r < 0.3: + other_name = rng.choice([c for c in CHESTS if c != name]) + elif r < 0.35: + other_kind = 'single' + if r < 0.95: + partner = '%d,%d,%d' % STEP[connected] + world[partner] = f'minecraft:{other_name}[facing={other_facing},type={other_kind}]' + steps, count, other = [], 0, 0 + for t in times(rng.randint(20, 70)): + step = {'time': t, 'partial': round(rng.random(), 4)} + r = rng.random() + if r < 0.12: + count = max(count, 0) + 1 + step['event'] = [1, count] + elif r < 0.22: + count -= 1 + step['event'] = [1, count] + elif r < 0.25: + step['event'] = [rng.choice([0, 2, 1]), rng.randint(-2, 3)] + if partner and rng.random() < 0.15: + other = other + 1 if rng.random() < 0.55 else other - 1 + step['partnerEvent'] = [1, other] + steps.append(step) + extra = {'world': world} + if partner: + extra['partner'] = partner + add('chest', block, steps, **extra) + + # Enchanting tables: players (and spectators) walking in and out of the + # 3-block reach; the class's shared RANDOM seeded per case. + for i in range(36): + p = pos() + centre = [p[0] + 0.5, p[1] + 0.5, p[2] + 0.5] + + def players(): + out = [] + for _ in range(rng.choice([0, 1, 1, 1, 2, 3])): + spread = rng.choice([1.5, 3, 5]) + out.append({'pos': [centre[k] + round(rng.uniform(-spread, spread) * 1024) / 1024 for k in range(3)], + 'spectator': rng.random() < 0.15}) + return out + steps = [] + for t in times(rng.randint(40, 160)): + step = {'time': t, 'partial': round(rng.random(), 4)} + if rng.random() < 0.08: + step['players'] = players() + steps.append(step) + case = {'name': f'book-{len(out)}', 'block': 'minecraft:enchanting_table', 'pos': p, 'steps': steps, + 'players': players(), 'seed': rng.randint(0, 2 ** 40)} + out.append(case) + + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--filter', default='') + parser.add_argument('--detail', type=int, default=3) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + libraries = baking.client_libraries() + build = lab.LOCAL / 'rust-block-entity-anim-parity' + build.mkdir(parents=True, exist_ok=True) + resources = lab.LOCAL / 'horizon-client' / '26.3' + chosen = [c for c in cases() if args.filter in c['name']] + inputs = build / 'inputs.jsonl' + inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen)) + classes = build / 'classes' + classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['client'], *libraries])) + + def run(command, name): + with (build / (name + '.log')).open('w') as log: + result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT) + if result.returncode: + print((build / (name + '.log')).read_text()[-4000:]) + sys.exit(f'{name} failed') + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes, + *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaBlockEntityAnimOracle'))], 'compile-java') + run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaBlockEntityAnimOracle', + inputs, build / 'vanilla.txt'], 'vanilla') + run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'block_entity_anim_fixture', '--', + resources, inputs, build / 'rust.txt'], 'rust') + + def split(path): + result, current = {}, None + for line in path.read_text().splitlines(): + if line.startswith('case '): + current = line[5:] + result[current] = [] + else: + result[current].append(line) + return result + vanilla, rust = split(build / 'vanilla.txt'), split(build / 'rust.txt') + kinds, failures, errors, steps = {}, {}, {}, 0 + for case in chosen: + name = case['name'] + kind = name.split('-')[0] + v, r = vanilla.get(name, []), rust.get(name, []) + total = kinds.setdefault(kind, [0, 0]) + total[1] += 1 + if v and v[0].startswith('error'): + errors.setdefault(kind, v[0]) + continue + steps += len(v) + bad = next((i for i, (a, b) in enumerate(zip(v, r)) if a != b), None) + if bad is None and len(v) != len(r): + bad = min(len(v), len(r)) + if bad is None: + total[0] += 1 + else: + failures.setdefault(kind, []).append((case, bad, v[bad] if bad < len(v) else None, r[bad] if bad < len(r) else None)) + for kind, error in sorted(errors.items()): + print(f'ORACLE ERROR {kind}: {error[:600]}') + for kind, items in sorted(failures.items()): + print(f'MISMATCH {kind}: {len(items)} cases') + for case, step, a, b in items[:args.detail]: + print(f' {case["name"]} {case["block"]} step {step}: {json.dumps(case["steps"][step] if step < len(case["steps"]) else None)}') + print(f' vanilla: {(a or "")[:500]}') + print(f' horizon: {(b or "")[:500]}') + for kind, (ok, n) in sorted(kinds.items()): + print(f'{kind}: {ok}/{n} cases match') + passed = sum(ok for ok, _ in kinds.values()) + print(f'{passed}/{len(chosen)} cases match ({steps} ticked steps)') + if failures or errors: + sys.exit(1) + print('block entity animation parity ok') + + +if __name__ == '__main__': + main()