2e3063d821
# Conflicts: # crates/horizon-client/examples/entity_anim_fixture.rs # crates/horizon-client/examples/mob_ai_probe.rs # crates/horizon-client/src/game/creatures.rs # crates/horizon-client/src/mobs.rs # crates/horizon-client/src/mobs/ai.rs # mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java # tools/test_mob_ai_parity.py
869 lines
31 KiB
Rust
869 lines
31 KiB
Rust
//! Replays `tools/test_mob_ai_parity.py` scenarios on Horizon's mob AI and
|
|
//! prints each mob's AI-visible state after every tick in the format of
|
|
//! `VanillaMobAiOracle`.
|
|
//!
|
|
//! usage: mob_ai_probe RESOURCES SCENARIOS OUTPUT
|
|
use horizon_client::{
|
|
assets::Assets,
|
|
biome::Biomes,
|
|
blocks::BlockFacts,
|
|
chunk::{Chunk, HEIGHT, MIN_Y},
|
|
collisions,
|
|
containers::{BlockEntity, CreakingHeart},
|
|
items::Items,
|
|
light::{LightTables, light_chunk},
|
|
mobs::{
|
|
Damage, MobType, creaking,
|
|
creaking_heart::{self, HeartEvent, HeartHost},
|
|
},
|
|
mobs::{
|
|
Mob, MobData, MobEvent, MobTypes, MobWorld, PlayerView, Seen, Species, Who,
|
|
control::Operation, spawning::LocalDifficulty,
|
|
},
|
|
world::World,
|
|
};
|
|
use horizon_core::{
|
|
geometry::{Aabb, Vec3},
|
|
random::LegacyRandom,
|
|
};
|
|
use horizon_world::{chunk::BlockState, registry::BlockRegistry, registry::BlockStateId};
|
|
use std::{collections::BTreeMap, fmt::Write as _, fs, path::Path, sync::Arc};
|
|
|
|
struct MobSpec {
|
|
kind: String,
|
|
pos: [f64; 3],
|
|
yaw: f32,
|
|
seed: i64,
|
|
baby: bool,
|
|
flags: Vec<String>,
|
|
}
|
|
#[derive(Default)]
|
|
struct Scenario {
|
|
name: String,
|
|
ticks: i32,
|
|
time: i64,
|
|
rain: bool,
|
|
thunder: bool,
|
|
origin: [i32; 2],
|
|
blocks: Vec<Vec<String>>,
|
|
player: Option<[f64; 3]>,
|
|
creative: bool,
|
|
/// The tick from which the player faces another yaw.
|
|
turn: Option<(i32, f32)>,
|
|
/// Creaking hearts placed when the scenario starts.
|
|
hearts: Vec<Vec<String>>,
|
|
/// `ServerLevel.isSpawningMonsters`.
|
|
spawning: bool,
|
|
/// The player hits a mob for 1 at the start of a tick: (tick, mob index).
|
|
hurts: Vec<(i32, usize)>,
|
|
hand: Option<String>,
|
|
mobs: Vec<MobSpec>,
|
|
}
|
|
|
|
fn parse(text: &str) -> Vec<Scenario> {
|
|
let mut out = Vec::new();
|
|
let mut cur: Option<Scenario> = None;
|
|
for line in text.lines() {
|
|
let f: Vec<&str> = line.split_whitespace().collect();
|
|
if f.is_empty() || f[0].starts_with('#') {
|
|
continue;
|
|
}
|
|
let s = cur.get_or_insert_with(Scenario::default);
|
|
match f[0] {
|
|
"scenario" => {
|
|
s.name = f[1].to_owned();
|
|
s.time = 6000;
|
|
for kv in &f[2..] {
|
|
let (k, v) = kv.split_once('=').unwrap_or((kv, ""));
|
|
match k {
|
|
"ticks" => s.ticks = v.parse().unwrap(),
|
|
"time" => s.time = v.parse().unwrap(),
|
|
"rain" => s.rain = true,
|
|
"thunder" => s.thunder = true,
|
|
"levelseed" => {}
|
|
"spawning" => s.spawning = true,
|
|
_ => panic!("unknown scenario option {kv}"),
|
|
}
|
|
}
|
|
}
|
|
"origin" => s.origin = [f[1].parse().unwrap(), f[2].parse().unwrap()],
|
|
"fill" | "block" => s.blocks.push(f.iter().map(|x| (*x).to_owned()).collect()),
|
|
"heart" => s.hearts.push(f.iter().map(|x| (*x).to_owned()).collect()),
|
|
"hurt" => s.hurts.push((f[1].parse().unwrap(), f[2].parse().unwrap())),
|
|
"player" => {
|
|
s.player = Some([
|
|
f[1].parse().unwrap(),
|
|
f[2].parse().unwrap(),
|
|
f[3].parse().unwrap(),
|
|
]);
|
|
for opt in &f[4..] {
|
|
if *opt == "creative" {
|
|
s.creative = true;
|
|
} else if let Some(t) = opt.strip_prefix("turn=") {
|
|
let (tick, yaw) = t.split_once(',').unwrap();
|
|
s.turn = Some((tick.parse().unwrap(), yaw.parse().unwrap()));
|
|
} else if let Some(item) = opt.strip_prefix("hand=") {
|
|
s.hand = Some(item.to_owned());
|
|
} else {
|
|
panic!("unknown player option {opt}");
|
|
}
|
|
}
|
|
}
|
|
"mob" => s.mobs.push(MobSpec {
|
|
kind: f[1].to_owned(),
|
|
pos: [
|
|
f[2].parse().unwrap(),
|
|
f[3].parse().unwrap(),
|
|
f[4].parse().unwrap(),
|
|
],
|
|
yaw: f[5].parse().unwrap(),
|
|
seed: f[6].parse().unwrap(),
|
|
baby: f[7..].contains(&"baby"),
|
|
flags: f[7..]
|
|
.iter()
|
|
.filter(|x| **x != "baby")
|
|
.map(|x| (*x).to_owned())
|
|
.collect(),
|
|
}),
|
|
"end" => out.push(cur.take().unwrap()),
|
|
other => panic!("unknown scenario line {other}"),
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// `minecraft:name[key=value,...]`
|
|
fn state(registry: &BlockRegistry, text: &str) -> BlockStateId {
|
|
let (name, props) = match text.split_once('[') {
|
|
Some((n, rest)) => (n, rest.trim_end_matches(']')),
|
|
None => (text, ""),
|
|
};
|
|
let mut properties = BTreeMap::new();
|
|
for kv in props.split(',').filter(|s| !s.is_empty()) {
|
|
let (k, v) = kv.split_once('=').expect("property");
|
|
properties.insert(k.to_owned(), v.to_owned());
|
|
}
|
|
registry
|
|
.resolve(&BlockState {
|
|
name: name.to_owned(),
|
|
properties,
|
|
})
|
|
.unwrap_or_else(|e| panic!("{text}: {e}"))
|
|
}
|
|
|
|
fn d(v: f64) -> String {
|
|
format!("{:x}", v.to_bits())
|
|
}
|
|
fn f(v: f32) -> String {
|
|
format!("{:x}", v.to_bits())
|
|
}
|
|
fn who(w: Option<Who>) -> String {
|
|
match w {
|
|
None => "none".into(),
|
|
Some(Who::Player) => "player".into(),
|
|
Some(Who::Mob(id)) => format!("e{id}"),
|
|
}
|
|
}
|
|
|
|
/// Vanilla's goal class for a Horizon goal (most share the name).
|
|
fn goal_name(m: &Mob, name: &str) -> String {
|
|
let vanilla = match name {
|
|
"Float" => "FloatGoal",
|
|
"Stroll" => "WaterAvoidingRandomStrollGoal",
|
|
"RandomStroll" => "RandomStrollGoal",
|
|
"RandomSwimming" => "RandomSwimmingGoal",
|
|
"LookAtPlayer" => "LookAtPlayerGoal",
|
|
"RandomLookAround" => "RandomLookAroundGoal",
|
|
"HurtByTarget" => "HurtByTargetGoal",
|
|
"NearestTarget" => "NearestAttackableTargetGoal",
|
|
"Panic" => "PanicGoal",
|
|
"Breed" => "BreedGoal",
|
|
"Tempt" => "TemptGoal",
|
|
"FollowParent" => "FollowParentGoal",
|
|
"MeleeAttack" => match m.species() {
|
|
Species::Zombie | Species::Husk | Species::ZombieVillager => "ZombieAttackGoal",
|
|
_ => "MeleeAttackGoal",
|
|
},
|
|
"MoveThroughVillage" => "MoveThroughVillageGoal",
|
|
"RestrictSun" => "RestrictSunGoal",
|
|
"FleeSun" => "FleeSunGoal",
|
|
"AvoidEntity" => "AvoidEntityGoal",
|
|
"BowAttack" => "RangedBowAttackGoal",
|
|
"Swell" => "SwellGoal",
|
|
"LeapAtTarget" => "LeapAtTargetGoal",
|
|
"EatBlock" => "EatBlockGoal",
|
|
"MoveTowardsRestriction" => "MoveTowardsRestrictionGoal",
|
|
"TradeWithPlayer" => "TradeWithPlayerGoal",
|
|
"LookAtTradingPlayer" => "LookAtTradingPlayerGoal",
|
|
"WanderToPosition" => "WanderToPositionGoal",
|
|
"DrinkItem" => "UseItemGoal",
|
|
"BreathAir" => "BreathAirGoal",
|
|
"TryFindWater" => "TryFindWaterGoal",
|
|
"RangedAttack" => "RangedAttackGoal",
|
|
"MoveTowardsTarget" => "MoveTowardsTargetGoal",
|
|
"DrownedGoToWater" => "DrownedGoToWaterGoal",
|
|
"TakeBlock" => "EndermanTakeBlockGoal",
|
|
"LeaveBlock" => "EndermanLeaveBlockGoal",
|
|
"FreezeWhenLookedAt" => "EndermanFreezeWhenLookedAt",
|
|
"LookForPlayer" => "EndermanLookForPlayerGoal",
|
|
"HealRaiders" => "NearestHealableRaiderTargetGoal",
|
|
other => return other.to_owned(),
|
|
};
|
|
vanilla.to_owned()
|
|
}
|
|
|
|
fn goals(m: &Mob, names: Vec<&'static str>) -> String {
|
|
if names.is_empty() {
|
|
return "-".into();
|
|
}
|
|
names
|
|
.iter()
|
|
.map(|n| goal_name(m, n))
|
|
.collect::<Vec<_>>()
|
|
.join("|")
|
|
}
|
|
|
|
fn seen(m: &Mob) -> Seen {
|
|
Seen {
|
|
id: m.id,
|
|
species: m.species(),
|
|
position: m.position,
|
|
bounds: m.bounds(),
|
|
eye_y: m.eye_y(),
|
|
alive: m.alive(),
|
|
baby: m.is_baby(),
|
|
in_love: if m.species() == Species::Villager {
|
|
horizon_client::mobs::villager::can_breed(m)
|
|
} else {
|
|
m.extra.in_love > 0
|
|
},
|
|
tame: m.extra.tame,
|
|
hostile: m.hostile(),
|
|
target: m.ai.target,
|
|
health: m.health,
|
|
variant: m.extra.variant,
|
|
color: m.extra.color,
|
|
job: (m.species() == Species::Villager)
|
|
.then_some(m.extra.home)
|
|
.flatten(),
|
|
bed: (m.species() == Species::Villager)
|
|
.then_some(m.extra.bed)
|
|
.flatten(),
|
|
yaw: m.yaw,
|
|
velocity: m.velocity,
|
|
leash: m.extra.leash,
|
|
caravan: horizon_client::mobs::caravan::head_of(m),
|
|
delay: m.extra.ints[5],
|
|
hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)),
|
|
active_raid: horizon_client::mobs::raider::has_active_raid(m),
|
|
player_rep: 0,
|
|
pushable: m.pushable(),
|
|
category: m.category(),
|
|
potential_job: horizon_client::mobs::villager_brain::potential_job_site(m),
|
|
meeting: (m.species() == Species::Villager)
|
|
.then_some(m.extra.meeting)
|
|
.flatten(),
|
|
profession: m.extra.variant2,
|
|
xp: horizon_client::mobs::villager::xp(m),
|
|
stats: [
|
|
f64::from(m.attrs.max_health),
|
|
m.extra.vector[0],
|
|
m.attrs.speed,
|
|
],
|
|
}
|
|
}
|
|
|
|
/// The probe's mobs as a creaking heart sees them: creakings it creates take
|
|
/// the n-th seed from 1000, as the oracle's do.
|
|
struct Host<'a> {
|
|
mobs: &'a mut Vec<Mob>,
|
|
added: Vec<Mob>,
|
|
types: &'a MobTypes,
|
|
created: &'a mut i64,
|
|
spawning: bool,
|
|
}
|
|
impl HeartHost for Host<'_> {
|
|
fn mob(&self, id: u32) -> Option<&Mob> {
|
|
self.mobs
|
|
.iter()
|
|
.chain(self.added.iter())
|
|
.find(|m| m.id == id)
|
|
}
|
|
fn mob_mut(&mut self, id: u32) -> Option<&mut Mob> {
|
|
self.mobs
|
|
.iter_mut()
|
|
.chain(self.added.iter_mut())
|
|
.find(|m| m.id == id)
|
|
}
|
|
fn mob_for_uuid(&self, uuid: [i32; 4]) -> Option<u32> {
|
|
self.mob(uuid[3] as u32)
|
|
.filter(|m| !m.removed)
|
|
.map(|m| m.id)
|
|
}
|
|
fn uuid_for(&mut self, id: u32) -> [i32; 4] {
|
|
[0, 0, 0, id as i32]
|
|
}
|
|
fn creaking_type(&self) -> Option<Arc<MobType>> {
|
|
self.types
|
|
.types
|
|
.get("minecraft:creaking")
|
|
.map(|t| Arc::new(t.clone()))
|
|
}
|
|
fn create_mob(&mut self, kind: Arc<MobType>, at: Vec3) -> Mob {
|
|
let seed = 1000 + *self.created;
|
|
*self.created += 1;
|
|
let mut m = Mob::new(200_000 + seed as u32, kind, at, 0.0);
|
|
m.random = LegacyRandom::new(seed);
|
|
horizon_client::mobs::monster_brain::init(&mut m, seed);
|
|
m
|
|
}
|
|
fn add_mob(&mut self, m: Mob) {
|
|
self.added.push(m);
|
|
}
|
|
fn spawning_monsters(&self) -> bool {
|
|
self.spawning
|
|
}
|
|
}
|
|
/// The heart's state, block entity and the level random, as the oracle
|
|
/// prints them.
|
|
fn print_heart(
|
|
out: &mut String,
|
|
t: i32,
|
|
registry: &BlockRegistry,
|
|
world: &World,
|
|
at: [i32; 3],
|
|
heart: &CreakingHeart,
|
|
lr: &LegacyRandom,
|
|
) {
|
|
let state = registry
|
|
.state(world.block(at[0], at[1], at[2]))
|
|
.and_then(|s| s.properties.get("creaking_heart_state").cloned())
|
|
.unwrap_or_default();
|
|
let _ = writeln!(
|
|
out,
|
|
"{t} heart {},{},{}\t{state}\t{} {} {} {} {}\tlrng {:x}",
|
|
at[0],
|
|
at[1],
|
|
at[2],
|
|
heart.ticker,
|
|
heart.emitter,
|
|
heart.output_signal,
|
|
heart.ticks_existed,
|
|
if heart.creaking.is_some() {
|
|
"linked"
|
|
} else {
|
|
"none"
|
|
},
|
|
lr.state()
|
|
);
|
|
}
|
|
|
|
/// Whether an event hurts the scenario's player (survival, normal difficulty,
|
|
/// no armour, made hurtable again every tick by the oracle).
|
|
fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool {
|
|
let Some(p) = player.filter(|p| !p.creative) else {
|
|
return false;
|
|
};
|
|
match e {
|
|
MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount > 0.0,
|
|
// ServerExplosion.hurtEntities: within twice the radius every hit does damage.
|
|
MobEvent::Explode(at, radius) => {
|
|
let d = Vec3::new(at[0], at[1], at[2])
|
|
.distance_squared(p.position)
|
|
.sqrt();
|
|
let r = 2.0 * f64::from(*radius);
|
|
d / r <= 1.0 && d != 0.0
|
|
}
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
fn print(out: &mut String, t: i32, i: usize, m: &Mob) {
|
|
let _ = write!(out, "{t} {i}");
|
|
if m.removed {
|
|
// Entity.RemovalReason: the end of the death animation, else a discard.
|
|
let reason = if m.alive() { "DISCARDED" } else { "KILLED" };
|
|
let _ = writeln!(out, " removed {reason}");
|
|
return;
|
|
}
|
|
let p = m.position;
|
|
let v = m.velocity;
|
|
let _ = write!(
|
|
out,
|
|
"\tp {},{},{}\tv {},{},{}",
|
|
d(p.x),
|
|
d(p.y),
|
|
d(p.z),
|
|
d(v.x),
|
|
d(v.y),
|
|
d(v.z)
|
|
);
|
|
let _ = write!(
|
|
out,
|
|
"\tr {},{},{},{}",
|
|
f(m.yaw),
|
|
f(m.head_pitch),
|
|
f(m.head_yaw),
|
|
f(m.body_yaw)
|
|
);
|
|
let _ = write!(
|
|
out,
|
|
"\tg {}{}\thp {}",
|
|
u8::from(m.on_ground),
|
|
u8::from(m.horizontal_collision),
|
|
f(m.health)
|
|
);
|
|
let _ = write!(
|
|
out,
|
|
"\tgoals {}\ttargets {}\ttarget {}",
|
|
goals(m, m.ai.goals.running_names()),
|
|
goals(m, m.ai.targets.running_names()),
|
|
who(m.ai.target)
|
|
);
|
|
let _ = write!(out, "\tnav ");
|
|
match &m.ai.nav.path {
|
|
None => out.push_str("none"),
|
|
Some(path) => {
|
|
let _ = write!(
|
|
out,
|
|
"{},{},{} {}/{}{}",
|
|
path.target[0],
|
|
path.target[1],
|
|
path.target[2],
|
|
path.next,
|
|
path.nodes.len(),
|
|
if path.next >= path.nodes.len() {
|
|
" done"
|
|
} else {
|
|
""
|
|
}
|
|
);
|
|
}
|
|
}
|
|
let mv = &m.ai.mov;
|
|
let op = match mv.operation {
|
|
Operation::Wait => "WAIT",
|
|
Operation::MoveTo => "MOVE_TO",
|
|
Operation::Strafe => "STRAFE",
|
|
Operation::Jumping => "JUMPING",
|
|
};
|
|
let _ = write!(
|
|
out,
|
|
"\tmove {op} {},{},{} {}",
|
|
d(mv.wanted[0]),
|
|
d(mv.wanted[1]),
|
|
d(mv.wanted[2]),
|
|
d(mv.speed_modifier)
|
|
);
|
|
let lk = &m.ai.look;
|
|
let _ = write!(
|
|
out,
|
|
"\tlook {} {},{},{}",
|
|
lk.cooldown,
|
|
d(lk.wanted[0]),
|
|
d(lk.wanted[1]),
|
|
d(lk.wanted[2])
|
|
);
|
|
let _ = write!(
|
|
out,
|
|
"\tin {},{},{},{}",
|
|
f(m.ai.xxa),
|
|
f(m.ai.zza),
|
|
f(m.ai.speed),
|
|
u8::from(m.ai.jumping)
|
|
);
|
|
let _ = write!(out, "\trng {:x}", m.random.state());
|
|
let brain = horizon_client::mobs::villager_brain::describe(m)
|
|
.or_else(|| horizon_client::mobs::monster_brain::describe(m))
|
|
.or_else(|| horizon_client::mobs::animal_brain::describe(m));
|
|
if let Some((acts, mem)) = brain {
|
|
let _ = write!(out, "\tact {acts}\tmem {mem}");
|
|
}
|
|
out.push('\n');
|
|
}
|
|
|
|
fn main() -> horizon_client::Result<()> {
|
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
|
if args.len() != 3 {
|
|
return Err("usage: mob_ai_probe RESOURCES SCENARIOS OUTPUT".into());
|
|
}
|
|
let root = Path::new(&args[0]);
|
|
let assets = Assets::load(root)?;
|
|
let registry = assets.registry;
|
|
let facts = BlockFacts::load(root, registry)?;
|
|
let data = MobData::load(root, &facts);
|
|
let types = MobTypes::load(root)?;
|
|
let biomes = Biomes::load(root)?;
|
|
let items = Items::load(root, registry, &facts)?;
|
|
let tables = LightTables::load(root, registry, &facts)?;
|
|
let collision = collisions::load(root, registry)?;
|
|
let air = registry.default_state("minecraft:air").ok_or("no air")?;
|
|
let layers = [
|
|
state(registry, "minecraft:bedrock"),
|
|
state(registry, "minecraft:dirt"),
|
|
state(registry, "minecraft:dirt"),
|
|
state(registry, "minecraft:grass_block"),
|
|
];
|
|
let plains = biomes.id("minecraft:plains");
|
|
let mut out = String::new();
|
|
for s in parse(&fs::read_to_string(&args[1])?) {
|
|
let _ = writeln!(out, "== {}", s.name);
|
|
let mut world = World::new(air, 0);
|
|
let (ocx, ocz) = (s.origin[0] >> 4, s.origin[1] >> 4);
|
|
const R: i32 = 4;
|
|
for cz in ocz - R..=ocz + R {
|
|
for cx in ocx - R..=ocx + R {
|
|
let mut chunk = Chunk::empty(cx, cz);
|
|
for qy in 0..HEIGHT / 4 {
|
|
for qz in 0..4 {
|
|
for qx in 0..4 {
|
|
chunk.set_biome_cell(qx, qy, qz, plains);
|
|
}
|
|
}
|
|
}
|
|
world.chunks.insert((cx, cz), Arc::new(chunk));
|
|
for z in 0..16 {
|
|
for x in 0..16 {
|
|
for (y, layer) in layers.iter().enumerate() {
|
|
world.set(cx * 16 + x, MIN_Y + y as i32, cz * 16 + z, *layer)?;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for b in &s.blocks {
|
|
let n = |i: usize| b[i].parse::<i32>().unwrap();
|
|
if b[0] == "block" {
|
|
world.set(n(1), n(2), n(3), state(registry, &b[4]))?;
|
|
} else {
|
|
let st = state(registry, &b[7]);
|
|
for x in n(1).min(n(4))..=n(1).max(n(4)) {
|
|
for y in n(2).min(n(5))..=n(2).max(n(5)) {
|
|
for z in n(3).min(n(6))..=n(3).max(n(6)) {
|
|
world.set(x, y, z, st)?;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let mut hearts: Vec<([i32; 3], CreakingHeart)> = Vec::new();
|
|
for h in &s.hearts {
|
|
let at = [
|
|
h[1].parse::<i32>().unwrap(),
|
|
h[2].parse::<i32>().unwrap(),
|
|
h[3].parse::<i32>().unwrap(),
|
|
];
|
|
world.set(at[0], at[1], at[2], state(registry, &h[4]))?;
|
|
hearts.push((at, CreakingHeart::default()));
|
|
}
|
|
let mut created = 0_i64;
|
|
let keys: Vec<(i32, i32)> = world.chunks.keys().copied().collect();
|
|
let lit: Vec<((i32, i32), Chunk)> = keys
|
|
.iter()
|
|
.map(|&(x, z)| {
|
|
let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|dz| {
|
|
std::array::from_fn(|dx| {
|
|
world
|
|
.chunks
|
|
.get(&(x + dx as i32 - 1, z + dz as i32 - 1))
|
|
.map(|c| &**c)
|
|
})
|
|
});
|
|
let mut c = (*world.chunks[&(x, z)]).clone();
|
|
c.sections = light_chunk(®ion, &tables, true);
|
|
c.lit = true;
|
|
((x, z), c)
|
|
})
|
|
.collect();
|
|
for (k, c) in lit {
|
|
world.chunks.insert(k, Arc::new(c));
|
|
}
|
|
world.day_time = s.time;
|
|
world.game_time = 1000;
|
|
let mut mobs: Vec<Mob> = Vec::new();
|
|
for (i, spec) in s.mobs.iter().enumerate() {
|
|
let kind = types
|
|
.types
|
|
.get(&spec.kind)
|
|
.ok_or_else(|| format!("unknown mob {}", spec.kind))?;
|
|
let mut m = Mob::new(
|
|
100_000 + i as u32,
|
|
Arc::new(kind.clone()),
|
|
Vec3::new(spec.pos[0], spec.pos[1], spec.pos[2]),
|
|
spec.yaw,
|
|
);
|
|
if spec.baby {
|
|
m.extra.age = -24000;
|
|
}
|
|
for flag in &spec.flags {
|
|
match flag.as_str() {
|
|
"persistent" => m.persistent = true,
|
|
"noai" => m.no_ai = true,
|
|
"inlove" => m.extra.in_love = 600,
|
|
"tame" => m.extra.tame = true,
|
|
x if x.starts_with("age=") => m.extra.age = x[4..].parse().unwrap(),
|
|
x if x.starts_with("strength=") => m.extra.variant2 = x[9..].parse().unwrap(),
|
|
"leashed" => m.extra.leash = Some(horizon_client::mobs::leash::Holder::Player),
|
|
x if x.starts_with("leashto=") => {
|
|
let n: u32 = x[8..].parse().unwrap();
|
|
m.extra.leash = Some(horizon_client::mobs::leash::Holder::Mob(100_000 + n));
|
|
}
|
|
other => panic!("unknown mob flag {other}"),
|
|
}
|
|
}
|
|
m.random = LegacyRandom::new(spec.seed);
|
|
if horizon_client::mobs::monster_brain::has_brain(m.species()) {
|
|
// The oracle delays the sensors again with the seeded random
|
|
// and seeds RunOne's shuffles with the mob's seed.
|
|
horizon_client::mobs::monster_brain::init(&mut m, spec.seed);
|
|
}
|
|
if m.species() == Species::Villager {
|
|
// The oracle seeds the random after the brain is built, then
|
|
// delays the sensors again and seeds the gates' shuffles.
|
|
horizon_client::mobs::villager_brain::init(
|
|
&mut m,
|
|
world.game_time,
|
|
s.time,
|
|
spec.seed,
|
|
);
|
|
}
|
|
// The same for the sniffer's and the happy ghast's brains.
|
|
if horizon_client::mobs::animal_brain::kind_of(&m).is_some() {
|
|
horizon_client::mobs::animal_brain::init(&mut m, spec.seed);
|
|
}
|
|
mobs.push(m);
|
|
}
|
|
let mut player = s.player.map(|p| {
|
|
let position = Vec3::new(p[0], p[1], p[2]);
|
|
PlayerView {
|
|
position,
|
|
bounds: Aabb::new(
|
|
Vec3::new(p[0] - 0.3, p[1], p[2] - 0.3),
|
|
Vec3::new(p[0] + 0.3, p[1] + 1.8, p[2] + 0.3),
|
|
),
|
|
eye: [p[0], p[1] + f64::from(1.62_f32), p[2]],
|
|
alive: true,
|
|
creative: s.creative,
|
|
sneaking: false,
|
|
look: [0.0, 0.0, 1.0],
|
|
main_hand: s.hand.as_deref().map(Into::into),
|
|
off_hand: None,
|
|
head: None,
|
|
armor_cover: 0.0,
|
|
spectator: false,
|
|
gold_armor: false,
|
|
hurt_by: None,
|
|
last_hurt: None,
|
|
velocity: Vec3::ZERO,
|
|
yaw: 0.0,
|
|
hero: false,
|
|
uuid: [0, 0x1234, 0, 0x5678],
|
|
allies: Default::default(),
|
|
}
|
|
});
|
|
let mut scratch = LegacyRandom::new(0);
|
|
for (i, m) in mobs.iter().enumerate() {
|
|
print(&mut out, 0, i, m);
|
|
}
|
|
// The MobWorld every step sees, over a snapshot of the mobs.
|
|
macro_rules! mob_world {
|
|
($snapshot:expr) => {
|
|
MobWorld {
|
|
teams: Default::default(),
|
|
world: &world,
|
|
registry,
|
|
facts: &facts,
|
|
collision: &collision,
|
|
data: &data,
|
|
player: player.clone(),
|
|
others: $snapshot,
|
|
daylight: (s.time.rem_euclid(24000)) < 12000,
|
|
game_time: world.game_time,
|
|
day_time: world.day_time,
|
|
raining: s.rain,
|
|
thundering: s.thunder,
|
|
nether: false,
|
|
block_tags: &items.block_tags,
|
|
biomes: &biomes,
|
|
mob_griefing: true,
|
|
difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0),
|
|
end: false,
|
|
world_seed: 0,
|
|
// FlatLevelSource.getSeaLevel.
|
|
sea_level: -63,
|
|
}
|
|
};
|
|
}
|
|
for t in 1..=s.ticks {
|
|
world.game_time += 1;
|
|
let mut heart_events_later: Vec<HeartEvent> = Vec::new();
|
|
// Creaking.tick reads the heart's block entity.
|
|
for (at, h) in &hearts {
|
|
world.block_entities.insert(
|
|
(at[0], at[1], at[2]),
|
|
BlockEntity::CreakingHeart(Box::new(h.clone())),
|
|
);
|
|
}
|
|
if let (Some(p), Some((tick, yaw))) = (player.as_mut(), s.turn)
|
|
&& t >= tick
|
|
{
|
|
// Entity.calculateViewVector(0, yaw).
|
|
let r = -yaw * horizon_core::geometry::trig::DEG_TO_RAD;
|
|
let (cos, sin) = (
|
|
horizon_core::geometry::trig::cos(f64::from(r)),
|
|
horizon_core::geometry::trig::sin(f64::from(r)),
|
|
);
|
|
p.look = [f64::from(sin), -0.0, f64::from(cos)];
|
|
p.yaw = yaw;
|
|
}
|
|
let mut snapshot: Vec<Seen> = mobs.iter().filter(|m| !m.removed).map(seen).collect();
|
|
let w = mob_world!(&snapshot);
|
|
let mut events = Vec::new();
|
|
let mut heart_events = Vec::new();
|
|
let mut added = Vec::new();
|
|
for &(tick, i) in &s.hurts {
|
|
if tick != t || i >= mobs.len() || mobs[i].removed {
|
|
continue;
|
|
}
|
|
let at = player
|
|
.as_ref()
|
|
.map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]);
|
|
mobs[i].damage(1.0, Damage::player(at));
|
|
// Creaking.hurtServer: the heart's reaction, then the sway.
|
|
if let Some((home, by_player)) = creaking::take_hurt(&mut mobs[i], &w) {
|
|
if by_player && let Some((_, h)) = hearts.iter_mut().find(|(at, _)| *at == home)
|
|
{
|
|
let mut host = Host {
|
|
mobs: &mut mobs,
|
|
added: Vec::new(),
|
|
types: &types,
|
|
created: &mut created,
|
|
spawning: s.spawning,
|
|
};
|
|
creaking_heart::creaking_hurt(
|
|
h,
|
|
home,
|
|
&w,
|
|
&mut scratch,
|
|
&mut host,
|
|
&mut heart_events,
|
|
);
|
|
added.append(&mut host.added);
|
|
}
|
|
for e in heart_events.drain(..) {
|
|
match e {
|
|
HeartEvent::Sound(name, _, volume, pitch) => {
|
|
events.push(MobEvent::Sound(name, [0.0; 3], volume, pitch))
|
|
}
|
|
HeartEvent::SetBlock(..) => heart_events_later.push(e),
|
|
HeartEvent::Mob(ev) => events.push(ev),
|
|
_ => {}
|
|
}
|
|
}
|
|
creaking::sway(&mut mobs[i], &mut events);
|
|
}
|
|
events.append(&mut mobs[i].outbox);
|
|
}
|
|
#[allow(unused_mut)] // filled only with the rng-trace feature
|
|
let mut traces: Vec<String> = Vec::new();
|
|
let mut pushes = Vec::new();
|
|
for i in 0..mobs.len() {
|
|
if mobs[i].removed {
|
|
continue;
|
|
}
|
|
let w = mob_world!(&snapshot);
|
|
let m = &mut mobs[i];
|
|
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
|
let from = events.len();
|
|
#[cfg(feature = "rng-trace")]
|
|
horizon_core::random::trace::set(true);
|
|
let alive = m.tick(&w, &mut scratch, &mut events);
|
|
#[cfg(feature = "rng-trace")]
|
|
{
|
|
horizon_core::random::trace::set(false);
|
|
for line in horizon_core::random::trace::take() {
|
|
traces.push(format!("{t} trace {i} {line}"));
|
|
}
|
|
}
|
|
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
|
|
if !alive {
|
|
m.removed = true;
|
|
}
|
|
horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from);
|
|
// ServerLevel ticks entities one after another: the ones
|
|
// after this mob see it as it is now.
|
|
if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) {
|
|
*e = seen(&mobs[i]);
|
|
e.alive &= !mobs[i].removed;
|
|
}
|
|
}
|
|
for m in &mut mobs {
|
|
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
|
}
|
|
let w = mob_world!(&snapshot);
|
|
// ServerLevel.tickBlockEntities: the hearts (none ticks once uprooted).
|
|
heart_events.append(&mut heart_events_later);
|
|
for (at, h) in &mut hearts {
|
|
let uprooted = registry
|
|
.state(w.world.block(at[0], at[1], at[2]))
|
|
.and_then(|s| s.properties.get("creaking_heart_state").cloned())
|
|
.is_some_and(|v| v == "uprooted");
|
|
if uprooted {
|
|
continue;
|
|
}
|
|
let mut host = Host {
|
|
mobs: &mut mobs,
|
|
added: Vec::new(),
|
|
types: &types,
|
|
created: &mut created,
|
|
spawning: s.spawning,
|
|
};
|
|
creaking_heart::server_tick(h, *at, &w, &mut scratch, &mut host, &mut heart_events);
|
|
added.append(&mut host.added);
|
|
}
|
|
drop(w);
|
|
mobs.append(&mut added);
|
|
for e in &heart_events {
|
|
match e {
|
|
HeartEvent::SetBlock(at, st) => world.set(at[0], at[1], at[2], *st)?,
|
|
HeartEvent::Sound(name, _, volume, pitch) => {
|
|
events.push(MobEvent::Sound(name, [0.0; 3], *volume, *pitch))
|
|
}
|
|
HeartEvent::Mob(ev) => events.push(ev.clone()),
|
|
_ => {}
|
|
}
|
|
}
|
|
for (i, m) in mobs.iter().enumerate() {
|
|
print(&mut out, t, i, m);
|
|
}
|
|
for e in &events {
|
|
if let MobEvent::Sound(name, _, volume, pitch) = e {
|
|
let _ = writeln!(
|
|
out,
|
|
"{t} sound minecraft:{name} {} {}",
|
|
f(*volume),
|
|
f(*pitch)
|
|
);
|
|
} else if let MobEvent::SoundId(name, _, volume, pitch) = e {
|
|
let _ = writeln!(out, "{t} sound {name} {} {}", f(*volume), f(*pitch));
|
|
} else if player_hurt(player.as_ref(), e) {
|
|
// The oracle's survival player, healed and made hurtable every tick,
|
|
// takes the damage (LivingEntity.playHurtSound).
|
|
let _ = writeln!(
|
|
out,
|
|
"{t} sound minecraft:entity.player.hurt 3f800000 3f800000"
|
|
);
|
|
}
|
|
}
|
|
for (at, h) in &hearts {
|
|
print_heart(&mut out, t, registry, &world, *at, h, &scratch);
|
|
}
|
|
for line in traces {
|
|
let _ = writeln!(out, "{line}");
|
|
}
|
|
}
|
|
}
|
|
fs::write(&args[2], out)?;
|
|
Ok(())
|
|
}
|