WIP: unfinished blocks parity work, stopped for the night

Uncommitted changes the agent had in progress when it was stopped; may not
build or pass its harnesses yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 22:24:03 +02:00
parent 1e03d531eb
commit f78de6d9ae
16 changed files with 1931 additions and 293 deletions
+32 -21
View File
@@ -19,6 +19,7 @@ mod control;
mod creaking;
mod creatures;
mod crossbow;
mod dispense_fixture;
mod dispenser;
mod dragon;
mod enchant_effects;
@@ -1050,8 +1051,9 @@ impl Game<'_> {
f64::from(pos[2]) + d(z),
];
let v = [d(x) - 0.5, d(y) - 0.5, d(z) - 0.5];
// LevelEventHandler (2001) runs on the client: its random, not the level's.
let particle =
Particle::terrain(&mut self.world.random, p, v, sprite.clone(), tint);
Particle::terrain(self.particles.random(), p, v, sprite.clone(), tint);
self.particles.push(particle);
}
}
@@ -1062,7 +1064,8 @@ impl Game<'_> {
let Some((sprite, tint)) = self.particle_sprite(state) else {
return;
};
let r = &mut self.world.random;
// Client-side particles draw from the client random, not the level's.
let r = self.particles.random();
let mut p = [0.0; 3];
for i in 0..3 {
let base = f64::from(pos[i]);
@@ -1089,7 +1092,8 @@ impl Game<'_> {
) {
self.next_entity += 1;
let p = Vec3::new(position[0], position[1], position[2]);
let bob = self.world.random.next_float() * std::f32::consts::PI * 2.0;
// ItemEntity.bobOffs comes from the entity's own random, not the level's.
let bob = self.particles.random().next_float() * std::f32::consts::PI * 2.0;
self.dropped.push(ItemEntity {
id: self.next_entity,
stack,
@@ -1102,23 +1106,36 @@ impl Game<'_> {
bob_offset: bob,
});
}
/// `Block.getDrops`: the block's loot table, drawing from its server random
/// sequence (`LootContext.Builder.create`), else the level random.
fn block_loot(&mut self, state: BlockStateId, held: Option<&ItemStack>) -> Vec<ItemStack> {
let registry = self.res.assets.registry;
match self.res.items.block_loot_sequence(registry, state) {
Some(sequence) => {
let random = self.rand_sequences.get(&sequence, self.level.seed);
self.res.items.block_drops(registry, state, held, random)
}
None => self
.res
.items
.block_drops(registry, state, held, &mut self.world.random),
}
}
/// Block.popResource
fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) {
self.attach_shulker_contents(pos, &mut stack);
self.attach_container_name(pos, &mut stack);
self.attach_banner_layers(pos, &mut stack);
// Block.popResource: Mth.nextDouble offsets from the level random; the
// motion is `new ItemEntity(..)`'s own, from the item's random.
let r = &mut self.world.random;
let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25;
let mut offset = || -0.25 + r.next_double() * 0.5;
let p = [
f64::from(pos[0]) + 0.5 + offset(),
f64::from(pos[1]) + 0.5 + offset() - 0.125,
f64::from(pos[2]) + 0.5 + offset(),
];
let v = [
r.next_double() * 0.2 - 0.1,
0.2,
r.next_double() * 0.2 - 0.1,
];
let v = dispenser::new_item_motion();
self.spawn_item(stack, p, v, 10);
}
/// Player.drop: thrown from the eyes along the view direction.
@@ -1390,6 +1407,7 @@ impl Game<'_> {
fn process_level_events(&mut self) -> Result<()> {
let events = std::mem::take(&mut self.level_events);
self.lan_record_events(&events);
dispense_fixture::record_events(&events);
for event in events {
match event {
LevelEvent::LevelEvent {
@@ -1463,12 +1481,7 @@ impl Game<'_> {
let name = self.res.facts.get(state).name.clone();
self.release_contents([pos.x, pos.y, pos.z], entity, &name);
}
let drops = self.res.items.block_drops(
self.res.assets.registry,
state,
None,
&mut self.world.random,
);
let drops = self.block_loot(state, None);
for d in drops {
if &*d.item != "minecraft:air" {
self.pop_resource([pos.x, pos.y, pos.z], d);
@@ -1777,12 +1790,7 @@ impl Game<'_> {
let harvest = !facts.requires_tool
|| self.res.items.correct_for_drops(held.as_ref(), &facts.name);
if harvest {
let drops = self.res.items.block_drops(
self.res.assets.registry,
state,
held.as_ref(),
&mut self.world.random,
);
let drops = self.block_loot(state, held.as_ref());
let silk = held
.as_ref()
.is_some_and(|h| h.enchantment_level("minecraft:silk_touch") > 0);
@@ -8641,6 +8649,9 @@ pub fn run() -> Result<()> {
eprintln!("Horizon: control socket {}", server.path().display());
game.control = Some(server);
}
if let Ok(spec) = std::env::var("HORIZON_DISPENSE_FIXTURE") {
return game.dispense_fixture(&spec);
}
match game.options.world.clone() {
_ if game.options.server.is_some() => {
let (address, name) = (
+10
View File
@@ -95,6 +95,16 @@ impl Boat {
}
}
/// Item id -> (boat entity id, wood).
impl Boat {
/// The vanilla entity type id (`oak_boat`, `bamboo_raft`).
pub(super) fn entity_type(&self) -> String {
if &*self.wood == "bamboo" {
"minecraft:bamboo_raft".to_owned()
} else {
format!("minecraft:{}_boat", self.wood)
}
}
}
pub(super) fn boat_wood(item: &str) -> Option<&str> {
let name = item.strip_prefix("minecraft:")?;
name.strip_suffix("_boat")
@@ -0,0 +1,449 @@
//! The Rust side of tools/test_dispenser_parity.py: with
//! `HORIZON_DISPENSE_FIXTURE=CASES,OUTPUT` the game loads its resources, runs
//! every case (a dispenser or dropper with items, blocks and target entities
//! around it) through `dispense_from` on a fresh headless world and prints what
//! changed in the format of `VanillaDispenserOracle`.
use super::{
Game,
dispenser::{Slot, body_in_head, mob_set_slot, mob_slot_item},
};
use horizon_client::{
Result,
chunk::Chunk,
containers::BlockEntity,
gamerules::Value as RuleValue,
item_data::{canon_stack, parse_stack},
mobs::{Mob, Species},
projectiles::ProjectileKind,
world::World,
};
use horizon_core::{
position::BlockPos,
random::{LegacyRandom, RandomSource},
};
use horizon_world::{level::Ticks, registry::BlockStateId};
use serde_json::Value;
use std::{cell::RefCell, collections::HashMap, fmt::Write as _, io::Write as _, sync::Arc};
thread_local! {
/// Level and game events recorded while a fixture case runs.
static LOG: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
}
/// Record a line if a fixture case is running.
pub(super) fn record(line: impl FnOnce() -> String) {
LOG.with(|log| {
if let Some(lines) = log.borrow_mut().as_mut() {
lines.push(line());
}
});
}
/// `Level.levelEvent` lines for the level events the behaviour library reported.
pub(super) fn record_events(events: &[horizon_world::level::LevelEvent]) {
for event in events {
if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = event {
record(|| format!("L {id} {},{},{} {data}", pos.x, pos.y, pos.z));
}
}
}
fn num(v: f64) -> String {
format!("{v:.6}")
}
fn floor_pos(p: [f64; 3]) -> String {
format!(
"{},{},{}",
p[0].floor() as i32,
p[1].floor() as i32,
p[2].floor() as i32
)
}
/// The targets a case put in front of the dispenser.
enum Target {
Mob(u32),
Stand(u32),
}
impl Game<'_> {
/// Run every case of `spec` ("CASES,OUTPUT") and write the results.
pub(super) fn dispense_fixture(&mut self, spec: &str) -> Result<()> {
let (input, output) = spec.split_once(',').ok_or("HORIZON_DISPENSE_FIXTURE=CASES,OUTPUT")?;
// Saplings and feature placers grow from the live feature registry.
self.install_live_features();
let text = std::fs::read_to_string(input)?;
let mut out = std::io::BufWriter::new(std::fs::File::create(output)?);
for (index, line) in text.lines().enumerate() {
let case: Value = serde_json::from_str(line)?;
writeln!(out, "case {index}")?;
match self.dispense_case(&case) {
Ok(lines) => {
for l in lines {
writeln!(out, "{l}")?;
}
}
Err(e) => writeln!(out, "failed {e}")?,
}
}
LOG.with(|log| *log.borrow_mut() = None);
Ok(())
}
fn fixture_reset(&mut self, seed: i64) {
self.world = World::new(self.res.facts.air, seed);
for cx in -2..=2 {
for cz in -2..=2 {
self.world
.chunks
.insert((cx, cz), Arc::new(Chunk::empty(cx, cz)));
}
}
self.block_ticks = Ticks::new(0);
self.tick_chunks.clear();
self.sync_tick_chunks();
self.mobs.clear();
self.dropped.clear();
self.creatures.projectiles.clear();
self.tnts.clear();
self.boats.clear();
self.carts.clear();
self.armor_stands.clear();
self.rockets.clear();
self.potions.clear_thrown();
self.level_events.clear();
self.orbs.clear();
self.falling.clear();
self.ui.rules = Default::default();
// The oracle level has world seed 0 and fresh random sequences.
self.level.seed = 0;
self.rand_sequences = Default::default();
}
fn dispense_case(&mut self, case: &Value) -> Result<Vec<String>> {
let seed = case["seed"].as_i64().unwrap_or(0);
self.fixture_reset(seed);
self.world.game_time = case["time"].as_i64().unwrap_or(0);
// The oracle level's clock stands at day time 6000.
self.world.day_time = 6000;
if let Some(rules) = case["rules"].as_object() {
for (name, value) in rules {
if let Some(b) = value.as_bool() {
self.ui.rules.set(name, RuleValue::Bool(b));
}
}
}
let mut before: HashMap<(i32, i32, i32), u32> = HashMap::new();
for cell in case["cells"].as_array().into_iter().flatten() {
let p = (
cell[0].as_i64().unwrap_or(0) as i32,
cell[1].as_i64().unwrap_or(0) as i32,
cell[2].as_i64().unwrap_or(0) as i32,
);
let state = BlockStateId(cell[3].as_u64().unwrap_or(0) as u32);
self.world.set(p.0, p.1, p.2, state)?;
before.insert(p, state.0);
if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) {
self.world.block_entities.insert(p, entity);
}
}
for item in case["items"].as_array().into_iter().flatten() {
let p = (
item[0].as_i64().unwrap_or(0) as i32,
item[1].as_i64().unwrap_or(0) as i32,
item[2].as_i64().unwrap_or(0) as i32,
);
let slot = item[3].as_u64().unwrap_or(0) as usize;
let stack = parse_stack(item[4].as_str().unwrap_or("-"))?;
if let Some(cell) = self
.world
.block_entities
.get_mut(&p)
.and_then(|e| e.slots_mut().get_mut(slot))
{
*cell = stack;
}
}
let mut targets = Vec::new();
for e in case["entities"].as_array().into_iter().flatten() {
targets.push(self.fixture_target(e)?);
}
// Creating the targets must not move the stream the dispenser draws from.
self.world.random = LegacyRandom::new(seed);
self.world.block_log = Some(Vec::new());
self.audio.capture = Some(Vec::new());
LOG.with(|log| *log.borrow_mut() = Some(Vec::new()));
let old_mobs: Vec<u32> = self.mobs.iter().map(|m| m.id).collect();
let old_stands: Vec<u32> = self.armor_stands.iter().map(|s| s.id).collect();
let pos = &case["pos"];
let origin = BlockPos::new(
pos[0].as_i64().unwrap_or(0) as i32,
pos[1].as_i64().unwrap_or(0) as i32,
pos[2].as_i64().unwrap_or(0) as i32,
);
let state = self.world.block(origin.x, origin.y, origin.z);
self.dispense_from(origin, state)?;
let mut out = Vec::new();
let mut changed: Vec<(i32, i32, i32)> = self.world.block_log.take().unwrap_or_default();
changed.sort_unstable();
changed.dedup();
for p in changed {
let now = self.world.block(p.0, p.1, p.2).0;
if before.get(&p).copied().unwrap_or(self.res.facts.air.0) != now {
out.push(format!("set {},{},{} {now}", p.0, p.1, p.2));
}
}
let mut containers: Vec<_> = self.world.block_entities.keys().copied().collect();
containers.sort_unstable();
for p in containers {
let entity = &self.world.block_entities[&p];
for (i, slot) in entity.slots().iter().enumerate() {
if let Some(stack) = slot {
out.push(format!(
"inv {},{},{} {i} {}",
p.0,
p.1,
p.2,
canon_stack(Some(stack))
));
}
}
}
self.fixture_entities(&old_mobs, &old_stands, &mut out);
for (i, t) in targets.iter().enumerate() {
out.push(self.fixture_describe(i, t));
}
let log = LOG.with(|log| log.borrow_mut().take()).unwrap_or_default();
out.extend(log);
for (sound, at, _, _) in self.audio.capture.take().unwrap_or_default() {
out.push(format!("S {} {sound}", floor_pos(at)));
}
out.push(format!("rng {}", self.world.random.next_long()));
Ok(out)
}
/// `EntityType.create` and `snapTo` for one target: no spawn finalization.
fn fixture_target(&mut self, e: &Value) -> Result<Target> {
let kind = e["type"].as_str().unwrap_or("minecraft:pig");
let p = &e["pos"];
let at = horizon_core::geometry::Vec3::new(
p[0].as_f64().unwrap_or(0.0),
p[1].as_f64().unwrap_or(0.0),
p[2].as_f64().unwrap_or(0.0),
);
let yaw = e["yaw"].as_f64().unwrap_or(0.0) as f32;
self.next_entity += 1;
let id = self.next_entity;
if kind == "minecraft:armor_stand" {
self.armor_stands
.push(horizon_client::entities::ArmorStand::new(id, at, yaw));
return Ok(Target::Stand(id));
}
let t = self
.res
.mob_types
.get(kind)
.cloned()
.ok_or_else(|| format!("no mob type {kind}"))?;
let mut mob = Mob::new(id, t, at, yaw);
// EntityType.create equips nothing (that is finalizeSpawn's job).
for slot in [
&mut mob.extra.main_hand,
&mut mob.extra.off_hand,
&mut mob.extra.head,
&mut mob.extra.chest,
&mut mob.extra.legs,
&mut mob.extra.feet,
] {
*slot = None;
}
let s = mob.species();
let flag = |name: &str| e[name].as_bool().unwrap_or(false);
let ageable = !matches!(
s,
Species::Zombie
| Species::Skeleton
| Species::Bogged
| Species::SnowGolem
);
if flag("baby") && ageable {
mob.extra.age = -24000;
}
let tamable = body_in_head(s)
|| matches!(s, Species::Cat | Species::Parrot | Species::Ocelot);
if flag("tame") && tamable {
mob.extra.tame = true;
}
if flag("sheared") && matches!(s, Species::Sheep | Species::Bogged | Species::SnowGolem) {
mob.extra.sheared = true;
}
if flag("chest")
&& matches!(
s,
Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama
)
{
mob.extra.chested = true;
}
if flag("loot") {
mob.extra.pick_up_loot = true;
}
if flag("brown") && s == Species::Mooshroom {
mob.extra.variant = 1;
}
for (slot, snbt) in e["equip"].as_object().into_iter().flatten() {
if let (Some(slot), Some(stack)) = (
Slot::from_name(slot),
parse_stack(snbt.as_str().unwrap_or("-"))?,
) {
mob_set_slot(&mut mob, slot, stack);
}
}
self.mobs.push(mob);
Ok(Target::Mob(id))
}
/// `T` lines: removal, equipment by `EquipmentSlot`, shearing readiness, chests.
fn fixture_describe(&self, index: usize, target: &Target) -> String {
let mut line = format!("T {index} ");
match *target {
Target::Stand(id) => {
line.push_str("minecraft:armor_stand");
let Some(stand) = self.armor_stands.iter().find(|s| s.id == id) else {
line.push_str(" removed");
return line;
};
for (slot, name) in [
(0, "mainhand"),
(1, "offhand"),
(2, "feet"),
(3, "legs"),
(4, "chest"),
(5, "head"),
] {
if let Some(s) = &stand.equipment[slot] {
let _ = write!(line, " {name}={}x{}", s.item, s.count);
}
}
}
Target::Mob(id) => {
let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
return line + "removed";
};
line.push_str(&m.kind.id);
if m.removed || !m.alive() {
line.push_str(" removed");
}
let s = m.species();
let x = &m.extra;
for (slot, name) in [
(Slot::MainHand, "mainhand"),
(Slot::OffHand, "offhand"),
(Slot::Feet, "feet"),
(Slot::Legs, "legs"),
(Slot::Chest, "chest"),
(Slot::Head, "head"),
(Slot::Body, "body"),
(Slot::Saddle, "saddle"),
] {
if let Some(item) = mob_slot_item(m, slot) {
let _ = write!(line, " {name}={item}x1");
}
}
let ready = match s {
Species::Sheep => Some(!x.sheared && !m.is_baby()),
Species::Mooshroom => Some(!m.is_baby()),
Species::Bogged => Some(!x.sheared),
Species::SnowGolem => Some(!x.sheared),
_ => None,
};
if let Some(r) = ready {
line.push_str(if r { " ready" } else { " unready" });
}
if x.chested && matches!(s, Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama) {
line.push_str(" chest");
}
}
}
line
}
/// `N` lines for every entity the dispenser added.
fn fixture_entities(&self, old_mobs: &[u32], old_stands: &[u32], out: &mut Vec<String>) {
let line = |kind: &str, p: [f64; 3], v: [f64; 3], extra: &str| {
let mut l = format!(
"N {kind} {} {} {} {} {} {}",
num(p[0]),
num(p[1]),
num(p[2]),
num(v[0]),
num(v[1]),
num(v[2])
);
if !extra.is_empty() {
l.push(' ');
l.push_str(extra);
}
l
};
for m in self.mobs.iter().filter(|m| !old_mobs.contains(&m.id)) {
let (p, v) = (m.position, m.velocity);
out.push(line(&m.kind.id, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
for s in self.armor_stands.iter().filter(|s| !old_stands.contains(&s.id)) {
let (p, v) = (s.position, s.velocity);
out.push(line("minecraft:armor_stand", [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
for d in &self.dropped {
let (p, v) = (d.position, d.velocity);
out.push(line(
"minecraft:item",
[p.x, p.y, p.z],
[v.x, v.y, v.z],
&canon_stack(Some(&d.stack)),
));
}
for shot in &self.creatures.projectiles {
let kind = match &shot.kind {
ProjectileKind::Arrow {
effect: Some(("minecraft:glowing", 200)),
..
} => "minecraft:spectral_arrow",
ProjectileKind::Arrow { .. } => "minecraft:arrow",
ProjectileKind::Snowball => "minecraft:snowball",
ProjectileKind::Egg => "minecraft:egg",
ProjectileKind::SmallFireball => "minecraft:small_fireball",
ProjectileKind::WindCharge => "minecraft:wind_charge",
_ => "minecraft:unknown_projectile",
};
let (p, v) = (shot.position, shot.velocity);
out.push(line(kind, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
for (kind, p, v) in self.potions.thrown_entities() {
out.push(line(kind, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
for (p, v) in self.rockets.iter().map(|r| r.motion()) {
out.push(line("minecraft:firework_rocket", [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
for t in &self.tnts {
let (p, v) = (t.position, t.velocity);
out.push(line(
"minecraft:tnt",
[p.x, p.y, p.z],
[v.x, v.y, v.z],
&format!("fuse={}", t.fuse),
));
}
for b in &self.boats {
let kind = b.entity_type();
let (p, v) = (b.position, b.velocity);
out.push(line(&kind, [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
for c in &self.carts {
let (p, v) = (c.position, c.velocity);
out.push(line(c.kind.id(), [p.x, p.y, p.z], [v.x, v.y, v.z], ""));
}
}
}
File diff suppressed because it is too large Load Diff
+9 -4
View File
@@ -29,6 +29,12 @@ pub(super) struct Rocket {
angled: bool,
icon: Option<String>,
}
impl Rocket {
/// Position and motion (the dispenser parity fixture).
pub(super) fn motion(&self) -> (Vec3, Vec3) {
(self.position, self.velocity)
}
}
fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
// The item's default component: flight 1, no explosions.
stack
@@ -39,10 +45,9 @@ fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
impl Game<'_> {
pub(super) fn new_rocket(&mut self, at: Vec3, stack: &ItemStack, attached: bool) -> Rocket {
let (flight, explosions) = fireworks_of(stack);
let r = &mut self.world.random;
let tri = |r: &mut horizon_core::random::LegacyRandom| {
0.002297 * (f64::from(r.next_float()) - f64::from(r.next_float()))
};
// FireworkRocketEntity: motion and lifetime come from the rocket's own random.
let r = &mut super::dispenser::entity_random();
let tri = |r: &mut horizon_core::random::LegacyRandom| r.triangle(0.0, 0.002297);
let velocity = Vec3::new(tri(r), 0.05, tri(r));
let lifetime = 10 * (1 + i32::from(flight))
+ r.next_int_bound(6).unwrap_or(0)
+21
View File
@@ -65,6 +65,27 @@ pub(super) struct PotionState {
std::collections::HashMap<String, horizon_core::random::XoroshiroRandom>,
}
impl PotionState {
/// Thrown potions in flight as (entity type, position, motion), for the
/// dispenser parity fixture.
pub(super) fn thrown_entities(&self) -> Vec<(&'static str, Vec3, Vec3)> {
self.thrown
.iter()
.map(|t| {
let kind = match &*t.stack.item {
"minecraft:lingering_potion" => "minecraft:lingering_potion",
"minecraft:experience_bottle" => "minecraft:experience_bottle",
_ => "minecraft:splash_potion",
};
(kind, t.position, t.velocity)
})
.collect()
}
pub(super) fn clear_thrown(&mut self) {
self.thrown.clear();
}
}
impl Game<'_> {
/// Right-click with a potion, splash/lingering potion or glass bottle.
pub(super) fn use_potion_item(&mut self, stack: &ItemStack) -> horizon_client::Result<bool> {
+3
View File
@@ -437,6 +437,9 @@ impl Game<'_> {
/// `Level.gameEvent`: tell the listeners within reach.
pub(super) fn post_game_event(&mut self, event: &'static str, pos: [f64; 3], ctx: Context) {
super::dispense_fixture::record(|| {
format!("G {},{},{} {event}", pos[0].floor() as i32, pos[1].floor() as i32, pos[2].floor() as i32)
});
if self.remote.is_some() || !self.sculk.tables.built {
return;
}
+49 -10
View File
@@ -526,13 +526,23 @@ impl Items {
pub fn has_loot_table(&self, id: &str) -> bool {
self.loot.contains_key(id)
}
/// The server random sequence the block's loot table draws from.
pub fn block_loot_sequence(&self, registry: &BlockRegistry, state: BlockStateId) -> Option<String> {
let block = registry.state(state)?;
let name = block.name.trim_start_matches("minecraft:");
let standing = name.replacen("_wall_", "_", 1);
let standing = standing.strip_prefix("wall_").unwrap_or(&standing);
let standing = standing.replacen("wall_", "", 1);
self.loot_sequence(&format!("minecraft:blocks/{name}"))
.or_else(|| self.loot_sequence(&format!("minecraft:blocks/{standing}")))
}
/// Evaluate the block's loot table for a player break without explosions.
pub fn block_drops(
&self,
registry: &BlockRegistry,
state: BlockStateId,
held: Option<&ItemStack>,
random: &mut LegacyRandom,
random: &mut impl RandomSource,
) -> Vec<ItemStack> {
let Some(block) = registry.state(state) else {
return vec![];
@@ -581,6 +591,34 @@ impl Items {
};
ctx.evaluate(table, random)
}
/// The server random sequence a loot table draws from (`random_sequence`):
/// vanilla's `LootContext.Builder.create` uses it instead of the level random.
pub fn loot_sequence(&self, id: &str) -> Option<String> {
self.loot.get(id)?["random_sequence"]
.as_str()
.map(str::to_owned)
}
/// `loot_table` drawing from any random (a random sequence).
pub fn loot_table_from(
&self,
id: &str,
killed_by_player: bool,
held: Option<&ItemStack>,
random: &mut impl RandomSource,
) -> Vec<ItemStack> {
let Some(table) = self.loot.get(id) else {
return vec![];
};
let empty = BTreeMap::new();
let ctx = LootContext {
items: self,
block: "",
properties: &empty,
held,
killed_by_player,
};
ctx.evaluate(table, random)
}
pub fn entity_drops(
&self,
entity: &str,
@@ -604,14 +642,15 @@ impl Items {
}
}
impl LootContext<'_> {
fn evaluate(&self, table: &Value, random: &mut LegacyRandom) -> Vec<ItemStack> {
fn evaluate(&self, table: &Value, random: &mut impl RandomSource) -> Vec<ItemStack> {
let ctx = self;
let mut out = Vec::new();
for pool in table["pools"].as_array().into_iter().flatten() {
if !ctx.conditions(pool, random) {
continue;
}
let rolls = ctx.number(&pool["rolls"], random).max(0.0) as u32;
// LootPool: rolls.getInt (Mth.randomBetweenInclusive for uniform rolls).
let rolls = ctx.int_number(&pool["rolls"], random).max(0) as u32;
for _ in 0..rolls {
let mut produced = Vec::new();
ctx.choose(
@@ -643,7 +682,7 @@ impl LootContext<'_> {
fn enchantment_level(&self, id: &str) -> u32 {
self.held.map_or(0, |h| h.enchantment_level(id))
}
fn number(&self, v: &Value, random: &mut LegacyRandom) -> f32 {
fn number(&self, v: &Value, random: &mut impl RandomSource) -> f32 {
match v {
Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32,
Value::Object(o) => match o
@@ -674,7 +713,7 @@ impl LootContext<'_> {
_ => 1.0,
}
}
fn int_number(&self, v: &Value, random: &mut LegacyRandom) -> i32 {
fn int_number(&self, v: &Value, random: &mut impl RandomSource) -> i32 {
if let Value::Object(o) = v
&& o.get("type")
.and_then(Value::as_str)
@@ -691,7 +730,7 @@ impl LootContext<'_> {
}
self.number(v, random).round() as i32
}
fn condition(&self, c: &Value, random: &mut LegacyRandom) -> bool {
fn condition(&self, c: &Value, random: &mut impl RandomSource) -> bool {
let (kind, c) = match c {
Value::String(s) => (s.as_str(), &Value::Null),
Value::Object(o) => (o.get("type").and_then(Value::as_str).unwrap_or(""), c),
@@ -800,7 +839,7 @@ impl LootContext<'_> {
_ => true,
}
}
fn conditions(&self, o: &Value, random: &mut LegacyRandom) -> bool {
fn conditions(&self, o: &Value, random: &mut impl RandomSource) -> bool {
if let Some(c) = o.get("condition")
&& !self.condition(c, random)
{
@@ -816,7 +855,7 @@ impl LootContext<'_> {
fn expand(
&self,
e: &Value,
random: &mut LegacyRandom,
random: &mut impl RandomSource,
out: &mut Vec<(i32, ItemStack, Value)>,
) -> bool {
if !self.conditions(e, random) {
@@ -874,7 +913,7 @@ impl LootContext<'_> {
_ => false,
}
}
fn choose(&self, entries: &[Value], random: &mut LegacyRandom, produced: &mut Vec<ItemStack>) {
fn choose(&self, entries: &[Value], random: &mut impl RandomSource, produced: &mut Vec<ItemStack>) {
let mut candidates = Vec::new();
for e in entries {
self.expand(e, random, &mut candidates);
@@ -901,7 +940,7 @@ impl LootContext<'_> {
self.modifiers(&modifiers, &mut stack, random);
produced.push(stack);
}
fn modifiers(&self, m: &Value, stack: &mut ItemStack, random: &mut LegacyRandom) {
fn modifiers(&self, m: &Value, stack: &mut ItemStack, random: &mut impl RandomSource) {
let list: Vec<&Value> = match m {
Value::Array(a) => a.iter().collect(),
Value::Object(_) => vec![m],
+2 -1
View File
@@ -1162,7 +1162,8 @@ impl Mob {
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 at = [self.position.x, self.eye_y(), self.position.z];
// Entity.playSound: at the entity's feet.
let at = [self.position.x, self.position.y, self.position.z];
events.push(MobEvent::Sound(event, at, ai::sound_volume(self), pitch));
}
}
+4
View File
@@ -414,6 +414,10 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
// Entity.baseTick ends with Leashable.tickLeash.
super::leash::tick(m, w, events);
}
/// `Mob.playAmbientSound` on demand: a spawn egg or a mob bucket just placed `m`.
pub fn ambient_sound(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
play_ambient(m, w, events);
}
fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
let sound = match m.species() {
// Warden.getAmbientSound: by anger, silent while roaring or digging.
+21 -5
View File
@@ -19,6 +19,10 @@ pub enum BucketContent {
Fluid(FluidKind),
/// `SolidBucketItem`: the block placed into an empty space (powder snow).
Powder,
/// `MobBucketItem` holding water: its empty sound posts no `FLUID_PLACE`.
MobWater,
/// `MobBucketItem` without a fluid (the sulfur cube bucket): only the sound.
Nothing,
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
@@ -58,14 +62,23 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
if self.is_in_valid_bounds(pos) && b.is_air(self.state(pos)) {
let snow = b.table.default_state(b.named.powder_snow);
self.set_block_and_update(pos, snow);
// SolidBucketItem.emptyContents: one FLUID_PLACE, then the place sound.
self.game_event(pos, "minecraft:fluid_place");
self.empty_sound(pos, sound);
let sound: Arc<str> = sound.into();
self.sound(pos, &sound, 1.0, 1.0);
return true;
}
return false;
}
BucketContent::Nothing => {
let sound: Arc<str> = sound.into();
self.sound(pos, &sound, 1.0, 1.0);
return true;
}
BucketContent::MobWater => FluidKind::Water,
BucketContent::Fluid(fluid) => fluid,
};
let mob = content == BucketContent::MobWater;
let state = self.state(pos);
// canBeReplaced(fluid): replaceable or not solid (portals refuse).
let may_replace = !b.instance_of(state, Class::EndPortal)
@@ -91,7 +104,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
}
if liquid_container && water {
self.place_liquid(pos, state, FluidState::new(FluidKind::Water, 8, false));
self.empty_sound(pos, sound);
self.empty_sound(pos, sound, mob);
return true;
}
if may_replace && !b.instance_of(state, Class::Liquid) {
@@ -112,13 +125,16 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
{
return false;
}
self.empty_sound(pos, sound);
self.empty_sound(pos, sound, mob);
true
}
fn empty_sound(&mut self, pos: BlockPos, sound: &str) {
/// `playEmptySound`: `MobBucketItem` overrides it without the game event.
fn empty_sound(&mut self, pos: BlockPos, sound: &str, mob: bool) {
let sound: Arc<str> = sound.into();
self.sound(pos, &sound, 1.0, 1.0);
self.game_event(pos, "minecraft:fluid_place");
if !mob {
self.game_event(pos, "minecraft:fluid_place");
}
}
}
+2
View File
@@ -265,7 +265,9 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
return false;
}
if b.is_block(state, b.named.powder_snow) {
// PowderSnowBlock.pickupBlock: the block breaks with its particles and sound.
self.set_block(pos, b.air(), 11);
self.level_event(2001, pos, state.0 as i32);
return true;
}
false
@@ -30,6 +30,8 @@ public final class ParityData {
public static RegistryAccess access;
public static RegistryOps<Tag> ops;
public static ServerLevel level;
/** The loot tables of the vanilla data pack. */
public static ReloadableServerRegistries.Holder loot;
public static void init() throws Exception {
SharedConstants.tryDetectVersion();
@@ -44,6 +46,7 @@ public final class ParityData {
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
var worldLayers = layers.replaceFrom(RegistryLayer.WORLD, world);
var loaded = ReloadableServerRegistries.reload(worldLayers, staticTags, resources, Runnable::run).join();
loot = new ReloadableServerRegistries.Holder(loaded.lookupWithUpdatedTags());
lookup = loaded.lookupWithUpdatedTags();
var components = BuiltInRegistries.DATA_COMPONENT_INITIALIZERS.build(lookup);
staticTags.forEach(Registry.PendingTags::apply);
@@ -91,6 +91,12 @@ public final class VanillaBlockUpdateOracle {
return old;
}
@Override
public void markUnsaved() { }
@Override
public BlockState getBlockState(BlockPos pos) { return world.getBlockState(pos); }
@Override
public FluidState getFluidState(BlockPos pos) { return world.getFluidState(pos); }
@Override
public net.minecraft.world.level.chunk.status.ChunkStatus getPersistedStatus() {
return net.minecraft.world.level.chunk.status.ChunkStatus.FULL;
}
@@ -145,6 +151,23 @@ public final class VanillaBlockUpdateOracle {
}
@Override public LevelChunk getChunkAt(BlockPos p) { return chunk; }
@Override public LevelChunk getChunk(int x, int z) { return chunk; }
@Override public net.minecraft.world.level.chunk.ChunkAccess getChunk(int x, int z, net.minecraft.world.level.chunk.status.ChunkStatus status, boolean load) { return chunk; }
net.minecraft.server.waypoints.ServerWaypointManager waypoints;
@Override public net.minecraft.server.waypoints.ServerWaypointManager getWaypointManager() {
if (waypoints == null) waypoints = new net.minecraft.server.waypoints.ServerWaypointManager();
return waypoints;
}
net.minecraft.server.ServerScoreboard scoreboard;
@Override public net.minecraft.server.ServerScoreboard getScoreboard() {
if (scoreboard == null) scoreboard = new net.minecraft.server.ServerScoreboard(server);
return scoreboard;
}
/** The biome every position reads (plains), for the oracles that load the world registries. */
net.minecraft.core.Holder<net.minecraft.world.level.biome.Biome> biome;
@Override public net.minecraft.core.Holder<net.minecraft.world.level.biome.Biome> getBiome(BlockPos p) {
if (biome == null) biome = registryAccess().lookupOrThrow(net.minecraft.core.registries.Registries.BIOME).getOrThrow(net.minecraft.world.level.biome.Biomes.PLAINS);
return biome;
}
@Override public boolean isLoaded(BlockPos p) { return true; }
@Override public boolean hasChunkAt(BlockPos p) { return true; }
@Override public boolean hasChunksAt(int x0, int z0, int x1, int z1) { return true; }
@@ -160,7 +183,7 @@ public final class VanillaBlockUpdateOracle {
@Override public LevelTicks<Fluid> getFluidTicks() { return fluidTicks; }
@Override public void sendBlockUpdated(BlockPos p, BlockState a, BlockState b, int f) { }
@Override public void setBlocksDirty(BlockPos p, BlockState a, BlockState b) { }
@Override public net.minecraft.core.RegistryAccess registryAccess() { return RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); }
@Override public net.minecraft.core.RegistryAccess registryAccess() { return registries != null ? registries : RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); }
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return FeatureFlags.DEFAULT_FLAGS; }
@Override public GameRules getGameRules() { return rules; }
@Override public net.minecraft.server.MinecraftServer getServer() { return server; }
@@ -174,12 +197,34 @@ public final class VanillaBlockUpdateOracle {
@Override public boolean isRainingAt(BlockPos p) { return raining; }
@Override public boolean isUnobstructed(BlockState state, BlockPos pos, net.minecraft.world.phys.shapes.CollisionContext c) { return true; }
@Override public boolean isUnobstructed(Entity entity) { return true; }
@Override public List<Entity> getEntities(Entity except, AABB box, java.util.function.Predicate<? super Entity> filter) { return List.of(); }
@Override public <T extends Entity> List<T> getEntitiesOfClass(Class<T> type, AABB box, java.util.function.Predicate<? super T> filter) { return List.of(); }
// Entities exist only when a harness opts in (the dispenser oracle);
// they are searched in the order they were added, as within one entity section.
List<Entity> entities;
net.minecraft.core.RegistryAccess registries;
@Override public List<Entity> getEntities(Entity except, AABB box, java.util.function.Predicate<? super Entity> filter) {
if (entities == null) return List.of();
List<Entity> out = new ArrayList<>();
for (Entity e : List.copyOf(entities)) if (e != except && !e.isRemoved() && e.getBoundingBox().intersects(box) && filter.test(e)) out.add(e);
return out;
}
@Override public <T extends Entity> void getEntities(net.minecraft.world.level.entity.EntityTypeTest<Entity, T> type, AABB box, java.util.function.Predicate<? super T> filter, List<? super T> out, int max) {
if (entities == null) return;
for (Entity e : List.copyOf(entities)) {
T t = type.tryCast(e);
if (t != null && !e.isRemoved() && e.getBoundingBox().intersects(box) && filter.test(t)) {
out.add(t);
if (out.size() >= max) return;
}
}
}
@Override public <T extends Entity> List<T> getEntitiesOfClass(Class<T> type, AABB box, java.util.function.Predicate<? super T> filter) {
return getEntities(net.minecraft.world.level.entity.EntityTypeTest.forClass(type), box, filter);
}
@Override public List<net.minecraft.server.level.ServerPlayer> players() { return List.of(); }
@Override public net.minecraft.world.entity.player.Player getNearestPlayer(double x, double y, double z, double d, boolean b) { return null; }
@Override public boolean addFreshEntity(Entity entity) {
emit("E " + BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()));
if (entities != null) entities.add(entity);
return true;
}
@Override public void levelEvent(Entity source, int type, BlockPos p, int data) { emit("L " + type + " " + pos(p) + " " + data); }
@@ -187,7 +232,7 @@ public final class VanillaBlockUpdateOracle {
emit("S " + pos(BlockPos.containing(x, y, z)) + " " + sound.value().location());
}
@Override public void playSeededSound(Entity except, Entity src, net.minecraft.core.Holder<SoundEvent> sound, SoundSource source, float volume, float pitch, long seed) {
emit("S entity " + sound.value().location());
emit("S " + (entities != null ? pos(BlockPos.containing(src.position())) : "entity") + " " + sound.value().location());
}
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> e, Vec3 p, net.minecraft.world.level.gameevent.GameEvent.Context c) {
emit("G " + pos(BlockPos.containing(p)) + " " + e.getRegisteredName());
@@ -252,6 +297,10 @@ public final class VanillaBlockUpdateOracle {
return attributes;
}
@Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return OVERWORLD_TYPE; }
@Override public long getOverworldClockTime() { return DAY.totalTicks(); }
@Override public float getMoonBrightness(BlockPos p) {
return net.minecraft.world.level.dimension.DimensionType.MOON_BRIGHTNESS_PER_PHASE[environmentAttributes().getValue(net.minecraft.world.attribute.EnvironmentAttributes.MOON_PHASE, p).index()];
}
@Override public net.minecraft.world.level.storage.ServerLevelData getLevelData() { return LEVEL_DATA; }
@Override public boolean anyPlayerCloseEnoughForSpawning(BlockPos p) { return false; }
@Override public void playSound(Entity except, double x, double y, double z, SoundEvent sound, SoundSource source, float volume, float pitch) {
@@ -339,13 +388,15 @@ public final class VanillaBlockUpdateOracle {
static final class Loot extends net.minecraft.server.ReloadableServerRegistries.Holder {
World world;
/** The real loot tables, for the oracles that compare drops (the dispenser's). */
net.minecraft.server.ReloadableServerRegistries.Holder delegate;
Loot() {
super(null);
}
@Override
public net.minecraft.world.level.storage.loot.LootTable getLootTable(net.minecraft.resources.ResourceKey<net.minecraft.world.level.storage.loot.LootTable> id) {
world.emit("D " + id.identifier());
return net.minecraft.world.level.storage.loot.LootTable.EMPTY;
return delegate != null ? delegate.getLootTable(id) : net.minecraft.world.level.storage.loot.LootTable.EMPTY;
}
}
@@ -371,6 +422,12 @@ public final class VanillaBlockUpdateOracle {
@Override public boolean isPublished() { return false; }
@Override public boolean shouldInformAdmins() { return false; }
@Override public boolean isSingleplayerOwner(net.minecraft.server.players.NameAndId id) { return false; }
net.minecraft.world.RandomSequences sequences;
/** Loot tables with a random_sequence draw from the server's sequences (world seed 0). */
@Override public RandomSource getRandomSequence(net.minecraft.resources.Identifier key) {
if (sequences == null) sequences = new net.minecraft.world.RandomSequences();
return sequences.get(key, 0L);
}
}
static List<String> summary(World w, Map<BlockPos, BlockState> before) {
@@ -0,0 +1,271 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.file.*;
import java.util.*;
import net.minecraft.core.BlockPos;
import net.minecraft.core.NonNullList;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.Container;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.item.PrimedTnt;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.gamerules.GameRules;
import net.minecraft.world.level.levelgen.LegacyRandomSource;
/**
* Drives vanilla `DispenserBlock.dispenseFrom` (and the dropper's) over the
* headless level of {@link VanillaBlockUpdateOracle}, with entities: the
* dispenser holds the case's items, target entities stand in front, and the
* result lists block changes, container contents, spawned entities with their
* position and motion, the targets' state afterwards, level events, sounds
* (those the client plays for level events included), game events and the
* level random. Every case runs twice: numbers that differ between the runs
* come from an entity's own unseeded random and are marked with "~".
* Used by tools/test_dispenser_parity.py.
*/
public final class VanillaDispenserOracle {
/** The sound LevelEventHandler plays for a level event a dispenser can cause, or null. */
static String eventSound(int id, int data) {
return switch (id) {
case 1000 -> "minecraft:block.dispenser.dispense";
case 1001 -> "minecraft:block.dispenser.fail";
case 1002 -> "minecraft:block.dispenser.launch";
case 1004 -> "minecraft:entity.firework_rocket.shoot";
case 1018 -> "minecraft:entity.blaze.shoot";
case 1051 -> "minecraft:entity.wind_charge.throw";
case 1505 -> "minecraft:item.bone_meal.use";
case 1009 -> data == 0 ? "minecraft:block.fire.extinguish" : data == 1 ? "minecraft:block.generic.extinguish_fire" : null;
case 2001 -> {
BlockState state = Block.stateById(data);
yield state.isAir() ? null : state.getSoundType().getBreakSound().location().toString();
}
default -> null;
};
}
public static void main(String[] args) throws Exception {
ParityData.init();
VanillaBlockUpdateOracle.AIR = Blocks.AIR.defaultBlockState();
Path resources = Path.of(args[0]);
VanillaLevelShapeOracle.bindFluidTags(resources.resolve("data/minecraft/tags/fluid"));
VanillaBlockUpdateOracle.OVERWORLD_TYPE = VanillaBlockUpdateOracle.loadOverworld();
var allocator = Class.forName("sun.misc.Unsafe");
var field = allocator.getDeclaredField("theUnsafe");
field.setAccessible(true);
VanillaBlockUpdateOracle.unsafe = field.get(null);
VanillaBlockUpdateOracle.allocate = allocator.getMethod("allocateInstance", Class.class);
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[2]))); var lines = Files.lines(Path.of(args[1]))) {
int index = 0;
for (var line : (Iterable<String>) lines::iterator) {
var f = JsonParser.parseString(line).getAsJsonObject();
List<String> a = attempt(f), b = attempt(f);
out.print("case " + index++ + "\n");
for (String s : merge(a, b)) out.print(s + "\n");
}
}
}
static List<String> attempt(JsonObject f) {
List<String> result = new ArrayList<>();
try {
run(f, result);
} catch (Throwable e) {
Throwable c = e;
while (c.getCause() != null) c = c.getCause();
StackTraceElement[] st = c.getStackTrace();
result.clear();
result.add("error " + c.getClass().getSimpleName() + " " + (st.length > 0 ? st[0].toString() : "") + " " + c.getMessage());
}
return result;
}
/** Lines equal in both runs stay; numbers that differ are marked "~" (from an unseeded entity random). */
static List<String> merge(List<String> a, List<String> b) {
if (a.size() != b.size()) return a;
List<String> out = new ArrayList<>();
for (int i = 0; i < a.size(); i++) {
String x = a.get(i), y = b.get(i);
if (x.equals(y)) {
out.add(x);
continue;
}
String[] p = x.split(" "), q = y.split(" ");
if (p.length != q.length) {
out.add(x);
continue;
}
for (int j = 0; j < p.length; j++) if (!p[j].equals(q[j])) p[j] = "~" + p[j];
out.add(String.join(" ", p));
}
return out;
}
static String num(double v) {
return String.format(Locale.ROOT, "%.6f", v);
}
static ItemStack stack(String snbt) throws Exception {
return ParityData.stack(snbt);
}
/** The item list of a container block entity (dispensers, droppers, chests, hoppers, barrels...). */
@SuppressWarnings("unchecked")
static NonNullList<ItemStack> slots(BlockEntity be) throws Exception {
for (Class<?> c = be.getClass(); c != null; c = c.getSuperclass()) {
for (Field fd : c.getDeclaredFields()) {
if (fd.getType() == NonNullList.class && !java.lang.reflect.Modifier.isStatic(fd.getModifiers())) {
fd.setAccessible(true);
return (NonNullList<ItemStack>) fd.get(be);
}
}
}
throw new IllegalStateException("no slots in " + be);
}
static Method dispenseFrom(Class<?> type) throws Exception {
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
try {
Method m = c.getDeclaredMethod("dispenseFrom", ServerLevel.class, BlockState.class, BlockPos.class);
m.setAccessible(true);
return m;
} catch (NoSuchMethodException ignored) {
}
}
throw new IllegalStateException("no dispenseFrom on " + type);
}
static Entity target(VanillaBlockUpdateOracle.World w, JsonObject e) throws Exception {
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(e.get("type").getAsString()));
Entity ent = type.create(w, EntitySpawnReason.COMMAND);
var p = e.getAsJsonArray("pos");
ent.snapTo(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble(), e.has("yaw") ? e.get("yaw").getAsFloat() : 0f, 0f);
if (e.has("baby") && ent instanceof AgeableMob ageable) ageable.setAge(-24000);
if (e.has("tame")) {
if (ent instanceof net.minecraft.world.entity.animal.equine.AbstractHorse horse) horse.setTamed(true);
if (ent instanceof TamableAnimal tamable) tamable.setTame(true, false);
}
if (e.has("sheared")) {
if (ent instanceof net.minecraft.world.entity.animal.sheep.Sheep sheep) sheep.setSheared(true);
if (ent instanceof net.minecraft.world.entity.monster.skeleton.Bogged bogged) bogged.setSheared(true);
if (ent instanceof net.minecraft.world.entity.animal.golem.SnowGolem golem) golem.setPumpkin(false);
}
if (e.has("chest") && ent instanceof net.minecraft.world.entity.animal.equine.AbstractChestedHorse chested) chested.setChest(true);
if (e.has("loot") && ent instanceof Mob mob) mob.setCanPickUpLoot(true);
if (e.has("brown") && ent instanceof net.minecraft.world.entity.animal.cow.MushroomCow cow) {
Method variant = net.minecraft.world.entity.animal.cow.MushroomCow.class.getDeclaredMethod("setVariant", net.minecraft.world.entity.animal.cow.MushroomCow.Variant.class);
variant.setAccessible(true);
variant.invoke(cow, net.minecraft.world.entity.animal.cow.MushroomCow.Variant.BROWN);
}
// A target has lived in the level for a while: past its first tick, so
// equipping it plays the equip sound.
VanillaBlockUpdateOracle.set(Entity.class, ent, "firstTick", false);
if (e.has("equip") && ent instanceof LivingEntity living) {
for (var slot : e.getAsJsonObject("equip").entrySet()) {
living.setItemSlot(EquipmentSlot.byName(slot.getKey()), stack(slot.getValue().getAsString()));
}
// A target that has ticked since it was equipped has run
// collectEquipmentChanges (a sulfur cube takes its archetype then).
Map<EquipmentSlot, ItemStack> last = new EnumMap<>(EquipmentSlot.class);
for (EquipmentSlot slot : EquipmentSlot.values()) last.put(slot, ItemStack.EMPTY);
Method collect = LivingEntity.class.getDeclaredMethod("collectEquipmentChanges", Map.class);
collect.setAccessible(true);
collect.invoke(ent, last);
}
return ent;
}
static void run(JsonObject f, List<String> result) throws Exception {
VanillaBlockUpdateOracle.World w = VanillaBlockUpdateOracle.build(f);
w.entities = new ArrayList<>();
w.registries = ParityData.access;
w.server.loot.delegate = ParityData.loot;
VanillaBlockUpdateOracle.set(Level.class, w, "damageSources", new net.minecraft.world.damagesource.DamageSources(ParityData.access));
if (f.has("rules")) {
for (var rule : f.getAsJsonObject("rules").entrySet()) {
if (rule.getKey().equals("tnt_explodes")) w.rules.set(GameRules.TNT_EXPLODES, rule.getValue().getAsBoolean(), null);
}
}
if (f.has("items")) {
for (var item : f.getAsJsonArray("items")) {
var it = item.getAsJsonArray();
BlockPos at = new BlockPos(it.get(0).getAsInt(), it.get(1).getAsInt(), it.get(2).getAsInt());
slots(w.getBlockEntity(at)).set(it.get(3).getAsInt(), stack(it.get(4).getAsString()));
}
}
if (f.has("entities")) {
for (var e : f.getAsJsonArray("entities")) w.entities.add(target(w, e.getAsJsonObject()));
}
// Creating the targets must not move the stream the dispenser draws from.
w.rng = new LegacyRandomSource(f.get("seed").getAsLong());
VanillaBlockUpdateOracle.set(Level.class, w, "random", w.rng);
w.log = new StringBuilder();
w.blockEvents.clear();
Map<BlockPos, BlockState> before = new HashMap<>(w.cells);
List<Entity> targets = List.copyOf(w.entities);
BlockPos origin = VanillaBlockUpdateOracle.readPos(f.getAsJsonArray("pos"));
BlockState state = w.getBlockState(origin);
dispenseFrom(state.getBlock().getClass()).invoke(state.getBlock(), w, state, origin);
result.addAll(VanillaBlockUpdateOracle.summary(w, before));
List<BlockPos> containers = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet());
containers.sort(Comparator.<BlockPos>comparingInt(q -> q.getX()).thenComparingInt(q -> q.getY()).thenComparingInt(q -> q.getZ()));
for (BlockPos at : containers) {
if (!(w.blockEntities.get(at) instanceof Container) || w.getBlockEntity(at) != w.blockEntities.get(at)) continue;
var items = slots(w.blockEntities.get(at));
for (int i = 0; i < items.size(); i++) {
if (!items.get(i).isEmpty()) result.add("inv " + VanillaBlockUpdateOracle.pos(at) + " " + i + " " + ParityData.canon(items.get(i)));
}
}
for (Entity e : w.entities) {
if (targets.contains(e)) continue;
StringBuilder line = new StringBuilder("N ").append(BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()));
line.append(' ').append(num(e.getX())).append(' ').append(num(e.getY())).append(' ').append(num(e.getZ()));
var v = e.getDeltaMovement();
line.append(' ').append(num(v.x)).append(' ').append(num(v.y)).append(' ').append(num(v.z));
if (e instanceof ItemEntity item) line.append(' ').append(ParityData.canon(item.getItem()));
if (e instanceof PrimedTnt tnt) line.append(" fuse=").append(tnt.getFuse());
result.add(line.toString());
}
for (int i = 0; i < targets.size(); i++) result.add(describe(i, targets.get(i)));
for (String s : w.log.toString().split("\n")) {
if (s.isEmpty() || s.startsWith("E ")) continue;
result.add(s);
if (s.startsWith("L ")) {
String[] p = s.split(" ");
String sound = eventSound(Integer.parseInt(p[1]), Integer.parseInt(p[3]));
if (sound != null) result.add("S " + p[2] + " " + sound);
}
}
result.addAll(w.blockEvents);
result.add("rng " + w.rng.nextLong());
}
/** A target's state after dispensing: removal, equipment and readiness for shearing. */
static String describe(int index, Entity e) {
StringBuilder line = new StringBuilder("T " + index + " " + BuiltInRegistries.ENTITY_TYPE.getKey(e.getType()));
if (e.isRemoved()) line.append(" removed");
if (e instanceof LivingEntity living) {
for (EquipmentSlot slot : EquipmentSlot.values()) {
ItemStack s = living.getItemBySlot(slot);
if (!s.isEmpty()) line.append(' ').append(slot.getName()).append('=').append(BuiltInRegistries.ITEM.getKey(s.getItem())).append('x').append(s.getCount());
}
}
boolean listed = e instanceof net.minecraft.world.entity.animal.sheep.Sheep || e instanceof net.minecraft.world.entity.animal.cow.MushroomCow
|| e instanceof net.minecraft.world.entity.monster.skeleton.Bogged || e instanceof net.minecraft.world.entity.animal.golem.SnowGolem;
if (listed && e instanceof Shearable shearable) line.append(shearable.readyForShearing() ? " ready" : " unready");
if (e instanceof net.minecraft.world.entity.animal.equine.AbstractChestedHorse chested && chested.hasChest()) line.append(" chest");
return line.toString();
}
}
+303
View File
@@ -0,0 +1,303 @@
#!/usr/bin/env python3
"""Compare vanilla dispensers and droppers with Horizon's, one activation per case.
A dispenser or dropper at the origin faces a random direction and holds the
case's items; the block in front (and below it) comes from a palette of blocks
the behaviours care about, and some cases put a target entity in front. Vanilla
`DispenserBlock.dispenseFrom` runs over the headless level of the block update
oracle (`VanillaDispenserOracle`); Horizon runs its game glue in a headless game
(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, container contents,
spawned entities (type, position, motion), the targets afterwards, level events,
sounds, game events and the level random. Motion drawn from an entity's own
unseeded random (vanilla marks it "~") is compared within its spread.
"""
import json
import os
import random
import subprocess
try:
from . import block_update_harness as h, lab, test_rust_parity as base
except ImportError:
import block_update_harness as h
import lab
import test_rust_parity as base
DIRECTIONS = ['down', 'up', 'north', 'south', 'west', 'east']
STEP = {'down': (0, -1, 0), 'up': (0, 1, 0), 'north': (0, 0, -1), 'south': (0, 0, 1), 'west': (-1, 0, 0), 'east': (1, 0, 0)}
def potion(item, name):
return '{id:"minecraft:%s",count:1,components:{"minecraft:potion_contents":{potion:"minecraft:%s"}}}' % (item, name)
def plain(item, count=1):
return '{id:"minecraft:%s",count:%d}' % (item, count)
# Items with the blocks and entities in front that exercise their behaviour.
ITEMS = {
'drop': [plain('stone', 5), plain('diamond'), plain('stick', 64), plain('oak_sapling', 3), plain('redstone', 2)],
'projectile': [plain('arrow', 3), potion('tipped_arrow', 'poison'), plain('spectral_arrow'), plain('egg', 2), plain('blue_egg'),
plain('brown_egg'), plain('snowball', 4), plain('experience_bottle'), potion('splash_potion', 'healing'),
potion('lingering_potion', 'swiftness'), plain('firework_rocket', 2), plain('fire_charge', 2), plain('wind_charge', 3)],
'bucket': [plain('water_bucket'), plain('lava_bucket'), plain('powder_snow_bucket'), plain('salmon_bucket'), plain('cod_bucket'),
plain('pufferfish_bucket'), plain('tropical_fish_bucket'), plain('axolotl_bucket'), plain('tadpole_bucket'),
plain('sulfur_cube_bucket'), plain('bucket'), plain('bucket', 3)],
'block': [plain('bone_meal', 4), plain('tnt', 2), plain('flint_and_steel'), plain('glowstone', 3), plain('honeycomb', 2),
plain('glass_bottle', 2), potion('potion', 'water'), potion('potion', 'healing'), plain('shulker_box'),
plain('red_shulker_box'), plain('carved_pumpkin'), plain('wither_skeleton_skull'), plain('shears'), plain('brush')],
'vehicle': [plain('oak_boat'), plain('bamboo_raft'), plain('minecart'), plain('chest_minecart'),
plain('furnace_minecart'), plain('tnt_minecart'), plain('hopper_minecart'), plain('armor_stand', 2)],
'spawn': [plain('pig_spawn_egg'), plain('sheep_spawn_egg', 2), plain('zombie_spawn_egg'), plain('cow_spawn_egg'), plain('chicken_spawn_egg')],
'equipment': [plain('iron_helmet'), plain('diamond_chestplate'), plain('leather_leggings'), plain('golden_boots'),
plain('turtle_helmet'), plain('saddle'), plain('iron_horse_armor'), plain('white_carpet'), plain('chest'),
plain('carved_pumpkin'), plain('elytra'), plain('wolf_armor'), plain('shears'), plain('brush'), plain('player_head')],
}
FRONT = {
'drop': ['air', 'stone', 'water', 'chest', 'hopper'],
'projectile': ['air', 'air', 'water', 'stone', 'glass'],
'bucket': ['air', 'air', 'water', 'water', 'lava', 'powder_snow', 'oak_slab', 'seagrass', 'stone', 'cauldron', 'kelp',
'grass_block', 'fire'],
'block': ['air', 'grass_block', 'wheat', 'oak_sapling', 'tnt', 'campfire', 'candle', 'respawn_anchor', 'beehive', 'bee_nest',
'copper_block', 'exposed_cut_copper_stairs', 'dirt', 'coarse_dirt', 'rooted_dirt', 'water', 'seagrass', 'stone',
'sweet_berry_bush', 'cocoa', 'obsidian', 'soul_campfire', 'candle_cake', 'netherrack', 'moss_block'],
'vehicle': ['air', 'air', 'water', 'rail', 'powered_rail', 'activator_rail', 'stone', 'detector_rail'],
'spawn': ['air', 'air', 'water', 'stone', 'grass_block'],
'equipment': ['air'],
}
BELOW = ['air', 'stone', 'water', 'rail', 'grass_block', 'soul_sand', 'dirt', 'farmland', 'netherrack']
TARGETS = {
'iron_helmet': ['zombie', 'skeleton', 'armor_stand', 'pig'],
'diamond_chestplate': ['zombie', 'armor_stand'],
'leather_leggings': ['skeleton', 'armor_stand'],
'golden_boots': ['zombie', 'armor_stand'],
'turtle_helmet': ['armor_stand', 'zombie'],
'saddle': ['pig', 'horse', 'strider', 'donkey', 'camel', 'llama'],
'iron_horse_armor': ['horse', 'donkey'],
'white_carpet': ['llama', 'horse', 'trader_llama'],
'chest': ['donkey', 'mule', 'llama', 'horse'],
'carved_pumpkin': ['zombie', 'armor_stand', 'snow_golem'],
'elytra': ['armor_stand', 'zombie'],
'wolf_armor': ['wolf'],
'shears': ['sheep', 'sheep', 'mooshroom', 'bogged', 'snow_golem'],
'brush': ['armadillo'],
'tnt': ['sulfur_cube'],
'flint_and_steel': ['sulfur_cube'],
'stone': ['sulfur_cube'],
'player_head': ['armor_stand', 'zombie'],
}
class States:
def __init__(self, facts):
self.facts = facts
def get(self, name, **props):
name = name if ':' in name else 'minecraft:' + name
best = self.facts.defaults[name]
if not props:
return best
for index in self.facts.by_block[name]:
have = self.facts.states[index][4].get('properties', {})
if all(have.get(k) == v for k, v in props.items()):
return index
raise KeyError((name, props))
def any(self, rng, name):
name = name if ':' in name else 'minecraft:' + name
return rng.choice(self.facts.by_block[name])
def front_state(states, rng, name):
"""Mostly the default state, sometimes a random one (charges, honey, ages, lit...)."""
if name in ('respawn_anchor', 'beehive', 'bee_nest', 'campfire', 'candle', 'wheat', 'sweet_berry_bush', 'rail', 'powered_rail',
'candle_cake', 'soul_campfire') or rng.random() < 0.3:
return states.any(rng, name)
return states.get(name)
def cases(facts, count, seed, only):
rng = random.Random(seed)
states = States(facts)
kinds = list(ITEMS)
for n in range(count):
kind = kinds[n % len(kinds)]
item = rng.choice(ITEMS[kind])
if only and only not in item:
continue
facing = rng.choice(DIRECTIONS)
block = 'dropper' if rng.random() < 0.12 else 'dispenser'
cells = [[0, 0, 0, states.get(block, facing=facing, triggered='false')]]
dx, dy, dz = STEP[facing]
front = (dx, dy, dz)
below = (dx, dy - 1, dz)
front_name = rng.choice(FRONT[kind])
if front_name != 'air':
h.put(cells, front, front_state(states, rng, front_name))
if below != (0, 0, 0) and rng.random() < 0.8:
name = rng.choice(BELOW)
if name != 'air':
h.put(cells, below, front_state(states, rng, name))
# A few random blocks around (portal frames, fire supports, neighbours).
for _ in range(rng.randrange(0, 6)):
at = (rng.randrange(-2, 3), rng.randrange(-2, 3), rng.randrange(-2, 3))
if at in ((0, 0, 0), front):
continue
h.put(cells, at, states.get(rng.choice(['stone', 'obsidian', 'dirt', 'water', 'soul_sand', 'grass_block', 'oak_planks'])))
items = []
slots = rng.sample(range(9), rng.choice([1, 1, 1, 2, 3, 9]))
for i, slot in enumerate(slots):
items.append([0, 0, 0, slot, item if i == 0 or rng.random() < 0.6 else plain('cobblestone', rng.randrange(1, 65))])
case = {**h.environment(rng), 'mode': 'dispense', 'pos': [0, 0, 0], 'cells': cells, 'items': items}
case.pop('raining', None)
case.pop('thundering', None)
if rng.random() < 0.08:
case['rules'] = {'tnt_explodes': False}
bare = item.split('"')[1].split(':')[1]
if kind == 'equipment' or (bare in TARGETS and rng.random() < 0.5):
entities = []
for _ in range(rng.choice([1, 1, 1, 2])):
target = {'type': 'minecraft:' + rng.choice(TARGETS.get(bare, ['zombie'])),
'pos': [dx + 0.5, dy + rng.choice([0.0, 0.0, 0.25]), dz + 0.5], 'yaw': rng.choice([0.0, 90.0, 180.0])}
for flag, odds in (('baby', 0.2), ('tame', 0.6), ('sheared', 0.25), ('chest', 0.15), ('loot', 0.5), ('brown', 0.3)):
if rng.random() < odds:
target[flag] = True
if target['type'] == 'minecraft:sulfur_cube' and rng.random() < 0.5:
target['equip'] = {'body': plain(rng.choice(['tnt', 'stone', 'slime_block']))}
entities.append(target)
case['entities'] = entities
if block == 'dropper' and rng.random() < 0.5:
h.put(cells, front, states.get(rng.choice(['chest', 'hopper', 'barrel', 'dispenser'])))
if rng.random() < 0.5:
items.append([dx, dy, dz, 0, plain(rng.choice(['stone', 'diamond', 'stick']), rng.randrange(1, 65))])
yield case
# Items whose behaviour runs Mob.finalizeSpawn (spawn eggs, mob buckets). The
# finalization draws belong to the entity spawning port; for these cases the
# level random's end state is not compared, everything else is.
FINALIZED = ('_spawn_egg', 'salmon_bucket', 'cod_bucket', 'pufferfish_bucket', 'tropical_fish_bucket', 'axolotl_bucket',
'tadpole_bucket', 'sulfur_cube_bucket')
def finalizes(case):
return any(any(tag in i[4] for tag in FINALIZED) for i in case['items'] if i[:3] == [0, 0, 0])
def run(command, **kwargs):
done = subprocess.run(command, capture_output=True, text=True, **kwargs)
if done.returncode:
print((done.stdout + done.stderr)[-4000:])
raise SystemExit(f'{command[0]} failed')
return done
def numbers_close(java, rust):
"""Token-wise equality; a "~" token is an unseeded entity draw and only needs to fall in its spread."""
a, b = java.split(' '), rust.split(' ')
if len(a) != len(b):
return False
for x, y in zip(a, b):
if x.startswith('~'):
try:
if abs(float(x[1:]) - float(y)) > 0.25:
return False
except ValueError:
return False
elif x != y:
return False
return True
def same(java, rust):
java = sorted(java)
rust = sorted(rust)
if len(java) != len(rust):
return False
pending = list(rust)
for line in java:
if line in pending:
pending.remove(line)
continue
if '~' not in line:
return False
match = next((r for r in pending if numbers_close(line, r)), None)
if match is None:
return False
pending.remove(match)
return True
def main():
parser = h.argument_parser(__doc__)
args = parser.parse_args()
if args.count == 40000:
args.count = 3000
lock, jars, libraries = base.verify_artifacts()
facts = h.load_facts()
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
work = lab.LOCAL / 'dispenser-parity'
work.mkdir(parents=True, exist_ok=True)
all_cases = list(cases(facts, args.count, args.seed, args.only))
(work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases))
classes = work / 'classes'
classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
java_root = lab.ROOT / 'mods/horizon/src/test/java'
run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn',
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
run([str(lab.ROOT / 'target/release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
# Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared.
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases))
groups, errors = {}, {}
unseeded = 0
for case, a, b in zip(all_cases, native, rust):
if a and a[0].startswith('error'):
errors.setdefault(a[0], []).append(case)
continue
if finalizes(case):
unseeded += 1
# The spawned mob's variant (and so its voice) is chosen in finalizeSpawn too.
a = [line for line in a if not line.startswith('rng ') and not line.endswith('.ambient')]
b = [line for line in b if not line.startswith('rng ') and not line.endswith('.ambient')]
if not same(a, b):
item = next(i[4] for i in case['items'] if i[:3] == [0, 0, 0])
block = facts.states[case['cells'][0][3]][0].split(':')[1]
groups.setdefault(f'{block} {item.split(chr(34))[1]}', []).append((case, a, b))
for kind, entries in sorted(errors.items(), key=lambda e: -len(e[1])):
print(f'oracle error x{len(entries)}: {kind}')
for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])):
print(f'{name}: {len(entries)} differing')
for case, a, b in entries[:args.show]:
print(' case ' + describe(case, facts))
print(' native ' + ' | '.join(sorted(a)))
print(' rust ' + ' | '.join(sorted(b)))
total = sum(len(v) for v in groups.values())
skipped = sum(len(v) for v in errors.values())
print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors; '
f'{unseeded} spawning cases compared without the final level random)')
(work / 'differences.json').write_text(json.dumps({k: [[c, a, b] for c, a, b in v[:5]] for k, v in groups.items()}))
h.finish(total)
def describe(case, facts):
cells = ' '.join(f'{c[0]},{c[1]},{c[2]}={facts.describe(c[3])}' for c in case['cells'])
extra = ''
if case.get('entities'):
extra += ' entities=' + json.dumps(case['entities'])
if case.get('rules'):
extra += ' rules=' + json.dumps(case['rules'])
return f'{cells} items={json.dumps(case["items"])}{extra} seed={case["seed"]}'
if __name__ == '__main__':
main()