From 81783a51256576ec71af48de5cb9b766585f1f10 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:22:29 +0200 Subject: [PATCH] Port PatrolSpawner, Raid and Raids exactly, and run the game on them The patrol spawner, the raid tick (countdown, spawn positions, wave composition, bonus wave, leaders, riders, boss bar, horn seed, raiders leaving, victory, loss, celebration) and the raids.dat codec with DataFixerUpper's partial results and fastutil's map order now follow vanilla line by line. tools/test_raid_parity.py runs vanilla's own PatrolSpawner, Raids and Raids.CODEC on a stand-in level: 1,900 cases match. In game, raiders join, are loaded, hurt and killed through addWaveMob, updateBossbar and removeFromRaid as vanilla calls them, the wave leader map lives in the raid, recruits take the raid's current wave, raid and patrol mobs keep their spawn rotation, and each dimension keeps its own raids.dat. Bad Omen and Raid Omen act from inside the effect tick, with the ConcurrentModificationException vanilla swallows when Raid Omen is first added, and the omen position is saved with the player. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/raid_fixture.rs | 1041 +++++++++++ crates/horizon-client/src/effects.rs | 114 ++ crates/horizon-client/src/game.rs | 1 - .../src/game/natural_spawning.rs | 6 +- crates/horizon-client/src/game/potions.rs | 10 +- crates/horizon-client/src/game/raids.rs | 812 ++++++--- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/mobs.rs | 1 + crates/horizon-client/src/mobs/raider.rs | 25 + crates/horizon-client/src/patrol.rs | 318 ++++ crates/horizon-client/src/raid.rs | 1560 ++++++++++++----- .../horizonlab/parity/VanillaRaidOracle.java | 727 ++++++++ tools/test_raid_parity.py | 378 ++++ 13 files changed, 4258 insertions(+), 736 deletions(-) create mode 100644 crates/horizon-client/examples/raid_fixture.rs create mode 100644 crates/horizon-client/src/patrol.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRaidOracle.java create mode 100644 tools/test_raid_parity.py diff --git a/crates/horizon-client/examples/raid_fixture.rs b/crates/horizon-client/examples/raid_fixture.rs new file mode 100644 index 000000000..dfe517e51 --- /dev/null +++ b/crates/horizon-client/examples/raid_fixture.rs @@ -0,0 +1,1041 @@ +//! Pillager patrols and raids for differential tests against vanilla +//! (tools/test_raid_parity.py): reads the cases of `VanillaRaidOracle` and +//! prints what `horizon_client::patrol` and `horizon_client::raid` do, in the +//! oracle's order and format. +//! +//! usage: raid_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + assets::Assets, + blocks::BlockFacts, + items::Items, + mobs::{ + Species, + data::MobData, + spawn_rules::{self, Dimension, SpawnLevel}, + spawn_selection::{self, Heightmap}, + spawning::LocalDifficulty, + }, + patrol::{self, GameplayAttributes, Member, PatrolLevel, PatrolSpawner}, + raid::{self, Action, BarName, RaidLevel, RaidPlayer, RaiderInfo, Raids}, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use horizon_world::{chunk::BlockState, nbt::Tag, registry::BlockStateId}; +use std::{ + cell::RefCell, + collections::{BTreeMap, HashMap, HashSet}, + fmt::Write as _, + fs, + path::Path, +}; + +#[derive(Clone, Copy)] +struct Bx([i32; 6]); +impl Bx { + fn parse(s: &str) -> Self { + let v: Vec = s.split(',').map(|n| n.parse().unwrap_or(0)).collect(); + Self([v[0], v[1], v[2], v[3], v[4], v[5]]) + } + fn has(&self, x: i32, y: i32, z: i32) -> bool { + let b = self.0; + x >= b[0] && x <= b[3] && y >= b[1] && y <= b[4] && z >= b[2] && z <= b[5] + } +} + +struct Shared<'a> { + facts: &'a BlockFacts, + data: &'a MobData, + block_tags: &'a HashMap>, + attributes: &'a GameplayAttributes, + air: BlockStateId, +} + +struct Player { + position: [f64; 3], + mode: String, + alive: bool, +} +impl Player { + fn block(&self) -> [i32; 3] { + [ + self.position[0].floor() as i32, + self.position[1].floor() as i32, + self.position[2].floor() as i32, + ] + } +} + +struct World<'a> { + s: &'a Shared<'a>, + blocks: Vec<(Bx, BlockStateId)>, + lights: Vec<(Bx, i32, i32)>, + biome: String, + sky: i32, + light: i32, + darken: i32, + difficulty: i32, + dimension: Dimension, + dimension_id: String, + unloaded: HashSet<(i32, i32)>, + no_ticking: HashSet<(i32, i32)>, + villages: Vec<[i32; 3]>, + pois: Vec<[i32; 3]>, + player: Option, + clock: i64, + inhabited: i64, + moon: f32, + patrols: bool, + raids: bool, +} +impl World<'_> { + fn lights_at(&self, x: i32, y: i32, z: i32) -> (i32, i32) { + self.lights + .iter() + .rev() + .find(|(b, ..)| b.has(x, y, z)) + .map_or((self.sky, self.light), |(_, s, b)| (*s, *b)) + } + fn min_y(&self) -> i32 { + if self.dimension == Dimension::Overworld { + -64 + } else { + 0 + } + } + fn max_y(&self) -> i32 { + if self.dimension == Dimension::Overworld { + 319 + } else { + 255 + } + } + fn loaded(&self, cx: i32, cz: i32) -> bool { + !self.unloaded.contains(&(cx, cz)) + } + fn height(&self, kind: Heightmap, x: i32, z: i32) -> i32 { + if !self.loaded(x >> 4, z >> 4) { + return self.min_y(); + } + (self.min_y()..=self.max_y()) + .rev() + .find(|&y| spawn_selection::heightmap_blocks(self, kind, x, y, z)) + .map_or(self.min_y(), |y| y + 1) + } + fn attribute(&self, key: &str) -> bool { + self.s + .attributes + .value(key, &self.dimension_id, &self.biome, self.clock) + } +} +impl SpawnLevel for World<'_> { + fn state(&self, x: i32, y: i32, z: i32) -> BlockStateId { + self.blocks + .iter() + .rev() + .find(|(b, _)| b.has(x, y, z)) + .map_or(self.s.air, |(_, s)| *s) + } + fn facts(&self) -> &BlockFacts { + self.s.facts + } + fn mob_data(&self) -> &MobData { + self.s.data + } + fn block_tag(&self, tag: &str, block: &str) -> bool { + self.s + .block_tags + .get(tag) + .is_some_and(|s| s.contains(block)) + } + fn biome_tag(&self, tag: &str, _: i32, _: i32, _: i32) -> bool { + self.s + .data + .biome_tags + .get(tag) + .is_some_and(|s| s.contains(&self.biome)) + } + fn sky_light(&self, x: i32, y: i32, z: i32) -> i32 { + self.lights_at(x, y, z).0 + } + fn block_light(&self, x: i32, y: i32, z: i32) -> i32 { + self.lights_at(x, y, z).1 + } + fn sky_darken(&self) -> i32 { + self.darken + } + fn thundering(&self) -> bool { + false + } + fn sea_level(&self) -> i32 { + 63 + } + fn world_surface(&self, x: i32, z: i32) -> i32 { + self.height(Heightmap::WorldSurface, x, z) + } + fn peaceful(&self) -> bool { + self.difficulty == 0 + } + fn dimension(&self) -> Dimension { + self.dimension + } + fn surface_slime_chance(&self, _: i32, _: i32, _: i32) -> f32 { + 0.0 + } + fn world_seed(&self) -> i64 { + 0 + } + fn player_near(&self, _: f64, _: f64, _: f64, _: f64) -> bool { + false + } +} +impl PatrolLevel for World<'_> { + fn spawn_patrols(&self) -> bool { + self.patrols + } + fn bright_outside(&self) -> bool { + self.dimension == Dimension::Overworld && self.darken < 4 + } + fn patrol_players(&self) -> Vec<([i32; 3], bool)> { + self.player + .iter() + .map(|p| (p.block(), p.mode == "spectator")) + .collect() + } + fn sections_to_village(&self, pos: [i32; 3]) -> i32 { + let s = [pos[0] >> 4, pos[1] >> 4, pos[2] >> 4]; + self.villages + .iter() + .map(|v| { + (v[0] - s[0]) + .abs() + .max((v[1] - s[1]).abs()) + .max((v[2] - s[2]).abs()) + }) + .fold(7, i32::min) + } + fn has_chunk(&self, cx: i32, cz: i32) -> bool { + self.loaded(cx, cz) + } + fn can_pillager_patrol_spawn(&self, _: [i32; 3]) -> bool { + self.attribute(patrol::CAN_PILLAGER_PATROL_SPAWN) + } + fn effective_difficulty(&self, pos: [i32; 3]) -> f32 { + let loaded = self.loaded(pos[0] >> 4, pos[2] >> 4); + LocalDifficulty::new( + self.difficulty as u8, + self.clock, + if loaded { self.inhabited } else { 0 }, + if loaded { self.moon } else { 0.0 }, + ) + .effective + } + fn motion_blocking_no_leaves(&self, x: i32, z: i32) -> i32 { + self.height(Heightmap::MotionBlockingNoLeaves, x, z) + } +} +impl RaidLevel for World<'_> { + fn difficulty(&self) -> i32 { + self.difficulty + } + fn has_chunk_at(&self, pos: [i32; 3]) -> bool { + self.loaded(pos[0] >> 4, pos[2] >> 4) + } + fn has_chunks_at(&self, x0: i32, z0: i32, x1: i32, z1: i32) -> bool { + patrol::has_chunks_at(self, x0, z0, x1, z1) + } + fn sections_to_village(&self, pos: [i32; 3]) -> i32 { + PatrolLevel::sections_to_village(self, pos) + } + fn surface_height(&self, x: i32, z: i32) -> i32 { + self.height(Heightmap::WorldSurface, x, z) + } + fn is_position_entity_ticking(&self, pos: [i32; 3]) -> bool { + let c = (pos[0] >> 4, pos[2] >> 4); + self.loaded(c.0, c.1) && !self.no_ticking.contains(&c) + } + fn ravager_can_spawn(&self, [x, y, z]: [i32; 3]) -> bool { + spawn_rules::is_spawn_position_ok(Species::Ravager, self, x, y, z) + || self.s.facts.get(self.state(x, y - 1, z)).name.as_ref() == "minecraft:snow" + && self.s.facts.is_air(self.state(x, y, z)) + } + fn player(&self) -> Option { + self.player.as_ref().map(|p| RaidPlayer { + position: p.position, + block: p.block(), + alive: p.alive, + }) + } +} + +fn parse_state(spec: &str) -> BlockState { + let (name, props) = match spec.split_once('[') { + Some((n, rest)) => (n, rest.trim_end_matches(']')), + None => (spec, ""), + }; + BlockState { + name: name.to_owned(), + properties: props + .split(',') + .filter(|p| !p.is_empty()) + .filter_map(|p| p.split_once('=')) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(), + } +} +fn bits64(v: f64) -> String { + format!("{:x}", v.to_bits()) +} +fn bits32(v: f32) -> String { + format!("{:x}", v.to_bits()) +} +fn ints(s: &str) -> Vec { + s.split(',').map(|n| n.parse().unwrap_or(0)).collect() +} +fn difficulty_id(name: &str) -> i32 { + match name { + "peaceful" => 0, + "easy" => 1, + "hard" => 3, + _ => 2, + } +} + +/// A raider of the scenario, by creation order. +struct Raider { + kind: String, + health: f32, + position: [i32; 3], + tick_count: i32, + no_action_time: i32, + ticks_outside: i32, + removed: bool, + in_level: bool, + patrol_leader: bool, + can_join: bool, + wave: i32, + raid: Option, +} +fn max_health(kind: &str) -> f32 { + match kind { + "minecraft:witch" => 26.0, + "minecraft:ravager" => 100.0, + _ => 24.0, + } +} +fn kind_of(t: raid::RaiderType) -> &'static str { + t.entity() +} + +const PLAYER_UUID: [i32; 4] = [0, 0x1234, 0, 0x5678]; + +/// `ClientboundSoundPacket`: positions travel as eighths of a block. +fn packet_coord(v: f64) -> f64 { + f64::from(((v * 8.0) as i32) as f32 / 8.0) +} + +fn raid_state(raids: &Raids, player_in: &dyn Fn(i32) -> bool) -> String { + let mut s = String::new(); + for id in raids.ids() { + let r = &raids.map[&id]; + let name = match r.bar.name { + BarName::Raid => "Raid".to_owned(), + BarName::Remaining(n) => format!("Raid - Raiders Remaining: {n}"), + BarName::Victory => "Raid - Victory".to_owned(), + BarName::Defeat => "Raid - Defeat".to_owned(), + }; + let leaders: Vec = r.leaders.keys().map(|k| k.to_string()).collect(); + let _ = write!( + s, + " ; r{id} {} act={} st={} om={} gs={} th={} alive={} c={},{},{} wp={} cel={} lead=[{}] bar={},{},{},{}", + r.status.name(), + i32::from(r.active), + i32::from(r.started), + r.omen_level, + r.groups_spawned, + bits32(r.total_health), + ALIVE.with(|a| a.borrow().get(&id).copied().unwrap_or(0)), + r.center[0], + r.center[1], + r.center[2], + r.wave_spawn_pos + .map_or("-".to_owned(), |p| format!("{},{},{}", p[0], p[1], p[2])), + r.celebration_ticks, + leaders.join(", "), + bits32(r.bar.progress), + name, + i32::from(r.bar.visible), + i32::from(r.bar.player && player_in(id)), + ); + } + for id in raids.ids() { + let r = &raids.map[&id]; + let _ = write!( + s, + " ; t{id} {} {} {}", + r.ticks_active, r.cooldown_ticks, r.post_raid_ticks + ); + } + s +} +thread_local! { + static ALIVE: RefCell> = RefCell::new(HashMap::new()); +} + +/// NBT as the oracle's canonical text. +fn canon(tag: &Tag) -> String { + match tag { + Tag::Byte(v) => format!("{v}b"), + Tag::Short(v) => format!("{v}s"), + Tag::Int(v) => v.to_string(), + Tag::Long(v) => format!("{v}L"), + Tag::Float(b) => format!("f{b:x}"), + Tag::Double(b) => format!("d{b:x}"), + Tag::String(s) => format!("\"{}\"", s.to_string_lossy()), + Tag::ByteArray(v) => { + let mut s = "[B;".to_owned(); + for b in v { + let _ = write!(s, "{},", *b as i8); + } + s + "]" + } + Tag::IntArray(v) => { + let mut s = "[I;".to_owned(); + for b in v { + let _ = write!(s, "{b},"); + } + s + "]" + } + Tag::LongArray(v) => { + let mut s = "[L;".to_owned(); + for b in v { + let _ = write!(s, "{b},"); + } + s + "]" + } + Tag::List(items) => { + let mut s = "[".to_owned(); + for t in items { + s += &canon(t); + s.push(','); + } + s + "]" + } + Tag::Compound(map) => { + let mut keys: Vec = map.keys().map(|k| k.to_string_lossy()).collect(); + keys.sort(); + let mut s = "{".to_owned(); + for k in keys { + let _ = write!(s, "{k}:{},", canon(tag.get(&k).unwrap_or(&Tag::End))); + } + s + "}" + } + Tag::End => "?".to_owned(), + } +} + +fn run_codec(c: &BTreeMap<&str, &str>) -> Result { + let hex = c.get("snbt").copied().unwrap_or(""); + let text: Vec = (0..hex.len() / 2) + .map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16)) + .collect::>() + .map_err(|e| e.to_string())?; + let text = String::from_utf8(text).map_err(|e| e.to_string())?; + let (tag, _) = horizon_world::nbt::parse_snbt(&text)?; + let raids = Raids::from_nbt(&tag, 0); + let fresh = raids.dirty && raids.map.is_empty() && raids.next_id == 1 && raids.tick == 0 && { + // A fresh Raids is dirty; a decoded one never is. + true + }; + let mut log = vec![if fresh { "fresh" } else { "decoded" }.to_owned()]; + log.push(canon(&raids.to_nbt())); + for id in raids.ids() { + let r = &raids.map[&id]; + log.push(format!( + "bar {id} {} {} {}", + bits32(r.bar.progress), + i32::from(r.bar.visible), + i32::from(raids.dirty) + )); + } + Ok(log.join(" ; ")) +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new( + args.get(1) + .ok_or("usage: raid_fixture RESOURCES INPUT OUTPUT")?, + ); + let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?; + let assets = Assets::load(root)?; + let registry = assets.registry; + let facts = BlockFacts::load(root, registry)?; + let data = MobData::load(root, &facts); + let items = Items::tags_only(root)?; + let attributes = GameplayAttributes::load(root); + let shared = Shared { + facts: &facts, + data: &data, + block_tags: &items.block_tags, + attributes: &attributes, + air: facts.air, + }; + let mut out = String::new(); + for raw in input.lines() { + if raw.trim().is_empty() { + continue; + } + let mut c = BTreeMap::new(); + let mut name = ""; + for token in raw.split_whitespace() { + match token.split_once('=') { + Some((k, v)) => { + c.insert(k, v); + } + None => name = token, + } + } + let get = + |k: &str, d: &'static str| -> String { c.get(k).copied().unwrap_or(d).to_owned() }; + let mode = get("mode", "raid"); + if mode == "codec" { + let line = match run_codec(&c) { + Ok(l) => l, + Err(e) => format!("error {e}"), + }; + let _ = writeln!(out, "{name} {line}"); + continue; + } + let indexed = |prefix: &str| -> Vec<&str> { + (0..) + .map_while(|i| c.get(format!("{prefix}{i}").as_str()).copied()) + .collect() + }; + let mut blocks = Vec::new(); + for k in indexed("k") { + let (b, s) = k.split_once('/').ok_or("bad block box")?; + blocks.push((Bx::parse(b), registry.resolve(&parse_state(s))?)); + } + let lights = indexed("l") + .into_iter() + .filter_map(|l| { + let (b, v) = l.split_once('/')?; + let (s, k) = v.split_once(',')?; + Some((Bx::parse(b), s.parse().ok()?, k.parse().ok()?)) + }) + .collect(); + let chunks = |key: &str| -> HashSet<(i32, i32)> { + c.get(key) + .map(|u| { + u.split(';') + .filter_map(|p| { + let (x, z) = p.split_once(',')?; + Some((x.parse().ok()?, z.parse().ok()?)) + }) + .collect() + }) + .unwrap_or_default() + }; + let triples = |key: &str| -> Vec<[i32; 3]> { + c.get(key) + .map(|u| { + u.split(';') + .map(ints) + .filter(|v| v.len() == 3) + .map(|v| [v[0], v[1], v[2]]) + .collect() + }) + .unwrap_or_default() + }; + let dimension_id = get("dim", "minecraft:overworld"); + let dimension = match dimension_id.as_str() { + "minecraft:the_nether" => Dimension::Nether, + "minecraft:the_end" => Dimension::End, + _ => Dimension::Overworld, + }; + let player = c.get("p0").map(|p| { + let mut parts = p.split('/'); + let v: Vec = parts + .next() + .unwrap_or("") + .split(',') + .map(|n| n.parse().unwrap_or(0.0)) + .collect(); + Player { + position: [v[0], v[1], v[2]], + mode: parts.next().unwrap_or("survival").to_owned(), + alive: true, + } + }); + let mut world = World { + s: &shared, + blocks, + lights, + biome: get("biome", "minecraft:plains"), + sky: get("sky", "15").parse()?, + light: get("light", "0").parse()?, + darken: get("darken", "0").parse()?, + difficulty: difficulty_id(&get("difficulty", "normal")), + dimension, + dimension_id: dimension_id.clone(), + unloaded: chunks("unloaded"), + no_ticking: chunks("noticking"), + villages: triples("vil"), + pois: triples("poi"), + player, + clock: get("clock", "200000").parse()?, + inhabited: get("inhabited", "0").parse()?, + moon: get("moon", "0.0").parse()?, + patrols: get("patrols", "1") != "0", + raids: get("raids", "1") != "0", + }; + let ticks: i32 = get("ticks", "1").parse()?; + let mut log: Vec = Vec::new(); + if mode == "patrol" { + let mut random = LegacyRandom::new(get("seed", "0").parse()?); + let mut spawner = PatrolSpawner { + next_tick: get("next", "0").parse()?, + }; + let enemies = get("enemies", "1") != "0"; + let mut spawn = |l: &World, m: Member, _: &mut LegacyRandom| -> bool { + // EntityType.create: no monsters in peaceful. + if l.difficulty == 0 { + return false; + } + let mut s = format!( + "spawn minecraft:pillager {} {} {}", + m.pos[0], m.pos[1], m.pos[2] + ); + if m.leader { + // The patrol target is drawn from the pillager's own random + // before it is placed: around the world origin. + let mut own = LegacyRandom::new(m.pos[0] as i64 ^ 0x5DEE); + let t = patrol::patrol_target([0, 0, 0], &mut own); + let origin = + t[1] == 0 && (-500..500).contains(&t[0]) && (-500..500).contains(&t[2]); + s += " leader banner patrolling"; + s += if origin { + " target" + } else { + " target-elsewhere" + }; + } else { + s += " patrolling"; + } + s += " wave=0 join"; + log.push(s); + true + }; + for _ in 0..ticks { + spawner.tick(&world, enemies, &mut random, &mut spawn); + } + log.push(format!( + "next {} {}", + spawner.next_tick, + random.next_int_bound(1000).unwrap_or(0) + )); + let _ = writeln!(out, "{name} {}", log.join(" ; ")); + continue; + } + + // raid + let seed: i64 = get("rseed", "1").parse()?; + let mut raids = Raids::default(); + let mut raiders: Vec = Vec::new(); + let mut events: BTreeMap> = BTreeMap::new(); + for e in indexed("ev") { + let (t, ev) = e.split_once(':').ok_or("bad event")?; + events.entry(t.parse()?).or_default().push(ev.to_owned()); + } + let raid_at = |raids: &Raids, pos: [i32; 3]| raids.nearby(pos).map(|(id, _)| id); + let living = |raiders: &[Raider], id: i32| -> f32 { + raiders + .iter() + .filter(|r| r.raid == Some(id)) + .map(|r| r.health) + .fold(0.0, |a, h| a + h) + }; + let mut last_state = String::new(); + for t in 0..=ticks { + for ev in events.get(&t).cloned().unwrap_or_default() { + log.push(format!("ev {ev}")); + let a: Vec<&str> = ev.split(':').collect(); + let idx = + |i: usize| -> usize { a.get(i).and_then(|v| v.parse().ok()).unwrap_or(0) }; + if ["hurt", "kill", "move", "age", "idle", "gone", "discard"].contains(&a[0]) + && idx(1) >= raiders.len() + { + log.push("noraider".into()); + continue; + } + if a[0] == "killall" || a[0] == "hurtall" { + for i in 0..raiders.len() { + let Some(id) = raiders[i].raid else { continue }; + if raiders[i].removed { + continue; + } + if a[0] == "hurtall" { + if raids.get(id).is_some_and(|r| r.active) { + let l = living(&raiders, id); + if let Some(r) = raids.get_mut(id) { + r.update_bossbar(l); + } + } + let amount: f32 = a[1].parse()?; + let max = max_health(&raiders[i].kind); + raiders[i].health = (raiders[i].health - amount).clamp(0.0, max); + continue; + } + raiders[i].raid = None; + let after = living(&raiders, id); + if let Some(r) = raids.get_mut(id) { + if raiders[i].patrol_leader { + r.remove_leader(raiders[i].wave); + } + if a.len() > 1 && world.player.is_some() { + r.add_hero(PLAYER_UUID); + } + r.remove_from_raid(raiders[i].health, false, after); + } + raiders[i].health = 0.0; + raiders[i].removed = true; + raiders[i].in_level = false; + } + continue; + } + match a[0] { + "omen" => { + let v = ints(a[2]); + let p = world.player.as_mut().ok_or("omen needs p0")?; + p.position = [ + f64::from(v[0]) + 0.5, + f64::from(v[1]), + f64::from(v[2]) + 0.5, + ]; + let pos = p.block(); + let spectator = p.mode == "spectator"; + // Raids.createOrExtendRaid. + if spectator || !world.raids || !world.attribute(patrol::CAN_START_RAID) { + log.push("noraid".into()); + continue; + } + let center = raid::raid_center(pos, &world.pois); + let known: HashSet = raids.ids().into_iter().collect(); + let (id, triggered) = raids.create_or_extend( + center, + world.difficulty, + Some(a[1].parse()?), + 0, + ); + if !known.contains(&id) + && let Some(r) = raids.get_mut(id) + { + r.reseed(seed + i64::from(id) * 1000); + } + if triggered { + log.push("stat minecraft:raid_trigger".into()); + } + } + "setomen" | "stop" => { + let at = world.player.as_ref().map(Player::block).unwrap_or_default(); + if let Some(id) = raid_at(&raids, at) + && let Some(r) = raids.get_mut(id) + { + if a[0] == "stop" { + r.stop(); + } else { + r.omen_level = a[1].parse()?; + } + } + } + "pmove" => { + let v: Vec = + a[1].split(',').map(|n| n.parse().unwrap_or(0.0)).collect(); + if let Some(p) = world.player.as_mut() { + p.position = [v[0], v[1], v[2]]; + } + } + "pdead" | "palive" => { + if let Some(p) = world.player.as_mut() { + p.alive = a[0] == "palive"; + } + } + "diff" => world.difficulty = difficulty_id(a[1]), + "rules" => world.raids = a[1] == "1", + "unload" | "load" | "notick" | "tick" => { + let v = ints(a[1]); + let key = (v[0], v[1]); + match a[0] { + "unload" => { + world.unloaded.insert(key); + } + "load" => { + world.unloaded.remove(&key); + } + "notick" => { + world.no_ticking.insert(key); + } + _ => { + world.no_ticking.remove(&key); + } + } + } + "vil" => { + let v = ints(a[1]); + world.villages.push([v[0], v[1], v[2]]); + } + "unvil" => { + let v = ints(a[1]); + world.villages.retain(|x| x[..] != v[..]); + } + "hurt" => { + let i = idx(1); + if let Some(id) = raiders[i].raid + && let Some(r) = raids.get_mut(id) + && r.active + { + r.update_bossbar(living(&raiders, id)); + } + let amount: f32 = a[2].parse()?; + // LivingEntity.setHealth clamps to [0, max]. + let max = max_health(&raiders[i].kind); + raiders[i].health = (raiders[i].health - amount).clamp(0.0, max); + } + "kill" => { + let i = idx(1); + if let Some(id) = raiders[i].raid { + raiders[i].raid = None; + let after = living(&raiders, id); + if let Some(r) = raids.get_mut(id) { + if raiders[i].patrol_leader { + r.remove_leader(raiders[i].wave); + } + if a.len() > 2 && world.player.is_some() { + r.add_hero(PLAYER_UUID); + } + r.remove_from_raid(raiders[i].health, false, after); + } + } + raiders[i].health = 0.0; + raiders[i].removed = true; + raiders[i].in_level = false; + } + "move" => { + let v = ints(a[2]); + raiders[idx(1)].position = [v[0], v[1], v[2]]; + } + "age" => raiders[idx(1)].tick_count = a[2].parse()?, + "idle" => raiders[idx(1)].no_action_time = a[2].parse()?, + "gone" => raiders[idx(1)].in_level = false, + "discard" => raiders[idx(1)].removed = true, + "join" | "loadmob" => { + let v = ints(a[2]); + let kind = format!("minecraft:{}", a[1]); + let health = max_health(&kind); + raiders.push(Raider { + kind, + health, + position: [v[0], v[1], v[2]], + tick_count: 0, + no_action_time: 0, + ticks_outside: 0, + removed: false, + in_level: true, + patrol_leader: false, + can_join: false, + wave: 0, + raid: None, + }); + let i = raiders.len() - 1; + if a[0] == "join" { + raiders[i].can_join = true; + if let Some(id) = raid_at(&raids, raiders[i].position) { + let wave = raids.map[&id].groups_spawned; + raiders[i].raid = Some(id); + let after = living(&raiders, id); + let r = raids.get_mut(id).ok_or("raid")?; + r.add_wave_mob(health, true, after); + let x = &mut raiders[i]; + x.wave = wave; + x.ticks_outside = 0; + } + } else { + let wave: i32 = a[3].parse()?; + raiders[i].wave = wave; + if a.len() > 4 { + raiders[i].patrol_leader = true; + } + let id: i32 = a.get(5).copied().unwrap_or("2").parse()?; + if raids.get(id).is_some() { + raiders[i].raid = Some(id); + let after = living(&raiders, id); + let r = raids.get_mut(id).ok_or("raid")?; + r.add_wave_mob(health, false, after); + if raiders[i].patrol_leader { + r.set_leader(wave, i as u32); + } + } + } + } + other => return Err(format!("event {other}").into()), + } + } + if t == 0 { + continue; + } + let before: Vec<(Option, i32)> = + raiders.iter().map(|r| (r.raid, r.ticks_outside)).collect(); + let members = |id: i32| -> Vec { + raiders + .iter() + .enumerate() + .filter(|(_, r)| r.raid == Some(id)) + .map(|(i, r)| RaiderInfo { + id: i as u32, + wave: r.wave, + health: r.health, + position: r.position, + tick_count: r.tick_count, + no_action_time: r.no_action_time, + ticks_outside: r.ticks_outside, + removed: r.removed, + other_dimension: false, + in_level: r.in_level, + patrol_leader: r.patrol_leader, + }) + .collect() + }; + let actions = raids.tick(&world, world.raids, &members); + for (id, action) in actions { + match action { + Action::Spawn { pos, wave, spawns } => { + let spawn = + |kind: &str, leader: bool, raiders: &mut Vec| -> usize { + raiders.push(Raider { + kind: kind.to_owned(), + health: max_health(kind), + position: [pos[0], pos[1] + 1, pos[2]], + tick_count: 0, + no_action_time: 0, + ticks_outside: 0, + removed: false, + in_level: true, + patrol_leader: leader, + can_join: true, + wave, + raid: Some(id), + }); + raiders.len() - 1 + }; + let mut lines = Vec::new(); + for s in &spawns { + let i = spawn(kind_of(s.kind), s.leader, &mut raiders); + if s.leader + && let Some(r) = raids.get_mut(id) + { + r.set_leader(wave, i as u32); + } + let mut line = format!( + "spawn {} {} {} {}", + kind_of(s.kind), + pos[0], + pos[1] + 1, + pos[2] + ); + if s.leader { + line += " leader banner patrolling"; + } + let _ = write!(line, " wave={wave} join"); + lines.push(line); + if let Some(rider) = s.rider { + spawn(kind_of(rider), false, &mut raiders); + // joinRaid adds the rider to the level before it mounts. + lines.push(format!( + "spawn {} {} {} {} wave={wave} join", + kind_of(rider), + pos[0], + pos[1] + 1, + pos[2] + )); + } + } + log.extend(lines); + } + Action::Horn { pos, seed } => { + if let Some(p) = world.player.as_ref() { + let in_raid = raids.get(id).is_some_and(|r| r.bar.player); + let (rx, rz) = (f64::from(pos[0]) + 0.5, f64::from(pos[2]) + 0.5); + let (px, py, pz) = (p.position[0], p.position[1], p.position[2]); + let d = ((rx - px) * (rx - px) + (rz - pz) * (rz - pz)).sqrt(); + let x = px + 13.0 / d * (rx - px); + let z = pz + 13.0 / d * (rz - pz); + if d <= 64.0 || in_raid { + log.push(format!( + "horn {seed} {} {} {}", + bits64(packet_coord(x)), + bits64(packet_coord(py)), + bits64(packet_coord(z)) + )); + } + } + } + Action::Remove { id: mob } => { + raiders[mob as usize].raid = None; + } + Action::SetOutside { id: mob, ticks } => { + raiders[mob as usize].ticks_outside = ticks; + } + Action::Victory { heroes, amplifier } => { + for h in heroes { + if h == PLAYER_UUID + && let Some(p) = world.player.as_ref() + && p.mode != "spectator" + { + log.push(format!( + "effect minecraft:hero_of_the_village {} {} false false true", + raid::HERO_DURATION, + // MobEffectInstance clamps the amplifier. + amplifier.clamp(0, 255) + )); + log.push("stat minecraft:raid_win".into()); + } + } + } + } + } + for (i, r) in raiders.iter().enumerate() { + if let Some((was, outside)) = before.get(i) { + if was.is_some() && r.raid.is_none() { + log.push(format!("leave {i}")); + } + if *outside != r.ticks_outside { + log.push(format!("out {i} {}", r.ticks_outside)); + } + } + } + ALIVE.with(|a| { + let mut a = a.borrow_mut(); + a.clear(); + for r in &raiders { + if let Some(id) = r.raid { + *a.entry(id).or_default() += 1; + } + } + }); + let state = raid_state(&raids, &|_| true); + let key: String = state + .split(" ; ") + .filter(|p| { + !(p.starts_with('t') && p[1..].starts_with(|c: char| c.is_ascii_digit())) + }) + .collect::>() + .join(" ; "); + if key != last_state || t % 1000 == 0 || t == ticks { + log.push(format!("t{t}{state}")); + } + last_state = key; + } + let _ = writeln!(out, "{name} {}", log.join(" ; ")); + } + fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index 3bc2e7fb2..0ff38fb7a 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -135,6 +135,16 @@ pub fn instant(id: &str, amp: i32, scale: f64) -> Option { _ => None, } } +/// What an omen's `applyEffectTick` decided. +#[derive(Clone, Debug, PartialEq)] +pub enum OmenTick { + /// It returned true: the effect counts down as usual. + Continue, + /// It returned false: the effect goes. + Remove, + /// It added this effect, then returned false. + Add(EffectInstance), +} #[derive(Clone, Debug, Default)] pub struct PlayerEffects { pub list: Vec, @@ -160,6 +170,71 @@ impl PlayerEffects { pub fn clear(&mut self) { self.list.clear(); } + /// `LivingEntity.tickEffects` (server part) with the omens' effect ticks: + /// `omen` answers `BadOmenMobEffect` (every tick) and `RaidOmenMobEffect` + /// (on its last tick). Returns the actions to apply, in order, and + /// whether Raid Omen was newly added. + /// + /// Bad Omen turning into a new Raid Omen adds an entry to the map being + /// iterated: vanilla's iterator then throws a + /// `ConcurrentModificationException`, which `tickEffects` swallows. Bad + /// Omen stays (not counted down) and the effects after it are not + /// ticked; the next tick refreshes Raid Omen and drops Bad Omen. + pub fn tick_with( + &mut self, + omen: &mut dyn FnMut(&EffectInstance) -> OmenTick, + ) -> (Vec, bool) { + self.tick_count = self.tick_count.wrapping_add(1); + let mut actions = Vec::new(); + let mut added = false; + let mut i = 0; + while i < self.list.len() { + let e = &self.list[i]; + if !(e.infinite() || e.duration > 0) { + self.list.remove(i); + continue; + } + let t = if e.infinite() { + self.tick_count + } else { + e.duration + }; + if let Some(a) = periodic(e.id, t, e.amplifier) { + actions.push(a); + } + let answer = match e.id { + "bad_omen" => omen(e), + "raid_omen" if t == 1 => omen(e), + _ => OmenTick::Continue, + }; + match answer { + OmenTick::Continue => {} + OmenTick::Remove => { + self.list.remove(i); + continue; + } + OmenTick::Add(effect) => { + if let Some(existing) = self.list.iter_mut().find(|x| x.id == effect.id) { + existing.update(&effect); + self.list.remove(i); + continue; + } + self.list.push(effect); + added = true; + break; + } + } + let e = &mut self.list[i]; + e.tick_down(); + e.downgrade(); + if e.infinite() || e.duration > 0 { + i += 1; + } else { + self.list.remove(i); + } + } + (actions, added) + } /// `LivingEntity.tickEffects` (server part): actions to apply, in order. pub fn tick(&mut self) -> Vec { self.tick_count = self.tick_count.wrapping_add(1); @@ -325,6 +400,45 @@ impl StatusFlags { mod tests { use super::*; + #[test] + fn bad_omen_in_a_village_becomes_raid_omen_over_two_ticks() { + let mut fx = PlayerEffects::default(); + fx.add(EffectInstance::new("bad_omen", 100, 1)); + fx.add(EffectInstance::new("speed", 50, 0)); + let mut convert = |e: &EffectInstance| match e.id { + "bad_omen" => OmenTick::Add(EffectInstance::new("raid_omen", 600, e.amplifier)), + _ => OmenTick::Continue, + }; + // The first tick adds Raid Omen and stops there (the iterator's + // ConcurrentModificationException): Bad Omen and Speed stay as they were. + let (_, added) = fx.tick_with(&mut convert); + assert!(added); + assert_eq!(fx.get("bad_omen").unwrap().duration, 100); + assert_eq!(fx.get("speed").unwrap().duration, 50); + assert_eq!(fx.get("raid_omen").unwrap().duration, 600); + // The second refreshes Raid Omen and drops Bad Omen. + let (_, added) = fx.tick_with(&mut convert); + assert!(!added); + assert!(fx.get("bad_omen").is_none()); + assert_eq!(fx.get("speed").unwrap().duration, 49); + assert_eq!(fx.get("raid_omen").unwrap().amplifier, 1); + } + #[test] + fn raid_omen_acts_on_its_last_tick() { + let mut fx = PlayerEffects::default(); + fx.add(EffectInstance::new("raid_omen", 2, 0)); + let mut seen = Vec::new(); + let mut watch = |e: &EffectInstance| { + seen.push(e.duration); + OmenTick::Remove + }; + fx.tick_with(&mut watch); + assert!(fx.get("raid_omen").is_some()); + fx.tick_with(&mut watch); + assert!(fx.get("raid_omen").is_none()); + assert_eq!(seen, vec![1]); + } + #[test] fn update_keeps_stronger_and_hides_longer() { let mut fx = PlayerEffects::default(); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 21e3400cb..be9322718 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2703,7 +2703,6 @@ impl Game<'_> { self.screen = Screen::Dead; self.capture(false); } - self.tick_omens(); self.tick_effects(); self.tick_burning(); self.tick_using(); diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 7d07f148b..852984823 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -24,8 +24,8 @@ use horizon_world::registry::BlockStateId; use std::collections::HashMap; /// The game level as natural spawning reads it. -struct GameLevel<'g, 'a> { - game: &'g Game<'a>, +pub(super) struct GameLevel<'g, 'a> { + pub(super) game: &'g Game<'a>, w: MobWorld<'g>, /// Boxes of the mobs this pass created, not yet in the game's list. pending: std::cell::RefCell>, @@ -194,7 +194,7 @@ impl NaturalLevel for GameLevel<'_, '_> { } } impl<'a> Game<'a> { - fn natural_level(&self) -> GameLevel<'_, 'a> { + pub(super) fn natural_level(&self) -> GameLevel<'_, 'a> { GameLevel { game: self, w: self.mob_world_base(&[]), diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index f0c5f57b1..7c36ac494 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -286,7 +286,15 @@ impl Game<'_> { // LivingEntity.die → removeAllEffects. self.potions.effects.clear(); } - for action in self.potions.effects.tick() { + // The omens act from inside the effect tick (BadOmenMobEffect, + // RaidOmenMobEffect). + let mut effects = std::mem::take(&mut self.potions.effects); + let (actions, raid_omen_added) = effects.tick_with(&mut |e| self.omen_tick(e)); + self.potions.effects = effects; + if raid_omen_added { + self.raid_omen_added(); + } + for action in actions { self.apply_effect_action(action); } let modifiers = self.potions.effects.modifiers(); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 91c454ce8..8fda0e671 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -1,12 +1,20 @@ //! Pillager patrols (`PatrolSpawner`), the raid omen, and raids (`Raids`): -//! their waves, boss bar, victory and the raiders' bookkeeping. +//! their waves, boss bar, victory and the raiders' bookkeeping. The rules are +//! `horizon_client::patrol` and `horizon_client::raid`; this is the game's +//! side of them. use super::{Dim, Game}; use horizon_client::mobs::villager as mobs_villager; use horizon_client::{ - effects::EffectInstance, + effects::{EffectInstance, OmenTick}, hud::{HudBatch, rgba}, - mobs::{Mob, Species, data, raider}, - raid::{self, Action, BarName, RaidLevel, RaiderInfo, RaiderType, Raids, Spawn}, + mobs::{ + Mob, Species, raider, + spawn_rules::{self, SpawnLevel}, + spawn_selection::{Heightmap, NaturalLevel}, + spawning, + }, + patrol::{GameplayAttributes, Member, PatrolLevel, PatrolSpawner}, + raid::{self, Action, BarName, RaidLevel, RaidPlayer, RaiderInfo, RaiderType, Raids, Spawn}, }; use horizon_core::{geometry::Vec3, random::RandomSource}; use std::collections::{HashMap, HashSet}; @@ -14,12 +22,17 @@ use std::collections::{HashMap, HashSet}; /// Patrol and raid state owned by the game. #[derive(Default)] pub(super) struct Raiding { - /// `PatrolSpawner.nextTick`. - patrol_next_tick: i32, + patrol: PatrolSpawner, + /// The raids of the dimension the player is in, and that dimension. raids: Raids, - loaded: bool, - /// `ServerPlayer.raidOmenPosition`. + loaded: Option, + /// `ServerPlayer.raidOmenPosition` (`raid_omen_position`), read from the + /// player data on first use. omen_position: Option<[i32; 3]>, + omen_loaded: bool, + /// The last raider hurt each raid's bar has seen (`Raider.hurtServer`). + bar_hurts: HashMap, + attributes: Option>, /// Beds near each raid's centre, rescanned now and then (`HOME` points /// of interest for `RaiderMoveThroughVillageGoal`). homes: HashMap>)>, @@ -44,12 +57,11 @@ pub(super) fn sections_to_village(centers: &HashSet<(i32, i32, i32)>, at: (i32, .map_or(7, |d| d.min(7)) } -/// The level as a raid sees it, with this tick's village and raider data. +/// The level as a raid sees it, with this tick's village data. struct Lvl<'a, 'g> { game: &'a Game<'g>, difficulty: i32, centers: &'a HashSet<(i32, i32, i32)>, - raiders: &'a HashMap>, } impl RaidLevel for Lvl<'_, '_> { fn difficulty(&self) -> i32 { @@ -58,45 +70,125 @@ impl RaidLevel for Lvl<'_, '_> { fn has_chunk_at(&self, p: [i32; 3]) -> bool { self.game.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) } - fn is_village(&self, p: [i32; 3]) -> bool { - sections_to_village(self.centers, section(p)) <= 1 + fn has_chunks_at(&self, x0: i32, z0: i32, x1: i32, z1: i32) -> bool { + (x0 >> 4..=x1 >> 4) + .all(|cx| (z0 >> 4..=z1 >> 4).all(|cz| self.game.world.chunks.contains_key(&(cx, cz)))) } - fn village_sections_near(&self, p: [i32; 3]) -> Vec<[i32; 3]> { - let (sx, sy, sz) = section(p); - let mut out = Vec::new(); - for dx in -2..=2 { - for dy in -2..=2 { - for dz in -2..=2 { - let s = (sx + dx, sy + dy, sz + dz); - let center = [s.0 * 16 + 8, s.1 * 16 + 8, s.2 * 16 + 8]; - if self.is_village(center) { - out.push(center); - } - } - } - } - out - } - fn raiders(&self, raid: i32) -> Vec { - self.raiders.get(&raid).cloned().unwrap_or_default() + fn sections_to_village(&self, p: [i32; 3]) -> i32 { + sections_to_village(self.centers, section(p)) } fn surface_height(&self, x: i32, z: i32) -> i32 { self.game.surface_height(x, z) } - fn is_ticking(&self, p: [i32; 3]) -> bool { - [(-10, -10), (10, -10), (-10, 10), (10, 10)] - .iter() - .all(|(dx, dz)| self.has_chunk_at([p[0] + dx, p[1], p[2] + dz])) + fn is_position_entity_ticking(&self, p: [i32; 3]) -> bool { + self.has_chunk_at(p) } - fn can_spawn_at(&self, p: [i32; 3]) -> bool { - if !self.is_ticking(p) { - return false; - } + fn ravager_can_spawn(&self, [x, y, z]: [i32; 3]) -> bool { let g = self.game; let w = g.mob_world_base(&[]); - horizon_client::mobs::spawning::placement_ok(Species::Ravager, &w, p[0], p[1], p[2]) - || w.block_name(p[0], p[1] - 1, p[2]) == "minecraft:snow" - && g.res.facts.is_air(g.world.block(p[0], p[1], p[2])) + spawn_rules::is_spawn_position_ok(Species::Ravager, &w, x, y, z) + || w.block_name(x, y - 1, z) == "minecraft:snow" + && g.res.facts.is_air(g.world.block(x, y, z)) + } + fn player(&self) -> Option { + let p = self.game.player.as_ref()?; + Some(RaidPlayer { + position: [p.position.x, p.position.y, p.position.z], + block: block_of(p.position), + alive: !p.health.dead_or_dying(), + }) + } +} + +/// The game level as the patrol spawner reads it. +struct PatrolCx<'a, 'g, 'h> { + level: super::natural_spawning::GameLevel<'a, 'g>, + centers: HashSet<(i32, i32, i32)>, + can_spawn: &'h dyn Fn(&Game, [i32; 3]) -> bool, +} +impl SpawnLevel for PatrolCx<'_, '_, '_> { + fn state(&self, x: i32, y: i32, z: i32) -> horizon_world::registry::BlockStateId { + self.level.state(x, y, z) + } + fn facts(&self) -> &horizon_client::blocks::BlockFacts { + self.level.facts() + } + fn mob_data(&self) -> &horizon_client::mobs::data::MobData { + self.level.mob_data() + } + fn block_tag(&self, tag: &str, block: &str) -> bool { + self.level.block_tag(tag, block) + } + fn biome_tag(&self, tag: &str, x: i32, y: i32, z: i32) -> bool { + self.level.biome_tag(tag, x, y, z) + } + fn sky_light(&self, x: i32, y: i32, z: i32) -> i32 { + self.level.sky_light(x, y, z) + } + fn block_light(&self, x: i32, y: i32, z: i32) -> i32 { + self.level.block_light(x, y, z) + } + fn sky_darken(&self) -> i32 { + SpawnLevel::sky_darken(&self.level) + } + fn thundering(&self) -> bool { + self.level.thundering() + } + fn sea_level(&self) -> i32 { + self.level.sea_level() + } + fn world_surface(&self, x: i32, z: i32) -> i32 { + self.level.world_surface(x, z) + } + fn peaceful(&self) -> bool { + self.level.peaceful() + } + fn dimension(&self) -> spawn_rules::Dimension { + self.level.dimension() + } + fn surface_slime_chance(&self, x: i32, y: i32, z: i32) -> f32 { + self.level.surface_slime_chance(x, y, z) + } + fn world_seed(&self) -> i64 { + self.level.world_seed() + } + fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool { + self.level.player_near(x, y, z, distance) + } +} +impl PatrolLevel for PatrolCx<'_, '_, '_> { + fn spawn_patrols(&self) -> bool { + self.level.game.ui.rules.bool("spawn_patrols") + } + fn bright_outside(&self) -> bool { + self.level.game.dim == Dim::Overworld && self.level.game.sky_darken() < 4 + } + fn patrol_players(&self) -> Vec<([i32; 3], bool)> { + let g = self.level.game; + g.player + .as_ref() + .map(|p| (block_of(p.position), g.spectator())) + .into_iter() + .collect() + } + fn sections_to_village(&self, pos: [i32; 3]) -> i32 { + sections_to_village(&self.centers, section(pos)) + } + fn has_chunk(&self, cx: i32, cz: i32) -> bool { + self.level.game.world.chunks.contains_key(&(cx, cz)) + } + fn can_pillager_patrol_spawn(&self, pos: [i32; 3]) -> bool { + (self.can_spawn)(self.level.game, pos) + } + fn effective_difficulty(&self, pos: [i32; 3]) -> f32 { + self.level + .game + .local_difficulty([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]) + .effective + } + fn motion_blocking_no_leaves(&self, x: i32, z: i32) -> i32 { + self.level + .heightmap(Heightmap::MotionBlockingNoLeaves, x, z) } } @@ -150,24 +242,37 @@ impl Game<'_> { fn player_block(&self) -> Option<[i32; 3]> { self.player.as_ref().map(|p| block_of(p.position)) } - fn raids_path(&self) -> std::path::PathBuf { - self.world_root.join("data/minecraft/raids.dat") + /// `dimensions//data/minecraft/raids.dat`: each dimension + /// keeps its own raids. + fn raids_path(&self, dim: Dim) -> std::path::PathBuf { + horizon_client::save::dimension_dir(&self.world_root, dim.id()) + .join("data/minecraft/raids.dat") } + /// The raids of the player's dimension (the previous one saved first). fn load_raids(&mut self) { - if self.raiding.loaded { + if self.raiding.loaded == Some(self.dim) { return; } - self.raiding.loaded = true; - let seed = self.world.random.next_long(); - if let Some(tag) = horizon_client::save::read_dat(&self.raids_path()) - && let Some(data) = tag.get("data") - { - self.raiding.raids = Raids::from_nbt(data, seed); + if self.raiding.loaded.is_some() { + self.save_raids(); } + self.raiding.loaded = Some(self.dim); + self.raiding.bar_hurts.clear(); + self.raiding.homes.clear(); + let seed = self.world.random.next_long(); + self.raiding.raids = match horizon_client::save::read_dat(&self.raids_path(self.dim)) + .and_then(|tag| tag.get("data").cloned()) + { + Some(data) => Raids::from_nbt(&data, seed), + None => Raids::default(), + }; } - /// `Raids` as `data/minecraft/raids.dat`, when it changed. + /// `Raids` as its dimension's `raids.dat`, when it changed. pub(super) fn save_raids(&mut self) { - if !self.raiding.loaded || !self.raiding.raids.dirty || self.remote.is_some() { + let Some(dim) = self.raiding.loaded else { + return; + }; + if !self.raiding.raids.dirty || self.remote.is_some() { return; } let tag = horizon_world::nbt::Tag::compound([ @@ -177,74 +282,132 @@ impl Game<'_> { horizon_world::nbt::Tag::Int(horizon_world::DATA_VERSION), ), ]); - if horizon_client::save::write_dat(&self.raids_path(), tag).is_ok() { + if horizon_client::save::write_dat(&self.raids_path(dim), tag).is_ok() { self.raiding.raids.dirty = false; } + self.save_raid_omen_position(); + } + /// `ServerPlayer.raidOmenPosition` from the player data. + fn load_raid_omen_position(&mut self) { + if self.raiding.omen_loaded { + return; + } + self.raiding.omen_loaded = true; + self.raiding.omen_position = match self + .level + .player_extra + .as_ref() + .and_then(|p| p.get("raid_omen_position")) + { + Some(horizon_world::nbt::Tag::IntArray(v)) if v.len() == 3 => Some([v[0], v[1], v[2]]), + _ => None, + }; + } + /// Writes `raid_omen_position` into the player data being saved. + fn save_raid_omen_position(&mut self) { + if !self.raiding.omen_loaded { + return; + } + let extra = self + .level + .player_extra + .get_or_insert_with(|| horizon_world::nbt::Tag::Compound(Default::default())); + if let horizon_world::nbt::Tag::Compound(map) = extra { + match self.raiding.omen_position { + Some(p) => { + map.insert( + "raid_omen_position".into(), + horizon_world::nbt::Tag::IntArray(p.to_vec()), + ); + } + None => { + map.remove(&"raid_omen_position".into()); + } + } + } + } + fn gameplay_attributes(&mut self) -> std::sync::Arc { + if self.raiding.attributes.is_none() { + self.raiding.attributes = Some(std::sync::Arc::new(GameplayAttributes::load( + &self.options.resources, + ))); + } + self.raiding.attributes.clone().unwrap_or_default() + } + /// A boolean gameplay attribute at a position (dimension, biome, then + /// the timelines at the overworld clock). + fn gameplay_attribute(&mut self, key: &str, at: [i32; 3]) -> bool { + let attributes = self.gameplay_attributes(); + let biome = self + .world + .chunks + .get(&(at[0] >> 4, at[2] >> 4)) + .map(|c| { + self.res + .biomes + .get(c.biome(at[0], at[1], at[2])) + .name + .clone() + }) + .unwrap_or_default(); + attributes.value(key, self.dim.id(), &biome, self.world.day_time) } - /// `BadOmenMobEffect` and `RaidOmenMobEffect`, before the effects tick: - /// Bad Omen inside a village becomes Raid Omen, which starts or extends a - /// raid when it runs out. - pub(super) fn tick_omens(&mut self) { - if self.dim != Dim::Overworld || self.spectator() { - return; + /// `BadOmenMobEffect` and `RaidOmenMobEffect.applyEffectTick` for the + /// player's effect tick: Bad Omen inside a village becomes Raid Omen, + /// whose last tick starts or extends a raid where it began. + pub(super) fn omen_tick(&mut self, e: &EffectInstance) -> OmenTick { + if self.spectator() || self.player.is_none() { + return OmenTick::Continue; } let Some(pos) = self.player_block() else { - return; + return OmenTick::Continue; }; self.load_raids(); - if let Some(amp) = self.potions.effects.amplifier("bad_omen") - && self.difficulty_id() != 0 - && sections_to_village(&self.village_centers(), section(pos)) <= 1 - && self - .raiding - .raids - .nearby(pos) - .is_none_or(|(_, r)| r.omen_level < raid::MAX_OMEN_LEVEL) - { - self.potions.effects.list.retain(|e| e.id != "bad_omen"); - self.potions - .effects - .add(EffectInstance::new("raid_omen", 600, amp)); - self.raiding.omen_position = Some(pos); - let eye = self.eye_position().unwrap_or_default(); - self.audio - .play("minecraft:event.mob_effect.raid_omen", Some(eye), 1.0, 1.0); - } - let due = self - .potions - .effects - .get("raid_omen") - .filter(|e| e.duration == 1) - .map(|e| e.amplifier); - if let Some(amp) = due - && let Some(at) = self.raiding.omen_position.take() - { - self.create_or_extend_raid(at, Some(amp)); + self.load_raid_omen_position(); + match e.id { + "bad_omen" => { + if self.difficulty_id() != 0 + && sections_to_village(&self.village_centers(), section(pos)) <= 1 + && self + .raiding + .raids + .nearby(pos) + .is_none_or(|(_, r)| r.omen_level < raid::MAX_OMEN_LEVEL) + { + self.raiding.omen_position = Some(pos); + return OmenTick::Add(EffectInstance::new("raid_omen", 600, e.amplifier)); + } + OmenTick::Continue + } + "raid_omen" => match self.raiding.omen_position.take() { + Some(at) => { + self.create_or_extend_raid(at, Some(e.amplifier)); + OmenTick::Remove + } + None => OmenTick::Continue, + }, + _ => OmenTick::Continue, } } - /// `Raids.createOrExtendRaid`: the raid centres on the claimed village - /// points within 64 blocks. + /// The Raid Omen sound when the effect is first added. + pub(super) fn raid_omen_added(&mut self) { + let eye = self.eye_position().unwrap_or_default(); + self.audio + .play("minecraft:event.mob_effect.raid_omen", Some(eye), 1.0, 1.0); + } + /// `Raids.createOrExtendRaid`: not for spectators, with the `raids` rule + /// and where raids may start; the raid centres on the occupied village + /// points of interest within 64 blocks. fn create_or_extend_raid(&mut self, at: [i32; 3], amplifier: Option) -> Option { - if !self.ui.rules.bool("raids") || self.dim != Dim::Overworld { + if self.spectator() + || !self.ui.rules.bool("raids") + || !self.gameplay_attribute(horizon_client::patrol::CAN_START_RAID, at) + { return None; } - let near: Vec<[i32; 3]> = self - .village_pois() - .into_iter() - .filter(|p| (0..3).map(|i| f64::from(p[i] - at[i]).powi(2)).sum::() <= 4096.0) - .collect(); - let center = if near.is_empty() { - at - } else { - let n = near.len() as f64; - let mean = |i: usize| near.iter().map(|p| f64::from(p[i])).sum::() / n; - [ - mean(0).floor() as i32, - mean(1).floor() as i32, - mean(2).floor() as i32, - ] - }; + self.load_raids(); + let center = raid::raid_center(at, &self.village_pois()); let seed = self.world.random.next_long(); let difficulty = self.difficulty_id(); let (id, triggered) = self @@ -270,19 +433,19 @@ impl Game<'_> { let Some(id) = self.create_or_extend_raid(at, None) else { return false; }; - if let Some(r) = self.raiding.raids.map.get_mut(&id) { + if let Some(r) = self.raiding.raids.get_mut(id) { r.omen_level = omen_level; } self.raiding.raids.dirty = true; true } pub(super) fn raid_command_stop(&mut self, id: i32) { - if let Some(r) = self.raiding.raids.map.get_mut(&id) { + if let Some(r) = self.raiding.raids.get_mut(id) { r.stop(); } } pub(super) fn raid_set_omen(&mut self, id: i32, level: i32) -> i32 { - let Some(r) = self.raiding.raids.map.get_mut(&id) else { + let Some(r) = self.raiding.raids.get_mut(id) else { return 0; }; std::mem::replace(&mut r.omen_level, level) @@ -299,12 +462,8 @@ impl Game<'_> { let Some(r) = self.raiding.raids.get(id) else { return String::new(); }; - let members: Vec<&Mob> = self - .mobs - .iter() - .filter(|m| m.alive() && raider::state(m).is_some_and(|s| s.raid_id == Some(id))) - .collect(); - let health: f32 = members.iter().map(|m| m.health).sum(); + let members: Vec<&Mob> = self.raid_members(id).collect(); + let health: f32 = members.iter().fold(0.0, |a, m| a + m.health); format!( "Num groups spawned: {} Raid omen level: {} Num mobs: {} Raid health: {} / {}", r.groups_spawned, @@ -314,9 +473,39 @@ impl Game<'_> { r.total_health ) } + /// A raid's members (`groupRaiderMap`): the living raiders it counts. + fn raid_members(&self, id: i32) -> impl Iterator { + self.mobs.iter().filter(move |m| { + m.alive() && !m.removed && raider::state(m).is_some_and(|s| s.raid_id == Some(id)) + }) + } + /// `getHealthOfLivingRaiders`, leaving out one raider. + fn raid_living_health(&self, id: i32, except: Option) -> f32 { + self.raid_members(id) + .filter(|m| Some(m.id) != except) + .fold(0.0, |a, m| a + m.health) + } + /// The bar update the last hurt raider of a raid asked for + /// (`Raider.hurtServer` runs `updateBossbar` before the damage). + fn flush_raid_bar(&mut self, id: i32) { + let seen = self.raiding.bar_hurts.get(&id).copied().unwrap_or(0); + let last = self + .raid_members(id) + .filter_map(|m| raider::state(m).map(|s| (s.hurt_seq, m.id, s.pre_hurt_health))) + .filter(|h| h.0 > seen) + .max_by_key(|h| h.0); + let Some((seq, mob, before)) = last else { + return; + }; + let living = self.raid_living_health(id, Some(mob)) + before; + if let Some(r) = self.raiding.raids.get_mut(id) { + r.update_bossbar(living); + } + self.raiding.bar_hurts.insert(id, seq); + } - /// The living raiders by raid. - fn raider_infos(&self, centers: &HashSet<(i32, i32, i32)>) -> HashMap> { + /// The members of every raid, for `Raids.tick`. + fn raider_infos(&self) -> HashMap> { let mut out: HashMap> = HashMap::new(); for m in &self.mobs { if !m.alive() || m.removed { @@ -330,48 +519,91 @@ impl Game<'_> { wave: s.wave, health: m.health, position, - age: m.age, + tick_count: m.age as i32, no_action_time: m.ai.no_action_time, ticks_outside: s.ticks_outside_raid, - in_village: sections_to_village(centers, section(position)) <= 1, + removed: false, + other_dimension: false, + in_level: true, + patrol_leader: s.patrol_leader, }); } out } + /// Raiders loaded with a `RaidId` join their raid + /// (`readAdditionalSaveData`: `addWaveMob` without counting health, and + /// the wave's leader). + fn register_loaded_raiders(&mut self) { + let pending: Vec<(u32, i32, i32, f32, bool)> = self + .mobs + .iter() + .filter(|m| m.alive() && !m.removed) + .filter_map(|m| { + let s = raider::state(m)?; + (!s.registered).then_some(())?; + Some((m.id, s.raid_id?, s.wave, m.health, s.patrol_leader)) + }) + .collect(); + for (mob, id, wave, health, leader) in pending { + let living = self.raid_living_health(id, None); + let known = match self.raiding.raids.get_mut(id) { + Some(r) => { + r.add_wave_mob(health, false, living); + if leader { + r.set_leader(wave, mob); + } + self.raiding.raids.dirty = true; + true + } + None => false, + }; + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + let s = raider::state_mut(m); + s.registered = true; + if !known { + s.raid_id = None; + } + } + } + } /// `ServerLevel.tick` for the raids and their raiders. pub(super) fn tick_raids(&mut self) { - if self.remote.is_some() || self.dim != Dim::Overworld { + if self.remote.is_some() { return; } self.load_raids(); + self.register_loaded_raiders(); + for id in self.raiding.raids.ids() { + self.flush_raid_bar(id); + } let centers = self.village_centers(); - let infos = self.raider_infos(¢ers); + let infos = self.raider_infos(); let mut raids = std::mem::take(&mut self.raiding.raids); let actions = { let lvl = Lvl { game: self, difficulty: self.difficulty_id(), centers: ¢ers, - raiders: &infos, }; - raids.tick(&lvl, self.ui.rules.bool("raids"), self.player_block()) + let members = |id: i32| infos.get(&id).cloned().unwrap_or_default(); + raids.tick(&lvl, self.ui.rules.bool("raids"), &members) }; self.raiding.raids = raids; for (id, action) in actions { self.apply_raid_action(id, action); } self.sync_raiders(¢ers); + let infos = self.raider_infos(); self.sync_villager_raids(&infos); } fn apply_raid_action(&mut self, id: i32, action: Action) { match action { Action::Spawn { pos, wave, spawns } => self.spawn_wave(id, pos, wave, &spawns), - Action::Horn { pos } => self.raid_horn(id, pos), + Action::Horn { pos, .. } => self.raid_horn(id, pos), Action::Remove { id: mob } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { let s = raider::state_mut(m); s.raid_id = None; - s.ticks_outside_raid = 0; s.active_raid = false; } } @@ -403,14 +635,14 @@ impl Game<'_> { let (rx, rz) = (f64::from(pos[0]) + 0.5, f64::from(pos[2]) + 0.5); let distance = ((rx - p.x).powi(2) + (rz - p.z).powi(2)).sqrt(); if distance <= 64.0 || in_raid { - let k = 13.0 / distance.max(1e-4); + let k = 13.0 / distance; let at = [p.x + k * (rx - p.x), p.y, p.z + k * (rz - p.z)]; self.audio - .play("minecraft:event.raid.horn", Some(at), 1.0, 1.0); + .play("minecraft:event.raid.horn", Some(at), 64.0, 1.0); } } - /// `Raid.spawnGroup`: a wave of raiders around `pos`, ravagers carrying - /// their riders. + /// `Raid.spawnGroup`: a wave of raiders at `pos`, the leader wearing the + /// banner, ravagers carrying their riders. fn spawn_wave(&mut self, raid_id: i32, pos: [i32; 3], wave: i32, spawns: &[Spawn]) { let odds = self .raiding @@ -421,6 +653,11 @@ impl Game<'_> { let Some(id) = self.spawn_raider(sp.kind, pos, raid_id, wave, sp.leader, odds) else { continue; }; + if sp.leader + && let Some(r) = self.raiding.raids.get_mut(raid_id) + { + r.set_leader(wave, id); + } if let Some(kind) = sp.rider && let Some(rider) = self.spawn_raider(kind, pos, raid_id, wave, false, odds) { @@ -428,7 +665,8 @@ impl Game<'_> { } } } - /// `Raid.joinRaid` for a new raider, with `applyRaidBuffs`. + /// `Raid.joinRaid` for a new raider: placed at the block's centre one + /// above, finalized for an event, its raid buffs applied. fn spawn_raider( &mut self, kind: RaiderType, @@ -443,22 +681,53 @@ impl Game<'_> { f64::from(pos[1]) + 1.0, f64::from(pos[2]) + 0.5, ]; - let id = self.spawn_mob_for(kind.entity(), at, false, true)?; + let id = self.spawn_event_mob(kind.entity(), at, leader, raider::Reason::Event)?; let m = self.mobs.iter_mut().find(|m| m.id == id)?; - if leader { - raider::set_patrol_leader(m, true); - } - raider::finalize(m, raider::Reason::Event); let s = raider::state_mut(m); s.raid_id = Some(raid_id); s.wave = wave; s.can_join_raid = true; s.ticks_outside_raid = 0; s.active_raid = true; + s.registered = true; m.on_ground = true; self.apply_raid_buffs(id, kind, wave, odds); Some(id) } + /// `EntityType.create` then `finalizeSpawn` for a patrol or a raid: the + /// mob keeps the default rotation; a leader is set before finalizing so + /// it wears the banner. + fn spawn_event_mob( + &mut self, + kind: &str, + at: [f64; 3], + leader: bool, + reason: raider::Reason, + ) -> Option { + let t = self.res.mob_types.get(kind).cloned()?; + self.next_entity += 1; + let mut mob = Mob::new(self.next_entity, t, Vec3::new(at[0], at[1], at[2]), 0.0); + if leader { + raider::set_patrol_leader(&mut mob, true); + if reason == raider::Reason::Patrol { + // findPatrolTarget runs before the mob is placed: the target + // is around the world origin. + raider::find_patrol_target_from(&mut mob, [0, 0, 0]); + } + } + let facts = self.biome_facts( + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ); + let difficulty = self.local_difficulty(at); + spawning::finalize(&mut mob, &facts, &difficulty); + raider::finalize(&mut mob, reason); + let id = mob.id; + self.mobs.push(mob); + self.enchant_spawn_equipment(id); + Some(id) + } /// Per-tick raid bookkeeping of every raider (and the ravagers they /// ride): the raid's state for the goals, joining and recruiting, @@ -500,7 +769,9 @@ impl Game<'_> { .map(|(i, e)| (i, e.position)) .collect(); let mut taken: Vec = Vec::new(); - let mut recruit: Vec<(i32, i32, Vec3)> = Vec::new(); + let mut recruit: Vec<(i32, Vec3)> = Vec::new(); + let mut joins: Vec<(u32, i32, f32)> = Vec::new(); + let mut new_leaders: Vec<(i32, i32, u32)> = Vec::new(); let homes = self.raid_homes(); for m in &mut self.mobs { let species = m.species(); @@ -556,15 +827,9 @@ impl Game<'_> { && s.can_join_raid && now % 20 == 0 && m.ai.no_action_time <= 2400 - && let Some((id, r)) = raids.nearby(block) + && let Some((id, _)) = raids.nearby(block) { - let wave = r.groups_spawned; - s.raid_id = Some(id); - s.wave = wave; - s.ticks_outside_raid = 0; - if let Some(r) = raids.map.get_mut(&id) { - r.total_health += health; - } + joins.push((m.id, id, health)); } // PathfindToRaidGoal.recruitNearby. if s.active_raid @@ -573,7 +838,7 @@ impl Game<'_> { && age % 20 == 0 && let Some(id) = s.raid_id { - recruit.push((id, s.wave, position)); + recruit.push((id, position)); } // ObtainRaidLeaderBannerGoal. s.banner_at = None; @@ -582,6 +847,7 @@ impl Game<'_> { && !s.raid_over && raider::can_be_leader(species) && m.extra.head.as_deref() != Some(raider::BANNER) + && raids.get(id).is_some_and(|r| r.leader(s.wave).is_none()) && !leaders.contains(&(id, s.wave)) { let near = banners @@ -602,6 +868,7 @@ impl Game<'_> { // pickUpItem: the banner becomes the wave's leader. taken.push(*i); leaders.insert((id, s.wave)); + new_leaders.push((id, s.wave, m.id)); s.banner_at = None; s.patrol_leader = true; s.patrolling = true; @@ -614,36 +881,55 @@ impl Game<'_> { for i in taken.into_iter().rev() { self.dropped.remove(i); } - // Recruiting: raiders nearby that are in no raid join this one. - for (id, wave, at) in recruit { - let now_nearby: Vec = positions - .iter() - .filter(|(_, p, active)| { - !active - && (p.x - at.x).abs() <= 16.0 - && (p.y - at.y).abs() <= 16.0 - && (p.z - at.z).abs() <= 16.0 - }) - .map(|(i, _, _)| *i) - .collect(); - for mid in now_nearby { - let Some(m) = self.mobs.iter_mut().find(|m| m.id == mid) else { - continue; - }; - let health = m.health; - let idle = m.ai.no_action_time; - let s = raider::state_mut(m); - if s.raid_id.is_none() && s.can_join_raid && idle <= 2400 { - s.raid_id = Some(id); - s.wave = wave; - s.ticks_outside_raid = 0; - s.active_raid = true; - if let Some(r) = self.raiding.raids.map.get_mut(&id) { - r.total_health += health; - } + for (id, wave, mob) in new_leaders { + if let Some(r) = self.raiding.raids.get_mut(id) { + r.set_leader(wave, mob); + } + } + // PathfindToRaidGoal.recruitNearby: raiders nearby in no active raid + // join this one at its current wave. + for (id, at) in recruit { + for (mid, p, active) in &positions { + if !active + && (p.x - at.x).abs() <= 16.0 + && (p.y - at.y).abs() <= 16.0 + && (p.z - at.z).abs() <= 16.0 + && let Some(m) = self.mobs.iter().find(|m| m.id == *mid) + && raider::state(m).is_some_and(|s| s.can_join_raid && s.raid_id != Some(id)) + && m.alive() + && m.ai.no_action_time <= 2400 + { + joins.push((*mid, id, m.health)); } } } + for (mob, id, health) in joins { + self.join_raid(mob, id, health); + } + } + /// `Raid.joinRaid` for a raider already in the world: it counts toward + /// the bar and takes the raid's current wave. + fn join_raid(&mut self, mob: u32, id: i32, health: f32) { + let Some(wave) = self.raiding.raids.get(id).map(|r| r.groups_spawned) else { + return; + }; + let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) else { + return; + }; + let s = raider::state_mut(m); + if s.raid_id == Some(id) { + return; + } + s.raid_id = Some(id); + s.wave = wave; + s.can_join_raid = true; + s.ticks_outside_raid = 0; + s.registered = true; + let living = self.raid_living_health(id, None); + if let Some(r) = self.raiding.raids.get_mut(id) { + r.add_wave_mob(health, true, living); + } + self.raiding.raids.dirty = true; } /// Beds within 64 blocks of each raid's centre (the `HOME` points of /// interest), rescanned every five seconds. @@ -700,16 +986,32 @@ impl Game<'_> { .map(|(id, (_, v))| (*id, v.clone())) .collect() } - /// `Raider.die`: the killing player becomes a hero of the village. + /// `Raider.die`: the wave loses its leader, the killing player becomes + /// a hero of the village, and the raider leaves the raid (its health + /// stays in the bar's total). pub(super) fn raider_died(&mut self, m: &Mob, by_player: bool) { - let Some(id) = raider::state(m).and_then(|s| s.raid_id) else { + let Some(s) = raider::state(m) else { return; }; - if by_player - && let Some(uuid) = self.level.player_uuid - && let Some(r) = self.raiding.raids.map.get_mut(&id) - { - r.add_hero(uuid); + let Some(id) = s.raid_id else { + return; + }; + let (leader, wave) = (s.patrol_leader, s.wave); + self.flush_raid_bar(id); + let living = self.raid_living_health(id, Some(m.id)); + let uuid = self.level.player_uuid; + if let Some(r) = self.raiding.raids.get_mut(id) { + if leader { + r.remove_leader(wave); + } + if by_player && let Some(uuid) = uuid { + r.add_hero(uuid); + } + r.remove_from_raid(m.health, false, living); + self.raiding.raids.dirty = true; + } + if let Some(dead) = self.mobs.iter_mut().find(|x| x.id == m.id) { + raider::state_mut(dead).raid_id = None; } } @@ -849,74 +1151,67 @@ impl Game<'_> { } out } - /// `ServerLevel.isCloseToVillage`. - pub(super) fn close_to_village(&self, at: [i32; 3], distance: i32) -> bool { - distance <= 6 && sections_to_village(&self.village_centers(), section(at)) <= distance - } - /// `PatrolSpawner.tick`: every 10 minutes, a fifth of the time in - /// daylight, a patrol of pillagers spawns 24 to 48 blocks from a player - /// who is not near a village. + /// `PatrolSpawner.tick` (`horizon_client::patrol`) on the game level: + /// the pillagers it accepts are created after the pass, finalized for a + /// patrol. pub(super) fn tick_patrol_spawner(&mut self) { - if self.dim != Dim::Overworld - || self.world.health_rules.difficulty == horizon_world::food::Difficulty::Peaceful - || !self.ui.rules.bool("spawn_monsters") - || !self.ui.rules.bool("spawn_patrols") - { + if self.dim != Dim::Overworld { return; } - self.raiding.patrol_next_tick -= 1; - if self.raiding.patrol_next_tick > 0 { - return; - } - let delay = self.world.random.next_int_bound(1200).unwrap_or(0); - self.raiding.patrol_next_tick += 12000 + delay; - let bright = self.sky_darken() < 4; - let r = &mut self.world.random; - if !bright || r.next_int_bound(5).unwrap_or(1) != 0 { - return; - } - // One player: `players.get(random.nextInt(1))`. - let _ = r.next_int_bound(1); - let Some(p) = self.player.as_ref().map(|p| p.position) else { - return; - }; - if self.spectator() { - return; - } - let block = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; - if self.close_to_village(block, 2) { - return; - } - let r = &mut self.world.random; - let x = (24 + r.next_int_bound(24).unwrap_or(0)) * if r.next_boolean() { -1 } else { 1 }; - let z = (24 + r.next_int_bound(24).unwrap_or(0)) * if r.next_boolean() { -1 } else { 1 }; - let mut at = [block[0] + x, block[1], block[2] + z]; - // hasChunksAt(±10). - for (dx, dz) in [(-10, -10), (10, -10), (-10, 10), (10, 10)] { - if !self + let attributes = self.gameplay_attributes(); + let biome_ok = |game: &Game, at: [i32; 3]| { + let biome = game .world .chunks - .contains_key(&((at[0] + dx) >> 4, (at[2] + dz) >> 4)) - { - return; - } + .get(&(at[0] >> 4, at[2] >> 4)) + .map(|c| { + game.res + .biomes + .get(c.biome(at[0], at[1], at[2])) + .name + .clone() + }) + .unwrap_or_default(); + attributes.value( + horizon_client::patrol::CAN_PILLAGER_PATROL_SPAWN, + game.dim.id(), + &biome, + game.world.day_time, + ) + }; + let enemies = self.ui.rules.bool("spawn_mobs") && self.ui.rules.bool("spawn_monsters"); + let mut random = std::mem::replace( + &mut self.world.random, + horizon_core::random::LegacyRandom::new(0), + ); + let mut members: Vec = Vec::new(); + let mut spawner = std::mem::take(&mut self.raiding.patrol); + { + let level = PatrolCx { + level: self.natural_level(), + centers: self.village_centers(), + can_spawn: &biome_ok, + }; + let mut spawn = + |l: &PatrolCx, m: Member, _: &mut horizon_core::random::LegacyRandom| { + // EntityType.create makes no monsters in peaceful. + if l.level.game.difficulty_id() == 0 { + return false; + } + members.push(m); + true + }; + spawner.tick(&level, enemies, &mut random, &mut spawn); } - // The `can_pillager_patrol_spawn` attribute: the early game timeline - // (first five days) and the mushroom fields forbid it. - let biome = self.biome_facts(at[0], at[1], at[2]); - if self.world.day_time < 120_000 || biome.mushroom { - return; - } - let f = self.local_difficulty([f64::from(at[0]), f64::from(at[1]), f64::from(at[2])]); - let group = f.effective.ceil() as i32 + 1; - for i in 0..group { - at[1] = self.motion_top(at[0], at[2]); - if !self.spawn_patrol_member(at, i == 0) && i == 0 { - break; - } - let r = &mut self.world.random; - at[0] += r.next_int_bound(5).unwrap_or(0) - r.next_int_bound(5).unwrap_or(0); - at[2] += r.next_int_bound(5).unwrap_or(0) - r.next_int_bound(5).unwrap_or(0); + self.raiding.patrol = spawner; + self.world.random = random; + for m in members { + let at = [ + f64::from(m.pos[0]), + f64::from(m.pos[1]), + f64::from(m.pos[2]), + ]; + self.spawn_event_mob("minecraft:pillager", at, m.leader, raider::Reason::Patrol); } } /// A raider's ominous banner (drop chance 2.0: always dropped) and a @@ -932,8 +1227,14 @@ impl Game<'_> { let mut effect = horizon_client::effects::EffectInstance::new("bad_omen", 120_000, i32::from(amplifier)); effect.visible = false; + let new = self.potions.effects.get("bad_omen").is_none(); self.potions.effects.add(effect); let eye = self.eye_position().unwrap_or_default(); + // MobEffect.onEffectAdded: Bad Omen's sound when it is new. + if new { + self.audio + .play("minecraft:event.mob_effect.bad_omen", Some(eye), 1.0, 1.0); + } self.audio .play("minecraft:item.ominous_bottle.dispose", Some(eye), 1.0, 1.0); if !self.creative @@ -945,33 +1246,6 @@ impl Game<'_> { } } } - /// `PatrolSpawner.spawnPatrolMember`: a pillager on a valid empty block - /// that may spawn there; the leader picks a target and wears the banner. - fn spawn_patrol_member(&mut self, at: [i32; 3], leader: bool) -> bool { - let state = self.world.block(at[0], at[1], at[2]); - let below = self.world.block(at[0], at[1] - 1, at[2]); - let empty = self.res.mob_data.state(state).flags & data::VALID_EMPTY_SPAWN != 0; - let valid = self.res.mob_data.state(below).flags & data::VALID_SPAWN != 0; - // PatrollingMonster.checkPatrollingMonsterSpawnRules. - if !empty || !valid || self.world.light(at[0], at[1], at[2]) & 15 > 8 { - return false; - } - let pos = [f64::from(at[0]), f64::from(at[1]), f64::from(at[2])]; - let Some(id) = self.spawn_mob_for("minecraft:pillager", pos, false, true) else { - return false; - }; - let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else { - return false; - }; - if leader { - raider::set_patrol_leader(m, true); - // findPatrolTarget runs before the mob is placed, so the target - // is around the world origin. - raider::find_patrol_target_from(m, [0, 0, 0]); - } - raider::finalize(m, raider::Reason::Patrol); - true - } } #[cfg(test)] diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 53685eeb2..6d5f036b0 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -74,6 +74,7 @@ pub mod options_fixes; pub mod options_ui; pub mod packs; pub mod particles; +pub mod patrol; pub mod pose; pub mod projectiles; pub mod raid; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index e6dd71e45..962e0f8cf 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1062,6 +1062,7 @@ impl Mob { .fold((0.0, 0.0), |(a, t), (x, y)| (a + x, t + y)) } pub fn damage(&mut self, amount: f32, source: Damage) -> bool { + raider::note_hurt(self); if !self.alive() || self.removed || self.invulnerable_flag { return false; } diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index e75464fc4..ba682af58 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -42,6 +42,31 @@ pub struct State { pub homes: Option>>, /// A ravager carrying a raider, set every tick from `Extra::rider`. pub rider: bool, + /// The raid counts this raider (`addWaveMob` ran since it joined or was + /// loaded with its `RaidId`). + pub registered: bool, + /// `Raider.hurtServer` updates the raid's bar before the damage lands: + /// when it was last hurt (see [`next_hurt_seq`]) and its health then. + pub hurt_seq: u64, + pub pre_hurt_health: f32, +} + +static HURT_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +/// A counter ordering the hurts of raiders across the game. +pub fn next_hurt_seq() -> u64 { + HURT_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1 +} +/// `Raider.hurtServer`: a raider in an active raid asks its raid to update +/// the bar with the health it has before this hit. +pub fn note_hurt(m: &mut Mob) { + let health = m.health; + if let Some(s) = m.extra.raider.as_deref_mut() + && s.raid_id.is_some() + && s.active_raid + { + s.hurt_seq = next_hurt_seq(); + s.pre_hurt_health = health; + } } impl State { /// A ravager carrying a raider (`hasControllingPassenger`). diff --git a/crates/horizon-client/src/patrol.rs b/crates/horizon-client/src/patrol.rs new file mode 100644 index 000000000..59c7539d9 --- /dev/null +++ b/crates/horizon-client/src/patrol.rs @@ -0,0 +1,318 @@ +//! `PatrolSpawner`: every ten to eleven minutes of daylight, one time in five, +//! a pillager patrol gathers 24 to 47 blocks from a random player who is not +//! near a village. The level is read through [`PatrolLevel`] and the pillagers +//! are made by the caller, so the game and the differential test +//! (`tools/test_raid_parity.py`) run the same decisions and random draws. +use crate::mobs::{ + Species, + spawn_rules::{self, Reason, SpawnLevel}, +}; +use horizon_core::random::RandomSource; + +/// What the patrol spawner reads from the level. +pub trait PatrolLevel: SpawnLevel { + /// The `spawn_patrols` game rule. + fn spawn_patrols(&self) -> bool; + /// `Level.isBrightOutside`: no fixed time and a sky darkening below 4. + fn bright_outside(&self) -> bool; + /// The level's players, in `level.players()` order: block position and + /// whether the player is a spectator. + fn patrol_players(&self) -> Vec<([i32; 3], bool)>; + /// `ServerLevel.sectionsToVillage` (`PoiManager`): 0 to 7. + fn sections_to_village(&self, pos: [i32; 3]) -> i32; + /// The chunk at chunk coordinates is loaded (`hasChunk`). + fn has_chunk(&self, cx: i32, cz: i32) -> bool; + /// The `gameplay/can_pillager_patrol_spawn` environment attribute. + fn can_pillager_patrol_spawn(&self, pos: [i32; 3]) -> bool; + /// `getCurrentDifficultyAt(pos).getEffectiveDifficulty()`. + fn effective_difficulty(&self, pos: [i32; 3]) -> f32; + /// `Heightmap.Types.MOTION_BLOCKING_NO_LEAVES` height of a column. + fn motion_blocking_no_leaves(&self, x: i32, z: i32) -> i32; +} + +/// `ServerLevel.isCloseToVillage`. +pub fn close_to_village(l: &L, pos: [i32; 3], sections: i32) -> bool { + sections <= 6 && l.sections_to_village(pos) <= sections +} + +/// `Level.hasChunksAt(x0, z0, x1, z1)`. +pub fn has_chunks_at(l: &L, x0: i32, z0: i32, x1: i32, z1: i32) -> bool { + (x0 >> 4..=x1 >> 4).all(|cx| (z0 >> 4..=z1 >> 4).all(|cz| l.has_chunk(cx, cz))) +} + +/// A pillager the spawner asks for: where, and whether it leads the patrol. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Member { + pub pos: [i32; 3], + pub leader: bool, +} + +/// `PatrolSpawner` (its countdown lives in memory: a fresh level tries at once). +#[derive(Clone, Debug, Default)] +pub struct PatrolSpawner { + pub next_tick: i32, +} + +impl PatrolSpawner { + /// `PatrolSpawner.tick`. `spawn_enemies` is the chunk source's flag + /// (`spawn_mobs` and `spawn_monsters`); `random` is the level random. + /// `spawn` creates, finalizes and adds a pillager at a position that + /// passed the spawn checks (`EntityType.create` succeeding), and says + /// whether it did. + pub fn tick( + &mut self, + level: &L, + spawn_enemies: bool, + random: &mut R, + spawn: &mut dyn FnMut(&L, Member, &mut R) -> bool, + ) { + if !spawn_enemies || !level.spawn_patrols() { + return; + } + self.next_tick -= 1; + if self.next_tick > 0 { + return; + } + self.next_tick += 12000 + random.next_int_bound(1200).unwrap_or(0); + if !level.bright_outside() || random.next_int_bound(5).unwrap_or(1) != 0 { + return; + } + let players = level.patrol_players(); + if players.is_empty() { + return; + } + let (player, spectator) = + players[random.next_int_bound(players.len() as i32).unwrap_or(0) as usize]; + if spectator || close_to_village(level, player, 2) { + return; + } + let x = (24 + random.next_int_bound(24).unwrap_or(0)) + * if random.next_boolean() { -1 } else { 1 }; + let z = (24 + random.next_int_bound(24).unwrap_or(0)) + * if random.next_boolean() { -1 } else { 1 }; + let mut pos = [player[0] + x, player[1], player[2] + z]; + if !has_chunks_at(level, pos[0] - 10, pos[2] - 10, pos[0] + 10, pos[2] + 10) + || !level.can_pillager_patrol_spawn(pos) + { + return; + } + let group = level.effective_difficulty(pos).ceil() as i32 + 1; + for i in 0..group { + pos[1] = level.motion_blocking_no_leaves(pos[0], pos[2]); + let leader = i == 0; + if !spawn_member(level, pos, leader, random, spawn) && leader { + break; + } + pos[0] += random.next_int_bound(5).unwrap_or(0) - random.next_int_bound(5).unwrap_or(0); + pos[2] += random.next_int_bound(5).unwrap_or(0) - random.next_int_bound(5).unwrap_or(0); + } + } +} + +/// `PatrolSpawner.spawnPatrolMember`: an empty spawn block for a pillager +/// whose `checkPatrollingMonsterSpawnRules` pass. +fn spawn_member( + level: &L, + pos: [i32; 3], + leader: bool, + random: &mut R, + spawn: &mut dyn FnMut(&L, Member, &mut R) -> bool, +) -> bool { + let [x, y, z] = pos; + if !spawn_rules::is_valid_empty_spawn(Species::Pillager, level, x, y, z) { + return false; + } + if !spawn_rules::check_spawn_rules(Species::Pillager, level, Reason::Patrol, random, x, y, z) { + return false; + } + spawn(level, Member { pos, leader }, random) +} + +/// `PatrollingMonster.findPatrolTarget` from a block position. +pub fn patrol_target(at: [i32; 3], random: &mut impl RandomSource) -> [i32; 3] { + let dx = -500 + random.next_int_bound(1000).unwrap_or(0); + let dz = -500 + random.next_int_bound(1000).unwrap_or(0); + [at[0] + dx, at[1], at[2] + dz] +} + +/// The boolean gameplay attributes patrols and raids read +/// (`gameplay/can_pillager_patrol_spawn`, `gameplay/can_start_raid`): the +/// dimension's value, the biome's, then the dimension's timelines (the early +/// game timeline forbids patrols for the first 120,000 ticks of the +/// overworld clock). +#[derive(Clone, Debug, Default)] +pub struct GameplayAttributes { + /// attribute -> dimension type -> value. + dimensions: std::collections::HashMap>, + /// attribute -> biome -> value. + biomes: std::collections::HashMap>, + /// attribute -> dimension type -> boolean tracks (keyframes, modifier). + tracks: std::collections::HashMap>>, +} +#[derive(Clone, Debug)] +struct BoolTrack { + keyframes: Vec<(i64, bool)>, + period: Option, + modifier: String, +} +impl BoolTrack { + /// `KeyframeTrackSampler.sample` for a value that is not interpolated. + fn sample(&self, ticks: i64) -> bool { + let t = match self.period { + Some(p) if p > 0 => ticks.rem_euclid(p), + _ => ticks, + }; + let mut value = self.keyframes[0].1; + for (at, v) in &self.keyframes { + if t >= *at { + value = *v; + } + } + value + } + fn apply(&self, base: bool, ticks: i64) -> bool { + let arg = self.sample(ticks); + match self.modifier.as_str() { + "and" => base && arg, + "or" => base || arg, + "xor" => base ^ arg, + "nand" => !(base && arg), + "nor" => !(base || arg), + "xnor" => base == arg, + _ => arg, + } + } +} +pub const CAN_PILLAGER_PATROL_SPAWN: &str = "minecraft:gameplay/can_pillager_patrol_spawn"; +pub const CAN_START_RAID: &str = "minecraft:gameplay/can_start_raid"; +impl GameplayAttributes { + /// Reads the dimension types, biomes and timelines under `root/data`. + pub fn load(root: &std::path::Path) -> Self { + use serde_json::Value; + let data = root.join("data/minecraft"); + let read = |p: std::path::PathBuf| -> Option { + serde_json::from_slice(&std::fs::read(p).ok()?).ok() + }; + let list = |dir: &str| -> Vec<(String, Value)> { + let mut out = Vec::new(); + if let Ok(entries) = std::fs::read_dir(data.join(dir)) { + for e in entries.flatten() { + let path = e.path(); + if let (Some(stem), Some(v)) = ( + path.file_stem().and_then(|s| s.to_str()).map(str::to_owned), + read(path.clone()), + ) { + out.push((format!("minecraft:{stem}"), v)); + } + } + } + out + }; + let keys = [CAN_PILLAGER_PATROL_SPAWN, CAN_START_RAID]; + let mut out = Self::default(); + let timelines: std::collections::HashMap = + list("timeline").into_iter().collect(); + // Tag values with nested tags resolved. + fn tag(data: &std::path::Path, name: &str, out: &mut Vec) { + let file = data.join(format!( + "tags/timeline/{}.json", + name.trim_start_matches('#') + .trim_start_matches("minecraft:") + )); + let Some(v) = std::fs::read(file) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + else { + return; + }; + for item in v["values"].as_array().into_iter().flatten() { + let s = item.as_str().or_else(|| item["id"].as_str()).unwrap_or(""); + if s.starts_with('#') { + tag(data, s, out); + } else if !s.is_empty() { + out.push(s.to_owned()); + } + } + } + for (dim, v) in list("dimension_type") { + for key in keys { + if let Some(b) = v["attributes"][key].as_bool() { + out.dimensions + .entry(key.into()) + .or_default() + .insert(dim.clone(), b); + } + } + let mut names = Vec::new(); + match &v["timelines"] { + Value::String(s) if s.starts_with('#') => tag(&data, s, &mut names), + Value::String(s) => names.push(s.clone()), + Value::Array(a) => { + names.extend(a.iter().filter_map(|x| x.as_str()).map(str::to_owned)) + } + _ => {} + } + for name in names { + let Some(t) = timelines.get(&name) else { + continue; + }; + for key in keys { + let track = &t["tracks"][key]; + let Some(frames) = track["keyframes"].as_array() else { + continue; + }; + let keyframes: Vec<(i64, bool)> = frames + .iter() + .filter_map(|f| Some((f["ticks"].as_i64()?, f["value"].as_bool()?))) + .collect(); + if keyframes.is_empty() { + continue; + } + out.tracks + .entry(key.into()) + .or_default() + .entry(dim.clone()) + .or_default() + .push(BoolTrack { + keyframes, + period: t["period_ticks"].as_i64(), + modifier: track["modifier"].as_str().unwrap_or("override").to_owned(), + }); + } + } + } + for (biome, v) in list("worldgen/biome") { + for key in keys { + if let Some(b) = v["attributes"][key].as_bool() { + out.biomes + .entry(key.into()) + .or_default() + .insert(biome.clone(), b); + } + } + } + out + } + /// The attribute in a dimension type and biome at an overworld clock time. + pub fn value(&self, key: &str, dimension: &str, biome: &str, clock: i64) -> bool { + let mut v = self + .dimensions + .get(key) + .and_then(|m| m.get(dimension)) + .copied() + .unwrap_or(true); + if let Some(b) = self.biomes.get(key).and_then(|m| m.get(biome)) { + v = *b; + } + for t in self + .tracks + .get(key) + .and_then(|m| m.get(dimension)) + .into_iter() + .flatten() + { + v = t.apply(v, clock); + } + v + } +} diff --git a/crates/horizon-client/src/raid.rs b/crates/horizon-client/src/raid.rs index a3be4d191..4b1185970 100644 --- a/crates/horizon-client/src/raid.rs +++ b/crates/horizon-client/src/raid.rs @@ -1,9 +1,17 @@ -//! Raids (`Raid` and `Raids`): the raid omen that starts one, the waves of -//! raiders each difficulty sends, the boss bar, victory and loss, and -//! `data/minecraft/raids.dat`. The world is reached through [`RaidLevel`] and -//! the results come back as [`Action`]s, so the rules can be tested alone. -use horizon_core::random::{LegacyRandom, RandomSource}; -use horizon_world::nbt::Tag; +//! Raids (`Raid` and `Raids`): the waves of raiders each difficulty sends, +//! where they gather around the village, the boss bar, victory, loss and the +//! celebration, the raid omen a player brings, and the per-dimension +//! `data/minecraft/raids.dat` saved data with vanilla's codec rules. +//! +//! The raid's members live in the game (each raider knows its raid and +//! wave); a raid reads them and the world through [`RaidLevel`] and asks the +//! game for its side effects with [`Action`]s, so the game and the +//! differential test (`tools/test_raid_parity.py`) run the same rules. +use horizon_core::{ + geometry::trig, + random::{LegacyRandom, RandomSource}, +}; +use horizon_world::nbt::{JavaString, Tag}; use std::collections::BTreeMap; pub const MAX_OMEN_LEVEL: i32 = 5; @@ -12,6 +20,8 @@ const TIMEOUT: i64 = 48_000; const PRE_RAID_TICKS: i32 = 300; const POST_RAID_LIMIT: i32 = 40; const CELEBRATION_TICKS: i32 = 600; +const MAX_NO_ACTION_TIME: i32 = 2400; +const OUTSIDE_RAID_BOUNDS_TIMEOUT: i32 = 30; /// `Raids.getNearbyRaid(pos, 9216)`: within 96 blocks. pub const VALID_RAID_RADIUS_SQR: f64 = 9216.0; /// `RAID_REMOVAL_THRESHOLD_SQR`: a raider this far from the centre leaves. @@ -19,6 +29,29 @@ const REMOVAL_THRESHOLD_SQR: f64 = 12544.0; /// `HERO_OF_THE_VILLAGE_DURATION`. pub const HERO_DURATION: i32 = 48_000; +/// `Mth.clamp(float)`: NaN passes through (`Math.min`). +fn clamp_f32(v: f32, lo: f32, hi: f32) -> f32 { + if v < lo { + lo + } else if v.is_nan() || v > hi { + if v.is_nan() { v } else { hi } + } else { + v + } +} +/// `getHealthOfLivingRaiders`: a float sum from zero (Rust's empty float +/// sum is -0.0). +pub fn living_health(members: &[RaiderInfo]) -> f32 { + members.iter().fold(0.0, |a, m| a + m.health) +} +/// `Vec3i.distSqr`. +fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> f64 { + (0..3) + .map(|i| f64::from(a[i]) - f64::from(b[i])) + .map(|d| d * d) + .sum() +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Status { Ongoing, @@ -27,6 +60,7 @@ pub enum Status { Stopped, } impl Status { + pub const ALL: [Self; 4] = [Self::Ongoing, Self::Victory, Self::Loss, Self::Stopped]; pub fn name(self) -> &'static str { match self { Self::Ongoing => "ongoing", @@ -35,13 +69,8 @@ impl Status { Self::Stopped => "stopped", } } - fn from_name(s: &str) -> Self { - match s { - "victory" => Self::Victory, - "loss" => Self::Loss, - "stopped" => Self::Stopped, - _ => Self::Ongoing, - } + pub fn from_name(s: &str) -> Option { + Self::ALL.into_iter().find(|v| v.name() == s) } } @@ -71,7 +100,7 @@ impl RaiderType { Self::Ravager => "minecraft:ravager", } } - /// The health `addWaveMob` counts toward the bar. + /// A freshly created raider's health (its maximum). pub fn health(self) -> f32 { match self { Self::Witch => 26.0, @@ -111,53 +140,74 @@ pub struct Spawn { pub rider: Option, } -/// A raider that belongs to a raid, as the level reports it. -#[derive(Clone, Debug)] +/// A member of a raid (`groupRaiderMap`), as the game reports it. +#[derive(Clone, Debug, Default)] pub struct RaiderInfo { pub id: u32, pub wave: i32, pub health: f32, + /// `blockPosition()`. pub position: [i32; 3], - /// `tickCount`. - pub age: u32, + pub tick_count: i32, pub no_action_time: i32, pub ticks_outside: i32, - pub in_village: bool, + /// `isRemoved()` (killed, discarded or unloaded). + pub removed: bool, + /// The raider is in another dimension. + pub other_dimension: bool, + /// `level.getEntity(uuid)` finds it. + pub in_level: bool, + pub patrol_leader: bool, +} + +/// The single player a raid sees (`level.players()`). +#[derive(Clone, Copy, Debug)] +pub struct RaidPlayer { + pub position: [f64; 3], + pub block: [i32; 3], + pub alive: bool, } /// What a raid asks of the world. pub trait RaidLevel { /// The world difficulty, 0 (peaceful) to 3 (hard). fn difficulty(&self) -> i32; + /// `Level.hasChunkAt`. fn has_chunk_at(&self, pos: [i32; 3]) -> bool; - /// `ServerLevel.isVillage`: within one section of a village centre. - fn is_village(&self, pos: [i32; 3]) -> bool; - /// Centres of the village sections within two sections of `pos`. - fn village_sections_near(&self, pos: [i32; 3]) -> Vec<[i32; 3]>; - /// The living raiders of a raid. - fn raiders(&self, raid: i32) -> Vec; - /// `Heightmap.WORLD_SURFACE` height at a column. + /// `Level.hasChunksAt(x0, z0, x1, z1)`. + fn has_chunks_at(&self, x0: i32, z0: i32, x1: i32, z1: i32) -> bool; + /// `ServerLevel.sectionsToVillage` (0 to 7). + fn sections_to_village(&self, pos: [i32; 3]) -> i32; + /// `Heightmap.Types.WORLD_SURFACE` height of a column. fn surface_height(&self, x: i32, z: i32) -> i32; - /// The chunks around the position are loaded and ticking. - fn is_ticking(&self, pos: [i32; 3]) -> bool; - /// A ravager may spawn there (or on snow), in loaded chunks. - fn can_spawn_at(&self, pos: [i32; 3]) -> bool; + /// `ServerLevel.isPositionEntityTicking`. + fn is_position_entity_ticking(&self, pos: [i32; 3]) -> bool; + /// The ravager's placement accepts the position, or it is air on snow. + fn ravager_can_spawn(&self, pos: [i32; 3]) -> bool; + fn player(&self) -> Option; +} +/// `ServerLevel.isVillage`. +pub fn is_village(level: &dyn RaidLevel, pos: [i32; 3]) -> bool { + level.sections_to_village(pos) <= 1 } /// What the game must do after a raid tick. #[derive(Clone, Debug, PartialEq)] pub enum Action { - /// Spawn the raiders of a wave around `pos`. + /// Spawn the raiders of a wave at `pos` (`spawnGroup`), in order, each + /// joining the raid at `wave`; the leader gets the banner first. Spawn { pos: [i32; 3], wave: i32, spawns: Vec, }, - /// The raid horn, heard by players near or in the raid. + /// `playSound`: the raid horn with its seed, heard by the player when + /// within 64 blocks or in the raid. Horn { pos: [i32; 3], + seed: i64, }, - /// A raider leaves the raid (far away, despawned or idle outside). + /// A raider leaves the raid (`removeFromRaid`: `setCurrentRaid(null)`). Remove { id: u32, }, @@ -165,7 +215,7 @@ pub enum Action { id: u32, ticks: i32, }, - /// The raid was won: heroes get the effect at `level` (amplifier). + /// The raid was won: heroes (in set order) get Hero of the Village. Victory { heroes: Vec<[i32; 4]>, amplifier: i32, @@ -180,12 +230,13 @@ pub enum BarName { Victory, Defeat, } +/// The raid's `ServerBossEvent` (red, ten notches). #[derive(Clone, Debug)] pub struct Bar { pub name: BarName, pub progress: f32, pub visible: bool, - /// The local player is in the raid (`ServerBossEvent.getPlayers`). + /// The local player sees the bar (`getPlayers` holds them). pub player: bool, } @@ -202,10 +253,13 @@ pub struct Raid { pub num_groups: i32, pub status: Status, pub center: [i32; 3], - pub heroes: Vec<[i32; 4]>, + /// `heroesOfTheVillage`, in the order they joined the set. + heroes: Vec<[i32; 4]>, pub bar: Bar, - celebration_ticks: i32, - wave_spawn_pos: Option<[i32; 3]>, + pub celebration_ticks: i32, + pub wave_spawn_pos: Option<[i32; 3]>, + /// `groupToLeaderMap`: wave to the leading raider's id. + pub leaders: BTreeMap, random: LegacyRandom, } impl Raid { @@ -232,9 +286,14 @@ impl Raid { }, celebration_ticks: 0, wave_spawn_pos: None, + leaders: BTreeMap::new(), random: LegacyRandom::new(seed), } } + /// Replaces the raid's random (vanilla's is unseeded). + pub fn reseed(&mut self, seed: i64) { + self.random = LegacyRandom::new(seed); + } pub fn is_over(&self) -> bool { self.is_victory() || self.is_loss() } @@ -283,8 +342,9 @@ impl Raid { && (self.groups_spawned < self.num_groups || self.should_spawn_bonus_group(alive)) && alive == 0 } - /// `Raid.absorbRaidOmen`: the omen level rises by the effect's level. - /// True when this is the omen that first triggers the raid. + /// `Raid.absorbRaidOmen` for a player with Raid Omen at `amplifier`. + /// True when this omen triggers the raid (no wave spawned yet: the + /// `raid_trigger` stat and the `voluntary_exile` advancement). pub fn absorb_omen(&mut self, amplifier: i32) -> bool { self.omen_level = (self.omen_level + amplifier + 1).clamp(0, MAX_OMEN_LEVEL); !self.has_first_wave_spawned() @@ -299,12 +359,47 @@ impl Raid { _ => 0.0, } } + /// `addHeroOfTheVillage`. pub fn add_hero(&mut self, uuid: [i32; 4]) { if !self.heroes.contains(&uuid) { self.heroes.push(uuid); } } - /// `Raid.getDefaultNumSpawns` and `getPotentialBonusSpawns`. + /// The heroes in the order vanilla's `HashSet` iterates them. + pub fn heroes(&self) -> Vec<[i32; 4]> { + java_hash_set_order(&self.heroes, 16) + } + /// `setLeader`: the raider leading a wave (it wears the banner). + pub fn set_leader(&mut self, wave: i32, id: u32) { + self.leaders.insert(wave, id); + } + pub fn remove_leader(&mut self, wave: i32) { + self.leaders.remove(&wave); + } + pub fn leader(&self, wave: i32) -> Option { + self.leaders.get(&wave).copied() + } + /// `updateBossbar` with the health of the living raiders. + pub fn update_bossbar(&mut self, living_health: f32) { + self.bar.progress = clamp_f32(living_health / self.total_health, 0.0, 1.0); + } + /// `addWaveMob` (joining or loading): the raider's health counts toward + /// the bar when `update_health`; `living_health` includes it. + pub fn add_wave_mob(&mut self, health: f32, update_health: bool, living_health: f32) { + if update_health { + self.total_health += health; + } + self.update_bossbar(living_health); + } + /// `removeFromRaid` of a member; `living_health` is without it. + pub fn remove_from_raid(&mut self, health: f32, from_total: bool, living_health: f32) { + if from_total { + self.total_health -= health; + } + self.update_bossbar(living_health); + } + + /// `getDefaultNumSpawns` and `getPotentialBonusSpawns`. fn wave_count(&mut self, kind: RaiderType, wave: i32, difficulty: i32, bonus: bool) -> i32 { let index = if bonus { self.num_groups } else { wave } as usize; let base = kind.spawns()[index.min(7)]; @@ -337,7 +432,7 @@ impl Raid { } /// The raiders of wave `wave` (`spawnGroup`): per type the counted /// spawns, the first able raider leading, and ravagers carrying a - /// pillager (the last normal wave) or an evoker and vindicators (hard). + /// pillager (wave 5) or an evoker then vindicators (wave 7 and later). pub fn compose_wave(&mut self, wave: i32, difficulty: i32, bonus: bool) -> Vec { let mut out = Vec::new(); let mut leader_set = false; @@ -369,67 +464,88 @@ impl Raid { } out } - /// The health `joinRaid` adds for a wave. - pub fn wave_health(spawns: &[Spawn]) -> f32 { - spawns - .iter() - .map(|s| s.kind.health() + s.rider.map_or(0.0, RaiderType::health)) - .sum() - } /// `Raid.findRandomSpawnPos`: a ring around the centre that closes in as /// the countdown runs down. fn find_spawn_pos(&mut self, level: &dyn RaidLevel, max_tries: i32) -> Option<[i32; 3]> { let seconds = self.cooldown_ticks / 20; let how_far = 0.22 * seconds as f32 - 0.24; let start = self.random.next_float() * (std::f32::consts::PI * 2.0); + let far = how_far.floor() as i32; for i in 0..max_tries { let angle = start + std::f32::consts::PI * i as f32 / 8.0; let x = self.center[0] - + (angle.cos() * 32.0 * how_far).floor() as i32 - + self.random.next_int_bound(3).unwrap_or(0) * how_far.floor() as i32; + + (trig::cos(f64::from(angle)) * 32.0 * how_far).floor() as i32 + + self.random.next_int_bound(3).unwrap_or(0) * far; let z = self.center[2] - + (angle.sin() * 32.0 * how_far).floor() as i32 - + self.random.next_int_bound(3).unwrap_or(0) * how_far.floor() as i32; + + (trig::sin(f64::from(angle)) * 32.0 * how_far).floor() as i32 + + self.random.next_int_bound(3).unwrap_or(0) * far; let y = level.surface_height(x, z); if (y - self.center[1]).abs() > 96 { continue; } let pos = [x, y, z]; - if (!level.is_village(pos) || seconds <= 7) && level.can_spawn_at(pos) { + if (!is_village(level, pos) || seconds <= 7) + && level.has_chunks_at(x - 10, z - 10, x + 10, z + 10) + && level.is_position_entity_ticking(pos) + && level.ravager_can_spawn(pos) + { return Some(pos); } } None } + /// `moveRaidCenterToNearbyVillageSection`: the closest village section + /// centre within two sections (first of equals in `SectionPos.cube` order). fn move_center_to_nearby_village(&mut self, level: &dyn RaidLevel) { let c = self.center; - let d = |p: &[i32; 3]| (0..3).map(|i| f64::from(p[i] - c[i]).powi(2)).sum::(); - if let Some(best) = level - .village_sections_near(c) - .into_iter() - .min_by(|a, b| d(a).total_cmp(&d(b))) - { - self.center = best; + let (sx, sy, sz) = (c[0] >> 4, c[1] >> 4, c[2] >> 4); + let mut best: Option<([i32; 3], f64)> = None; + // SectionPos.cube: BetweenClosed over x fastest, then y, then z. + for dz in -2..=2 { + for dy in -2..=2 { + for dx in -2..=2 { + let s = [sx + dx, sy + dy, sz + dz]; + let center = [s[0] * 16 + 8, s[1] * 16 + 8, s[2] * 16 + 8]; + if !is_village(level, center) { + continue; + } + let d = dist_sqr(center, c); + if best.is_none_or(|b| d < b.1) { + best = Some((center, d)); + } + } + } + } + if let Some((center, _)) = best { + self.center = center; } } - /// Boss bar progress while raiders are alive (`updateBossbar`). - pub fn update_bar(&mut self, living_health: f32) { - self.bar.progress = if self.total_health > 0.0 { - (living_health / self.total_health).clamp(0.0, 1.0) - } else { - 0.0 - }; + /// The countdown's bar progress and the local player's membership + /// (`updatePlayers`). + fn update_players(&mut self, in_raid: bool) { + self.bar.player = in_raid; } - /// `Raid.tick`. `raiders` are the living members; `player` is whether - /// the local player's position falls in this raid. - pub fn tick(&mut self, id: i32, level: &dyn RaidLevel, player: bool) -> Vec { + + /// `Raid.tick`. `members` are the raid's raiders; `in_raid` answers + /// whether the player stands in this raid (`getRaidAt(pos) == this`, + /// with the raid's current centre and state). + pub fn tick( + &mut self, + level: &dyn RaidLevel, + members: &[RaiderInfo], + in_raid: &dyn Fn(&Raid, [i32; 3]) -> bool, + ) -> Vec { let mut actions = Vec::new(); if self.is_stopped() { return actions; } - let raiders = level.raiders(id); - let alive = raiders.len(); + let player_in = |raid: &Raid| { + level + .player() + .is_some_and(|p| p.alive && in_raid(raid, p.block)) + }; if self.status == Status::Ongoing { + let mut members: Vec = members.to_vec(); let was_active = self.active; self.active = level.has_chunk_at(self.center); if level.difficulty() == 0 { @@ -442,10 +558,10 @@ impl Raid { if !self.active { return actions; } - if !level.is_village(self.center) { + if !is_village(level, self.center) { self.move_center_to_nearby_village(level); } - if !level.is_village(self.center) { + if !is_village(level, self.center) { if self.groups_spawned > 0 { self.status = Status::Loss; } else { @@ -457,12 +573,7 @@ impl Raid { self.stop(); return actions; } - // Raid.updateBossbar, as raiders are hurt, die or leave. - if alive > 0 { - self.update_bar(raiders.iter().map(|r| r.health).sum()); - } else if self.started && !self.has_more_waves() { - self.bar.progress = 0.0; - } + let alive = members.len(); if alive == 0 && self.has_more_waves() { if self.cooldown_ticks <= 0 { if self.cooldown_ticks == 0 && self.groups_spawned > 0 { @@ -473,23 +584,30 @@ impl Raid { } else { let cached = self.wave_spawn_pos.is_some(); let mut try_find = !cached && self.cooldown_ticks % 5 == 0; - if cached && !self.wave_spawn_pos.is_some_and(|p| level.is_ticking(p)) { + if let Some(p) = self.wave_spawn_pos + && !level.is_position_entity_ticking(p) + { try_find = true; } if try_find { self.wave_spawn_pos = self.find_spawn_pos(level, 8); } if self.cooldown_ticks == PRE_RAID_TICKS || self.cooldown_ticks % 20 == 0 { - self.bar.player = player; + let p = player_in(self); + self.update_players(p); } self.cooldown_ticks -= 1; - self.bar.progress = - ((PRE_RAID_TICKS - self.cooldown_ticks) as f32 / 300.0).clamp(0.0, 1.0); + self.bar.progress = clamp_f32( + (PRE_RAID_TICKS - self.cooldown_ticks) as f32 / 300.0, + 0.0, + 1.0, + ); } } if self.ticks_active % 20 == 0 { - self.bar.player = player; - self.update_raiders(&raiders, level, &mut actions); + let p = player_in(self); + self.update_players(p); + self.update_raiders(level, &mut members, &mut actions); self.bar.name = if alive > 0 && alive <= 2 { BarName::Remaining(alive as i32) } else { @@ -498,28 +616,24 @@ impl Raid { } let mut sound = false; let mut attempt = 0; - let mut spawned_alive = alive; - while self.should_spawn_group(spawned_alive) { - let pos = self - .wave_spawn_pos - .or_else(|| self.find_spawn_pos(level, 20)); + while self.should_spawn_group(members.len()) { + let pos = match self.wave_spawn_pos { + Some(p) => Some(p), + None => self.find_spawn_pos(level, 20), + }; if let Some(pos) = pos { self.started = true; - let wave = self.groups_spawned + 1; - let bonus = self.should_spawn_bonus_group(spawned_alive); - let difficulty = level.difficulty(); - let spawns = self.compose_wave(wave, difficulty, bonus); - self.total_health = Self::wave_health(&spawns); - spawned_alive = spawns - .iter() - .map(|s| 1 + usize::from(s.rider.is_some())) - .sum(); - self.wave_spawn_pos = None; - self.groups_spawned += 1; - self.bar.progress = 1.0; - actions.push(Action::Spawn { pos, wave, spawns }); + let spawns = self.spawn_group(level, pos, &mut members); + actions.push(Action::Spawn { + pos, + wave: self.groups_spawned, + spawns, + }); if !sound { - actions.push(Action::Horn { pos }); + actions.push(Action::Horn { + pos, + seed: self.random.next_long(), + }); sound = true; } } else { @@ -536,7 +650,7 @@ impl Raid { } else { self.status = Status::Victory; actions.push(Action::Victory { - heroes: self.heroes.clone(), + heroes: self.heroes(), amplifier: self.omen_level - 1, }); } @@ -548,7 +662,8 @@ impl Raid { return actions; } if self.celebration_ticks % 20 == 0 { - self.bar.player = player; + let p = player_in(self); + self.update_players(p); self.bar.visible = true; if self.is_victory() { self.bar.progress = 0.0; @@ -560,37 +675,331 @@ impl Raid { } actions } - /// `Raid.updateRaiders`. + /// `spawnGroup`: the wave's raiders join at `pos` (each `addWaveMob` + /// counting its health), then the wave counter moves on. + fn spawn_group( + &mut self, + level: &dyn RaidLevel, + pos: [i32; 3], + members: &mut Vec, + ) -> Vec { + let wave = self.groups_spawned + 1; + self.total_health = 0.0; + let bonus = self.should_spawn_bonus_group(members.len()); + let spawns = self.compose_wave(wave, level.difficulty(), bonus); + let mut join = |raid: &mut Self, kind: RaiderType| { + members.push(RaiderInfo { + wave, + health: kind.health(), + position: pos, + in_level: true, + ..RaiderInfo::default() + }); + let living = living_health(members); + raid.add_wave_mob(kind.health(), true, living); + }; + for s in &spawns { + join(self, s.kind); + if let Some(rider) = s.rider { + join(self, rider); + } + } + self.wave_spawn_pos = None; + self.groups_spawned += 1; + let living = living_health(members); + self.update_bossbar(living); + spawns + } + /// `Raid.updateRaiders`: members that are gone, too far or idle outside + /// the village too long leave the raid. fn update_raiders( &mut self, - raiders: &[RaiderInfo], level: &dyn RaidLevel, + members: &mut Vec, actions: &mut Vec, ) { - let _ = level; - for r in raiders { - let d = (0..3) - .map(|i| f64::from(self.center[i] - r.position[i]).powi(2)) - .sum::(); - let mut remove = d >= REMOVAL_THRESHOLD_SQR; - if !remove && r.age > 600 { - let mut outside = r.ticks_outside; - if !r.in_village && r.no_action_time > 2400 { - outside += 1; + let mut leaving = Vec::new(); + for r in members.iter_mut() { + if r.removed + || r.other_dimension + || dist_sqr(self.center, r.position) >= REMOVAL_THRESHOLD_SQR + { + leaving.push(r.id); + } else if r.tick_count > 600 { + if !r.in_level { + leaving.push(r.id); + } + if !is_village(level, r.position) && r.no_action_time > MAX_NO_ACTION_TIME { + r.ticks_outside += 1; actions.push(Action::SetOutside { id: r.id, - ticks: outside, + ticks: r.ticks_outside, }); } - remove = outside >= 30; + if r.ticks_outside >= OUTSIDE_RAID_BOUNDS_TIMEOUT && !leaving.contains(&r.id) { + leaving.push(r.id); + } } - if remove { - self.total_health -= r.health; - actions.push(Action::Remove { id: r.id }); + } + for id in leaving { + let Some(i) = members.iter().position(|m| m.id == id) else { + continue; + }; + let r = members.remove(i); + let living = living_health(members); + self.remove_from_raid(r.health, true, living); + actions.push(Action::Remove { id }); + if r.patrol_leader { + self.remove_leader(r.wave); } } } +} +// ------------------------------------------------------------------ Raids + +/// `Raids`: the raids of a dimension by id, in vanilla's +/// `Int2ObjectOpenHashMap` (its iteration order is the tick and save order). +#[derive(Clone, Debug)] +pub struct Raids { + pub map: BTreeMap, + order: IntOpenHashOrder, + pub next_id: i32, + pub tick: i32, + /// Changed since the last save. + pub dirty: bool, +} +impl Default for Raids { + /// `new Raids()` (dirty, so a fresh level writes its file). + fn default() -> Self { + Self { + map: BTreeMap::new(), + order: IntOpenHashOrder::new(), + next_id: 1, + tick: 0, + dirty: true, + } + } +} +impl Raids { + pub fn get(&self, id: i32) -> Option<&Raid> { + self.map.get(&id) + } + pub fn get_mut(&mut self, id: i32) -> Option<&mut Raid> { + self.map.get_mut(&id) + } + /// The raid ids in iteration order. + pub fn ids(&self) -> Vec { + self.order.iter() + } + fn insert(&mut self, id: i32, raid: Raid) { + if self.map.insert(id, raid).is_none() { + self.order.put(id); + } + } + /// `Raids.getNearbyRaid(pos, 9216)`: the closest active raid. + pub fn nearby(&self, pos: [i32; 3]) -> Option<(i32, &Raid)> { + nearest( + self.ids() + .into_iter() + .filter_map(|id| Some((id, self.map.get(&id)?))), + pos, + ) + .map(|id| (id, &self.map[&id])) + } + /// `Raids.createOrExtendRaid` once the caller found the village centre + /// (`raid_center`): the raid at that position or a new one, then the + /// player's Raid Omen at `omen_amplifier` absorbed. Returns the raid id + /// and whether the omen triggered it. + pub fn create_or_extend( + &mut self, + raid_center: [i32; 3], + difficulty: i32, + omen_amplifier: Option, + seed: i64, + ) -> (i32, bool) { + let id = match self.nearby(raid_center) { + Some((id, _)) => id, + None => { + self.next_id += 1; + let id = self.next_id; + self.insert(id, Raid::new(raid_center, difficulty, seed)); + id + } + }; + let mut triggered = false; + if let Some(raid) = self.map.get_mut(&id) + && (!raid.started || raid.omen_level < MAX_OMEN_LEVEL) + && let Some(amp) = omen_amplifier + { + triggered = raid.absorb_omen(amp); + } + self.dirty = true; + (id, triggered) + } + /// `Raids.tick`: each raid in map order (stopped ones removed, every + /// raid stopped when the `raids` rule is off). `members` gives a raid's + /// raiders. Returns the raids' actions. + pub fn tick( + &mut self, + level: &dyn RaidLevel, + rules_raids: bool, + members: &dyn Fn(i32) -> Vec, + ) -> Vec<(i32, Action)> { + self.tick += 1; + let mut out = Vec::new(); + let map = &mut self.map; + let mut removed_any = false; + let ids = self.order.iter(); + let mut visit = |id: i32| -> bool { + // The raids in map order as they stand when this one ticks. + let snapshot: Vec<(i32, [i32; 3], bool)> = ids + .iter() + .filter_map(|i| map.get(i).map(|r| (*i, r.center, r.active))) + .collect(); + let Some(raid) = map.get_mut(&id) else { + return false; + }; + if !rules_raids { + raid.stop(); + } + if raid.is_stopped() { + removed_any = true; + return true; + } + let order = &snapshot; + let in_raid = |r: &Raid, pos: [i32; 3]| { + let mut best: Option<(i32, f64)> = None; + for (i, c, active) in order { + let (c, active) = if *i == id { + (r.center, r.active) + } else { + (*c, *active) + }; + let d = dist_sqr(c, pos); + if active && d < best.map_or(VALID_RAID_RADIUS_SQR, |b| b.1) { + best = Some((*i, d)); + } + } + best.is_some_and(|b| b.0 == id) + }; + for a in raid.tick(level, &members(id), &in_raid) { + out.push((id, a)); + } + false + }; + let gone = self.order.iterate_removing(&mut visit); + for id in gone { + map.remove(&id); + } + if removed_any || self.tick % 200 == 0 { + self.dirty = true; + } + // Raid.tick marks the data dirty while a raid runs. + if self + .map + .values() + .any(|r| r.status == Status::Ongoing && r.active) + { + self.dirty = true; + } + out + } + + /// `Raids.CODEC`: `{raids: [...], next_id, tick}` in the entry set's + /// stream order. + pub fn to_nbt(&self) -> Tag { + let raids: Vec = self + .order + .stream() + .into_iter() + .map(|id| { + let mut tag = self.map[&id].to_nbt(); + if let Tag::Compound(map) = &mut tag { + map.insert("id".into(), Tag::Int(id)); + } + tag + }) + .collect(); + let mut tag = Tag::compound([ + ("next_id", Tag::Int(self.next_id)), + ("tick", Tag::Int(self.tick)), + ]); + // optionalFieldOf("raids", List.of()) leaves the default out. + if !raids.is_empty() + && let Tag::Compound(map) = &mut tag + { + map.insert("raids".into(), Tag::List(raids)); + } + tag + } + /// `Raids.CODEC.parse(...).resultOrPartial()`, or a fresh `Raids` when + /// nothing decodes. Raids that fail to decode are dropped; a raid whose + /// heroes partly fail keeps the others. + pub fn from_nbt(tag: &Tag, seed: i64) -> Self { + let Some(decoded) = decode_raids(tag) else { + return Self::default(); + }; + let mut out = Self { + dirty: false, + next_id: decoded.next_id, + tick: decoded.tick, + ..Self::default() + }; + for (i, (id, raid)) in decoded.raids.into_iter().enumerate() { + let mut raid = raid; + raid.random = LegacyRandom::new(seed.wrapping_add(i as i64)); + // Int2ObjectOpenHashMap.put: a repeated id replaces the raid. + out.map.insert(id, raid); + out.order.put(id); + } + out + } +} +/// The id of the closest active raid within 96 blocks (`getNearbyRaid`). +fn nearest<'a>(raids: impl Iterator, pos: [i32; 3]) -> Option { + let mut best: Option<(i32, f64)> = None; + for (id, r) in raids { + let d = dist_sqr(r.center, pos); + if r.active && d < best.map_or(VALID_RAID_RADIUS_SQR, |b| b.1) { + best = Some((id, d)); + } + } + best.map(|b| b.0) +} + +/// `Raids.createOrExtendRaid`'s centre: the mean of the occupied village +/// points of interest within 64 blocks (`BlockPos.containing`), else the +/// omen's position. +pub fn raid_center(omen_pos: [i32; 3], village_pois: &[[i32; 3]]) -> [i32; 3] { + let near: Vec<&[i32; 3]> = village_pois + .iter() + .filter(|p| { + (0..3).all(|i| i == 1 || (p[i] - omen_pos[i]).abs() <= 64) + && dist_sqr(**p, omen_pos) <= 4096.0 + }) + .collect(); + if near.is_empty() { + return omen_pos; + } + let mut total = [0.0f64; 3]; + for p in &near { + for i in 0..3 { + total[i] += f64::from(p[i]); + } + } + let scale = 1.0 / near.len() as f64; + [ + (total[0] * scale).floor() as i32, + (total[1] * scale).floor() as i32, + (total[2] * scale).floor() as i32, + ] +} + +// ------------------------------------------------------------------ codec + +impl Raid { + /// `Raid.MAP_CODEC` fields. pub fn to_nbt(&self) -> Tag { Tag::compound([ ("started", Tag::Byte(i8::from(self.started))), @@ -607,7 +1016,7 @@ impl Raid { ( "heroes_of_the_village", Tag::List( - self.heroes + self.heroes() .iter() .map(|u| Tag::IntArray(u.to_vec())) .collect(), @@ -615,191 +1024,486 @@ impl Raid { ), ]) } - pub fn from_nbt(tag: &Tag, seed: i64) -> Option { - let int = |k: &str| match tag.get(k) { - Some(Tag::Int(v)) => Some(*v), - Some(Tag::Byte(v)) => Some(i32::from(*v)), - Some(Tag::Short(v)) => Some(i32::from(*v)), - _ => None, - }; - let center = match tag.get("center") { - Some(Tag::IntArray(v)) if v.len() == 3 => [v[0], v[1], v[2]], - _ => return None, - }; - let mut raid = Self::new(center, 0, seed); - raid.started = int("started")? != 0; - raid.active = int("active")? != 0; - raid.ticks_active = match tag.get("ticks_active") { - Some(Tag::Long(v)) => *v, - _ => 0, - }; - raid.omen_level = int("raid_omen_level").unwrap_or(0); - raid.groups_spawned = int("groups_spawned").unwrap_or(0); - raid.cooldown_ticks = int("cooldown_ticks").unwrap_or(PRE_RAID_TICKS); - raid.post_raid_ticks = int("post_raid_ticks").unwrap_or(0); - raid.total_health = match tag.get("total_health") { - Some(Tag::Float(bits)) => f32::from_bits(*bits), - _ => 0.0, - }; - raid.num_groups = int("group_count").unwrap_or(0); - raid.status = match tag.get("status") { - Some(Tag::String(s)) => Status::from_name(&s.to_string_lossy()), - _ => Status::Ongoing, - }; - if let Some(Tag::List(heroes)) = tag.get("heroes_of_the_village") { - for h in heroes { - if let Tag::IntArray(v) = h - && v.len() == 4 - { - raid.heroes.push([v[0], v[1], v[2], v[3]]); - } + /// The private codec constructor: a loaded raid's bar is visible with + /// full progress until the raid updates it. + fn loaded(fields: RaidFields) -> Self { + let mut raid = Self::new(fields.center, 0, 0); + raid.started = fields.started; + raid.active = fields.active; + raid.ticks_active = fields.ticks_active; + raid.omen_level = fields.omen_level; + raid.groups_spawned = fields.groups_spawned; + raid.cooldown_ticks = fields.cooldown_ticks; + raid.post_raid_ticks = fields.post_raid_ticks; + raid.total_health = fields.total_health; + raid.num_groups = fields.num_groups; + raid.status = fields.status; + // Sets.newHashSet(list), then addAll into the raid's own set. + let cap = java_table_size_for(java_hash_set_capacity(fields.heroes.len())); + let mut unique: Vec<[i32; 4]> = Vec::new(); + for h in fields.heroes { + if !unique.contains(&h) { + unique.push(h); } } - raid.bar.visible = raid.active; - Some(raid) + raid.heroes = java_hash_set_order(&unique, cap); + raid.bar.progress = 1.0; + raid } } -/// `Raids`: the raids of a dimension by id. -#[derive(Clone, Debug)] -pub struct Raids { - pub map: BTreeMap, +struct RaidFields { + started: bool, + active: bool, + ticks_active: i64, + omen_level: i32, + groups_spawned: i32, + cooldown_ticks: i32, + post_raid_ticks: i32, + total_health: f32, + num_groups: i32, + status: Status, + center: [i32; 3], + heroes: Vec<[i32; 4]>, +} + +/// A DataFixerUpper result: a value, and whether an error was reported +/// (`Some` with an error is a partial result). +type Decoded = (Option, bool); + +/// `NbtOps.getNumberValue`: the numeric tags as Java numbers. +#[derive(Clone, Copy)] +enum Number { + Long(i64), + Float(f32), + Double(f64), +} +fn number(tag: &Tag) -> Option { + Some(match tag { + Tag::Byte(v) => Number::Long(i64::from(*v)), + Tag::Short(v) => Number::Long(i64::from(*v)), + Tag::Int(v) => Number::Long(i64::from(*v)), + Tag::Long(v) => Number::Long(*v), + Tag::Float(b) => Number::Float(f32::from_bits(*b)), + Tag::Double(b) => Number::Double(f64::from_bits(*b)), + _ => return None, + }) +} +impl Number { + /// `Number.intValue`: integers truncate, floating values convert like + /// Java's `(int)` cast. + fn int(self) -> i32 { + match self { + Self::Long(v) => v as i32, + Self::Float(v) => v as i32, + Self::Double(v) => v as i32, + } + } + fn long(self) -> i64 { + match self { + Self::Long(v) => v, + Self::Float(v) => v as i64, + Self::Double(v) => v as i64, + } + } + fn float(self) -> f32 { + match self { + Self::Long(v) => v as f32, + Self::Float(v) => v, + Self::Double(v) => v as f32, + } + } + fn double(self) -> f64 { + match self { + Self::Long(v) => v as f64, + Self::Float(v) => f64::from(v), + Self::Double(v) => v, + } + } +} +/// `DynamicOps.getIntStream` through `NbtOps`: an int array, or a list or +/// array whose elements are all numbers. +fn int_stream(tag: &Tag) -> Option> { + match tag { + Tag::IntArray(v) => Some(v.clone()), + Tag::ByteArray(v) => Some(v.iter().map(|b| i32::from(*b as i8)).collect()), + Tag::LongArray(v) => Some(v.iter().map(|l| *l as i32).collect()), + Tag::List(items) => items.iter().map(|t| number(t).map(Number::int)).collect(), + _ => None, + } +} +/// `ops.getList`: the elements of any collection tag. +fn collection(tag: &Tag) -> Option> { + match tag { + Tag::List(items) => Some(items.clone()), + Tag::ByteArray(v) => Some(v.iter().map(|b| Tag::Byte(*b as i8)).collect()), + Tag::IntArray(v) => Some(v.iter().map(|i| Tag::Int(*i)).collect()), + Tag::LongArray(v) => Some(v.iter().map(|i| Tag::Long(*i)).collect()), + _ => None, + } +} +fn field<'a>(tag: &'a Tag, key: &str) -> Option<&'a Tag> { + match tag { + Tag::Compound(map) => map.get(&JavaString::from(key)), + _ => None, + } +} +/// `Codec.list(UUIDUtil.CODEC)`: good entries kept, an error if any failed. +fn decode_uuids(tag: &Tag) -> Decoded> { + let Some(items) = collection(tag) else { + return (None, true); + }; + let mut out = Vec::new(); + let mut error = false; + for item in &items { + // Util.fixedSize: a longer stream is a partial result of its start. + match int_stream(item) { + Some(v) if v.len() >= 4 => { + error |= v.len() > 4; + out.push([v[0], v[1], v[2], v[3]]); + } + _ => error = true, + } + } + (Some(out), error) +} +/// `Raid.MAP_CODEC` over a compound (missing or mistyped fields fail with +/// no partial result; a partial heroes list leaves a partial raid). +fn decode_raid(tag: &Tag) -> Decoded { + let num = |k: &str| field(tag, k).and_then(number); + let ( + Some(started), + Some(active), + Some(ticks_active), + Some(omen), + Some(groups), + Some(cooldown), + Some(post), + Some(health), + Some(count), + ) = ( + num("started"), + num("active"), + num("ticks_active"), + num("raid_omen_level"), + num("groups_spawned"), + num("cooldown_ticks"), + num("post_raid_ticks"), + num("total_health"), + num("group_count"), + ) + else { + return (None, true); + }; + let status = match field(tag, "status") { + Some(Tag::String(s)) => Status::from_name(&s.to_string_lossy()), + _ => None, + }; + // Util.fixedSize: a longer stream is a partial result of its start. + let center = field(tag, "center") + .and_then(int_stream) + .filter(|v| v.len() >= 3); + let (Some(status), Some(center)) = (status, center) else { + return (None, true); + }; + let Some(heroes_tag) = field(tag, "heroes_of_the_village") else { + return (None, true); + }; + let (heroes, error) = decode_uuids(heroes_tag); + let Some(heroes) = heroes else { + return (None, true); + }; + let fields = RaidFields { + started: started.double() != 0.0, + active: active.double() != 0.0, + ticks_active: ticks_active.long(), + omen_level: omen.int(), + groups_spawned: groups.int(), + cooldown_ticks: cooldown.int(), + post_raid_ticks: post.int(), + total_health: health.float(), + num_groups: count.int(), + status, + center: [center[0], center[1], center[2]], + heroes, + }; + (Some(fields), error) +} +struct DecodedRaids { + raids: Vec<(i32, Raid)>, next_id: i32, tick: i32, - /// Changed since the last save. - pub dirty: bool, } -impl Default for Raids { - fn default() -> Self { +/// `Raids.CODEC` with `resultOrPartial`. +fn decode_raids(tag: &Tag) -> Option { + if !matches!(tag, Tag::Compound(_)) { + return None; + } + let mut raids = Vec::new(); + if let Some(list) = field(tag, "raids") { + // optionalFieldOf: a value that is no list decodes partially, to none. + let items = collection(list).unwrap_or_default(); + for item in &items { + let id = field(item, "id").and_then(number); + let (raid, _) = if matches!(item, Tag::Compound(_)) { + decode_raid(item) + } else { + (None, true) + }; + if let (Some(id), Some(raid)) = (id, raid) { + raids.push((id.int(), Raid::loaded(raid))); + } + } + } + let next_id = field(tag, "next_id").and_then(number)?.int(); + let tick = field(tag, "tick").and_then(number)?.int(); + Some(DecodedRaids { + raids, + next_id, + tick, + }) +} + +// ------------------------------------------------------------------ Java collections + +/// `HashMap.hash` of a `UUID` built from its four ints. +fn uuid_hash(u: [i32; 4]) -> i32 { + let most = (i64::from(u[0]) << 32) | (i64::from(u[1]) & 0xffff_ffff); + let least = (i64::from(u[2]) << 32) | (i64::from(u[3]) & 0xffff_ffff); + let hilo = most ^ least; + let h = ((hilo >> 32) as i32) ^ (hilo as i32); + h ^ ((h as u32) >> 16) as i32 +} +/// `HashSet(Collection)`'s requested capacity (JDK 19+: `newHashMap(max(n, 12))`). +fn java_hash_set_capacity(n: usize) -> usize { + (n.max(12) as f64 / 0.75).ceil() as usize +} +/// `HashMap.tableSizeFor`. +fn java_table_size_for(cap: usize) -> usize { + cap.max(1).next_power_of_two() +} +/// The iteration order of a `HashSet` whose table started at +/// `capacity` (doubling past three quarters full), given insertion order. +pub fn java_hash_set_order(items: &[[i32; 4]], capacity: usize) -> Vec<[i32; 4]> { + let mut cap = capacity.max(1); + while items.len() as f64 > cap as f64 * 0.75 { + cap *= 2; + } + let mut keyed: Vec<(usize, usize)> = items + .iter() + .enumerate() + .map(|(i, u)| ((uuid_hash(*u) as u32 as usize) & (cap - 1), i)) + .collect(); + keyed.sort(); + keyed.into_iter().map(|(_, i)| items[i]).collect() +} + +/// `HashCommon.mix` for ints. +fn mix(x: i32) -> i32 { + let h = x.wrapping_mul(0x9E37_79B9_u32 as i32); + h ^ ((h as u32) >> 16) as i32 +} +fn array_size(expected: usize) -> usize { + ((expected as f64 / 0.75).ceil() as usize) + .next_power_of_two() + .max(2) +} +fn max_fill(n: usize) -> usize { + ((n as f64 * 0.75).ceil() as usize).min(n - 1) +} +/// The key layout of a fastutil `Int2ObjectOpenHashMap` (default size and +/// load factor), for its iteration order. +#[derive(Clone, Debug)] +struct IntOpenHashOrder { + key: Vec, + null_key: bool, + n: usize, + min_n: usize, + size: usize, +} +impl IntOpenHashOrder { + fn new() -> Self { + let n = array_size(16); Self { - map: BTreeMap::new(), - next_id: 1, - tick: 0, - dirty: false, + key: vec![0; n], + null_key: false, + n, + min_n: n, + size: 0, } } -} -impl Raids { - pub fn get(&self, id: i32) -> Option<&Raid> { - self.map.get(&id) + fn mask(&self) -> usize { + self.n - 1 } - pub fn id_of(&self, raid: &Raid) -> Option { - self.map - .iter() - .find(|(_, r)| std::ptr::eq(*r, raid)) - .map(|(id, _)| *id) + fn slot(&self, k: i32) -> usize { + (mix(k) as u32 as usize) & self.mask() } - /// `Raids.getNearbyRaid`: the closest active raid within 96 blocks. - pub fn nearby(&self, pos: [i32; 3]) -> Option<(i32, &Raid)> { - let mut best: Option<(i32, &Raid, f64)> = None; - for (id, r) in &self.map { - let d = (0..3) - .map(|i| f64::from(r.center[i] - pos[i]).powi(2)) - .sum::(); - if r.active && d < best.map_or(VALID_RAID_RADIUS_SQR, |b| b.2) { - best = Some((*id, r, d)); + fn find(&self, k: i32) -> Option { + if k == 0 { + return self.null_key.then_some(self.n); + } + let mut pos = self.slot(k); + loop { + match self.key[pos] { + 0 => return None, + c if c == k => return Some(pos), + _ => pos = (pos + 1) & self.mask(), } } - best.map(|(id, r, _)| (id, r)) } - /// `Raids.createOrExtendRaid`, after the caller found the village centre: - /// the raid at that position (a new one if none), with the omen's level - /// absorbed. Returns the raid id and whether the omen triggered it. - pub fn create_or_extend( - &mut self, - center: [i32; 3], - difficulty: i32, - omen_amplifier: Option, - seed: i64, - ) -> (i32, bool) { - let id = match self.nearby(center) { - Some((id, _)) => id, - None => { - self.next_id += 1; - self.map - .insert(self.next_id, Raid::new(center, difficulty, seed)); - self.next_id - } - }; - let mut triggered = false; - if let Some(raid) = self.map.get_mut(&id) - && (!raid.started || raid.omen_level < MAX_OMEN_LEVEL) - && let Some(amp) = omen_amplifier - { - triggered = raid.absorb_omen(amp); + fn put(&mut self, k: i32) { + if self.find(k).is_some() { + return; + } + if k == 0 { + self.null_key = true; + } else { + let mut pos = self.slot(k); + while self.key[pos] != 0 { + pos = (pos + 1) & self.mask(); + } + self.key[pos] = k; + } + let before = self.size; + self.size += 1; + if before >= max_fill(self.n) { + self.rehash(array_size(self.size + 1)); } - self.dirty = true; - (id, triggered) } - /// `Raids.tick`: every raid, stopped ones removed. `rules_raids` is the - /// `raids` game rule; `player` the local player's block position. - pub fn tick( - &mut self, - level: &dyn RaidLevel, - rules_raids: bool, - player: Option<[i32; 3]>, - ) -> Vec<(i32, Action)> { - self.tick += 1; - let inside = player.and_then(|p| self.nearby(p).map(|(id, _)| id)); + fn rehash(&mut self, new_n: usize) { + let mask = new_n - 1; + let mut new_key = vec![0; new_n]; + let mut i = self.n; + let real = self.size - usize::from(self.null_key); + for _ in 0..real { + loop { + i -= 1; + if self.key[i] != 0 { + break; + } + } + let k = self.key[i]; + let mut pos = (mix(k) as u32 as usize) & mask; + while new_key[pos] != 0 { + pos = (pos + 1) & mask; + } + new_key[pos] = k; + } + self.n = new_n; + self.key = new_key; + } + /// `shiftKeys` after the key at `pos` went; returns keys that wrapped + /// from the start of the table to its end. + fn shift_keys(&mut self, mut pos: usize) -> Vec { + let mut wrapped = Vec::new(); + let mask = self.mask(); + loop { + let last = pos; + pos = (last + 1) & mask; + let curr = loop { + let curr = self.key[pos]; + if curr == 0 { + self.key[last] = 0; + return wrapped; + } + let slot = (mix(curr) as u32 as usize) & mask; + let moves = if last <= pos { + last >= slot || slot > pos + } else { + last >= slot && slot > pos + }; + if moves { + break curr; + } + pos = (pos + 1) & mask; + }; + if pos < last { + wrapped.push(curr); + } + self.key[last] = curr; + } + } + /// `remove(k)`, shrinking a sparse table. + fn remove(&mut self, k: i32) { + if k == 0 { + if self.null_key { + self.null_key = false; + self.size -= 1; + } + return; + } + let Some(pos) = self.find(k) else { return }; + self.size -= 1; + self.shift_keys(pos); + if self.n > self.min_n && self.size < max_fill(self.n) / 4 && self.n > 16 { + self.rehash(self.n / 2); + } + } + /// The entry set's stream (`MapSpliterator`): the null key, then the + /// table upward. `Raids.CODEC` encodes in this order. + fn stream(&self) -> Vec { let mut out = Vec::new(); - let mut gone = Vec::new(); - for (id, raid) in &mut self.map { - if !rules_raids { - raid.stop(); - } - if raid.is_stopped() { - gone.push(*id); - continue; - } - for a in raid.tick(*id, level, inside == Some(*id)) { - out.push((*id, a)); - } + if self.null_key { + out.push(0); } - for id in gone { - self.map.remove(&id); - self.dirty = true; + out.extend(self.key[..self.n].iter().copied().filter(|k| *k != 0)); + out + } + /// The iterator (`MapIterator`): the null key, then the table downward. + fn iter(&self) -> Vec { + let mut out = Vec::new(); + if self.null_key { + out.push(0); } - if self.tick % 200 == 0 || !out.is_empty() { - self.dirty = true; + for pos in (0..self.n).rev() { + if self.key[pos] != 0 { + out.push(self.key[pos]); + } } out } - pub fn to_nbt(&self) -> Tag { - let raids = self - .map - .iter() - .map(|(id, r)| { - let mut tag = r.to_nbt(); - if let Tag::Compound(map) = &mut tag { - map.insert("id".into(), Tag::Int(*id)); + /// A `values().iterator()` pass that removes the keys `visit` says to + /// (the iterator's own removal, with wrapped entries); returns them. + fn iterate_removing(&mut self, visit: &mut dyn FnMut(i32) -> bool) -> Vec { + let mut removed = Vec::new(); + let mut pos = self.n as isize; + let mut c = self.size; + let mut must_null = self.null_key; + let mut wrapped: Vec = Vec::new(); + while c > 0 { + c -= 1; + // nextEntry + let (k, last): (i32, Option) = if must_null { + must_null = false; + (0, Some(self.n)) + } else { + loop { + pos -= 1; + if pos < 0 { + let k = wrapped[(-pos - 1) as usize]; + break (k, None); + } + if self.key[pos as usize] != 0 { + break (self.key[pos as usize], Some(pos as usize)); + } } - tag - }) - .collect(); - Tag::compound([ - ("raids", Tag::List(raids)), - ("next_id", Tag::Int(self.next_id)), - ("tick", Tag::Int(self.tick)), - ]) - } - pub fn from_nbt(tag: &Tag, seed: i64) -> Self { - let mut out = Self::default(); - if let Some(Tag::Int(v)) = tag.get("next_id") { - out.next_id = *v; - } - if let Some(Tag::Int(v)) = tag.get("tick") { - out.tick = *v; - } - if let Some(Tag::List(list)) = tag.get("raids") { - for (i, r) in list.iter().enumerate() { - if let Some(Tag::Int(id)) = r.get("id") - && let Some(raid) = Raid::from_nbt(r, seed.wrapping_add(i as i64)) - { - out.map.insert(*id, raid); + }; + if visit(k) { + removed.push(k); + match last { + Some(l) if l == self.n => { + self.null_key = false; + self.size -= 1; + } + Some(l) => { + wrapped.extend(self.shift_keys(l)); + self.size -= 1; + } + None => self.remove(k), } } } - out + removed } } @@ -808,35 +1512,45 @@ mod tests { use super::*; struct Level { - village: bool, - raiders: Vec, difficulty: i32, + village: bool, + loaded: bool, } impl RaidLevel for Level { fn difficulty(&self) -> i32 { self.difficulty } fn has_chunk_at(&self, _: [i32; 3]) -> bool { + self.loaded + } + fn has_chunks_at(&self, _: i32, _: i32, _: i32, _: i32) -> bool { true } - fn is_village(&self, _: [i32; 3]) -> bool { - self.village - } - fn village_sections_near(&self, _: [i32; 3]) -> Vec<[i32; 3]> { - Vec::new() - } - fn raiders(&self, _: i32) -> Vec { - self.raiders.clone() + fn sections_to_village(&self, _: [i32; 3]) -> i32 { + if self.village { 0 } else { 7 } } fn surface_height(&self, _: i32, _: i32) -> i32 { 64 } - fn is_ticking(&self, _: [i32; 3]) -> bool { + fn is_position_entity_ticking(&self, _: [i32; 3]) -> bool { true } - fn can_spawn_at(&self, _: [i32; 3]) -> bool { + fn ravager_can_spawn(&self, _: [i32; 3]) -> bool { true } + fn player(&self) -> Option { + None + } + } + fn level(difficulty: i32) -> Level { + Level { + difficulty, + village: true, + loaded: true, + } + } + fn nobody(_: &Raid, _: [i32; 3]) -> bool { + false } fn count(spawns: &[Spawn], kind: RaiderType) -> usize { spawns.iter().filter(|s| s.kind == kind).count() @@ -844,226 +1558,148 @@ mod tests { #[test] fn waves_per_difficulty() { - assert_eq!( - [0, 1, 2, 3].map(num_groups), - [0, 3, 5, 7], - "peaceful, easy, normal, hard" - ); - } - #[test] - fn first_wave_is_four_pillagers_plus_bonus() { - // Normal difficulty always adds one bonus roll (0 or 1) per - // pillager and vindicator slot: wave 1 has 4 pillagers and 0-1 more. - for seed in 0..50 { - let mut raid = Raid::new([0, 64, 0], 2, seed); - let w = raid.compose_wave(1, 2, false); - let pillagers = count(&w, RaiderType::Pillager); - assert!((4..=5).contains(&pillagers), "{pillagers}"); - assert!(count(&w, RaiderType::Vindicator) <= 1); - assert_eq!(count(&w, RaiderType::Ravager), 0); - assert_eq!(w.iter().filter(|s| s.leader).count(), 1); - } + assert_eq!(num_groups(0), 0); + assert_eq!(num_groups(1), 3); + assert_eq!(num_groups(2), 5); + assert_eq!(num_groups(3), 7); } #[test] fn ravagers_carry_riders_by_wave() { - // Wave 5 on normal: the ravager carries a pillager. - let mut raid = Raid::new([0, 64, 0], 2, 1); - let w = raid.compose_wave(5, 2, false); - let ravagers: Vec<_> = w.iter().filter(|s| s.kind == RaiderType::Ravager).collect(); - assert_eq!(ravagers.len(), 1); - assert_eq!(ravagers[0].rider, Some(RaiderType::Pillager)); - // Wave 7 on hard: an evoker rides the first ravager, vindicators the rest. - let mut raid = Raid::new([0, 64, 0], 3, 1); - let w = raid.compose_wave(7, 3, false); - let riders: Vec<_> = w + let mut raid = Raid::new([0, 64, 0], 3, 7); + let w5 = raid.compose_wave(5, 3, false); + assert!( + w5.iter() + .filter(|s| s.kind == RaiderType::Ravager) + .all(|s| s.rider == Some(RaiderType::Pillager)) + ); + let w7 = raid.compose_wave(7, 3, false); + let riders: Vec<_> = w7 .iter() .filter(|s| s.kind == RaiderType::Ravager) .map(|s| s.rider) .collect(); - assert!(riders.len() >= 2); assert_eq!(riders[0], Some(RaiderType::Evoker)); assert!( riders[1..] .iter() .all(|r| *r == Some(RaiderType::Vindicator)) ); - // Wave 4 has no ravager. - let mut raid = Raid::new([0, 64, 0], 3, 1); - assert_eq!( - count(&raid.compose_wave(4, 3, false), RaiderType::Ravager), - 0 - ); - } - #[test] - fn witches_arrive_from_wave_five_and_bonus_waves_reuse_the_last_row() { - let mut raid = Raid::new([0, 64, 0], 2, 3); - assert_eq!(count(&raid.compose_wave(3, 2, false), RaiderType::Witch), 0); - assert_eq!(count(&raid.compose_wave(4, 2, false), RaiderType::Witch), 3); - // Bonus wave of a normal raid: the wave-5 row (and a possible - // extra ravager). - let bonus = raid.compose_wave(6, 2, true); - assert_eq!(count(&bonus, RaiderType::Evoker), 1); - assert!((1..=2).contains(&count(&bonus, RaiderType::Ravager))); - assert!(count(&bonus, RaiderType::Witch) <= 1); + assert_eq!(count(&w7, RaiderType::Evoker), 2); } #[test] fn only_able_raiders_lead() { - let mut raid = Raid::new([0, 64, 0], 3, 9); - let w = raid.compose_wave(4, 3, false); - assert!( - w.iter() - .filter(|s| s.leader) - .all(|s| s.kind.can_be_leader()) - ); + let mut raid = Raid::new([0, 64, 0], 2, 1); + let w = raid.compose_wave(4, 2, false); assert_eq!(w.iter().filter(|s| s.leader).count(), 1); + assert!(w.iter().find(|s| s.leader).unwrap().kind.can_be_leader()); } #[test] fn omen_levels_stack_and_clamp() { let mut raid = Raid::new([0, 64, 0], 2, 1); - assert!(raid.absorb_omen(1)); - assert_eq!(raid.omen_level, 2); + assert!(raid.absorb_omen(0)); + assert_eq!(raid.omen_level, 1); raid.absorb_omen(4); - assert_eq!(raid.omen_level, MAX_OMEN_LEVEL); + assert_eq!(raid.omen_level, 5); assert_eq!(raid.enchant_odds(), 0.75); } #[test] - fn a_raid_counts_down_spawns_and_is_won() { - let level = Level { - village: true, - raiders: Vec::new(), - difficulty: 1, - }; - let mut raid = Raid::new([0, 64, 0], 1, 5); + fn a_raid_counts_down_then_spawns_a_wave() { + let l = level(2); + let mut raid = Raid::new([0, 64, 0], 2, 3); raid.absorb_omen(0); - let mut spawned = 0; - // 300 ticks of countdown, then the first wave. + let mut spawned = None; for _ in 0..400 { - for a in raid.tick(1, &level, true) { - if let Action::Spawn { wave, .. } = a { - spawned += 1; - assert_eq!(wave, 1); + for a in raid.tick(&l, &[], &nobody) { + if let Action::Spawn { wave, spawns, .. } = a { + spawned = Some((wave, spawns)); } } - if spawned > 0 { + if spawned.is_some() { break; } } - assert_eq!(spawned, 1); - assert!(raid.started && raid.groups_spawned == 1); + let (wave, spawns) = spawned.expect("a wave"); + assert_eq!(wave, 1); + assert!(count(&spawns, RaiderType::Pillager) >= 4); assert_eq!(raid.bar.progress, 1.0); - assert!(raid.total_health > 0.0); + assert!(raid.started); } #[test] - fn the_last_wave_cleared_wins_after_a_pause() { - let level = Level { - village: true, - raiders: Vec::new(), - difficulty: 1, - }; - let mut raid = Raid::new([0, 64, 0], 1, 5); - raid.started = true; - raid.groups_spawned = raid.num_groups; - raid.cooldown_ticks = 0; - let mut won = false; - for _ in 0..60 { - for a in raid.tick(1, &level, true) { - if let Action::Victory { amplifier, .. } = a { - won = true; - assert_eq!(amplifier, -1); - } - } - } - assert!(won && raid.is_victory()); - // The celebration lasts 600 ticks, then the raid stops. - for _ in 0..600 { - raid.tick(1, &level, true); - } - assert!(raid.is_stopped()); - } - #[test] - fn losing_the_village_loses_the_raid() { - let level = Level { - village: false, - raiders: Vec::new(), - difficulty: 2, - }; - let mut raid = Raid::new([0, 64, 0], 2, 5); - raid.started = true; - raid.groups_spawned = 2; - raid.tick(1, &level, true); + fn losing_the_village_after_a_wave_loses_the_raid() { + let mut l = level(2); + let mut raid = Raid::new([0, 64, 0], 2, 3); + raid.groups_spawned = 1; + l.village = false; + raid.tick(&l, &[], &nobody); assert!(raid.is_loss()); - // Before any wave, losing the village just cancels the raid. - let mut fresh = Raid::new([0, 64, 0], 2, 5); - fresh.tick(1, &level, true); + let mut fresh = Raid::new([0, 64, 0], 2, 3); + fresh.tick(&l, &[], &nobody); assert!(fresh.is_stopped()); } #[test] fn peaceful_stops_raids() { - let level = Level { - village: true, - raiders: Vec::new(), - difficulty: 0, - }; - let mut raid = Raid::new([0, 64, 0], 2, 5); - raid.tick(1, &level, true); + let mut raid = Raid::new([0, 64, 0], 2, 3); + raid.tick(&level(0), &[], &nobody); assert!(raid.is_stopped()); } #[test] - fn far_or_idle_raiders_leave() { - let raider = |id, x, no_action, outside| RaiderInfo { - id, - wave: 1, - health: 24.0, - position: [x, 64, 0], - age: 1000, - no_action_time: no_action, - ticks_outside: outside, - in_village: false, - }; - let level = Level { - village: true, - raiders: vec![ - raider(1, 500, 0, 0), - raider(2, 10, 3000, 29), - raider(3, 10, 0, 0), - ], - difficulty: 2, - }; - let mut raid = Raid::new([0, 64, 0], 2, 1); - raid.started = true; - raid.groups_spawned = 1; - raid.total_health = 72.0; - raid.ticks_active = 19; - let actions = raid.tick(1, &level, true); - assert!(actions.contains(&Action::Remove { id: 1 })); - assert!(actions.contains(&Action::Remove { id: 2 })); - assert!(!actions.contains(&Action::Remove { id: 3 })); - assert_eq!(raid.total_health, 24.0); + fn bar_progress_follows_java_clamp() { + let mut raid = Raid::new([0, 64, 0], 2, 3); + raid.update_bossbar(0.0); + assert!(raid.bar.progress.is_nan()); + raid.total_health = 48.0; + raid.update_bossbar(24.0); + assert_eq!(raid.bar.progress, 0.5); } #[test] fn raids_round_trip_through_nbt() { let mut raids = Raids::default(); - let (id, triggered) = raids.create_or_extend([10, 64, 20], 2, Some(2), 7); - assert_eq!(id, 2); + let (id, triggered) = raids.create_or_extend([10, 64, 10], 2, Some(1), 5); assert!(triggered); - raids.map.get_mut(&id).unwrap().add_hero([1, 2, 3, 4]); - let back = Raids::from_nbt(&raids.to_nbt(), 1); - let raid = back.get(2).unwrap(); - assert_eq!(raid.center, [10, 64, 20]); - assert_eq!(raid.omen_level, 3); - assert_eq!(raid.num_groups, 5); - assert_eq!(raid.heroes, vec![[1, 2, 3, 4]]); - assert_eq!(raid.status, Status::Ongoing); + assert_eq!(id, 2); + raids.get_mut(id).unwrap().add_hero([1, 2, 3, 4]); + let tag = raids.to_nbt(); + let back = Raids::from_nbt(&tag, 0); + assert_eq!(back.next_id, 2); + let r = back.get(id).unwrap(); + assert_eq!(r.omen_level, 2); + assert_eq!(r.heroes(), vec![[1, 2, 3, 4]]); + assert_eq!(back.to_nbt(), tag); } #[test] fn a_second_omen_extends_the_nearby_raid() { let mut raids = Raids::default(); let (a, _) = raids.create_or_extend([0, 64, 0], 2, Some(0), 1); - let (b, again) = raids.create_or_extend([20, 64, 20], 2, Some(1), 1); + let (b, triggered) = raids.create_or_extend([20, 64, 0], 2, Some(0), 2); assert_eq!(a, b); - assert!(again); - assert_eq!(raids.get(a).unwrap().omen_level, 3); - let (c, _) = raids.create_or_extend([300, 64, 0], 2, Some(0), 1); - assert_ne!(a, c); + assert!(triggered); + assert_eq!(raids.get(a).unwrap().omen_level, 2); + } + #[test] + fn fastutil_order_iterates_from_the_top_of_the_table() { + let mut o = IntOpenHashOrder::new(); + for k in 2..40 { + o.put(k); + } + let it = o.iter(); + assert_eq!(it.len(), 38); + let mut sorted = it.clone(); + sorted.sort(); + assert_eq!(sorted, (2..40).collect::>()); + let mut seen = Vec::new(); + let removed = o.iterate_removing(&mut |k| { + seen.push(k); + k % 3 == 0 + }); + assert_eq!(seen.len(), 38); + assert_eq!(o.iter().len(), 38 - removed.len()); + } + #[test] + fn the_centre_is_the_mean_of_nearby_points() { + assert_eq!(raid_center([0, 64, 0], &[]), [0, 64, 0]); + assert_eq!( + raid_center([0, 64, 0], &[[10, 64, 10], [11, 65, 10], [200, 64, 0]]), + [10, 64, 10] + ); } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRaidOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRaidOracle.java new file mode 100644 index 000000000..7458d7e5a --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRaidOracle.java @@ -0,0 +1,727 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.function.Predicate; +import net.minecraft.SharedConstants; +import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.nbt.*; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ClientboundSoundPacket; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.PlayerAdvancements; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.level.ServerBossEvent; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.stats.Stat; +import net.minecraft.tags.TagLoader; +import net.minecraft.util.Mth; +import net.minecraft.util.RandomSource; +import net.minecraft.world.BossEvent; +import net.minecraft.world.Difficulty; +import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.effect.MobEffect; +import net.minecraft.world.effect.MobEffectInstance; +import net.minecraft.world.effect.MobEffects; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.monster.PatrollingMonster; +import net.minecraft.world.entity.raid.Raid; +import net.minecraft.world.entity.raid.Raider; +import net.minecraft.world.entity.raid.Raids; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeManager; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.gamerules.GameRules; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.level.levelgen.PatrolSpawner; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.level.storage.LevelData; +import net.minecraft.world.phys.Vec3; + +/** + * Original oracle: pillager patrols and raids as vanilla runs them, on a + * stand-in ServerLevel built from boxes of blocks and light, one biome, + * village sections (the POI distance tracker's answer), unloaded and + * non-ticking chunks, and at most one player. Three modes: + * + * - patrol: PatrolSpawner.tick for some ticks with the level random seeded; + * finalizeSpawn reads a fixed "neutral" random (nextInt 0, nextFloat 0.75) + * so its own draws stay out of the spawner's sequence; + * - raid: Raids.tick over scripted ticks, with the raid's random seeded and + * scripted raider events (hurt, kill, move, idle, join, load, leave the + * level), omens through Raids.createOrExtendRaid, and world changes; + * - codec: Raids.CODEC decoding an SNBT tag with resultOrPartial (else a fresh + * Raids), then encoding it. + * + * Each case prints one line of events in a format the Rust fixture + * (raid_fixture) reproduces. + */ +public final class VanillaRaidOracle { + static Object unsafe; + static Method allocate, putObject, objectFieldOffset; + + static Object alloc(Class c) throws Exception { return allocate.invoke(unsafe, c); } + + static void put(Object target, Class owner, String field, Object value) throws Exception { + Field f = owner.getDeclaredField(field); + putObject.invoke(unsafe, target, (long) objectFieldOffset.invoke(unsafe, f), value); + } + + static Object get(Object target, Class owner, String field) throws Exception { + Field f = owner.getDeclaredField(field); + f.setAccessible(true); + return f.get(target); + } + + record Box(int x0, int y0, int z0, int x1, int y1, int z1) { + boolean has(int x, int y, int z) { return x >= x0 && x <= x1 && y >= y0 && y <= y1 && z >= z0 && z <= z1; } + static Box parse(String s) { + String[] p = s.split(","); + return new Box(Integer.parseInt(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2]), + Integer.parseInt(p[3]), Integer.parseInt(p[4]), Integer.parseInt(p[5])); + } + } + + /** finalizeSpawn's random: the same answer every time. */ + static final class Neutral implements RandomSource { + @Override public RandomSource fork() { return this; } + @Override public net.minecraft.world.level.levelgen.PositionalRandomFactory forkPositional() { throw new UnsupportedOperationException(); } + @Override public void setSeed(long seed) {} + @Override public int nextInt() { return 0; } + @Override public int nextInt(int bound) { return 0; } + @Override public long nextLong() { return 0L; } + @Override public boolean nextBoolean() { return false; } + @Override public float nextFloat() { return 0.75F; } + @Override public double nextDouble() { return 0.75; } + @Override public double nextGaussian() { return 0.0; } + } + + static final class Lvl extends ServerLevel { + Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } + RegistryAccess registries; + net.minecraft.server.MinecraftServer fake; + @Override public net.minecraft.server.MinecraftServer getServer() { return fake; } + List> blocks = new ArrayList<>(); + List> lights = new ArrayList<>(); + Holder biome; + int sky, block, darken; + Difficulty difficulty; + DimensionType dimensionType; + ResourceKey dimensionKey; + Set unloaded = new HashSet<>(); + Set noTicking = new HashSet<>(); + List villages = new ArrayList<>(); + List pois = new ArrayList<>(); + List entities = new ArrayList<>(); + List playerList = new ArrayList<>(); + net.minecraft.world.attribute.EnvironmentAttributeSystem attributes; + BiomeManager biomeManager; + GameRules rules; + RandomSource neutral = new Neutral(); + RandomSource main; + boolean finalizing, grouped; + long clock, inhabited; + float moon; + List log; + @Override public RegistryAccess registryAccess() { return registries; } + @Override public Difficulty getDifficulty() { return difficulty; } + @Override public long getGameTime() { return 0L; } + int next = 1; + @Override public int getNextEntityId() { return next++; } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); } + @Override public BlockState getBlockState(BlockPos pos) { + for (int i = blocks.size() - 1; i >= 0; i--) + if (blocks.get(i).getKey().has(pos.getX(), pos.getY(), pos.getZ())) return blocks.get(i).getValue(); + return Blocks.AIR.defaultBlockState(); + } + @Override public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); } + @Override public BlockGetter getChunkForCollisions(int chunkX, int chunkZ) { return this; } + int[] light(BlockPos pos) { + for (int i = lights.size() - 1; i >= 0; i--) + if (lights.get(i).getKey().has(pos.getX(), pos.getY(), pos.getZ())) return lights.get(i).getValue(); + return new int[] {sky, block}; + } + @Override public int getBrightness(LightLayer layer, BlockPos pos) { int[] l = light(pos); return layer == LightLayer.SKY ? l[0] : l[1]; } + @Override public int getRawBrightness(BlockPos pos, int darkening) { int[] l = light(pos); return Math.max(l[1], l[0] - darkening); } + @Override public int getSkyDarken() { return darken; } + @Override public boolean isBrightOutside() { return !dimensionType.hasFixedTime() && darken < 4; } + @Override public boolean hasChunk(int x, int z) { return !unloaded.contains(ChunkPos.pack(x, z)); } + @Override public boolean isPositionEntityTicking(BlockPos pos) { + long key = ChunkPos.pack(pos.getX() >> 4, pos.getZ() >> 4); + return !unloaded.contains(key) && !noTicking.contains(key); + } + @Override public int getHeight(Heightmap.Types type, int x, int z) { + if (!hasChunk(x >> 4, z >> 4)) return getMinY(); + for (int y = getMaxY(); y >= getMinY(); y--) + if (type.isOpaque().test(getBlockState(new BlockPos(x, y, z)))) return y + 1; + return getMinY(); + } + @Override public int sectionsToVillage(SectionPos pos) { + int best = 7; + for (int[] v : villages) + best = Math.min(best, Math.max(Math.abs(v[0] - pos.x()), Math.max(Math.abs(v[1] - pos.y()), Math.abs(v[2] - pos.z())))); + return best; + } + @Override public DimensionType dimensionType() { return dimensionType; } + @Override public ResourceKey dimension() { return dimensionKey; } + @Override public Holder getBiome(BlockPos pos) { return biome; } + @Override public BiomeManager getBiomeManager() { return biomeManager; } + @Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; } + @Override public GameRules getGameRules() { return rules; } + net.minecraft.world.level.border.WorldBorder border = new net.minecraft.world.level.border.WorldBorder(); + @Override public net.minecraft.world.level.border.WorldBorder getWorldBorder() { return border; } + net.minecraft.world.entity.ai.village.poi.PoiManager poi; + @Override public net.minecraft.world.entity.ai.village.poi.PoiManager getPoiManager() { return poi; } + @Override public RandomSource getRandom() { return finalizing ? neutral : main; } + @Override public DifficultyInstance getCurrentDifficultyAt(BlockPos pos) { + // The patrol spawner asks once for its group size; later asks come from spawnPatrolMember, right before finalizeSpawn. + if (grouped) finalizing = true; + grouped = true; + boolean loaded = hasChunk(pos.getX() >> 4, pos.getZ() >> 4); + return new DifficultyInstance(difficulty, clock, loaded ? inhabited : 0L, loaded ? moon : 0.0F); + } + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override public List players() { return playerList; } + @Override public List getPlayers(Predicate filter) { + List out = new ArrayList<>(); + for (ServerPlayer p : playerList) if (filter.test(p)) out.add(p); + return out; + } + @Override public Entity getEntity(UUID uuid) { + for (ServerPlayer p : playerList) if (p.getUUID().equals(uuid)) return p; + for (Entity e : entities) if (e.getUUID().equals(uuid)) return e; + return null; + } + @Override public boolean addFreshEntity(Entity entity) { + entities.add(entity); + finalizing = false; + return true; + } + @Override public void addFreshEntityWithPassengers(Entity entity) { + for (Entity e : entity.getSelfAndPassengers().toList()) { + addFreshEntity(e); + spawned(e); + } + } + @Override public void gameEvent(Entity source, Holder event, Vec3 pos) {} + @Override public void gameEvent(Holder event, Vec3 pos, net.minecraft.world.level.gameevent.GameEvent.Context context) {} + @Override public void broadcastEntityEvent(Entity entity, byte event) {} + + void spawned(Entity e) { + String type = BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()).toString(); + StringBuilder s = new StringBuilder("spawn " + type + " " + Mth.floor(e.getX()) + " " + Mth.floor(e.getY()) + " " + Mth.floor(e.getZ())); + if (e.getVehicle() != null) s.append(" rider"); + if (e instanceof PatrollingMonster m) { + boolean banner = !m.getItemBySlot(EquipmentSlot.HEAD).isEmpty(); + s.append(m.isPatrolLeader() ? " leader" : "").append(banner ? " banner" : ""); + try { if ((boolean) isPatrolling.invoke(m)) s.append(" patrolling"); } catch (Exception ex) { throw new RuntimeException(ex); } + BlockPos t = m.getPatrolTarget(); + if (t != null) { + boolean origin = t.getY() == 0 && t.getX() >= -500 && t.getX() < 500 && t.getZ() >= -500 && t.getZ() < 500; + s.append(origin ? " target" : " target-elsewhere"); + } + } + if (e instanceof Raider r) s.append(" wave=").append(r.getWave()).append(r.canJoinRaid() ? " join" : ""); + log.add(s.toString()); + } + } + + static Method isPatrolling; + + static final class Adv extends PlayerAdvancements { + Adv() { super(null, null, null, null, null); } + @Override public Map getTriggerMapForType( + net.minecraft.advancements.triggers.CriterionTrigger type) { return null; } + } + + static final class Conn extends ServerGamePacketListenerImpl { + Conn() { super(null, null, null, null); } + List log; + @Override public void send(Packet packet) { + if (packet instanceof ClientboundSoundPacket p) + log.add("horn " + p.getSeed() + " " + bits(p.getX()) + " " + bits(p.getY()) + " " + bits(p.getZ())); + } + } + + static final class OraclePlayer extends ServerPlayer { + OraclePlayer() { super(null, null, null, null); } + GameType mode; + boolean alive; + int omen = -1; + List log; + PlayerAdvancements adv; + @Override public boolean isSpectator() { return mode == GameType.SPECTATOR; } + @Override public boolean isCreative() { return mode == GameType.CREATIVE; } + @Override public GameType gameMode() { return mode; } + @Override public boolean isAlive() { return alive; } + @Override public MobEffectInstance getEffect(Holder effect) { + return effect == MobEffects.RAID_OMEN && omen >= 0 ? new MobEffectInstance(MobEffects.RAID_OMEN, 600, omen) : null; + } + @Override public boolean addEffect(MobEffectInstance effect, Entity source) { + log.add("effect " + BuiltInRegistries.MOB_EFFECT.getKey(effect.getEffect().value()) + " " + effect.getDuration() + " " + effect.getAmplifier() + + " " + effect.isAmbient() + " " + effect.isVisible() + " " + effect.showIcon()); + return true; + } + @Override public void awardStat(Stat stat, int count) { log.add("stat " + stat.getValue()); } + @Override public PlayerAdvancements getAdvancements() { return adv; } + } + + static String bits(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); } + static String bits(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); } + + static Field raidMap, raidRandom, raidEvent, raidsField, celebrationTicks, waveSpawnPos, noActionTime, removalReason, groupToLeader; + + static String raidState(Raids raids, OraclePlayer player) throws Exception { + @SuppressWarnings("unchecked") + var map = (it.unimi.dsi.fastutil.ints.Int2ObjectMap) raidMap.get(raids); + StringBuilder s = new StringBuilder(); + for (var entry : map.int2ObjectEntrySet()) { + Raid r = entry.getValue(); + ServerBossEvent bar = (ServerBossEvent) raidEvent.get(r); + String name = bar.getName().getString(); + @SuppressWarnings("unchecked") + Optional wave = (Optional) waveSpawnPos.get(r); + @SuppressWarnings("unchecked") + Map leaders = (Map) groupToLeader.get(r); + s.append(" ; r").append(entry.getIntKey()) + .append(" ").append(r.isStopped() ? "stopped" : r.isVictory() ? "victory" : r.isLoss() ? "loss" : "ongoing") + .append(" act=").append(r.isActive() ? 1 : 0) + .append(" st=").append(r.isStarted() ? 1 : 0) + .append(" om=").append(r.getRaidOmenLevel()) + .append(" gs=").append(r.getGroupsSpawned()) + .append(" th=").append(bits(r.getTotalHealth())) + .append(" alive=").append(r.getTotalRaidersAlive()) + .append(" c=").append(r.getCenter().getX()).append(",").append(r.getCenter().getY()).append(",").append(r.getCenter().getZ()) + .append(" wp=").append(wave.map(p -> p.getX() + "," + p.getY() + "," + p.getZ()).orElse("-")) + .append(" cel=").append(celebrationTicks.getInt(r)) + .append(" lead=").append(new TreeSet<>(leaders.keySet())) + .append(" bar=").append(bits(bar.getProgress())).append(",").append(name).append(",").append(bar.isVisible() ? 1 : 0) + .append(",").append(player != null && bar.getPlayers().contains(player) ? 1 : 0); + } + // Ticks active, cooldown and post-raid ticks through the codec (no getters). + for (var entry : map.int2ObjectEntrySet()) { + CompoundTag t = (CompoundTag) Raid.MAP_CODEC.codec().encodeStart(NbtOps.INSTANCE, entry.getValue()).getOrThrow(); + s.append(" ; t").append(entry.getIntKey()).append(" ").append(t.getLongOr("ticks_active", -1)).append(" ") + .append(t.getIntOr("cooldown_ticks", -1)).append(" ").append(t.getIntOr("post_raid_ticks", -1)); + } + return s.toString(); + } + + /** NBT as canonical text: sorted compound keys, exact numbers. */ + static String canon(Tag tag) { + return switch (tag) { + case ByteTag b -> b.value() + "b"; + case ShortTag v -> v.value() + "s"; + case IntTag v -> Integer.toString(v.value()); + case LongTag v -> v.value() + "L"; + case FloatTag v -> "f" + bits(v.value()); + case DoubleTag v -> "d" + bits(v.value()); + case StringTag v -> "\"" + v.value() + "\""; + case ByteArrayTag v -> { StringBuilder s = new StringBuilder("[B;"); for (byte x : v.getAsByteArray()) s.append(x).append(","); yield s + "]"; } + case IntArrayTag v -> { StringBuilder s = new StringBuilder("[I;"); for (int x : v.getAsIntArray()) s.append(x).append(","); yield s + "]"; } + case LongArrayTag v -> { StringBuilder s = new StringBuilder("[L;"); for (long x : v.getAsLongArray()) s.append(x).append(","); yield s + "]"; } + case ListTag v -> { StringBuilder s = new StringBuilder("["); for (Tag x : v) s.append(canon(x)).append(","); yield s + "]"; } + case CompoundTag v -> { + StringBuilder s = new StringBuilder("{"); + for (String k : new TreeSet<>(v.keySet())) s.append(k).append(":").append(canon(v.get(k))).append(","); + yield s + "}"; + } + default -> "?"; + }; + } + + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + unsafe = unsafeField.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class); + objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class); + var repo = ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected()); + var layers = RegistryLayer.createRegistryAccess(); + var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC)); + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world); + var loaded = net.minecraft.server.ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join(); + HolderLookup.Provider lookup = loaded.lookupWithUpdatedTags(); + var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup); + staticTags.forEach(Registry.PendingTags::apply); + components.forEach(net.minecraft.core.component.DataComponentInitializers.PendingComponents::apply); + RegistryAccess access = loaded.layers().compositeAccess(); + var biomes = access.lookupOrThrow(Registries.BIOME); + var dimensions = access.lookupOrThrow(Registries.DIMENSION_TYPE); + var blockLookup = access.lookupOrThrow(Registries.BLOCK); + + isPatrolling = PatrollingMonster.class.getDeclaredMethod("isPatrolling"); + isPatrolling.setAccessible(true); + raidMap = Raids.class.getDeclaredField("raidMap"); raidMap.setAccessible(true); + raidRandom = Raid.class.getDeclaredField("random"); raidRandom.setAccessible(true); + raidEvent = Raid.class.getDeclaredField("raidEvent"); raidEvent.setAccessible(true); + celebrationTicks = Raid.class.getDeclaredField("celebrationTicks"); celebrationTicks.setAccessible(true); + waveSpawnPos = Raid.class.getDeclaredField("waveSpawnPos"); waveSpawnPos.setAccessible(true); + groupToLeader = Raid.class.getDeclaredField("groupToLeaderMap"); groupToLeader.setAccessible(true); + noActionTime = LivingEntity.class.getDeclaredField("noActionTime"); noActionTime.setAccessible(true); + removalReason = Entity.class.getDeclaredField("removalReason"); removalReason.setAccessible(true); + + var server = (net.minecraft.server.MinecraftServer) alloc(net.minecraft.server.dedicated.DedicatedServer.class); + put(server, net.minecraft.server.MinecraftServer.class, "debugSubscribers", alloc(net.minecraft.util.debug.ServerDebugSubscribers.class)); + Lvl level = (Lvl) alloc(Lvl.class); + level.fake = server; + put(level, ServerLevel.class, "server", server); + level.registries = access; + level.blocks = new ArrayList<>(); + level.lights = new ArrayList<>(); + level.unloaded = new HashSet<>(); + level.noTicking = new HashSet<>(); + level.villages = new ArrayList<>(); + level.pois = new ArrayList<>(); + level.entities = new ArrayList<>(); + level.playerList = new ArrayList<>(); + level.neutral = new Neutral(); + level.border = new net.minecraft.world.level.border.WorldBorder(); + level.biomeManager = new BiomeManager((x, y, z) -> level.biome, 0L) { + @Override public Holder getBiome(BlockPos pos) { return level.biome; } + @Override public Holder getBiome(int x, int y, int z) { return level.biome; } + @Override public Holder getNoiseBiomeAtPosition(double x, double y, double z) { return level.biome; } + @Override public Holder getNoiseBiomeAtPosition(BlockPos pos) { return level.biome; } + @Override public Holder getNoiseBiomeAtQuart(int x, int y, int z) { return level.biome; } + }; + // The village points of interest for createOrExtendRaid. + var poi = (net.minecraft.world.entity.ai.village.poi.PoiManager) alloc(PoiStub.class); + ((PoiStub) poi).level = level; + level.poi = poi; + Field uuidField = Entity.class.getDeclaredField("uuid"); + uuidField.setAccessible(true); + Field entityId = Entity.class.getDeclaredField("id"); + entityId.setAccessible(true); + + List lines = Files.readAllLines(Path.of(args[0])); + try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) { + for (String raw : lines) { + if (raw.isBlank()) continue; + Map c = new LinkedHashMap<>(); + for (String token : raw.trim().split("\\s+")) { + int eq = token.indexOf('='); + if (eq < 0) c.put("name", token); else c.put(token.substring(0, eq), token.substring(eq + 1)); + } + List log = new ArrayList<>(); + level.log = log; + try { + String mode = c.getOrDefault("mode", "raid"); + if (mode.equals("codec")) { + String snbt = new String(java.util.HexFormat.of().parseHex(c.get("snbt")), StandardCharsets.UTF_8); + Tag tag = TagParser.parseCompoundFully(snbt); + Optional parsed = Raids.CODEC.parse(NbtOps.INSTANCE, tag).resultOrPartial(); + Raids raids = parsed.orElseGet(Raids::new); + log.add(parsed.isPresent() ? "decoded" : "fresh"); + log.add(canon(Raids.CODEC.encodeStart(NbtOps.INSTANCE, raids).getOrThrow())); + // The decoded raids' bars. + @SuppressWarnings("unchecked") + var map = (it.unimi.dsi.fastutil.ints.Int2ObjectMap) raidMap.get(raids); + for (var e : map.int2ObjectEntrySet()) { + ServerBossEvent bar = (ServerBossEvent) raidEvent.get(e.getValue()); + log.add("bar " + e.getIntKey() + " " + bits(bar.getProgress()) + " " + (bar.isVisible() ? 1 : 0) + " " + (raids.isDirty() ? 1 : 0)); + } + w.println(c.get("name") + " " + String.join(" ; ", log)); + continue; + } + level.dimensionKey = ResourceKey.create(Registries.DIMENSION, Identifier.parse(c.getOrDefault("dim", "minecraft:overworld"))); + level.dimensionType = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, level.dimensionKey.identifier())).value(); + level.blocks.clear(); + for (int i = 0; c.containsKey("k" + i); i++) { + String[] p = c.get("k" + i).split("/", 2); + level.blocks.add(Map.entry(Box.parse(p[0]), net.minecraft.commands.arguments.blocks.BlockStateParser.parseForBlock(blockLookup, p[1], false).blockState())); + } + level.lights.clear(); + for (int i = 0; c.containsKey("l" + i); i++) { + String[] p = c.get("l" + i).split("/", 2); + String[] v = p[1].split(","); + level.lights.add(Map.entry(Box.parse(p[0]), new int[] {Integer.parseInt(v[0]), Integer.parseInt(v[1])})); + } + level.biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(c.getOrDefault("biome", "minecraft:plains")))); + level.sky = Integer.parseInt(c.getOrDefault("sky", "15")); + level.block = Integer.parseInt(c.getOrDefault("light", "0")); + level.darken = Integer.parseInt(c.getOrDefault("darken", "0")); + level.difficulty = Difficulty.byName(c.getOrDefault("difficulty", "normal")); + level.clock = Long.parseLong(c.getOrDefault("clock", "200000")); + level.inhabited = Long.parseLong(c.getOrDefault("inhabited", "0")); + level.moon = Float.parseFloat(c.getOrDefault("moon", "0.0")); + level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags()); + level.rules.set(GameRules.SPAWN_PATROLS, !c.getOrDefault("patrols", "1").equals("0"), null); + level.rules.set(GameRules.RAIDS, !c.getOrDefault("raids", "1").equals("0"), null); + var clocks = (net.minecraft.world.clock.ClockManager) def -> new net.minecraft.world.clock.ClockInstance() { + @Override public long totalTicks() { return level.clock; } + @Override public float partialTick() { return 0.0F; } + @Override public float rate() { return 1.0F; } + @Override public boolean isPaused() { return false; } + }; + var attrs = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addStaticLayers(level); + level.dimensionType.timelines().forEach(t -> attrs.addTimelineLayer(t, clocks)); + level.attributes = attrs.build(); + level.unloaded.clear(); + for (String key : new String[] {"unloaded", "noticking"}) { + if (!c.containsKey(key)) continue; + for (String u : c.get(key).split(";")) { + String[] p = u.split(","); + (key.equals("unloaded") ? level.unloaded : level.noTicking).add(ChunkPos.pack(Integer.parseInt(p[0]), Integer.parseInt(p[1]))); + } + } + if (!c.containsKey("noticking")) level.noTicking.clear(); + level.villages.clear(); + if (c.containsKey("vil")) for (String v : c.get("vil").split(";")) { + String[] p = v.split(","); + level.villages.add(new int[] {Integer.parseInt(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2])}); + } + level.pois.clear(); + if (c.containsKey("poi")) for (String v : c.get("poi").split(";")) { + String[] p = v.split(","); + level.pois.add(new BlockPos(Integer.parseInt(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2]))); + } + level.entities.clear(); + level.next = 1; + level.playerList.clear(); + level.finalizing = false; + level.grouped = false; + level.main = RandomSource.create(Long.parseLong(c.getOrDefault("seed", "0"))); + put(level, Level.class, "random", level.main); + Raids raids = new Raids(); + put(level, ServerLevel.class, "raids", raids); + OraclePlayer player = null; + Conn conn = (Conn) alloc(Conn.class); + conn.log = log; + if (c.containsKey("p0")) { + String[] p = c.get("p0").split("/"); + String[] v = p[0].split(","); + player = (OraclePlayer) alloc(OraclePlayer.class); + player.mode = GameType.byName(p.length > 1 ? p[1] : "survival"); + player.alive = true; + player.log = log; + player.adv = (PlayerAdvancements) alloc(Adv.class); + player.connection = conn; + entityId.setInt(player, 100000); + uuidField.set(player, new UUID(0x1234L, 0x5678L)); + put(player, Entity.class, "level", level); + setPosition(player, Double.parseDouble(v[0]), Double.parseDouble(v[1]), Double.parseDouble(v[2])); + level.playerList.add(player); + } + int ticks = Integer.parseInt(c.getOrDefault("ticks", "1")); + if (mode.equals("patrol")) { + PatrolSpawner spawner = new PatrolSpawner(); + Field next = PatrolSpawner.class.getDeclaredField("nextTick"); + next.setAccessible(true); + next.setInt(spawner, Integer.parseInt(c.getOrDefault("next", "0"))); + boolean enemies = !c.getOrDefault("enemies", "1").equals("0"); + for (int t = 0; t < ticks; t++) { + level.grouped = false; + level.finalizing = false; + spawner.tick(level, enemies); + } + log.add("next " + next.getInt(spawner) + " " + level.main.nextInt(1000)); + w.println(c.get("name") + " " + String.join(" ; ", log)); + continue; + } + // raid: the first omen makes the raid at its position (village centre from the POIs). + level.main = level.neutral; + put(level, Level.class, "random", level.neutral); + level.finalizing = true; + long seed = Long.parseLong(c.getOrDefault("rseed", "1")); + List tracked = new ArrayList<>(); + Set seeded = Collections.newSetFromMap(new IdentityHashMap<>()); + Map> events = new TreeMap<>(); + for (int i = 0; c.containsKey("ev" + i); i++) { + String[] p = c.get("ev" + i).split(":", 2); + events.computeIfAbsent(p[0], k -> new ArrayList<>()).add(p[1]); + } + String lastState = ""; + for (int t = 0; t <= ticks; t++) { + int before = level.entities.size(); + for (String ev : events.getOrDefault(Integer.toString(t), List.of())) { + String[] a = ev.split(":"); + log.add("ev " + ev); + if (Set.of("hurt", "kill", "move", "age", "idle", "gone", "discard").contains(a[0]) && Integer.parseInt(a[1]) >= tracked.size()) { + log.add("noraider"); + continue; + } + if (a[0].equals("killall") || a[0].equals("hurtall")) { + for (int i = 0; i < tracked.size(); i++) { + Raider r = tracked.get(i); + if (r.getCurrentRaid() == null || r.isRemoved()) continue; + if (a[0].equals("hurtall")) { + if (r.hasActiveRaid()) r.getCurrentRaid().updateBossbar(); + r.setHealth(r.getHealth() - Float.parseFloat(a[1])); + continue; + } + Raid raid = r.getCurrentRaid(); + if (r.isPatrolLeader()) raid.removeLeader(r.getWave()); + if (a.length > 1 && player != null) raid.addHeroOfTheVillage(player); + raid.removeFromRaid(level, r, false); + r.setHealth(0.0F); + removalReason.set(r, Entity.RemovalReason.KILLED); + level.entities.remove(r); + } + continue; + } + switch (a[0]) { + case "omen" -> { + if (player == null) throw new IllegalStateException("omen needs p0"); + String[] v = a[2].split(","); + setPosition(player, Integer.parseInt(v[0]) + 0.5, Integer.parseInt(v[1]), Integer.parseInt(v[2]) + 0.5); + player.omen = Integer.parseInt(a[1]); + Raid r = raids.createOrExtendRaid(player, player.blockPosition()); + player.omen = -1; + if (r == null) log.add("noraid"); + else if (seeded.add(r)) { + int id = raids.getId(r).orElse(-1); + raidRandom.set(r, RandomSource.create(seed + id * 1000L)); + } + } + case "setomen" -> { + Raid r = level.getRaidAt(player.blockPosition()); + if (r != null) r.setRaidOmenLevel(Integer.parseInt(a[1])); + } + case "stop" -> { + Raid r = level.getRaidAt(player.blockPosition()); + if (r != null) r.stop(); + } + case "pmove" -> { + String[] v = a[1].split(","); + setPosition(player, Double.parseDouble(v[0]), Double.parseDouble(v[1]), Double.parseDouble(v[2])); + } + case "pdead" -> player.alive = false; + case "palive" -> player.alive = true; + case "diff" -> level.difficulty = Difficulty.byName(a[1]); + case "rules" -> level.rules.set(GameRules.RAIDS, a[1].equals("1"), null); + case "unload" -> level.unloaded.add(chunk(a[1])); + case "load" -> level.unloaded.remove(chunk(a[1])); + case "notick" -> level.noTicking.add(chunk(a[1])); + case "tick" -> level.noTicking.remove(chunk(a[1])); + case "vil" -> level.villages.add(ints(a[1])); + case "unvil" -> level.villages.removeIf(v -> Arrays.equals(v, ints(a[1]))); + case "hurt" -> { + Raider r = tracked.get(Integer.parseInt(a[1])); + if (r.hasActiveRaid()) r.getCurrentRaid().updateBossbar(); + r.setHealth(r.getHealth() - Float.parseFloat(a[2])); + } + case "kill" -> { + Raider r = tracked.get(Integer.parseInt(a[1])); + Raid raid = r.getCurrentRaid(); + if (raid != null) { + if (r.isPatrolLeader()) raid.removeLeader(r.getWave()); + if (a.length > 2 && player != null) raid.addHeroOfTheVillage(player); + raid.removeFromRaid(level, r, false); + } + r.setHealth(0.0F); + removalReason.set(r, Entity.RemovalReason.KILLED); + level.entities.remove(r); + } + case "move" -> { + String[] v = a[2].split(","); + tracked.get(Integer.parseInt(a[1])).setPos(Integer.parseInt(v[0]) + 0.5, Integer.parseInt(v[1]), Integer.parseInt(v[2]) + 0.5); + } + case "age" -> tracked.get(Integer.parseInt(a[1])).tickCount = Integer.parseInt(a[2]); + case "idle" -> noActionTime.setInt(tracked.get(Integer.parseInt(a[1])), Integer.parseInt(a[2])); + case "gone" -> level.entities.remove(tracked.get(Integer.parseInt(a[1]))); + case "discard" -> removalReason.set(tracked.get(Integer.parseInt(a[1])), Entity.RemovalReason.DISCARDED); + case "join", "loadmob" -> { + EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(a[1])); + Raider r = (Raider) type.create(level, EntitySpawnReason.LOAD); + String[] v = a[2].split(","); + r.setPos(Integer.parseInt(v[0]) + 0.5, Integer.parseInt(v[1]), Integer.parseInt(v[2]) + 0.5); + level.entities.add(r); + tracked.add(r); + if (a[0].equals("join")) { + r.setCanJoinRaid(true); + Raid near = level.getRaidAt(r.blockPosition()); + if (near != null && Raids.canJoinRaid(r)) near.joinRaid(level, near.getGroupsSpawned(), r, null, true); + } else { + // readAdditionalSaveData: wave, leader, then the raid by id. + int wave = Integer.parseInt(a[3]); + r.setWave(wave); + if (a.length > 4) r.setPatrolLeader(true); + Raid raid = raids.get(Integer.parseInt(a.length > 5 ? a[5] : "2")); + r.setCurrentRaid(raid); + if (raid != null) { + raid.addWaveMob(level, wave, r, false); + if (r.isPatrolLeader()) raid.setLeader(wave, r); + } + } + } + default -> throw new IllegalArgumentException("event " + a[0]); + } + } + if (t == 0) continue; + Map raidOf = new IdentityHashMap<>(); + Map outside = new IdentityHashMap<>(); + for (Raider r : tracked) { raidOf.put(r, r.getCurrentRaid()); outside.put(r, r.getTicksOutsideRaid()); } + before = level.entities.size(); + raids.tick(level); + for (Entity e : level.entities.subList(before, level.entities.size())) if (e instanceof Raider r) tracked.add(r); + for (int i = 0; i < tracked.size(); i++) { + Raider r = tracked.get(i); + if (raidOf.containsKey(r) && raidOf.get(r) != null && r.getCurrentRaid() == null) log.add("leave " + i); + if (outside.containsKey(r) && outside.get(r) != r.getTicksOutsideRaid()) log.add("out " + i + " " + r.getTicksOutsideRaid()); + } + String state = raidState(raids, player); + String key = state.replaceAll(" ; t\\d+ [^;]*", ""); + if (!key.equals(lastState) || t % 1000 == 0 || t == ticks) log.add("t" + t + state); + lastState = key; + } + w.println(c.get("name") + " " + String.join(" ; ", log)); + } catch (Throwable t) { + Throwable cause = t; + while ((cause instanceof InvocationTargetException || cause instanceof RuntimeException && cause.getCause() != null) && cause.getCause() != null) cause = cause.getCause(); + StringBuilder line = new StringBuilder(c.get("name") + " error " + cause); + if (System.getenv("ORACLE_TRACE") != null) for (var frame : cause.getStackTrace()) line.append("\n at ").append(frame); + w.println(line); + } + } + } + System.exit(0); + } + + static long chunk(String s) { String[] p = s.split(","); return ChunkPos.pack(Integer.parseInt(p[0]), Integer.parseInt(p[1])); } + static int[] ints(String s) { return Arrays.stream(s.split(",")).mapToInt(Integer::parseInt).toArray(); } + + static void setPosition(Entity e, double x, double y, double z) throws Exception { + put(e, Entity.class, "position", new Vec3(x, y, z)); + put(e, Entity.class, "blockPosition", BlockPos.containing(x, y, z)); + } + + /** The village points of interest: all occupied, in the order given. */ + static final class PoiStub extends net.minecraft.world.entity.ai.village.poi.PoiManager { + PoiStub() { super(null, null, null, false, null, null, null); } + Lvl level; + @Override public java.util.stream.Stream getInSquare( + Predicate> predicate, BlockPos center, int radius, + net.minecraft.world.entity.ai.village.poi.PoiManager.Occupancy occupancy) { + var type = BuiltInRegistries.POINT_OF_INTEREST_TYPE.getOrThrow(net.minecraft.world.entity.ai.village.poi.PoiTypes.MEETING); + List out = new ArrayList<>(); + for (BlockPos p : level.pois) + if (Math.abs(p.getX() - center.getX()) <= radius && Math.abs(p.getZ() - center.getZ()) <= radius) + out.add(new net.minecraft.world.entity.ai.village.poi.PoiRecord(p, type, () -> {})); + return out.stream(); + } + } +} diff --git a/tools/test_raid_parity.py b/tools/test_raid_parity.py new file mode 100644 index 000000000..1aef07ec6 --- /dev/null +++ b/tools/test_raid_parity.py @@ -0,0 +1,378 @@ +#!/usr/bin/env python3 +"""Compare pillager patrols, raids and the raids saved data with vanilla. + +Java (VanillaRaidOracle) runs vanilla's PatrolSpawner, Raids/Raid and +Raids.CODEC on a stand-in ServerLevel built from each case: boxes of blocks and +light, one biome, village sections (the point of interest distance tracker), +village points of interest, unloaded and non-ticking chunks, the overworld +clock, local difficulty inputs and at most one player. Rust (raid_fixture) runs +horizon_client::patrol and horizon_client::raid on the same world. Modes: + +- patrol: PatrolSpawner.tick over many ticks (countdown, daylight, the one in + five draw, the player, village distance, chunk and environment attribute + checks, group size from the local difficulty, the members' heightmap + positions and spawn rules, leader, banner and target), then the next draw of + the level random, which pins every draw in between; +- raid: Raids.tick over scripted ticks: omens through createOrExtendRaid (the + village centre from points of interest, the omen absorbed, the raid trigger + stat), the countdown and its cached spawn position, wave composition by + difficulty and bonus wave, findRandomSpawnPos, joining, leaders and riders, + the boss bar (progress bits, title, visibility, the player), the horn with + its seed and position, raiders leaving (far, gone, removed, idle outside the + village), hurt, killed, joining and loaded raiders, victory with Hero of the + Village, loss when the village goes, the celebration, peaceful, the raids + rule, unloaded and non-ticking chunks and the timeout; +- codec: Raids.CODEC decoding generated and mutated raids.dat data (missing, + mistyped and partly broken fields, number type conversions, duplicate ids) + with resultOrPartial, then encoding it back. + +finalizeSpawn runs with a fixed random in the oracle (the patrol spawner's own +draws are compared); raid buffs draw from each raider's unseeded random and +are not compared. A patrol leader's target is drawn from the pillager's +unseeded random; only that it lies around the world origin is compared. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +GROUND = ['minecraft:grass_block', 'minecraft:dirt', 'minecraft:sand', 'minecraft:stone', 'minecraft:snow_block', + 'minecraft:podzol', 'minecraft:mycelium', 'minecraft:gravel', 'minecraft:red_sand', 'minecraft:moss_block'] +ODD = ['minecraft:water', 'minecraft:lava', 'minecraft:oak_leaves', 'minecraft:magma_block', 'minecraft:ice', + 'minecraft:glass', 'minecraft:bedrock', 'minecraft:snow[layers=1]', 'minecraft:snow[layers=8]', + 'minecraft:powder_snow', 'minecraft:oak_slab[type=bottom]', 'minecraft:oak_slab[type=top]', 'minecraft:barrier', + 'minecraft:short_grass', 'minecraft:rail', 'minecraft:cobweb', 'minecraft:oak_fence', 'minecraft:scaffolding', + 'minecraft:sweet_berry_bush', 'minecraft:fire', 'minecraft:spawner', 'minecraft:white_carpet'] +BIOMES = ['minecraft:plains', 'minecraft:desert', 'minecraft:mushroom_fields', 'minecraft:forest', 'minecraft:snowy_plains', + 'minecraft:taiga', 'minecraft:savanna', 'minecraft:deep_dark', 'minecraft:river', 'minecraft:jungle'] +DIFFICULTIES = ['peaceful', 'easy', 'normal', 'hard'] +RAIDERS = ['pillager', 'vindicator', 'evoker', 'witch', 'ravager'] + + +def box(x0, y0, z0, x1, y1, z1): + return f'{x0},{y0},{z0},{x1},{y1},{z1}' + + +def terrain(rng, w, cx, cz, top=63, span=220): + """Ground boxes around (cx, cz): a base with rises, dips, water and odd blocks.""" + ground = rng.choice(GROUND) + k = [f'{box(cx - span, -64, cz - span, cx + span, top, cz + span)}/{ground}'] + for _ in range(rng.randrange(0, 14)): + x, z = cx + rng.randrange(-span, span), cz + rng.randrange(-span, span) + sx, sz = rng.randrange(1, 30), rng.randrange(1, 30) + kind = rng.random() + if kind < 0.3: + h = top + rng.randrange(1, 12) if rng.random() < 0.8 else top + rng.randrange(100, 140) + k.append(f'{box(x, top + 1, z, x + sx, h, z + sz)}/{rng.choice(GROUND)}') + elif kind < 0.55: + d = top - rng.randrange(1, 8) + k.append(f'{box(x, d, z, x + sx, top, z + sz)}/minecraft:water') + elif kind < 0.65: + k.append(f'{box(x, top - rng.randrange(1, 120), z, x + sx, top, z + sz)}/minecraft:air') + else: + y = top + 1 + rng.randrange(0, 3) + k.append(f'{box(x, y, z, x + sx, y + rng.randrange(0, 3), z + sz)}/{rng.choice(ODD)}') + for i, v in enumerate(k): + w[f'k{i}'] = v + + +def lights(rng, w, cx, cz, span=80): + n = 0 + for _ in range(rng.randrange(0, 6)): + x, z = cx + rng.randrange(-span, span), cz + rng.randrange(-span, span) + w[f'l{n}'] = f'{box(x, -64, z, x + rng.randrange(1, 40), 320, z + rng.randrange(1, 40))}/{rng.randrange(0, 16)},{rng.randrange(0, 16)}' + n += 1 + + +def tokens(name, w): + return name + ' ' + ' '.join(f'{k}={v}' for k, v in w.items()) + + +def patrol_cases(rng, count): + out = [] + for i in range(count): + w = {'mode': 'patrol', 'seed': rng.randrange(-2**40, 2**40)} + px, pz = rng.randrange(-300, 300), rng.randrange(-300, 300) + terrain(rng, w, px, pz, span=90) + lights(rng, w, px, pz, span=60) + w['biome'] = rng.choice(BIOMES) + w['difficulty'] = rng.choice(DIFFICULTIES + ['hard', 'normal']) + w['darken'] = rng.choice([0, 0, 0, 0, 0, 1, 3, 4, 5, 11]) + w['sky'] = rng.choice([15, 15, 15, 7, 0]) + w['light'] = rng.choice([0, 0, 0, 0, 0, 5, 8, 9, 15]) + w['clock'] = rng.choice([0, 1000, 119999, 120000, 150000, 2000000, 5000000, 5000000, rng.randrange(0, 10**7), rng.randrange(0, 10**7)]) + w['inhabited'] = rng.choice([0, 0, 72000, 3600000, rng.randrange(0, 4 * 10**6)]) + w['moon'] = rng.choice(['0.0', '0.25', '0.5', '0.75', '1.0']) + w['dim'] = rng.choice(['minecraft:overworld'] * 12 + ['minecraft:the_nether', 'minecraft:the_end']) + if rng.random() < 0.85: + w['p0'] = f'{px + 0.5},{rng.choice([64, 64, 70, 40])},{pz + 0.5}' + rng.choice([''] * 8 + ['/spectator', '/creative']) + if rng.random() < 0.3: + vx, vz = (px >> 4) + rng.randrange(-4, 5), (pz >> 4) + rng.randrange(-4, 5) + w['vil'] = f'{vx},{rng.randrange(2, 6)},{vz}' + if rng.random() < 0.35: + w['unloaded'] = ';'.join(f'{(px >> 4) + rng.randrange(-5, 6)},{(pz >> 4) + rng.randrange(-5, 6)}' + for _ in range(rng.randrange(1, 8))) + if rng.random() < 0.05: + w['patrols'] = 0 + if rng.random() < 0.05: + w['enemies'] = 0 + w['next'] = rng.choice([0, 0, 1, 2, 7, -5]) + w['ticks'] = rng.choice([1, 2, 3, 12001, 26000, 40000, 66000, 90000, 130000]) + out.append(tokens(f'patrol{i}', w)) + return out + + +def raid_cases(rng, count): + out = [] + for i in range(count): + cx, cz = rng.randrange(-200, 200), rng.randrange(-200, 200) + w = {'mode': 'raid', 'rseed': rng.randrange(-2**40, 2**40)} + terrain(rng, w, cx, cz, span=110) + w['difficulty'] = rng.choice(['easy', 'normal', 'hard', 'hard', 'normal']) + w['biome'] = rng.choice(BIOMES) + if rng.random() < 0.06: + w['dim'] = rng.choice(['minecraft:the_nether', 'minecraft:the_end']) + # The village: a few sections around the centre, points of interest in them. + sx, sz = cx >> 4, cz >> 4 + sections = {(sx, 4, sz)} + for _ in range(rng.randrange(0, 6)): + sections.add((sx + rng.randrange(-2, 3), rng.choice([3, 4, 4, 5]), sz + rng.randrange(-2, 3))) + w['vil'] = ';'.join(f'{a},{b},{c}' for a, b, c in sorted(sections)) + pois = [(cx + rng.randrange(-40, 41), 64 + rng.randrange(-3, 4), cz + rng.randrange(-40, 41)) + for _ in range(rng.randrange(0, 12))] + if pois: + w['poi'] = ';'.join(f'{a},{b},{c}' for a, b, c in pois) + if rng.random() < 0.15: + w['unloaded'] = ';'.join(f'{sx + rng.randrange(-8, 9)},{sz + rng.randrange(-8, 9)}' for _ in range(rng.randrange(1, 10))) + if rng.random() < 0.15: + w['noticking'] = ';'.join(f'{sx + rng.randrange(-8, 9)},{sz + rng.randrange(-8, 9)}' for _ in range(rng.randrange(1, 10))) + far = rng.random() < 0.15 + w['p0'] = f'{cx + (rng.randrange(80, 150) if far else rng.randrange(-20, 20)) + 0.5},64,{cz + rng.randrange(-20, 20) + 0.5}' \ + + rng.choice([''] * 10 + ['/spectator']) + ev = [] + + def at(t, e): + ev.append((t, e)) + omen_pos = f'{cx + rng.randrange(-30, 31)},64,{cz + rng.randrange(-30, 31)}' + at(0, f'omen:{rng.choice([0, 0, 0, 1, 2, 4])}:{omen_pos}') + style = rng.choice(['win', 'win', 'win', 'lose', 'leave', 'misc', 'idle', 'timeout' if rng.random() < 0.15 else 'win']) + ticks = rng.choice([700, 1500, 3000, 4500, 6000]) + hero = rng.random() < 0.8 + if style == 'win': + step = rng.choice([7, 25, 60, 130]) + for t in range(301, ticks, step): + if rng.random() < 0.3: + at(t, f'hurtall:{rng.choice(["0.5", "4", "11.25", "30"])}') + at(t, 'killall:p' if hero else 'killall') + if rng.random() < 0.4: + at(rng.randrange(310, 1200), f'omen:{rng.randrange(0, 3)}:{omen_pos}') + elif style == 'lose': + for t in range(301, ticks, 97): + at(t, 'killall:p') + gone = rng.randrange(320, 2000) + for a, b, c in sorted(sections): + at(gone, f'unvil:{a},{b},{c}') + elif style == 'leave': + at(320, f'move:0:{cx + rng.choice([-120, 130, 200])},64,{cz}') + at(321, f'move:1:{cx + 40},64,{cz + 60}') + at(330, 'age:1:700') + at(330, 'idle:1:2500') + at(340, 'age:2:900') + at(345, 'gone:2') + at(350, 'discard:3') + at(360, 'hurt:1:3.5') + at(400, 'kill:1:p') + for t in range(1500, ticks, 113): + at(t, 'killall:p') + elif style == 'idle': + for j in range(4): + at(310, f'age:{j}:{rng.choice([500, 601, 650, 2000])}') + at(310, f'idle:{j}:{rng.choice([2000, 2401, 3000])}') + at(310, f'move:{j}:{cx + rng.randrange(-90, 90)},64,{cz + rng.randrange(-90, 90)}') + for t in range(1400, ticks, 211): + at(t, 'killall:p') + elif style == 'timeout': + ticks = 48100 + else: # misc + at(rng.randrange(1, 400), f'join:{rng.choice(RAIDERS)}:{cx + rng.randrange(-30, 30)},64,{cz + rng.randrange(-30, 30)}') + at(rng.randrange(300, 700), f'loadmob:{rng.choice(RAIDERS[:3])}:{cx},64,{cz}:{rng.randrange(0, 3)}:leader') + at(rng.randrange(300, 700), f'loadmob:{rng.choice(RAIDERS)}:{cx + 3},64,{cz}:{rng.randrange(0, 3)}') + at(rng.randrange(1, 900), f'join:{rng.choice(RAIDERS)}:{cx + rng.randrange(-30, 30)},64,{cz + rng.randrange(-30, 30)}') + for _ in range(rng.randrange(1, 5)): + at(rng.randrange(1, 2000), rng.choice([ + f'diff:{rng.choice(DIFFICULTIES)}', 'rules:0', 'rules:1', f'unload:{sx},{sz}', f'load:{sx},{sz}', + f'notick:{sx + rng.randrange(-6, 7)},{sz + rng.randrange(-6, 7)}', 'pdead', 'palive', + f'pmove:{cx + rng.randrange(-120, 120) + 0.5},64,{cz + 0.5}', f'setomen:{rng.randrange(0, 6)}', 'stop', + f'vil:{sx + rng.randrange(-3, 4)},4,{sz + rng.randrange(-3, 4)}', + f'hurt:{rng.randrange(0, 6)}:{rng.choice(["1", "2.5", "50"])}', f'kill:{rng.randrange(0, 6)}', + f'omen:{rng.randrange(0, 3)}:{cx + rng.randrange(-200, 200)},64,{cz + rng.randrange(-200, 200)}', + ])) + for t in range(400, ticks, 157): + at(t, 'killall:p') + w['ticks'] = ticks + for j, (t, e) in enumerate(sorted(ev, key=lambda x: x[0])): + w[f'ev{j}'] = f'{t}:{e}' + out.append(tokens(f'raid{i}', w)) + return out + + +def snbt_number(rng, v, kind): + """A number as SNBT of the field's type, or of another numeric type.""" + if rng.random() < 0.85: + return {'b': f'{v}b', 'i': str(v), 'l': f'{v}L', 'f': f'{v}f'}[kind] + t = rng.choice(['b', 's', 'i', 'l', 'f', 'd']) + if t == 'b': + return f'{max(-128, min(127, v))}b' + if t == 's': + return f'{max(-32768, min(32767, v))}s' + if t == 'l': + return f'{v}L' + if t == 'f': + return f'{v}.5f' if rng.random() < 0.5 else f'{v}f' + if t == 'd': + return f'{v}.75d' if rng.random() < 0.5 else f'{v}d' + return str(v) + + +def raid_snbt(rng, rid): + fields = { + 'id': snbt_number(rng, rid, 'i'), + 'started': snbt_number(rng, rng.randrange(0, 2), 'b'), + 'active': snbt_number(rng, rng.randrange(0, 2), 'b'), + 'ticks_active': snbt_number(rng, rng.randrange(0, 50000), 'l'), + 'raid_omen_level': snbt_number(rng, rng.randrange(0, 6), 'i'), + 'groups_spawned': snbt_number(rng, rng.randrange(0, 9), 'i'), + 'cooldown_ticks': snbt_number(rng, rng.randrange(0, 301), 'i'), + 'post_raid_ticks': snbt_number(rng, rng.randrange(0, 41), 'i'), + 'total_health': rng.choice(['0.0f', '96.0f', '322.5f', '24.0f', f'{rng.randrange(0, 500)}f', f'{rng.randrange(0, 500)}.25d', '7L']), + 'group_count': snbt_number(rng, rng.choice([0, 3, 5, 7]), 'i'), + 'status': '"' + rng.choice(['ongoing', 'victory', 'loss', 'stopped']) + '"', + 'center': rng.choice(['[I;{0},{1},{2}]', '[{0},{1},{2}]', '[I;{0},{1},{2}]', '[L;{0}L,{1}L,{2}L]', '[B;{3}b,{3}b,{3}b]']) + .format(rng.randrange(-30000, 30000), rng.randrange(-64, 320), rng.randrange(-30000, 30000), rng.randrange(-100, 100)), + 'heroes_of_the_village': '[' + ','.join( + rng.choice(['[I;{0},{1},{2},{3}]', '[I;{0},{1},{2},{3}]', '[{0},{1},{2},{3}]']) + .format(*(rng.randrange(-2**31, 2**31) for _ in range(4))) for _ in range(rng.randrange(0, 20))) + ']', + } + # Mutations: a missing field, a wrong type, a bad status or centre, broken heroes. + roll = rng.random() + if roll < 0.08: + del fields[rng.choice(list(fields))] + elif roll < 0.14: + fields[rng.choice(list(fields))] = rng.choice(['"text"', '{}', '[]', '[I;1,2]']) + elif roll < 0.18: + fields['status'] = '"won"' + elif roll < 0.22: + fields['center'] = '[I;1,2,3,4]' + elif roll < 0.3: + fields['heroes_of_the_village'] = '[[I;1,2,3,4],[I;1,2],"x",[I;5,6,7,8]]' + elif roll < 0.34: + fields['extra'] = '1b' + return '{' + ','.join(f'{k}:{v}' for k, v in fields.items()) + '}' + + +def codec_cases(rng, count): + out = [] + for i in range(count): + n = rng.choice([0, 1, 1, 2, 3, 5, 12, 30]) + ids = [rng.choice([rng.randrange(1, 40), rng.randrange(-5, 5), rng.randrange(0, 1000)]) for _ in range(n)] + raids = ','.join(raid_snbt(rng, rid) for rid in ids) + top = {'raids': f'[{raids}]', 'next_id': snbt_number(rng, rng.randrange(0, 100), 'i'), 'tick': snbt_number(rng, rng.randrange(0, 10**6), 'i')} + roll = rng.random() + if roll < 0.05: + del top['raids'] + elif roll < 0.1: + del top[rng.choice(['next_id', 'tick'])] + elif roll < 0.13: + top['raids'] = '"none"' + elif roll < 0.16: + top['raids'] = '[1,2,3]' + text = '{' + ','.join(f'{k}:{v}' for k, v in top.items()) + '}' + out.append(f'codec{i} mode=codec snbt={text.encode().hex()}') + return out + + +def corpus(seed=26_3): + rng = random.Random(seed) + return patrol_cases(rng, 1000) + raid_cases(rng, 400) + codec_cases(rng, 500) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + parser.add_argument('--only', help='only cases whose name starts with this') + args = parser.parse_args() + build = lab.LOCAL / 'rust-raid-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/VanillaRaidOracle.java' + sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/raid_fixture.rs', + lab.ROOT / 'crates/horizon-client/src/raid.rs', lab.ROOT / 'crates/horizon-client/src/patrol.rs'] + tested = base.source_hashes(sources) + inputs = build / 'inputs.txt' + cases = corpus() + if args.only: + cases = [c for c in cases if c.startswith(args.only)] + 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.VanillaRaidOracle', inputs, build / 'server.txt'], 'server') + run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'raid_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/raid_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 = [] + for a, b in zip(vanilla, rust): + if a == b: + continue + xs, ys = a.split(' ; '), b.split(' ; ') + i = next((i for i, (p, q) in enumerate(zip(xs, ys)) if p != q), min(len(xs), len(ys))) + bad.append((xs[0].split(' ')[0], ' ; '.join(xs[max(0, i - 2):i + 2]), ' ; '.join(ys[max(0, i - 2):i + 2]))) + if bad or len(vanilla) != len(rust): + report = '\n'.join(f' {n}\n vanilla {a[:1200]}\n rust {b[:1200]}' for n, 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 = {m: sum(1 for c in cases if f' mode={m}' in c) for m in ('patrol', 'raid', 'codec')} + spawns = sum(line.count(' ; spawn minecraft:pillager') for line in vanilla if line.startswith('patrol')) + waves = sum(line.count(' ; horn ') for line in vanilla if line.startswith('raid')) + raiders = sum(line.count(' ; spawn ') for line in vanilla if line.startswith('raid')) + victories = sum('effect minecraft:hero_of_the_village' in line for line in vanilla) + losses = sum(' loss ' in line for line in vanilla) + fresh = sum(line.split(' ', 1)[1].startswith('fresh') for line in vanilla if line.startswith('codec')) + lab.write_json(build / 'report.json', { + 'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': count, + 'patrol_spawns': spawns, 'raid_horns': waves, 'raiders_spawned': raiders, 'hero_effects': victories, 'losses': losses, + 'codec_fresh': fresh, 'sources_sha256': tested, + 'scope': 'PatrolSpawner.tick and spawnPatrolMember; Raids.tick, createOrExtendRaid and getNearbyRaid; Raid.tick, ' + 'spawnGroup, joinRaid, addWaveMob, removeFromRaid, updateRaiders, updateBossbar, playSound, findRandomSpawnPos, ' + 'moveRaidCenterToNearbyVillageSection, absorbRaidOmen, leaders and heroes; Raids.CODEC with resultOrPartial. ' + 'finalizeSpawn runs with a fixed random; raid buffs and patrol targets come from unseeded entity randoms.'}) + print(f'{count["patrol"]:,} patrol, {count["raid"]:,} raid and {count["codec"]:,} codec cases match vanilla ' + f'({spawns:,} patrol pillagers, {waves:,} raid waves, {raiders:,} raiders, {victories} victories, {losses} losses)') + + +if __name__ == '__main__': + main()