From b8711a7c642af2989367c82e21284e232c8cecbf Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:25:06 +0200 Subject: [PATCH] Add a sculk vibration harness against a vanilla server level VanillaSculkOracle runs sensor, calibrated sensor and shrieker scenarios (scripted game events and block changes, the player's warning level) in a real headless level ticked in ServerLevel.tick's order; the game runs the same scenarios through its own sculk code (HORIZON_SCULK_FIXTURE). Fixes found on the way: sculk block entities tick in the order they were added, the entity phase of sculk runs before the block entities, client side effects of level events draw from the client random, scheduled ticks run one at a time so a shrieker summons inline, wardens are summoned as SpawnUtil does (obstruction by entities, the yaw and finalizeSpawn draws, agitated sounds of discarded attempts), and an empty level no longer draws the level random every tick. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 34 +- crates/horizon-client/src/game/creatures.rs | 13 +- .../src/game/dispense_fixture.rs | 8 + crates/horizon-client/src/game/sculk.rs | 173 +++-- .../horizon-client/src/game/sculk_fixture.rs | 616 +++++++++++++++ crates/horizon-client/src/mobs/warden.rs | 13 + crates/horizon-client/src/sculk.rs | 4 + crates/horizon-world/src/level/tick.rs | 66 ++ .../horizonlab/parity/VanillaSculkOracle.java | 712 ++++++++++++++++++ tools/test_sculk_parity.py | 289 +++++++ 10 files changed, 1875 insertions(+), 53 deletions(-) create mode 100644 crates/horizon-client/src/game/sculk_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSculkOracle.java create mode 100644 tools/test_sculk_parity.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 21e3400cb..921188bc7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -72,6 +72,7 @@ mod render_tick; mod scoreboard; mod screens; mod sculk; +mod sculk_fixture; mod shield; mod sign_edit; mod sniffers; @@ -1362,7 +1363,10 @@ impl Game<'_> { for pos in inside { b.entity_inside(level, ticks, pos); } - b.tick_scheduled(level, ticks); + }); + self.process_level_events()?; + self.tick_scheduled()?; + self.with_level(|b, level, ticks| { for (x, z, sections) in ticking { b.tick_chunk_random( level, @@ -1376,6 +1380,28 @@ impl Game<'_> { }); self.process_level_events() } + /// `ServerLevel.tick`'s scheduled block then fluid ticks, one at a time: + /// the side effects of each (a shrieker summoning a warden, drops, game + /// events) happen before the next tick runs, as they do inline in vanilla. + pub(super) fn tick_scheduled(&mut self) -> Result<()> { + for fluids in [false, true] { + if !self.with_level(|b, level, ticks| b.scheduled_begin(level, ticks, fluids)) { + continue; + } + loop { + let more = + self.with_level(|b, level, ticks| b.scheduled_step(level, ticks, fluids)); + if !self.level_events.is_empty() { + self.process_level_events()?; + } + if !more { + break; + } + } + self.with_level(|b, _, ticks| b.scheduled_finish(ticks, fluids)); + } + Ok(()) + } /// Side effects reported by the behaviour library, in vanilla order. fn process_level_events(&mut self) -> Result<()> { let events = std::mem::take(&mut self.level_events); @@ -2746,7 +2772,8 @@ impl Game<'_> { } if running { self.tick_block_entities()?; - self.tick_sculk()?; + self.tick_sculk_entities(); + self.tick_sculk_blocks()?; self.tick_brewing_stands()?; } if let Some(r) = &self.renderer { @@ -8158,6 +8185,9 @@ pub fn run() -> Result<()> { if let Ok(spec) = std::env::var("HORIZON_DISPENSE_FIXTURE") { return game.dispense_fixture(&spec); } + if let Ok(spec) = std::env::var("HORIZON_SCULK_FIXTURE") { + return game.sculk_fixture(&spec); + } match game.options.world.clone() { _ if game.options.server.is_some() => { let (address, name) = ( diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 0d7e34572..c25a2c25a 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -437,6 +437,11 @@ impl Game<'_> { self.tick_patrol_spawner(); } self.tick_raids(); + self.tick_creature_entities() + } + /// The entity phase of `tick_creatures`: every mob's tick, deaths, and the + /// projectiles and effects that follow from them. + pub(super) fn tick_creature_entities(&mut self) -> Result<()> { let uuid = self.level.player_uuid; let snapshot: Vec = self.mobs.iter().map(|m| seen(m, uuid)).collect(); let mut events = Vec::new(); @@ -1244,7 +1249,13 @@ impl Game<'_> { .filter(|m| m.alive() && m.species() == Species::Breeze) .map(|m| m.id) .collect(); - let jitter = self.world.random.next_float(); + // Drawn only when a breeze could deflect a projectile: an empty + // level must not move the level random every tick. + let jitter = if breezes.is_empty() || projectiles.is_empty() { + 0.0 + } else { + self.world.random.next_float() + }; let w = self.mob_world_base(&[]); let pw = ProjWorld { w: &w, targets }; projectiles.retain_mut(|p| { diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index a906ba259..ed7c96025 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -38,6 +38,14 @@ pub(super) fn record(line: impl FnOnce() -> String) { } }); } +/// Start recording level and game event lines (another fixture's case). +pub(super) fn start_recording() { + LOG.with(|log| *log.borrow_mut() = Some(Vec::new())); +} +/// The lines recorded since `start_recording`; recording stops. +pub(super) fn stop_recording() -> Vec { + LOG.with(|log| log.borrow_mut().take()).unwrap_or_default() +} /// `Level.levelEvent` lines for the level events the behaviour library reported. pub(super) fn record_events(events: &[horizon_world::level::LevelEvent]) { for event in events { diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 61ff84bd9..4b2d63944 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -67,8 +67,9 @@ pub(super) struct SculkState { /// The player's warning level toward a warden. pub tracker: WardenSpawnTracker, tables: Tables, - index: HashSet<(i32, i32, i32)>, - known: HashSet<(i32, i32)>, + /// The sculk block entities in the order they were added. + index: Index, + pub known: HashSet<(i32, i32)>, steps: HashMap, damaged: HashMap, last_health: Option, @@ -77,7 +78,36 @@ pub(super) struct SculkState { /// Who causes the block changes being processed (the player's actions). pub actor: Option, ticks: u32, - tracker_loaded: bool, + pub tracker_loaded: bool, +} +/// An insertion-ordered set of block positions (`Level.blockEntityTickers` +/// keeps the order block entities were added in). +#[derive(Default)] +struct Index { + order: Vec<(i32, i32, i32)>, + set: HashSet<(i32, i32, i32)>, +} +impl Index { + fn insert(&mut self, key: (i32, i32, i32)) { + if self.set.insert(key) { + self.order.push(key); + } + } + fn remove(&mut self, key: &(i32, i32, i32)) { + if self.set.remove(key) { + self.order.retain(|k| k != key); + } + } + fn contains(&self, key: &(i32, i32, i32)) -> bool { + self.set.contains(key) + } + fn iter(&self) -> impl Iterator { + self.order.iter() + } + fn retain(&mut self, mut keep: impl FnMut(&(i32, i32, i32)) -> bool) { + self.order.retain(|k| keep(k)); + self.set = self.order.iter().copied().collect(); + } } const KIND_SENSOR: u8 = 1; const KIND_CALIBRATED: u8 = 2; @@ -228,7 +258,7 @@ impl Game<'_> { // ---- setup and the block entity index ---- - fn sculk_prepare(&mut self) { + pub(super) fn sculk_prepare(&mut self) { if self.sculk.tables.built { return; } @@ -293,7 +323,7 @@ impl Game<'_> { } /// Find the sculk blocks of chunks that just became resident, and apply /// the block writes recorded since the last tick. - fn sculk_sync_index(&mut self) { + pub(super) fn sculk_sync_index(&mut self) { // Chunks that arrived or left (every half second is plenty). if self.sculk.ticks.is_multiple_of(10) { let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect(); @@ -660,14 +690,22 @@ impl Game<'_> { // ---- ticking ---- - /// The block entities of sculk: vibration tickers and catalysts, then the - /// entity-driven events of this tick. - pub(super) fn tick_sculk(&mut self) -> Result<()> { + /// The entity phase of a tick for sculk: the player's warden spawn + /// tracker (`ServerPlayer.tick`), and the events of entities standing on + /// and moving over blocks. + pub(super) fn tick_sculk_entities(&mut self) { self.sculk.ticks = self.sculk.ticks.wrapping_add(1); self.sculk_prepare(); self.load_warden_tracker(); self.sculk.tracker.tick(); self.tick_darkness_blend(); + self.sculk_step_on(); + self.tick_entity_events(); + } + /// The block entity phase for sculk: vibration tickers and catalysts, in + /// the order the block entities were added (`Level.tickBlockEntities`). + pub(super) fn tick_sculk_blocks(&mut self) -> Result<()> { + self.sculk_prepare(); self.sculk_sync_index(); let keys: Vec<(i32, i32, i32)> = self.sculk.index.iter().copied().collect(); for key in keys { @@ -677,8 +715,6 @@ impl Game<'_> { } self.tick_sculk_block(key)?; } - self.sculk_step_on(); - self.tick_entity_events(); Ok(()) } /// `ServerLevel.shouldTickBlocksAt`, as `tick_blocks` decides it. @@ -975,11 +1011,18 @@ impl Game<'_> { ]; self.audio.play(sound, Some(at), 5.0, 1.0); } - /// `SpawnUtil.trySpawnMob` for a warden around the shrieker. + /// `SpawnUtil.trySpawnMob(WARDEN, TRIGGERED, level, pos, 20, 5, 6, + /// ON_TOP_OF_COLLIDER, false)`: every candidate spot creates a warden + /// (`EntityType.create` draws its yaw from the level random and + /// `finalizeSpawn` plays its agitated sound), which is discarded when + /// `checkSpawnObstruction` fails. fn try_summon_warden(&mut self, key: (i32, i32, i32), warning: i32) -> bool { if warning < 4 { return false; } + let Some(kind) = self.res.mob_types.get("minecraft:warden").cloned() else { + return false; + }; for _ in 0..20 { let r = &mut self.world.random; let dx = r.next_int_bound(11).unwrap_or(0) - 5; @@ -992,17 +1035,27 @@ impl Game<'_> { f64::from(at.1), f64::from(at.2) + 0.5, ]; - if !self.warden_fits(spot) { - continue; - } - let Some(id) = self.spawn_mob("minecraft:warden", spot, false) else { - continue; - }; + let yaw = horizon_client::camera::wrap_degrees(self.world.random.next_float() * 360.0); + self.next_entity += 1; + let mut mob = Mob::new( + self.next_entity, + kind.clone(), + horizon_core::geometry::Vec3::new(spot[0], spot[1], spot[2]), + yaw, + ); + // Warden.finalizeSpawn, then Mob.finalizeSpawn's draws from the + // level random: the follow range bonus and left-handedness. let mut events = Vec::new(); - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { - warden::finalize(m, true, &mut events); - } + warden::finalize(&mut mob, true, &mut events); let _ = self.handle_mob_events(events); + let r = &mut self.world.random; + let bonus = r.triangle(0.0, 0.11485000000000001); + mob.attrs.follow_range += mob.kind.follow_range * bonus; + let _left_handed = r.next_float() < 0.05; + if !self.warden_fits(&mob) { + continue; + } + self.mobs.push(mob); return true; } false @@ -1025,32 +1078,43 @@ impl Game<'_> { } None } - /// `Warden.checkSpawnObstruction`: no liquid and no collision in its box. - fn warden_fits(&self, at: [f64; 3]) -> bool { - use horizon_core::geometry::{Aabb, Vec3}; - let Some(kind) = self.res.mob_types.get("minecraft:warden") else { + /// `Warden.checkSpawnObstruction`: no liquid in its box, no living entity + /// in the way (`isUnobstructed`), and no block collision. + fn warden_fits(&self, mob: &Mob) -> bool { + let bounds = mob.bounds(); + let player_blocks = !self.spectator() + && self.player.as_ref().is_some_and(|p| { + let w = f64::from(p.dimensions.width) / 2.0; + let b = horizon_core::geometry::Aabb::new( + horizon_core::geometry::Vec3::new( + p.position.x - w, + p.position.y, + p.position.z - w, + ), + horizon_core::geometry::Vec3::new( + p.position.x + w, + p.position.y + f64::from(p.dimensions.height), + p.position.z + w, + ), + ); + !p.health.dead_or_dying() && b.intersects(bounds) + }); + if player_blocks + || self + .mobs + .iter() + .any(|m| !m.removed && m.alive() && m.bounds().intersects(bounds)) + { return false; - }; - let half = kind.width / 2.0; - let bounds = Aabb::new( - Vec3::new(at[0] - half, at[1], at[2] - half), - Vec3::new(at[0] + half, at[1] + kind.height, at[2] + half), - ); + } let others: Vec = Vec::new(); let w = self.mob_world_base(&others); - let min = [ - bounds.min_position().x, - bounds.min_position().y, - bounds.min_position().z, - ]; - let max = [ - bounds.max_position().x, - bounds.max_position().y, - bounds.max_position().z, - ]; - for x in min[0].floor() as i32..=max[0].floor() as i32 { - for y in min[1].floor() as i32..=max[1].floor() as i32 { - for z in min[2].floor() as i32..=max[2].floor() as i32 { + let min = bounds.min_position(); + let max = bounds.max_position(); + // Level.containsAnyLiquid: floor(min) up to ceil(max), exclusive. + for x in min.x.floor() as i32..max.x.ceil() as i32 { + for y in min.y.floor() as i32..max.y.ceil() as i32 { + for z in min.z.floor() as i32..max.z.ceil() as i32 { if w.fluid(x, y, z) != horizon_client::blocks::Fluid::None { return false; } @@ -1197,7 +1261,8 @@ impl Game<'_> { let c = center(key); let options = ParticleOptions::simple(ParticleType::SculkSoul); for _ in 0..2 { - let r = &mut self.world.random; + // Client-side (LevelEventHandler / particles): the client random. + let r = self.particles.random(); let p = [ c[0] + r.next_gaussian() * 0.2, c[1] + 0.65, @@ -1217,7 +1282,8 @@ impl Game<'_> { let c = center((pos.x, pos.y, pos.z)); let count = data >> 6; if count > 0 { - let r = &mut self.world.random; + // Client-side (LevelEventHandler / particles): the client random. + let r = self.particles.random(); if r.next_float() < 0.3 + count as f32 * 0.1 { let volume = 0.15 + 0.02 * (count * count) as f32 * r.next_float(); let pitch = 0.4 + 0.3 * count as f32 * r.next_float(); @@ -1256,7 +1322,11 @@ impl Game<'_> { .collect() }; for (direction, roll, factor) in faces { - let repetitions = self.world.random.next_int_bound(count + 1).unwrap_or(0); + let repetitions = self + .particles + .random() + .next_int_bound(count + 1) + .unwrap_or(0); for _ in 0..repetitions { self.spawn_particle_on_face(pos, direction, roll, factor); } @@ -1272,7 +1342,8 @@ impl Game<'_> { let (particles, spread) = if solid { (40, 0.45f32) } else { (20, 0.25f32) }; let options = ParticleOptions::simple(ParticleType::SculkChargePop); for _ in 0..particles { - let r = &mut self.world.random; + // Client-side (LevelEventHandler / particles): the client random. + let r = self.particles.random(); let v = [ 2.0 * r.next_float() - 1.0, 2.0 * r.next_float() - 1.0, @@ -1296,7 +1367,8 @@ impl Game<'_> { fn spawn_particle_on_face(&mut self, pos: BlockPos, face: Direction, roll: f32, factor: f64) { let c = center((pos.x, pos.y, pos.z)); let step = face.normal(); - let r = &mut self.world.random; + // Client-side (LevelEventHandler / particles): the client random. + let r = self.particles.random(); let mut jitter = || r.next_double() - 0.5; let mut at = [0.0; 3]; for i in 0..3 { @@ -1327,7 +1399,7 @@ impl Game<'_> { } let state = self.world.block(pos.x, pos.y, pos.z); if self.state_property(state, "waterlogged") != Some("true") { - let pitch = 0.6 + self.world.random.next_float() * 0.4; + let pitch = 0.6 + self.particles.random().next_float() * 0.4; self.audio.play( "minecraft:block.sculk_shrieker.shriek", Some([f64::from(pos.x) + 0.5, top, f64::from(pos.z) + 0.5]), @@ -1356,7 +1428,8 @@ impl Game<'_> { return; }; for _ in 0..30 { - let r = &mut self.world.random; + // Client-side (LevelEventHandler / particles): the client random. + let r = self.particles.random(); let off = |v: f32| f64::from(v * 1.4 - 0.7); let p = [ at[0] + off(r.next_float()), diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs new file mode 100644 index 000000000..9fbd47d09 --- /dev/null +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -0,0 +1,616 @@ +//! The Rust side of tools/test_sculk_parity.py: with +//! `HORIZON_SCULK_FIXTURE=SCENARIOS,OUTPUT` the game loads its resources and +//! runs every scenario (sculk blocks, the player with a warning level, scripted +//! game events and block changes) through its own sculk code on a fresh +//! headless world, ticking in `ServerLevel.tick`'s order, and prints what +//! changed after every tick in the format of `VanillaSculkOracle`. +use super::{Game, dispense_fixture}; +use horizon_client::{ + Result, + chunk::{Chunk, MIN_Y}, + command::args::GameMode, + containers::BlockEntity, + mobs::{Mob, Who}, + motion::PlayerMotion, + sculk::{Info, SculkKind, WardenSpawnTracker}, + world::World, +}; +use horizon_core::{ + geometry::{Direction, Vec3}, + position::BlockPos, + random::LegacyRandom, +}; +use horizon_world::{chunk::BlockState, level::Ticks, registry::BlockStateId}; +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + fmt::Write as _, + io::Write as _, + sync::Arc, +}; +use winit::keyboard::KeyCode; + +struct MobSpec { + kind: String, + pos: [f64; 3], + yaw: f32, + seed: i64, + flags: Vec, +} +#[derive(Default)] +struct Scenario { + name: String, + ticks: i32, + origin: [i32; 2], + level_seed: i64, + difficulty: String, + wardens: bool, + blocks: Vec>, + player: Option<[f64; 3]>, + mode: String, + sneak: bool, + warning: Option, + mobs: Vec, + watch: Vec<[i32; 3]>, + actions: Vec<(i32, Vec)>, +} + +fn parse(text: &str) -> Vec { + let mut out = Vec::new(); + let mut cur: Option = None; + for line in text.lines() { + let f: Vec<&str> = line.split_whitespace().collect(); + if f.is_empty() || f[0].starts_with('#') { + continue; + } + let s = cur.get_or_insert_with(Scenario::default); + match f[0] { + "scenario" => { + s.name = f[1].to_owned(); + s.difficulty = "normal".into(); + s.wardens = true; + s.mode = "survival".into(); + for kv in &f[2..] { + let (k, v) = kv.split_once('=').unwrap_or((kv, "")); + match k { + "ticks" => s.ticks = v.parse().unwrap_or(0), + "levelseed" => s.level_seed = v.parse().unwrap_or(0), + "difficulty" => s.difficulty = v.to_owned(), + "nowardens" => s.wardens = false, + _ => {} + } + } + } + "origin" => s.origin = [f[1].parse().unwrap_or(0), f[2].parse().unwrap_or(0)], + "fill" | "block" => s.blocks.push(f.iter().map(|x| (*x).to_owned()).collect()), + "player" => { + s.player = Some([ + f[1].parse().unwrap_or(0.0), + f[2].parse().unwrap_or(0.0), + f[3].parse().unwrap_or(0.0), + ]); + for w in &f[4..] { + if *w == "sneak" { + s.sneak = true; + } else if let Some(level) = w.strip_prefix("warn=") { + s.warning = level.parse().ok(); + } else { + s.mode = (*w).to_owned(); + } + } + } + "mob" => s.mobs.push(MobSpec { + kind: f[1].to_owned(), + pos: [ + f[2].parse().unwrap_or(0.0), + f[3].parse().unwrap_or(0.0), + f[4].parse().unwrap_or(0.0), + ], + yaw: f[5].parse().unwrap_or(0.0), + seed: f[6].parse().unwrap_or(0), + flags: f[7..].iter().map(|x| (*x).to_owned()).collect(), + }), + "watch" => s.watch.push([ + f[1].parse().unwrap_or(0), + f[2].parse().unwrap_or(0), + f[3].parse().unwrap_or(0), + ]), + "at" => s.actions.push(( + f[1].parse().unwrap_or(0), + f[2..].iter().map(|x| (*x).to_owned()).collect(), + )), + "end" => out.extend(cur.take()), + _ => {} + } + } + out +} + +fn d(v: f64) -> String { + format!("{:x}", v.to_bits()) +} +fn f(v: f32) -> String { + format!("{:x}", v.to_bits()) +} + +/// Sounds the client plays for level events (3006 sculk charge, 3007 +/// shriek): vanilla's server never sends them. +const CLIENT_SOUNDS: &[&str] = &[ + "minecraft:block.sculk_shrieker.shriek", + "minecraft:block.sculk.charge", +]; + +impl Game<'_> { + /// Run every scenario of `spec` ("SCENARIOS,OUTPUT") and write the results. + pub(super) fn sculk_fixture(&mut self, spec: &str) -> Result<()> { + let (input, output) = spec + .split_once(',') + .ok_or("HORIZON_SCULK_FIXTURE=SCENARIOS,OUTPUT")?; + let text = std::fs::read_to_string(input)?; + let mut out = std::io::BufWriter::new(std::fs::File::create(output)?); + for s in parse(&text) { + writeln!(out, "== {}", s.name)?; + match self.sculk_scenario(&s) { + Ok(lines) => out.write_all(lines.as_bytes())?, + Err(e) => writeln!(out, "0 failed {e}")?, + } + } + Ok(()) + } + + /// `minecraft:name[key=value,...]` to a state. + fn fixture_state(&self, text: &str) -> Result { + let (name, props) = match text.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (text, ""), + }; + let registry = self.res.assets.registry; + let base = registry + .default_state(name) + .ok_or_else(|| format!("unknown block {name}"))?; + let mut properties: BTreeMap = registry + .state(base) + .map(|s| s.properties.clone().into_iter().collect()) + .unwrap_or_default(); + for kv in props.split(',').filter(|s| !s.is_empty()) { + let (k, v) = kv.split_once('=').ok_or("property")?; + properties.insert(k.to_owned(), v.to_owned()); + } + Ok(registry.resolve(&BlockState { + name: name.to_owned(), + properties, + })?) + } + + /// `BlockStateParser.serialize`. + fn fixture_state_text(&self, state: BlockStateId) -> String { + let Some(s) = self.res.assets.registry.state(state) else { + return "?".into(); + }; + if s.properties.is_empty() { + return s.name.clone(); + } + let mut sorted: Vec<(&String, &String)> = s.properties.iter().collect(); + sorted.sort(); + let props: Vec = sorted.iter().map(|(k, v)| format!("{k}={v}")).collect(); + format!("{}[{}]", s.name, props.join(",")) + } + + fn fixture_who(&self, who: Option, names: &HashMap) -> String { + match who { + None => "none".into(), + Some(Who::Player) => "player".into(), + Some(Who::Mob(id)) => names.get(&id).cloned().unwrap_or_else(|| format!("e{id}")), + } + } + + fn fixture_info(&self, info: Option<&Info>, names: &HashMap) -> String { + let Some(i) = info else { + return "-".into(); + }; + // A source entity that is gone reads as none (VibrationInfo.getEntity). + let alive = |w: Option| match w { + Some(Who::Mob(id)) if !self.mobs.iter().any(|m| m.id == id && !m.removed) => None, + other => other, + }; + format!( + "{}/{}/{},{},{}/{}/{}", + i.event.trim_start_matches("minecraft:"), + f(i.distance), + d(i.pos[0]), + d(i.pos[1]), + d(i.pos[2]), + self.fixture_who(alive(i.source), names), + self.fixture_who(alive(i.owner), names) + ) + } + + fn sculk_describe(&self, p: [i32; 3], names: &HashMap) -> String { + let state = self.world.block(p[0], p[1], p[2]); + let mut line = self.fixture_state_text(state); + if let Some(BlockEntity::Sculk(e)) = self.world.block_entities.get(&(p[0], p[1], p[2])) { + let vibration = |line: &mut String| { + let v = &e.vibration; + let _ = write!( + line, + " cur={} travel={}", + self.fixture_info(v.current.as_ref(), names), + v.travel + ); + match v.selector.current() { + None => line.push_str(" sel=-"), + Some((info, tick)) => { + let _ = write!( + line, + " sel={}@{tick}", + self.fixture_info(Some(&info), names) + ); + } + } + }; + match e.kind { + SculkKind::Sensor | SculkKind::Calibrated => { + let _ = write!(line, " freq={}", e.last_frequency); + vibration(&mut line); + } + SculkKind::Shrieker => { + let _ = write!(line, " warn={}", e.warning_level); + vibration(&mut line); + } + SculkKind::Catalyst => { + let _ = write!(line, " cursors={}", e.spreader.cursors.len()); + for c in &e.spreader.cursors { + let _ = write!( + line, + " {},{},{}:{}:{}:{}:", + c.pos.x, c.pos.y, c.pos.z, c.charge, c.update_delay, c.decay_delay + ); + match &c.facings { + None => line.push('-'), + Some(faces) => { + let mut faces = faces.clone(); + faces.sort_by_key(|d| *d as u8); + for d in faces { + line.push(match d { + Direction::Down => 'd', + Direction::Up => 'u', + Direction::North => 'n', + Direction::South => 's', + Direction::West => 'w', + Direction::East => 'e', + }); + } + } + } + } + } + } + } + line + } + + fn sculk_fixture_reset(&mut self, s: &Scenario) -> Result<()> { + self.world = World::new(self.res.facts.air, 0); + let plains = u32::from(self.res.biomes.id("minecraft:plains")); + let layers = [ + self.fixture_state("minecraft:bedrock")?, + self.fixture_state("minecraft:dirt")?, + self.fixture_state("minecraft:dirt")?, + self.fixture_state("minecraft:grass_block")?, + ]; + let (ocx, ocz) = (s.origin[0] >> 4, s.origin[1] >> 4); + for cx in ocx - 4..=ocx + 4 { + for cz in ocz - 4..=ocz + 4 { + let mut chunk = Chunk::empty(cx, cz); + for section in &mut chunk.sections { + Arc::make_mut(section).biomes = horizon_core::paletted::PalettedContainer::new( + horizon_client::chunk::BIOME_STRATEGY, + plains, + ); + } + chunk.lit = true; + self.world.chunks.insert((cx, cz), Arc::new(chunk)); + for x in 0..16 { + for z in 0..16 { + for (y, layer) in layers.iter().enumerate() { + self.world + .set(cx * 16 + x, MIN_Y + y as i32, cz * 16 + z, *layer)?; + } + } + } + } + } + self.block_ticks = Ticks::new(0); + self.tick_chunks.clear(); + self.sync_tick_chunks(); + self.mobs.clear(); + self.dropped.clear(); + self.level_events.clear(); + self.ui.rules = Default::default(); + for (rule, value) in [ + ("spawn_mobs", false), + ("spawn_monsters", false), + ("spawn_patrols", false), + ("spawn_phantoms", false), + ("spawn_wandering_traders", false), + ("advance_time", false), + ("advance_weather", false), + ("raids", false), + ("spawn_wardens", s.wardens), + ] { + self.ui + .rules + .set(rule, horizon_client::gamerules::Value::Bool(value)); + } + self.ui.rules.set( + "random_tick_speed", + horizon_client::gamerules::Value::Int(0), + ); + use horizon_world::food::Difficulty; + let difficulty = match s.difficulty.as_str() { + "peaceful" => Difficulty::Peaceful, + "easy" => Difficulty::Easy, + "hard" => Difficulty::Hard, + _ => Difficulty::Normal, + }; + self.world.health_rules.difficulty = difficulty; + self.ui.difficulty = match difficulty { + Difficulty::Peaceful => 0, + Difficulty::Easy => 1, + Difficulty::Normal => 2, + Difficulty::Hard => 3, + }; + self.level.seed = 0; + self.potions.effects = Default::default(); + self.sculk = Default::default(); + self.sculk.tracker_loaded = true; + self.sculk_prepare(); + Ok(()) + } + + fn sculk_scenario(&mut self, s: &Scenario) -> Result { + self.sculk_fixture_reset(s)?; + let at = s.player.unwrap_or([ + f64::from(s.origin[0]) + 0.5, + 100.0, + f64::from(s.origin[1]) + 0.5, + ]); + self.mode = match s.mode.as_str() { + "creative" => GameMode::Creative, + "spectator" => GameMode::Spectator, + "adventure" => GameMode::Adventure, + _ => GameMode::Survival, + }; + self.creative = self.mode == GameMode::Creative; + let mut player = PlayerMotion::new(self.motion, Vec3::new(at[0], at[1], at[2]))?; + player.spectator = self.mode == GameMode::Spectator; + self.player = Some(player); + self.keys.clear(); + if s.sneak { + self.keys.insert(KeyCode::ShiftLeft); + } + self.sculk.tracker = WardenSpawnTracker::default(); + if let Some(level) = s.warning { + self.sculk.tracker.set_warning_level(level); + } + // The blocks, in order (sculk block entities tick in the order they + // were placed), with `Level.setBlock(pos, state, 2 | 16)` at game time 1000. + self.world.game_time = 1000; + let mut cells = Vec::new(); + for b in &s.blocks { + let n = |i: usize| b[i].parse::().unwrap_or(0); + if b[0] == "block" { + cells.push((BlockPos::new(n(1), n(2), n(3)), self.fixture_state(&b[4])?)); + } else { + let state = self.fixture_state(&b[7])?; + for x in n(1).min(n(4))..=n(1).max(n(4)) { + for y in n(2).min(n(5))..=n(2).max(n(5)) { + for z in n(3).min(n(6))..=n(3).max(n(6)) { + cells.push((BlockPos::new(x, y, z), state)); + } + } + } + } + } + self.with_level(|b, level, ticks| { + for (pos, state) in cells { + b.set_block(level, ticks, pos, state, 2 | 16); + } + }); + self.level_events.clear(); + self.sculk.known = self.world.chunks.keys().copied().collect(); + self.sculk_sync_index(); + let mut names: HashMap = HashMap::new(); + let mut sources: Vec = Vec::new(); + for spec in &s.mobs { + let kind = self + .res + .mob_types + .get(&spec.kind) + .cloned() + .ok_or_else(|| format!("unknown mob {}", spec.kind))?; + let id = 100_000 + sources.len() as u32; + let mut m = Mob::new( + id, + kind, + Vec3::new(spec.pos[0], spec.pos[1], spec.pos[2]), + spec.yaw, + ); + for flag in &spec.flags { + match flag.as_str() { + "persistent" => m.persistent = true, + "noai" => m.no_ai = true, + _ => {} + } + } + m.random = LegacyRandom::new(spec.seed); + names.insert(id, format!("m{}", sources.len())); + sources.push(id); + self.mobs.push(m); + } + self.next_entity = self.next_entity.max(200_000); + self.world.day_time = 6000; + self.world.random = LegacyRandom::new(s.level_seed); + self.audio.capture = Some(Vec::new()); + let mut known: HashSet = self.mobs.iter().map(|m| m.id).collect(); + let mut known_items = self.dropped.len(); + let mut last: HashMap<[i32; 3], String> = HashMap::new(); + let (mut last_player, mut last_rng) = (String::new(), String::new()); + let mut out = String::new(); + for t in 0..=s.ticks { + dispense_fixture::start_recording(); + if t > 0 { + self.sculk_fixture_tick(t, s, &sources)?; + } + let mut lines: Vec = Vec::new(); + for p in &s.watch { + let line = self.sculk_describe(*p, &names); + if last.get(p) != Some(&line) { + last.insert(*p, line.clone()); + lines.push(format!("blk {},{},{} {line}", p[0], p[1], p[2])); + } + } + let tr = self.sculk.tracker; + let dark = self + .potions + .effects + .get("darkness") + .map_or("-".to_owned(), |e| e.duration.to_string()); + let now = format!( + "warn {} {} dark {dark}", + tr.warning_level, tr.cooldown_ticks + ); + if now != last_player { + last_player = now.clone(); + lines.push(now); + } + let mut fresh: Vec<&Mob> = self + .mobs + .iter() + .filter(|m| !known.contains(&m.id)) + .collect(); + fresh.sort_by_key(|m| m.id); + let fresh: Vec<(u32, String)> = fresh + .iter() + .map(|m| { + ( + m.id, + format!( + "new {} {},{},{}", + m.kind.id, + d(m.position.x), + d(m.position.y), + d(m.position.z) + ), + ) + }) + .collect(); + for (id, line) in fresh { + known.insert(id); + names.insert(id, format!("n{}", names.len())); + // An entity's own random is unseeded in vanilla: the oracle + // seeds what appeared, and so does this. + let seed = 0x5eed + names.len() as i64; + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.random = LegacyRandom::new(seed); + horizon_client::mobs::warden::delay_sensors(m); + } + lines.push(line); + } + for i in known_items..self.dropped.len() { + let d = &self.dropped[i]; + names.insert(u32::MAX - i as u32, format!("n{}", names.len())); + lines.push(format!( + "new minecraft:item {},{},{}", + self::d(d.position.x), + self::d(d.position.y), + self::d(d.position.z) + )); + } + known_items = self.dropped.len(); + for line in dispense_fixture::stop_recording() { + if let Some(rest) = line.strip_prefix("L ") { + lines.push(format!("level {rest}")); + } + } + for (sound, at, volume, pitch) in + self.audio.capture.replace(Vec::new()).unwrap_or_default() + { + if CLIENT_SOUNDS.contains(&sound.as_str()) { + continue; + } + lines.push(format!( + "sound {sound} {},{},{} {} {}", + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + f(volume), + f(pitch) + )); + } + let rng = format!("rng {:x}", self.world.random.state()); + if rng != last_rng { + last_rng = rng.clone(); + lines.push(rng); + } + for line in lines { + let _ = writeln!(out, "{t} {line}"); + } + } + self.audio.capture = None; + Ok(out) + } + + /// One `ServerLevel.tick` of a scenario. + fn sculk_fixture_tick(&mut self, t: i32, s: &Scenario, sources: &[u32]) -> Result<()> { + self.world.game_time += 1; + // Scheduled block and fluid ticks, then block events. + self.tick_scheduled()?; + self.with_level(|b, level, ticks| b.run_block_events(level, ticks)); + self.process_level_events()?; + // The scenario's actions happen among the entities. + for (tick, words) in &s.actions { + if *tick != t { + continue; + } + match words[0].as_str() { + "event" => { + let event = horizon_client::sculk::intern(&words[1]) + .ok_or_else(|| format!("unknown game event {}", words[1]))?; + let num = |i: usize| words[i].parse::().unwrap_or(0.0); + let pos = [num(2), num(3), num(4)]; + let who = match words[5].as_str() { + "none" => None, + "player" => Some(Who::Player), + m => sources + .get(m[1..].parse::().unwrap_or(usize::MAX)) + .map(|id| Who::Mob(*id)), + }; + let state = match words.get(6) { + Some(text) => Some(self.fixture_state(text)?), + None => None, + }; + let ctx = self.who_context(who, state); + self.post_game_event(event, pos, ctx); + } + "set" => { + let n = |i: usize| words[i].parse::().unwrap_or(0); + let pos = BlockPos::new(n(1), n(2), n(3)); + let state = self.fixture_state(&words[4])?; + self.with_level(|b, level, ticks| { + b.set_block(level, ticks, pos, state, 3); + }); + self.process_level_events()?; + } + other => return Err(format!("unknown action {other}").into()), + } + } + // Entities: the player's warden spawn tracker, then the mobs. + self.tick_sculk_entities(); + // (ServerChunkCache.tick, natural spawning and its chunk shuffle, is not run.) + self.tick_creature_entities()?; + self.tick_items(); + // Block entities. + self.tick_sculk_blocks()?; + Ok(()) + } +} diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs index 7480b3b00..f92e02f7a 100644 --- a/crates/horizon-client/src/mobs/warden.rs +++ b/crates/horizon-client/src/mobs/warden.rs @@ -392,6 +392,19 @@ pub fn register(m: &mut Mob) { w.sensor_timer = phase; } } +/// `Sensor.randomlyDelayStart` for the warden's sensors, in brain order +/// (`NEAREST_PLAYERS`, then `WARDEN_ENTITY_SENSOR`, which sets the phase of +/// the combined scan here). +pub fn delay_sensors(m: &mut Mob) { + if m.species() != Species::Warden { + return; + } + let _players = m.random.next_int_bound(20).unwrap_or(0); + let entities = m.random.next_int_bound(20).unwrap_or(0); + if let Some(w) = m.extra.warden.as_mut() { + w.sensor_timer = entities; + } +} /// `Warden.finalizeSpawn`: a minute until it digs back down; a summoned /// warden climbs out of the ground first. pub fn finalize(m: &mut Mob, triggered: bool, events: &mut Vec) { diff --git a/crates/horizon-client/src/sculk.rs b/crates/horizon-client/src/sculk.rs index e7eb4b7ce..58ac921ff 100644 --- a/crates/horizon-client/src/sculk.rs +++ b/crates/horizon-client/src/sculk.rs @@ -229,6 +229,10 @@ impl Selector { pub fn start_over(&mut self) { self.current = None; } + /// The candidate kept so far and the tick it came in. + pub fn current(&self) -> Option<(Info, i64)> { + self.current + } } /// `VibrationSystem.Data`. #[derive(Clone, Debug, Default, PartialEq)] diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index f801f95ba..60093c360 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -1541,6 +1541,72 @@ impl Behaviours { let _ = ticks.fluids.finish_tick(); ticks.handling_tick = false; } + /// `tick_scheduled` one tick at a time, for a caller that must act on + /// each tick's side effects before the next runs (as vanilla runs them + /// inline): `scheduled_begin`, then `scheduled_step` until it returns + /// false, then `scheduled_finish`; block ticks first, then fluid ticks. + /// Returns whether ticks are due (false: nothing to step or finish). + pub fn scheduled_begin( + &self, + level: &mut L, + ticks: &mut Ticks, + fluids: bool, + ) -> bool { + let time = level.game_time(); + ticks.handling_tick = true; + let level_ref: &L = level; + let queue = if fluids { + &mut ticks.fluids + } else { + &mut ticks.blocks + }; + let ok = queue + .begin_tick(time, 65536, |chunk: ChunkPos| { + level_ref.is_ticking_chunk(chunk) + }) + .is_ok(); + if !ok { + ticks.handling_tick = false; + } + ok + } + /// Run the next due tick; false when none is left. + pub fn scheduled_step( + &self, + level: &mut L, + ticks: &mut Ticks, + fluids: bool, + ) -> bool { + if fluids { + let Ok(Some(tick)) = ticks.fluids.next_tick() else { + return false; + }; + let mut sim = self.sim(level, ticks); + let fluid = self.fluid(sim.state(tick.pos)).kind(); + if TickTypeId(fluid as u32) == tick.kind { + sim.fluid_tick(tick.pos); + } + } else { + let Ok(Some(tick)) = ticks.blocks.next_tick() else { + return false; + }; + let mut sim = self.sim(level, ticks); + let state = sim.state(tick.pos); + if u32::from(self.block(state).0) == tick.kind.0 { + sim.tick_block(state, tick.pos); + } + } + true + } + /// End a `scheduled_begin` phase. + pub fn scheduled_finish(&self, ticks: &mut Ticks, fluids: bool) { + let _ = if fluids { + ticks.fluids.finish_tick() + } else { + ticks.blocks.finish_tick() + }; + ticks.handling_tick = false; + } /// Random-tick one chunk (`ServerLevel.tickChunk` block part). `sections` /// yields the minimum block Y of every section the caller considers /// randomly ticking (vanilla: sections containing randomly-ticking states), diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSculkOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSculkOracle.java new file mode 100644 index 000000000..b94199720 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSculkOracle.java @@ -0,0 +1,712 @@ +package dev.horizonlab.parity; + +import com.mojang.authlib.GameProfile; +import com.mojang.serialization.Lifecycle; +import io.netty.channel.embedded.EmbeddedChannel; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.Proxy; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.BooleanSupplier; +import net.minecraft.SharedConstants; +import net.minecraft.SystemReport; +import net.minecraft.commands.Commands; +import net.minecraft.commands.arguments.blocks.BlockStateParser; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.Holder; +import net.minecraft.core.MappedRegistry; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.gametest.framework.GameTestServer; +import net.minecraft.gizmos.GizmoCollector; +import net.minecraft.gizmos.Gizmos; +import net.minecraft.network.Connection; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.PacketFlow; +import net.minecraft.network.protocol.game.ClientboundLevelEventPacket; +import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket; +import net.minecraft.network.protocol.game.ClientboundSoundPacket; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.Services; +import net.minecraft.server.WorldLoader; +import net.minecraft.server.WorldStem; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.progress.LoggingLevelLoadListener; +import net.minecraft.server.network.CommonListenerCookie; +import net.minecraft.server.notifications.EmptyNotificationService; +import net.minecraft.server.notifications.NotificationManager; +import net.minecraft.server.packs.repository.PackRepository; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.permissions.LevelBasedPermissionSet; +import net.minecraft.server.permissions.PermissionSet; +import net.minecraft.server.players.NameAndId; +import net.minecraft.server.players.PlayerList; +import net.minecraft.util.Util; +import net.minecraft.util.datafix.DataFixers; +import net.minecraft.util.debugchart.LocalSampleLogger; +import net.minecraft.util.debugchart.SampleLogger; +import net.minecraft.world.Difficulty; +import net.minecraft.world.clock.WorldClocks; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.monster.warden.WardenSpawnTracker; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.level.DataPackConfig; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.LevelSettings; +import net.minecraft.world.level.WorldDataConfiguration; +import net.minecraft.world.level.block.SculkSpreader; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.SculkCatalystBlockEntity; +import net.minecraft.world.level.block.entity.SculkSensorBlockEntity; +import net.minecraft.world.level.block.entity.SculkShriekerBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.dimension.LevelStem; +import net.minecraft.world.level.gameevent.GameEvent; +import net.minecraft.world.level.gameevent.vibrations.VibrationInfo; +import net.minecraft.world.level.gameevent.vibrations.VibrationSelector; +import net.minecraft.world.level.gameevent.vibrations.VibrationSystem; +import net.minecraft.world.level.gamerules.GameRules; +import net.minecraft.world.level.levelgen.LegacyRandomSource; +import net.minecraft.world.level.levelgen.WorldDimensions; +import net.minecraft.world.level.levelgen.WorldGenSettings; +import net.minecraft.world.level.levelgen.WorldOptions; +import net.minecraft.world.level.levelgen.presets.WorldPresets; +import net.minecraft.world.level.storage.LevelDataAndDimensions; +import net.minecraft.world.level.storage.LevelStorageSource; +import net.minecraft.world.level.storage.PrimaryLevelData; +import net.minecraft.world.phys.Vec3; + +/** + * Sculk oracle: a real (headless, flat, structure-free) vanilla server level, as in + * {@link VanillaMobAiOracle}. Each scenario builds blocks, places the player and entities, and + * then runs its ticks the way ServerLevel.tick orders them (game time, scheduled block and fluid + * ticks, block events, the scenario's scripted game events and actions, the player's warden spawn + * tracker and the entities, then the block entities) while the rest of the level stands still. After + * every tick it prints what changed at the watched blocks (state and the sculk block entity: + * vibration, selector, frequency, warning level, charge cursors), the sounds and level events, + * the player's warning level and darkness, entities that appeared, and the level random. + * Used by tools/test_sculk_parity.py. + */ +public final class VanillaSculkOracle { + static final List SCENARIOS = new ArrayList<>(); + static PrintWriter out; + static final List LOG = new ArrayList<>(); + + /** Draws of the level random with their callers (SCULK_TRACE=1). */ + static final class TracingRandom extends LegacyRandomSource { + TracingRandom(long seed) { super(seed); } + @Override + public int next(int bits) { + int v = super.next(bits); + StringBuilder sb = new StringBuilder("trace " + bits + ":"); + int n = 0; + for (StackTraceElement e : new Throwable().getStackTrace()) { + String c = e.getClassName(); + if (c.contains("RandomSource") || c.contains("TracingRandom") || c.contains("Mth")) continue; + sb.append(' ').append(c.substring(c.lastIndexOf('.') + 1)).append('.').append(e.getMethodName()).append(':').append(e.getLineNumber()); + if (++n == 6) break; + } + LOG.add(sb.toString()); + return v; + } + } + + static final class MobSpec { + String type; + double x, y, z; + float yaw; + long seed; + List flags = new ArrayList<>(); + } + + /** A scripted action at a tick. */ + static final class Action { + int tick; + String[] words; + } + + static final class Scenario { + String name; + int ticks; + int originX, originZ; + long levelSeed = 0; + Difficulty difficulty = Difficulty.NORMAL; + boolean wardens = true; + List blocks = new ArrayList<>(); + double[] player; + String mode = "survival"; + boolean sneak; + int warning = -1; + List mobs = new ArrayList<>(); + List watch = new ArrayList<>(); + List actions = new ArrayList<>(); + } + + static void parse(Path path) throws Exception { + Scenario s = null; + for (String raw : Files.readAllLines(path)) { + String line = raw.strip(); + if (line.isEmpty() || line.startsWith("#")) continue; + String[] f = line.split("\\s+"); + switch (f[0]) { + case "scenario" -> { + s = new Scenario(); + s.name = f[1]; + for (int i = 2; i < f.length; i++) { + String[] kv = f[i].split("=", 2); + switch (kv[0]) { + case "ticks" -> s.ticks = Integer.parseInt(kv[1]); + case "levelseed" -> s.levelSeed = Long.parseLong(kv[1]); + case "difficulty" -> s.difficulty = Difficulty.byName(kv[1]); + case "nowardens" -> s.wardens = false; + default -> throw new IllegalArgumentException(line); + } + } + } + case "origin" -> { s.originX = Integer.parseInt(f[1]); s.originZ = Integer.parseInt(f[2]); } + case "fill", "block" -> s.blocks.add(f); + case "player" -> { + s.player = new double[] {Double.parseDouble(f[1]), Double.parseDouble(f[2]), Double.parseDouble(f[3])}; + for (int i = 4; i < f.length; i++) { + if (f[i].equals("sneak")) s.sneak = true; + else if (f[i].startsWith("warn=")) s.warning = Integer.parseInt(f[i].substring(5)); + else s.mode = f[i]; + } + } + case "mob" -> { + MobSpec m = new MobSpec(); + m.type = f[1]; + m.x = Double.parseDouble(f[2]); + m.y = Double.parseDouble(f[3]); + m.z = Double.parseDouble(f[4]); + m.yaw = Float.parseFloat(f[5]); + m.seed = Long.parseLong(f[6]); + for (int i = 7; i < f.length; i++) m.flags.add(f[i]); + s.mobs.add(m); + } + case "watch" -> s.watch.add(new int[] {Integer.parseInt(f[1]), Integer.parseInt(f[2]), Integer.parseInt(f[3])}); + case "at" -> { + Action a = new Action(); + a.tick = Integer.parseInt(f[1]); + a.words = java.util.Arrays.copyOfRange(f, 2, f.length); + s.actions.add(a); + } + case "end" -> { SCENARIOS.add(s); s = null; } + default -> throw new IllegalArgumentException(line); + } + } + } + + public static void main(String[] args) throws Exception { + parse(Path.of(args[0])); + out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + Util.startTimerHackThread(); + Path universe = Files.createTempDirectory("horizon-sculk"); + LevelStorageSource.LevelStorageAccess access = LevelStorageSource.createDefault(universe).createAccess("sculkworld"); + PackRepository packs = ServerPacksSource.createPackRepository(access); + MinecraftServer.spin(thread -> Server.create(thread, access, packs)); + } + + static String d(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); } + static String f(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); } + static String pos(BlockPos p) { return p.getX() + "," + p.getY() + "," + p.getZ(); } + + static Field field(Class c, String name) throws Exception { + for (Class k = c; k != null; k = k.getSuperclass()) { + try { + Field fl = k.getDeclaredField(name); + fl.setAccessible(true); + return fl; + } catch (NoSuchFieldException e) { + // keep looking + } + } + throw new NoSuchFieldException(name); + } + + static Method method(Class c, String name, Class... types) throws Exception { + for (Class k = c; k != null; k = k.getSuperclass()) { + try { + Method m = k.getDeclaredMethod(name, types); + m.setAccessible(true); + return m; + } catch (NoSuchMethodException e) { + // keep looking + } + } + throw new NoSuchMethodException(name); + } + + static Object get(Object o, String name) throws Exception { return field(o.getClass(), name).get(o); } + + static long seedOf(Object random) throws Exception { + return ((java.util.concurrent.atomic.AtomicLong) field(LegacyRandomSource.class, "seed").get(random)).get(); + } + + static final class Server extends MinecraftServer { + static final FeatureFlagSet FEATURES = FeatureFlags.REGISTRY + .allFlags() + .subtract(FeatureFlagSet.of(FeatureFlags.REDSTONE_EXPERIMENTS, FeatureFlags.MINECART_IMPROVEMENTS)); + final LocalSampleLogger sampleLogger = new LocalSampleLogger(4); + int scenario = 0; + int phase = 0; + int wait = 0; + ServerPlayer player; + Map names = new HashMap<>(); + int[] forced; + static final int RESET = 24; + + static Server create(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs) { + try { + packs.reload(); + ArrayList enabled = new ArrayList<>(packs.getAvailableIds()); + enabled.remove("vanilla"); + enabled.addFirst("vanilla"); + WorldDataConfiguration config = new WorldDataConfiguration(new DataPackConfig(enabled, List.of()), FEATURES); + LevelSettings settings = new LevelSettings("Sculk Level", GameType.SURVIVAL, LevelSettings.DifficultySettings.DEFAULT, true, config); + WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packs, config, false, true); + WorldLoader.InitConfig init = new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, LevelBasedPermissionSet.OWNER); + WorldStem stem = Util.blockUntilDone(executor -> WorldLoader.load(init, context -> { + Registry none = new MappedRegistry<>(Registries.LEVEL_STEM, Lifecycle.stable()).freeze(); + WorldDimensions dims = context.datapackWorldRegistries().lookupOrThrow(Registries.WORLD_PRESET) + .getOrThrow(WorldPresets.FLAT).value().createWorldDimensions(); + WorldDimensions.Complete complete = dims.bake(none); + PrimaryLevelData data = new PrimaryLevelData(settings, complete.specialWorldProperty(), complete.lifecycle()); + return new WorldLoader.DataLoadOutput<>( + new LevelDataAndDimensions.WorldDataAndGenSettings(data, new WorldGenSettings(new WorldOptions(0L, false, false), dims)), + complete.dimensionsRegistryAccess()); + }, WorldStem::new, Util.backgroundExecutor(), executor)).get(); + GameRules rules = new GameRules(FEATURES); + rules.set(GameRules.SPAWN_MOBS, false, null); + rules.set(GameRules.SPAWN_MONSTERS, false, null); + rules.set(GameRules.SPAWN_PATROLS, false, null); + rules.set(GameRules.SPAWN_PHANTOMS, false, null); + rules.set(GameRules.SPAWN_WANDERING_TRADERS, false, null); + rules.set(GameRules.ADVANCE_TIME, false, null); + rules.set(GameRules.ADVANCE_WEATHER, false, null); + rules.set(GameRules.RAIDS, false, null); + rules.set(GameRules.RANDOM_TICK_SPEED, 0, null); + Field nf = GameTestServer.class.getDeclaredField("NO_SERVICES"); + nf.setAccessible(true); + return new Server(thread, access, packs, stem, rules, (Services) nf.get(null)); + } catch (Exception e) { + e.printStackTrace(); + System.exit(2); + throw new IllegalStateException(e); + } + } + + Server(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs, WorldStem stem, GameRules rules, Services services) { + super(thread, access, packs, stem, Optional.of(rules), Proxy.NO_PROXY, DataFixers.getDataFixer(), services, + LoggingLevelLoadListener.forDedicatedServer(), false, new NotificationManager()); + } + + @Override + protected boolean initServer() { + this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, new EmptyNotificationService()) { + @Override + public void broadcast(Player except, double x, double y, double z, double range, ResourceKey dim, Packet packet) { + capture(packet); + } + }); + Gizmos.withCollector(GizmoCollector.NOOP); + this.loadLevel(); + return true; + } + + static void capture(Packet packet) { + if (packet instanceof ClientboundSoundPacket p) { + LOG.add("sound " + p.getSound().value().location() + " " + (int) Math.floor(p.getX()) + "," + (int) Math.floor(p.getY()) + "," + + (int) Math.floor(p.getZ()) + " " + f(p.getVolume()) + " " + f(p.getPitch())); + } else if (packet instanceof ClientboundSoundEntityPacket p) { + LOG.add("sound " + p.getSound().value().location() + " entity " + f(p.getVolume()) + " " + f(p.getPitch())); + } else if (packet instanceof ClientboundLevelEventPacket p) { + LOG.add("level " + p.getType() + " " + pos(p.getPos()) + " " + p.getData()); + if (p.getType() == 2001) { + // LevelEventHandler: the block's break sound (the client plays it). + BlockState state = net.minecraft.world.level.block.Block.stateById(p.getData()); + if (!state.isAir()) { + var sound = state.getSoundType(); + LOG.add("sound " + sound.getBreakSound().location() + " " + pos(p.getPos()) + " " + f((sound.getVolume() + 1.0F) / 2.0F) + + " " + f(sound.getPitch() * 0.8F)); + } + } + } + } + + @Override + protected void tickServer(BooleanSupplier haveTime) { + try { + step(haveTime); + } catch (Throwable t) { + t.printStackTrace(); + out.flush(); + System.exit(3); + } + } + + ServerLevel level() { return this.overworld(); } + + void step(BooleanSupplier haveTime) throws Exception { + if (scenario >= SCENARIOS.size()) { + out.close(); + Runtime.getRuntime().halt(0); + return; + } + Scenario s = SCENARIOS.get(scenario); + ServerLevel level = level(); + int cx = s.originX >> 4, cz = s.originZ >> 4; + switch (phase) { + case 0 -> { + // Every scenario at the same origin reuses the forced chunks (reset between scenarios). + if (forced == null || forced[0] != cx || forced[1] != cz) { + if (forced != null) + for (int dx = -4; dx <= 4; dx++) + for (int dz = -4; dz <= 4; dz++) + level.setChunkForced(forced[0] + dx, forced[1] + dz, false); + for (int dx = -4; dx <= 4; dx++) + for (int dz = -4; dz <= 4; dz++) + level.setChunkForced(cx + dx, cz + dz, true); + forced = new int[] {cx, cz}; + } + phase = 1; + super.tickServer(haveTime); + } + case 1 -> { + super.tickServer(haveTime); + boolean ready = true; + for (int dx = -4; dx <= 4 && ready; dx++) + for (int dz = -4; dz <= 4 && ready; dz++) + ready = level.isPositionEntityTicking(new BlockPos((cx + dx) * 16, -60, (cz + dz) * 16)); + if (ready) { + // Built and run within one server tick: nothing ticks in between (light is + // not updated either; nothing sculk does reads it). + reset(s, level); + this.getWorldData().overworldData().setGameTime(1000L); + build(s, level); + run(s, level); + scenario++; + phase = 0; + } + } + default -> throw new IllegalStateException(); + } + } + + /** Put the flat preset back around the origin: no blocks, block entities, ticks or entities left from the last scenario. */ + void reset(Scenario s, ServerLevel level) throws Exception { + for (Entity e : level.getAllEntities()) if (!(e instanceof ServerPlayer)) e.discard(); + BlockState bedrock = net.minecraft.world.level.block.Blocks.BEDROCK.defaultBlockState(); + BlockState dirt = net.minecraft.world.level.block.Blocks.DIRT.defaultBlockState(); + BlockState grass = net.minecraft.world.level.block.Blocks.GRASS_BLOCK.defaultBlockState(); + BlockState air = net.minecraft.world.level.block.Blocks.AIR.defaultBlockState(); + int flags = 2 | 16 | 256 | 512; + BlockPos.MutableBlockPos p = new BlockPos.MutableBlockPos(); + for (int x = s.originX - RESET; x <= s.originX + RESET; x++) + for (int z = s.originZ - RESET; z <= s.originZ + RESET; z++) + for (int y = -64; y <= -30; y++) { + BlockState want = y == -64 ? bedrock : y < -61 ? dirt : y == -61 ? grass : air; + p.set(x, y, z); + if (level.getBlockState(p) != want) level.setBlock(p, want, flags); + } + var box = new net.minecraft.world.level.levelgen.structure.BoundingBox(s.originX - RESET - 2, -64, s.originZ - RESET - 2, + s.originX + RESET + 2, 0, s.originZ + RESET + 2); + level.getBlockTicks().clearArea(box); + level.getFluidTicks().clearArea(box); + ((java.util.Collection) get(level, "blockEvents")).clear(); + } + + static BlockState parseState(ServerLevel level, String text) throws Exception { + return BlockStateParser.parseForBlock(level.holderLookup(Registries.BLOCK), text, false).blockState(); + } + + void build(Scenario s, ServerLevel level) throws Exception { + for (String[] b : s.blocks) { + if (b[0].equals("block")) { + level.setBlock(new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])), parseState(level, b[4]), 2 | 16); + } else { + BlockState state = parseState(level, b[7]); + int x0 = Integer.parseInt(b[1]), y0 = Integer.parseInt(b[2]), z0 = Integer.parseInt(b[3]); + int x1 = Integer.parseInt(b[4]), y1 = Integer.parseInt(b[5]), z1 = Integer.parseInt(b[6]); + for (int x = Math.min(x0, x1); x <= Math.max(x0, x1); x++) + for (int y = Math.min(y0, y1); y <= Math.max(y0, y1); y++) + for (int z = Math.min(z0, z1); z <= Math.max(z0, z1); z++) + level.setBlock(new BlockPos(x, y, z), state, 2 | 16); + } + } + } + + String who(Entity e) { + if (e == null) return "none"; + if (e instanceof ServerPlayer) return "player"; + return names.getOrDefault(e, "e" + e.getId()); + } + + Entity source(String word, List mobs) { + if (word.equals("none")) return null; + if (word.equals("player")) return player; + return mobs.get(Integer.parseInt(word.substring(1))); + } + + void run(Scenario s, ServerLevel level) throws Exception { + out.println("== " + s.name); + this.getWorldData().overworldData().setGameTime(1000L); + var clock = level.registryAccess().lookupOrThrow(Registries.WORLD_CLOCK).getOrThrow(WorldClocks.OVERWORLD); + this.clockManager().setTotalTicks(clock, 6000L); + level.setRainLevel(0.0F); + level.setThunderLevel(0.0F); + this.setDifficulty(s.difficulty, true); + level.getGameRules().set(GameRules.SPAWN_WARDENS, s.wardens, this); + names.clear(); + if (player == null) { + CommonListenerCookie cookie = CommonListenerCookie.createInitial(new GameProfile(new UUID(0x1234L, 0x5678L), "horizon-sculk"), false); + player = new ServerPlayer(this, level, cookie.gameProfile(), cookie.clientInformation()); + Connection connection = new Connection(PacketFlow.SERVERBOUND); + new EmbeddedChannel(connection); + this.getPlayerList().placeNewPlayer(connection, player, cookie); + } + player.removeAllEffects(); + field(ServerPlayer.class, "wardenSpawnTracker").set(player, new WardenSpawnTracker()); + if (s.warning >= 0) player.getWardenSpawnTracker().setWarningLevel(s.warning); + double[] at = s.player != null ? s.player : new double[] {s.originX + 0.5, 100.0, s.originZ + 0.5}; + player.setGameMode(switch (s.mode) { + case "creative" -> GameType.CREATIVE; + case "spectator" -> GameType.SPECTATOR; + case "adventure" -> GameType.ADVENTURE; + default -> GameType.SURVIVAL; + }); + player.snapTo(at[0], at[1], at[2], 0.0F, 0.0F); + player.setDeltaMovement(Vec3.ZERO); + player.setShiftKeyDown(s.sneak); + List mobs = new ArrayList<>(); + int id = 100000; + for (MobSpec spec : s.mobs) { + EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(spec.type)); + Mob mob = (Mob) type.create(level, EntitySpawnReason.COMMAND); + mob.setId(id++); + mob.snapTo(spec.x, spec.y, spec.z, spec.yaw, 0.0F); + mob.setYHeadRot(spec.yaw); + mob.setYBodyRot(spec.yaw); + for (String flag : spec.flags) { + if (flag.equals("persistent")) mob.setPersistenceRequired(); + else if (flag.equals("noai")) mob.setNoAi(true); + else throw new IllegalArgumentException(flag); + } + level.addFreshEntity(mob); + mob.getRandom().setSeed(spec.seed); + names.put(mob, "m" + mobs.size()); + mobs.add(mob); + } + Object manager = get(level, "entityManager"); + Method managerTick = method(manager.getClass(), "tick"); + managerTick.invoke(manager); + Set known = new HashSet<>(); + for (Entity e : level.getAllEntities()) known.add(e); + if (System.getenv("SCULK_TRACE") != null) field(Level.class, "random").set(level, new TracingRandom(0L)); + level.getRandom().setSeed(s.levelSeed); + Method tickTime = method(ServerLevel.class, "tickTime"); + Method tickBlock = method(ServerLevel.class, "tickBlock", BlockPos.class, net.minecraft.world.level.block.Block.class); + Method tickFluid = method(ServerLevel.class, "tickFluid", BlockPos.class, net.minecraft.world.level.material.Fluid.class); + Method runBlockEvents = method(ServerLevel.class, "runBlockEvents"); + net.minecraft.world.level.entity.EntityTickList tickList = (net.minecraft.world.level.entity.EntityTickList) get(level, "entityTickList"); + Map last = new HashMap<>(); + String lastPlayer = ""; + String lastRng = ""; + LOG.clear(); + for (int t = 0; t <= s.ticks; t++) { + if (t > 0) { + level.environmentAttributes().invalidateTickCache(); + tickTime.invoke(level); + long time = level.getGameTime(); + level.getBlockTicks().tick(time, 65536, (p, b) -> { + try { tickBlock.invoke(level, p, b); } catch (Exception e) { throw new RuntimeException(e); } + }); + level.getFluidTicks().tick(time, 65536, (p, fl) -> { + try { tickFluid.invoke(level, p, fl); } catch (Exception e) { throw new RuntimeException(e); } + }); + runBlockEvents.invoke(level); + for (Action a : s.actions) if (a.tick == t) act(level, a.words, mobs); + // The player first (it joined first): only its warden spawn tracker. + player.getWardenSpawnTracker().tick(); + tickList.forEach(e -> { + if (e instanceof ServerPlayer || e.isRemoved()) return; + e.checkDespawn(); + if (e.isRemoved()) return; + level.tickNonPassenger(e); + }); + level.tickBlockEntities(); + managerTick.invoke(manager); + } + List lines = new ArrayList<>(); + for (int[] w : s.watch) { + BlockPos p = new BlockPos(w[0], w[1], w[2]); + String line = describe(level, p); + String key = pos(p); + if (!line.equals(last.get(key))) { + last.put(key, line); + lines.add("blk " + key + " " + line); + } + } + WardenSpawnTracker tracker = player.getWardenSpawnTracker(); + MobEffectInstance dark = player.getEffect(MobEffects.DARKNESS); + String now = "warn " + tracker.getWarningLevel() + " " + + field(WardenSpawnTracker.class, "cooldownTicks").getInt(tracker) + " dark " + (dark == null ? "-" : String.valueOf(dark.getDuration())); + if (!now.equals(lastPlayer)) { + lastPlayer = now; + lines.add(now); + } + List fresh = new ArrayList<>(); + for (Entity e : level.getAllEntities()) if (!known.contains(e)) fresh.add(e); + fresh.sort(Comparator.comparingInt(Entity::getId)); + for (Entity e : fresh) { + known.add(e); + names.put(e, "n" + names.size()); + // An entity's own random is unseeded: seed what appeared, as Horizon does. + if (e instanceof Mob mob) { + mob.getRandom().setSeed(0x5eedL + names.size()); + @SuppressWarnings("unchecked") + Map> sensors = + (Map>) get(mob.getBrain(), "sensors"); + for (var sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom()); + } + lines.add("new " + BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()) + " " + d(e.getX()) + "," + d(e.getY()) + "," + d(e.getZ())); + } + lines.addAll(LOG); + LOG.clear(); + String rng = "rng " + Long.toHexString(seedOf(level.getRandom())); + if (!rng.equals(lastRng)) { + lastRng = rng; + lines.add(rng); + } + for (String line : lines) out.println(t + " " + line); + } + for (Mob mob : mobs) mob.discard(); + for (Entity e : level.getAllEntities()) if (!(e instanceof ServerPlayer)) e.discard(); + // Out of the way while the next scenario is built. + player.snapTo(s.originX + 0.5, 100.0, s.originZ + 0.5, 0.0F, 0.0F); + player.removeAllEffects(); + managerTick.invoke(manager); + out.flush(); + } + + /** A scripted action: `event NAME x y z SOURCE [STATE]` or `set x y z STATE` (setBlock with update flags 3). */ + void act(ServerLevel level, String[] w, List mobs) throws Exception { + switch (w[0]) { + case "event" -> { + Holder event = BuiltInRegistries.GAME_EVENT.get(Identifier.parse(w[1])).orElseThrow(); + Vec3 at = new Vec3(Double.parseDouble(w[2]), Double.parseDouble(w[3]), Double.parseDouble(w[4])); + Entity source = source(w[5], mobs); + BlockState state = w.length > 6 ? parseState(level, w[6]) : null; + level.gameEvent(event, at, GameEvent.Context.of(source, state)); + } + case "set" -> level.setBlock(new BlockPos(Integer.parseInt(w[1]), Integer.parseInt(w[2]), Integer.parseInt(w[3])), parseState(level, w[4]), 3); + default -> throw new IllegalArgumentException(String.join(" ", w)); + } + } + + String describe(ServerLevel level, BlockPos p) throws Exception { + StringBuilder sb = new StringBuilder(); + BlockState state = level.getBlockState(p); + sb.append(BlockStateParser_serialize(state)); + BlockEntity be = level.getBlockEntity(p); + if (be instanceof SculkSensorBlockEntity sensor) { + sb.append(" freq=").append(sensor.getLastVibrationFrequency()).append(vibration(level, sensor.getVibrationData())); + } else if (be instanceof SculkShriekerBlockEntity shrieker) { + sb.append(" warn=").append(field(SculkShriekerBlockEntity.class, "warningLevel").getInt(shrieker)).append(vibration(level, shrieker.getVibrationData())); + } else if (be instanceof SculkCatalystBlockEntity catalyst) { + SculkSpreader spreader = catalyst.getListener().getSculkSpreader(); + sb.append(" cursors=").append(spreader.getCursors().size()); + for (SculkSpreader.ChargeCursor c : spreader.getCursors()) { + sb.append(' ').append(pos(c.getPos())).append(':').append(c.getCharge()).append(':') + .append(field(SculkSpreader.ChargeCursor.class, "updateDelay").getInt(c)).append(':').append(c.getDecayDelay()).append(':'); + @SuppressWarnings("unchecked") + Set facings = (Set) field(SculkSpreader.ChargeCursor.class, "facings").get(c); + if (facings == null) sb.append('-'); + else { + List list = new ArrayList<>(facings); + list.sort(Comparator.comparingInt(Direction::ordinal)); + for (Direction dir : list) sb.append(dir.getSerializedName().charAt(0)); + } + } + } + return sb.toString(); + } + + static String BlockStateParser_serialize(BlockState state) { + return BlockStateParser.serialize(state); + } + + String vibration(ServerLevel level, VibrationSystem.Data data) throws Exception { + StringBuilder sb = new StringBuilder(); + VibrationInfo info = data.getCurrentVibration(); + sb.append(" cur=").append(info(level, info)).append(" travel=").append(data.getTravelTimeInTicks()); + VibrationSelector selector = data.getSelectionStrategy(); + @SuppressWarnings("unchecked") + Optional current = (Optional) field(VibrationSelector.class, "currentVibrationData").get(selector); + if (current.isEmpty()) sb.append(" sel=-"); + else { + Object ev = current.get(); + VibrationInfo chosen = (VibrationInfo) method(ev.getClass(), "event").invoke(ev); + long tick = (long) method(ev.getClass(), "tick").invoke(ev); + sb.append(" sel=").append(info(level, chosen)).append('@').append(tick); + } + return sb.toString(); + } + + String info(ServerLevel level, VibrationInfo info) { + if (info == null) return "-"; + Vec3 p = info.pos(); + Entity source = info.getEntity(level).orElse(null); + Entity owner = info.getProjectileOwner(level).orElse(null); + return info.gameEvent().unwrapKey().orElseThrow().identifier().getPath() + "/" + f(info.distance()) + "/" + d(p.x) + "," + d(p.y) + "," + d(p.z) + + "/" + who(source) + "/" + who(owner); + } + + @Override protected SampleLogger getTickTimeLogger() { return sampleLogger; } + @Override public boolean isTickTimeLoggingEnabled() { return false; } + @Override protected void waitUntilNextTick() { this.runAllTasks(); } + @Override public SystemReport fillServerSystemReport(SystemReport report) { report.setDetail("Type", "Sculk oracle"); return report; } + @Override protected void onServerExit() { super.onServerExit(); System.exit(0); } + @Override protected void onServerCrash(net.minecraft.CrashReport report) { super.onServerCrash(report); System.exit(1); } + @Override public boolean isHardcore() { return false; } + @Override public LevelBasedPermissionSet operatorUserPermissions() { return LevelBasedPermissionSet.ALL; } + @Override public PermissionSet getFunctionCompilationPermissions() { return LevelBasedPermissionSet.OWNER; } + @Override public boolean shouldRconBroadcast() { return false; } + @Override public boolean isDedicatedServer() { return false; } + @Override public int getRateLimitPacketsPerSecond() { return 0; } + @Override public int getCommandSpamThresholdSeconds() { return 0; } + @Override public int getChatSpamThresholdSeconds() { return 0; } + @Override public boolean useNativeTransport() { return false; } + @Override public boolean isPublished() { return false; } + @Override public boolean shouldInformAdmins() { return false; } + @Override public boolean isSingleplayerOwner(NameAndId nameAndId) { return false; } + @Override public int getMaxPlayers() { return 1; } + } +} diff --git a/tools/test_sculk_parity.py b/tools/test_sculk_parity.py new file mode 100644 index 000000000..7b182157b --- /dev/null +++ b/tools/test_sculk_parity.py @@ -0,0 +1,289 @@ +#!/usr/bin/env python3 +"""Differential sculk harness: sensors, calibrated sensors, shriekers, catalysts and wardens. + +The Java oracle (VanillaSculkOracle) runs each scenario in a real, headless, flat vanilla server +level: it builds the blocks, places the player (with a warning level) and entities, and ticks the +level in ServerLevel.tick's order while scripted game events and block changes happen at given +ticks. Horizon runs the same scenarios through its game code (`HORIZON_SCULK_FIXTURE`, the +same functions the game ticks). Both print, per tick, what changed at the watched blocks (state, +vibration, selector, last frequency, warning level, charge cursors), sounds, level events, the +player's warden warning level and darkness, new entities, and the level random. The harness +reports each scenario's first differing tick. + + python3 tools/test_sculk_parity.py [--only NAME ...] [--count N] [--rust-only] [--java-only] [--report-only] +""" +import argparse +import os +import random +import subprocess + +try: + from . import lab, oracle_harness, test_rust_parity as base, test_model_baking_parity as baking +except ImportError: + import lab + import oracle_harness + import test_rust_parity as base + import test_model_baking_parity as baking + +FLOOR = -60 # top of the flat preset's grass layer + 1 +SENSOR = 'minecraft:sculk_sensor' +CALIBRATED = 'minecraft:calibrated_sculk_sensor' +SHRIEKER = 'minecraft:sculk_shrieker' +CATALYST = 'minecraft:sculk_catalyst' + +# Game events that sculk listens to (and some that it does not), by frequency. +EVENTS = ['step', 'swim', 'flap', 'projectile_land', 'hit_ground', 'splash', 'item_interact_finish', 'projectile_shoot', + 'instrument_play', 'entity_action', 'elytra_glide', 'unequip', 'entity_dismount', 'equip', 'entity_interact', + 'shear', 'entity_mount', 'entity_damage', 'drink', 'eat', 'container_close', 'block_close', 'block_deactivate', + 'block_detach', 'container_open', 'block_open', 'block_activate', 'block_attach', 'prime_fuse', 'note_block_play', + 'block_change', 'block_destroy', 'fluid_pickup', 'block_place', 'fluid_place', 'entity_place', 'lightning_strike', + 'teleport', 'entity_die', 'explode', 'item_interact_start', 'jukebox_play', 'shriek', 'resonate_3', 'resonate_11'] + + +def handwritten(): + s = [] + + def add(name, ticks, lines, opts=''): + s.append((name, ticks, opts, lines)) + + sensor = f'block 0 {FLOOR} 0 {SENSOR}' + watch = f'watch 0 {FLOOR} 0' + add('sensor_step', 60, [sensor, watch, 'player 3.5 -60 0.5', 'at 2 event minecraft:step 3.5 -60 0.5 player']) + add('sensor_out_of_range', 30, [sensor, watch, 'player 9.5 -60 0.5', 'at 2 event minecraft:step 9.5 -60 0.5 player']) + add('sensor_edge_of_range', 40, [sensor, watch, 'player 8.5 -60 0.5', 'at 2 event minecraft:step 8.5 -60 0.5 player']) + add('sensor_wool', 40, [sensor, watch, f'fill 2 {FLOOR} -3 2 {FLOOR + 3} 3 minecraft:white_wool', + 'player 4.5 -60 0.5', 'at 2 event minecraft:block_place 4.5 -60 0.5 player']) + add('sensor_sneak', 60, [sensor, watch, 'player 3.5 -60 0.5 sneak', 'at 2 event minecraft:step 3.5 -60 0.5 player', + 'at 3 event minecraft:entity_damage 3.5 -60 0.5 player']) + add('sensor_spectator', 40, [sensor, watch, 'player 3.5 -60 0.5 spectator', 'at 2 event minecraft:step 3.5 -60 0.5 player']) + add('sensor_wool_dampens', 40, [sensor, watch, 'player 3.5 -60 0.5', + 'at 2 event minecraft:step 3.5 -60 0.5 player minecraft:white_wool']) + add('sensor_own_place', 40, [sensor, watch, 'at 2 event minecraft:block_place 0.5 -59.5 0.5 none', + 'at 6 event minecraft:block_change 0.5 -59.5 0.5 none']) + add('sensor_selector', 60, [sensor, watch, 'player 3.5 -60 0.5', + 'at 2 event minecraft:step 5.5 -60 0.5 player', + 'at 2 event minecraft:explode 5.5 -60 0.5 none', + 'at 2 event minecraft:eat 2.5 -60 0.5 player', + 'at 2 event minecraft:block_place 6.5 -60 0.5 none', + 'at 3 event minecraft:block_destroy 1.5 -60 0.5 none']) + add('sensor_cooldown', 120, [sensor, watch, 'player 3.5 -60 0.5'] + + [f'at {t} event minecraft:block_change 4.5 -60 {0.5 + (t % 5)} player' for t in range(2, 100, 3)]) + add('sensor_redstone', 60, [sensor, watch, f'block 1 {FLOOR} 0 minecraft:redstone_wire', f'block 2 {FLOOR} 0 minecraft:redstone_wire', + f'block 0 {FLOOR} 1 minecraft:comparator[facing=north]', f'block 0 {FLOOR} 2 minecraft:redstone_wire', + f'watch 1 {FLOOR} 0', f'watch 2 {FLOOR} 0', f'watch 0 {FLOOR} 1', f'watch 0 {FLOOR} 2', + 'player 5.5 -60 3.5', 'at 2 event minecraft:container_open 5.5 -60 3.5 player']) + add('sensor_resonance', 80, [sensor, watch, f'block 1 {FLOOR} 0 minecraft:amethyst_block', + f'block 4 {FLOOR} 0 {CALIBRATED}[facing=north]', f'watch 4 {FLOOR} 0', + f'block 6 {FLOOR} 0 {SENSOR}', f'watch 6 {FLOOR} 0', + 'player -3.5 -60 0.5', 'at 2 event minecraft:block_place -3.5 -60 0.5 player']) + for power in (0, 3, 7, 13): + cal = f'block 0 {FLOOR} 0 {CALIBRATED}[facing=north]' + lines = [cal, watch, 'player 3.5 -60 0.5'] + if power: + # A redstone wire behind (south of a north-facing sensor) carries the input power. + lines += [f'block 0 {FLOOR} 1 minecraft:redstone_wire[power={power},north=side,south=side]', f'watch 0 {FLOOR} 1'] + lines += [f'at {2 + 4 * i} event minecraft:{e} 3.5 -60 {0.5 + i} player' for i, e in + enumerate(['block_change', 'eat', 'step', 'block_destroy', 'container_open', 'entity_die', 'drink', 'block_place'])] + add(f'calibrated_power_{power}', 90, lines) + shrieker = f'block 0 {FLOOR} 0 {SHRIEKER}' + # Shriekers hear only a sensor's tendrils clicking: a sensor beside it hears the player. + near = [f'block 2 {FLOOR} 0 {SENSOR}', f'watch 2 {FLOOR} 0'] + for warn in (0, 1, 2, 3): + add(f'shrieker_warn_{warn}', 120, [f'block 0 {FLOOR} 0 {SHRIEKER}[can_summon=true]', watch, *near, f'player 3.5 -60 0.5 warn={warn}', + 'at 2 event minecraft:step 3.5 -60 0.5 player']) + add('shrieker_no_summon', 120, [shrieker, watch, *near, 'player 3.5 -60 0.5 warn=2', 'at 2 event minecraft:step 3.5 -60 0.5 player']) + add('shrieker_peaceful', 120, [f'block 0 {FLOOR} 0 {SHRIEKER}[can_summon=true]', watch, *near, 'player 3.5 -60 0.5 warn=1', + 'at 2 event minecraft:step 3.5 -60 0.5 player'], 'difficulty=peaceful') + add('shrieker_rule_off', 120, [f'block 0 {FLOOR} 0 {SHRIEKER}[can_summon=true]', watch, *near, 'player 3.5 -60 0.5 warn=1', + 'at 2 event minecraft:step 3.5 -60 0.5 player'], 'nowardens') + add('shrieker_unheard', 60, [f'block 0 {FLOOR} 0 {SHRIEKER}[can_summon=true]', watch, *near, 'player 3.5 -60 0.5', + 'at 2 event minecraft:step 3.5 -60 0.5 none', 'at 4 event minecraft:block_change 3.5 -60 0.5 player', + 'at 6 event minecraft:eat 3.5 -60 0.5 player']) + add('shrieker_cooldown', 600, [f'block 0 {FLOOR} 0 {SHRIEKER}[can_summon=true]', watch, *near, 'player 3.5 -60 0.5'] + + [f'at {t} event minecraft:step 3.5 -60 0.5 player' for t in range(2, 600, 37)]) + add('shrieker_removed_while_shrieking', 60, [f'block 0 {FLOOR} 0 {SHRIEKER}[can_summon=true]', watch, *near, 'player 3.5 -60 0.5 warn=2', + 'at 2 event minecraft:step 3.5 -60 0.5 player', f'at 20 set 0 {FLOOR} 0 minecraft:air']) + add('shrieker_summons', 200, [f'block 0 {FLOOR} 0 {SHRIEKER}[can_summon=true]', watch, *near, 'player 3.5 -60 0.5 warn=3', + 'at 2 event minecraft:step 3.5 -60 0.5 player']) + add('shrieker_creative', 60, [f'block 0 {FLOOR} 0 {SHRIEKER}[can_summon=true]', watch, *near, 'player 3.5 -60 0.5 creative warn=2', + 'at 2 event minecraft:step 3.5 -60 0.5 player']) + return s + + +def random_scenarios(count, seed): + rng = random.Random(seed) + out = [] + sculk = [SENSOR, SENSOR, SENSOR, CALIBRATED, CALIBRATED, SHRIEKER, SHRIEKER] + others = ['minecraft:white_wool', 'minecraft:red_wool', 'minecraft:amethyst_block', 'minecraft:stone', 'minecraft:redstone_wire', + 'minecraft:redstone_block', 'minecraft:white_carpet', 'minecraft:glass'] + facings = ['north', 'south', 'east', 'west'] + for n in range(count): + lines = [] + cells = {} + for _ in range(rng.randrange(1, 5)): + x, y, z = rng.randrange(-4, 5), FLOOR + rng.randrange(0, 3), rng.randrange(-4, 5) + kind = rng.choice(sculk) + if kind == CALIBRATED: + kind += f'[facing={rng.choice(facings)}]' + elif kind == SHRIEKER and rng.random() < 0.6: + kind += '[can_summon=true]' + cells[(x, y, z)] = kind + for _ in range(rng.randrange(0, 10)): + x, y, z = rng.randrange(-5, 6), FLOOR + rng.randrange(0, 3), rng.randrange(-5, 6) + cells.setdefault((x, y, z), rng.choice(others)) + for (x, y, z), state in sorted(cells.items()): + # Nothing floats: blocks above the floor stand on stone. + for below in range(FLOOR, y): + cells.setdefault((x, below, z), 'minecraft:stone') + # Wire and carpet stand on a full block, or they would pop (items are another harness's work). + solid = {'minecraft:' + n for n in ('stone', 'white_wool', 'red_wool', 'amethyst_block', 'redstone_block', 'glass')} + for (x, y, z), state in sorted(cells.items(), key=lambda c: c[0][1]): + if ('redstone_wire' in state or 'carpet' in state) and y > FLOOR and cells[(x, y - 1, z)] not in solid: + cells[(x, y, z)] = 'minecraft:stone' + for (x, y, z), state in sorted(cells.items(), key=lambda c: (c[0][1], c[0][0], c[0][2])): + lines.append(f'block {x} {y} {z} {state}') + if any(k in state for k in ('sculk', 'redstone_wire')): + lines.append(f'watch {x} {y} {z}') + px, pz = rng.randrange(-7, 8) + 0.5, rng.randrange(-7, 8) + 0.5 + mode = rng.choice(['', '', '', '', ' creative', ' sneak']) + warn = rng.choice([0, 0, 1, 2, 3, 3]) + lines.append(f'player {px} {FLOOR + 3} {pz}{mode} warn={warn}') + ticks = rng.choice([60, 100, 160]) + for _ in range(rng.randrange(1, 12)): + t = rng.randrange(1, ticks - 20) + ev = rng.choice(EVENTS) + x, y, z = rng.uniform(-9, 9), FLOOR + rng.uniform(-1, 4), rng.uniform(-9, 9) + source = rng.choice(['player', 'player', 'player', 'none']) + if source == 'player': + x, y, z = px, FLOOR + 3, pz + lines.append(f'at {t} event minecraft:{ev} {x!r} {y!r} {z!r} {source}') + # A block nothing stands on is replaced. + free = [c for c in cells if (c[0], c[1] + 1, c[2]) not in cells] + if free and rng.random() < 0.3: + (x, y, z) = rng.choice(free) + lines.append(f'at {rng.randrange(1, ticks - 5)} set {x} {y} {z} {rng.choice(["minecraft:air", "minecraft:stone"])}') + opts = rng.choice(['', '', '', 'difficulty=peaceful', 'nowardens', f'levelseed={rng.randrange(1 << 30)}']) + out.append((f'random_{n}', ticks, opts, lines)) + return out + + +def scenarios(count, seed): + return handwritten() + random_scenarios(count, seed) + + +def write_scenarios(path, chosen): + lines = [] + for i, (name, ticks, opts, body) in chosen: + # One origin for all: the oracle resets the area between scenarios. + ox, oz = 512, 0 + lines.append(f'scenario {name} ticks={ticks} {opts}'.rstrip()) + lines.append(f'origin {ox} {oz}') + for line in body: + f = line.split() + if f[0] == 'player': + f[1] = repr(float(f[1]) + ox) + f[3] = repr(float(f[3]) + oz) + elif f[0] == 'mob': + f[2] = repr(float(f[2]) + ox) + f[4] = repr(float(f[4]) + oz) + elif f[0] in ('block', 'watch'): + f[1] = str(int(f[1]) + ox) + f[3] = str(int(f[3]) + oz) + elif f[0] == 'fill': + for k in (1, 4): + f[k] = str(int(f[k]) + ox) + for k in (3, 6): + f[k] = str(int(f[k]) + oz) + elif f[0] == 'at' and f[2] == 'event': + f[4] = repr(float(f[4]) + ox) + f[6] = repr(float(f[6]) + oz) + elif f[0] == 'at' and f[2] == 'set': + f[3] = str(int(f[3]) + ox) + f[5] = str(int(f[5]) + oz) + lines.append(' '.join(f)) + lines.append('end') + path.write_text('\n'.join(lines) + '\n') + + +def parse(path): + """{scenario: {tick: [lines]}}""" + result, cur = {}, None + for line in path.read_text().splitlines(): + if line.startswith('== '): + cur = result.setdefault(line[3:], {}) + continue + t, _, rest = line.partition(' ') + if rest.startswith('trace '): + # SCULK_TRACE=1: the level random's callers, for reading only. + continue + cur.setdefault(int(t), []).append(rest) + return result + + +def compare(vanilla, rust): + report, clean = [], 0 + for name, v in vanilla.items(): + r = rust.get(name) + if r is None: + report.append(f'{name}: missing from Horizon') + continue + bad = None + for t in sorted(set(v) | set(r)): + a, b = v.get(t, []), r.get(t, []) + if sorted(a) != sorted(b): + bad = t + report.append(f'{name}: first difference at tick {t}') + for line in a: + if line not in b: + report.append(f' vanilla {line}') + for line in b: + if line not in a: + report.append(f' horizon {line}') + break + if bad is None: + clean += 1 + report.append(f'{name}: all {len(v)} ticks match') + return report, clean + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--only', nargs='*') + parser.add_argument('--count', type=int, default=300, help='random scenarios besides the handwritten ones') + parser.add_argument('--seed', type=int, default=1) + parser.add_argument('--java-only', action='store_true') + parser.add_argument('--rust-only', action='store_true', help='reuse the last vanilla output') + parser.add_argument('--report-only', action='store_true', help='print differences without failing') + args = parser.parse_args() + build = lab.LOCAL / 'sculk-parity' + build.mkdir(parents=True, exist_ok=True) + chosen = [(i, s) for i, s in enumerate(scenarios(args.count, args.seed)) if not args.only or any(o in s[0] for o in args.only)] + inputs = build / 'scenarios.txt' + write_scenarios(inputs, chosen) + lock, jars, _ = base.verify_artifacts() + resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] + if not args.rust_only: + classes, dependencies, _ = oracle_harness.compile_oracle(build, 'VanillaSculkOracle', jars, baking.client_libraries(), + lock['minecraft']['java_major']) + oracle_harness.run_logged(['java', '-Xmx3g', '-Djava.awt.headless=true', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaSculkOracle', inputs, build / 'vanilla.txt'], + build, 'vanilla', timeout=3600) + if not args.java_only: + oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], + build, 'compile-rust') + oracle_harness.run_logged([lab.cargo_target() / 'release/horizon-client', '--resources', resources], build, 'horizon', + env={**os.environ, 'HORIZON_SCULK_FIXTURE': f'{inputs},{build / "horizon.txt"}', 'HORIZON_NO_AUDIO': '1'}) + if args.java_only: + return + names = {s[0] for _, s in chosen} + vanilla = {k: v for k, v in parse(build / 'vanilla.txt').items() if k in names} + report, clean = compare(vanilla, parse(build / 'horizon.txt')) + (build / 'report.txt').write_text('\n'.join(report) + '\n') + print('\n'.join(line for line in report if not line.endswith('ticks match'))) + print(f'{clean}/{len(vanilla)} scenarios match on every tick') + if not args.report_only and clean != len(vanilla): + raise SystemExit(1) + + +if __name__ == '__main__': + main()