From 2567a4a41aaeb13318756d2deba5331d81f61d63 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 22:01:15 +0200 Subject: [PATCH] Add the vault's server logic with a parity harness vault::Vault is VaultBlockEntity with its config, server and shared data: load and save, Server.tick (display item cycling, VaultState.tickAndGetNext, ejection, transitions with their sounds and level events) and VaultBlock.useItemOn / tryInsertKey (keys, rewarded players, fail sounds, the reward roll with its random sequence). tools/test_vault_parity.py runs 3,000 cases against vanilla through a new mode=vault of the natural spawn oracle and fixture. Part of #223. Co-Authored-By: Claude Opus 5.5 --- .../examples/natural_spawn_fixture.rs | 203 ++++- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/vault.rs | 745 ++++++++++++++++++ .../parity/VanillaNaturalSpawnOracle.java | 108 ++- tools/test_vault_parity.py | 225 ++++++ 5 files changed, 1277 insertions(+), 5 deletions(-) create mode 100644 crates/horizon-client/src/vault.rs create mode 100644 tools/test_vault_parity.py diff --git a/crates/horizon-client/examples/natural_spawn_fixture.rs b/crates/horizon-client/examples/natural_spawn_fixture.rs index 3ce9f6c5a..ba5fc8710 100644 --- a/crates/horizon-client/examples/natural_spawn_fixture.rs +++ b/crates/horizon-client/examples/natural_spawn_fixture.rs @@ -17,13 +17,16 @@ //! a `mobs::trial_spawner::TrialSpawner` with the game time advancing and //! print its states, events, spawns and ejected items. //! +//! Vault cases (`mode=vault`, tools/test_vault_parity.py) tick a +//! `vault::Vault` the same way, with players moving and using keys on it. +//! //! usage: natural_spawn_fixture RESOURCES INPUT OUTPUT use horizon_client::{ assets::Assets, biome::{Biomes, SpawnEntry}, blocks::BlockFacts, collisions::{self, LookupCollisions, no_collision_empty}, - items::Items, + items::{ItemStack, Items}, mobs::{ MobTypes, Species, data::MobData, @@ -37,6 +40,7 @@ use horizon_client::{ species::{self, Baby}, trial_spawner::{TrialEvent, TrialPlayer, TrialSpawner, TrialSpawnerLevel, TrialState}, }, + vault::{Vault, VaultEvent, VaultLevel, VaultPlayer, VaultState}, }; use horizon_core::{ geometry::Aabb, @@ -472,7 +476,7 @@ fn main() -> horizon_client::Result<()> { let data = MobData::load(root, &facts); let items = Items::tags_only(root)?; // Trial spawner rewards: the loot tables and the configs. - let loot = if input.contains("mode=trial") { + let loot = if input.contains("mode=trial") || input.contains("mode=vault") { horizon_client::mobs::trial_spawner::load_registry(root); horizon_client::structure_blocks::loot_data(root) } else { @@ -706,6 +710,9 @@ fn main() -> horizon_client::Result<()> { } else if mode == "trial" { let loot = loot.as_ref().ok_or("no loot tables")?; trial_case(&world, registry, loot, &get, &mut random, &mut log)?; + } else if mode == "vault" { + let loot = loot.as_ref().ok_or("no loot tables")?; + vault_case(world.players.clone(), loot, &get, &mut random, &mut log)?; } else if mode == "gen" { let mut gen_random = LegacyRandom::new(get("gseed", "0").parse()?); // The level random of the spawn predicates: no creature's predicate @@ -1101,3 +1108,195 @@ fn trial_case( log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0))); Ok(()) } + +/// What a vault reads: the game time and the case's players, moved by `move`. +struct VaultWorld { + time: i64, + players: Vec<([f64; 3], String)>, +} +impl VaultLevel for VaultWorld { + fn game_time(&self) -> i64 { + self.time + } + fn players(&self) -> Vec { + self.players + .iter() + .enumerate() + .map(|(i, (p, mode))| VaultPlayer { + uuid: [0, 0, 0, i as i32 + 1], + block: p.map(|v| v.floor() as i32), + spectator: mode == "spectator", + }) + .collect() + } +} +/// A UUID's low 64 bits, as the oracle prints players. +fn uuid_low(u: &[i32; 4]) -> String { + ((i64::from(u[2]) << 32) | i64::from(u[3] as u32)).to_string() +} +/// The display item and the connected players as the oracle prints them. +fn vault_shared(v: &Vault) -> String { + let mut connected: Vec = v.connected_players.iter().map(uuid_low).collect(); + connected.sort(); + format!( + "{} [{}]", + v.display_item + .as_ref() + .map_or_else(|| "-".to_owned(), |s| format!("{}*{}", s.item, s.count)), + connected.join(",") + ) +} + +/// `VaultBlockEntity.Server.tick` `ticks` times from game time `t0` at `spos` +/// on a vault block in state `state` (ominous with `ominous=1`) loaded from +/// `snbt` (base64 SNBT), with the case's key uses (`use`) and player moves +/// (`move`) before each tick, as the oracle logs it. +fn vault_case( + players: Vec<([f64; 3], String)>, + loot: &horizon_world::loot::LootData, + get: &dyn Fn(&str, &'static str) -> String, + random: &mut LegacyRandom, + log: &mut Vec, +) -> horizon_client::Result<()> { + let v: Vec = get("spos", "0,0,0") + .split(',') + .map(|n| n.parse().unwrap_or(0)) + .collect(); + let pos = [v[0], v[1], v[2]]; + let mut state = VaultState::from_name(&get("state", "inactive")).ok_or("bad state")?; + let ominous = get("ominous", "0") == "1"; + let text = horizon_client::skins::base64_decode(&get("snbt", "")).ok_or("bad snbt")?; + let tag = horizon_world::nbt::parse_snbt(&String::from_utf8(text)?)?.0; + let mut vault = Vault::load(&tag); + let schedule = |key: &str| -> Vec> { + get(key, "") + .split(';') + .filter(|s| !s.is_empty()) + .map(|s| s.split('/').map(str::to_owned).collect()) + .collect() + }; + let (uses, moves) = (schedule("use"), schedule("move")); + let ticks: i64 = get("ticks", "1").parse()?; + let t0: i64 = get("t0", "0").parse()?; + let seed: i64 = get("wseed", "0").parse()?; + let mut sequences = horizon_client::random_sequences::RandomSequences::default(); + let mut world = VaultWorld { time: t0, players }; + let center = pos.map(|v| f64::from(v) + 0.5); + for tick in 0..ticks { + world.time = t0 + tick; + let at = |s: &[String]| s[0].parse() == Ok(tick); + for m in moves.iter().filter(|m| at(m)) { + let v: Vec = m[2].split(',').map(|n| n.parse().unwrap_or(0.0)).collect(); + world.players[m[1].parse::()?].0 = [v[0], v[1], v[2]]; + } + let mut events = Vec::new(); + let mut roll = |table: &str, random: &mut LegacyRandom, sequence: bool| { + let drops = match loot.random_sequence(table).filter(|_| sequence) { + Some(s) => loot.roll_split(table, sequences.get(s, seed)), + None => loot.roll_split(table, random), + }; + drops + .iter() + .map(horizon_client::structure_blocks::loot_item_with_components) + .collect() + }; + for u in uses.iter().filter(|u| at(u)) { + let player: usize = u[1].parse()?; + let mut stack = ItemStack::new(&u[2], u[3].parse()?); + let used = vault.use_item_on( + &world, + random, + pos, + state, + ominous, + [0, 0, 0, player as i32 + 1], + Some(&stack), + &mut roll, + &mut events, + ); + if world.players[player].1 != "creative" { + stack.count -= used.unwrap_or(0); + } + vault_events(&mut events, &mut state, ominous, tick, center, &vault, log); + log.push(format!( + "{tick} use {} {}", + if used.is_some() { "ok" } else { "pass" }, + stack.count + )); + } + vault.server_tick(&world, random, pos, state, ominous, &mut roll, &mut events); + vault_events(&mut events, &mut state, ominous, tick, center, &vault, log); + } + let saved = vault.save(); + let config = saved + .iter() + .find(|(k, _)| *k == "config") + .and_then(|(_, t)| match t { + Tag::Compound(c) => { + let mut keys: Vec = c.keys().map(|k| k.to_string_lossy()).collect(); + keys.sort(); + Some(keys.join(",")) + } + _ => None, + }) + .unwrap_or_default(); + let eject: Vec = vault + .items_to_eject + .iter() + .map(|s| format!("{}*{}", s.item, s.count)) + .collect(); + log.push(format!( + "end state={} rewarded={} resumes={} eject={} total={} shared={} config={config}", + state.name(), + vault + .rewarded_players + .iter() + .map(uuid_low) + .collect::>() + .join(","), + vault.state_updating_resumes_at, + eject.join(","), + vault.total_ejections_needed, + vault_shared(&vault), + )); + log.push(format!("next {}", random.next_int_bound(1000).unwrap_or(0))); + Ok(()) +} +/// Logs a vault's events and applies its state changes. +fn vault_events( + events: &mut Vec, + state: &mut VaultState, + ominous: bool, + tick: i64, + center: [f64; 3], + vault: &Vault, + log: &mut Vec, +) { + for e in events.drain(..) { + match e { + VaultEvent::State(s) => { + *state = s; + log.push(format!("{tick} state {} {ominous}", s.name())); + } + VaultEvent::BlockUpdated => log.push(format!("{tick} update {}", vault_shared(vault))), + VaultEvent::LevelEvent(id, data) => log.push(format!("{tick} levent {id} {data}")), + VaultEvent::Sound(name, volume, pitch) => log.push(format!( + "{tick} sound minecraft:{name} {} {} {} {volume:?} {pitch:?}", + bits(center[0]), + bits(center[1]), + bits(center[2]) + )), + VaultEvent::Eject(stack, v) => log.push(format!( + "{tick} item {} {} {} {} {} {} {} {}", + stack.item, + stack.count, + bits(center[0]), + bits(center[1] + 0.7 - 0.125), + bits(center[2]), + bits(v[0]), + bits(v[1]), + bits(v[2]) + )), + } + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 319f1fa50..c12cd3ded 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -168,6 +168,7 @@ pub mod title_edition; pub mod ui; pub mod ui_theme; pub mod vanillagen; +pub mod vault; pub mod weather; pub mod widgets; pub mod window; diff --git a/crates/horizon-client/src/vault.rs b/crates/horizon-client/src/vault.rs new file mode 100644 index 000000000..deb82682e --- /dev/null +++ b/crates/horizon-client/src/vault.rs @@ -0,0 +1,745 @@ +//! The vault (`VaultBlockEntity` with its `VaultConfig`, `VaultServerData` +//! and `VaultSharedData`): the server tick that walks `VaultState` (inactive, +//! active while players who were not rewarded yet are near, unlocking when one +//! inserts the key, ejecting the rewards one by one) and the key insertion. +//! +//! The state lives in the block (`vault_state`); the tick reads it and reports +//! the next one. The level's random draws the display item and throws the +//! rewards; the loot tables go through the caller, so the game and a +//! differential test world roll them the same way. +use crate::items::ItemStack; +use horizon_core::random::RandomSource; +use horizon_world::nbt::{Compound, Tag}; + +/// A player's UUID as its four ints (`UUIDUtil.CODEC`). +pub type Uuid = [i32; 4]; + +/// `BuiltInLootTables.TRIAL_CHAMBERS_REWARD`, the default config's table. +pub const DEFAULT_LOOT_TABLE: &str = "minecraft:chests/trial_chambers/reward"; +const DEFAULT_ACTIVATION_RANGE: f64 = 4.0; +const DEFAULT_DEACTIVATION_RANGE: f64 = 4.5; +/// `VaultServerData.MAX_REWARD_PLAYERS`. +const MAX_REWARD_PLAYERS: usize = 128; +/// `UNLOCKING_DELAY_TICKS`, `INSERT_FAIL_SOUND_BUFFER_TICKS` and the 20 ticks +/// of `VaultState` between player checks and ejections. +const UNLOCKING_DELAY: i64 = 14; +const INSERT_FAIL_SOUND_BUFFER: i64 = 15; +const STATE_DELAY: i64 = 20; + +/// `VaultConfig`. +#[derive(Clone, Debug, PartialEq)] +pub struct VaultConfig { + pub loot_table: String, + pub activation_range: f64, + pub deactivation_range: f64, + /// None when the config has no key (`ItemStack.EMPTY`): the vault never opens. + pub key_item: Option, + pub override_loot_table_to_display: Option, +} + +impl Default for VaultConfig { + /// `VaultConfig.DEFAULT`: the trial key and the trial chambers' reward. + fn default() -> Self { + Self { + loot_table: DEFAULT_LOOT_TABLE.into(), + activation_range: DEFAULT_ACTIVATION_RANGE, + deactivation_range: DEFAULT_DEACTIVATION_RANGE, + key_item: Some(ItemStack::new("minecraft:trial_key", 1)), + override_loot_table_to_display: None, + } + } +} + +impl VaultConfig { + /// `VaultConfig.CODEC`: a field that fails to decode takes its default + /// (the key's is none); an activation range past the deactivation range + /// fails the whole config. + fn decode(tag: &Tag) -> Option { + let Tag::Compound(_) = tag else { + return None; + }; + let range = |k: &str, default: f64| crate::save::float(tag.get(k)).unwrap_or(default); + let config = Self { + loot_table: identifier(tag.get("loot_table")) + .unwrap_or_else(|| DEFAULT_LOOT_TABLE.into()), + activation_range: range("activation_range", DEFAULT_ACTIVATION_RANGE), + deactivation_range: range("deactivation_range", DEFAULT_DEACTIVATION_RANGE), + key_item: tag.get("key_item").and_then(stack), + override_loot_table_to_display: identifier(tag.get("override_loot_table_to_display")), + }; + (config.activation_range <= config.deactivation_range).then_some(config) + } + /// The fields that differ from their defaults. + fn encode(&self) -> Tag { + let mut out = Compound::new(); + if self.loot_table != DEFAULT_LOOT_TABLE { + out.insert( + "loot_table".into(), + Tag::String(self.loot_table.as_str().into()), + ); + } + if self.activation_range != DEFAULT_ACTIVATION_RANGE { + out.insert( + "activation_range".into(), + Tag::Double(self.activation_range.to_bits()), + ); + } + if self.deactivation_range != DEFAULT_DEACTIVATION_RANGE { + out.insert( + "deactivation_range".into(), + Tag::Double(self.deactivation_range.to_bits()), + ); + } + if let Some(key) = &self.key_item { + out.insert("key_item".into(), crate::save::item_to_nbt(key)); + } + if let Some(table) = &self.override_loot_table_to_display { + out.insert( + "override_loot_table_to_display".into(), + Tag::String(table.as_str().into()), + ); + } + Tag::Compound(out) + } +} + +/// `VaultState`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum VaultState { + #[default] + Inactive, + Active, + Unlocking, + Ejecting, +} + +impl VaultState { + const ALL: [Self; 4] = [ + Self::Inactive, + Self::Active, + Self::Unlocking, + Self::Ejecting, + ]; + pub fn name(self) -> &'static str { + match self { + Self::Inactive => "inactive", + Self::Active => "active", + Self::Unlocking => "unlocking", + Self::Ejecting => "ejecting", + } + } + pub fn from_name(name: &str) -> Option { + Self::ALL.into_iter().find(|s| s.name() == name) + } +} + +/// A player the vault can detect (`PlayerDetector.INCLUDING_CREATIVE_PLAYERS`). +#[derive(Clone, Copy, Debug)] +pub struct VaultPlayer { + pub uuid: Uuid, + pub block: [i32; 3], + pub spectator: bool, +} + +/// What a vault did that the level shows or sends. +#[derive(Clone, Debug, PartialEq)] +pub enum VaultEvent { + /// `setBlockAndUpdate` with this `vault_state`. + State(VaultState), + /// `sendBlockUpdated`: the clients load the new shared data. + BlockUpdated, + /// `levelEvent(id, pos, data)`. + LevelEvent(i32, i32), + /// `playSound(null, vault, sound, BLOCKS, volume, pitch)`. + Sound(&'static str, f32, f32), + /// `DefaultDispenseItemBehavior.spawnItem` from the top of the vault: + /// the item and its velocity. + Eject(ItemStack, [f64; 3]), +} + +/// What a vault reads from the level. +pub trait VaultLevel { + fn game_time(&self) -> i64; + /// `level.getPlayers()`, in the server's order. + fn players(&self) -> Vec; +} + +/// Rolls a loot table (`LootTable.getRandomItems`, stacks split) with the +/// level random, or with the table's random sequence when the flag is set and +/// the table has one. +pub type Roll<'a, R> = dyn FnMut(&str, &mut R, bool) -> Vec + 'a; + +/// `VaultBlockEntity`: its config, server data and shared data. +#[derive(Clone, Debug, PartialEq)] +pub struct Vault { + pub config: VaultConfig, + /// `VaultServerData`, oldest rewarded player first. + pub rewarded_players: Vec, + pub state_updating_resumes_at: i64, + /// Popped from the end. + pub items_to_eject: Vec, + pub total_ejections_needed: i32, + pub last_insert_fail_timestamp: i64, + /// `VaultSharedData`. + pub display_item: Option, + pub connected_players: Vec, + pub connected_particles_range: f64, + /// The shared data changed since the last tick sent it. + pub shared_dirty: bool, +} + +impl Default for Vault { + fn default() -> Self { + Self { + config: VaultConfig::default(), + rewarded_players: Vec::new(), + state_updating_resumes_at: 0, + items_to_eject: Vec::new(), + total_ejections_needed: 0, + last_insert_fail_timestamp: 0, + display_item: None, + connected_players: Vec::new(), + connected_particles_range: DEFAULT_DEACTIVATION_RANGE, + shared_dirty: false, + } + } +} + +/// An `Identifier` (`minecraft` when the namespace is left out). +fn identifier(t: Option<&Tag>) -> Option { + match t? { + Tag::String(s) => crate::mobs::spawner::normalize_id(&s.to_string_lossy()), + _ => None, + } +} +/// `ItemStack.CODEC`: an item other than air, 1 to 99 of it. +fn stack(tag: &Tag) -> Option { + let id = identifier(tag.get("id"))?; + if let Some(count) = tag.get("count") + && !crate::save::number(Some(count)).is_some_and(|c| (1..=99).contains(&c)) + { + return None; + } + let mut item = crate::save::item_from_nbt(tag)?; + item.item = id.as_str().into(); + (&*item.item != "minecraft:air").then_some(item) +} +/// `UUIDUtil.CODEC_LINKED_SET`: every entry a UUID, duplicates dropped. +fn uuids(tag: Option<&Tag>) -> Option> { + let Tag::List(list) = tag? else { + return None; + }; + let mut out: Vec = Vec::new(); + for t in list { + let Tag::IntArray(v) = t else { + return None; + }; + let u = ::try_from(v.as_slice()).ok()?; + if !out.contains(&u) { + out.push(u); + } + } + Some(out) +} +fn encode_uuids(list: &[Uuid]) -> Tag { + Tag::List(list.iter().map(|u| Tag::IntArray(u.to_vec())).collect()) +} +/// `ItemStack.matches`, with None as the empty stack. +fn matches(a: Option<&ItemStack>, b: Option<&ItemStack>) -> bool { + match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => a.count == b.count && a.same_item_same_components(b), + _ => false, + } +} +fn same_set(a: &[Uuid], b: &[Uuid]) -> bool { + a.len() == b.len() && a.iter().all(|u| b.contains(u)) +} + +impl Vault { + /// `loadAdditional`. `VaultServerData.set` leaves the total of ejections + /// out, so a vault loaded mid-ejection counts from 0. + pub fn load(tag: &Tag) -> Self { + let mut v = Self { + config: tag + .get("config") + .map_or_else(|| Some(VaultConfig::default()), VaultConfig::decode) + .unwrap_or_default(), + ..Self::default() + }; + if let Some(Tag::Compound(_)) = tag.get("server_data") { + let server = tag.get("server_data"); + let get = |k: &str| server.and_then(|s| s.get(k)); + v.rewarded_players = uuids(get("rewarded_players")).unwrap_or_default(); + v.state_updating_resumes_at = + crate::save::number(get("state_updating_resumes_at")).unwrap_or(0); + v.items_to_eject = match get("items_to_eject") { + Some(Tag::List(list)) => list + .iter() + .map(stack) + .collect::>() + .unwrap_or_default(), + _ => Vec::new(), + }; + } + if let Some(Tag::Compound(_)) = tag.get("shared_data") { + let shared = tag.get("shared_data"); + let get = |k: &str| shared.and_then(|s| s.get(k)); + v.display_item = get("display_item").and_then(stack); + v.connected_players = uuids(get("connected_players")).unwrap_or_default(); + v.connected_particles_range = crate::save::float(get("connected_particles_range")) + .unwrap_or(DEFAULT_DEACTIVATION_RANGE); + } + v + } + /// `saveAdditional`: the config, shared data and server data. + pub fn save(&self) -> Vec<(&'static str, Tag)> { + let mut server = Compound::new(); + if !self.rewarded_players.is_empty() { + server.insert( + "rewarded_players".into(), + encode_uuids(&self.rewarded_players), + ); + } + if self.state_updating_resumes_at != 0 { + server.insert( + "state_updating_resumes_at".into(), + Tag::Long(self.state_updating_resumes_at), + ); + } + if !self.items_to_eject.is_empty() { + let items = self + .items_to_eject + .iter() + .map(crate::save::item_to_nbt) + .collect(); + server.insert("items_to_eject".into(), Tag::List(items)); + } + if self.total_ejections_needed != 0 { + server.insert( + "total_ejections_needed".into(), + Tag::Int(self.total_ejections_needed), + ); + } + vec![ + ("config", self.config.encode()), + ("shared_data", self.update_shared()), + ("server_data", Tag::Compound(server)), + ] + } + /// `VaultSharedData.CODEC`. + fn update_shared(&self) -> Tag { + let mut out = Compound::new(); + if let Some(item) = &self.display_item { + out.insert("display_item".into(), crate::save::item_to_nbt(item)); + } + if !self.connected_players.is_empty() { + out.insert( + "connected_players".into(), + encode_uuids(&self.connected_players), + ); + } + if self.connected_particles_range != DEFAULT_DEACTIVATION_RANGE { + out.insert( + "connected_particles_range".into(), + Tag::Double(self.connected_particles_range.to_bits()), + ); + } + Tag::Compound(out) + } + /// `getUpdateTag`: the shared data the clients see. + pub fn update_tag(&self) -> Tag { + Tag::compound([("shared_data", self.update_shared())]) + } + /// `VaultSharedData.setDisplayItem`. + fn set_display_item(&mut self, item: Option) { + if !matches(self.display_item.as_ref(), item.as_ref()) { + self.display_item = item; + self.shared_dirty = true; + } + } + /// `canEjectReward`. + fn can_eject_reward(&self, state: VaultState) -> bool { + self.config.key_item.is_some() && state != VaultState::Inactive + } + /// `cycleDisplayItemFromLootTable`: one item of the display table, rolled + /// with the level random (`Util.getRandom`). + fn cycle_display_item( + &mut self, + state: VaultState, + random: &mut R, + roll: &mut Roll, + ) { + if !self.can_eject_reward(state) { + self.set_display_item(None); + return; + } + let table = self + .config + .override_loot_table_to_display + .as_ref() + .unwrap_or(&self.config.loot_table); + let mut items = roll(table, random, false); + let item = if items.is_empty() { + None + } else { + let i = random.next_int_bound(items.len() as i32).unwrap_or(0) as usize; + Some(items.swap_remove(i)) + }; + self.set_display_item(item); + } + /// `VaultSharedData.updateConnectedPlayersWithinRange` with + /// `PlayerDetector.INCLUDING_CREATIVE_PLAYERS`. + fn update_connected_players(&mut self, l: &L, pos: [i32; 3], range: f64) { + let found: Vec = l + .players() + .into_iter() + .filter(|p| { + let d = [0, 1, 2].map(|i| f64::from(p.block[i] - pos[i])); + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < range * range && !p.spectator + }) + .map(|p| p.uuid) + .filter(|u| !self.rewarded_players.contains(u)) + .collect(); + if !same_set(&self.connected_players, &found) { + self.connected_players = found; + self.shared_dirty = true; + } + } + /// `updateStateForConnectedPlayers`. + fn update_state_for_connected_players( + &mut self, + l: &L, + pos: [i32; 3], + range: f64, + ) -> VaultState { + self.update_connected_players(l, pos, range); + self.state_updating_resumes_at = l.game_time() + STATE_DELAY; + if self.connected_players.is_empty() { + VaultState::Inactive + } else { + VaultState::Active + } + } + /// `VaultServerData.ejectionProgress`. + fn ejection_progress(&self) -> f32 { + if self.total_ejections_needed == 1 { + return 1.0; + } + // Mth.inverseLerp(size, 1, total), in floats. + let size = self.items_to_eject.len() as f32; + 1.0 - (size - 1.0) / (self.total_ejections_needed as f32 - 1.0) + } + /// `VaultState.tickAndGetNext`. + fn tick_and_get_next( + &mut self, + l: &L, + random: &mut R, + pos: [i32; 3], + state: VaultState, + events: &mut Vec, + ) -> VaultState { + match state { + VaultState::Inactive => { + self.update_state_for_connected_players(l, pos, self.config.activation_range) + } + VaultState::Active => { + self.update_state_for_connected_players(l, pos, self.config.deactivation_range) + } + VaultState::Unlocking => { + self.state_updating_resumes_at = l.game_time() + STATE_DELAY; + VaultState::Ejecting + } + VaultState::Ejecting => { + // The progress counts the item being ejected. + let progress = self.ejection_progress(); + let Some(item) = self.items_to_eject.pop() else { + self.total_ejections_needed = 0; + return self.update_state_for_connected_players( + l, + pos, + self.config.deactivation_range, + ); + }; + // DefaultDispenseItemBehavior.spawnItem going up, accuracy 2: the + // power only scales x and z, which are 0. + random.next_double(); + let spread = 0.017_227_5 * 2.0; + let v = [ + random.triangle(0.0, spread), + random.triangle(0.2, spread), + random.triangle(0.0, spread), + ]; + events.push(VaultEvent::Eject(item, v)); + events.push(VaultEvent::LevelEvent(3017, 0)); + events.push(VaultEvent::Sound( + "block.vault.eject_item", + 1.0, + 0.8 + 0.4 * progress, + )); + self.set_display_item(self.items_to_eject.last().cloned()); + self.state_updating_resumes_at = l.game_time() + STATE_DELAY; + VaultState::Ejecting + } + } + } + /// `VaultState.onTransition`: `from`'s exit, then `to`'s entry. + #[allow(clippy::too_many_arguments)] + fn on_transition( + &mut self, + from: VaultState, + to: VaultState, + ominous: bool, + random: &mut R, + roll: &mut Roll, + events: &mut Vec, + ) { + events.push(VaultEvent::State(to)); + if from == VaultState::Ejecting { + events.push(VaultEvent::Sound("block.vault.close_shutter", 1.0, 1.0)); + } + match to { + VaultState::Inactive => { + self.set_display_item(None); + events.push(VaultEvent::LevelEvent(3016, i32::from(ominous))); + } + VaultState::Active => { + if self.display_item.is_none() { + self.cycle_display_item(to, random, roll); + } + events.push(VaultEvent::LevelEvent(3015, i32::from(ominous))); + } + VaultState::Unlocking => { + events.push(VaultEvent::Sound("block.vault.insert_item", 1.0, 1.0)) + } + VaultState::Ejecting => { + events.push(VaultEvent::Sound("block.vault.open_shutter", 1.0, 1.0)) + } + } + } + /// `VaultBlockEntity.Server.tick`: the next state of the block. + #[allow(clippy::too_many_arguments)] + pub fn server_tick( + &mut self, + l: &L, + random: &mut R, + pos: [i32; 3], + state: VaultState, + ominous: bool, + roll: &mut Roll, + events: &mut Vec, + ) -> VaultState { + let now = l.game_time(); + if now % 20 == 0 && state == VaultState::Active { + self.cycle_display_item(state, random, roll); + } + let mut next = state; + if now >= self.state_updating_resumes_at { + next = self.tick_and_get_next(l, random, pos, state, events); + if next != state { + self.on_transition(state, next, ominous, random, roll, events); + } + } + if std::mem::take(&mut self.shared_dirty) { + events.push(VaultEvent::BlockUpdated); + } + next + } + /// `VaultBlock.useItemOn`: None when the item passes to the empty hand (an + /// empty hand or a vault that is not active), else how many of `stack` + /// the vault takes (none from a player with infinite materials). + #[allow(clippy::too_many_arguments)] + pub fn use_item_on( + &mut self, + l: &L, + random: &mut R, + pos: [i32; 3], + state: VaultState, + ominous: bool, + player: Uuid, + stack: Option<&ItemStack>, + roll: &mut Roll, + events: &mut Vec, + ) -> Option { + let stack = stack.filter(|s| s.count > 0)?; + (state == VaultState::Active).then(|| { + self.try_insert_key(l, random, pos, state, ominous, player, stack, roll, events) + }) + } + /// `VaultBlockEntity.Server.tryInsertKey`: how many of `stack` the vault + /// takes. + #[allow(clippy::too_many_arguments)] + fn try_insert_key( + &mut self, + l: &L, + random: &mut R, + pos: [i32; 3], + state: VaultState, + ominous: bool, + player: Uuid, + stack: &ItemStack, + roll: &mut Roll, + events: &mut Vec, + ) -> u32 { + if !self.can_eject_reward(state) { + return 0; + } + let Some(key) = &self.config.key_item else { + return 0; + }; + let key_count = key.count; + if !(stack.same_item_same_components(key) && stack.count >= key_count) { + self.play_insert_fail_sound(l, "block.vault.insert_item_fail", events); + return 0; + } + if self.rewarded_players.contains(&player) { + self.play_insert_fail_sound(l, "block.vault.reject_rewarded_player", events); + return 0; + } + let items = roll(&self.config.loot_table.clone(), random, true); + if items.is_empty() { + return 0; + } + // unlock + self.total_ejections_needed = items.len() as i32; + self.items_to_eject = items; + self.set_display_item(self.items_to_eject.last().cloned()); + self.state_updating_resumes_at = l.game_time() + UNLOCKING_DELAY; + self.on_transition(state, VaultState::Unlocking, ominous, random, roll, events); + // addToRewardedPlayers + if !self.rewarded_players.contains(&player) { + self.rewarded_players.push(player); + if self.rewarded_players.len() > MAX_REWARD_PLAYERS { + self.rewarded_players.remove(0); + } + } + self.update_connected_players(l, pos, self.config.deactivation_range); + key_count + } + /// `playInsertFailSound`: at most once every 15 ticks. + fn play_insert_fail_sound( + &mut self, + l: &L, + sound: &'static str, + events: &mut Vec, + ) { + if l.game_time() >= self.last_insert_fail_timestamp + INSERT_FAIL_SOUND_BUFFER { + events.push(VaultEvent::Sound(sound, 1.0, 1.0)); + self.last_insert_fail_timestamp = l.game_time(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::random::LegacyRandom; + + fn tag(snbt: &str) -> Tag { + horizon_world::nbt::parse_snbt(snbt).expect("snbt").0 + } + struct Level { + time: i64, + players: Vec, + } + impl VaultLevel for Level { + fn game_time(&self) -> i64 { + self.time + } + fn players(&self) -> Vec { + self.players.clone() + } + } + + #[test] + fn a_missing_config_is_the_trial_key_and_an_invalid_one_too() { + assert_eq!(Vault::load(&tag("{}")).config, VaultConfig::default()); + let v = Vault::load(&tag( + "{config:{activation_range:5.0d,deactivation_range:4.0d}}", + )); + assert_eq!(v.config, VaultConfig::default()); + // A config without a key never opens. + let v = Vault::load(&tag( + r#"{config:{loot_table:"minecraft:chests/trial_chambers/reward_ominous"}}"#, + )); + assert_eq!(v.config.key_item, None); + assert!(!v.can_eject_reward(VaultState::Active)); + } + + #[test] + fn a_rewarded_player_is_refused_and_a_new_one_unlocks() { + let player = [0, 0, 0, 1]; + let l = Level { + time: 100, + players: vec![VaultPlayer { + uuid: player, + block: [1, 0, 0], + spectator: false, + }], + }; + let mut v = Vault::default(); + let mut random = LegacyRandom::new(1); + let mut events = Vec::new(); + let key = ItemStack::new("minecraft:trial_key", 1); + let mut roll = + |_: &str, _: &mut LegacyRandom, _: bool| vec![ItemStack::new("minecraft:diamond", 2)]; + let pos = [0, 0, 0]; + let taken = v.use_item_on( + &l, + &mut random, + pos, + VaultState::Inactive, + false, + player, + Some(&key), + &mut roll, + &mut events, + ); + assert_eq!(taken, None); + let taken = v.use_item_on( + &l, + &mut random, + pos, + VaultState::Active, + false, + player, + Some(&key), + &mut roll, + &mut events, + ); + assert_eq!(taken, Some(1)); + assert_eq!(events[0], VaultEvent::State(VaultState::Unlocking)); + assert_eq!(v.rewarded_players, [player]); + assert_eq!(v.state_updating_resumes_at, 114); + events.clear(); + let taken = v.use_item_on( + &l, + &mut random, + pos, + VaultState::Active, + false, + player, + Some(&key), + &mut roll, + &mut events, + ); + assert_eq!(taken, Some(0)); + assert_eq!( + events, + [VaultEvent::Sound( + "block.vault.reject_rewarded_player", + 1.0, + 1.0 + )] + ); + } + + #[test] + fn saved_data_round_trips() { + let v = Vault::load(&tag( + r#"{server_data:{rewarded_players:[[I;0,0,0,1]],state_updating_resumes_at:40L,items_to_eject:[{id:"minecraft:emerald",count:3}]},shared_data:{display_item:{id:"minecraft:emerald",count:3}}}"#, + )); + let saved = Tag::compound(v.save()); + assert_eq!(Vault::load(&saved), v); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java index 5c2e9569d..6c40115ba 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java @@ -81,7 +81,9 @@ import net.minecraft.world.phys.Vec3; * Spawner cases tick a SpawnerBlockEntity; trial cases tick a * TrialSpawnerBlockEntity with the game time advancing, its block's state * changes, sounds, ejected items (loot tables and random sequences of the - * vanilla data) and, when asked, the death of every mob it spawned. + * vanilla data) and, when asked, the death of every mob it spawned. Vault + * cases tick a VaultBlockEntity the same way, with players moving and using + * keys on it. */ public final class VanillaNaturalSpawnOracle { static Object unsafe; @@ -226,10 +228,14 @@ public final class VanillaNaturalSpawnOracle { @Override public boolean setBlock(BlockPos pos, BlockState state, int flags, int recursionLeft) { blocks.add(Map.entry(new Box(pos.getX(), pos.getY(), pos.getZ(), pos.getX(), pos.getY(), pos.getZ()), state)); if (trial != null && trial.getBlockPos().equals(pos)) trial.setBlockState(state); - if (tick >= 0) log.add(tick + " state " + state.getOptionalValue(net.minecraft.world.level.block.TrialSpawnerBlock.STATE).map(v -> v.getSerializedName()).orElse("-") + if (tick >= 0) log.add(tick + " state " + state.getOptionalValue(net.minecraft.world.level.block.TrialSpawnerBlock.STATE).map(v -> v.getSerializedName()) + .or(() -> state.getOptionalValue(net.minecraft.world.level.block.VaultBlock.STATE).map(v -> v.getSerializedName())).orElse("-") + " " + state.getOptionalValue(net.minecraft.world.level.block.TrialSpawnerBlock.OMINOUS).orElse(false)); return true; } + @Override public net.minecraft.world.level.block.entity.BlockEntity getBlockEntity(BlockPos pos) { + return trial != null && trial.getBlockPos().equals(pos) ? trial : null; + } @Override public void blockEntityChanged(BlockPos pos) {} @Override public void updateNeighbourForOutputSignal(BlockPos pos, net.minecraft.world.level.block.Block block) {} @Override public Entity getEntity(UUID uuid) { @@ -241,7 +247,11 @@ public final class VanillaNaturalSpawnOracle { if (tick >= 0) log.add(tick + " sound " + sound.location() + " " + bits(x) + " " + bits(y) + " " + bits(z) + " " + volume + " " + pitch); } @Override public void blockEvent(BlockPos pos, net.minecraft.world.level.block.Block block, int b0, int b1) { if (tick >= 0) log.add(tick + " bevent " + b0 + " " + b1); } - @Override public void sendBlockUpdated(BlockPos pos, BlockState old, BlockState current, int flags) { if (tick >= 0) log.add(tick + " update"); } + @Override public void sendBlockUpdated(BlockPos pos, BlockState old, BlockState current, int flags) { + if (tick < 0) return; + if (trial instanceof net.minecraft.world.level.block.entity.vault.VaultBlockEntity vault) log.add(tick + " update " + vaultShared(vault.getSharedData())); + else log.add(tick + " update"); + } @Override public void levelEvent(Entity source, int type, BlockPos pos, int data) { if (tick >= 0) log.add(tick + " levent " + type + " " + data); } @Override public void gameEvent(Holder event, Vec3 at, net.minecraft.world.level.gameevent.GameEvent.Context context) { if (tick >= 0) log.add(tick + " gevent " + event.unwrapKey().orElseThrow().identifier() + " " + Mth.floor(at.x) + " " + Mth.floor(at.y) + " " + Mth.floor(at.z)); @@ -380,6 +390,96 @@ public final class VanillaNaturalSpawnOracle { @Override public boolean isCreative() { return mode == GameType.CREATIVE; } @Override public GameType gameMode() { return mode; } @Override public boolean isAlive() { return true; } + // Vault key insertion: no attributes, stats or abilities on the stand-in. + @Override public float getLuck() { return 0.0F; } + @Override public void awardStat(net.minecraft.stats.Stat stat, int count) {} + @Override public boolean hasInfiniteMaterials() { return mode == GameType.CREATIVE; } + } + + static String stack(net.minecraft.world.item.ItemStack s) { + return s.isEmpty() ? "-" : BuiltInRegistries.ITEM.getKey(s.getItem()) + "*" + s.getCount(); + } + /** A UUID set as the players' indices (the low bits), sorted. */ + static String players(java.util.Collection set) { + return set.stream().map(u -> Long.toString(u.getLeastSignificantBits())).sorted().collect(java.util.stream.Collectors.joining(",", "[", "]")); + } + @SuppressWarnings("unchecked") + static String vaultShared(net.minecraft.world.level.block.entity.vault.VaultSharedData shared) { + try { + Field connected = shared.getClass().getDeclaredField("connectedPlayers"); + connected.setAccessible(true); + return stack(shared.getDisplayItem()) + " " + players((Set) connected.get(shared)); + } catch (ReflectiveOperationException e) { + throw new RuntimeException(e); + } + } + + /** + * VaultBlockEntity.Server.tick `ticks` times from game time `t0` at `spos`, + * on a vault block in state `state` (ominous when `ominous=1`) loaded from + * `snbt` (base64 SNBT). Before a tick's server tick, `use` (`;` apart, + * tick/player/item/count) has a player use that stack on the vault + * (VaultBlock.useItemOn) and `move` (tick/player/x,y,z) moves a player. + */ + static void vaultCase(Lvl level, Map c, RegistryAccess access, HolderLookup blockLookup, + RandomSource mainRandom, List log) throws Exception { + level.spawnerRandom = mainRandom; + level.tick = -1; + String[] sp = c.get("spos").split(","); + BlockPos at = new BlockPos(Integer.parseInt(sp[0]), Integer.parseInt(sp[1]), Integer.parseInt(sp[2])); + BlockState block = net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blockLookup, + "minecraft:vault[vault_state=" + c.getOrDefault("state", "inactive") + ",ominous=" + c.getOrDefault("ominous", "0").equals("1") + "]", false).blockState(); + level.blocks.add(Map.entry(new Box(at.getX(), at.getY(), at.getZ(), at.getX(), at.getY(), at.getZ()), block)); + var nbt = net.minecraft.nbt.TagParser.parseCompoundFully(new String(Base64.getDecoder().decode(c.get("snbt")), StandardCharsets.UTF_8)); + var entity = new net.minecraft.world.level.block.entity.vault.VaultBlockEntity(at, block); + entity.setLevel(level); + level.trial = entity; + entity.loadWithComponents(net.minecraft.world.level.storage.TagValueInput.create(net.minecraft.util.ProblemReporter.DISCARDING, access, nbt)); + Map> uses = new HashMap<>(), moves = new HashMap<>(); + for (String u : c.getOrDefault("use", "").split(";")) if (!u.isEmpty()) uses.computeIfAbsent(Integer.parseInt(u.split("/")[0]), k -> new ArrayList<>()).add(u.split("/")); + for (String m : c.getOrDefault("move", "").split(";")) if (!m.isEmpty()) moves.computeIfAbsent(Integer.parseInt(m.split("/")[0]), k -> new ArrayList<>()).add(m.split("/")); + int ticks = Integer.parseInt(c.getOrDefault("ticks", "1")); + long t0 = Long.parseLong(c.getOrDefault("t0", "0")); + try { + for (int t = 0; t < ticks; t++) { + level.tick = t; + level.time = t0 + t; + for (String[] m : moves.getOrDefault(t, List.of())) { + Entity p = level.playerList.get(Integer.parseInt(m[1])); + String[] v = m[2].split(","); + Vec3 to = new Vec3(Double.parseDouble(v[0]), Double.parseDouble(v[1]), Double.parseDouble(v[2])); + put(p, Entity.class, "position", to); + put(p, Entity.class, "blockPosition", BlockPos.containing(to)); + } + for (String[] u : uses.getOrDefault(t, List.of())) { + Player p = level.playerList.get(Integer.parseInt(u[1])); + var item = new net.minecraft.world.item.ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse(u[2])), Integer.parseInt(u[3])); + var result = ((net.minecraft.world.level.block.VaultBlock) Blocks.VAULT).useItemOn(item, level.getBlockState(at), level, at, p, + net.minecraft.world.InteractionHand.MAIN_HAND, null); + log.add(t + " use " + (result instanceof net.minecraft.world.InteractionResult.Success ? "ok" : "pass") + " " + item.getCount()); + } + BlockState state = level.getBlockState(at); + net.minecraft.world.level.block.entity.vault.VaultBlockEntity.Server.tick(level, at, state, entity.getConfig(), entity.getServerData(), entity.getSharedData()); + } + } finally { + level.tick = -1; + level.spawnerRandom = null; + } + CompoundTag saved = entity.saveWithoutMetadata(access); + CompoundTag server = saved.getCompoundOrEmpty("server_data"); + StringBuilder eject = new StringBuilder(); + for (var t : server.getListOrEmpty("items_to_eject")) { + CompoundTag item = (CompoundTag) t; + eject.append(eject.isEmpty() ? "" : ",").append(item.getStringOr("id", "-")).append('*').append(item.getIntOr("count", 1)); + } + StringBuilder rewarded = new StringBuilder(); + for (var t : server.getListOrEmpty("rewarded_players")) + rewarded.append(rewarded.isEmpty() ? "" : ",").append(net.minecraft.core.UUIDUtil.uuidFromIntArray(((net.minecraft.nbt.IntArrayTag) t).getAsIntArray()).getLeastSignificantBits()); + log.add("end state=" + level.getBlockState(at).getValue(net.minecraft.world.level.block.VaultBlock.STATE).getSerializedName() + + " rewarded=" + rewarded + " resumes=" + server.getLongOr("state_updating_resumes_at", 0L) + " eject=" + eject + + " total=" + server.getIntOr("total_ejections_needed", 0) + " shared=" + vaultShared(entity.getSharedData()) + + " config=" + saved.getCompoundOrEmpty("config").keySet().stream().sorted().collect(java.util.stream.Collectors.joining(","))); + log.add("next " + mainRandom.nextInt(1000)); } static String bits(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); } @@ -656,6 +756,8 @@ public final class VanillaNaturalSpawnOracle { log.add("next " + mainRandom.nextInt(1000)); } else if (mode.equals("trial")) { trialCase(level, c, access, blockLookup, mainRandom, log); + } else if (mode.equals("vault")) { + vaultCase(level, c, access, blockLookup, mainRandom, log); } else if (mode.equals("gen")) { level.logColumns = true; int n = level.entities.size(); diff --git a/tools/test_vault_parity.py b/tools/test_vault_parity.py new file mode 100644 index 000000000..7eeace526 --- /dev/null +++ b/tools/test_vault_parity.py @@ -0,0 +1,225 @@ +#!/usr/bin/env python3 +"""Compare vaults (VaultBlockEntity.Server, VaultState and VaultBlock.useItemOn) with vanilla. + +Java (VanillaNaturalSpawnOracle, mode=vault) loads a VaultBlockEntity from +each case's NBT on the oracle's stand-in ServerLevel, on a vault block in the +case's state, and runs `VaultBlockEntity.Server.tick` tick by tick with the +game time advancing; before a tick, players move and use stacks on the vault +through `VaultBlock.useItemOn`. Rust (natural_spawn_fixture, mode=vault) loads +`vault::Vault` from the same NBT and does the same. Both log, tick by tick, +the block's state changes, the level events, the sounds (with their pitch), +each ejected item (type, count, position and velocity bits), every shared data +update (display item and connected players), each use (accepted or not and +the stack left), and at the end the saved server and shared data, the saved +config's fields and the next draw of the level random, which pins every draw +in between (the display item rolls, the ejection velocities). + +Configs are the default, the ominous vaults' and inline ones from the edge +values up (activation past deactivation, keys of two, no key); saved data has +rewarded players, a paused state, items left to eject and display items. +Players stand in and out of the activation and deactivation ranges in every +game mode, walk in and out, and use trial keys, ominous keys, too few keys and +other items, more than once and after being rewarded. +""" +import argparse +import base64 +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab, test_rust_parity as base, test_natural_spawn_parity as natural +except ImportError: + import lab + import test_rust_parity as base + import test_natural_spawn_parity as natural + +box = natural.box +STATES = ['inactive', 'active', 'unlocking', 'ejecting'] +TABLES = ['minecraft:chests/trial_chambers/reward', 'minecraft:chests/trial_chambers/reward_ominous', + 'minecraft:chests/trial_chambers/reward_rare', 'minecraft:chests/trial_chambers/reward_common', + 'minecraft:spawners/trial_chamber/consumables', 'minecraft:chests/simple_dungeon', 'minecraft:empty'] +ITEMS = ['minecraft:trial_key', 'minecraft:ominous_trial_key', 'minecraft:diamond', 'minecraft:emerald', + 'minecraft:golden_apple', 'minecraft:arrow', 'minecraft:heavy_core'] + + +def uuid(rng): + return '[I;' + ','.join(str(rng.randrange(-2**31, 2**31)) for _ in range(4)) + ']' + + +def player_uuid(i): + return f'[I;0,0,0,{i + 1}]' + + +def stack(rng): + item = rng.choice(ITEMS) + return f'{{id:"{item}",count:{rng.choice([1, 1, 1, 2, 3, 64])}}}' + + +def config(rng): + r = rng.random() + if r < 0.35: + return None + if r < 0.6: + # The ominous vaults of the trial chambers. + return '{key_item:{count:1,id:"minecraft:ominous_trial_key"},loot_table:"minecraft:chests/trial_chambers/reward_ominous"}' + fields = [] + if rng.random() < 0.5: + fields.append(f'loot_table:"{rng.choice(TABLES)}"') + if rng.random() < 0.4: + fields.append(f'activation_range:{rng.choice([0.0, 1.0, 2.5, 4.0, 6.0])}d') + if rng.random() < 0.4: + fields.append(f'deactivation_range:{rng.choice([0.5, 3.0, 4.5, 8.0])}d') + if rng.random() < 0.85: + key = rng.choice(['minecraft:trial_key', 'minecraft:trial_key', 'minecraft:ominous_trial_key', 'minecraft:diamond']) + fields.append(f'key_item:{{count:{rng.choice([1, 1, 1, 2])},id:"{key}"}}') + if rng.random() < 0.3: + fields.append(f'override_loot_table_to_display:"{rng.choice(TABLES)}"') + return '{' + ','.join(fields) + '}' + + +def vault_snbt(rng, now, count): + fields = [] + c = config(rng) + if c is not None: + fields.append(f'config:{c}') + server = [] + if count and rng.random() < 0.25: + rewarded = rng.sample(range(count), rng.randrange(1, count + 1)) + server.append('rewarded_players:[' + ','.join(player_uuid(i) for i in rewarded) + ']') + elif rng.random() < 0.1: + server.append(f'rewarded_players:[{uuid(rng)}]') + if rng.random() < 0.3: + server.append(f'state_updating_resumes_at:{now + rng.choice([-20, 0, 5, 19, 40])}L') + if rng.random() < 0.15: + server.append('items_to_eject:[' + ','.join(stack(rng) for _ in range(rng.randrange(1, 4))) + ']') + if rng.random() < 0.1: + server.append(f'total_ejections_needed:{rng.choice([0, 1, 3])}') + if server or rng.random() < 0.3: + fields.append('server_data:{' + ','.join(server) + '}') + shared = [] + if rng.random() < 0.25: + shared.append(f'display_item:{stack(rng)}') + if count and rng.random() < 0.2: + shared.append('connected_players:[' + ','.join(player_uuid(i) for i in range(rng.randrange(1, count + 1))) + ']') + if rng.random() < 0.1: + shared.append(f'connected_particles_range:{rng.choice([2.0, 4.5, 9.0])}d') + if shared: + fields.append('shared_data:{' + ','.join(shared) + '}') + return '{' + ','.join(fields) + '}' + + +def spot(rng, vpos): + """A player position near the vault, around its activation (4) and deactivation (4.5) ranges.""" + d = rng.choice([0.5, 1.5, 2.5, 3.5, 4.2, 4.6, 5.5, 8.0]) + dx = rng.uniform(-d, d) + dz = rng.choice([-1, 1]) * max(0.0, d * d - dx * dx) ** 0.5 + return vpos[0] + 0.5 + dx, vpos[1] + rng.choice([0, 0, 0, 1, -1, 3]), vpos[2] + 0.5 + dz + + +def corpus(): + rng = random.Random(0x5641554c) + cases = [] + for k in range(3000): + w = natural.World(rng) + w.kv['dim'] = w.dim = 'minecraft:overworld' + vpos = (rng.randrange(-8, 9), rng.randrange(-40, 20), rng.randrange(-8, 9)) + w.block(box(vpos[0] - 10, vpos[1] - 1, vpos[2] - 10, vpos[0] + 10, vpos[1] - 1, vpos[2] + 10), 'minecraft:tuff_bricks') + count = rng.choice([0, 1, 1, 1, 2, 2, 3]) + modes = [] + for _ in range(count): + mode = rng.choice(['survival'] * 6 + ['creative', 'adventure', 'spectator']) + modes.append(mode) + x, y, z = spot(rng, vpos) + w.players.append(f'{x:.3f},{y:.3f},{z:.3f}/{mode}') + natural.common(w, rng, rng.randrange(-2**47, 2**47)) + for key in ('unloaded', 'respawn', 'spawners', 'rules'): + w.kv.pop(key, None) + t0 = rng.choice([0, 1, 15, 19, 20, 1000, rng.randrange(0, 10**6), rng.randrange(10**9, 10**12)]) + ticks = rng.choice([1, 2, 20, 21, 60, 100, 200, 400]) + w.kv['spos'] = f'{vpos[0]},{vpos[1]},{vpos[2]}' + w.kv['state'] = rng.choices(STATES, [5, 5, 1, 1])[0] + w.kv['ominous'] = int(rng.random() < 0.3) + w.kv['snbt'] = base64.b64encode(vault_snbt(rng, t0, count).encode()).decode() + w.kv['t0'] = t0 + w.kv['ticks'] = ticks + if count: + uses = [] + for _ in range(rng.choice([0, 1, 1, 2, 3, 6])): + item = rng.choice(['minecraft:trial_key'] * 4 + ['minecraft:ominous_trial_key'] * 2 + ITEMS) + uses.append(f'{rng.randrange(ticks)}/{rng.randrange(count)}/{item}/{rng.choice([1, 1, 1, 2, 5])}') + if uses: + w.kv['use'] = ';'.join(uses) + moves = [] + for _ in range(rng.choice([0, 0, 1, 2, 4])): + x, y, z = spot(rng, vpos) + moves.append(f'{rng.randrange(ticks)}/{rng.randrange(count)}/{x:.3f},{y:.3f},{z:.3f}') + if moves: + w.kv['move'] = ';'.join(moves) + cases.append(f'vault/{k} mode=vault {w.tokens()}') + return cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + args = parser.parse_args() + build = lab.LOCAL / 'rust-vault-parity' + build.mkdir(parents=True, exist_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = base.verify_artifacts() + resources = lab.LOCAL / 'horizon-client/26.3' + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs', + lab.ROOT / 'crates/horizon-client/src/vault.rs'] + tested = base.source_hashes(sources) + inputs = build / 'inputs.txt' + cases = corpus() + inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8') + classes = build / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, libraries)) + + def run(command, name): + with (build / (name + '.log')).open('w', encoding='utf-8') as log: + base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), + '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java') + run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), + 'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture' + run([binary, resources, inputs, build / 'rust.txt'], 'rust') + vanilla = (build / 'server.txt').read_text().splitlines() + errors = [l for l in vanilla if ' error ' in l] + if errors: + raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}') + rust = (build / 'rust.txt').read_text().splitlines() + bad = [(a, b) for a, b in zip(vanilla, rust) if a != b] + if bad or len(vanilla) != len(rust): + report = '\n'.join(f' vanilla {a[:2000]}\n rust {b[:2000]}' for a, b in bad[:12]) + raise SystemExit(f'{len(bad)} of {len(vanilla)} cases differ (rust {len(rust)} lines):\n{report}') + base.ensure_sources_unchanged(sources, tested) + count = lambda text: sum(line.count(text) for line in vanilla) + stats = {'uses_on_active': count(' use ok '), 'refused': count('reject_rewarded_player'), 'wrong_keys': count('insert_item_fail'), + 'items': count(' item minecraft:'), 'states': count(' state '), 'updates': count(' update ')} + for state in STATES: + stats[f'reached_{state}'] = sum(f' state {state} ' in line for line in vanilla) + lab.write_json(build / 'report.json', { + 'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases), + **stats, 'sources_sha256': tested, + 'scope': 'VaultBlockEntity: load and save (VaultConfig with its validation, VaultServerData, VaultSharedData), ' + 'Server.tick (display item cycling from the loot table, VaultState.tickAndGetNext for every state with ' + 'connected players in range, ejection with spawnItem and its pitch, onTransition sounds and level ' + 'events, shared data updates), VaultBlock.useItemOn and Server.tryInsertKey (key checks, rewarded ' + 'players, fail sounds and their buffer, reward roll with the random sequence, unlocking, creative ' + 'players keep the key) with every level random draw.'}) + print(f'{len(cases):,} vault cases match vanilla (' + ', '.join(f'{v:,} {k}' for k, v in stats.items()) + ')') + + +if __name__ == '__main__': + main()