diff --git a/crates/horizon-client/examples/cloud_fixture.rs b/crates/horizon-client/examples/cloud_fixture.rs index e21f3386e..7c00bfb3a 100644 --- a/crates/horizon-client/examples/cloud_fixture.rs +++ b/crates/horizon-client/examples/cloud_fixture.rs @@ -20,10 +20,15 @@ fn main() -> Result<(), Box> { write!(output, " {x},{z},{direction},{}", u8::from(inside)).unwrap(); } }; + let radius = if *kind == 2 { + clouds::radius_cells(*x) + } else { + *x + }; if *kind == 0 { cell(*x, *z, *neighbors); } else { - for (x, z) in clouds::cells(*x) { + for (x, z) in clouds::cells(radius) { cell(x, z, 0); } } diff --git a/crates/horizon-client/examples/container_screen_probe.rs b/crates/horizon-client/examples/container_screen_probe.rs new file mode 100644 index 000000000..b89b23a2a --- /dev/null +++ b/crates/horizon-client/examples/container_screen_probe.rs @@ -0,0 +1,86 @@ +#![forbid(unsafe_code)] +//! Runs tools/test_container_screen_parity.py's screens and mouse events +//! through `horizon_client::container_screen`. +use horizon_client::{ + Result, + container_screen::{Book, Button, Clicks, Image, Release, Target, clicked_outside}, + menu::Input, +}; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +fn input_name(input: Input) -> &'static str { + match input { + Input::Pickup => "PICKUP", + Input::QuickMove => "QUICK_MOVE", + Input::Swap => "SWAP", + Input::Clone => "CLONE", + Input::Throw => "THROW", + Input::QuickCraft => "QUICK_CRAFT", + Input::PickupAll => "PICKUP_ALL", + } +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let input = BufReader::new(File::open(&args[1])?); + let mut out = BufWriter::new(File::create(&args[2])?); + for (n, line) in input.lines().enumerate() { + let c: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + let int = |v: &Value| v.as_i64().unwrap() as i32; + let image = Image { + left: int(&c["image"][0]), + top: int(&c["image"][1]), + width: int(&c["image"][2]), + height: int(&c["image"][3]), + }; + let book = c.get("book").map(|b| Book { + visible: b[0].as_bool().unwrap(), + selected_tab_hovered: b[1].as_bool().unwrap(), + }); + let mut clicks = Clicks::default(); + for ev in c["events"].as_array().unwrap() { + let name = ev[0].as_str().unwrap(); + let (x, y) = (ev[1].as_f64().unwrap(), ev[2].as_f64().unwrap()); + let outside = clicked_outside(x, y, image, book); + let mut line = format!("{name} {outside}"); + if name != "point" { + // The case says whether the event is over the menu's slot (7). + let on_slot = ev[6].as_bool().unwrap(); + line += &format!(" {on_slot}"); + let target = Target::of(on_slot.then_some(7), outside); + let button = match ev[3].as_i64().unwrap() { + 1 => Button::Left, + 3 => Button::Right, + _ => Button::Middle, + }; + let shift = ev[4].as_i64().unwrap() & 3 != 0; + let carried_empty = !ev[5].as_bool().unwrap(); + let click = if name == "press" { + clicks.press(&target, button, carried_empty, shift, false) + } else { + match clicks.release(&target, button, carried_empty, false, shift, false) { + Release::Click(input) => Some(input), + Release::QuickCraft => panic!("no drags in these cases"), + Release::Nothing => None, + } + }; + if let Some(input) = click { + let id = match target { + Target::Slot(s) => s, + Target::Outside => -999, + Target::Nothing => -1, + }; + line += &format!(" click {id} {} {}", button.menu_button(), input_name(input)); + } + } + writeln!(out, "{line}")?; + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/examples/entity_components_probe.rs b/crates/horizon-client/examples/entity_components_probe.rs new file mode 100644 index 000000000..0d4a51e8c --- /dev/null +++ b/crates/horizon-client/examples/entity_components_probe.rs @@ -0,0 +1,89 @@ +#![forbid(unsafe_code)] +//! Runs tools/test_entity_components_parity.py's entities and advancement +//! entity predicates through `horizon_client::advancements::entity`, with the +//! variant component `mobs::finalize::species_variant_component` reports. +use horizon_client::{ + Result, + advancements::{EntityView, World, entity}, + mobs::{ + Species, + finalize::{species_variant_component, variant_index}, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +/// Nothing but the entity: these predicates read only its type and components. +struct Empty; +impl World for Empty { + fn dimension(&self) -> &str { + "minecraft:overworld" + } + fn biome(&self, _: [i32; 3]) -> String { + "minecraft:plains".into() + } + fn structures(&self, _: [i32; 3]) -> Vec { + Vec::new() + } + fn block(&self, _: [i32; 3]) -> (String, BTreeMap) { + ("minecraft:air".into(), BTreeMap::new()) + } + fn fluid(&self, _: [i32; 3]) -> Option { + None + } + fn can_see_sky(&self, _: [i32; 3]) -> bool { + true + } + fn light(&self, _: [i32; 3]) -> i32 { + 15 + } + fn smokey(&self, _: [i32; 3]) -> bool { + false + } + fn in_tag(&self, _: &str, _: &str, _: &str) -> bool { + false + } +} + +fn species(id: &str) -> Species { + match id { + "minecraft:wolf" => Species::Wolf, + "minecraft:cat" => Species::Cat, + "minecraft:frog" => Species::Frog, + "minecraft:pig" => Species::Pig, + "minecraft:cow" => Species::Cow, + "minecraft:chicken" => Species::Chicken, + other => panic!("no species for {other}"), + } +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let input = BufReader::new(File::open(&args[1])?); + let mut out = BufWriter::new(File::create(&args[2])?); + for (n, line) in input.lines().enumerate() { + let c: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + let kind = c["type"].as_str().unwrap(); + let s = species(kind); + let variant = variant_index(s, c["variant"].as_str().unwrap()); + let view = EntityView { + kind: kind.to_owned(), + position: [0.5, 64.0, 0.5], + components: species_variant_component(s, variant) + .map(|(id, v)| (id.to_owned(), v)) + .into_iter() + .collect(), + ..Default::default() + }; + for p in c["predicates"].as_array().unwrap() { + writeln!(out, "{}", entity(p, &view, &Empty, [2.5, 64.0, 0.5]))?; + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/examples/environment_fixture.rs b/crates/horizon-client/examples/environment_fixture.rs index 3300df232..d92123a2c 100644 --- a/crates/horizon-client/examples/environment_fixture.rs +++ b/crates/horizon-client/examples/environment_fixture.rs @@ -64,6 +64,10 @@ fn main() -> horizon_client::Result<()> { ); put("visual/fog_start_distance", format!("{:?}", sky.fog_start)); put("visual/fog_end_distance", format!("{:?}", sky.fog_end)); + put( + "visual/cloud_fog_end_distance", + format!("{:?}", sky.cloud_fog_end), + ); out.push_str(&row); out.push_str("}\n"); } diff --git a/crates/horizon-client/examples/fire_starter_sound_probe.rs b/crates/horizon-client/examples/fire_starter_sound_probe.rs new file mode 100644 index 000000000..62fab117a --- /dev/null +++ b/crates/horizon-client/examples/fire_starter_sound_probe.rs @@ -0,0 +1,32 @@ +#![forbid(unsafe_code)] +//! Runs tools/test_fire_starter_sound_parity.py's level random seeds through +//! the fire charge's use sound (`horizon_client::items::fire_starter_pitch`). +use horizon_client::{ + Result, + items::{fire_starter_pitch, fire_starter_sound}, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let input = BufReader::new(File::open(&args[1])?); + let mut out = BufWriter::new(File::create(&args[2])?); + for line in input.lines() { + let mut random = LegacyRandom::new(line?.trim().parse()?); + let pitch = fire_starter_pitch(true, &mut random); + writeln!( + out, + "{} {} {} {}", + fire_starter_sound(true), + 1.0f32.to_bits() as i32, + pitch.to_bits() as i32, + random.next_long() + )?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/examples/first_person_probe.rs b/crates/horizon-client/examples/first_person_probe.rs index 3fe203a48..7b1143114 100644 --- a/crates/horizon-client/examples/first_person_probe.rs +++ b/crates/horizon-client/examples/first_person_probe.rs @@ -5,7 +5,7 @@ use horizon_client::{ Result, attack_strength::{AttackStrength, HeldStack}, first_person::{ - Clicks, Hand, HandHeights, HandWorld, Hit, SwingAnimation, SwingState, UseResult, + Clicks, Hand, HandHeights, HandSway, HandWorld, Hit, SwingAnimation, SwingState, UseResult, swing_duration, }, }; @@ -308,6 +308,9 @@ fn run(case: &Value, out: &mut impl Write) -> Result<()> { let mut strength = AttackStrength::default(); // FirstPersonHandsAndItems' visible items start as ItemStack.EMPTY. let mut visible = [0usize, 0usize]; + // The player's xRot and yRot, and the hands' lag behind them. + let mut rot = [0.0f32; 2]; + let mut sway = HandSway::default(); for (s, step) in case["steps"].as_array().unwrap().iter().enumerate() { probe.step = step; probe.events.clear(); @@ -327,6 +330,10 @@ fn run(case: &Value, out: &mut impl Write) -> Result<()> { step["ud"].as_bool().unwrap(), ); probe.swing.tick(); + if let Some(r) = step["rot"].as_array() { + rot = [fl(&r[0]), fl(&r[1])]; + } + sway.tick(rot[0], rot[1]); let main = probe.stack(Hand::Main).clone(); strength.tick(held(&main)); // FirstPersonHandsAndItems.tick: shouldInstantlyReplaceVisibleItem @@ -363,7 +370,7 @@ fn run(case: &Value, out: &mut impl Write) -> Result<()> { let d = &clicks.destroying; writeln!( out, - "tick {s} {current} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}", + "tick {s} {current} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}", sw.ticks, fb(sw.animation), fb(sw.old_animation), @@ -379,7 +386,11 @@ fn run(case: &Value, out: &mut impl Write) -> Result<()> { clicks.right_click_delay, d.delay, d.active, - fb(d.progress) + fb(d.progress), + fb(sway.x_bob), + fb(sway.y_bob), + fb(sway.x_bob_o), + fb(sway.y_bob_o) )?; } Ok(()) diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 2434a5b5d..863e3786e 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -1,9 +1,11 @@ //! Menu clicks for tools/test_menu_click_parity.py: reads one JSON case per //! line (menu, creative, slots, carried, data, ops) and prints the oracle's -//! state lines after every click. +//! state lines after every click. The `*_be` furnace menus run over a furnace +//! block entity: its data slots follow `Furnace::input_clicked`. //! //! usage: menu_fixture RESOURCES INPUT OUTPUT use horizon_client::{ + containers::{Furnace, FurnaceKind}, crafting::Recipes, item_data::{canon_stack, parse_stack}, items::Items, @@ -46,7 +48,20 @@ fn main() -> horizon_client::Result<()> { let mut out = String::new(); for line in input.lines() { let case: Value = serde_json::from_str(line)?; - let kind = Kind::parse(case["menu"].as_str().unwrap_or_default()).ok_or("menu kind")?; + let name = case["menu"].as_str().unwrap_or_default(); + // FurnaceMenu over the server's AbstractFurnaceBlockEntity. + let furnace_kind = match name { + "furnace_be" => Some(FurnaceKind::Furnace), + "blast_furnace_be" => Some(FurnaceKind::BlastFurnace), + "smoker_be" => Some(FurnaceKind::Smoker), + _ => None, + }; + let kind = Kind::parse( + name.strip_suffix("_be") + .filter(|_| furnace_kind.is_some()) + .unwrap_or(name), + ) + .ok_or("menu kind")?; let mut menu = Menu::new(kind); menu.creative = case["creative"].as_bool().unwrap_or(false); for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() { @@ -57,6 +72,15 @@ fn main() -> horizon_client::Result<()> { for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() { menu.data[i] = v.as_i64().unwrap_or(0) as i32; } + let mut furnace = furnace_kind.map(|kind| Furnace { + kind, + items: [0, 1, 2].map(|i| menu.slot(i).cloned()), + lit_remaining: menu.data[0], + lit_total: menu.data[1], + cooking_timer: menu.data[2], + cooking_total: menu.data[3], + speed: 1.0, + }); menu.drops.clear(); out += &format!("init {}\n", state(&menu)); for op in case["ops"].as_array().ok_or("ops")? { @@ -80,7 +104,15 @@ fn main() -> horizon_client::Result<()> { _ => {} } let kind = Input::parse(op[2].as_str().unwrap_or_default()).ok_or("input")?; - match menu.click(&env, slot, button, kind) { + let clicked = menu.click(&env, slot, button, kind); + if let Some(f) = furnace.as_mut() { + let before = f.items[0].clone(); + f.items = [0, 1, 2].map(|i| menu.slot(i).cloned()); + f.input_clicked(&recipes, before); + menu.data[2] = f.cooking_timer; + menu.data[3] = f.cooking_total; + } + match clicked { Ok(()) => out += &format!("{}\n", state(&menu)), Err(name) => out += &format!("error {name}\n"), } diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 40527b810..f90fbfc3e 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -56,6 +56,9 @@ struct Scenario { spawning: bool, /// The player hits a mob for 1 at the start of a tick: (tick, mob index). hurts: Vec<(i32, usize)>, + /// The player feeds an animal at the start of a tick (Animal.mobInteract): + /// (tick, mob index); the scenario only feeds each animal its food. + feeds: Vec<(i32, usize)>, hand: Option, mobs: Vec, } @@ -92,6 +95,7 @@ fn parse(text: &str) -> Vec { } "heart" => s.hearts.push(f.iter().map(|x| (*x).to_owned()).collect()), "hurt" => s.hurts.push((f[1].parse().unwrap(), f[2].parse().unwrap())), + "feed" => s.feeds.push((f[1].parse().unwrap(), f[2].parse().unwrap())), "player" => { s.player = Some([ f[1].parse().unwrap(), @@ -893,6 +897,9 @@ fn main() -> horizon_client::Result<()> { } }); let mut scratch = LegacyRandom::new(0); + // The level's random for eating sounds: only goats and sniffers draw + // from it, and the scenarios feed neither. + let mut level_random = LegacyRandom::new(0); for (i, m) in mobs.iter().enumerate() { print(&mut out, 0, i, m, s.creative); } @@ -996,6 +1003,16 @@ fn main() -> horizon_client::Result<()> { } events.append(&mut mobs[i].outbox); } + for &(tick, i) in &s.feeds { + if tick != t || i >= mobs.len() || mobs[i].removed { + continue; + } + if let Some(Some((name, volume, pitch))) = + horizon_client::mobs::ai::feed_animal(&mut mobs[i], &mut level_random) + { + events.push(MobEvent::Sound(name, [0.0; 3], volume, pitch)); + } + } #[allow(unused_mut)] // filled only with the rng-trace feature let mut traces: Vec = Vec::new(); let mut pushes = Vec::new(); diff --git a/crates/horizon-client/examples/pack_resources_fixture.rs b/crates/horizon-client/examples/pack_resources_fixture.rs new file mode 100644 index 000000000..00238fa94 --- /dev/null +++ b/crates/horizon-client/examples/pack_resources_fixture.rs @@ -0,0 +1,92 @@ +//! The resource root Horizon builds for a pack selection (`packs::build_overlay`) +//! and what its loaders read from it, for VanillaPackResourcesOracle. +use horizon_client::{lang::Language, packs, sound_events::SoundRegistry}; +use std::{fmt::Write, fs, path::PathBuf}; +fn fnv(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| { + (h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3) + }) +} +/// `namespace:path` to a file under the root's `assets/`. +fn asset(root: &std::path::Path, id: &str, prefix: &str, suffix: &str) -> PathBuf { + let (namespace, path) = id.split_once(':').unwrap_or(("minecraft", id)); + root.join("assets") + .join(namespace) + .join(format!("{prefix}{path}{suffix}")) +} +fn types(root: &std::path::Path, file: PathBuf, key: &str) -> String { + let _ = root; + let value: serde_json::Value = fs::read(file) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default(); + value[key] + .as_array() + .into_iter() + .flatten() + .map(|v| { + let t = v["type"].as_str().unwrap_or("?"); + format!(" {}", t.strip_prefix("minecraft:").unwrap_or(t)) + }) + .collect() +} +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let input = fs::read_to_string(&args[1])?; + let mut lines = input.lines(); + let root: Vec<&str> = lines.next().ok_or("empty input")?.split(' ').collect(); + let vanilla = PathBuf::from(root[1]); + let ids: Vec = root[3..].iter().map(|s| (*s).to_owned()).collect(); + let all = packs::discover(&vanilla, &PathBuf::from(root[2])); + let enabled = packs::enabled(&all, &ids); + let overlay = PathBuf::from(&args[2]).with_extension("overlay"); + packs::build_overlay(&vanilla, &enabled, &overlay)?; + let language = Language::load(&[&overlay], "en_us"); + let sounds = SoundRegistry::load(&overlay); + let mut out = String::new(); + for line in lines { + let (kind, arg) = line.split_once(' ').unwrap_or((line, "")); + write!(out, "{line} =>")?; + match kind { + "file" => match fs::read(asset(&overlay, arg, "", "")) { + Ok(bytes) => write!(out, " {:x}", fnv(&bytes))?, + Err(_) => out.push_str(" missing"), + }, + "lang" => write!(out, " {}", language.get(arg).unwrap_or(arg))?, + "sound" => { + let event = if arg.contains(':') { + arg.to_owned() + } else { + format!("minecraft:{arg}") + }; + match sounds.get(&event) { + None => out.push_str(" missing"), + Some(e) => { + write!(out, " subtitle={}", e.subtitle.as_deref().unwrap_or("none"))?; + for s in &e.sounds { + if s.event { + out.push_str(" event"); + } else { + write!(out, " {}*{}", s.location, s.weight)?; + } + } + } + } + } + "font" => out.push_str(&types( + &overlay, + asset(&overlay, arg, "font/", ".json"), + "providers", + )), + "atlas" => out.push_str(&types( + &overlay, + asset(&overlay, arg, "atlases/", ".json"), + "sources", + )), + _ => return Err(format!("unknown query {line}").into()), + } + out.push('\n'); + } + fs::write(&args[2], out)?; + Ok(()) +} diff --git a/crates/horizon-client/examples/particle_providers_probe.rs b/crates/horizon-client/examples/particle_providers_probe.rs new file mode 100644 index 000000000..ddd71b52e --- /dev/null +++ b/crates/horizon-client/examples/particle_providers_probe.rs @@ -0,0 +1,217 @@ +#![forbid(unsafe_code)] +//! Runs tools/test_particle_providers_parity.py's particles through +//! `ParticleEngine`: built with the seeds the vanilla oracle recovered, then +//! ticked over air or a stone floor at y 63, printing their state each tick. +use horizon_client::{ + Result, + assets::Assets, + blocks::BlockFacts, + chunk::Chunk, + collisions, + particles::{ParticleEngine, ParticleLevel, ParticleOptions, ParticleSnapshot, ParticleType}, + world::World, +}; +use serde_json::Value; +use std::{ + collections::HashMap, + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, + path::Path, + sync::Arc, +}; + +fn d(v: f64) -> String { + format!("{:016x}", v.to_bits()) +} +fn f(v: f32) -> String { + format!("{:08x}", v.to_bits()) +} +fn color(v: &Value, default: u32) -> u32 { + v.as_u64().map_or(default, |c| c as u32) +} +fn rgb(c: u32) -> [f32; 3] { + [ + ((c >> 16) & 255) as f32 / 255.0, + ((c >> 8) & 255) as f32 / 255.0, + (c & 255) as f32 / 255.0, + ] +} +fn options(case: &Value) -> Option { + let ty = ParticleType::from_name(case["type"].as_str()?)?; + let o = &case["options"]; + let scale = o["scale"].as_f64().unwrap_or(1.0) as f32; + let c = color(&o["color"], 0xFFFF_FFFF); + let argb = { + let [r, g, b] = rgb(c); + [r, g, b, ((c >> 24) & 255) as f32 / 255.0] + }; + Some(match ty { + ParticleType::Block | ParticleType::BlockCrumble | ParticleType::DustPillar => { + ParticleOptions::block(ty, "terrain".into(), 0xFF_FFFF) + } + // Stone's map colour: FallingDustParticle.Provider's tint without a tint source. + ParticleType::FallingDust => ParticleOptions::block(ty, "terrain".into(), 0x70_7070), + ParticleType::Dust => ParticleOptions::dust(rgb(c), scale), + ParticleType::DustColorTransition => { + ParticleOptions::dust_transition(rgb(c), rgb(color(&o["to"], 0)), scale) + } + ParticleType::Effect | ParticleType::InstantEffect => ParticleOptions { + scale, + ..ParticleOptions::colored(ty, argb) + }, + ParticleType::EntityEffect | ParticleType::TintedLeaves => { + ParticleOptions::colored(ty, argb) + } + ParticleType::DragonBreath => ParticleOptions { + scale, + ..ParticleOptions::simple(ty) + }, + ParticleType::SculkCharge => ParticleOptions::sculk_charge(scale), + ParticleType::Shriek => ParticleOptions::shriek(scale as i32), + ParticleType::Trail => { + let t = &o["target"]; + ParticleOptions::trail( + [t[0].as_f64()?, t[1].as_f64()?, t[2].as_f64()?], + c & 0xFF_FFFF, + o["duration"].as_i64()? as i32, + ) + } + _ => ParticleOptions::simple(ty), + }) +} +fn state(s: &ParticleSnapshot) -> String { + let mut out = format!( + "{} {} {} {}", + s.age, + s.lifetime, + u8::from(s.removed), + u8::from(s.on_ground) + ); + for v in s.position.iter().chain(&s.velocity).chain(&s.previous) { + out += &format!(" {}", d(*v)); + } + if let Some(q) = &s.quad { + out += &format!(" | {} {}", f(q.size[0]), f(q.size[1])); + for v in q.rgba.iter().chain(&q.roll) { + out += &format!(" {}", f(*v)); + } + out += &format!(" {}", q.sprite); + for v in q.uv { + out += &format!(" {}", f(v)); + } + out += &format!(" {:x}", q.light); + } + out +} +fn world(assets: &Assets, facts: &BlockFacts, floor: bool) -> Result { + let mut world = World::new(facts.air, 0); + let stone = assets + .registry + .default_state("minecraft:stone") + .ok_or("missing stone")?; + for cz in -3..=2 { + for cx in -3..=2 { + world + .chunks + .insert((cx, cz), Arc::new(Chunk::empty(cx, cz))); + if floor { + for z in 0..16 { + for x in 0..16 { + world.set(cx * 16 + x, 63, cz * 16 + z, stone)?; + } + } + } + } + } + Ok(world) +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new(".local/horizon-client/26.3"); + let assets = Assets::load(root)?; + let facts = BlockFacts::load(root, assets.registry)?; + let collision = collisions::load(root, assets.registry)?; + let worlds = [ + world(&assets, &facts, false)?, + world(&assets, &facts, true)?, + ]; + let mut engine = ParticleEngine::new(root, &HashMap::new()); + // The oracle's output: the seed line of each case. + let mut seeds = Vec::new(); + for line in BufReader::new(File::open(&args[2])?).lines() { + let line = line?; + if line.starts_with("seed ") || line.starts_with("null ") || line == "no provider" { + seeds.push(line); + } + } + let mut out = BufWriter::new(File::create(&args[3])?); + for (n, line) in BufReader::new(File::open(&args[1])?).lines().enumerate() { + let case: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + let Some(options) = options(&case) else { + writeln!(out, "no provider")?; + continue; + }; + let seed = case["seed"].as_i64().ok_or("seed")?; + engine.seed_randoms(seed, seed ^ 0x6C_6576_656C, seed ^ 0x73_7065_6C6C); + engine.requested = Some(Vec::new()); + engine.sounds.clear(); + let level = ParticleLevel { + world: &worlds[usize::from(case["floor"].as_bool() == Some(true))], + facts: &facts, + collision: &collision, + player: None, + }; + let v = |key: &str| -> [f64; 3] { + std::array::from_fn(|i| case[key][i].as_f64().unwrap_or(0.0)) + }; + let seed_line = seeds.get(n).cloned().unwrap_or_default(); + let local = seed_line + .split(' ') + .nth(1) + .and_then(|s| s.parse::().ok()) + .unwrap_or(0); + let Some(mut particle) = engine.probe_create(&options, v("pos"), v("vel"), local, &level) + else { + writeln!(out, "null {}", engine.next_randoms()[0])?; + continue; + }; + writeln!(out, "{seed_line}")?; + let [a, b, c] = engine.next_randoms(); + writeln!(out, "next {a} {b} {c}")?; + let events = |engine: &mut ParticleEngine, out: &mut BufWriter| -> Result<()> { + for (o, p, v) in engine.requested.replace(Vec::new()).unwrap_or_default() { + write!(out, "+ {}", o.ty.name())?; + for x in p.iter().chain(&v) { + write!(out, " {}", d(*x))?; + } + writeln!(out)?; + } + for (name, p, volume, pitch) in std::mem::take(&mut engine.sounds) { + writeln!( + out, + "~ {name} {} {} {} {} {}", + d(p[0]), + d(p[1]), + d(p[2]), + f(volume), + f(pitch) + )?; + } + Ok(()) + }; + writeln!(out, "0 {}", state(&engine.snapshot(&particle)))?; + events(&mut engine, &mut out)?; + let ticks = case["ticks"].as_i64().unwrap_or(0); + let mut t = 1; + while t <= ticks && particle.is_alive() { + engine.probe_tick(&mut particle, &level); + writeln!(out, "{t} {}", state(&engine.snapshot(&particle)))?; + events(&mut engine, &mut out)?; + t += 1; + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/examples/scene_collision_probe.rs b/crates/horizon-client/examples/scene_collision_probe.rs index f46723326..f7ed87ea7 100644 --- a/crates/horizon-client/examples/scene_collision_probe.rs +++ b/crates/horizon-client/examples/scene_collision_probe.rs @@ -40,6 +40,7 @@ fn main() -> Result<()> { let mut scene = collisions::SceneCollisions { world: &world, binding: &binding, + subject: None, }; fs::write( dir.join("scene.json"), diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs index 6cdec8587..e5309912b 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/scene_motion_probe.rs @@ -165,6 +165,17 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> { .filter_map(|e| match e { MotionEvent::Fall(e) => Some(e.trace()), MotionEvent::Health(e) => Some(e.trace()), + MotionEvent::Snowflake { position, velocity } => Some(format!( + "snowflake {:016x},{:016x},{:016x} {:016x},{:016x},{:016x}", + position.x.to_bits(), + position.y.to_bits(), + position.z.to_bits(), + velocity.x.to_bits(), + velocity.y.to_bits(), + velocity.z.to_bits() + )), + // The oracle marks every getAdvancements call (ENTER_BLOCK.trigger) so. + MotionEvent::EnterBlock { .. } => Some("hurt-criterion".into()), MotionEvent::Waypoint { receiver, enabled } => Some(format!( "waypoint {} {enabled}", if *receiver { "receive" } else { "transmit" } @@ -232,6 +243,8 @@ fn main() -> Result<()> { instances.next().expect("unexpected instance allocation") }), )?; + // The oracle runs block-inside effects only in "snow_tick". + player.block_effects = false; for op in f["ops"].as_array().unwrap() { let mut world = MotionWorld { player: &mut player, @@ -409,6 +422,26 @@ fn main() -> Result<()> { op["jumping"].as_bool().unwrap(), )?; } + "snow_tick" => { + // The clock, then the player tick: baseTick's powder snow + // flags lead PlayerMotion::player_movement_tick. + world.player.health.advance_clock(); + let v = vector(&op["value"]); + world.player.block_effects = true; + let ticked = world.player_movement_tick( + [v.x as f32, v.z as f32], + op["jumping"].as_bool().unwrap(), + ); + world.player.block_effects = false; + ticked?; + } + "boots" => { + // Leather boots are also freeze-immune wearables. + let boots = op["value"].as_bool().unwrap(); + world.player.leather_boots = boots; + world.player.freeze_immune = boots; + } + "frozen" => world.player.ticks_frozen = op["value"].as_i64().unwrap() as i32, "trigger" => world.player.jump_trigger_time = op["value"].as_i64().unwrap() as i32, "delay" => world.player.no_jump_delay = op["value"].as_i64().unwrap() as i32, "move" => world.move_self(vector(&op["value"]))?, @@ -478,7 +511,18 @@ fn main() -> Result<()> { } let check_block = scene.block(25, 3, 25); snapshot(&mut out, &player)?; - writeln!(out, "block {}", check_block.0)?; + let stuck = player.stuck_multiplier; + writeln!( + out, + "block {} frozen {} {} {} {:016x},{:016x},{:016x}", + check_block.0, + player.ticks_frozen, + player.in_powder_snow, + player.was_in_powder_snow, + stuck.x.to_bits(), + stuck.y.to_bits(), + stuck.z.to_bits() + )?; let h = &player.health; let canonical = |v: f32| { if v.is_nan() { diff --git a/crates/horizon-client/examples/weather_fixture.rs b/crates/horizon-client/examples/weather_fixture.rs new file mode 100644 index 000000000..15aab6bdb --- /dev/null +++ b/crates/horizon-client/examples/weather_fixture.rs @@ -0,0 +1,59 @@ +//! WeatherEffectRenderer column instances and quads, without a GPU. +use horizon_client::weather; +use std::{fmt::Write, fs}; +fn bits(value: f32) -> String { + if value.is_nan() { + "nan".into() + } else { + format!("{:x}", value.to_bits()) + } +} +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let mut output = String::new(); + for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() { + let p: Vec<&str> = line.split_whitespace().collect(); + let int = |i: usize| p[i].parse::().unwrap(); + let kind = int(0); + let ticks: i64 = p[1].parse()?; + let (x, bottom, top, z, light) = (int(2), int(3), int(4), int(5), int(6)); + let partial: f32 = p[7].parse()?; + let camera = [p[8].parse()?, p[9].parse()?, p[10].parse()?]; + let radius = int(11); + let intensity: f32 = p[12].parse()?; + let mut random = weather::column_random(x, z); + let column = if kind == 0 { + weather::rain_column(&mut random, ticks, x, bottom, top, z, light, partial) + } else { + weather::snow_column(&mut random, ticks, x, bottom, top, z, light, partial) + }; + write!( + output, + "{case} {} {} {} {} {} {} {}", + column.x, + column.z, + column.bottom_y, + column.top_y, + bits(column.u_offset), + bits(column.v_offset), + column.light_coords + )?; + let max_alpha = if kind == 0 { 1.0 } else { 0.8 }; + for v in weather::column_quad(&column, camera, max_alpha, radius, intensity) { + write!( + output, + " |{},{},{},{},{},{:x},{}", + bits(v.pos[0]), + bits(v.pos[1]), + bits(v.pos[2]), + bits(v.uv[0]), + bits(v.uv[1]), + v.color, + v.light_coords + )?; + } + output.push('\n'); + } + fs::write(&args[2], output)?; + Ok(()) +} diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 14754d3b7..4a2666ded 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -294,6 +294,8 @@ pub struct EntityView { pub struck: Vec, pub fishing_open_water: Option, pub variant: Option, + /// The data components the entity reports (`Entity.get`): id and value. + pub components: Vec<(String, String)>, } fn range_f(v: &Value, x: f64) -> bool { match v { @@ -310,7 +312,7 @@ fn range_i(v: &Value, x: i64) -> bool { range_f(v, x as f64) } /// A registry id, `#tag`, or list matched against one id. -fn id_matches(v: &Value, registry: &str, id: &str, w: &dyn World) -> bool { +pub fn id_matches(v: &Value, registry: &str, id: &str, w: &dyn World) -> bool { match v { Value::Null => true, Value::String(s) => match s.strip_prefix('#') { @@ -442,6 +444,26 @@ pub fn location(v: &Value, p: [f64; 3], w: &dyn World) -> bool { } true } +/// `DataComponentExactPredicate.test` on an entity: every expected +/// component equals what the entity reports (absent ones never match). +fn components(expected: &Value, have: &[(String, String)]) -> bool { + let full = |id: &str| { + if id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + } + }; + expected.as_object().is_some_and(|o| { + o.iter().all(|(id, want)| { + let id = full(id); + want.as_str().is_some_and(|want| { + have.iter() + .any(|(k, v)| full(k) == id && full(v) == full(want)) + }) + }) + }) +} /// `EntityPredicate` (26.x keyed sub-predicates). pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> bool { if v.is_null() { @@ -521,7 +543,8 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo "minecraft:type_specific/fishing_hook" => p["in_open_water"] .as_bool() .is_none_or(|want| e.fishing_open_water == Some(want)), - "minecraft:components" | "minecraft:predicates" => true, + "minecraft:components" => components(p, &e.components), + "minecraft:predicates" => true, _ => false, }; if !ok { diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index fd6e196ee..edfdcf0ea 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -180,15 +180,43 @@ impl Assets { .collect::>()?, )); let mut material_states = [BlockStateId(0); 6]; - let mut sprites = crate::sprites::Sprites::default(); for (layer, name) in MATERIALS.iter().enumerate() { - let state = registry + material_states[layer] = registry .default_state(&format!("minecraft:{name}")) .ok_or_else(|| invalid("missing test-scene material"))?; - material_states[layer] = state; - sprites.insert(root, &format!("minecraft:block/{name}"))?; } let registry: &'static BlockRegistry = Box::leak(Box::new(registry)); + Self::with_models( + root, + registry, + properties, + material_states, + blocks_fluid_flow, + ) + } + /// The same blocks with the models and sprites of another resource root + /// (resource packs changed): the registry and block facts come from the + /// game data, which resource packs do not touch. + pub fn reload(&self, root: &Path) -> Result { + Self::with_models( + root, + self.registry, + self.properties.clone(), + self.material_states, + self.blocks_fluid_flow.clone(), + ) + } + fn with_models( + root: &Path, + registry: &'static BlockRegistry, + properties: Properties, + material_states: [BlockStateId; 6], + blocks_fluid_flow: BTreeSet, + ) -> Result { + let mut sprites = crate::sprites::Sprites::default(); + for name in MATERIALS { + sprites.insert(root, &format!("minecraft:block/{name}"))?; + } let models = crate::models::prepare(root, registry, &mut sprites)?; // Fluids are drawn by the fluid renderer, not block models; breaking // progress uses the destroy-stage overlays. @@ -204,6 +232,7 @@ impl Assets { for stage in 0..10 { sprites.insert(root, &format!("minecraft:block/destroy_stage_{stage}"))?; } + sprites.finish(); Ok(Self { registry, properties, diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 69a29217c..034354ade 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -600,6 +600,16 @@ impl Audio { pub fn stop_all(&mut self) { self.engine.stop_all(&mut self.backend); } + /// `SoundManager.reload` (resource packs changed): stop every sound, then + /// read sound events and sound files from the new resource root. + pub fn reload(&mut self, root: &Path) { + self.stop_all(); + self.engine.registry = SoundRegistry::load(root); + self.backend.root = root.to_owned(); + let mut cache = self.backend.cache.lock().unwrap(); + cache.entries.clear(); + cache.bytes = 0; + } /// Play a sound event at a world position, as `ClientLevel.playLocalSound` /// (a `SimpleSoundInstance` seeded from the level random), or relative to /// the listener without attenuation (`None`). diff --git a/crates/horizon-client/src/camera.rs b/crates/horizon-client/src/camera.rs index f74f083cd..17b68ccb9 100644 --- a/crates/horizon-client/src/camera.rs +++ b/crates/horizon-client/src/camera.rs @@ -590,6 +590,12 @@ impl Camera { modify_fov_based_on_death_or_fluid(partial, 70.0, effect_scale, dead, fluid) } } +/// `Camera.update`: the far plane covers four times the render distance and +/// the whole cloud range (`depthFar`). +pub fn depth_far(render_distance_chunks: i32, cloud_range_chunks: i32) -> f32 { + (render_distance_chunks as f32 * 16.0 * 4.0).max((cloud_range_chunks * 16) as f32) +} + /// `Projection.getMatrix` for a perspective set up by `setupPerspective`: /// JOML's `Matrix4f.setPerspective(fov * DEG_TO_RAD, width / height, near, /// far, zZeroToOne)`, column-major. Vanilla passes its planes reversed @@ -768,6 +774,13 @@ pub fn bob_matrix(state: &BobState, damage_tilt_strength: f64, bob_view_option: #[cfg(test)] mod tests { + #[test] + fn depth_far_covers_the_cloud_range() { + // renderDistance 2 with the default Cloud Distance (128 chunks). + assert_eq!(super::depth_far(2, 128), 2048.0); + assert_eq!(super::depth_far(32, 2), 2048.0); + assert_eq!(super::depth_far(12, 12), 768.0); + } use super::*; #[test] fn view_keeps_yaw_at_vertical_pitch_limits() { diff --git a/crates/horizon-client/src/clouds.rs b/crates/horizon-client/src/clouds.rs index 161edb168..b29fdf7ee 100644 --- a/crates/horizon-client/src/clouds.rs +++ b/crates/horizon-client/src/clouds.rs @@ -32,6 +32,12 @@ pub fn faces(mask: u16) -> impl Iterator { ) } +/// `CloudRenderer.prepare`: the cell radius for the Cloud Distance option +/// (in chunks), independent of the render distance. +pub fn radius_cells(cloud_range_chunks: i32) -> i32 { + ((cloud_range_chunks * 16) as f32 / 12.0).ceil() as i32 +} + /// CloudRenderer builds cells in expanding Manhattan rings, nearest first. pub fn cells(radius: i32) -> impl Iterator { (0..=2 * radius).flat_map(move |ring| { @@ -71,6 +77,12 @@ mod tests { assert_eq!(face_mask(2, 2, 0.0, [false; 4]), 3); } #[test] + fn cloud_distance_sets_the_radius() { + assert_eq!(radius_cells(2), 3); + assert_eq!(radius_cells(12), 16); + assert_eq!(radius_cells(128), 171); + } + #[test] fn connected_cells_have_no_exterior_walls() { assert_eq!(face_mask(2, 2, 10.0, [false; 4]), 1); } diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 47b5d7981..d65851636 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -39,9 +39,24 @@ pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result { pub world: &'w World, pub binding: &'w BlockCollisionRegistry<'r>, + /// The entity colliding, for powder snow; None: no fall, no boots. + pub subject: Option, } impl SceneCollisions<'_, '_> { /// Position contexts permit geometric movement probes without inventing a @@ -169,18 +184,18 @@ impl LiquidCollisionWorld for SceneCollisions<'_, '_> { } impl PowderSnowWorld for SceneCollisions<'_, '_> { type Error = io::Error; - // Entities here are never falling blocks and wear no leather boots. fn powder_snow_entity(&mut self, _: EntityIdentity) -> io::Result { + let subject = self.subject.unwrap_or_default(); Ok(PowderSnowEntity { - fall_distance: 0.0, - falling_block: false, + fall_distance: subject.fall_distance, + falling_block: subject.falling_block, }) } fn powder_snow_walkable_tag(&mut self, _: EntityIdentity) -> io::Result { - Ok(false) + Ok(self.subject.is_some_and(|s| s.walkable_type)) } fn feet_are_leather_boots(&mut self, _: EntityIdentity) -> io::Result { - Ok(false) + Ok(self.subject.is_some_and(|s| s.leather_boots)) } } diff --git a/crates/horizon-client/src/container_screen.rs b/crates/horizon-client/src/container_screen.rs new file mode 100644 index 000000000..2c490861a --- /dev/null +++ b/crates/horizon-client/src/container_screen.rs @@ -0,0 +1,278 @@ +//! The mouse handling every survival and container screen shares +//! (`AbstractContainerScreen.mouseClicked` / `mouseReleased`): which slot id +//! a click targets (-999 outside the window, `hasClickedOutside` with the +//! recipe book's own rule) and which `ContainerInput` it sends. Shift is +//! the event's own modifiers (`InputWithModifiers.hasShiftDown`: the +//! physical Shift keys, never the remapped or toggled sneak key). + +use crate::menu::Input; + +/// The screen's window: `leftPos`, `topPos`, `imageWidth`, `imageHeight`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Image { + pub left: i32, + pub top: i32, + pub width: i32, + pub height: i32, +} + +/// The recipe book of an `AbstractRecipeBookScreen`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Book { + /// `RecipeBookComponent.isVisible`. + pub visible: bool, + /// `selectedTab.isHoveredOrFocused()`. + pub selected_tab_hovered: bool, +} + +/// `RecipeBookComponent.IMAGE_WIDTH`. +const BOOK_WIDTH: i32 = 147; + +fn outside(mx: f64, my: f64, image: Image) -> bool { + mx < f64::from(image.left) + || my < f64::from(image.top) + || mx >= f64::from(image.left + image.width) + || my >= f64::from(image.top + image.height) +} + +/// `AbstractContainerScreen.hasClickedOutside`, or +/// `AbstractRecipeBookScreen.hasClickedOutside` when the screen has a book +/// (`RecipeBookComponent.hasClickedOutside`: a click on the book, or with +/// its selected tab hovered, is not outside). +pub fn clicked_outside(mx: f64, my: f64, image: Image, book: Option) -> bool { + let out = outside(mx, my, image); + let Some(book) = book else { + return out; + }; + let book_outside = !book.visible || { + let on_book = f64::from(image.left - BOOK_WIDTH) < mx + && mx < f64::from(image.left) + && f64::from(image.top) < my + && my < f64::from(image.top + image.height); + out && !on_book && !book.selected_tab_hovered + }; + book_outside && out +} + +/// What a click points at: a slot, outside the window (slot id -999), or +/// neither (slot id -1). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Target { + Slot(S), + Outside, + Nothing, +} + +impl Target { + /// Outside wins over a hovered slot, as in `mouseClicked`. + pub fn of(slot: Option, outside: bool) -> Self { + match slot { + _ if outside => Self::Outside, + Some(s) => Self::Slot(s), + None => Self::Nothing, + } + } +} + +/// The left, right and middle buttons (SDL's 1, 3 and 2). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Button { + Left, + Right, + Middle, +} + +impl Button { + /// `getContainerClickButton`: the button a menu click carries. + pub fn menu_button(self) -> i32 { + match self { + Self::Left => 0, + Self::Right => 1, + Self::Middle => 2, + } + } +} + +/// The input state `mouseClicked`/`mouseReleased` keep between events. +#[derive(Clone, Debug, Default)] +pub struct Clicks { + /// `isQuickCrafting` with `quickCraftingButton`. + quick_crafting: Option