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 <noreply@anthropic.com>
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -135,6 +135,16 @@ pub fn instant(id: &str, amp: i32, scale: f64) -> Option<EffectAction> {
|
||||
_ => 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<EffectInstance>,
|
||||
@@ -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<EffectAction>, 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<EffectAction> {
|
||||
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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<Vec<Aabb>>,
|
||||
@@ -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(&[]),
|
||||
|
||||
@@ -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();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -42,6 +42,31 @@ pub struct State {
|
||||
pub homes: Option<std::sync::Arc<Vec<[i32; 3]>>>,
|
||||
/// 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`).
|
||||
|
||||
@@ -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: PatrolLevel + ?Sized>(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: PatrolLevel + ?Sized>(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<L: PatrolLevel, R: RandomSource>(
|
||||
&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<L: PatrolLevel, R: RandomSource>(
|
||||
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<String, std::collections::HashMap<String, bool>>,
|
||||
/// attribute -> biome -> value.
|
||||
biomes: std::collections::HashMap<String, std::collections::HashMap<String, bool>>,
|
||||
/// attribute -> dimension type -> boolean tracks (keyframes, modifier).
|
||||
tracks: std::collections::HashMap<String, std::collections::HashMap<String, Vec<BoolTrack>>>,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
struct BoolTrack {
|
||||
keyframes: Vec<(i64, bool)>,
|
||||
period: Option<i64>,
|
||||
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<Value> {
|
||||
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<String, Value> =
|
||||
list("timeline").into_iter().collect();
|
||||
// Tag values with nested tags resolved.
|
||||
fn tag(data: &std::path::Path, name: &str, out: &mut Vec<String>) {
|
||||
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::<serde_json::Value>(&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
|
||||
}
|
||||
}
|
||||
+1098
-462
File diff suppressed because it is too large
Load Diff
@@ -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<Map.Entry<Box, BlockState>> blocks = new ArrayList<>();
|
||||
List<Map.Entry<Box, int[]>> lights = new ArrayList<>();
|
||||
Holder<Biome> biome;
|
||||
int sky, block, darken;
|
||||
Difficulty difficulty;
|
||||
DimensionType dimensionType;
|
||||
ResourceKey<Level> dimensionKey;
|
||||
Set<Long> unloaded = new HashSet<>();
|
||||
Set<Long> noTicking = new HashSet<>();
|
||||
List<int[]> villages = new ArrayList<>();
|
||||
List<BlockPos> pois = new ArrayList<>();
|
||||
List<Entity> entities = new ArrayList<>();
|
||||
List<ServerPlayer> 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<String> 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<Level> dimension() { return dimensionKey; }
|
||||
@Override public Holder<Biome> 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<ServerPlayer> getPlayers(Predicate<? super ServerPlayer> filter) {
|
||||
List<ServerPlayer> 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<net.minecraft.world.level.gameevent.GameEvent> event, Vec3 pos) {}
|
||||
@Override public void gameEvent(Holder<net.minecraft.world.level.gameevent.GameEvent> 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 <T extends net.minecraft.advancements.CriterionTriggerInstance> Map<PlayerAdvancements.TriggerInstanceKey, T> getTriggerMapForType(
|
||||
net.minecraft.advancements.triggers.CriterionTrigger<T> type) { return null; }
|
||||
}
|
||||
|
||||
static final class Conn extends ServerGamePacketListenerImpl {
|
||||
Conn() { super(null, null, null, null); }
|
||||
List<String> 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<String> 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<MobEffect> 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<Raid>) 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<BlockPos> wave = (Optional<BlockPos>) waveSpawnPos.get(r);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<Integer, Raider> leaders = (Map<Integer, Raider>) 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<Biome> getBiome(BlockPos pos) { return level.biome; }
|
||||
@Override public Holder<Biome> getBiome(int x, int y, int z) { return level.biome; }
|
||||
@Override public Holder<Biome> getNoiseBiomeAtPosition(double x, double y, double z) { return level.biome; }
|
||||
@Override public Holder<Biome> getNoiseBiomeAtPosition(BlockPos pos) { return level.biome; }
|
||||
@Override public Holder<Biome> 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<String> 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<String, String> 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<String> 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<Raids> 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<Raid>) 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<Raider> tracked = new ArrayList<>();
|
||||
Set<Raid> seeded = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
Map<String, List<String>> 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<Raider, Raid> raidOf = new IdentityHashMap<>();
|
||||
Map<Raider, Integer> 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<net.minecraft.world.entity.ai.village.poi.PoiRecord> getInSquare(
|
||||
Predicate<Holder<net.minecraft.world.entity.ai.village.poi.PoiType>> 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<net.minecraft.world.entity.ai.village.poi.PoiRecord> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user