Add a differential mob AI harness and match vanilla mob movement math
VanillaMobAiOracle runs vanilla mobs in a real headless flat server level, ticking them as ServerLevel does while the rest of the level stands still; mob_ai_probe replays the same scenarios on Horizon. Both print each mob's AI-visible state every tick (position, motion, rotations, goals, targets, navigation, controls, input, brain activities and memories, sounds) and tools/test_mob_ai_parity.py reports the first divergence. Fixes found: float entity dimensions, Mth.sin/cos in moveRelative and the strafe/swim controls, Mth.atan2 and the float thresholds of the controls, RandomPos float constants, the ambient sound clock starting at zero, hurt and death sounds drawn from the mob's own random (also when burning), knockback for every damage type not tagged no_knockback, Entity.move's collision flags, restitution and footstep/swim sounds, and mob sound volumes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,505 @@
|
||||
//! 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,
|
||||
items::Items,
|
||||
light::{LightTables, light_chunk},
|
||||
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,
|
||||
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" => {}
|
||||
_ => 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()),
|
||||
"player" => {
|
||||
s.player = Some([
|
||||
f[1].parse().unwrap(),
|
||||
f[2].parse().unwrap(),
|
||||
f[3].parse().unwrap(),
|
||||
]);
|
||||
s.creative = f.get(4) == Some(&"creative");
|
||||
}
|
||||
"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",
|
||||
"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",
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
fn print(out: &mut String, t: i32, i: usize, m: &Mob) {
|
||||
let _ = write!(out, "{t} {i}");
|
||||
if m.removed {
|
||||
let _ = writeln!(out, " removed DISCARDED");
|
||||
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 _ = writeln!(
|
||||
out,
|
||||
"\tin {},{},{},{}",
|
||||
f(m.ai.xxa),
|
||||
f(m.ai.zza),
|
||||
f(m.ai.speed),
|
||||
u8::from(m.ai.jumping)
|
||||
);
|
||||
}
|
||||
|
||||
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 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;
|
||||
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,
|
||||
other => panic!("unknown mob flag {other}"),
|
||||
}
|
||||
}
|
||||
m.random = LegacyRandom::new(spec.seed);
|
||||
mobs.push(m);
|
||||
}
|
||||
let 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: None,
|
||||
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],
|
||||
}
|
||||
});
|
||||
let mut scratch = LegacyRandom::new(0);
|
||||
for t in 1..=s.ticks {
|
||||
world.game_time += 1;
|
||||
let snapshot: Vec<Seen> = mobs.iter().filter(|m| !m.removed).map(seen).collect();
|
||||
let w = MobWorld {
|
||||
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),
|
||||
};
|
||||
let mut events = Vec::new();
|
||||
for m in &mut mobs {
|
||||
if m.removed {
|
||||
continue;
|
||||
}
|
||||
if !m.tick(&w, &mut scratch, &mut events) {
|
||||
m.removed = true;
|
||||
}
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fs::write(&args[2], out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -4893,9 +4893,6 @@ impl Game<'_> {
|
||||
);
|
||||
}
|
||||
self.last_hurt_by_player.insert(mob.id);
|
||||
// getHurtSound / getDeathSound (by species state).
|
||||
let voice = horizon_client::mobs::ai::voice_sounds(mob);
|
||||
let dead = !mob.alive();
|
||||
let sound = if crit {
|
||||
"minecraft:entity.player.attack.crit"
|
||||
} else if scale > 0.9 {
|
||||
@@ -4904,10 +4901,15 @@ impl Game<'_> {
|
||||
"minecraft:entity.player.attack.weak"
|
||||
};
|
||||
self.audio.play(sound, Some(center), 1.0, 1.0);
|
||||
let event = format!("minecraft:{}", voice[if dead { 2 } else { 1 }]);
|
||||
let pitch =
|
||||
(self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0;
|
||||
self.audio.play(&event, Some(center), 1.0, pitch);
|
||||
// The hurt or death sound the mob raised (getHurtSound / getDeathSound,
|
||||
// its voice pitch from its own random).
|
||||
let queued = std::mem::take(&mut self.mobs[index].outbox);
|
||||
for event in queued {
|
||||
if let horizon_client::mobs::MobEvent::Sound(s, _, volume, pitch) = event {
|
||||
self.audio
|
||||
.play(&format!("minecraft:{s}"), Some(center), volume, pitch);
|
||||
}
|
||||
}
|
||||
self.post_attack(index);
|
||||
if let Some(stack) = self.inventory[self.selected].clone()
|
||||
&& let Some(max) = self
|
||||
|
||||
@@ -734,6 +734,12 @@ impl Game<'_> {
|
||||
self.tick_player_effects();
|
||||
self.piglin_pickups();
|
||||
self.sulfur_cube_pickups();
|
||||
// Hurt and death sounds of damage dealt outside the mob ticks.
|
||||
let mut queued = Vec::new();
|
||||
for m in &mut self.mobs {
|
||||
queued.append(&mut m.outbox);
|
||||
}
|
||||
self.handle_mob_events(queued)?;
|
||||
Ok(())
|
||||
}
|
||||
/// LivingEntity.die / dropAllDeathLoot.
|
||||
@@ -950,24 +956,18 @@ impl Game<'_> {
|
||||
if let Some(t) = self.mobs.iter_mut().find(|m| m.id == target) {
|
||||
let hit = t.damage(amount, source);
|
||||
if hit {
|
||||
let (voice, center, dead) = (
|
||||
horizon_client::mobs::ai::voice_sounds(t),
|
||||
t.center(),
|
||||
!t.alive(),
|
||||
);
|
||||
killed = dead;
|
||||
let pitch = (self.world.random.next_float()
|
||||
- self.world.random.next_float())
|
||||
* 0.2
|
||||
+ 1.0;
|
||||
let s = voice[if dead { 2 } else { 1 }];
|
||||
if !s.is_empty() {
|
||||
self.audio.play(
|
||||
&format!("minecraft:{s}"),
|
||||
Some(center),
|
||||
1.0,
|
||||
pitch,
|
||||
);
|
||||
killed = !t.alive();
|
||||
// The hurt or death sound the mob raised.
|
||||
let center = t.center();
|
||||
for event in std::mem::take(&mut t.outbox) {
|
||||
if let MobEvent::Sound(s, _, volume, pitch) = event {
|
||||
self.audio.play(
|
||||
&format!("minecraft:{s}"),
|
||||
Some(center),
|
||||
volume,
|
||||
pitch,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -419,6 +419,22 @@ impl Damage {
|
||||
DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava | DamageKind::Fireball
|
||||
)
|
||||
}
|
||||
/// DamageTypeTags.NO_KNOCKBACK
|
||||
pub fn no_knockback(&self) -> bool {
|
||||
matches!(
|
||||
self.kind,
|
||||
DamageKind::Explosion
|
||||
| DamageKind::Fall
|
||||
| DamageKind::OnFire
|
||||
| DamageKind::InFire
|
||||
| DamageKind::Lava
|
||||
| DamageKind::Drown
|
||||
| DamageKind::Magic
|
||||
| DamageKind::Cactus
|
||||
| DamageKind::Generic
|
||||
| DamageKind::InWall
|
||||
)
|
||||
}
|
||||
pub fn is_projectile(&self) -> bool {
|
||||
matches!(
|
||||
self.kind,
|
||||
@@ -589,6 +605,10 @@ pub struct Mob {
|
||||
pub attrs: Attrs,
|
||||
/// The player riding this mob and its input.
|
||||
pub rider: Option<equine::Rider>,
|
||||
/// Events raised outside a tick (hurt and death sounds of damage taken
|
||||
/// from the game), handed over with the next tick's events or drained
|
||||
/// by the game.
|
||||
pub outbox: Vec<MobEvent>,
|
||||
}
|
||||
/// Events a mob tick asks the game to act on.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -934,7 +954,8 @@ impl Mob {
|
||||
previous_limb_speed: 0.0,
|
||||
swell: 0,
|
||||
previous_swell: 0,
|
||||
ambient_timer: -kind.ambient_interval,
|
||||
// Mob.ambientSoundTime starts at 0.
|
||||
ambient_timer: 0,
|
||||
fall_distance: 0.0,
|
||||
persistent: false,
|
||||
random,
|
||||
@@ -955,6 +976,7 @@ impl Mob {
|
||||
name_visible: false,
|
||||
anim: anim::AnimState::default(),
|
||||
rider: None,
|
||||
outbox: Vec::new(),
|
||||
attrs: Attrs {
|
||||
speed: kind.speed,
|
||||
attack_damage: kind.attack_damage,
|
||||
@@ -1063,17 +1085,35 @@ impl Mob {
|
||||
self.ai.last_hurt_by_player = 100;
|
||||
}
|
||||
}
|
||||
if knock
|
||||
&& let Some(f) = source.from
|
||||
&& !matches!(source.kind, DamageKind::Explosion)
|
||||
{
|
||||
let (dx, dz) = (f[0] - self.position.x, f[2] - self.position.z);
|
||||
// dealDefaultKnockback, unless the damage type is tagged no_knockback;
|
||||
// a source without a position knocks in a random direction.
|
||||
if knock && !source.no_knockback() {
|
||||
let (dx, dz) = source
|
||||
.from
|
||||
.map_or((0.0, 0.0), |f| (f[0] - self.position.x, f[2] - self.position.z));
|
||||
self.knockback(0.4, dx, dz);
|
||||
}
|
||||
ai::after_hurt(self, &source);
|
||||
if self.health <= 0.0 {
|
||||
self.health = 0.0;
|
||||
}
|
||||
if knock {
|
||||
// playHurtSound (Mob: also resets the ambient sound clock) or the
|
||||
// death sound: makeSound draws the voice pitch whenever there is a sound.
|
||||
let dead = !self.alive();
|
||||
let sound = ai::voice_sounds(self)[if dead { 2 } else { 1 }];
|
||||
if !dead {
|
||||
self.ambient_timer = -self.kind.ambient_interval;
|
||||
}
|
||||
if !sound.is_empty() {
|
||||
let pitch = self.voice_pitch();
|
||||
if !self.silent {
|
||||
let at = [self.position.x, self.position.y, self.position.z];
|
||||
self.outbox
|
||||
.push(MobEvent::Sound(sound, at, ai::sound_volume(self), pitch));
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
/// LivingEntity.knockback(power, xd, zd) towards the negative direction.
|
||||
@@ -1082,7 +1122,7 @@ impl Mob {
|
||||
if power <= 0.0 {
|
||||
return;
|
||||
}
|
||||
while xd * xd + zd * zd < 1.0e-5 {
|
||||
while xd * xd + zd * zd < f64::from(1.0e-5_f32) {
|
||||
xd = (self.random.next_double() - self.random.next_double()) * 0.01;
|
||||
zd = (self.random.next_double() - self.random.next_double()) * 0.01;
|
||||
}
|
||||
@@ -1158,10 +1198,14 @@ impl Mob {
|
||||
let at = [self.position.x, self.eye_y(), self.position.z];
|
||||
events.push(MobEvent::Sound(event, at, 1.0, 1.0));
|
||||
}
|
||||
/// LivingEntity.getVoicePitch.
|
||||
pub fn voice_pitch(&mut self) -> f32 {
|
||||
(self.random.next_float() - self.random.next_float()) * 0.2
|
||||
+ if self.is_baby() { 1.5 } else { 1.0 }
|
||||
}
|
||||
/// Mob.playSound with LivingEntity.getVoicePitch.
|
||||
pub fn voice(&mut self, event: &'static str, events: &mut Vec<MobEvent>) {
|
||||
let pitch = (self.random.next_float() - self.random.next_float()) * 0.2
|
||||
+ if self.is_baby() { 1.5 } else { 1.0 };
|
||||
let pitch = self.voice_pitch();
|
||||
let at = [self.position.x, self.eye_y(), self.position.z];
|
||||
events.push(MobEvent::Sound(event, at, ai::sound_volume(self), pitch));
|
||||
}
|
||||
|
||||
@@ -47,6 +47,8 @@ pub struct Ai {
|
||||
/// Swing animation progress (attackAnim) and ticks.
|
||||
pub swing_time: i32,
|
||||
pub swinging: bool,
|
||||
/// Walked distance and the next footstep.
|
||||
pub steps: super::living::Steps,
|
||||
}
|
||||
impl Mob {
|
||||
/// LivingEntity.swing
|
||||
@@ -298,6 +300,7 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
|
||||
if m.alive() {
|
||||
m.body_rotation_tick();
|
||||
}
|
||||
events.append(&mut m.outbox);
|
||||
m.update_walk_animation();
|
||||
m.anim.end_tick(m.ai.swinging);
|
||||
tick_swing(m);
|
||||
@@ -326,6 +329,9 @@ fn tick_swing(m: &mut Mob) {
|
||||
/// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick.
|
||||
fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
m.fluids = w.fluids(m.bounds(), m.eye_y());
|
||||
if m.fluids.in_water {
|
||||
m.fall_distance = 0.0;
|
||||
}
|
||||
// Fire: water extinguishes, lava ignites, burning hurts every second.
|
||||
if m.fluids.in_water && m.fire_ticks > 0 {
|
||||
m.fire_ticks = 0;
|
||||
@@ -401,6 +407,8 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
if !m.alive() {
|
||||
m.death_time += 1;
|
||||
}
|
||||
// Hurt sounds of the damage above come before the ambient sound.
|
||||
events.append(&mut m.outbox);
|
||||
// Mob.baseTick: ambient sounds.
|
||||
if m.alive() {
|
||||
let roll = m.random.next_int_bound(1000).unwrap_or(999);
|
||||
@@ -752,17 +760,15 @@ pub fn sound_volume(m: &Mob) -> f32 {
|
||||
Species::Slime | Species::MagmaCube | Species::SulfurCube => {
|
||||
0.4 * m.extra.size.max(1) as f32
|
||||
}
|
||||
Species::Cod
|
||||
| Species::Salmon
|
||||
| Species::TropicalFish
|
||||
| Species::Pufferfish
|
||||
| Species::Bat => 0.1,
|
||||
Species::Squid | Species::GlowSquid => 0.4,
|
||||
Species::Horse
|
||||
| Species::Donkey
|
||||
| Species::Mule
|
||||
| Species::Llama
|
||||
| Species::TraderLlama => 0.8,
|
||||
Species::Bat => 0.1,
|
||||
Species::Squid
|
||||
| Species::GlowSquid
|
||||
| Species::Cow
|
||||
| Species::Mooshroom
|
||||
| Species::Bee
|
||||
| Species::Allay
|
||||
| Species::Wolf => 0.4,
|
||||
s if super::equine::is_equine(s) => 0.8,
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
@@ -972,3 +978,127 @@ fn tick_effects(m: &mut Mob) {
|
||||
effects.retain(|e| e.1 > 0);
|
||||
m.extra.effects = effects;
|
||||
}
|
||||
|
||||
/// `Entity.getMovementEmission` is not NONE (silverfish, endermites,
|
||||
/// shulkers, guardians and breezes emit only events, no step sounds).
|
||||
pub fn emits_movement(m: &Mob) -> bool {
|
||||
!matches!(m.species(), Species::Shulker)
|
||||
}
|
||||
/// The movement emission includes sounds.
|
||||
pub fn movement_sounds(m: &Mob) -> bool {
|
||||
!matches!(
|
||||
m.species(),
|
||||
Species::Silverfish
|
||||
| Species::Endermite
|
||||
| Species::Guardian
|
||||
| Species::ElderGuardian
|
||||
| Species::Breeze
|
||||
)
|
||||
}
|
||||
/// `playStepSound`: the species' footstep, or the block's step sound at 15%.
|
||||
pub fn step_sound(
|
||||
m: &Mob,
|
||||
w: &MobWorld,
|
||||
pos: [i32; 3],
|
||||
state: horizon_world::registry::BlockStateId,
|
||||
) -> Option<(&'static str, f32, f32)> {
|
||||
use Species as S;
|
||||
let baby = m.is_baby();
|
||||
let quiet = |s: &'static str| Some((s, 0.15, 1.0));
|
||||
match m.species() {
|
||||
// Silent footsteps, or only movement events.
|
||||
S::Allay
|
||||
| S::Bee
|
||||
| S::Cod
|
||||
| S::Salmon
|
||||
| S::TropicalFish
|
||||
| S::Pufferfish
|
||||
| S::Tadpole
|
||||
| S::HappyGhast
|
||||
| S::Nautilus
|
||||
| S::ZombieNautilus
|
||||
| S::Silverfish
|
||||
| S::Endermite
|
||||
| S::Guardian
|
||||
| S::ElderGuardian
|
||||
| S::Breeze => None,
|
||||
S::Armadillo => quiet("entity.armadillo.step"),
|
||||
S::Chicken if baby => quiet("entity.baby_chicken.step"),
|
||||
S::Chicken => quiet("entity.chicken.step"),
|
||||
S::Cow | S::Mooshroom => quiet("entity.cow.step"),
|
||||
S::Pig if baby => quiet("entity.baby_pig.step"),
|
||||
S::Pig => quiet("entity.pig.step"),
|
||||
S::Wolf => quiet("entity.wolf.step"),
|
||||
S::Llama | S::TraderLlama => quiet("entity.llama.step"),
|
||||
S::Frog => quiet("entity.frog.step"),
|
||||
S::Goat => quiet("entity.goat.step"),
|
||||
S::Panda => quiet("entity.panda.step"),
|
||||
S::Parrot => quiet("entity.parrot.step"),
|
||||
S::PolarBear => quiet("entity.polar_bear.step"),
|
||||
S::Sheep => quiet("entity.sheep.step"),
|
||||
S::Sniffer => quiet("entity.sniffer.step"),
|
||||
S::Turtle if baby => quiet("entity.turtle.shamble_baby"),
|
||||
S::Turtle => quiet("entity.turtle.shamble"),
|
||||
S::Creaking => quiet("entity.creaking.step"),
|
||||
S::Hoglin => quiet("entity.hoglin.step"),
|
||||
S::Zoglin => quiet("entity.zoglin.step"),
|
||||
S::Piglin => quiet("entity.piglin.step"),
|
||||
S::PiglinBrute => quiet("entity.piglin_brute.step"),
|
||||
S::Ravager => quiet("entity.ravager.step"),
|
||||
S::Skeleton => quiet("entity.skeleton.step"),
|
||||
S::Stray => quiet("entity.stray.step"),
|
||||
S::Bogged => quiet("entity.bogged.step"),
|
||||
S::Parched => quiet("entity.parched.step"),
|
||||
S::WitherSkeleton => quiet("entity.wither_skeleton.step"),
|
||||
S::Spider | S::CaveSpider => quiet("entity.spider.step"),
|
||||
S::Zombie | S::ZombifiedPiglin => quiet("entity.zombie.step"),
|
||||
S::Husk => quiet("entity.husk.step"),
|
||||
S::Drowned => quiet("entity.drowned.step"),
|
||||
S::ZombieVillager => quiet("entity.zombie_villager.step"),
|
||||
S::CamelHusk => Some(("entity.camel_husk.step", 0.4, 1.0)),
|
||||
S::Camel => Some(("entity.camel.step", 1.0, 1.0)),
|
||||
S::IronGolem => Some(("entity.iron_golem.step", 1.0, 1.0)),
|
||||
S::Strider if m.fluids.in_lava => Some(("entity.strider.step_lava", 1.0, 1.0)),
|
||||
S::Strider => Some(("entity.strider.step", 1.0, 1.0)),
|
||||
S::Warden => Some(("entity.warden.step", 10.0, 1.0)),
|
||||
_ => {
|
||||
// Entity.playStepSound: the block's sound type.
|
||||
let _ = pos;
|
||||
let sounds = &w.facts.get(state).sounds;
|
||||
let step: &'static str = super::ai::intern_sound(&sounds.step);
|
||||
Some((step, sounds.volume * 0.15, sounds.pitch))
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A block sound id as a static string (the block facts intern them).
|
||||
pub fn intern_sound(s: &std::sync::Arc<str>) -> &'static str {
|
||||
use std::{collections::HashSet, sync::Mutex};
|
||||
static NAMES: Mutex<Option<HashSet<&'static str>>> = Mutex::new(None);
|
||||
let mut names = NAMES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let set = names.get_or_insert_with(HashSet::new);
|
||||
let key = s.strip_prefix("minecraft:").unwrap_or(s);
|
||||
if let Some(found) = set.get(key) {
|
||||
return found;
|
||||
}
|
||||
let leaked: &'static str = Box::leak(key.to_owned().into_boxed_str());
|
||||
set.insert(leaked);
|
||||
leaked
|
||||
}
|
||||
/// `getSwimSound`.
|
||||
pub fn swim_sound(m: &Mob) -> &'static str {
|
||||
match m.species() {
|
||||
Species::Drowned => "entity.drowned.swim",
|
||||
Species::Axolotl => "entity.axolotl.swim",
|
||||
Species::Dolphin => "entity.dolphin.swim",
|
||||
Species::Cod
|
||||
| Species::Salmon
|
||||
| Species::TropicalFish
|
||||
| Species::Pufferfish
|
||||
| Species::Tadpole => "entity.fish.swim",
|
||||
Species::Nautilus if m.is_baby() => "entity.baby_nautilus.swim",
|
||||
Species::Nautilus => "entity.nautilus.swim",
|
||||
Species::ZombieNautilus => "entity.zombie_nautilus.swim",
|
||||
Species::Turtle => "entity.turtle.swim",
|
||||
_ => "entity.generic.swim",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
//! Mob controls: `MoveControl` (with the flying and smooth-swimming
|
||||
//! variants), `LookControl`, `JumpControl` and `BodyRotationControl`.
|
||||
use super::{Mob, MobWorld, living::wrap};
|
||||
use horizon_core::geometry::trig;
|
||||
|
||||
/// `2.5000003E-7F` widened: the squared distance controls treat as arrived.
|
||||
const ARRIVED: f64 = 2.500_000_3e-7_f32 as f64;
|
||||
/// `1.0E-5F` widened.
|
||||
const EPSILON: f64 = 1.0e-5_f32 as f64;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Operation {
|
||||
@@ -117,8 +123,8 @@ impl Mob {
|
||||
let (dx, dz) = (at[0] - self.position.x, at[2] - self.position.z);
|
||||
let dy = at[1] - self.eye_y();
|
||||
let sd = (dx * dx + dz * dz).sqrt();
|
||||
let y_rot = (dz.atan2(dx).to_degrees() as f32) - 90.0;
|
||||
let x_rot = -(dy.atan2(sd).to_degrees() as f32);
|
||||
let y_rot = trig::atan2_degrees(dz, dx) - 90.0;
|
||||
let x_rot = -trig::atan2_degrees(dy, sd);
|
||||
self.head_pitch = rotate_toward_max(self.head_pitch, x_rot, x_max);
|
||||
self.yaw = rotate_toward_max(self.yaw, y_rot, y_max);
|
||||
}
|
||||
@@ -139,12 +145,12 @@ impl Mob {
|
||||
wy - self.position.y,
|
||||
wz - self.position.z,
|
||||
);
|
||||
if xd * xd + yd * yd + zd * zd < 2.500_000_3e-7 {
|
||||
if xd * xd + yd * yd + zd * zd < ARRIVED {
|
||||
self.ai.yya = 0.0;
|
||||
self.ai.zza = 0.0;
|
||||
return;
|
||||
}
|
||||
let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0;
|
||||
let y_rot = trig::atan2_degrees(zd, xd) - 90.0;
|
||||
self.yaw = rotlerp(self.yaw, y_rot, 90.0);
|
||||
let speed = (self.ai.mov.speed_modifier
|
||||
* if self.on_ground {
|
||||
@@ -154,8 +160,8 @@ impl Mob {
|
||||
}) as f32;
|
||||
self.set_speed(speed);
|
||||
let sd = (xd * xd + zd * zd).sqrt();
|
||||
if yd.abs() > 1.0e-5 || sd.abs() > 1.0e-5 {
|
||||
let x_rot = -(yd.atan2(sd).to_degrees() as f32);
|
||||
if yd.abs() > EPSILON || sd.abs() > EPSILON {
|
||||
let x_rot = -trig::atan2_degrees(yd, sd);
|
||||
self.head_pitch = rotlerp(self.head_pitch, x_rot, max_turn);
|
||||
self.ai.yya = if yd > 0.0 { speed } else { -speed };
|
||||
}
|
||||
@@ -184,10 +190,10 @@ impl Mob {
|
||||
wy - self.position.y,
|
||||
wz - self.position.z,
|
||||
);
|
||||
if xd * xd + yd * yd + zd * zd < 2.500_000_3e-7 {
|
||||
if xd * xd + yd * yd + zd * zd < ARRIVED {
|
||||
self.ai.zza = 0.0;
|
||||
} else {
|
||||
let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0;
|
||||
let y_rot = trig::atan2_degrees(zd, xd) - 90.0;
|
||||
self.yaw = rotlerp(self.yaw, y_rot, max_turn_y);
|
||||
self.body_yaw = self.yaw;
|
||||
self.head_yaw = self.yaw;
|
||||
@@ -195,15 +201,13 @@ impl Mob {
|
||||
if self.fluids.in_water {
|
||||
self.ai.speed = speed * in_water;
|
||||
let sd = (xd * xd + zd * zd).sqrt();
|
||||
if yd.abs() > 1.0e-5 || sd.abs() > 1.0e-5 {
|
||||
let x_rot = -(yd.atan2(sd).to_degrees() as f32);
|
||||
if yd.abs() > EPSILON || sd.abs() > EPSILON {
|
||||
let x_rot = -trig::atan2_degrees(yd, sd);
|
||||
let x_rot = wrap(x_rot).clamp(-max_turn_x, max_turn_x);
|
||||
self.head_pitch = rotate_towards(self.head_pitch, x_rot, 5.0);
|
||||
}
|
||||
let (c, s) = (
|
||||
self.head_pitch.to_radians().cos(),
|
||||
self.head_pitch.to_radians().sin(),
|
||||
);
|
||||
let angle = f64::from(self.head_pitch * trig::DEG_TO_RAD);
|
||||
let (c, s) = (trig::cos(angle), trig::sin(angle));
|
||||
self.ai.zza = c * speed;
|
||||
self.ai.yya = -s * speed;
|
||||
} else {
|
||||
@@ -229,7 +233,7 @@ impl Mob {
|
||||
fn ground_move_tick(&mut self, w: &MobWorld, attr_speed: f64) {
|
||||
match self.ai.mov.operation {
|
||||
Operation::Strafe => {
|
||||
let speed = (self.ai.mov.speed_modifier * attr_speed) as f32;
|
||||
let speed = self.ai.mov.speed_modifier as f32 * attr_speed as f32;
|
||||
let (mut xa, mut za) = (self.ai.mov.strafe_forwards, self.ai.mov.strafe_right);
|
||||
let mut dist = (xa * xa + za * za).sqrt();
|
||||
if dist < 1.0 {
|
||||
@@ -238,7 +242,8 @@ impl Mob {
|
||||
dist = speed / dist;
|
||||
xa *= dist;
|
||||
za *= dist;
|
||||
let (s, c) = (self.yaw.to_radians().sin(), self.yaw.to_radians().cos());
|
||||
let angle = f64::from(self.yaw * trig::DEG_TO_RAD);
|
||||
let (s, c) = (trig::sin(angle), trig::cos(angle));
|
||||
let dx = xa * c - za * s;
|
||||
let dz = za * c + xa * s;
|
||||
if !self.walkable(w, dx, dz) {
|
||||
@@ -258,11 +263,11 @@ impl Mob {
|
||||
wy - self.position.y,
|
||||
wz - self.position.z,
|
||||
);
|
||||
if xd * xd + yd * yd + zd * zd < 2.500_000_3e-7 {
|
||||
if xd * xd + yd * yd + zd * zd < ARRIVED {
|
||||
self.ai.zza = 0.0;
|
||||
return;
|
||||
}
|
||||
let y_rot = (zd.atan2(xd).to_degrees() as f32) - 90.0;
|
||||
let y_rot = trig::atan2_degrees(zd, xd) - 90.0;
|
||||
self.yaw = rotlerp(self.yaw, y_rot, 90.0);
|
||||
self.set_speed((self.ai.mov.speed_modifier * attr_speed) as f32);
|
||||
let (bx, by, bz) = (
|
||||
@@ -359,9 +364,9 @@ impl Mob {
|
||||
);
|
||||
let sd = (xd * xd + zd * zd).sqrt();
|
||||
let x =
|
||||
(yd.abs() > 1.0e-5 || sd.abs() > 1.0e-5).then(|| -(yd.atan2(sd).to_degrees() as f32));
|
||||
let y = (zd.abs() > 1.0e-5 || xd.abs() > 1.0e-5)
|
||||
.then(|| (zd.atan2(xd).to_degrees() as f32) - 90.0);
|
||||
(yd.abs() > EPSILON || sd.abs() > EPSILON).then(|| -trig::atan2_degrees(yd, sd));
|
||||
let y = (zd.abs() > EPSILON || xd.abs() > EPSILON)
|
||||
.then(|| trig::atan2_degrees(zd, xd) - 90.0);
|
||||
(x, y)
|
||||
}
|
||||
/// JumpControl.tick.
|
||||
@@ -374,7 +379,7 @@ impl Mob {
|
||||
let dx = self.position.x - self.previous.x;
|
||||
let dz = self.position.z - self.previous.z;
|
||||
let max = self.kind.max_head_y_rot;
|
||||
if dx * dx + dz * dz > 2.500_000_3e-7 {
|
||||
if dx * dx + dz * dz > ARRIVED {
|
||||
self.body_yaw = self.yaw;
|
||||
self.head_yaw = rotate_if_necessary(self.head_yaw, self.body_yaw, max);
|
||||
self.ai.body.last_stable_head = self.head_yaw;
|
||||
|
||||
@@ -196,10 +196,12 @@ impl Mob {
|
||||
zd: f64,
|
||||
max_rad: f64,
|
||||
) -> Option<[i32; 3]> {
|
||||
let center = zd.atan2(xd) - std::f64::consts::FRAC_PI_2;
|
||||
let center =
|
||||
horizon_core::geometry::trig::atan2(zd, xd) - f64::from(std::f32::consts::FRAC_PI_2);
|
||||
let yrad = center + f64::from(2.0 * self.random.next_float() - 1.0) * max_rad;
|
||||
let dist =
|
||||
(min + self.random.next_double().sqrt() * (max - min)) * std::f64::consts::SQRT_2;
|
||||
(min + self.random.next_double().sqrt() * (max - min))
|
||||
* f64::from(std::f32::consts::SQRT_2);
|
||||
let xt = -dist * yrad.sin();
|
||||
let zt = dist * yrad.cos();
|
||||
if xt.abs() > max || zt.abs() > max {
|
||||
|
||||
@@ -4,8 +4,27 @@
|
||||
//! damage, fire and the walk animation.
|
||||
use super::{Mob, MobEvent, MobWorld};
|
||||
use crate::{blocks::Fluid, collisions::SceneCollisions};
|
||||
use horizon_core::geometry::{Aabb, Vec3};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3, trig},
|
||||
random::RandomSource,
|
||||
};
|
||||
|
||||
/// `Entity.moveDist`, `flyDist` and `nextStep`.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Steps {
|
||||
pub move_dist: f32,
|
||||
pub fly_dist: f32,
|
||||
pub next_step: f32,
|
||||
}
|
||||
impl Default for Steps {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
move_dist: 0.0,
|
||||
fly_dist: 0.0,
|
||||
next_step: 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Fluids {
|
||||
pub water: f64,
|
||||
@@ -87,18 +106,22 @@ impl Mob {
|
||||
}
|
||||
/// Entity dimensions: the type's, a class's BABY_DIMENSIONS, or the
|
||||
/// slime size scaling.
|
||||
/// `EntityDimensions` (float width, height and eye height) widened to double.
|
||||
pub fn dims(&self) -> (f64, f64, f64) {
|
||||
let k = &self.kind;
|
||||
let (mut w, mut h, mut e) = (k.width, k.height, k.eye_height);
|
||||
let (mut w, mut h, mut e) = (k.width as f32, k.height as f32, k.eye_height as f32);
|
||||
// Sniffer.DIGGING_DIMENSIONS: 0.4 lower, its eyes at 0.81.
|
||||
if k.species == super::Species::Sniffer && super::sniffer::digging(self) {
|
||||
(h, e) = (h - f64::from(0.4_f32), f64::from(0.81_f32));
|
||||
(h, e) = (h - 0.4, 0.81);
|
||||
}
|
||||
if self.is_baby() {
|
||||
match super::species::def(k.species).baby {
|
||||
super::species::Baby::Abs(bw, bh, be) => (w, h, e) = (bw, bh, be),
|
||||
super::species::Baby::Abs(bw, bh, be) => {
|
||||
(w, h, e) = (bw as f32, bh as f32, be as f32)
|
||||
}
|
||||
super::species::Baby::Scale(s, eye) => {
|
||||
(w, h, e) = (w * s, h * s, eye.unwrap_or(e * s))
|
||||
let s = s as f32;
|
||||
(w, h, e) = (w * s, h * s, eye.map_or(e * s, |x| x as f32))
|
||||
}
|
||||
super::species::Baby::None => {}
|
||||
}
|
||||
@@ -109,13 +132,13 @@ impl Mob {
|
||||
e = 0.85;
|
||||
}
|
||||
if self.kind.species == super::Species::Pufferfish {
|
||||
let s = super::aquatic::puff_scale(self.extra.size);
|
||||
let s = super::aquatic::puff_scale(self.extra.size) as f32;
|
||||
(w, h, e) = (w * s, h * s, e * s);
|
||||
} else if self.extra.size > 0 {
|
||||
let s = f64::from(self.extra.size);
|
||||
let s = self.extra.size as f32;
|
||||
(w, h, e) = (w * s, h * s, e * s);
|
||||
}
|
||||
(w, h, e)
|
||||
(f64::from(w), f64::from(h), f64::from(e))
|
||||
}
|
||||
pub fn eye_height(&self) -> f64 {
|
||||
self.dims().2
|
||||
@@ -149,8 +172,13 @@ impl Mob {
|
||||
return;
|
||||
}
|
||||
let v = if len_sq > 1.0 {
|
||||
// Vec3.normalize
|
||||
let l = len_sq.sqrt();
|
||||
Vec3::new(input.x / l, input.y / l, input.z / l)
|
||||
if l < f64::from(1.0e-5_f32) {
|
||||
Vec3::ZERO
|
||||
} else {
|
||||
Vec3::new(input.x / l, input.y / l, input.z / l)
|
||||
}
|
||||
} else {
|
||||
input
|
||||
};
|
||||
@@ -159,10 +187,8 @@ impl Mob {
|
||||
v.y * f64::from(speed),
|
||||
v.z * f64::from(speed),
|
||||
);
|
||||
let (s, c) = (
|
||||
f64::from(self.yaw.to_radians().sin()),
|
||||
f64::from(self.yaw.to_radians().cos()),
|
||||
);
|
||||
let angle = f64::from(self.yaw * trig::DEG_TO_RAD);
|
||||
let (s, c) = (f64::from(trig::sin(angle)), f64::from(trig::cos(angle)));
|
||||
self.velocity = Vec3::new(
|
||||
self.velocity.x + (v.x * c - v.z * s),
|
||||
self.velocity.y + v.y,
|
||||
@@ -181,38 +207,128 @@ impl Mob {
|
||||
let moved = scene
|
||||
.resolve(self.bounds(), wanted, step, self.on_ground)
|
||||
.unwrap_or(Vec3::ZERO);
|
||||
self.position = Vec3::new(
|
||||
self.position.x + moved.x,
|
||||
self.position.y + moved.y,
|
||||
self.position.z + moved.z,
|
||||
);
|
||||
let x_hit = (moved.x - wanted.x).abs() > 1.0e-5;
|
||||
let z_hit = (moved.z - wanted.z).abs() > 1.0e-5;
|
||||
let length = moved.x * moved.x + moved.y * moved.y + moved.z * moved.z;
|
||||
let wanted_length = wanted.x * wanted.x + wanted.y * wanted.y + wanted.z * wanted.z;
|
||||
if length > 1.0e-7 || wanted_length - length < 1.0e-7 {
|
||||
self.position = Vec3::new(
|
||||
self.position.x + moved.x,
|
||||
self.position.y + moved.y,
|
||||
self.position.z + moved.z,
|
||||
);
|
||||
}
|
||||
// !Mth.equal(delta, movement)
|
||||
let differs = |a: f64, b: f64| (b - a).abs() >= f64::from(1.0e-5_f32);
|
||||
let x_hit = differs(wanted.x, moved.x);
|
||||
let z_hit = differs(wanted.z, moved.z);
|
||||
self.horizontal_collision = x_hit || z_hit;
|
||||
let vertical = (moved.y - wanted.y).abs() > 1.0e-5;
|
||||
self.vertical_collision_below = vertical && wanted.y < 0.0;
|
||||
self.on_ground = self.vertical_collision_below;
|
||||
if x_hit {
|
||||
self.velocity.x = 0.0;
|
||||
let moved_vertically = wanted.y.abs() > 0.0;
|
||||
let mut vertical = false;
|
||||
if moved_vertically {
|
||||
vertical = wanted.y != moved.y;
|
||||
self.vertical_collision_below = vertical && wanted.y < 0.0;
|
||||
self.on_ground = self.vertical_collision_below;
|
||||
}
|
||||
if z_hit {
|
||||
self.velocity.z = 0.0;
|
||||
}
|
||||
if vertical {
|
||||
self.velocity.y = 0.0;
|
||||
// LivingEntity.checkFallDamage refreshes the fluid state out of water
|
||||
// (touching water resets the fall).
|
||||
if !self.fluids.in_water {
|
||||
self.fluids = w.fluids(self.bounds(), self.eye_y());
|
||||
if self.fluids.in_water {
|
||||
self.fall_distance = 0.0;
|
||||
}
|
||||
}
|
||||
// Entity.checkFallDamage
|
||||
if !self.fluids.in_water && moved.y < 0.0 {
|
||||
self.fall_distance -= f64::from(moved.y as f32);
|
||||
}
|
||||
if self.on_ground {
|
||||
if self.fall_distance > 0.0 {
|
||||
self.cause_fall_damage(events);
|
||||
}
|
||||
self.fall_distance = 0.0;
|
||||
} else if moved.y < 0.0 {
|
||||
self.fall_distance -= moved.y;
|
||||
}
|
||||
if self.fluids.in_water {
|
||||
self.fall_distance = 0.0;
|
||||
// restituteMovementAfterCollisions with no bounciness: the colliding
|
||||
// components become (signed) zero.
|
||||
if moved_vertically && vertical || self.horizontal_collision {
|
||||
let v = self.velocity;
|
||||
if x_hit {
|
||||
self.velocity.x = -v.x * 0.0;
|
||||
}
|
||||
if z_hit {
|
||||
self.velocity.z = -v.z * 0.0;
|
||||
}
|
||||
if vertical {
|
||||
self.velocity.y = (0.0 - v.y) * 1.0 * 0.0;
|
||||
}
|
||||
}
|
||||
self.movement_emission(w, moved, events);
|
||||
}
|
||||
/// Entity.applyMovementEmissionAndPlaySound: walked distance, footsteps
|
||||
/// and swimming sounds.
|
||||
fn movement_emission(&mut self, w: &MobWorld, moved: Vec3, events: &mut Vec<MobEvent>) {
|
||||
if !super::ai::emits_movement(self) || self.extra.mount.is_some() {
|
||||
return;
|
||||
}
|
||||
let full = (moved.length() * f64::from(0.6_f32)) as f32;
|
||||
let horizontal =
|
||||
((moved.x * moved.x + moved.z * moved.z).sqrt() * f64::from(0.6_f32)) as f32;
|
||||
let on = self.on_pos(1.0e-5);
|
||||
let state = w.world.block(on[0], on[1], on[2]);
|
||||
let climbable = w.facts.get(state).name.as_ref() == "minecraft:powder_snow"
|
||||
|| w.has_tag("minecraft:climbable", &w.facts.get(state).name);
|
||||
let steps = &mut self.ai.steps;
|
||||
steps.move_dist += if climbable { full } else { horizontal };
|
||||
steps.fly_dist += full;
|
||||
if steps.move_dist > steps.next_step && !w.facts.is_air(state) {
|
||||
let legacy = self.on_pos(0.2);
|
||||
let legacy_state = w.world.block(legacy[0], legacy[1], legacy[2]);
|
||||
let produced = !w.facts.is_air(legacy_state)
|
||||
&& (self.on_ground || climbable)
|
||||
&& !self.fluids_swimming();
|
||||
if produced {
|
||||
if let Some((sound, volume, pitch)) =
|
||||
super::ai::step_sound(self, w, legacy, legacy_state)
|
||||
&& !self.silent
|
||||
{
|
||||
let at = [self.position.x, self.position.y, self.position.z];
|
||||
events.push(MobEvent::Sound(sound, at, volume, pitch));
|
||||
}
|
||||
self.ai.steps.next_step = (self.ai.steps.move_dist as i32).wrapping_add(1) as f32;
|
||||
} else if self.fluids.in_water {
|
||||
self.ai.steps.next_step = (self.ai.steps.move_dist as i32).wrapping_add(1) as f32;
|
||||
// Entity.waterSwimSound
|
||||
let v = self.velocity;
|
||||
let volume = 1.0_f32.min(
|
||||
(v.x * v.x * f64::from(0.2_f32) + v.y * v.y + v.z * v.z * f64::from(0.2_f32))
|
||||
.sqrt() as f32
|
||||
* 0.35,
|
||||
);
|
||||
if !super::ai::movement_sounds(self) {
|
||||
return;
|
||||
}
|
||||
let pitch = 1.0 + (self.random.next_float() - self.random.next_float()) * 0.4;
|
||||
if !self.silent {
|
||||
let at = [self.position.x, self.position.y, self.position.z];
|
||||
events.push(MobEvent::Sound(
|
||||
super::ai::swim_sound(self),
|
||||
at,
|
||||
volume,
|
||||
pitch,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Entity.isSwimming (mobs never swim in the player sense).
|
||||
fn fluids_swimming(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// Entity.getOnPos(offset) without a supporting block record.
|
||||
pub fn on_pos(&self, offset: f32) -> [i32; 3] {
|
||||
[
|
||||
self.position.x.floor() as i32,
|
||||
(self.position.y - f64::from(offset)).floor() as i32,
|
||||
self.position.z.floor() as i32,
|
||||
]
|
||||
}
|
||||
fn cause_fall_damage(&mut self, events: &mut Vec<MobEvent>) {
|
||||
if self.kind.flags.fall_immune {
|
||||
|
||||
@@ -23,6 +23,62 @@ pub fn cos(angle: f64) -> f32 {
|
||||
sine_table()[((angle * SCALE + 16384.0) as i64 & 65535) as usize]
|
||||
}
|
||||
|
||||
/// `Mth.atan2`: vanilla's table-driven arctangent.
|
||||
pub fn atan2(mut y: f64, mut x: f64) -> f64 {
|
||||
static TABLES: OnceLock<(Vec<f64>, Vec<f64>)> = OnceLock::new();
|
||||
let (asin, cos) = TABLES.get_or_init(|| {
|
||||
(0..257)
|
||||
.map(|i| {
|
||||
let a = (f64::from(i) / 256.0).asin();
|
||||
(a, a.cos())
|
||||
})
|
||||
.unzip()
|
||||
});
|
||||
let frac_bias = f64::from_bits(4_805_340_802_404_319_232);
|
||||
let d2 = x * x + y * y;
|
||||
if d2.is_nan() {
|
||||
return f64::NAN;
|
||||
}
|
||||
let negative_y = y < 0.0;
|
||||
if negative_y {
|
||||
y = -y;
|
||||
}
|
||||
let negative_x = x < 0.0;
|
||||
if negative_x {
|
||||
x = -x;
|
||||
}
|
||||
let steep = y > x;
|
||||
if steep {
|
||||
std::mem::swap(&mut x, &mut y);
|
||||
}
|
||||
// Mth.fastInvSqrt
|
||||
let half = 0.5 * d2;
|
||||
let mut r = f64::from_bits((6_910_469_410_427_058_090i64 - (d2.to_bits() as i64 >> 1)) as u64);
|
||||
r *= 1.5 - half * r * r;
|
||||
x *= r;
|
||||
y *= r;
|
||||
let yp = frac_bias + y;
|
||||
let index = yp.to_bits() as i32 as usize;
|
||||
let s_phi = yp - frac_bias;
|
||||
let sd = y * cos[index] - x * s_phi;
|
||||
let mut theta = asin[index] + (6.0 + sd * sd) * sd * 0.166_666_666_666_666_66;
|
||||
if steep {
|
||||
theta = std::f64::consts::FRAC_PI_2 - theta;
|
||||
}
|
||||
if negative_x {
|
||||
theta = std::f64::consts::PI - theta;
|
||||
}
|
||||
if negative_y {
|
||||
theta = -theta;
|
||||
}
|
||||
theta
|
||||
}
|
||||
/// `(float)(Mth.atan2(y, x) * 180.0F / (float)Math.PI)`: the angle in degrees
|
||||
/// as the AI controls compute it.
|
||||
pub fn atan2_degrees(y: f64, x: f64) -> f32 {
|
||||
(atan2(y, x) * 180.0 / f64::from(std::f32::consts::PI)) as f32
|
||||
}
|
||||
|
||||
/// `Mth.sin` / `Mth.cos` on a float, as the models call them.
|
||||
pub trait Mth {
|
||||
fn msin(self) -> f32;
|
||||
|
||||
@@ -0,0 +1,563 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.serialization.Lifecycle;
|
||||
import io.netty.channel.embedded.EmbeddedChannel;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.Proxy;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.SystemReport;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.arguments.blocks.BlockStateParser;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.GlobalPos;
|
||||
import net.minecraft.core.MappedRegistry;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.gametest.framework.GameTestServer;
|
||||
import net.minecraft.gizmos.GizmoCollector;
|
||||
import net.minecraft.gizmos.Gizmos;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.PacketFlow;
|
||||
import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundSoundPacket;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.Services;
|
||||
import net.minecraft.server.WorldLoader;
|
||||
import net.minecraft.server.WorldStem;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.level.progress.LoggingLevelLoadListener;
|
||||
import net.minecraft.server.network.CommonListenerCookie;
|
||||
import net.minecraft.server.notifications.EmptyNotificationService;
|
||||
import net.minecraft.server.notifications.NotificationManager;
|
||||
import net.minecraft.server.packs.repository.PackRepository;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
||||
import net.minecraft.server.permissions.PermissionSet;
|
||||
import net.minecraft.server.players.NameAndId;
|
||||
import net.minecraft.server.players.PlayerList;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.util.datafix.DataFixers;
|
||||
import net.minecraft.util.debugchart.LocalSampleLogger;
|
||||
import net.minecraft.util.debugchart.SampleLogger;
|
||||
import net.minecraft.world.clock.WorldClocks;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntitySpawnReason;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.entity.Mob;
|
||||
import net.minecraft.world.entity.AgeableMob;
|
||||
import net.minecraft.world.entity.ai.Brain;
|
||||
import net.minecraft.world.entity.ai.behavior.BlockPosTracker;
|
||||
import net.minecraft.world.entity.ai.behavior.EntityTracker;
|
||||
import net.minecraft.world.entity.ai.control.LookControl;
|
||||
import net.minecraft.world.entity.ai.control.MoveControl;
|
||||
import net.minecraft.world.entity.ai.goal.GoalSelector;
|
||||
import net.minecraft.world.entity.ai.goal.WrappedGoal;
|
||||
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
|
||||
import net.minecraft.world.entity.ai.memory.WalkTarget;
|
||||
import net.minecraft.world.entity.ai.navigation.PathNavigation;
|
||||
import net.minecraft.world.entity.ai.sensing.Sensor;
|
||||
import net.minecraft.world.flag.FeatureFlagSet;
|
||||
import net.minecraft.world.flag.FeatureFlags;
|
||||
import net.minecraft.world.level.DataPackConfig;
|
||||
import net.minecraft.world.level.GameType;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.LevelSettings;
|
||||
import net.minecraft.world.level.WorldDataConfiguration;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.dimension.LevelStem;
|
||||
import net.minecraft.world.level.gamerules.GameRules;
|
||||
import net.minecraft.world.level.levelgen.WorldDimensions;
|
||||
import net.minecraft.world.level.levelgen.WorldGenSettings;
|
||||
import net.minecraft.world.level.levelgen.WorldOptions;
|
||||
import net.minecraft.world.level.levelgen.presets.WorldPresets;
|
||||
import net.minecraft.world.level.storage.LevelDataAndDimensions;
|
||||
import net.minecraft.world.level.storage.LevelStorageSource;
|
||||
import net.minecraft.world.level.storage.PrimaryLevelData;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/**
|
||||
* Mob AI oracle: a real (headless, flat, structure-free) vanilla server level. Each scenario
|
||||
* builds blocks, places a target player and mobs with seeded random sources, then ticks the
|
||||
* mobs exactly as ServerLevel.tick does (despawn check, then tickNonPassenger) while the rest of
|
||||
* the level stands still (no block ticks, weather, spawning or random ticks), printing the
|
||||
* AI-visible state of every mob after each tick: position, motion, rotations, running goals,
|
||||
* targets, navigation, move/look/jump controls, brain activities and memories, and sounds.
|
||||
*/
|
||||
public final class VanillaMobAiOracle {
|
||||
static final List<Scenario> SCENARIOS = new ArrayList<>();
|
||||
static PrintWriter out;
|
||||
static final List<String> SOUNDS = new ArrayList<>();
|
||||
|
||||
static final class MobSpec {
|
||||
String type;
|
||||
double x, y, z;
|
||||
float yaw;
|
||||
long seed;
|
||||
boolean baby;
|
||||
List<String> flags = new ArrayList<>();
|
||||
}
|
||||
|
||||
static final class Scenario {
|
||||
String name;
|
||||
int ticks;
|
||||
long time = 6000;
|
||||
boolean rain, thunder;
|
||||
int originX, originZ;
|
||||
List<String[]> blocks = new ArrayList<>();
|
||||
double[] player;
|
||||
boolean creative;
|
||||
List<MobSpec> mobs = new ArrayList<>();
|
||||
long levelSeed = 0;
|
||||
}
|
||||
|
||||
static void parse(Path path) throws Exception {
|
||||
Scenario s = null;
|
||||
for (String raw : Files.readAllLines(path)) {
|
||||
String line = raw.strip();
|
||||
if (line.isEmpty() || line.startsWith("#")) continue;
|
||||
String[] f = line.split("\\s+");
|
||||
switch (f[0]) {
|
||||
case "scenario" -> {
|
||||
s = new Scenario();
|
||||
s.name = f[1];
|
||||
for (int i = 2; i < f.length; i++) {
|
||||
String[] kv = f[i].split("=", 2);
|
||||
switch (kv[0]) {
|
||||
case "ticks" -> s.ticks = Integer.parseInt(kv[1]);
|
||||
case "time" -> s.time = Long.parseLong(kv[1]);
|
||||
case "rain" -> s.rain = true;
|
||||
case "thunder" -> s.thunder = true;
|
||||
case "levelseed" -> s.levelSeed = Long.parseLong(kv[1]);
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
case "origin" -> { s.originX = Integer.parseInt(f[1]); s.originZ = Integer.parseInt(f[2]); }
|
||||
case "fill", "block" -> s.blocks.add(f);
|
||||
case "player" -> {
|
||||
s.player = new double[] {Double.parseDouble(f[1]), Double.parseDouble(f[2]), Double.parseDouble(f[3])};
|
||||
s.creative = f.length > 4 && f[4].equals("creative");
|
||||
}
|
||||
case "mob" -> {
|
||||
MobSpec m = new MobSpec();
|
||||
m.type = f[1];
|
||||
m.x = Double.parseDouble(f[2]);
|
||||
m.y = Double.parseDouble(f[3]);
|
||||
m.z = Double.parseDouble(f[4]);
|
||||
m.yaw = Float.parseFloat(f[5]);
|
||||
m.seed = Long.parseLong(f[6]);
|
||||
for (int i = 7; i < f.length; i++) {
|
||||
if (f[i].equals("baby")) m.baby = true; else m.flags.add(f[i]);
|
||||
}
|
||||
s.mobs.add(m);
|
||||
}
|
||||
case "end" -> { SCENARIOS.add(s); s = null; }
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
parse(Path.of(args[0]));
|
||||
out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])));
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
Util.startTimerHackThread();
|
||||
Path universe = Files.createTempDirectory("horizon-mob-ai");
|
||||
LevelStorageSource.LevelStorageAccess access = LevelStorageSource.createDefault(universe).createAccess("aiworld");
|
||||
PackRepository packs = ServerPacksSource.createPackRepository(access);
|
||||
MinecraftServer.spin(thread -> Server.create(thread, access, packs));
|
||||
}
|
||||
|
||||
static String d(double v) { return Long.toHexString(Double.doubleToRawLongBits(v)); }
|
||||
static String f(float v) { return Integer.toHexString(Float.floatToRawIntBits(v)); }
|
||||
|
||||
static Field field(Class<?> c, String name) throws Exception {
|
||||
for (Class<?> k = c; k != null; k = k.getSuperclass()) {
|
||||
try {
|
||||
Field fl = k.getDeclaredField(name);
|
||||
fl.setAccessible(true);
|
||||
return fl;
|
||||
} catch (NoSuchFieldException e) {
|
||||
// keep looking
|
||||
}
|
||||
}
|
||||
throw new NoSuchFieldException(name);
|
||||
}
|
||||
|
||||
static Method method(Class<?> c, String name, Class<?>... types) throws Exception {
|
||||
for (Class<?> k = c; k != null; k = k.getSuperclass()) {
|
||||
try {
|
||||
Method m = k.getDeclaredMethod(name, types);
|
||||
m.setAccessible(true);
|
||||
return m;
|
||||
} catch (NoSuchMethodException e) {
|
||||
// keep looking
|
||||
}
|
||||
}
|
||||
throw new NoSuchMethodException(name);
|
||||
}
|
||||
|
||||
static Object get(Object o, String name) throws Exception { return field(o.getClass(), name).get(o); }
|
||||
|
||||
static final class Server extends MinecraftServer {
|
||||
static final FeatureFlagSet FEATURES = FeatureFlags.REGISTRY
|
||||
.allFlags()
|
||||
.subtract(FeatureFlagSet.of(FeatureFlags.REDSTONE_EXPERIMENTS, FeatureFlags.MINECART_IMPROVEMENTS));
|
||||
final LocalSampleLogger sampleLogger = new LocalSampleLogger(4);
|
||||
int scenario = 0;
|
||||
int phase = 0;
|
||||
int wait = 0;
|
||||
ServerPlayer player;
|
||||
int failures = 0;
|
||||
|
||||
static Server create(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs) {
|
||||
try {
|
||||
packs.reload();
|
||||
ArrayList<String> enabled = new ArrayList<>(packs.getAvailableIds());
|
||||
enabled.remove("vanilla");
|
||||
enabled.addFirst("vanilla");
|
||||
WorldDataConfiguration config = new WorldDataConfiguration(new DataPackConfig(enabled, List.of()), FEATURES);
|
||||
LevelSettings settings = new LevelSettings("AI Level", GameType.SURVIVAL, LevelSettings.DifficultySettings.DEFAULT, true, config);
|
||||
WorldLoader.PackConfig packConfig = new WorldLoader.PackConfig(packs, config, false, true);
|
||||
WorldLoader.InitConfig init = new WorldLoader.InitConfig(packConfig, Commands.CommandSelection.DEDICATED, LevelBasedPermissionSet.OWNER);
|
||||
WorldStem stem = Util.<WorldStem>blockUntilDone(executor -> WorldLoader.load(init, context -> {
|
||||
Registry<LevelStem> none = new MappedRegistry<>(Registries.LEVEL_STEM, Lifecycle.stable()).freeze();
|
||||
WorldDimensions dims = context.datapackWorldRegistries().lookupOrThrow(Registries.WORLD_PRESET)
|
||||
.getOrThrow(WorldPresets.FLAT).value().createWorldDimensions();
|
||||
WorldDimensions.Complete complete = dims.bake(none);
|
||||
PrimaryLevelData data = new PrimaryLevelData(settings, complete.specialWorldProperty(), complete.lifecycle());
|
||||
return new WorldLoader.DataLoadOutput<>(
|
||||
new LevelDataAndDimensions.WorldDataAndGenSettings(data, new WorldGenSettings(new WorldOptions(0L, false, false), dims)),
|
||||
complete.dimensionsRegistryAccess());
|
||||
}, WorldStem::new, Util.backgroundExecutor(), executor)).get();
|
||||
GameRules rules = new GameRules(FEATURES);
|
||||
rules.set(GameRules.SPAWN_MOBS, false, null);
|
||||
rules.set(GameRules.SPAWN_MONSTERS, false, null);
|
||||
rules.set(GameRules.SPAWN_PATROLS, false, null);
|
||||
rules.set(GameRules.SPAWN_PHANTOMS, false, null);
|
||||
rules.set(GameRules.SPAWN_WANDERING_TRADERS, false, null);
|
||||
rules.set(GameRules.SPAWN_WARDENS, false, null);
|
||||
rules.set(GameRules.ADVANCE_TIME, false, null);
|
||||
rules.set(GameRules.ADVANCE_WEATHER, false, null);
|
||||
rules.set(GameRules.RAIDS, false, null);
|
||||
Field nf = GameTestServer.class.getDeclaredField("NO_SERVICES");
|
||||
nf.setAccessible(true);
|
||||
return new Server(thread, access, packs, stem, rules, (Services) nf.get(null));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(2);
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
Server(Thread thread, LevelStorageSource.LevelStorageAccess access, PackRepository packs, WorldStem stem, GameRules rules, Services services) {
|
||||
super(thread, access, packs, stem, Optional.of(rules), Proxy.NO_PROXY, DataFixers.getDataFixer(), services,
|
||||
LoggingLevelLoadListener.forDedicatedServer(), false, new NotificationManager());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean initServer() {
|
||||
this.setPlayerList(new PlayerList(this, this.registries(), this.playerDataStorage, new EmptyNotificationService()) {
|
||||
@Override
|
||||
public void broadcast(Player except, double x, double y, double z, double range, ResourceKey<Level> dim, Packet<?> packet) {
|
||||
capture(packet);
|
||||
}
|
||||
});
|
||||
Gizmos.withCollector(GizmoCollector.NOOP);
|
||||
this.loadLevel();
|
||||
return true;
|
||||
}
|
||||
|
||||
static void capture(Packet<?> packet) {
|
||||
if (packet instanceof ClientboundSoundPacket p) {
|
||||
SOUNDS.add(p.getSound().value().location() + " " + f(p.getVolume()) + " " + f(p.getPitch()));
|
||||
} else if (packet instanceof ClientboundSoundEntityPacket p) {
|
||||
SOUNDS.add(p.getSound().value().location() + " " + f(p.getVolume()) + " " + f(p.getPitch()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tickServer(BooleanSupplier haveTime) {
|
||||
try {
|
||||
step(haveTime);
|
||||
} catch (Throwable t) {
|
||||
t.printStackTrace();
|
||||
out.flush();
|
||||
System.exit(3);
|
||||
}
|
||||
}
|
||||
|
||||
ServerLevel level() { return this.overworld(); }
|
||||
|
||||
void step(BooleanSupplier haveTime) throws Exception {
|
||||
if (scenario >= SCENARIOS.size()) {
|
||||
out.close();
|
||||
// Nothing to save: skip the shutdown.
|
||||
Runtime.getRuntime().halt(0);
|
||||
return;
|
||||
}
|
||||
Scenario s = SCENARIOS.get(scenario);
|
||||
ServerLevel level = level();
|
||||
int cx = s.originX >> 4, cz = s.originZ >> 4;
|
||||
switch (phase) {
|
||||
case 0 -> {
|
||||
for (int dx = -4; dx <= 4; dx++)
|
||||
for (int dz = -4; dz <= 4; dz++)
|
||||
level.setChunkForced(cx + dx, cz + dz, true);
|
||||
phase = 1;
|
||||
super.tickServer(haveTime);
|
||||
}
|
||||
case 1 -> {
|
||||
super.tickServer(haveTime);
|
||||
boolean ready = true;
|
||||
for (int dx = -4; dx <= 4 && ready; dx++)
|
||||
for (int dz = -4; dz <= 4 && ready; dz++)
|
||||
ready = level.isPositionEntityTicking(new BlockPos((cx + dx) * 16, -60, (cz + dz) * 16));
|
||||
if (ready) {
|
||||
build(s, level);
|
||||
phase = 2;
|
||||
wait = 0;
|
||||
}
|
||||
}
|
||||
case 2 -> {
|
||||
super.tickServer(haveTime);
|
||||
if (!level.getChunkSource().getLightEngine().hasLightWork() && ++wait > 5) {
|
||||
run(s, level);
|
||||
for (int dx = -4; dx <= 4; dx++)
|
||||
for (int dz = -4; dz <= 4; dz++)
|
||||
level.setChunkForced(cx + dx, cz + dz, false);
|
||||
scenario++;
|
||||
phase = 0;
|
||||
}
|
||||
}
|
||||
default -> throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
void build(Scenario s, ServerLevel level) throws Exception {
|
||||
var blocks = level.holderLookup(Registries.BLOCK);
|
||||
for (String[] b : s.blocks) {
|
||||
if (b[0].equals("block")) {
|
||||
BlockState state = BlockStateParser.parseForBlock(blocks, b[4], false).blockState();
|
||||
level.setBlock(new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])), state, 2 | 16);
|
||||
} else {
|
||||
BlockState state = BlockStateParser.parseForBlock(blocks, b[7], false).blockState();
|
||||
int x0 = Integer.parseInt(b[1]), y0 = Integer.parseInt(b[2]), z0 = Integer.parseInt(b[3]);
|
||||
int x1 = Integer.parseInt(b[4]), y1 = Integer.parseInt(b[5]), z1 = Integer.parseInt(b[6]);
|
||||
for (int x = Math.min(x0, x1); x <= Math.max(x0, x1); x++)
|
||||
for (int y = Math.min(y0, y1); y <= Math.max(y0, y1); y++)
|
||||
for (int z = Math.min(z0, z1); z <= Math.max(z0, z1); z++)
|
||||
level.setBlock(new BlockPos(x, y, z), state, 2 | 16);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void run(Scenario s, ServerLevel level) throws Exception {
|
||||
out.println("== " + s.name);
|
||||
var clock = level.registryAccess().lookupOrThrow(Registries.WORLD_CLOCK).getOrThrow(WorldClocks.OVERWORLD);
|
||||
this.clockManager().setTotalTicks(clock, s.time);
|
||||
// isRaining/isThundering read the rain and thunder levels only.
|
||||
level.setRainLevel(s.rain ? 1.0F : 0.0F);
|
||||
level.setThunderLevel(s.thunder ? 1.0F : 0.0F);
|
||||
if (s.player != null) {
|
||||
if (player == null) {
|
||||
CommonListenerCookie cookie = CommonListenerCookie.createInitial(new GameProfile(new UUID(0x1234L, 0x5678L), "horizon-ai"), false);
|
||||
player = new ServerPlayer(this, level, cookie.gameProfile(), cookie.clientInformation());
|
||||
Connection connection = new Connection(PacketFlow.SERVERBOUND);
|
||||
new EmbeddedChannel(connection);
|
||||
this.getPlayerList().placeNewPlayer(connection, player, cookie);
|
||||
}
|
||||
player.setGameMode(s.creative ? GameType.CREATIVE : GameType.SURVIVAL);
|
||||
player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F);
|
||||
player.setDeltaMovement(Vec3.ZERO);
|
||||
} else if (player != null) {
|
||||
player.snapTo(s.originX + 5000, -60, s.originZ, 0.0F, 0.0F);
|
||||
}
|
||||
List<Mob> mobs = new ArrayList<>();
|
||||
int id = 100000;
|
||||
for (MobSpec spec : s.mobs) {
|
||||
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(net.minecraft.resources.Identifier.parse(spec.type));
|
||||
Mob mob = (Mob) type.create(level, EntitySpawnReason.COMMAND);
|
||||
mob.setId(id++);
|
||||
mob.snapTo(spec.x, spec.y, spec.z, spec.yaw, 0.0F);
|
||||
mob.setYHeadRot(spec.yaw);
|
||||
mob.setYBodyRot(spec.yaw);
|
||||
if (spec.baby) {
|
||||
if (mob instanceof AgeableMob a) a.setBaby(true);
|
||||
else mob.setBaby(true);
|
||||
}
|
||||
for (String flag : spec.flags) {
|
||||
if (flag.equals("persistent")) mob.setPersistenceRequired();
|
||||
else if (flag.equals("noai")) mob.setNoAi(true);
|
||||
else throw new IllegalArgumentException(flag);
|
||||
}
|
||||
level.addFreshEntity(mob);
|
||||
mob.getRandom().setSeed(spec.seed);
|
||||
Brain<?> brain = mob.getBrain();
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<Object, Sensor<?>> sensors = (Map<Object, Sensor<?>>) get(brain, "sensors");
|
||||
for (Sensor<?> sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom());
|
||||
mobs.add(mob);
|
||||
}
|
||||
level.getRandom().setSeed(s.levelSeed);
|
||||
SOUNDS.clear();
|
||||
Method tickTime = method(ServerLevel.class, "tickTime");
|
||||
Object manager = get(level, "entityManager");
|
||||
Method managerTick = method(manager.getClass(), "tick");
|
||||
for (int t = 1; t <= s.ticks; t++) {
|
||||
level.environmentAttributes().invalidateTickCache();
|
||||
level.updateSkyBrightness();
|
||||
tickTime.invoke(level);
|
||||
if (player != null && s.player != null) {
|
||||
player.setHealth(player.getMaxHealth());
|
||||
player.setInvulnerableTime(0);
|
||||
player.hurtTime = 0;
|
||||
player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F);
|
||||
player.setDeltaMovement(Vec3.ZERO);
|
||||
}
|
||||
SOUNDS.clear();
|
||||
for (Mob mob : mobs) {
|
||||
if (mob.isRemoved()) continue;
|
||||
mob.checkDespawn();
|
||||
if (mob.isRemoved()) continue;
|
||||
level.tickNonPassenger(mob);
|
||||
}
|
||||
managerTick.invoke(manager);
|
||||
for (int i = 0; i < mobs.size(); i++) print(t, i, mobs.get(i));
|
||||
for (String sound : SOUNDS) out.println(t + " sound " + sound);
|
||||
}
|
||||
for (Mob mob : mobs) mob.discard();
|
||||
managerTick.invoke(manager);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
static String who(Entity e) {
|
||||
if (e == null) return "none";
|
||||
if (e instanceof ServerPlayer) return "player";
|
||||
return "e" + e.getId();
|
||||
}
|
||||
|
||||
static String goals(GoalSelector selector) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (WrappedGoal g : selector.getAvailableGoals()) {
|
||||
if (!g.isRunning()) continue;
|
||||
if (sb.length() > 0) sb.append('|');
|
||||
Class<?> c = g.getGoal().getClass();
|
||||
String name = c.getSimpleName();
|
||||
if (name.isEmpty()) name = c.getName().substring(c.getName().lastIndexOf('.') + 1);
|
||||
sb.append(name);
|
||||
}
|
||||
return sb.length() == 0 ? "-" : sb.toString();
|
||||
}
|
||||
|
||||
static String pos(BlockPos p) { return p.getX() + "," + p.getY() + "," + p.getZ(); }
|
||||
|
||||
static String value(Object v) {
|
||||
if (v == null) return "null";
|
||||
if (v instanceof Entity e) return who(e);
|
||||
if (v instanceof BlockPos p) return pos(p);
|
||||
if (v instanceof GlobalPos g) return pos(g.pos());
|
||||
if (v instanceof WalkTarget w) return value(w.getTarget()) + "/" + f(w.getSpeedModifier()) + "/" + w.getCloseEnoughDist();
|
||||
if (v instanceof EntityTracker e) return who(e.getEntity());
|
||||
if (v instanceof BlockPosTracker b) return pos(b.currentBlockPosition());
|
||||
if (v instanceof Boolean || v instanceof Integer || v instanceof Long) return v.toString();
|
||||
if (v instanceof net.minecraft.util.Unit) return "u";
|
||||
if (v instanceof Collection<?> c) return "n" + c.size();
|
||||
if (v instanceof net.minecraft.world.level.pathfinder.Path p) return "path" + pos(p.getTarget());
|
||||
return v.getClass().getSimpleName();
|
||||
}
|
||||
|
||||
void print(int t, int i, Mob m) throws Exception {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(t).append(' ').append(i);
|
||||
if (m.isRemoved()) {
|
||||
out.println(sb.append(" removed ").append(m.getRemovalReason()));
|
||||
return;
|
||||
}
|
||||
sb.append("\tp ").append(d(m.getX())).append(',').append(d(m.getY())).append(',').append(d(m.getZ()));
|
||||
Vec3 v = m.getDeltaMovement();
|
||||
sb.append("\tv ").append(d(v.x)).append(',').append(d(v.y)).append(',').append(d(v.z));
|
||||
sb.append("\tr ").append(f(m.getYRot())).append(',').append(f(m.getXRot())).append(',').append(f(m.getYHeadRot())).append(',').append(f(m.yBodyRot));
|
||||
sb.append("\tg ").append(m.onGround() ? 1 : 0).append(m.horizontalCollision ? 1 : 0);
|
||||
sb.append("\thp ").append(f(m.getHealth()));
|
||||
sb.append("\tgoals ").append(goals((GoalSelector) get(m, "goalSelector")));
|
||||
sb.append("\ttargets ").append(goals((GoalSelector) get(m, "targetSelector")));
|
||||
sb.append("\ttarget ").append(who(m.getTarget()));
|
||||
PathNavigation nav = m.getNavigation();
|
||||
var path = nav.getPath();
|
||||
sb.append("\tnav ");
|
||||
if (path == null) sb.append("none");
|
||||
else sb.append(pos(path.getTarget())).append(' ').append(path.getNextNodeIndex()).append('/').append(path.getNodeCount())
|
||||
.append(path.isDone() ? " done" : "");
|
||||
MoveControl mc = m.getMoveControl();
|
||||
sb.append("\tmove ").append(get(mc, "operation")).append(' ').append(d((double) get(mc, "wantedX"))).append(',')
|
||||
.append(d((double) get(mc, "wantedY"))).append(',').append(d((double) get(mc, "wantedZ"))).append(' ')
|
||||
.append(d((double) get(mc, "speedModifier")));
|
||||
LookControl lc = m.getLookControl();
|
||||
sb.append("\tlook ").append(get(lc, "lookAtCooldown")).append(' ').append(d((double) get(lc, "wantedX"))).append(',')
|
||||
.append(d((double) get(lc, "wantedY"))).append(',').append(d((double) get(lc, "wantedZ")));
|
||||
sb.append("\tin ").append(f(m.xxa)).append(',').append(f(m.zza)).append(',').append(f(m.getSpeed())).append(',')
|
||||
.append(field(LivingEntity.class, "jumping").getBoolean(m) ? 1 : 0);
|
||||
Brain<?> brain = m.getBrain();
|
||||
if (!brain.getActiveActivities().isEmpty() && !((Map<?, ?>) get(brain, "sensors")).isEmpty()) {
|
||||
List<String> acts = new ArrayList<>();
|
||||
for (var a : brain.getActiveActivities()) acts.add(a.getName());
|
||||
acts.sort(null);
|
||||
sb.append("\tact ").append(String.join("|", acts));
|
||||
List<String> mem = new ArrayList<>();
|
||||
brain.forEach(new Brain.Visitor() {
|
||||
@Override public <U> void acceptEmpty(MemoryModuleType<U> type) {}
|
||||
@Override public <U> void accept(MemoryModuleType<U> type, U value) { mem.add(name(type) + "=" + value(value)); }
|
||||
@Override public <U> void accept(MemoryModuleType<U> type, U value, long ttl) { mem.add(name(type) + "=" + value(value) + "@" + ttl); }
|
||||
});
|
||||
mem.sort(null);
|
||||
sb.append("\tmem ").append(String.join(" ", mem));
|
||||
}
|
||||
out.println(sb);
|
||||
}
|
||||
|
||||
static String name(MemoryModuleType<?> type) {
|
||||
return BuiltInRegistries.MEMORY_MODULE_TYPE.getKey(type).getPath();
|
||||
}
|
||||
|
||||
@Override protected SampleLogger getTickTimeLogger() { return sampleLogger; }
|
||||
@Override public boolean isTickTimeLoggingEnabled() { return false; }
|
||||
@Override protected void waitUntilNextTick() { this.runAllTasks(); }
|
||||
@Override public SystemReport fillServerSystemReport(SystemReport report) { report.setDetail("Type", "Mob AI oracle"); return report; }
|
||||
@Override protected void onServerExit() { super.onServerExit(); System.exit(0); }
|
||||
@Override protected void onServerCrash(net.minecraft.CrashReport report) { super.onServerCrash(report); System.exit(1); }
|
||||
@Override public boolean isHardcore() { return false; }
|
||||
@Override public LevelBasedPermissionSet operatorUserPermissions() { return LevelBasedPermissionSet.ALL; }
|
||||
@Override public PermissionSet getFunctionCompilationPermissions() { return LevelBasedPermissionSet.OWNER; }
|
||||
@Override public boolean shouldRconBroadcast() { return false; }
|
||||
@Override public boolean isDedicatedServer() { return false; }
|
||||
@Override public int getRateLimitPacketsPerSecond() { return 0; }
|
||||
@Override public int getCommandSpamThresholdSeconds() { return 0; }
|
||||
@Override public int getChatSpamThresholdSeconds() { return 0; }
|
||||
@Override public boolean useNativeTransport() { return false; }
|
||||
@Override public boolean isPublished() { return false; }
|
||||
@Override public boolean shouldInformAdmins() { return false; }
|
||||
@Override public boolean isSingleplayerOwner(NameAndId nameAndId) { return false; }
|
||||
@Override public int getMaxPlayers() { return 1; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Differential mob AI harness.
|
||||
|
||||
The Java oracle (VanillaMobAiOracle) runs vanilla mobs in a real, headless, flat vanilla server
|
||||
level: each scenario builds a scene, places a target player and mobs with seeded random sources
|
||||
and ticks the mobs the way ServerLevel.tick does. The Rust probe (mob_ai_probe) replays the same
|
||||
scenarios on Horizon's mob AI. Both print every mob's AI-visible state after every tick (position,
|
||||
motion, rotations, running goals and target goals, attack target, navigation path, move and look
|
||||
controls, movement input, brain activities and memories) and the sounds played; this harness
|
||||
reports, per scenario and mob, how many ticks match before the first divergence and what differs.
|
||||
|
||||
python3 tools/test_mob_ai_parity.py [--only NAME ...] [--rust-only] [--java-only] [--strict]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness, test_rust_parity as base, test_model_baking_parity as baking
|
||||
except ImportError:
|
||||
import lab
|
||||
import oracle_harness
|
||||
import test_rust_parity as base
|
||||
import test_model_baking_parity as baking
|
||||
|
||||
FLOOR = -60 # top of the flat preset's grass layer + 1
|
||||
|
||||
|
||||
def ring(x0, z0, size, state, y=FLOOR):
|
||||
return [f'fill {x0 - size} {y} {z0 - size} {x0 + size} {y} {z0 + size} {state}']
|
||||
|
||||
|
||||
# Each scenario is (name, ticks, options, lines); positions are relative to the scenario origin
|
||||
# and translated by the generator so scenarios never share chunks.
|
||||
def scenarios():
|
||||
s = []
|
||||
|
||||
def add(name, ticks, lines, opts=''):
|
||||
s.append((name, ticks, opts, lines))
|
||||
|
||||
# Passive and hostile land mobs on open grass with a survival player nearby.
|
||||
for species, seed in [('zombie', 1), ('skeleton', 2), ('creeper', 3), ('spider', 4), ('husk', 5),
|
||||
('cow', 6), ('pig', 7), ('chicken', 8), ('sheep', 9), ('wandering_trader', 10),
|
||||
('villager', 11), ('drowned', 12), ('enderman', 13), ('witch', 14)]:
|
||||
add(f'{species}_player', 200, [
|
||||
'player 6.5 -60 0.5',
|
||||
f'mob minecraft:{species} 0.5 -60 0.5 0 {seed} persistent',
|
||||
])
|
||||
add(f'{species}_alone', 200, [
|
||||
f'mob minecraft:{species} 0.5 -60 0.5 90 {seed * 7 + 1} persistent',
|
||||
])
|
||||
# Drowned in a pool with the player on the shore and in the water.
|
||||
add('drowned_pool', 200, ['fill -6 -64 -6 6 -61 6 minecraft:water',
|
||||
'player 9.5 -60 0.5',
|
||||
'mob minecraft:drowned 0.5 -63 0.5 0 21 persistent'])
|
||||
add('drowned_pool_swimmer', 200, ['fill -6 -64 -6 6 -61 6 minecraft:water',
|
||||
'player 3.5 -62 0.5',
|
||||
'mob minecraft:drowned -3.5 -63 0.5 0 22 persistent'])
|
||||
# Night: undead do not burn, monsters seek darkness.
|
||||
add('zombie_night', 200, ['player 10.5 -60 0.5', 'mob minecraft:zombie 0.5 -60 0.5 0 31 persistent'], 'time=18000')
|
||||
add('skeleton_day_burn', 120, ['mob minecraft:skeleton 0.5 -60 0.5 0 32 persistent'])
|
||||
# The wither (summoned, not built: no invulnerable spawn phase).
|
||||
add('wither_player', 200, ['player 10.5 -60 0.5', 'mob minecraft:wither 0.5 -58 0.5 0 41 persistent'])
|
||||
# A villager with a job site, a bed and a bell.
|
||||
add('villager_village', 300, [
|
||||
'block 4 -60 0 minecraft:composter',
|
||||
'block -4 -60 2 minecraft:red_bed[facing=north,part=foot]',
|
||||
'block -4 -60 1 minecraft:red_bed[facing=north,part=head]',
|
||||
'block 0 -60 -6 minecraft:bell',
|
||||
'player 12.5 -60 0.5',
|
||||
'mob minecraft:villager 0.5 -60 0.5 0 51 persistent',
|
||||
])
|
||||
return s
|
||||
|
||||
|
||||
def write_scenarios(path, chosen):
|
||||
lines = []
|
||||
for i, (name, ticks, opts, body) in chosen:
|
||||
ox, oz = 512 * (i + 1), 0
|
||||
lines.append(f'scenario {name} ticks={ticks} {opts}'.rstrip())
|
||||
lines.append(f'origin {ox} {oz}')
|
||||
for line in body:
|
||||
f = line.split()
|
||||
if f[0] == 'player':
|
||||
f[1] = repr(float(f[1]) + ox)
|
||||
f[3] = repr(float(f[3]) + oz)
|
||||
elif f[0] == 'mob':
|
||||
f[2] = repr(float(f[2]) + ox)
|
||||
f[4] = repr(float(f[4]) + oz)
|
||||
elif f[0] == 'block':
|
||||
f[1] = str(int(f[1]) + ox)
|
||||
f[3] = str(int(f[3]) + oz)
|
||||
elif f[0] == 'fill':
|
||||
for k in (1, 4):
|
||||
f[k] = str(int(f[k]) + ox)
|
||||
for k in (3, 6):
|
||||
f[k] = str(int(f[k]) + oz)
|
||||
lines.append(' '.join(f))
|
||||
lines.append('end')
|
||||
path.write_text('\n'.join(lines) + '\n')
|
||||
|
||||
|
||||
def parse(path):
|
||||
"""{scenario: {tick: {mob: {field: value}}, sounds: {tick: [..]}}}"""
|
||||
result, cur = {}, None
|
||||
for line in path.read_text().splitlines():
|
||||
if line.startswith('== '):
|
||||
cur = result.setdefault(line[3:], {'ticks': {}, 'sounds': {}})
|
||||
continue
|
||||
head, *fields = line.split('\t')
|
||||
parts = head.split(' ', 2)
|
||||
t = int(parts[0])
|
||||
if parts[1] == 'sound':
|
||||
cur['sounds'].setdefault(t, []).append(parts[2])
|
||||
continue
|
||||
mob = int(parts[1])
|
||||
row = {}
|
||||
if len(parts) > 2:
|
||||
row['removed'] = parts[2]
|
||||
for f in fields:
|
||||
k, _, v = f.partition(' ')
|
||||
row[k] = v
|
||||
cur['ticks'].setdefault(t, {})[mob] = row
|
||||
return result
|
||||
|
||||
|
||||
def decode(value):
|
||||
"""Hex float/double fields made readable."""
|
||||
def one(x):
|
||||
try:
|
||||
if len(x) > 8:
|
||||
return f'{struct.unpack(">d", int(x, 16).to_bytes(8, "big"))[0]!r}'
|
||||
return f'{struct.unpack(">f", int(x, 16).to_bytes(4, "big"))[0]:.9g}'
|
||||
except ValueError:
|
||||
return x
|
||||
out = []
|
||||
for word in value.split(' '):
|
||||
out.append(','.join(one(p) if all(c in '0123456789abcdef' for c in p) and len(p) >= 5 else p for p in word.split(',')))
|
||||
return ' '.join(out)
|
||||
|
||||
|
||||
def compare(vanilla, rust, fields=None):
|
||||
"""Returns (report lines, totals)."""
|
||||
report, totals = [], {'mob_ticks': 0, 'matched': 0, 'scenarios': 0, 'clean': 0}
|
||||
for name, v in vanilla.items():
|
||||
r = rust.get(name)
|
||||
totals['scenarios'] += 1
|
||||
if r is None:
|
||||
report.append(f'{name}: missing from Horizon')
|
||||
continue
|
||||
mobs = sorted({m for t in v['ticks'].values() for m in t})
|
||||
clean = True
|
||||
for mob in mobs:
|
||||
ticks = sorted(v['ticks'])
|
||||
first = None
|
||||
for t in ticks:
|
||||
a = v['ticks'][t].get(mob)
|
||||
b = r['ticks'].get(t, {}).get(mob)
|
||||
totals['mob_ticks'] += 1
|
||||
if a == b or (b is not None and fields and all(a.get(k) == b.get(k) for k in fields)):
|
||||
if first is None:
|
||||
totals['matched'] += 1
|
||||
continue
|
||||
if first is None:
|
||||
first = t
|
||||
diffs = []
|
||||
for k in (a or {}):
|
||||
if b is None or a.get(k) != b.get(k):
|
||||
diffs.append(f'{k}: vanilla {decode(a.get(k, "?"))} | horizon {decode((b or {}).get(k, "?"))}')
|
||||
for k in (b or {}):
|
||||
if a is None or k not in a:
|
||||
diffs.append(f'{k}: vanilla ? | horizon {decode(b[k])}')
|
||||
report.append(f'{name} mob {mob}: first divergence at tick {t} of {len(ticks)}')
|
||||
report.extend(' ' + d for d in diffs[:12])
|
||||
if first is not None:
|
||||
clean = False
|
||||
# Sounds: first differing tick.
|
||||
for t in sorted(set(v['sounds']) | set(r['sounds'])):
|
||||
if v['sounds'].get(t, []) != r['sounds'].get(t, []):
|
||||
report.append(f'{name}: sounds differ at tick {t}: vanilla {v["sounds"].get(t, [])} | horizon {r["sounds"].get(t, [])}')
|
||||
clean = False
|
||||
break
|
||||
totals['clean'] += clean
|
||||
if clean:
|
||||
report.append(f'{name}: all {len(v["ticks"])} ticks match')
|
||||
return report, totals
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('--only', nargs='*')
|
||||
parser.add_argument('--java-only', action='store_true')
|
||||
parser.add_argument('--rust-only', action='store_true', help='reuse the last vanilla output')
|
||||
parser.add_argument('--strict', action='store_true', help='fail on any divergence')
|
||||
args = parser.parse_args()
|
||||
build = lab.LOCAL / 'mob-ai-parity'
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
chosen = [(i, s) for i, s in enumerate(scenarios()) if not args.only or any(o in s[0] for o in args.only)]
|
||||
inputs = build / 'scenarios.txt'
|
||||
write_scenarios(inputs, chosen)
|
||||
lock, jars, _ = base.verify_artifacts()
|
||||
if not args.rust_only:
|
||||
classes, dependencies, _ = oracle_harness.compile_oracle(build, 'VanillaMobAiOracle', jars, baking.client_libraries(),
|
||||
lock['minecraft']['java_major'])
|
||||
oracle_harness.run_logged(['java', '-Xmx3g', '-Djava.awt.headless=true', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt'],
|
||||
build, 'vanilla', timeout=3600)
|
||||
if not args.java_only:
|
||||
oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'mob_ai_probe'],
|
||||
build, 'compile-rust')
|
||||
binary = lab.ROOT / 'target/release/examples/mob_ai_probe'
|
||||
oracle_harness.run_logged([binary, lab.ROOT / '.local/horizon-client/26.3', inputs, build / 'horizon.txt'], build, 'horizon')
|
||||
if args.java_only:
|
||||
return
|
||||
names = {s[0] for _, s in chosen}
|
||||
vanilla = {k: v for k, v in parse(build / 'vanilla.txt').items() if k in names}
|
||||
report, totals = compare(vanilla, parse(build / 'horizon.txt'))
|
||||
(build / 'report.txt').write_text('\n'.join(report) + '\n')
|
||||
print('\n'.join(report))
|
||||
print(f"{totals['clean']}/{totals['scenarios']} scenarios match entirely; "
|
||||
f"{totals['matched']}/{totals['mob_ticks']} mob-ticks match before each mob's first divergence")
|
||||
if args.strict and totals['clean'] != totals['scenarios']:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user