Merge branch 'parity-base' into parity/rendering-be

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-12 14:08:02 +02:00
52 changed files with 12898 additions and 455 deletions
+4 -4
View File
@@ -37,20 +37,20 @@ round-trip harness has not been rerun.
| Rendering | 0.75 | Entity models match over 150 layers; block entity renderers and HUD overlays not compared |
| Lighting | 1 | None: saved and relit light matches vanilla, slabs and stairs included |
| World generation | 1 | None: 2,352 whole chunks over 225 structure sites, in all three dimensions, identical to vanilla |
| Region files and saves | 0.75 | Save round-trip harness fails; older DataVersions are not upgraded |
| Region files and saves | 0.75 | Saves round-trip with vanilla, and worlds from 1.18.2 to 26.2 upgrade as vanilla's DataFixers do over 22 sample worlds; worlds older than 1.18.2 are not upgraded |
| Entities and physics | 0.75 | Attributes, dimensions, death loot, spawn rules and natural spawning (15,500 NaturalSpawner cases) match; AI not compared; drowned, villagers, traders and the wither unverified |
| Interaction and inventory | 1 | None: menu clicks match over 6,000 click sequences |
| Menus, HUD and chat | 0.75 | Commands parse as vanilla over 39,685 inputs, but /item modify, /spectate, /waypoint and /dialog do not run; no tab list or world border rendering |
| Audio | 0.75 | Sound engine, music and ambience not compared with vanilla |
| Block behaviours and ticking | 0.75 | Block updates, random ticks and redstone match vanilla; dispensers lack several behaviours |
| Block behaviours and ticking | 0.75 | Block updates, random ticks, redstone and dispensers match vanilla; a container replaced by another block keeps its contents instead of spilling them, and there are no copper golems |
### Next steps
1. Rerun the save round-trip harness and upgrade saves from older DataVersions.
1. Upgrade saves older than 1.18.2 (the DataFixers before DataVersion 2970).
2. Draw every item through the item model pipeline, and add the resource pack screen.
3. An audio harness: sound engine attenuation, weighted sound events, music and ambience.
4. A mob AI harness, and an oracle for drowned, villagers, traders and the wither.
5. The missing commands and dispenser behaviours, the tab list and world border rendering.
5. The missing commands, containers spilling when replaced, copper golems, the tab list and world border rendering.
6. Test LAN hosting with a vanilla client, and add a dedicated server mode.
```sh
+11 -10
View File
@@ -1136,22 +1136,19 @@ pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option<ArmorStand> {
a.on_ground = flag(tag, "OnGround");
Some(a)
}
/// A boat entity (`minecraft:<wood>_boat`, `minecraft:bamboo_raft`).
/// A boat entity (`minecraft:<wood>_boat`, `minecraft:bamboo_chest_raft`...):
/// chest boats keep their slots in `Items` (`ContainerHelper.saveAllItems`).
pub fn boat_to_nbt(
wood: &str,
id: &str,
position: Vec3,
motion: Vec3,
yaw: f32,
uuid: [i32; 4],
raw: Option<&Tag>,
items: Option<&[Option<crate::items::ItemStack>]>,
) -> Tag {
let id = if wood == "bamboo" {
"minecraft:bamboo_raft".to_owned()
} else {
format!("minecraft:{wood}_boat")
};
Base {
id: &id,
let mut tag = Base {
id,
uuid,
position,
motion,
@@ -1159,7 +1156,11 @@ pub fn boat_to_nbt(
on_ground: false,
fall_distance: 0.0,
}
.tag(raw)
.tag(raw);
if let (Some(items), Tag::Compound(map)) = (items, &mut tag) {
map.insert("Items".into(), crate::save::encode_items(items));
}
tag
}
/// A vehicle's base entity tag (boats and minecarts).
pub fn vehicle_to_nbt(
+38 -23
View File
@@ -19,6 +19,7 @@ mod control;
mod creaking;
mod creatures;
mod crossbow;
mod dispense_fixture;
mod dispenser;
mod dragon;
mod enchant_effects;
@@ -1027,8 +1028,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);
}
}
@@ -1039,7 +1041,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]);
@@ -1066,7 +1069,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,
@@ -1079,23 +1083,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.
@@ -1370,6 +1387,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 {
@@ -1377,10 +1395,14 @@ impl Game<'_> {
pos,
data,
} => {
// LevelRenderer: destroy particles and the block's break sound.
// LevelEventHandler: destroy particles and the block's
// break sound (none for air).
let state = BlockStateId(data as u32);
let p = [pos.x, pos.y, pos.z];
self.destroy_particles(p, state);
if self.res.facts.is_air(state) {
continue;
}
let sounds = self.res.facts.get(state).sounds.clone();
let c = [
f64::from(pos.x) + 0.5,
@@ -1443,12 +1465,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);
@@ -1794,12 +1811,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);
@@ -4867,8 +4879,8 @@ impl Game<'_> {
creative: bool,
) -> Result<()> {
let save_root = std::env::current_dir()?.join("saves").join(folder);
horizon_client::save::upgrade_older_world(&save_root)?;
horizon_client::save::migrate_legacy(&save_root)?;
horizon_client::save::check_data_version(&save_root)?;
self.session_lock = None;
self.session_lock = Some(horizon_client::save::SessionLock::acquire(&save_root)?);
self.persist = Default::default();
@@ -8164,6 +8176,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) = (
+96 -17
View File
@@ -48,7 +48,12 @@ pub(super) struct Boat {
/// left, right, up, down
pub input: [bool; 4],
pub on_ground: bool,
/// `ChestBoat`: a chest with 27 slots in the back seat.
pub chest: bool,
pub items: Vec<Option<ItemStack>>,
}
/// `ChestBoat.CONTAINER_SIZE`.
pub(super) const CHEST_SLOTS: usize = 27;
const WIDTH: f64 = 1.375;
const HEIGHT: f64 = 0.5625;
/// Player.DEFAULT_VEHICLE_ATTACHMENT minus the boat's passenger attachment.
@@ -76,8 +81,16 @@ impl Boat {
paddling: [false; 2],
input: [false; 4],
on_ground: false,
chest: false,
items: Vec::new(),
}
}
/// A chest boat or chest raft.
pub fn with_chest(mut self) -> Self {
self.chest = true;
self.items = vec![None; CHEST_SLOTS];
self
}
pub fn bounds(&self) -> Aabb {
let (w, p) = (WIDTH / 2.0, self.position);
Aabb::new(
@@ -95,6 +108,30 @@ impl Boat {
}
}
/// Item id -> (boat entity id, wood).
impl Boat {
/// The vanilla entity type id (`oak_boat`, `bamboo_chest_raft`), also
/// the item it drops.
pub(super) fn entity_type(&self) -> String {
let chest = if self.chest { "chest_" } else { "" };
if &*self.wood == "bamboo" {
format!("minecraft:bamboo_{chest}raft")
} else {
format!("minecraft:{}_{chest}boat", self.wood)
}
}
}
/// The wood of a boat or chest boat item or entity type, and whether it
/// carries a chest.
pub(super) fn any_boat_wood(item: &str) -> Option<(&str, bool)> {
let name = item.strip_prefix("minecraft:")?;
if let Some(wood) = name
.strip_suffix("_chest_boat")
.or_else(|| name.strip_suffix("_chest_raft"))
{
return Some((wood, true));
}
boat_wood(item).map(|w| (w, false))
}
pub(super) fn boat_wood(item: &str) -> Option<&str> {
let name = item.strip_prefix("minecraft:")?;
name.strip_suffix("_boat")
@@ -103,10 +140,20 @@ pub(super) fn boat_wood(item: &str) -> Option<&str> {
}
pub(super) struct BoatModels {
pub models: HashMap<String, Part>,
pub chest_models: HashMap<String, Part>,
}
impl BoatModels {
/// Whether a boat of this wood (with or without a chest) can be drawn.
pub fn has(&self, wood: &str, chest: bool) -> bool {
if chest {
self.chest_models.contains_key(wood)
} else {
self.models.contains_key(wood)
}
}
pub fn load(root: &std::path::Path) -> Self {
let mut models = HashMap::new();
let mut chest_models = HashMap::new();
if let Ok(bytes) = std::fs::read(root.join("entity-models.json"))
&& let Ok(serde_json::Value::Object(all)) =
serde_json::from_slice::<serde_json::Value>(&bytes)
@@ -119,9 +166,19 @@ impl BoatModels {
{
models.insert(wood.to_owned(), part);
}
if let Some(wood) = key
.strip_prefix("minecraft:chest_boat/")
.and_then(|k| k.strip_suffix("#main"))
&& let Some(part) = horizon_client::mobs::load_model(root, key)
{
chest_models.insert(wood.to_owned(), part);
}
}
}
Self { models }
Self {
models,
chest_models,
}
}
}
impl Game<'_> {
@@ -457,10 +514,10 @@ impl Game<'_> {
}
/// `BoatItem.use`: aim at a block or the water surface.
pub(super) fn place_boat(&mut self, stack: &ItemStack) -> bool {
let Some(wood) = boat_wood(&stack.item) else {
let Some((wood, chest)) = any_boat_wood(&stack.item) else {
return false;
};
if !self.boat_models.models.contains_key(wood) {
if !self.boat_models.has(wood, chest) {
return false;
}
let Some(eye) = self.eye_position() else {
@@ -507,12 +564,15 @@ impl Game<'_> {
(None, Some(w)) => w.0,
(None, None) => return false,
};
let boat = Boat::new(
let mut boat = Boat::new(
self.next_entity + 1,
Arc::from(wood),
Vec3::new(hit[0], hit[1], hit[2]),
self.yaw,
);
if chest {
boat = boat.with_chest();
}
let bb = boat.bounds();
let (lo, hi) = (bb.min_position(), bb.max_position());
let e = 1.0e-7;
@@ -575,11 +635,24 @@ impl Game<'_> {
return false;
};
let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft);
if !self.before_block(d)
|| sneaking
|| self.boats[i].out_of_control >= 60.0
|| self.riding.is_some()
{
if !self.before_block(d) {
return false;
}
// ChestBoat.interact: sneaking (or a full seat) opens the chest.
if self.boats[i].chest && (sneaking || self.riding.is_some()) {
let b = &self.boats[i];
let key = (i32::MAX - 15, super::minecarts::CART_KEY_Y, b.id as i32);
self.world.block_entities.insert(
key,
horizon_client::containers::BlockEntity::Chest(b.items.clone()),
);
self.container = Some(key);
self.screen = super::Screen::Inventory;
self.capture(false);
self.right = false;
return true;
}
if sneaking || self.boats[i].out_of_control >= 60.0 || self.riding.is_some() {
return false;
}
self.riding = Some(self.boats[i].id);
@@ -601,13 +674,13 @@ impl Game<'_> {
let destroyed = self.creative || b.damage > 40.0;
if destroyed {
let b = self.boats.remove(i);
let at = [b.position.x, b.position.y, b.position.z];
if !self.creative && self.ui.rules.bool("entity_drops") {
let item = if &*b.wood == "bamboo" {
"minecraft:bamboo_raft".to_owned()
} else {
format!("minecraft:{}_boat", b.wood)
};
let at = [b.position.x, b.position.y, b.position.z];
// ChestBoat.destroy: chestVehicleDestroyed spills the contents.
for stack in b.items.iter().flatten() {
self.spawn_item(stack.clone(), at, super::dispenser::new_item_motion(), 10);
}
let item = b.entity_type();
self.spawn_item(
ItemStack {
item: Arc::from(item.as_str()),
@@ -628,14 +701,20 @@ impl Game<'_> {
pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let a = alpha as f32;
for b in &self.boats {
let Some(model) = self.boat_models.models.get(&*b.wood) else {
let models = if b.chest {
&self.boat_models.chest_models
} else {
&self.boat_models.models
};
let Some(model) = models.get(&*b.wood) else {
continue;
};
let folder = if b.chest { "chest_boat" } else { "boat" };
let Some(uv) = self
.res
.atlas
.sprites
.get(&format!("entity/boat/{}", b.wood))
.get(&format!("entity/{folder}/{}", b.wood))
.map(|r| [r.u0, r.v0, r.u1, r.v1])
else {
continue;
+5 -7
View File
@@ -266,13 +266,11 @@ impl Game<'_> {
}
}
Target::Painting(_) => "minecraft:painting".into(),
Target::Boat(id) => self.boats.iter().find(|b| b.id == id).map_or_else(
|| "minecraft:oak_boat".into(),
|b| {
let kind = if &*b.wood == "bamboo" { "raft" } else { "boat" };
format!("minecraft:{}_{kind}", b.wood)
},
),
Target::Boat(id) => self
.boats
.iter()
.find(|b| b.id == id)
.map_or_else(|| "minecraft:oak_boat".into(), |b| b.entity_type()),
Target::Cart(id) => self
.carts
.iter()
@@ -73,12 +73,13 @@ impl Game<'_> {
let uuid = self.uuid_for(id);
let b = self.boats.iter().find(|b| b.id == id)?;
entity_nbt::boat_to_nbt(
&b.wood,
&b.entity_type(),
b.position,
b.velocity,
b.yaw,
uuid,
self.persist.raw.get(&id),
b.chest.then_some(&b.items[..]),
)
}
Target::Cart(id) => {
@@ -0,0 +1,510 @@
//! 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);
// The oracle level is plains everywhere (bone meal's flowers, freezing).
let plains = u32::from(self.res.biomes.id("minecraft:plains"));
for cx in -2..=2 {
for cz in -2..=2 {
let mut chunk = Chunk::empty(cx, cz);
for section in &mut chunk.sections {
Arc::make_mut(section).biomes = horizon_core::paletted::PalettedContainer::new(
horizon_client::chunk::BIOME_STRATEGY,
plains,
);
}
self.world.chunks.insert((cx, cz), Arc::new(chunk));
}
}
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 plays on normal difficulty.
self.ui.difficulty = 2;
// 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);
// The oracle level answers one sky and one block light everywhere.
let light = case["light"].as_array();
let level = |i: usize, default: i64| {
light
.and_then(|l| l.get(i))
.and_then(Value::as_i64)
.unwrap_or(default) as u8
};
let packed = (level(0, 15) << 4) | level(1, 0);
for chunk in self.world.chunks.values_mut() {
for section in &mut Arc::make_mut(chunk).sections {
Arc::make_mut(section).light = horizon_client::chunk::Light::Uniform(packed);
}
}
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)?);
}
// Leashable.setLeashedTo: a lead from a target to an earlier one.
for (e, t) in case["entities"]
.as_array()
.into_iter()
.flatten()
.zip(&targets)
{
let (Some(holder), Target::Mob(id)) = (e["leash"].as_u64(), t) else {
continue;
};
let holder = match targets.get(holder as usize) {
Some(Target::Mob(h)) => horizon_client::mobs::leash::Holder::Mob(*h),
_ => continue,
};
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == *id) {
m.extra.leash = Some(holder);
}
}
// 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");
}
if x.leash.is_some() {
line.push_str(" leashed");
}
}
}
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)
+62 -18
View File
@@ -24,6 +24,7 @@ impl Game<'_> {
if self.golem_block(below(1)) == "minecraft:snow_block"
&& self.golem_block(below(2)) == "minecraft:snow_block"
{
// The pattern ("^", "#", "#") is one column.
return Some((
"minecraft:snow_golem",
vec![head, below(1), below(2)],
@@ -38,9 +39,11 @@ impl Game<'_> {
&& self.golem_block(side(0, 2)) == "minecraft:iron_block"
&& [-1, 1].iter().all(|&s| air(side(s, 0)) && air(side(s, 2)))
{
let mut blocks = vec![head];
blocks.extend((-1..=1).map(|s| side(s, 1)));
blocks.push(side(0, 2));
// Every cell of ("~^~", "###", "~#~"), the air ones included.
let blocks = (-1..=1)
.flat_map(|s| (0..3).map(move |row| (s, row)))
.map(|(s, row)| side(s, row))
.collect();
return Some(("minecraft:iron_golem", blocks, side(0, 2)));
}
}
@@ -58,27 +61,68 @@ impl Game<'_> {
let Some((kind, blocks, base)) = self.find_golem(head) else {
return self.try_spawn_copper_golem(head);
};
for p in blocks {
let state = self.world.block(p[0], p[1], p[2]);
self.destroy_particles(p, state);
self.level_set(p, self.world.air)?;
}
// CarvedPumpkinBlock.spawnGolemInWorld
self.clear_pattern_blocks(&blocks)?;
let at = [
f64::from(base[0]) + 0.5,
f64::from(base[1]) + 0.05,
f64::from(base[2]) + 0.5,
];
if let Some(id) = self.spawn_mob(kind, at, false)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
m.yaw = 0.0;
m.body_yaw = 0.0;
m.head_yaw = 0.0;
m.previous_yaw = 0.0;
m.previous_body_yaw = 0.0;
m.previous_head_yaw = 0.0;
self.create_triggered(kind, at, 0.0);
self.update_pattern_blocks(&blocks)
}
/// Whether placing a golem head at `head` completes a snow or iron golem.
pub(super) fn completes_golem(&self, head: [i32; 3]) -> bool {
self.find_golem(head).is_some()
}
/// `EntityType.create(level, TRIGGERED)` and `snapTo`: a built golem or
/// wither has no spawn finalization and draws nothing from the level.
pub(super) fn create_triggered(&mut self, kind: &str, at: [f64; 3], yaw: f32) -> Option<u32> {
let t = self.res.mob_types.get(kind).cloned()?;
self.next_entity += 1;
let mut mob = horizon_client::mobs::Mob::new(
self.next_entity,
t,
horizon_core::geometry::Vec3::new(at[0], at[1], at[2]),
yaw,
);
mob.head_yaw = yaw;
mob.body_yaw = yaw;
mob.previous_yaw = yaw;
mob.previous_body_yaw = yaw;
mob.previous_head_yaw = yaw;
let id = mob.id;
self.mobs.push(mob);
Some(id)
}
/// `CarvedPumpkinBlock.clearPatternBlocks`: every cell of the match
/// becomes air (flags 2) with its destroy event (2001).
pub(super) fn clear_pattern_blocks(&mut self, cells: &[[i32; 3]]) -> Result<()> {
let air = self.world.air;
for &p in cells {
let state = self.world.block(p[0], p[1], p[2]);
let pos = horizon_core::position::BlockPos::new(p[0], p[1], p[2]);
self.with_level(|b, level, ticks| b.set_block(level, ticks, pos, air, 2));
self.level_events
.push(horizon_world::level::LevelEvent::LevelEvent {
id: 2001,
pos,
data: state.0 as i32,
});
}
Ok(())
self.process_level_events()
}
/// `CarvedPumpkinBlock.updatePatternBlocks`: neighbours of every cell
/// hear that air arrived.
pub(super) fn update_pattern_blocks(&mut self, cells: &[[i32; 3]]) -> Result<()> {
let air = self.world.air;
for &p in cells {
let pos = horizon_core::position::BlockPos::new(p[0], p[1], p[2]);
self.with_level(|b, level, ticks| {
b.update_neighbors_at(level, ticks, pos, b.block(air))
});
}
self.process_level_events()
}
/// A pumpkin on a copper block: the block turns into the matching copper
/// chest (facing the pumpkin's way) and a copper golem appears where the
+3 -7
View File
@@ -8,7 +8,6 @@ use horizon_client::{
mesher::Vertex,
mobs::leash::{self, Holder, Pending},
};
use horizon_core::random::RandomSource;
use horizon_world::nbt::Tag;
/// `Vec3.yRot(angle)`.
@@ -66,13 +65,10 @@ impl Game<'_> {
})
.collect()
}
/// `Entity.spawnAtLocation(level, Items.LEAD)`: the item entity draws its
/// motion from its own random, not the level's.
fn drop_lead_item(&mut self, at: [f64; 3]) {
let r = &mut self.world.random;
let v = [
f64::from(r.next_float()) * 0.2 - 0.1,
0.2,
f64::from(r.next_float()) * 0.2 - 0.1,
];
let v = super::dispenser::new_item_motion();
self.spawn_item(ItemStack::new("minecraft:lead", 1), at, v, 10);
}
/// `Leashable.dropLeash` / `removeLeash`: the lead falls as an item.
+29 -3
View File
@@ -28,6 +28,9 @@ pub(super) enum CartKind {
Hopper,
Furnace,
Tnt,
/// `MinecartCommandBlock`; its command block holds no command, so an
/// activator rail runs nothing.
CommandBlock,
}
impl CartKind {
pub fn from_id(id: &str) -> Option<Self> {
@@ -37,6 +40,7 @@ impl CartKind {
"hopper_minecart" => Self::Hopper,
"furnace_minecart" => Self::Furnace,
"tnt_minecart" => Self::Tnt,
"command_block_minecart" => Self::CommandBlock,
_ => return None,
})
}
@@ -47,6 +51,7 @@ impl CartKind {
Self::Hopper => "minecraft:hopper_minecart",
Self::Furnace => "minecraft:furnace_minecart",
Self::Tnt => "minecraft:tnt_minecart",
Self::CommandBlock => "minecraft:command_block_minecart",
}
}
fn slots(self) -> usize {
@@ -192,6 +197,7 @@ impl CartModels {
CartKind::Hopper,
CartKind::Furnace,
CartKind::Tnt,
CartKind::CommandBlock,
];
let models = kinds
.into_iter()
@@ -981,6 +987,8 @@ impl Game<'_> {
self.prime_cart(&mut c);
self.carts[i] = c;
}
// BaseCommandBlock.usedBy: only an operator in creative opens it.
CartKind::CommandBlock => return false,
}
self.swing_arm();
true
@@ -990,9 +998,10 @@ impl Game<'_> {
let Some(key) = self.container.filter(|k| k.1 == CART_KEY_Y) else {
return;
};
if let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key)
&& let Some(c) = self.carts.iter_mut().find(|c| c.id as i32 == key.2)
{
let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key) else {
return;
};
if let Some(c) = self.carts.iter_mut().find(|c| c.id as i32 == key.2) {
c.items = items;
let at = [c.position.x, c.position.y, c.position.z];
if c.kind == CartKind::Chest {
@@ -1000,15 +1009,24 @@ impl Game<'_> {
self.audio
.play("minecraft:block.chest.close", Some(at), 0.5, pitch);
}
} else if let Some(b) = self.boats.iter_mut().find(|b| b.id as i32 == key.2) {
b.items = items;
}
}
/// The open cart's kind when a cart container is shown.
pub(super) fn open_cart_kind(&self) -> Option<CartKind> {
let key = self.container.filter(|k| k.1 == CART_KEY_Y)?;
// A chest boat's chest shows like a chest minecart's.
self.carts
.iter()
.find(|c| c.id as i32 == key.2)
.map(|c| c.kind)
.or_else(|| {
self.boats
.iter()
.any(|b| b.chest && b.id as i32 == key.2)
.then_some(CartKind::Chest)
})
}
/// `VehicleEntity.hurtServer` from the player's attack.
pub(super) fn attack_cart(&mut self, damage: f32) -> bool {
@@ -1121,6 +1139,7 @@ impl Game<'_> {
],
),
CartKind::Tnt => registry.default_state("minecraft:tnt"),
CartKind::CommandBlock => registry.default_state("minecraft:command_block"),
}
}
/// `AbstractMinecartRenderer` (old render): on the rail between the
@@ -1284,6 +1303,13 @@ impl Minecart {
put("Fuel", Tag::Short(self.fuel as i16));
}
CartKind::Tnt => put("fuse", Tag::Int(self.fuse)),
// BaseCommandBlock.save of an empty command block.
CartKind::CommandBlock => {
put("Command", Tag::String(JavaString::from("")));
put("SuccessCount", Tag::Int(0));
put("TrackOutput", Tag::Byte(1));
put("UpdateLastExecution", Tag::Byte(1));
}
CartKind::Rideable => {}
}
}
+19 -9
View File
@@ -198,18 +198,27 @@ impl Game<'_> {
});
}
}
k if super::boats::boat_wood(k).is_some()
&& self
.boat_models
.models
.contains_key(super::boats::boat_wood(k).unwrap_or("")) =>
k if super::boats::any_boat_wood(k)
.is_some_and(|(wood, chest)| self.boat_models.has(wood, chest)) =>
{
if let Some((position, velocity, yaw)) = entity_nbt::boat_from_nbt(&tag) {
self.next_entity += 1;
let id = self.next_entity;
let wood =
std::sync::Arc::from(super::boats::boat_wood(k).unwrap_or("oak"));
let mut b = super::boats::Boat::new(id, wood, position, yaw);
let (wood, chest) =
super::boats::any_boat_wood(k).unwrap_or(("oak", false));
let mut b = super::boats::Boat::new(
id,
std::sync::Arc::from(wood),
position,
yaw,
);
if chest {
b = b.with_chest();
b.items = horizon_client::save::decode_items(
tag.get("Items"),
super::boats::CHEST_SLOTS,
);
}
b.velocity = velocity;
self.remember(id, uuid, tag);
self.boats.push(b);
@@ -536,12 +545,13 @@ impl Game<'_> {
.copied()
.unwrap_or_else(random_uuid);
let tag = entity_nbt::boat_to_nbt(
&b.wood,
&b.entity_type(),
b.position,
b.velocity,
b.yaw,
uuid,
self.persist.raw.get(&b.id),
b.chest.then_some(&b.items[..]),
);
out.entry(chunk_of(b.position)).or_default().push(tag);
}
+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> {
+8
View File
@@ -437,6 +437,14 @@ 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;
}
+11 -16
View File
@@ -40,35 +40,30 @@ impl Game<'_> {
if !ok {
continue;
}
for row in 0..3 {
for c in 0..3 {
let p = at(c, row);
let state = self.world.block(p[0], p[1], p[2]);
if !self.res.facts.is_air(state) {
self.destroy_particles(p, state);
self.world.set(p[0], p[1], p[2], self.world.air)?;
}
}
}
// WitherSkullBlock.checkSpawn: clear the pattern, the wither
// appears on the middle of the bottom row, then neighbours update.
let cells: Vec<[i32; 3]> = (0..3)
.flat_map(|c| (0..3).map(move |row| (c, row)))
.map(|(c, row)| at(c, row))
.collect();
self.clear_pattern_blocks(&cells)?;
let base = at(1, 2);
let at = [
f64::from(base[0]) + 0.5,
f64::from(base[1]) + 0.55,
f64::from(base[2]) + 0.5,
];
if let Some(id) = self.spawn_mob("minecraft:wither", at, true)
let yaw = if ax == 1 { 0.0 } else { 90.0 };
if let Some(id) = self.create_triggered("minecraft:wither", at, yaw)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
let yaw = if ax == 1 { 0.0 } else { 90.0 };
m.yaw = yaw;
m.body_yaw = yaw;
m.previous_body_yaw = yaw;
m.head_yaw = yaw;
m.persistent = true;
horizon_client::mobs::wither::make_invulnerable(m);
let view =
self.mob_entity(&self.mobs.iter().find(|m| m.id == id).cloned().unwrap());
self.trigger_entity("minecraft:summoned_entity", "entity", &view);
}
self.update_pattern_blocks(&cells)?;
return Ok(());
}
}
+58 -10
View File
@@ -526,13 +526,27 @@ 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 +595,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 +646,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 +686,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 +717,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 +734,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 +843,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 +859,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 +917,12 @@ 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 +949,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],
+14 -1
View File
@@ -995,6 +995,18 @@ impl Mob {
},
kind,
};
// setCanPickUpLoot(true) in the Villager, AbstractPiglin, Allay,
// Dolphin, Fox and Panda constructors.
mob.extra.pick_up_loot = matches!(
mob.species(),
Species::Villager
| Species::Piglin
| Species::PiglinBrute
| Species::Allay
| Species::Dolphin
| Species::Fox
| Species::Panda
);
ai::register(&mut mob);
mob
}
@@ -1216,7 +1228,8 @@ impl Mob {
/// Mob.playSound with LivingEntity.getVoicePitch.
pub fn voice(&mut self, event: &'static str, events: &mut Vec<MobEvent>) {
let pitch = self.voice_pitch();
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
@@ -420,6 +420,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.
+31 -12
View File
@@ -111,10 +111,13 @@ impl SessionLock {
Ok(Self(file))
}
}
/// Refuse a world last saved by an older game version: chunks are only read
/// at the current DataVersion, and the DataFixerUpper chain is not ported.
/// `tools/upgrade_world.py` runs vanilla's own upgrader (`--forceUpgrade`).
pub fn check_data_version(world: &Path) -> Result<()> {
/// Bring a world last saved by an older game version to the current format, as
/// 26.3 does when it opens one: the file fixes and level.dat first
/// (`FileFixerUpper`), then the DataFixers upgrades of every chunk, entity chunk,
/// POI chunk, player, saved data, advancements and statistics file. Vanilla runs
/// the latter as it reads each file; Horizon runs them all on opening, which reads
/// the same data. Worlds older than the ported fixes (1.18.2) are refused.
pub fn upgrade_older_world(world: &Path) -> Result<()> {
let Some(root) = read_dat(&world.join("level.dat")) else {
return Ok(());
};
@@ -122,14 +125,20 @@ pub fn check_data_version(world: &Path) -> Result<()> {
.get("Data")
.and_then(|d| number(d.get("DataVersion")))
.unwrap_or(i64::from(DATA_VERSION));
if version < i64::from(DATA_VERSION) {
if version >= i64::from(DATA_VERSION) {
return Ok(());
}
if version < i64::from(horizon_world::datafix::OLDEST_SUPPORTED) {
return Err(format!(
"{} was saved with DataVersion {version} (this game is {DATA_VERSION}); \
upgrade it first with tools/upgrade_world.py",
world.display()
"{} was saved with DataVersion {version}; worlds older than DataVersion {} (1.18.2) \
cannot be upgraded yet (tools/upgrade_world.py runs vanilla's own upgrader)",
world.display(),
horizon_world::datafix::OLDEST_SUPPORTED
)
.into());
}
horizon_world::datafix::files::upgrade_world(world)
.map_err(|e| format!("upgrading {}: {e}", world.display()))?;
Ok(())
}
/// Move a world saved by an older Horizon build (pre-26.3 layout with a
@@ -2181,14 +2190,24 @@ impl<G: ChunkGenerator> ChunkGenerator for Persistent<G> {
#[cfg(test)]
mod tests {
#[test]
fn old_data_version_is_refused() {
fn older_worlds_are_upgraded_on_opening() {
let dir = std::env::temp_dir().join(format!("horizon-dv-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let level =
|v: i32| Tag::compound([("Data", Tag::compound([("DataVersion", Tag::Int(v))]))]);
let version = |dir: &std::path::Path| {
super::read_dat(&dir.join("level.dat"))
.and_then(|r| super::number(r.get("Data")?.get("DataVersion")))
};
// 1.18, older than the ported fixes: refused, left as it is.
super::write_dat(&dir.join("level.dat"), level(2860)).unwrap();
assert!(super::upgrade_older_world(&dir).is_err());
assert_eq!(version(&dir), Some(2860));
// 1.21.1: upgraded to the current version.
super::write_dat(&dir.join("level.dat"), level(3955)).unwrap();
assert!(super::check_data_version(&dir).is_err());
super::write_dat(&dir.join("level.dat"), level(super::DATA_VERSION)).unwrap();
assert!(super::check_data_version(&dir).is_ok());
super::upgrade_older_world(&dir).unwrap();
assert_eq!(version(&dir), Some(i64::from(super::DATA_VERSION)));
super::upgrade_older_world(&dir).unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
@@ -0,0 +1,45 @@
//! Upgrade a copy of a world saved by 1.20 to 26.2 to the 26.3 format, as
//! vanilla 26.3 does when it opens it and reads every file:
//! `datafix_world IN_WORLD OUT_WORLD` (used by tools/test_datafix_parity.py).
use horizon_world::datafix::files;
use std::{env, fs, io, path::Path, process::ExitCode};
fn copy(from: &Path, to: &Path) -> io::Result<()> {
fs::create_dir_all(to)?;
for entry in fs::read_dir(from)? {
let entry = entry?;
let target = to.join(entry.file_name());
if entry.file_type()?.is_dir() {
copy(&entry.path(), &target)?;
} else if entry.file_name() != "session.lock" {
fs::copy(entry.path(), target)?;
}
}
Ok(())
}
fn main() -> ExitCode {
let args: Vec<String> = env::args().skip(1).collect();
let [input, output] = args.as_slice() else {
eprintln!("usage: datafix_world IN_WORLD OUT_WORLD");
return ExitCode::from(2);
};
let output = Path::new(output);
let result = (|| {
if output.exists() {
fs::remove_dir_all(output)?;
}
copy(Path::new(input), output)?;
files::upgrade_world(output)
})();
match result {
Ok(version) => {
println!("upgraded {} from DataVersion {version}", output.display());
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("datafix_world: {e}");
ExitCode::FAILURE
}
}
}
+241
View File
@@ -0,0 +1,241 @@
//! What DataFixerUpper's `Dynamic` over `NbtOps` does with values: number and
//! string views, maps and lists, field edits. Fixes use these to stay close to
//! the Java they port.
use crate::nbt::{Compound, JavaString, Tag};
pub fn key(s: &str) -> JavaString {
JavaString::from(s)
}
pub fn string(s: &str) -> Tag {
Tag::String(JavaString::from(s))
}
pub fn empty_map() -> Tag {
Tag::Compound(Compound::new())
}
pub fn boolean(b: bool) -> Tag {
Tag::Byte(i8::from(b))
}
pub fn int_list(values: &[i32]) -> Tag {
Tag::IntArray(values.to_vec())
}
/// A Java `Number` from a numeric tag (`Tag.asNumber`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Number {
Byte(i8),
Short(i16),
Int(i32),
Long(i64),
Float(f32),
Double(f64),
}
impl Number {
pub fn int_value(self) -> i32 {
match self {
Self::Byte(v) => i32::from(v),
Self::Short(v) => i32::from(v),
Self::Int(v) => v,
Self::Long(v) => v as i32,
Self::Float(v) => v as i32,
Self::Double(v) => v as i32,
}
}
pub fn long_value(self) -> i64 {
match self {
Self::Byte(v) => i64::from(v),
Self::Short(v) => i64::from(v),
Self::Int(v) => i64::from(v),
Self::Long(v) => v,
Self::Float(v) => v as i64,
Self::Double(v) => v as i64,
}
}
pub fn double_value(self) -> f64 {
match self {
Self::Byte(v) => f64::from(v),
Self::Short(v) => f64::from(v),
Self::Int(v) => f64::from(v),
Self::Long(v) => v as f64,
Self::Float(v) => f64::from(v),
Self::Double(v) => v,
}
}
pub fn float_value(self) -> f32 {
match self {
Self::Double(v) => v as f32,
Self::Long(v) => v as f32,
other => other.double_value() as f32,
}
}
pub fn byte_value(self) -> i8 {
match self {
Self::Byte(v) => v,
Self::Short(v) => v as i8,
Self::Int(v) => v as i8,
Self::Long(v) => v as i8,
Self::Float(v) => (v as i32) as i8,
Self::Double(v) => (v as i32) as i8,
}
}
/// `Number.toString` of the boxed value.
pub fn java_string(self) -> String {
match self {
Self::Byte(v) => v.to_string(),
Self::Short(v) => v.to_string(),
Self::Int(v) => v.to_string(),
Self::Long(v) => v.to_string(),
Self::Float(v) => crate::datafix::json::java_float_string(v),
Self::Double(v) => crate::datafix::json::java_double_string(v),
}
}
}
pub fn as_number(tag: &Tag) -> Option<Number> {
Some(match tag {
Tag::Byte(v) => Number::Byte(*v),
Tag::Short(v) => Number::Short(*v),
Tag::Int(v) => Number::Int(*v),
Tag::Long(v) => Number::Long(*v),
Tag::Float(v) => Number::Float(f32::from_bits(*v)),
Tag::Double(v) => Number::Double(f64::from_bits(*v)),
_ => return None,
})
}
pub fn as_int(tag: Option<&Tag>, default: i32) -> i32 {
tag.and_then(as_number).map_or(default, Number::int_value)
}
pub fn as_long(tag: Option<&Tag>, default: i64) -> i64 {
tag.and_then(as_number).map_or(default, Number::long_value)
}
pub fn as_double(tag: Option<&Tag>, default: f64) -> f64 {
tag.and_then(as_number)
.map_or(default, Number::double_value)
}
pub fn as_float(tag: Option<&Tag>, default: f32) -> f32 {
tag.and_then(as_number).map_or(default, Number::float_value)
}
/// `NbtOps.getBooleanValue`: a number that is not zero.
pub fn as_bool_opt(tag: Option<&Tag>) -> Option<bool> {
tag.and_then(as_number).map(|n| n.double_value() != 0.0)
}
pub fn as_bool(tag: Option<&Tag>, default: bool) -> bool {
as_bool_opt(tag).unwrap_or(default)
}
pub fn as_str(tag: Option<&Tag>) -> Option<String> {
match tag {
Some(Tag::String(s)) => Some(s.to_string_lossy()),
_ => None,
}
}
pub fn as_string(tag: Option<&Tag>, default: &str) -> String {
as_str(tag).unwrap_or_else(|| default.to_owned())
}
/// `NbtOps.getStream`: the elements of a list or of a number array.
pub fn stream(tag: Option<&Tag>) -> Vec<Tag> {
match tag {
Some(Tag::List(v)) => v.clone(),
Some(Tag::ByteArray(v)) => v.iter().map(|b| Tag::Byte(*b as i8)).collect(),
Some(Tag::IntArray(v)) => v.iter().map(|i| Tag::Int(*i)).collect(),
Some(Tag::LongArray(v)) => v.iter().map(|l| Tag::Long(*l)).collect(),
_ => Vec::new(),
}
}
pub fn is_list(tag: Option<&Tag>) -> bool {
matches!(
tag,
Some(Tag::List(_) | Tag::ByteArray(_) | Tag::IntArray(_) | Tag::LongArray(_))
)
}
pub fn get<'a>(tag: &'a Tag, field: &str) -> Option<&'a Tag> {
tag.get(field)
}
pub fn map(tag: &Tag) -> Option<&Compound> {
match tag {
Tag::Compound(c) => Some(c),
_ => None,
}
}
pub fn map_mut(tag: &mut Tag) -> Option<&mut Compound> {
match tag {
Tag::Compound(c) => Some(c),
_ => None,
}
}
/// `Dynamic.set`: only maps change.
pub fn set(tag: &mut Tag, field: &str, value: Tag) {
if let Tag::End = tag {
*tag = empty_map();
}
if let Tag::Compound(c) = tag {
c.insert(key(field), value);
}
}
pub fn remove(tag: &mut Tag, field: &str) -> Option<Tag> {
match tag {
Tag::Compound(c) => c.remove(&key(field)),
_ => None,
}
}
pub fn has(tag: &Tag, field: &str) -> bool {
tag.get(field).is_some()
}
/// `Dynamic.renameField`.
pub fn rename(tag: &mut Tag, from: &str, to: &str) {
if let Some(v) = remove(tag, from) {
set(tag, to, v);
}
}
/// `Dynamic.update`: apply `f` to a field that is present.
pub fn update(tag: &mut Tag, field: &str, f: impl FnOnce(Tag) -> Tag) {
if let Some(v) = remove(tag, field) {
set(tag, field, f(v));
}
}
/// `Dynamic.update` in place.
pub fn update_mut(tag: &mut Tag, field: &str, f: impl FnOnce(&mut Tag)) {
if let Some(v) = tag.get_mut(field) {
f(v);
}
}
/// `Dynamic.renameAndFixField`: the fixed value under the new name, removed when
/// the fix gives nothing.
pub fn rename_and_fix(tag: &mut Tag, from: &str, to: &str, f: impl FnOnce(Tag) -> Option<Tag>) {
if let Some(v) = remove(tag, from)
&& let Some(v) = f(v)
{
set(tag, to, v);
}
}
/// `Dynamic.copyField`.
pub fn copy_field(from: &Tag, field: &str, to: &mut Tag, to_field: &str) {
if let Some(v) = from.get(field) {
set(to, to_field, v.clone());
}
}
/// `Dynamic.equals(emptyMap())`: the map a record remembers it was read from
/// (see `datafix::mark_read`) is not part of the value.
pub fn is_empty_map(tag: &Tag) -> bool {
matches!(tag, Tag::Compound(c) if c.keys().all(|k| *k == key(super::LAST_READ)))
}
/// `Dynamic.orElseEmptyMap` of an optional field.
pub fn or_empty_map(tag: Option<&Tag>) -> Tag {
tag.cloned().unwrap_or_else(empty_map)
}
/// Apply `f` to every element of a list field (`Dynamic.createList(asStream().map(f))`).
pub fn map_list(tag: &mut Tag, field: &str, mut f: impl FnMut(Tag) -> Tag) {
if let Some(v) = tag.get(field)
&& is_list(Some(v))
{
let list = stream(Some(v)).into_iter().map(&mut f).collect();
set(tag, field, Tag::List(list));
}
}
/// `NamespacedSchema.ensureNamespaced`.
pub fn namespaced(id: &str) -> String {
match crate::datafix::identifier(id) {
Some((ns, path)) => format!("{ns}:{path}"),
None => id.to_owned(),
}
}
+680
View File
@@ -0,0 +1,680 @@
//! Opening an older world as 26.3 does: the file fixes of `FileFixerUpper`
//! (`net.minecraft.util.filefix`, from DataVersion 4772 on) that move the
//! files into the 26.x layout, then level.dat brought to the current version,
//! and the upgrades vanilla runs as it reads each file ([`upgrade_world`]
//! does them all at once, as a converter).
use super::dynamic::{as_bool, as_int, as_str, int_list, remove, set, string};
use super::json::{self, Json};
use super::schema::Ty;
use super::{CURRENT, update};
use crate::compression::Compression;
use crate::nbt::{self, Compound, JavaString, Limits, NamedTag, Tag};
use crate::region::{ChunkRecord, RegionFile, RegionWriter};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
/// The name `SharedConstants.getCurrentVersion().name()` writes in level.dat.
pub const VERSION_NAME: &str = "26.3";
const FILE_FIXER_INTRODUCTION: i32 = 4772;
/// The versions of the file fixes, in order.
const FILE_FIXES: [i32; 3] = [4772, 4773, 4899];
fn invalid(message: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message.into())
}
/// `NbtIo.readCompressed`: the root compound of a gzip NBT file, if it exists.
pub fn read_dat(path: &Path) -> io::Result<Option<Tag>> {
let bytes = match fs::read(path) {
Ok(b) => b,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
let limits = Limits::default();
let raw = Compression::Gzip.decode(&bytes, limits.max_bytes)?;
let (root, _) = nbt::read_named(&raw, limits).map_err(|e| invalid(e.to_string()))?;
Ok(Some(root.tag))
}
/// `NbtIo.writeCompressed`, creating the parent folders.
pub fn write_dat(path: &Path, tag: &Tag) -> io::Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let root = NamedTag {
name: JavaString::default(),
tag: tag.clone(),
};
let raw = nbt::write_named(&root, Limits::default()).map_err(|e| invalid(e.to_string()))?;
fs::write(path, Compression::Gzip.encode(&raw)?)
}
/// `NbtUtils.getDataVersion`.
pub fn data_version(tag: &Tag, default: i32) -> i32 {
match tag.get("DataVersion") {
Some(Tag::Int(v)) => *v,
_ => default,
}
}
/// `FileFixerUpper.requiresFileFixing`.
pub fn requires_file_fixing(level_version: i32) -> bool {
let from = if level_version < FILE_FIXER_INTRODUCTION {
0
} else {
level_version
};
from < *FILE_FIXES.last().unwrap()
}
// ------------------------------------------------------------------ file operations
fn resolve(base: &Path, relative: &str) -> PathBuf {
base.join(relative.trim_start_matches('/'))
}
/// `FileFixUtil.moveFile`: nothing when the source is missing, an error when
/// the target exists.
fn move_file(base: &Path, from: &str, to: &str) -> io::Result<()> {
let from = resolve(base, from);
if !from.exists() {
return Ok(());
}
let to = resolve(base, to);
if to.exists() {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!(
"cannot move {} to {}: target already exists",
from.display(),
to.display()
),
));
}
if let Some(parent) = to.parent() {
fs::create_dir_all(parent)?;
}
fs::rename(from, to)
}
/// `FileFixUtil.deleteFileOrEmptyDirectory`.
fn delete(base: &Path, relative: &str) -> io::Result<()> {
let path = resolve(base, relative);
if path.is_dir() {
let entries: Vec<_> = fs::read_dir(&path)?.collect::<Result<_, _>>()?;
if entries.len() == 1 && entries[0].file_name() == ".DS_Store" {
let _ = fs::remove_file(entries[0].path());
}
if fs::read_dir(&path)?.next().is_some() {
return Ok(());
}
fs::remove_dir(&path)
} else if path.exists() {
fs::remove_file(&path)
} else {
Ok(())
}
}
fn subdirectories(path: &Path) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = fs::read_dir(path)
.map(|r| {
r.filter_map(Result::ok)
.map(|e| e.path())
.filter(|p| p.is_dir())
.collect()
})
.unwrap_or_default();
out.sort();
out
}
/// `FileRelation.DIMENSIONS`.
fn dimensions(base: &Path) -> Vec<PathBuf> {
let root = base.join("dimensions");
let defaults = || {
["overworld", "the_nether", "the_end"]
.map(|d| base.join("dimensions/minecraft").join(d))
.to_vec()
};
if !root.exists() {
return defaults();
}
let found: Vec<PathBuf> = subdirectories(&root)
.iter()
.flat_map(|ns| subdirectories(ns))
.collect();
if found.is_empty() { defaults() } else { found }
}
// ------------------------------------------------------------------ file accessors
/// `LevelDat.read`: level.dat's `Data` brought to `version`.
fn read_level(base: &Path, version: i32) -> io::Result<Option<Tag>> {
Ok(read_dat(&base.join("level.dat"))?.map(|root| {
let mut data = root
.get("Data")
.cloned()
.unwrap_or_else(|| Tag::Compound(Compound::new()));
let from = data_version(&data, -1);
update(Ty::Level, &mut data, from, version);
data
}))
}
fn write_level(base: &Path, mut data: Tag, version: i32) -> io::Result<()> {
set(&mut data, "DataVersion", Tag::Int(version));
write_dat(&base.join("level.dat"), &Tag::compound([("Data", data)]))
}
/// `SavedDataNbt.write`.
fn write_saved_data(path: &Path, data: Tag, version: i32) -> io::Result<()> {
write_dat(
path,
&Tag::compound([("data", data), ("DataVersion", Tag::Int(version))]),
)
}
/// `SavedDataNbt.read`: the `data` of a saved data file brought to `version`.
fn read_saved_data(path: &Path, ty: Ty, version: i32) -> io::Result<Option<Tag>> {
Ok(read_dat(path)?.map(|mut tag| {
let from = data_version(&tag, -1);
update(ty, &mut tag, from, version);
tag.get("data")
.cloned()
.unwrap_or_else(|| Tag::Compound(Compound::new()))
}))
}
// ------------------------------------------------------------------ the file fixes
/// 4772: `ResourcePackLocationFileFix`, `DimensionStorageFileFix`,
/// `PlayerStorageFileFix`, `LevelDatToSavedDataFileFix`, `RemoveObsoleteFilesFileFix`.
fn fix_4772(base: &Path) -> io::Result<()> {
move_file(base, "resources.zip", "resourcepacks/resources.zip")?;
for dim in dimensions(base) {
let data = dim.join("data");
move_file(&data, "chunks.dat", "minecraft/chunk_tickets.dat")?;
move_file(&data, "raids.dat", "minecraft/raids.dat")?;
move_file(&data, "world_border.dat", "minecraft/world_border.dat")?;
}
for (from, to) in [
("data", "dimensions/minecraft/overworld/data/minecraft"),
(
"DIM-1/data",
"dimensions/minecraft/the_nether/data/minecraft",
),
("DIM1/data", "dimensions/minecraft/the_end/data/minecraft"),
] {
for (a, b) in [
("chunks.dat", "chunk_tickets.dat"),
("raids.dat", "raids.dat"),
("raids_end.dat", "raids.dat"),
("world_border.dat", "world_border.dat"),
] {
move_file(base, &format!("{from}/{a}"), &format!("{to}/{b}"))?;
}
}
delete(base, "DIM1/data")?;
delete(base, "DIM-1/data")?;
let data = base.join("data");
for (a, b) in [
("scoreboard.dat", "minecraft/scoreboard.dat"),
("stopwatches.dat", "minecraft/stopwatches.dat"),
] {
move_file(&data, a, b)?;
}
regex_move(&data, |name| {
let ns = name
.strip_prefix("command_storage_")?
.strip_suffix(".dat")?;
(!ns.is_empty()
&& ns
.bytes()
.all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'_' | b'.' | b'-')))
.then(|| format!("{ns}/command_storage.dat"))
})?;
move_file(&data, "idcounts.dat", "minecraft/maps/last_id.dat")?;
regex_move(&data, |name| {
let id = name.strip_prefix("map_")?.strip_suffix(".dat")?;
(!id.is_empty() && id.bytes().all(|b| b.is_ascii_digit()))
.then(|| format!("minecraft/maps/{id}.dat"))
})?;
move_file(
&data,
"random_sequences.dat",
"minecraft/random_sequences.dat",
)?;
for (from, to) in [
("", "dimensions/minecraft/overworld"),
("DIM-1", "dimensions/minecraft/the_nether"),
("DIM1", "dimensions/minecraft/the_end"),
] {
for f in ["region", "entities", "poi"] {
move_file(base, &format!("{from}/{f}"), &format!("{to}/{f}"))?;
}
}
delete(base, "DIM-1")?;
delete(base, "DIM1")?;
move_file(base, "advancements", "players/advancements")?;
move_file(base, "playerdata", "players/data")?;
move_file(base, "stats", "players/stats")?;
level_dat_to_saved_data(base)?;
for f in [
"data/villages.dat",
"data/villages_end.dat",
"data/villages_nether.dat",
"data/advancements",
"data/functions",
] {
delete(base, f)?;
}
for s in [
"Monument",
"Stronghold",
"Mineshaft",
"Temple",
"Mansion",
"Village",
"Fortress",
"EndCity",
] {
delete(base, &format!("data/{s}.dat"))?;
delete(base, &format!("data/{s}_index.dat"))?;
}
Ok(())
}
/// `RegexMove` over the files of a folder.
fn regex_move(folder: &Path, rename: impl Fn(&str) -> Option<String>) -> io::Result<()> {
if !folder.is_dir() {
return Ok(());
}
let mut names: Vec<String> = fs::read_dir(folder)?
.filter_map(Result::ok)
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
names.sort();
for name in names {
if let Some(new) = rename(&name) {
move_file(folder, &name, &new)?;
}
}
Ok(())
}
fn level_dat_to_saved_data(base: &Path) -> io::Result<()> {
const V: i32 = 4772;
let Some(mut content) = read_level(base, V)? else {
return Ok(());
};
let data = base.join("data/minecraft");
let dim_data = |dim: &str, file: &str| {
base.join(format!("dimensions/minecraft/{dim}/data/minecraft/{file}"))
};
let extract = |content: &mut Tag, key: &str, path: PathBuf| -> io::Result<()> {
if let Some(tag) = remove(content, key) {
write_saved_data(&path, tag, V)?;
}
Ok(())
};
extract(
&mut content,
"dragon_fight",
dim_data("the_end", "ender_dragon_fight.dat"),
)?;
if let Some(mut player) = remove(&mut content, "Player") {
let from = data_version(&player, -1);
update(Ty::Player, &mut player, from, V);
let uuid = match player.get("UUID") {
Some(u) => u.clone(),
None => {
set(&mut player, "DataVersion", Tag::Int(V));
write_dat(
&base.join("players/data/00000000-0000-0000-0000-000000000000.dat"),
&player,
)?;
int_list(&[0, 0, 0, 0])
}
};
set(&mut content, "singleplayer_uuid", uuid);
}
extract(
&mut content,
"wandering_trader_migration_data",
data.join("wandering_trader.dat"),
)?;
extract(
&mut content,
"CustomBossEvents",
data.join("custom_boss_events.dat"),
)?;
extract(&mut content, "weather_data", data.join("weather.dat"))?;
extract(
&mut content,
"scheduled_events",
data.join("scheduled_events.dat"),
)?;
if let Some(border) = content.get("world_border").cloned() {
for (dim, divider) in [("overworld", 1.0), ("the_nether", 8.0), ("the_end", 1.0)] {
let mut b = border.clone();
for k in ["center_x", "center_z"] {
if let Some(v) = b.get(k) {
let v = super::dynamic::as_double(Some(v), 0.0) / divider;
set(&mut b, k, Tag::Double(v.to_bits()));
}
}
write_saved_data(&dim_data(dim, "world_border.dat"), b, V)?;
}
}
remove(&mut content, "world_border");
extract(&mut content, "game_rules", data.join("game_rules.dat"))?;
if let Some(mut settings) = remove(&mut content, "world_gen_settings") {
let from = data_version(&content, -1);
update(Ty::WorldGenSettings, &mut settings, from, V);
write_saved_data(&data.join("world_gen_settings.dat"), settings, V)?;
}
extract(&mut content, "world_clocks", data.join("world_clocks.dat"))?;
write_level(base, content, V)
}
/// 4773: `GeneratedStructuresRenameFileFix`.
fn fix_4773(base: &Path) -> io::Result<()> {
for ns in subdirectories(&base.join("generated")) {
move_file(&ns, "structures", "structure")?;
}
Ok(())
}
/// 4899: `ReenableSpectatorsGenerateChunksInHardcoreWorldsFileFix`.
fn fix_4899(base: &Path) -> io::Result<()> {
const V: i32 = 4899;
let Some(level) = read_level(base, V)? else {
return Ok(());
};
let hardcore = level
.get("difficulty_settings")
.is_some_and(|d| as_bool(d.get("hardcore"), false));
if level.get("singleplayer_uuid").is_some() && hardcore {
let path = base.join("data/minecraft/game_rules.dat");
if let Some(mut rules) = read_saved_data(&path, Ty::SavedGameRules, V)? {
if rules.get("minecraft:spectators_generate_chunks").is_some() {
set(
&mut rules,
"minecraft:spectators_generate_chunks",
Tag::Byte(1),
);
}
write_saved_data(&path, rules, V)?;
}
}
Ok(())
}
/// `FileFixerUpper.addVersionsToLevelData`.
fn add_versions(data: &mut Tag) {
set(data, "DataVersion", Tag::Int(CURRENT));
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64);
set(data, "LastPlayed", Tag::Long(now));
set(
data,
"Version",
Tag::compound([
("Name", string(VERSION_NAME)),
("Id", Tag::Int(CURRENT)),
("Snapshot", Tag::Byte(0)),
("Series", string("main")),
]),
);
}
/// `FileFixerUpper.fix`: the file fixes a world saved at an older version
/// needs, then its level.dat at the current version. Returns the DataVersion
/// the world had.
pub fn fix_world_files(base: &Path) -> io::Result<i32> {
let root = read_dat(&base.join("level.dat"))?.ok_or_else(|| invalid("missing level.dat"))?;
let mut data = root
.get("Data")
.cloned()
.unwrap_or_else(|| Tag::Compound(Compound::new()));
let loaded = data_version(&data, -1);
if loaded >= CURRENT {
return Ok(loaded);
}
let mut from = loaded;
if requires_file_fixing(loaded) {
let start = if loaded < FILE_FIXER_INTRODUCTION {
0
} else {
loaded
};
for version in FILE_FIXES {
if version > start && version <= CURRENT {
match version {
4772 => fix_4772(base)?,
4773 => fix_4773(base)?,
_ => fix_4899(base)?,
}
}
}
// `writeUpdatedLevelData`, then the world swapped in and read again.
let root =
read_dat(&base.join("level.dat"))?.ok_or_else(|| invalid("missing level.dat"))?;
data = root
.get("Data")
.cloned()
.unwrap_or_else(|| Tag::Compound(Compound::new()));
from = data_version(&data, -1);
let _ = fs::remove_file(base.join("level.dat_old"));
let _ = fs::remove_file(base.join("session.lock"));
}
update(Ty::Level, &mut data, from, CURRENT);
add_versions(&mut data);
write_dat(&base.join("level.dat"), &Tag::compound([("Data", data)]))?;
Ok(loaded)
}
// ------------------------------------------------------------------ the read-time upgrades
/// Chunk generator types per dimension from `world_gen_settings.dat`.
fn generators(base: &Path) -> io::Result<Vec<(String, String)>> {
let Some(tag) = read_dat(&base.join("data/minecraft/world_gen_settings.dat"))? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
if let Some(Tag::Compound(dims)) = tag.get("data").and_then(|d| d.get("dimensions")) {
for (id, dim) in dims {
if let Some(ty) = dim.get("generator").and_then(|g| as_str(g.get("type"))) {
out.push((id.to_string_lossy(), ty));
}
}
}
Ok(out)
}
fn files_with_suffix(folder: &Path, suffix: &str) -> Vec<PathBuf> {
let mut out: Vec<PathBuf> = fs::read_dir(folder)
.map(|r| {
r.filter_map(Result::ok)
.map(|e| e.path())
.filter(|p| p.is_file() && p.to_string_lossy().ends_with(suffix))
.collect()
})
.unwrap_or_default();
out.sort();
out
}
/// Rewrite every chunk of the region files of a folder with `fix`.
fn upgrade_regions(folder: &Path, mut fix: impl FnMut(&mut Tag)) -> io::Result<()> {
let limits = Limits::default();
for path in files_with_suffix(folder, ".mca") {
let mut region = RegionFile::open(&path)?;
let positions: Vec<_> = region.chunks().map(|(p, _)| p).collect();
let mut records = Vec::new();
for pos in positions {
let Some(record) = region.read(pos)? else {
continue;
};
let mut root = record.nbt(limits)?;
fix(&mut root.tag);
records.push((
pos,
ChunkRecord::from_nbt(&root, record.compression, record.timestamp, limits)?,
));
}
drop(region);
let staging = folder.join(".datafix");
fs::create_dir_all(&staging)?;
let temporary = staging.join(path.file_name().unwrap_or_default());
let _ = fs::remove_file(&temporary);
let mut writer = RegionWriter::create(&temporary)?;
for (pos, record) in &records {
writer.write(*pos, record)?;
}
writer.finish()?;
fs::rename(&temporary, &path)?;
fs::remove_dir(&staging)?;
}
Ok(())
}
/// `SavedDataStorage.readTagFromDisk` over every known file of a data folder.
fn upgrade_saved_data(data: &Path) -> io::Result<()> {
if !data.is_dir() {
return Ok(());
}
let mut files = Vec::new();
let mut stack = vec![data.to_path_buf()];
while let Some(dir) = stack.pop() {
for entry in fs::read_dir(&dir)?.filter_map(Result::ok) {
let p = entry.path();
if p.is_dir() {
stack.push(p);
} else if p.to_string_lossy().ends_with(".dat") {
files.push(p);
}
}
}
files.sort();
for file in files {
let relative = file
.strip_prefix(data)
.unwrap_or(&file)
.to_string_lossy()
.replace('\\', "/");
let Some(ty) = super::saved_data_type(&relative) else {
continue;
};
if let Some(mut tag) = read_dat(&file)? {
super::update_saved_data(ty, &mut tag);
set(&mut tag, "DataVersion", Tag::Int(CURRENT));
write_dat(&file, &tag)?;
}
}
Ok(())
}
/// A JSON file of the player folders as NBT for the fixes (`JsonOps` and
/// `NbtOps` see the same structure), booleans kept apart.
fn json_to_tag(j: &Json) -> Tag {
match j {
Json::Bool(b) => Tag::compound([("\u{0}bool", Tag::Byte(i8::from(*b)))]),
Json::Arr(items) => Tag::List(items.iter().map(json_to_tag).collect()),
Json::Obj(entries) => Tag::Compound(
entries
.iter()
.map(|(k, v)| (JavaString(k.clone()), json_to_tag(v)))
.collect(),
),
other => json::to_nbt(other).unwrap_or(Tag::End),
}
}
fn tag_to_json(t: &Tag) -> Json {
match t {
Tag::Compound(c) if c.len() == 1 && c.contains_key(&JavaString::from("\u{0}bool")) => {
Json::Bool(as_int(t.get("\u{0}bool"), 0) != 0)
}
Tag::List(items) => Json::Arr(items.iter().map(tag_to_json).collect()),
Tag::Compound(c) => Json::Obj(
c.iter()
.map(|(k, v)| (k.0.clone(), tag_to_json(v)))
.collect(),
),
other => json::from_nbt(other),
}
}
fn upgrade_json(path: &Path, ty: Ty) -> io::Result<()> {
let text = fs::read_to_string(path)?;
let units: Vec<u16> = text.encode_utf16().collect();
let parsed = json::parse_lenient(&units)
.ok_or_else(|| invalid(format!("bad JSON in {}", path.display())))?;
let mut tag = json_to_tag(&parsed);
let from = super::dynamic::as_int(tag.get("DataVersion"), 1343);
if ty == Ty::Advancements {
// `PlayerAdvancements`: the version field is not part of the data.
remove(&mut tag, "DataVersion");
}
update(ty, &mut tag, from, CURRENT);
set(&mut tag, "DataVersion", Tag::Int(CURRENT));
let out = json::to_stable_string(&tag_to_json(&tag));
fs::write(path, String::from_utf16_lossy(&out))
}
/// Everything vanilla upgrades as it reads a world, done at once: every chunk,
/// entity chunk and POI chunk, saved data, player, advancements and
/// statistics file. Run after [`fix_world_files`].
pub fn upgrade_world_data(base: &Path) -> io::Result<()> {
let generators = generators(base)?;
for ns in subdirectories(&base.join("dimensions")) {
for dim in subdirectories(&ns) {
let id = format!(
"{}:{}",
ns.file_name().unwrap_or_default().to_string_lossy(),
dim.file_name().unwrap_or_default().to_string_lossy()
);
let generator = generators
.iter()
.find(|(d, _)| *d == id)
.map(|(_, g)| g.clone());
upgrade_regions(&dim.join("region"), |tag| {
super::update_chunk(tag, &id, generator.as_deref())
})?;
upgrade_regions(&dim.join("entities"), |tag| {
super::update_region_tag(Ty::EntityChunk, tag)
})?;
upgrade_regions(&dim.join("poi"), |tag| {
super::update_region_tag(Ty::PoiChunk, tag)
})?;
upgrade_saved_data(&dim.join("data"))?;
}
}
upgrade_saved_data(&base.join("data"))?;
for file in files_with_suffix(&base.join("players/data"), ".dat") {
if let Some(mut tag) = read_dat(&file)? {
super::update_player(&mut tag);
set(&mut tag, "DataVersion", Tag::Int(CURRENT));
write_dat(&file, &tag)?;
}
}
for file in files_with_suffix(&base.join("players/advancements"), ".json") {
upgrade_json(&file, Ty::Advancements)?;
}
for file in files_with_suffix(&base.join("players/stats"), ".json") {
upgrade_json(&file, Ty::Stats)?;
}
Ok(())
}
/// Bring a whole world saved by 1.20 to 26.2 to the 26.3 format in place.
pub fn upgrade_world(base: &Path) -> io::Result<i32> {
let version = fix_world_files(base)?;
upgrade_world_data(base)?;
Ok(version)
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,714 @@
//! Fixes of 1.19 to 1.20 (keys 3076 to 3459): what worlds saved by 1.18.2 to
//! 1.19.4 need before the fixes of [`super::fixes_a`]. The options fixes of
//! this range (3201, 3214, 3319) are client settings, not world data.
use super::dynamic::{
as_number, as_str, is_list, namespaced, remove, rename, set, stream, string, update,
};
use super::fixes_a::fix_block_pos;
use super::fixes_b::feature_flag_remove;
use super::schema::{Key, Ty, key};
use super::{Cx, FixFn, id_is, renamer, reread_as};
use crate::nbt::{Compound, Tag};
pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
out.push((key(3077, 0), chunk_delete_ignored_light));
out.push((key(3084, 0), |cx| {
cx.rename(Ty::GameEventName, renamer(GAME_EVENTS))
}));
out.push((key(3086, 0), |cx| {
entity_variant(cx, "minecraft:cat", "CatType", cat_type)
}));
out.push((key(3086, 0), |cx| {
criteria_rename(cx, "minecraft:husbandry/complete_catalogue", &|s| {
CAT_TEXTURES
.iter()
.find(|(from, _)| *from == s)
.map(|(_, to)| (*to).to_owned())
});
}));
out.push((key(3087, 0), |cx| {
entity_variant(cx, "minecraft:frog", "Variant", |n| match n {
0 => Some("minecraft:temperate"),
1 => Some("minecraft:warm"),
2 => Some("minecraft:cold"),
_ => None,
})
}));
out.push((key(3090, 0), |cx| {
cx.entity("minecraft:painting", |e| {
rename(e, "Motive", "variant");
rename(e, "Facing", "facing");
})
}));
out.push((key(3093, 0), |cx| {
cx.entity("minecraft:goat", |e| {
set(e, "HasLeftHorn", Tag::Byte(1));
set(e, "HasRightHorn", Tag::Byte(1));
})
}));
out.push((key(3094, 0), goat_horn_id));
out.push((key(3097, 0), filtered_books));
out.push((key(3097, 0), filtered_signs));
out.push((key(3097, 0), |cx| {
cx.entity("minecraft:cat", |e| {
if as_str(e.get("variant")).as_deref() == Some("minecraft:british") {
set(e, "variant", string("minecraft:british_shorthair"));
}
})
}));
out.push((key(3097, 0), |cx| {
criteria_rename(cx, "minecraft:husbandry/complete_catalogue", &|s| {
(s == "minecraft:british").then(|| "minecraft:british_shorthair".to_owned())
});
}));
out.push((key(3097, 0), |cx| {
poi_records(cx, |r| {
!matches!(
as_str(r.get("type")).as_deref(),
Some("minecraft:unemployed" | "minecraft:nitwit") | None
)
})
}));
out.push((key(3108, 0), |cx| {
cx.each_out(Ty::Chunk, |c| {
let dimension = c.get("__context").and_then(|x| as_str(x.get("dimension")));
if dimension.as_deref() != Some("minecraft:overworld") {
remove(c, "blending_data");
}
})
}));
out.push((key(3209, 0), pig_spawn_egg));
out.push((key(3322, 0), effect_duration));
out.push((key(3438, 0), |cx| {
cx.each(Ty::BlockEntity, |be| {
if id_is(be, "minecraft:suspicious_sand") {
set(be, "id", string("minecraft:brushable_block"));
}
})
}));
out.push((key(3438, 0), |cx| {
cx.each_out(Ty::BlockEntity, |be| {
if id_is(be, "minecraft:brushable_block") {
rename(be, "loot_table", "LootTable");
rename(be, "loot_table_seed", "LootTableSeed");
}
})
}));
out.push((key(3438, 0), |cx| {
cx.rename(Ty::ItemName, renamer(POTTERY_SHARDS))
}));
out.push((key(3439, 0), |cx| sign_double_sided(cx, "minecraft:sign")));
out.push((key(3439, 1), |cx| {
sign_double_sided(cx, "minecraft:hanging_sign")
}));
out.push((key(3440, 0), multi_noise_preset));
out.push((key(3440, 0), |cx| {
feature_flag_remove(cx, &["minecraft:update_1_20"])
}));
out.push((key(3447, 0), |cx| {
cx.rename(Ty::ItemName, |id| {
let id = namespaced(id);
POTTERY_SHERDS
.iter()
.find(|(from, _)| *from == id)
.map(|(_, to)| *to)
})
}));
// DecoratedPotFieldRenameFix converts unchecked: the typed shards are written
// as sherds, and the raw shards come back from the block entity's remainder.
out.push((key(3448, 0), |cx| {
cx.each(Ty::BlockEntity, |be| {
if id_is(be, "minecraft:decorated_pot")
&& let Some(shards) = be.get("shards").cloned()
{
set(be, "sherds", shards);
super::drop_typed(be, "shards");
}
})
}));
out.push((key(3450, 0), remap_chunk_status));
out.push((key(3451, 0), chunk_delete_light));
out.push((key(3459, 0), legacy_dragon_fight));
}
// ------------------------------------------------------------------ 3077, 3451
/// `ChunkDeleteIgnoredLightDataFix`.
fn chunk_delete_ignored_light(cx: &mut Cx) {
cx.each(Ty::Chunk, |c| {
let light_on = c
.get("isLightOn")
.and_then(as_number)
.is_some_and(|n| n.double_value() != 0.0);
if !light_on && let Some(Tag::List(sections)) = c.get_mut("sections") {
for s in sections {
remove(s, "BlockLight");
remove(s, "SkyLight");
}
}
});
}
/// `ChunkDeleteLightFix`.
fn chunk_delete_light(cx: &mut Cx) {
cx.each(Ty::Chunk, |c| {
remove(c, "isLightOn");
if let Some(Tag::List(sections)) = c.get_mut("sections") {
for s in sections {
remove(s, "BlockLight");
remove(s, "SkyLight");
}
}
});
}
// ------------------------------------------------------------------ 3084
const GAME_EVENTS: &[(&str, &str)] = &[
("minecraft:block_press", "minecraft:block_activate"),
("minecraft:block_switch", "minecraft:block_activate"),
("minecraft:block_unpress", "minecraft:block_deactivate"),
("minecraft:block_unswitch", "minecraft:block_deactivate"),
("minecraft:drinking_finish", "minecraft:drink"),
("minecraft:elytra_free_fall", "minecraft:elytra_glide"),
("minecraft:entity_damaged", "minecraft:entity_damage"),
("minecraft:entity_dying", "minecraft:entity_die"),
("minecraft:entity_killed", "minecraft:entity_die"),
("minecraft:mob_interact", "minecraft:entity_interact"),
("minecraft:ravager_roar", "minecraft:entity_roar"),
("minecraft:ring_bell", "minecraft:block_change"),
("minecraft:shulker_close", "minecraft:container_close"),
("minecraft:shulker_open", "minecraft:container_open"),
("minecraft:wolf_shaking", "minecraft:entity_shake"),
];
// ------------------------------------------------------------------ 3086, 3087, 3097
fn cat_type(n: i32) -> Option<&'static str> {
Some(match n {
1 => "minecraft:black",
2 => "minecraft:red",
3 => "minecraft:siamese",
4 => "minecraft:british",
5 => "minecraft:calico",
6 => "minecraft:persian",
7 => "minecraft:ragdoll",
8 => "minecraft:white",
9 => "minecraft:jellie",
10 => "minecraft:all_black",
// The map's default return value.
_ => "minecraft:tabby",
})
}
/// `EntityVariantFix`: the numeric variant written to `variant`; the old field
/// stays (`updateAndRename` only sets the new key). An id the map has no entry
/// for gives Java's `null`, which `createString` cannot take: such a variant is
/// left as the number.
fn entity_variant(cx: &mut Cx, id: &str, field: &str, ids: fn(i32) -> Option<&'static str>) {
cx.entity(id, |e| {
let Some(value) = e.get(field).cloned() else {
return;
};
let new = match as_number(&value).map(|n| ids(n.int_value())) {
Some(Some(name)) => string(name),
_ => value,
};
set(e, "variant", new);
});
}
const CAT_TEXTURES: &[(&str, &str)] = &[
("textures/entity/cat/tabby.png", "minecraft:tabby"),
("textures/entity/cat/black.png", "minecraft:black"),
("textures/entity/cat/red.png", "minecraft:red"),
("textures/entity/cat/siamese.png", "minecraft:siamese"),
(
"textures/entity/cat/british_shorthair.png",
"minecraft:british",
),
("textures/entity/cat/calico.png", "minecraft:calico"),
("textures/entity/cat/persian.png", "minecraft:persian"),
("textures/entity/cat/ragdoll.png", "minecraft:ragdoll"),
("textures/entity/cat/white.png", "minecraft:white"),
("textures/entity/cat/jellie.png", "minecraft:jellie"),
("textures/entity/cat/all_black.png", "minecraft:all_black"),
];
/// `CriteriaRenameFix`: the criteria keys of one advancement.
fn criteria_rename(cx: &mut Cx, advancement: &str, conversions: &dyn Fn(&str) -> Option<String>) {
cx.each(Ty::Advancements, |v| {
let Some(criteria) = v.get_mut(advancement).and_then(|a| a.get_mut("criteria")) else {
return;
};
if let Tag::Compound(c) = criteria {
let old = std::mem::take(c);
for (k, value) in old {
let name = k.to_string_lossy();
let k = conversions(&name).map_or(k, |n| n.as_str().into());
c.insert(k, value);
}
}
});
}
// ------------------------------------------------------------------ 3094, 3097
/// The `tag` of every stack whose id passes `filter` (`ItemStackTagFix`).
fn item_tag(cx: &mut Cx, filter: impl Fn(&str) -> bool, mut f: impl FnMut(&mut Tag)) {
cx.item(filter, |s| {
if let Some(tag) = s.get_mut("tag") {
f(tag);
}
});
}
const INSTRUMENTS: [&str; 8] = [
"minecraft:ponder_goat_horn",
"minecraft:sing_goat_horn",
"minecraft:seek_goat_horn",
"minecraft:feel_goat_horn",
"minecraft:admire_goat_horn",
"minecraft:call_goat_horn",
"minecraft:yearn_goat_horn",
"minecraft:dream_goat_horn",
];
/// `GoatHornIdFix`.
fn goat_horn_id(cx: &mut Cx) {
item_tag(
cx,
|id| id == "minecraft:goat_horn",
|tag| {
let variant = super::dynamic::as_int(tag.get("SoundVariant"), 0);
let sound = INSTRUMENTS[if (0..8).contains(&variant) {
variant as usize
} else {
0
}];
remove(tag, "SoundVariant");
set(tag, "instrument", string(sound));
},
);
}
/// `FilteredBooksFix`.
fn filtered_books(cx: &mut Cx) {
item_tag(
cx,
|id| id == "minecraft:writable_book" || id == "minecraft:written_book",
|tag| {
remove(tag, "filtered_title");
remove(tag, "filtered_pages");
},
);
}
/// `FilteredSignsFix` (a `NamedEntityWriteReadFix` over signs only).
fn filtered_signs(cx: &mut Cx) {
let k = cx.k;
cx.block_entity("minecraft:sign", |be| {
for i in 1..=4 {
remove(be, &format!("FilteredText{i}"));
}
reread_as(Ty::BlockEntity, k, be);
});
}
/// `AbstractPoiSectionFix`: the records of every POI section kept by `keep`.
fn poi_records(cx: &mut Cx, keep: impl Fn(&Tag) -> bool) {
cx.each(Ty::PoiChunk, |poi| {
let Some(Tag::Compound(sections)) = poi.get_mut("Sections") else {
return;
};
for section in sections.values_mut() {
if let Some(records) = section.get("Records")
&& is_list(Some(records))
{
let kept: Vec<Tag> = stream(Some(records))
.into_iter()
.filter(|r| keep(r))
.collect();
set(section, "Records", Tag::List(kept));
}
}
});
}
// ------------------------------------------------------------------ 3209
/// `ItemStackSpawnEggFix` for `minecraft:pig_spawn_egg`: an egg whose entity has
/// an id becomes that entity's egg.
fn pig_spawn_egg(cx: &mut Cx) {
cx.item(
|id| id == "minecraft:pig_spawn_egg",
|s| {
let entity = s
.get("tag")
.and_then(|t| t.get("EntityTag"))
.and_then(|e| as_str(e.get("id")));
if let Some(entity) = entity {
let egg = SPAWN_EGGS
.iter()
.find(|(e, _)| *e == namespaced(&entity))
.map_or("minecraft:pig_spawn_egg", |(_, egg)| egg);
set(s, "id", string(egg));
}
},
);
}
const SPAWN_EGGS: &[(&str, &str)] = &[
("minecraft:bat", "minecraft:bat_spawn_egg"),
("minecraft:blaze", "minecraft:blaze_spawn_egg"),
("minecraft:cave_spider", "minecraft:cave_spider_spawn_egg"),
("minecraft:chicken", "minecraft:chicken_spawn_egg"),
("minecraft:cow", "minecraft:cow_spawn_egg"),
("minecraft:creeper", "minecraft:creeper_spawn_egg"),
("minecraft:donkey", "minecraft:donkey_spawn_egg"),
(
"minecraft:elder_guardian",
"minecraft:elder_guardian_spawn_egg",
),
("minecraft:ender_dragon", "minecraft:ender_dragon_spawn_egg"),
("minecraft:enderman", "minecraft:enderman_spawn_egg"),
("minecraft:endermite", "minecraft:endermite_spawn_egg"),
(
"minecraft:evocation_illager",
"minecraft:evocation_illager_spawn_egg",
),
("minecraft:ghast", "minecraft:ghast_spawn_egg"),
("minecraft:guardian", "minecraft:guardian_spawn_egg"),
("minecraft:horse", "minecraft:horse_spawn_egg"),
("minecraft:husk", "minecraft:husk_spawn_egg"),
("minecraft:iron_golem", "minecraft:iron_golem_spawn_egg"),
("minecraft:llama", "minecraft:llama_spawn_egg"),
("minecraft:magma_cube", "minecraft:magma_cube_spawn_egg"),
("minecraft:mooshroom", "minecraft:mooshroom_spawn_egg"),
("minecraft:mule", "minecraft:mule_spawn_egg"),
("minecraft:ocelot", "minecraft:ocelot_spawn_egg"),
("minecraft:pufferfish", "minecraft:pufferfish_spawn_egg"),
("minecraft:parrot", "minecraft:parrot_spawn_egg"),
("minecraft:pig", "minecraft:pig_spawn_egg"),
("minecraft:polar_bear", "minecraft:polar_bear_spawn_egg"),
("minecraft:rabbit", "minecraft:rabbit_spawn_egg"),
("minecraft:sheep", "minecraft:sheep_spawn_egg"),
("minecraft:shulker", "minecraft:shulker_spawn_egg"),
("minecraft:silverfish", "minecraft:silverfish_spawn_egg"),
("minecraft:skeleton", "minecraft:skeleton_spawn_egg"),
(
"minecraft:skeleton_horse",
"minecraft:skeleton_horse_spawn_egg",
),
("minecraft:slime", "minecraft:slime_spawn_egg"),
("minecraft:snow_golem", "minecraft:snow_golem_spawn_egg"),
("minecraft:spider", "minecraft:spider_spawn_egg"),
("minecraft:squid", "minecraft:squid_spawn_egg"),
("minecraft:stray", "minecraft:stray_spawn_egg"),
("minecraft:turtle", "minecraft:turtle_spawn_egg"),
("minecraft:vex", "minecraft:vex_spawn_egg"),
("minecraft:villager", "minecraft:villager_spawn_egg"),
(
"minecraft:vindication_illager",
"minecraft:vindication_illager_spawn_egg",
),
("minecraft:witch", "minecraft:witch_spawn_egg"),
("minecraft:wither", "minecraft:wither_spawn_egg"),
(
"minecraft:wither_skeleton",
"minecraft:wither_skeleton_spawn_egg",
),
("minecraft:wolf", "minecraft:wolf_spawn_egg"),
("minecraft:zombie", "minecraft:zombie_spawn_egg"),
("minecraft:zombie_horse", "minecraft:zombie_horse_spawn_egg"),
(
"minecraft:zombie_pigman",
"minecraft:zombie_pigman_spawn_egg",
),
(
"minecraft:zombie_villager",
"minecraft:zombie_villager_spawn_egg",
),
];
// ------------------------------------------------------------------ 3322
const POTION_ITEMS: [&str; 4] = [
"minecraft:potion",
"minecraft:splash_potion",
"minecraft:lingering_potion",
"minecraft:tipped_arrow",
];
/// `EffectDurationFix.fix`: every effect's factor data counts ticks active.
fn effect_list(list: Tag) -> Tag {
if !is_list(Some(&list)) {
return list;
}
Tag::List(
stream(Some(&list))
.into_iter()
.map(|mut effect| {
let duration = super::dynamic::as_int(effect.get("Duration"), -1);
update(&mut effect, "FactorCalculationData", |mut data| {
let timestamp =
super::dynamic::as_int(data.get("effect_changed_timestamp"), -1);
remove(&mut data, "effect_changed_timestamp");
set(
&mut data,
"ticks_active",
Tag::Int(timestamp.wrapping_sub(duration)),
);
data
});
effect
})
.collect(),
)
}
fn effect_duration(cx: &mut Cx) {
let living = |e: &mut Tag| {
for field in ["Effects", "ActiveEffects", "CustomPotionEffects"] {
update(e, field, effect_list);
}
};
cx.each(Ty::Entity, living);
cx.each(Ty::Player, living);
item_tag(
cx,
|id| POTION_ITEMS.contains(&id),
|tag| update(tag, "CustomPotionEffects", effect_list),
);
}
// ------------------------------------------------------------------ 3438, 3447
const POTTERY_SHARDS: &[(&str, &str)] = &[
(
"minecraft:pottery_shard_archer",
"minecraft:archer_pottery_shard",
),
(
"minecraft:pottery_shard_prize",
"minecraft:prize_pottery_shard",
),
(
"minecraft:pottery_shard_arms_up",
"minecraft:arms_up_pottery_shard",
),
(
"minecraft:pottery_shard_skull",
"minecraft:skull_pottery_shard",
),
];
const POTTERY_SHERDS: &[(&str, &str)] = &[
(
"minecraft:angler_pottery_shard",
"minecraft:angler_pottery_sherd",
),
(
"minecraft:archer_pottery_shard",
"minecraft:archer_pottery_sherd",
),
(
"minecraft:arms_up_pottery_shard",
"minecraft:arms_up_pottery_sherd",
),
(
"minecraft:blade_pottery_shard",
"minecraft:blade_pottery_sherd",
),
(
"minecraft:brewer_pottery_shard",
"minecraft:brewer_pottery_sherd",
),
(
"minecraft:burn_pottery_shard",
"minecraft:burn_pottery_sherd",
),
(
"minecraft:danger_pottery_shard",
"minecraft:danger_pottery_sherd",
),
(
"minecraft:explorer_pottery_shard",
"minecraft:explorer_pottery_sherd",
),
(
"minecraft:friend_pottery_shard",
"minecraft:friend_pottery_sherd",
),
(
"minecraft:heart_pottery_shard",
"minecraft:heart_pottery_sherd",
),
(
"minecraft:heartbreak_pottery_shard",
"minecraft:heartbreak_pottery_sherd",
),
(
"minecraft:howl_pottery_shard",
"minecraft:howl_pottery_sherd",
),
(
"minecraft:miner_pottery_shard",
"minecraft:miner_pottery_sherd",
),
(
"minecraft:mourner_pottery_shard",
"minecraft:mourner_pottery_sherd",
),
(
"minecraft:plenty_pottery_shard",
"minecraft:plenty_pottery_sherd",
),
(
"minecraft:prize_pottery_shard",
"minecraft:prize_pottery_sherd",
),
(
"minecraft:sheaf_pottery_shard",
"minecraft:sheaf_pottery_sherd",
),
(
"minecraft:shelter_pottery_shard",
"minecraft:shelter_pottery_sherd",
),
(
"minecraft:skull_pottery_shard",
"minecraft:skull_pottery_sherd",
),
(
"minecraft:snort_pottery_shard",
"minecraft:snort_pottery_sherd",
),
];
// ------------------------------------------------------------------ 3439
/// `LegacyComponentDataFixUtils.createEmptyComponent`.
fn empty_component() -> Tag {
string("{\"text\":\"\"}")
}
/// `BlockEntitySignDoubleSidedEditableTextFix` (a `NamedEntityWriteReadFix`).
fn sign_double_sided(cx: &mut Cx, id: &str) {
let k = cx.k;
cx.block_entity(id, |be| {
let lines: Vec<Tag> = (1..=4)
.map(|i| {
be.get(&format!("Text{i}"))
.cloned()
.unwrap_or_else(empty_component)
})
.collect();
let filtered: Vec<Option<Tag>> = (1..=4)
.map(|i| be.get(&format!("FilteredText{i}")).cloned())
.collect();
let mut front = Compound::new();
front.insert("messages".into(), Tag::List(lines.clone()));
front.insert(
"color".into(),
be.get("Color").cloned().unwrap_or_else(|| string("black")),
);
front.insert(
"has_glowing_text".into(),
be.get("GlowingText").cloned().unwrap_or(Tag::Byte(0)),
);
if filtered.iter().any(Option::is_some) {
let messages = filtered
.into_iter()
.zip(&lines)
.map(|(f, line)| f.unwrap_or_else(|| line.clone()))
.collect();
front.insert("filtered_messages".into(), Tag::List(messages));
}
set(be, "front_text", Tag::Compound(front));
let back = Tag::compound([
("messages", Tag::List(vec![empty_component(); 4])),
("color", string("black")),
("has_glowing_text", Tag::Byte(0)),
]);
set(be, "back_text", back);
set(be, "is_waxed", Tag::Byte(0));
set(be, "_filtered_correct", Tag::Byte(1));
for field in super::fixes_a::SIGN_FIELDS_TO_DROP {
remove(be, field);
}
reread_as(Ty::BlockEntity, k, be);
});
}
// ------------------------------------------------------------------ 3440
/// `NamespacedTypeRenameFix` over `MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST`: the
/// preset of a multi-noise biome source in the world generation settings.
fn multi_noise_preset(cx: &mut Cx) {
cx.each(Ty::WorldGenSettings, |v| {
let Some(Tag::Compound(dims)) = v.get_mut("dimensions") else {
return;
};
for dim in dims.values_mut() {
let Some(g) = dim.get_mut("generator") else {
continue;
};
if as_str(g.get("type")).as_deref() != Some("minecraft:noise") {
continue;
}
let Some(source) = g.get_mut("biome_source") else {
continue;
};
if as_str(source.get("type")).as_deref() != Some("minecraft:multi_noise") {
continue;
}
if let Some(preset) = as_str(source.get("preset"))
&& namespaced(&preset) == "minecraft:overworld_update_1_20"
{
set(source, "preset", string("minecraft:overworld"));
}
}
});
}
// ------------------------------------------------------------------ 3450, 3459
/// `RemapChunkStatusFix`: statuses namespaced, then mapped.
fn remap_chunk_status(cx: &mut Cx) {
let fix = |v: Tag| match as_str(Some(&v)) {
Some(s) => {
let s = namespaced(&s);
string(match s.as_str() {
"minecraft:liquid_carvers" => "minecraft:carvers",
"minecraft:heightmaps" => "minecraft:spawn",
other => other,
})
}
None => v,
};
cx.each(Ty::Chunk, |c| {
update(c, "Status", fix);
if let Some(retrogen) = c.get_mut("below_zero_retrogen") {
update(retrogen, "target_status", fix);
}
});
}
/// `LegacyDragonFightFix`.
fn legacy_dragon_fight(cx: &mut Cx) {
cx.each(Ty::Level, |level| {
if level.get("DragonFight").is_some() {
return;
}
let legacy = level
.get("DimensionData")
.and_then(|d| d.get("1"))
.and_then(|d| d.get("DragonFight"))
.cloned()
.unwrap_or_else(super::dynamic::empty_map);
let mut fight = legacy;
update(&mut fight, "ExitPortalLocation", fix_block_pos);
set(level, "DragonFight", fight);
});
}
File diff suppressed because it is too large Load Diff
+644
View File
@@ -0,0 +1,644 @@
//! The JSON that DataFixers read and write: Gson's `JsonReader` in strict and
//! lenient mode, `GsonHelper.toStableString`, and `JsonOps.convertTo` into NBT.
//! Strings stay UTF-16 like Java's; numbers keep their literal like Gson's
//! `LazilyParsedNumber`.
use crate::nbt::{Compound, JavaString, Tag};
#[derive(Clone, Debug, PartialEq)]
pub enum Json {
Null,
Bool(bool),
/// The literal as written (`LazilyParsedNumber`) or `Number.toString`.
Num(String),
Str(Vec<u16>),
Arr(Vec<Json>),
/// Insertion order, a repeated key replacing the value in place.
Obj(Vec<(Vec<u16>, Json)>),
}
impl Json {
pub fn get(&self, key: &str) -> Option<&Json> {
let key: Vec<u16> = key.encode_utf16().collect();
match self {
Json::Obj(entries) => entries.iter().find(|(k, _)| *k == key).map(|(_, v)| v),
_ => None,
}
}
fn insert(entries: &mut Vec<(Vec<u16>, Json)>, key: Vec<u16>, value: Json) {
if let Some(e) = entries.iter_mut().find(|(k, _)| *k == key) {
e.1 = value;
} else {
entries.push((key, value));
}
}
pub fn object(entries: Vec<(&str, Json)>) -> Json {
let mut out = Vec::new();
for (k, v) in entries {
Json::insert(&mut out, k.encode_utf16().collect(), v);
}
Json::Obj(out)
}
pub fn string(s: &str) -> Json {
Json::Str(s.encode_utf16().collect())
}
}
#[derive(Clone, Copy, PartialEq)]
enum Mode {
Strict,
Lenient,
}
struct Reader<'a> {
s: &'a [u16],
pos: usize,
mode: Mode,
}
type R<T> = Result<T, ()>;
const fn u(c: char) -> u16 {
c as u16
}
impl Reader<'_> {
fn lenient(&self) -> bool {
self.mode == Mode::Lenient
}
fn peek_char(&self) -> Option<u16> {
self.s.get(self.pos).copied()
}
/// `JsonReader.nextNonWhitespace`, with comments when lenient.
fn skip_ws(&mut self) -> R<Option<u16>> {
loop {
let Some(c) = self.peek_char() else {
return Ok(None);
};
match c {
0x20 | 0x0A | 0x09 | 0x0D => self.pos += 1,
0x2F if self.s.get(self.pos + 1) == Some(&u('*'))
|| self.s.get(self.pos + 1) == Some(&u('/')) =>
{
if !self.lenient() {
return Err(());
}
if self.s[self.pos + 1] == u('*') {
let start = self.pos + 2;
let end = (start..self.s.len().saturating_sub(1))
.find(|&i| self.s[i] == u('*') && self.s[i + 1] == u('/'))
.ok_or(())?;
self.pos = end + 2;
} else {
self.skip_line();
}
}
0x23 => {
if !self.lenient() {
return Err(());
}
self.skip_line();
}
_ => return Ok(Some(c)),
}
}
}
fn skip_line(&mut self) {
while let Some(c) = self.peek_char() {
self.pos += 1;
if c == 0x0A || c == 0x0D {
break;
}
}
}
fn value(&mut self, depth: usize) -> R<Json> {
if depth > 255 {
return Err(());
}
let c = self.skip_ws()?.ok_or(())?;
match c {
0x7B => self.object(depth),
0x5B => self.array(depth),
0x22 => {
self.pos += 1;
Ok(Json::Str(self.quoted(0x22)?))
}
0x27 => {
if !self.lenient() {
return Err(());
}
self.pos += 1;
Ok(Json::Str(self.quoted(0x27)?))
}
_ => self.literal(),
}
}
fn object(&mut self, depth: usize) -> R<Json> {
self.pos += 1;
let mut entries = Vec::new();
if self.skip_ws()? == Some(u('}')) {
self.pos += 1;
return Ok(Json::Obj(entries));
}
loop {
let c = self.skip_ws()?.ok_or(())?;
let name = match c {
0x22 => {
self.pos += 1;
self.quoted(0x22)?
}
0x27 if self.lenient() => {
self.pos += 1;
self.quoted(0x27)?
}
_ if self.lenient() => {
let lit = self.unquoted();
if lit.is_empty() {
return Err(());
}
lit
}
_ => return Err(()),
};
match self.skip_ws()?.ok_or(())? {
0x3A => self.pos += 1,
0x3D if self.lenient() => {
self.pos += 1;
if self.peek_char() == Some(u('>')) {
self.pos += 1;
}
}
_ => return Err(()),
}
let value = self.value(depth + 1)?;
Json::insert(&mut entries, name, value);
match self.skip_ws()?.ok_or(())? {
0x7D => {
self.pos += 1;
return Ok(Json::Obj(entries));
}
0x2C => self.pos += 1,
0x3B if self.lenient() => self.pos += 1,
_ => return Err(()),
}
}
}
fn array(&mut self, depth: usize) -> R<Json> {
self.pos += 1;
let mut out = Vec::new();
if self.skip_ws()? == Some(u(']')) {
self.pos += 1;
return Ok(Json::Arr(out));
}
loop {
let c = self.skip_ws()?.ok_or(())?;
// Lenient: an empty element between separators is a null.
if self.lenient() && (c == u(',') || c == u(';')) {
out.push(Json::Null);
self.pos += 1;
continue;
}
if self.lenient() && c == u(']') {
out.push(Json::Null);
self.pos += 1;
return Ok(Json::Arr(out));
}
out.push(self.value(depth + 1)?);
match self.skip_ws()?.ok_or(())? {
0x5D => {
self.pos += 1;
return Ok(Json::Arr(out));
}
0x2C => self.pos += 1,
0x3B if self.lenient() => self.pos += 1,
_ => return Err(()),
}
}
}
fn quoted(&mut self, quote: u16) -> R<Vec<u16>> {
let mut out = Vec::new();
loop {
let c = self.peek_char().ok_or(())?;
self.pos += 1;
if c == quote {
return Ok(out);
}
if c == u('\\') {
let e = self.peek_char().ok_or(())?;
self.pos += 1;
match e {
0x75 => {
let hex = self.s.get(self.pos..self.pos + 4).ok_or(())?;
let text = String::from_utf16(hex).map_err(|_| ())?;
out.push(u16::from_str_radix(&text, 16).map_err(|_| ())?);
self.pos += 4;
}
0x74 => out.push(u('\t')),
0x62 => out.push(0x08),
0x6E => out.push(u('\n')),
0x72 => out.push(u('\r')),
0x66 => out.push(0x0C),
0x0A | 0x22 | 0x5C | 0x2F => out.push(e),
0x27 => out.push(e),
_ if self.lenient() => out.push(e),
_ => return Err(()),
}
} else {
if !self.lenient() && c < 0x20 {
return Err(());
}
out.push(c);
}
}
}
fn unquoted(&mut self) -> Vec<u16> {
let start = self.pos;
while let Some(c) = self.peek_char() {
if matches!(
c,
0x2F | 0x5C
| 0x3B
| 0x23
| 0x3D
| 0x7B
| 0x7D
| 0x5B
| 0x5D
| 0x3A
| 0x2C
| 0x20
| 0x09
| 0x0C
| 0x0D
| 0x0A
) {
break;
}
self.pos += 1;
}
self.s[start..self.pos].to_vec()
}
/// A keyword, a number, or (lenient) an unquoted string.
fn literal(&mut self) -> R<Json> {
let lit = self.unquoted();
if lit.is_empty() {
return Err(());
}
let text = String::from_utf16_lossy(&lit);
for (word, value) in [
("true", Json::Bool(true)),
("false", Json::Bool(false)),
("null", Json::Null),
] {
if text.len() == word.len()
&& text
.chars()
.zip(word.chars())
.all(|(a, b)| a == b || self.lenient() && a == b.to_ascii_uppercase())
{
return Ok(value);
}
}
if is_json_number(&text) {
return Ok(Json::Num(text));
}
if self.lenient() {
return Ok(Json::Str(lit));
}
Err(())
}
}
/// `JsonReader.peekNumber`.
fn is_json_number(s: &str) -> bool {
let b = s.as_bytes();
let mut i = 0;
if b.get(i) == Some(&b'-') {
i += 1;
}
match b.get(i) {
Some(b'0') => {
i += 1;
if b.get(i).is_some_and(u8::is_ascii_digit) {
return false;
}
}
Some(c) if c.is_ascii_digit() => {
while b.get(i).is_some_and(u8::is_ascii_digit) {
i += 1;
}
}
_ => return false,
}
if b.get(i) == Some(&b'.') {
i += 1;
if !b.get(i).is_some_and(u8::is_ascii_digit) {
return false;
}
while b.get(i).is_some_and(u8::is_ascii_digit) {
i += 1;
}
}
if matches!(b.get(i), Some(b'e' | b'E')) {
i += 1;
if matches!(b.get(i), Some(b'+' | b'-')) {
i += 1;
}
if !b.get(i).is_some_and(u8::is_ascii_digit) {
return false;
}
while b.get(i).is_some_and(u8::is_ascii_digit) {
i += 1;
}
}
i == b.len()
}
fn parse_mode(s: &[u16], mode: Mode) -> Option<Json> {
let mut r = Reader { s, pos: 0, mode };
let value = r.value(0).ok()?;
// JsonParser.parseReader: the whole document must be consumed.
if r.skip_ws().ok()?.is_some() {
if mode == Mode::Lenient && value == Json::Null {
return Some(value);
}
return None;
}
Some(value)
}
/// `LenientJsonParser.parse` (Gson `JsonParser.parseString`).
pub fn parse_lenient(s: &[u16]) -> Option<Json> {
parse_mode(s, Mode::Lenient)
}
/// `StrictJsonParser.parse`.
pub fn parse_strict(s: &[u16]) -> Option<Json> {
parse_mode(s, Mode::Strict)
}
/// `GsonHelper.toStableString`: keys in natural (UTF-16) order, Gson escaping.
pub fn to_stable_string(json: &Json) -> Vec<u16> {
let mut out = Vec::new();
write(json, &mut out);
out
}
fn write(json: &Json, out: &mut Vec<u16>) {
let push = |out: &mut Vec<u16>, s: &str| out.extend(s.encode_utf16());
match json {
Json::Null => push(out, "null"),
Json::Bool(b) => push(out, if *b { "true" } else { "false" }),
Json::Num(n) => push(out, n),
Json::Str(s) => write_string(s, out),
Json::Arr(items) => {
out.push(u('['));
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push(u(','));
}
write(item, out);
}
out.push(u(']'));
}
Json::Obj(entries) => {
let mut sorted: Vec<&(Vec<u16>, Json)> = entries.iter().collect();
sorted.sort_by(|a, b| a.0.cmp(&b.0));
out.push(u('{'));
for (i, (k, v)) in sorted.into_iter().enumerate() {
if i > 0 {
out.push(u(','));
}
write_string(k, out);
out.push(u(':'));
write(v, out);
}
out.push(u('}'));
}
}
}
/// `JsonWriter.string` without HTML escaping.
fn write_string(s: &[u16], out: &mut Vec<u16>) {
out.push(u('"'));
for &c in s {
match c {
0x22 => out.extend("\\\"".encode_utf16()),
0x5C => out.extend("\\\\".encode_utf16()),
0x09 => out.extend("\\t".encode_utf16()),
0x08 => out.extend("\\b".encode_utf16()),
0x0A => out.extend("\\n".encode_utf16()),
0x0D => out.extend("\\r".encode_utf16()),
0x0C => out.extend("\\f".encode_utf16()),
c if c < 0x20 || c == 0x2028 || c == 0x2029 => {
out.extend(format!("\\u{c:04x}").encode_utf16());
}
c => out.push(c),
}
}
out.push(u('"'));
}
/// `JsonOps.convertTo(NbtOps)`. Nulls give `None` (an end tag in Java).
pub fn to_nbt(json: &Json) -> Option<Tag> {
Some(match json {
Json::Null => return None,
Json::Bool(b) => Tag::Byte(i8::from(*b)),
Json::Str(s) => Tag::String(JavaString(s.clone())),
Json::Num(n) => number_to_nbt(n),
Json::Arr(items) => Tag::List(items.iter().filter_map(to_nbt).collect()),
Json::Obj(entries) => {
let mut c = Compound::new();
for (k, v) in entries {
if let Some(v) = to_nbt(v) {
c.insert(JavaString(k.clone()), v);
}
}
Tag::Compound(c)
}
})
}
/// `JsonOps.convertTo` for a number: the smallest integer tag that holds an
/// exact integral value, else float when exact, else double.
fn number_to_nbt(literal: &str) -> Tag {
if let Some(l) = exact_long(literal) {
if let Ok(b) = i8::try_from(l) {
return Tag::Byte(b);
}
if let Ok(s) = i16::try_from(l) {
return Tag::Short(s);
}
if let Ok(i) = i32::try_from(l) {
return Tag::Int(i);
}
return Tag::Long(l);
}
let d: f64 = literal.parse().unwrap_or(0.0);
let f = d as f32;
if f64::from(f) == d {
Tag::Float(f.to_bits())
} else {
Tag::Double(d.to_bits())
}
}
/// `BigDecimal.longValueExact` of a JSON number literal.
fn exact_long(literal: &str) -> Option<i64> {
let (mantissa, exponent) = match literal.find(['e', 'E']) {
Some(i) => (&literal[..i], literal[i + 1..].parse::<i64>().ok()?),
None => (literal, 0),
};
let negative = mantissa.starts_with('-');
let mantissa = mantissa.trim_start_matches('-');
let (int_part, frac) = match mantissa.find('.') {
Some(i) => (&mantissa[..i], &mantissa[i + 1..]),
None => (mantissa, ""),
};
let mut digits: String = format!("{int_part}{frac}");
let mut scale = frac.len() as i64 - exponent;
// Trailing zeros of the unscaled value do not change the value.
while scale > 0 && digits.ends_with('0') {
digits.pop();
scale -= 1;
}
if scale > 0 {
return None;
}
let digits = digits.trim_start_matches('0');
if digits.is_empty() {
return Some(0);
}
if digits.len() as i64 - scale > 19 {
return None;
}
let mut value: i128 = digits.parse().ok()?;
for _ in 0..-scale {
value = value.checked_mul(10)?;
}
let value = if negative { -value } else { value };
i64::try_from(value).ok()
}
/// `NbtOps.convertTo(JsonOps)`.
pub fn from_nbt(tag: &Tag) -> Json {
match tag {
Tag::End => Json::Null,
Tag::Byte(v) => Json::Num(v.to_string()),
Tag::Short(v) => Json::Num(v.to_string()),
Tag::Int(v) => Json::Num(v.to_string()),
Tag::Long(v) => Json::Num(v.to_string()),
Tag::Float(v) => Json::Num(java_float_string(f32::from_bits(*v))),
Tag::Double(v) => Json::Num(java_double_string(f64::from_bits(*v))),
Tag::ByteArray(v) => Json::Arr(
v.iter()
.map(|b| Json::Num((*b as i8).to_string()))
.collect(),
),
Tag::IntArray(v) => Json::Arr(v.iter().map(|i| Json::Num(i.to_string())).collect()),
Tag::LongArray(v) => Json::Arr(v.iter().map(|l| Json::Num(l.to_string())).collect()),
Tag::String(s) => Json::Str(s.0.clone()),
Tag::List(items) => Json::Arr(items.iter().map(from_nbt).collect()),
Tag::Compound(c) => Json::Obj(c.iter().map(|(k, v)| (k.0.clone(), from_nbt(v))).collect()),
}
}
/// Java `Double.toString`.
pub fn java_double_string(d: f64) -> String {
java_fp_string(d, format!("{d:e}"))
}
/// Java `Float.toString`.
pub fn java_float_string(f: f32) -> String {
java_fp_string(f64::from(f), format!("{f:e}"))
}
fn java_fp_string(d: f64, sci: String) -> String {
if d.is_nan() {
return "NaN".into();
}
if d.is_infinite() {
return if d > 0.0 { "Infinity" } else { "-Infinity" }.into();
}
if d == 0.0 {
return if d.is_sign_negative() { "-0.0" } else { "0.0" }.into();
}
// `sci` is Rust's shortest round-trip form: d.ddde<exp>.
let (mantissa, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
let exp: i32 = exp.parse().unwrap_or(0);
let negative = mantissa.starts_with('-');
let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
let sign = if negative { "-" } else { "" };
let a = d.abs();
if (1e-3..1e7).contains(&a) {
if exp >= 0 {
let e = exp as usize;
let (int, frac) = if digits.len() > e + 1 {
(digits[..=e].to_string(), digits[e + 1..].to_string())
} else {
(format!("{digits:0<width$}", width = e + 1), String::new())
};
let frac = if frac.is_empty() { "0".into() } else { frac };
format!("{sign}{int}.{frac}")
} else {
let zeros = "0".repeat((-exp - 1) as usize);
format!("{sign}0.{zeros}{digits}")
}
} else {
let (first, rest) = digits.split_at(1);
let rest = if rest.is_empty() { "0" } else { rest };
format!("{sign}{first}.{rest}E{exp}")
}
}
/// A string value as a JSON text component (`{"text": s}`), stable string.
pub fn text_component_json(text: &[u16]) -> Vec<u16> {
to_stable_string(&Json::Obj(vec![(
"text".encode_utf16().collect(),
Json::Str(text.to_vec()),
)]))
}
pub fn translatable_component_json(key: &str) -> Vec<u16> {
to_stable_string(&Json::object(vec![("translate", Json::string(key))]))
}
#[cfg(test)]
mod tests {
use super::*;
fn w(s: &str) -> Vec<u16> {
s.encode_utf16().collect()
}
#[test]
fn numbers_become_the_smallest_tag() {
let tag = |s: &str| to_nbt(&parse_strict(&w(s)).unwrap()).unwrap();
assert_eq!(tag("1"), Tag::Byte(1));
assert_eq!(tag("1.0"), Tag::Byte(1));
assert_eq!(tag("1e2"), Tag::Byte(100));
assert_eq!(tag("300"), Tag::Short(300));
assert_eq!(tag("1.5"), Tag::Float(1.5f32.to_bits()));
assert_eq!(tag("0.1"), Tag::Double(0.1f64.to_bits()));
assert_eq!(tag("3000000000"), Tag::Long(3_000_000_000));
}
#[test]
fn lenient_reads_what_strict_refuses() {
assert!(parse_strict(&w("hello")).is_none());
assert_eq!(parse_lenient(&w("hello")), Some(Json::string("hello")));
assert!(parse_lenient(&w("hello world")).is_none());
assert_eq!(
parse_lenient(&w("{a:'b'}")),
Some(Json::object(vec![("a", Json::string("b"))]))
);
}
#[test]
fn stable_strings_sort_keys() {
let j = parse_strict(&w(r#"{"text":"a","color":"red"}"#)).unwrap();
assert_eq!(
String::from_utf16(&to_stable_string(&j)).unwrap(),
r#"{"color":"red","text":"a"}"#
);
}
#[test]
fn java_floating_point_strings() {
assert_eq!(java_double_string(1.0), "1.0");
assert_eq!(java_double_string(0.001), "0.001");
assert_eq!(java_double_string(1e7), "1.0E7");
assert_eq!(java_double_string(123456.789), "123456.789");
assert_eq!(java_double_string(1e-4), "1.0E-4");
assert_eq!(java_float_string(0.1), "0.1");
assert_eq!(java_float_string(1.5e10), "1.5E10");
}
}
+299
View File
@@ -0,0 +1,299 @@
//! Vanilla's DataFixers from the 1.19 schemas on (`net.minecraft.util.datafix`):
//! the data of worlds saved by 1.18.2 to 26.2 brought to the 26.3 format exactly
//! as 26.3 does when it reads them, and the file fixes it runs when it opens
//! such a world (`net.minecraft.util.filefix`).
//!
//! DataFixerUpper reads the data once with the schema of its version (running
//! the schema's read hooks), applies every fix with a key above that version
//! in order, and writes it with the current schema. Each fix finds its values
//! with the schema just below its own key ([`schema`]). Data older than
//! [`OLDEST_SUPPORTED`] needs fixes that are not ported. The fixes of client
//! files (options, hotbars, debug profiles) are not ported either.
pub mod dynamic;
pub mod files;
mod fixes_a;
mod fixes_b;
mod fixes_c;
mod fixes_old;
mod items;
pub mod json;
pub mod schema;
mod text;
use crate::nbt::Tag;
use dynamic::{as_str, string};
use schema::{Key, Ty, key, walk};
/// The DataVersion of the game.
pub const CURRENT: i32 = crate::DATA_VERSION;
/// Data saved before this DataVersion (1.18.2 is 2975) needs fixes that are not
/// ported (2967 and 2970, and everything before).
pub const OLDEST_SUPPORTED: i32 = 2970;
/// `Identifier.tryParse` validity, as `NamespacedSchema.ensureNamespaced` uses it.
pub fn identifier(id: &str) -> Option<(String, String)> {
let (ns, path) = match id.split_once(':') {
Some((ns, path)) => (if ns.is_empty() { "minecraft" } else { ns }, path),
None => ("minecraft", id),
};
let ns_ok = ns
.bytes()
.all(|c| matches!(c, b'a'..=b'z' | b'0'..=b'9' | b'_' | b'-' | b'.'));
let path_ok = path
.bytes()
.all(|c| matches!(c, b'a'..=b'z' | b'0'..=b'9' | b'_' | b'-' | b'.' | b'/'));
(ns_ok && path_ok).then(|| (ns.to_owned(), path.to_owned()))
}
/// What a fix works on: the root value, its type and the fix's key.
pub struct Cx<'a> {
root: Ty,
data: &'a mut Tag,
k: Key,
}
impl Cx<'_> {
/// Every value of `ty`, read with the fix's input schema.
pub fn each(&mut self, ty: Ty, mut f: impl FnMut(&mut Tag)) {
walk(self.root, self.data, self.k - 1, ty, &mut f);
}
/// Every value of `ty` read with the fix's output schema (fixes declared
/// on `getOutputSchema().getType(...)`).
pub fn each_out(&mut self, ty: Ty, mut f: impl FnMut(&mut Tag)) {
walk(self.root, self.data, self.k, ty, &mut f);
}
/// Every entity of one type (`NamedEntityFix` and friends).
pub fn entity(&mut self, id: &str, mut f: impl FnMut(&mut Tag)) {
self.each(Ty::Entity, |e| {
if id_is(e, id) {
f(e);
}
});
}
/// Every block entity of one type.
pub fn block_entity(&mut self, id: &str, mut f: impl FnMut(&mut Tag)) {
self.each(Ty::BlockEntity, |e| {
if id_is(e, id) {
f(e);
}
});
}
/// Every item stack whose id passes `filter`.
pub fn item(&mut self, filter: impl Fn(&str) -> bool, mut f: impl FnMut(&mut Tag)) {
self.each(Ty::ItemStack, |s| {
if let Some(id) = as_str(s.get("id"))
&& filter(&dynamic::namespaced(&id))
{
f(s);
}
});
}
/// A name type renamed in place (`fixTypeEverywhere` over a namespaced string).
pub fn rename(&mut self, ty: Ty, rename: impl Fn(&str) -> Option<&'static str>) {
self.each(ty, |v| {
if let Some(name) = as_str(Some(v))
&& let Some(new) = rename(&name)
{
*v = string(new);
}
});
}
}
/// DataFixerUpper reads a record's typed fields from its map without taking
/// them out: the record's remainder keeps the whole map it was read from, and
/// writing lays the typed fields over it. A typed field that a fix drops (by
/// casting to a type without it) therefore comes back on write with its value
/// from that read. Each entity keeps that map under this key while fixes run.
pub(crate) const LAST_READ: &str = "\u{0}last_read";
/// Remember a record's current fields as the map it was read from.
pub fn mark_read(e: &mut Tag) {
if let Tag::Compound(_) = e {
let mut raw = e.clone();
strip_last_read(&mut raw);
dynamic::set(e, LAST_READ, raw);
}
}
/// `Util.writeAndReadTypedOrThrow` over an entity by the fix with key `k`: it is
/// written and read again with the output schema, so it (and every entity inside
/// it) now remembers its current fields as the map it was last read from.
pub fn reread(k: Key, e: &mut Tag) {
reread_as(Ty::Entity, k, e);
}
/// [`reread`] for a value of another type (a block entity).
pub fn reread_as(ty: Ty, k: Key, v: &mut Tag) {
walk(ty, v, k, Ty::BlockEntity, &mut mark_read);
walk(ty, v, k, Ty::Entity, &mut mark_read);
}
/// A typed field dropped from an entity: what writing the entity gives back for
/// it (its value in the map the entity was last read from, if any).
pub fn drop_typed(e: &mut Tag, field: &str) {
match e.get(LAST_READ).and_then(|raw| raw.get(field)).cloned() {
Some(raw) => dynamic::set(e, field, raw),
None => {
dynamic::remove(e, field);
}
}
}
fn strip_last_read(v: &mut Tag) {
match v {
Tag::Compound(c) => {
c.remove(&dynamic::key(LAST_READ));
for value in c.values_mut() {
strip_last_read(value);
}
}
Tag::List(items) => items.iter_mut().for_each(strip_last_read),
_ => {}
}
}
/// The entity or block entity `id` field, namespaced.
pub fn id_is(v: &Tag, id: &str) -> bool {
as_str(v.get("id")).is_some_and(|s| dynamic::namespaced(&s) == id)
}
/// `createRenamer`: the id namespaced, looked up in a table.
pub fn renamer<'a>(
table: &'a [(&'a str, &'static str)],
) -> impl Fn(&str) -> Option<&'static str> + 'a {
move |id: &str| {
let id = dynamic::namespaced(id);
table
.iter()
.find(|(from, _)| *from == id)
.map(|(_, to)| *to)
}
}
type FixFn = fn(&mut Cx);
/// Every ported fix (from the 1.19 schemas on), in DataFixers order.
fn fixes() -> Vec<(Key, FixFn)> {
let mut out = Vec::new();
fixes_old::register(&mut out);
fixes_a::register(&mut out);
fixes_b::register(&mut out);
fixes_c::register(&mut out);
out
}
/// `DataFixer.update(type, data, from, to)` for a root value.
pub fn update(root: Ty, data: &mut Tag, from: i32, to: i32) {
if from >= to {
return;
}
let from_key = key(from.max(0) as u32, 0);
let to_version = to as u32;
// The data is read once with the schema of its version (its read hooks)...
walk(root, data, from_key, Ty::BlockEntity, &mut mark_read);
walk(root, data, from_key, Ty::Entity, &mut mark_read);
read_hooks(root, data, from_key);
// ...then every fix above that key, up to the target version...
for (k, fix) in fixes() {
if k > from_key && k / 10 <= to_version {
fix(&mut Cx { root, data, k });
}
}
// ...and written with the target schema (its write hooks).
write_hooks(root, data, key(to_version, 9));
strip_last_read(data);
}
/// The read hooks of the schema the data was saved with.
fn read_hooks(root: Ty, data: &mut Tag, k: Key) {
walk(root, data, k, Ty::ItemStack, &mut |stack| {
if k < key(3818, 5) {
items::add_names(stack);
} else if let Tag::String(_) = stack {
// V3818_5 UNPACK_PLAIN_ID: a bare item id is a stack of one.
*stack = Tag::compound([("id", stack.clone()), ("count", Tag::Int(1))]);
}
});
walk(root, data, k, Ty::Objective, &mut fixes_a::unpack_objective);
}
fn write_hooks(root: Ty, data: &mut Tag, k: Key) {
walk(root, data, k, Ty::Objective, &mut fixes_a::repack_objective);
}
/// `SimpleRegionStorage.upgradeChunkTag` for a region chunk (`ChunkMap`):
/// the dimension and generator are passed to the fixes as `__context`.
pub fn update_chunk(tag: &mut Tag, dimension: &str, generator: Option<&str>) {
let version = dynamic::as_int(tag.get("DataVersion"), -1);
if version >= CURRENT {
return;
}
let mut context = Tag::compound([("dimension", string(dimension))]);
if let Some(g) = generator {
dynamic::set(&mut context, "generator", string(g));
}
dynamic::set(tag, "__context", context);
update(Ty::Chunk, tag, version, CURRENT);
dynamic::remove(tag, "__context");
dynamic::set(tag, "DataVersion", Tag::Int(CURRENT));
}
/// `SimpleRegionStorage.upgradeChunkTag` for entity chunks (default version -1)
/// and POI chunks (default 1945).
pub fn update_region_tag(root: Ty, tag: &mut Tag) {
let default = if root == Ty::PoiChunk { 1945 } else { -1 };
let version = dynamic::as_int(tag.get("DataVersion"), default);
if version >= CURRENT {
return;
}
update(root, tag, version, CURRENT);
dynamic::set(tag, "DataVersion", Tag::Int(CURRENT));
}
/// `PlayerDataStorage.load`: the DataVersion field stays as loaded.
pub fn update_player(tag: &mut Tag) {
let version = dynamic::as_int(tag.get("DataVersion"), -1);
update(Ty::Player, tag, version, CURRENT);
}
/// The saved data type of a file below a `data` folder (`namespace/path.dat`).
pub fn saved_data_type(relative: &str) -> Option<Ty> {
let name = relative.strip_suffix(".dat").unwrap_or(relative);
if name.ends_with("/command_storage") {
return Some(Ty::SavedCommandStorage);
}
if let Some(n) = name.strip_prefix("minecraft/maps/")
&& !n.is_empty()
&& n.bytes().all(|b| b.is_ascii_digit())
{
return Some(Ty::SavedMapData);
}
Some(match name {
"minecraft/custom_boss_events" => Ty::SavedCustomBossEvents,
"minecraft/scoreboard" => Ty::SavedScoreboard,
"minecraft/chunk_tickets" => Ty::SavedTickets,
"minecraft/world_border" => Ty::SavedWorldBorder,
"minecraft/game_rules" => Ty::SavedGameRules,
"minecraft/ender_dragon_fight" => Ty::SavedEnderDragonFight,
"minecraft/wandering_trader" => Ty::SavedWanderingTrader,
"minecraft/maps/last_id" => Ty::SavedMapIndex,
"minecraft/weather" => Ty::SavedWeather,
"minecraft/scheduled_events" => Ty::SavedScheduledEvents,
"minecraft/world_gen_settings" => Ty::SavedWorldGenSettings,
"minecraft/random_sequences" => Ty::SavedRandomSequences,
"minecraft/stopwatches" => Ty::SavedStopwatches,
"minecraft/raids" => Ty::SavedRaids,
"minecraft/world_clocks" => Ty::SavedWorldClocks,
_ => return None,
})
}
/// `SavedDataStorage.readTagFromDisk`: default version 1343, field kept.
pub fn update_saved_data(ty: Ty, tag: &mut Tag) {
let version = dynamic::as_int(tag.get("DataVersion"), 1343);
update(ty, tag, version, CURRENT);
}
#[cfg(test)]
mod tests;
+860
View File
@@ -0,0 +1,860 @@
//! Where DataFixerUpper finds each type inside the data, schema by schema
//! (`net.minecraft.util.datafix.schemas`), from the 1.20 schemas on.
//!
//! `walk` visits every value of the target type under a root of a given type,
//! children before parents (DataFixerUpper rewrites recursive types bottom-up).
//! Keys are `version * 10 + sub-version` as in `DataFixUtils.makeKey`, and a
//! fix with key K reads its input with the schema just below K.
use super::dynamic::{as_str, namespaced};
use crate::nbt::Tag;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Ty {
Level,
/// `LIGHTWEIGHT_LEVEL`: the level data apart from its typed fields (the same value).
LightweightLevel,
Player,
Chunk,
EntityChunk,
PoiChunk,
BlockEntity,
EntityTree,
Entity,
ItemStack,
DataComponents,
TextComponent,
VillagerTrade,
Particle,
BlockState,
FlatBlockState,
BlockName,
ItemName,
EntityName,
Biome,
Recipe,
StructureFeature,
GameEventName,
Advancements,
Stats,
Hotbar,
Objective,
Team,
WorldGenSettings,
SavedCustomBossEvents,
SavedMapData,
SavedScoreboard,
SavedWorldGenSettings,
SavedStructureFeatureIndices,
/// Saved data that has no typed fields (`DSL.remainder`).
SavedRemainder,
/// Each saved data kind still needs its own identity for fixes that target it.
SavedEnderDragonFight,
SavedGameRules,
SavedTickets,
SavedRaids,
SavedRandomSequences,
SavedWorldBorder,
SavedWeather,
SavedWorldClocks,
SavedWanderingTrader,
SavedScheduledEvents,
SavedMapIndex,
SavedCommandStorage,
SavedStopwatches,
Options,
DebugProfile,
}
/// A schema key: `version * 10 + sub`.
pub type Key = u32;
pub const fn key(version: u32, sub: u32) -> Key {
version * 10 + sub
}
pub struct Walker<'f> {
/// The schema the data is read with.
pub k: Key,
pub target: Ty,
pub f: &'f mut dyn FnMut(&mut Tag),
}
impl Walker<'_> {
pub fn walk(&mut self, ty: Ty, v: &mut Tag) {
self.children(ty, v);
if ty == self.target {
(self.f)(v);
}
}
fn field(&mut self, ty: Ty, v: &mut Tag, name: &str) {
if let Some(child) = v.get_mut(name) {
self.walk(ty, child);
}
}
fn list(&mut self, ty: Ty, v: &mut Tag, name: &str) {
if let Some(Tag::List(items)) = v.get_mut(name) {
for item in items {
self.walk(ty, item);
}
}
}
fn list_in(&mut self, ty: Ty, items: &mut Tag) {
if let Tag::List(items) = items {
for item in items {
self.walk(ty, item);
}
}
}
/// `DSL.compoundList(type)`: every value of a map.
fn values(&mut self, ty: Ty, v: &mut Tag, name: &str) {
if let Some(Tag::Compound(c)) = v.get_mut(name) {
for value in c.values_mut() {
self.walk(ty, value);
}
}
}
/// A list of compounds, each with a typed field.
fn list_of_field(&mut self, ty: Ty, v: &mut Tag, list: &str, field: &str) {
if let Some(Tag::List(items)) = v.get_mut(list) {
for item in items {
self.field(ty, item, field);
}
}
}
/// `DSL.compoundList(keyType, valueType)` with typed string keys: keys are
/// renamed in place by the callback (as a string tag).
fn keys(&mut self, ty: Ty, v: &mut Tag, name: &str) {
if ty != self.target {
return;
}
if let Some(Tag::Compound(c)) = v.get_mut(name) {
let entries: Vec<_> = std::mem::take(c).into_iter().collect();
for (k, value) in entries {
let mut key_tag = Tag::String(k.clone());
(self.f)(&mut key_tag);
let k = match key_tag {
Tag::String(s) => s,
_ => k,
};
c.insert(k, value);
}
}
}
fn children(&mut self, ty: Ty, v: &mut Tag) {
let k = self.k;
match ty {
Ty::Level => {
if k < key(4771, 0) {
if let Some(Tag::Compound(c)) = v.get_mut("CustomBossEvents") {
for e in c.values_mut() {
self.field(Ty::TextComponent, e, "Name");
}
}
}
self.walk(Ty::LightweightLevel, v);
}
Ty::Player => {
if k >= key(4312, 0) {
self.equipment(v);
}
if let Some(rv) = v.get_mut("RootVehicle") {
self.field(Ty::EntityTree, rv, "Entity");
}
self.list(Ty::EntityTree, v, "ender_pearls");
self.list(Ty::ItemStack, v, "Inventory");
self.list(Ty::ItemStack, v, "EnderItems");
self.field(Ty::EntityTree, v, "ShoulderEntityLeft");
self.field(Ty::EntityTree, v, "ShoulderEntityRight");
if let Some(book) = v.get_mut("recipeBook") {
self.list(Ty::Recipe, book, "recipes");
self.list(Ty::Recipe, book, "toBeDisplayed");
}
}
Ty::Chunk => {
self.list(Ty::EntityTree, v, "entities");
if let Some(Tag::List(items)) = v.get_mut("block_entities") {
for be in items {
// DSL.or(BLOCK_ENTITY, remainder): unknown ids stay as they are.
if block_entity_known(be, k) {
self.walk(Ty::BlockEntity, be);
}
}
}
self.list_of_field(Ty::BlockName, v, "block_ticks", "i");
if let Some(Tag::List(sections)) = v.get_mut("sections") {
for s in sections {
if let Some(b) = s.get_mut("biomes") {
self.list(Ty::Biome, b, "palette");
}
if let Some(b) = s.get_mut("block_states") {
self.list(Ty::BlockState, b, "palette");
}
}
}
if let Some(s) = v.get_mut("structures") {
self.values(Ty::StructureFeature, s, "starts");
}
}
Ty::EntityChunk => self.list(Ty::EntityTree, v, "Entities"),
Ty::EntityTree => {
self.list(Ty::EntityTree, v, "Passengers");
self.walk(Ty::Entity, v);
}
Ty::Entity => self.entity(v),
Ty::BlockEntity => self.block_entity(v),
Ty::ItemStack => self.item_stack(v),
Ty::DataComponents => self.components(v),
Ty::TextComponent => self.text(v),
Ty::VillagerTrade => {
self.field(Ty::ItemStack, v, "buy");
self.field(Ty::ItemStack, v, "buyB");
self.field(Ty::ItemStack, v, "sell");
}
Ty::Particle => {
if k >= key(3818, 4) {
self.field(Ty::ItemStack, v, "item");
self.field(Ty::BlockState, v, "block_state");
}
}
Ty::Hotbar => {
if let Tag::Compound(c) = v {
for row in c.values_mut() {
self.list_in(Ty::ItemStack, row);
}
}
}
Ty::Stats => {
if let Some(stats) = v.get_mut("stats") {
self.keys(Ty::BlockName, stats, "minecraft:mined");
for s in ["crafted", "used", "broken", "picked_up", "dropped"] {
self.keys(Ty::ItemName, stats, &format!("minecraft:{s}"));
}
self.keys(Ty::EntityName, stats, "minecraft:killed");
self.keys(Ty::EntityName, stats, "minecraft:killed_by");
}
}
Ty::Advancements => {
for (adv, kind) in [
("minecraft:adventure/adventuring_time", Ty::Biome),
("minecraft:adventure/kill_a_mob", Ty::EntityName),
("minecraft:adventure/kill_all_mobs", Ty::EntityName),
("minecraft:husbandry/bred_all_animals", Ty::EntityName),
] {
if let Some(a) = v.get_mut(adv) {
self.keys(kind, a, "criteria");
}
}
}
Ty::Objective => {
// The hook unpacked CriteriaName into CriteriaType {type, id}.
if let Some(ct) = v.get_mut("CriteriaType") {
let kind = match as_str(ct.get("type")).as_deref() {
Some("minecraft:mined") => Some(Ty::BlockName),
Some(
"minecraft:crafted"
| "minecraft:used"
| "minecraft:broken"
| "minecraft:picked_up"
| "minecraft:dropped",
) => Some(Ty::ItemName),
Some("minecraft:killed" | "minecraft:killed_by") => Some(Ty::EntityName),
_ => None,
};
if let Some(kind) = kind {
self.field(kind, ct, "id");
}
}
self.field(Ty::TextComponent, v, "DisplayName");
}
Ty::Team => {
for f in ["MemberNamePrefix", "MemberNameSuffix", "DisplayName"] {
self.field(Ty::TextComponent, v, f);
}
}
Ty::SavedCustomBossEvents => {
if let Some(Tag::Compound(c)) = v.get_mut("data") {
for e in c.values_mut() {
self.field(Ty::TextComponent, e, "Name");
}
}
}
Ty::SavedMapData => {
if let Some(d) = v.get_mut("data") {
let name = if k >= key(3813, 0) { "name" } else { "Name" };
self.list_of_field(Ty::TextComponent, d, "banners", name);
}
}
Ty::SavedScoreboard => {
if let Some(d) = v.get_mut("data") {
self.list(Ty::Objective, d, "Objectives");
self.list(Ty::Team, d, "Teams");
self.list_of_field(Ty::TextComponent, d, "PlayerScores", "display");
}
}
Ty::SavedWorldGenSettings => self.field(Ty::WorldGenSettings, v, "data"),
Ty::SavedStructureFeatureIndices => {
if let Some(d) = v.get_mut("data") {
self.values(Ty::StructureFeature, d, "Features");
}
}
Ty::WorldGenSettings => self.world_gen(v),
_ => {}
}
}
fn equipment(&mut self, v: &mut Tag) {
if self.k >= key(4301, 0) {
if let Some(eq) = v.get_mut("equipment") {
for slot in [
"mainhand", "offhand", "feet", "legs", "chest", "head", "body", "saddle",
] {
self.field(Ty::ItemStack, eq, slot);
}
}
} else {
self.list(Ty::ItemStack, v, "ArmorItems");
self.list(Ty::ItemStack, v, "HandItems");
self.field(Ty::ItemStack, v, "body_armor_item");
self.field(Ty::ItemStack, v, "saddle");
}
}
fn entity(&mut self, v: &mut Tag) {
let k = self.k;
self.equipment(v);
self.field(Ty::TextComponent, v, "CustomName");
let id = namespaced(&as_str(v.get("id")).unwrap_or_default());
let id = id.as_str();
let listener = |w: &mut Self, v: &mut Tag| {
if let Some(l) = v.get_mut("listener")
&& let Some(e) = l.get_mut("event")
{
w.field(Ty::GameEventName, e, "game_event");
}
};
match id {
"minecraft:area_effect_cloud" => {
let f = if k >= key(4420, 0) {
"custom_particle"
} else {
"Particle"
};
self.field(Ty::Particle, v, f);
}
"minecraft:arrow" | "minecraft:spectral_arrow" => {
self.field(Ty::BlockState, v, "inBlockState");
if k >= key(3685, 0) {
self.field(Ty::ItemStack, v, "item");
}
if k >= key(3938, 0) {
self.field(Ty::ItemStack, v, "weapon");
}
}
"minecraft:trident" => {
self.field(Ty::BlockState, v, "inBlockState");
let f = if k >= key(3685, 0) { "item" } else { "Trident" };
self.field(Ty::ItemStack, v, f);
}
"minecraft:chest_minecart" | "minecraft:hopper_minecart" => {
self.field(Ty::BlockState, v, "DisplayState");
self.list(Ty::ItemStack, v, "Items");
}
"minecraft:minecart" | "minecraft:furnace_minecart" | "minecraft:tnt_minecart" => {
self.field(Ty::BlockState, v, "DisplayState");
}
"minecraft:command_block_minecart" => {
self.field(Ty::BlockState, v, "DisplayState");
self.field(Ty::TextComponent, v, "LastOutput");
}
"minecraft:spawner_minecart" => {
self.field(Ty::BlockState, v, "DisplayState");
self.spawner(v);
}
"minecraft:donkey" | "minecraft:mule" => {
self.list(Ty::ItemStack, v, "Items");
if k < key(4300, 0) {
self.field(Ty::ItemStack, v, "SaddleItem");
}
}
"minecraft:llama" | "minecraft:trader_llama" => {
self.list(Ty::ItemStack, v, "Items");
if k < key(4300, 0) {
self.field(Ty::ItemStack, v, "SaddleItem");
}
let split = if id == "minecraft:llama" {
key(3808, 1)
} else {
key(3808, 2)
};
if k < split {
self.field(Ty::ItemStack, v, "DecorItem");
}
}
"minecraft:horse" => {
if k < key(4300, 0) {
self.field(Ty::ItemStack, v, "SaddleItem");
}
if k < key(3808, 0) {
self.field(Ty::ItemStack, v, "ArmorItem");
}
}
"minecraft:skeleton_horse" | "minecraft:zombie_horse" => {
if k < key(4300, 0) {
self.field(Ty::ItemStack, v, "SaddleItem");
}
}
"minecraft:enderman" => self.field(Ty::BlockState, v, "carriedBlockState"),
"minecraft:falling_block" => {
self.field(Ty::BlockState, v, "BlockState");
self.field(Ty::BlockEntity, v, "TileEntityData");
}
"minecraft:firework_rocket" => self.field(Ty::ItemStack, v, "FireworksItem"),
"minecraft:item" | "minecraft:item_frame" | "minecraft:glow_item_frame" => {
self.field(Ty::ItemStack, v, "Item");
}
"minecraft:potion" if k < key(4306, 0) => self.field(Ty::ItemStack, v, "Item"),
"minecraft:splash_potion" | "minecraft:lingering_potion" if k >= key(4306, 0) => {
self.field(Ty::ItemStack, v, "Item");
}
"minecraft:villager" | "minecraft:wandering_trader" => {
self.list(Ty::ItemStack, v, "Inventory");
if let Some(o) = v.get_mut("Offers") {
self.list(Ty::VillagerTrade, o, "Recipes");
}
}
"minecraft:zombie_villager" => {
if let Some(o) = v.get_mut("Offers") {
self.list(Ty::VillagerTrade, o, "Recipes");
}
}
"minecraft:pillager" | "minecraft:piglin" => self.list(Ty::ItemStack, v, "Inventory"),
"minecraft:allay" => {
self.list(Ty::ItemStack, v, "Inventory");
listener(self, v);
}
"minecraft:warden" => listener(self, v),
"minecraft:tnt" if k >= key(3683, 0) => self.field(Ty::BlockState, v, "block_state"),
"minecraft:chest_boat" if k < key(4067, 0) => self.list(Ty::ItemStack, v, "Items"),
"minecraft:item_display" => self.field(Ty::ItemStack, v, "item"),
"minecraft:block_display" => self.field(Ty::BlockState, v, "block_state"),
"minecraft:text_display" => self.field(Ty::TextComponent, v, "text"),
"minecraft:ominous_item_spawner" if k >= key(3825, 0) => {
self.field(Ty::ItemStack, v, "item")
}
_ if k >= key(4067, 0)
&& (id.ends_with("_chest_boat") || id == "minecraft:bamboo_chest_raft") =>
{
self.list(Ty::ItemStack, v, "Items");
}
_ => {}
}
}
/// `UNTAGGED_SPAWNER` (V2831).
fn spawner(&mut self, v: &mut Tag) {
if let Some(Tag::List(items)) = v.get_mut("SpawnPotentials") {
for p in items {
if let Some(d) = p.get_mut("data") {
self.field(Ty::EntityTree, d, "entity");
}
}
}
if let Some(d) = v.get_mut("SpawnData") {
self.field(Ty::EntityTree, d, "entity");
}
}
fn block_entity(&mut self, v: &mut Tag) {
let k = self.k;
self.field(Ty::DataComponents, v, "components");
let id = namespaced(&as_str(v.get("id")).unwrap_or_default());
let named_inventory = |w: &mut Self, v: &mut Tag| {
w.list(Ty::ItemStack, v, "Items");
w.field(Ty::TextComponent, v, "CustomName");
};
match id.as_str() {
"minecraft:furnace" | "minecraft:smoker" | "minecraft:blast_furnace" => {
named_inventory(self, v);
self.keys(Ty::Recipe, v, "RecipesUsed");
}
"minecraft:chest"
| "minecraft:trapped_chest"
| "minecraft:dispenser"
| "minecraft:dropper"
| "minecraft:hopper"
| "minecraft:shulker_box"
| "minecraft:brewing_stand"
| "minecraft:barrel" => {
named_inventory(self, v);
}
"minecraft:crafter" if k >= key(3682, 0) => named_inventory(self, v),
"minecraft:jukebox" => self.field(Ty::ItemStack, v, "RecordItem"),
"minecraft:sign" | "minecraft:hanging_sign" => {
for side in ["front_text", "back_text"] {
if let Some(s) = v.get_mut(side) {
self.list(Ty::TextComponent, s, "messages");
self.list(Ty::TextComponent, s, "filtered_messages");
}
}
}
"minecraft:mob_spawner" => self.spawner(v),
"minecraft:piston" => self.field(Ty::BlockState, v, "blockState"),
"minecraft:enchanting_table" | "minecraft:beacon" | "minecraft:banner" => {
self.field(Ty::TextComponent, v, "CustomName");
}
"minecraft:skull" => self.field(Ty::TextComponent, v, "custom_name"),
"minecraft:command_block" => {
self.field(Ty::TextComponent, v, "CustomName");
self.field(Ty::TextComponent, v, "LastOutput");
}
"minecraft:jigsaw" => self.field(Ty::FlatBlockState, v, "final_state"),
"minecraft:campfire" | "minecraft:chiseled_bookshelf" => {
self.list(Ty::ItemStack, v, "Items")
}
"minecraft:shelf" if k >= key(4533, 0) => self.list(Ty::ItemStack, v, "Items"),
"minecraft:lectern" => self.field(Ty::ItemStack, v, "Book"),
"minecraft:beehive" => {
if k >= key(3818, 0) {
self.list_of_field(Ty::EntityTree, v, "bees", "entity_data");
} else {
self.list_of_field(Ty::EntityTree, v, "Bees", "EntityData");
}
}
"minecraft:sculk_sensor" | "minecraft:sculk_shrieker" => {
if let Some(l) = v.get_mut("listener")
&& let Some(e) = l.get_mut("event")
{
self.field(Ty::GameEventName, e, "game_event");
}
}
"minecraft:decorated_pot" => {
if k >= key(4996, 1) {
if let Some(s) = v.get_mut("sherds") {
for side in ["back", "left", "right", "front"] {
self.field(Ty::ItemStack, s, side);
}
}
} else if k >= key(3448, 0) {
self.list(Ty::ItemName, v, "sherds");
} else {
self.list(Ty::ItemName, v, "shards");
}
self.field(Ty::ItemStack, v, "item");
}
"minecraft:brushable_block" | "minecraft:suspicious_sand" => {
self.field(Ty::ItemStack, v, "item")
}
"minecraft:trial_spawner" if k >= key(3689, 0) => {
if let Some(Tag::List(items)) = v.get_mut("spawn_potentials") {
for p in items {
if let Some(d) = p.get_mut("data") {
self.field(Ty::EntityTree, d, "entity");
}
}
}
if let Some(d) = v.get_mut("spawn_data") {
self.field(Ty::EntityTree, d, "entity");
}
}
"minecraft:vault" if k >= key(3807, 0) => {
if let Some(c) = v.get_mut("config") {
self.field(Ty::ItemStack, c, "key_item");
}
if let Some(c) = v.get_mut("server_data") {
self.list(Ty::ItemStack, c, "items_to_eject");
}
if let Some(c) = v.get_mut("shared_data") {
self.field(Ty::ItemStack, c, "display_item");
}
}
"minecraft:test_instance_block" if k >= key(4302, 0) => {
if let Some(d) = v.get_mut("data") {
self.field(Ty::TextComponent, d, "error_message");
}
self.list_of_field(Ty::TextComponent, v, "errors", "text");
}
_ => {}
}
}
fn item_stack(&mut self, v: &mut Tag) {
if self.k >= key(3818, 5) {
self.field(Ty::ItemName, v, "id");
self.field(Ty::DataComponents, v, "components");
return;
}
self.field(Ty::ItemName, v, "id");
let Some(tag) = v.get_mut("tag") else {
return;
};
self.field(Ty::EntityTree, tag, "EntityTag");
self.field(Ty::BlockEntity, tag, "BlockEntityTag");
self.list(Ty::BlockName, tag, "CanDestroy");
self.list(Ty::BlockName, tag, "CanPlaceOn");
self.list(Ty::ItemStack, tag, "Items");
self.list(Ty::ItemStack, tag, "ChargedProjectiles");
self.list(Ty::TextComponent, tag, "pages");
self.values(Ty::TextComponent, tag, "filtered_pages");
if let Some(d) = tag.get_mut("display") {
self.field(Ty::TextComponent, d, "Name");
self.list(Ty::TextComponent, d, "Lore");
}
}
fn components(&mut self, v: &mut Tag) {
let k = self.k;
if k < key(3818, 3) {
return;
}
let Tag::Compound(_) = v else {
return;
};
self.list_of_field(Ty::EntityTree, v, "minecraft:bees", "entity_data");
self.field(Ty::BlockEntity, v, "minecraft:block_entity_data");
self.list(Ty::ItemStack, v, "minecraft:bundle_contents");
for c in ["minecraft:can_break", "minecraft:can_place_on"] {
let Some(p) = v.get_mut(c) else {
continue;
};
if k >= key(4307, 0) {
// A predicate or a list of them.
if let Tag::List(items) = p {
for item in items {
self.blocks_predicate(item);
}
} else {
self.blocks_predicate(p);
}
} else if let Some(Tag::List(items)) = p.get_mut("predicates") {
for item in items {
self.blocks_predicate(item);
}
}
}
self.list(Ty::ItemStack, v, "minecraft:charged_projectiles");
self.list_of_field(Ty::ItemStack, v, "minecraft:container", "item");
self.field(Ty::EntityTree, v, "minecraft:entity_data");
if k >= key(4996, 0) {
if let Some(p) = v.get_mut("minecraft:pot_decorations") {
for side in ["back", "left", "right", "front"] {
self.field(Ty::ItemStack, p, side);
}
}
} else {
self.list(Ty::ItemName, v, "minecraft:pot_decorations");
}
if k < key(4059, 0) {
if let Some(f) = v.get_mut("minecraft:food") {
self.field(Ty::ItemStack, f, "using_converts_to");
}
} else {
self.field(Ty::ItemStack, v, "minecraft:use_remainder");
if let Some(e) = v.get_mut("minecraft:equippable")
&& let Some(a) = e.get_mut("allowed_entities")
{
if let Tag::List(_) = a {
self.list_in(Ty::EntityName, a);
} else {
self.walk(Ty::EntityName, a);
}
}
self.field(Ty::ItemStack, v, "minecraft:sulfur_cube_content");
}
self.field(Ty::TextComponent, v, "minecraft:custom_name");
self.field(Ty::TextComponent, v, "minecraft:item_name");
self.list(Ty::TextComponent, v, "minecraft:lore");
if let Some(b) = v.get_mut("minecraft:written_book_content")
&& let Some(Tag::List(pages)) = b.get_mut("pages")
{
for page in pages {
// DSL.or({raw, filtered}, TEXT_COMPONENT): any compound is the filterable form.
if let Tag::Compound(_) = page {
self.field(Ty::TextComponent, page, "raw");
self.field(Ty::TextComponent, page, "filtered");
} else {
self.walk(Ty::TextComponent, page);
}
}
}
}
fn blocks_predicate(&mut self, p: &mut Tag) {
if let Some(b) = p.get_mut("blocks") {
if let Tag::List(_) = b {
self.list_in(Ty::BlockName, b);
} else {
self.walk(Ty::BlockName, b);
}
}
}
fn text(&mut self, v: &mut Tag) {
let k = self.k;
if k < key(4290, 0) {
return;
}
match v {
Tag::List(_) => self.list_in(Ty::TextComponent, v),
Tag::Compound(_) => {
self.list(Ty::TextComponent, v, "extra");
self.field(Ty::TextComponent, v, "separator");
if k >= key(4292, 0) {
if let Some(h) = v.get_mut("hover_event") {
match as_str(h.get("action")).as_deref() {
Some("show_text") => self.field(Ty::TextComponent, h, "value"),
Some("show_item") => self.walk(Ty::ItemStack, h),
Some("show_entity") => {
self.field(Ty::EntityName, h, "id");
self.field(Ty::TextComponent, h, "name");
}
_ => {}
}
}
} else if let Some(h) = v.get_mut("hoverEvent") {
match as_str(h.get("action")).as_deref() {
Some("show_text") => self.field(Ty::TextComponent, h, "contents"),
Some("show_item") => {
if let Some(c) = h.get_mut("contents") {
// DSL.or(ITEM_STACK, ITEM_NAME)
if let Tag::Compound(_) = c {
self.walk(Ty::ItemStack, c);
} else {
self.walk(Ty::ItemName, c);
}
}
}
Some("show_entity") => {
if let Some(c) = h.get_mut("contents") {
self.field(Ty::EntityName, c, "type");
self.field(Ty::TextComponent, c, "name");
}
}
_ => {}
}
}
}
_ => {}
}
}
/// `WORLD_GEN_SETTINGS` (V2832).
fn world_gen(&mut self, v: &mut Tag) {
let Some(Tag::Compound(dims)) = v.get_mut("dimensions") else {
return;
};
for dim in dims.values_mut() {
let Some(g) = dim.get_mut("generator") else {
continue;
};
match as_str(g.get("type")).as_deref() {
Some("minecraft:flat") => {
if let Some(s) = g.get_mut("settings") {
self.field(Ty::Biome, s, "biome");
self.list_of_field(Ty::BlockName, s, "layers", "block");
}
}
Some("minecraft:noise") => {
if let Some(b) = g.get_mut("biome_source") {
match as_str(b.get("type")).as_deref() {
Some("minecraft:fixed") => self.field(Ty::Biome, b, "biome"),
Some("minecraft:checkerboard") => self.list(Ty::Biome, b, "biomes"),
_ => {}
}
}
if let Some(s) = g.get_mut("settings")
&& let Tag::Compound(_) = s
{
self.field(Ty::BlockName, s, "default_block");
self.field(Ty::BlockName, s, "default_fluid");
}
}
_ => {}
}
}
}
}
/// Block entity ids the schema at `k` knows (others are read as remainder).
pub fn block_entity_known(be: &Tag, k: Key) -> bool {
let id = namespaced(&as_str(be.get("id")).unwrap_or_default());
let since = match id.as_str() {
"minecraft:sculk_catalyst" => key(3076, 0),
"minecraft:sculk_shrieker" => key(3078, 0),
"minecraft:hanging_sign" => key(3202, 0),
"minecraft:chiseled_bookshelf" => key(3204, 0),
"minecraft:decorated_pot" => key(3327, 0),
"minecraft:suspicious_sand" => return (key(3327, 0)..key(3438, 0)).contains(&k),
"minecraft:crafter" => key(3682, 0),
"minecraft:trial_spawner" => key(3689, 0),
"minecraft:vault" => key(3807, 0),
"minecraft:creaking_heart" => key(4071, 0),
"minecraft:test_block" | "minecraft:test_instance_block" => key(4302, 0),
"minecraft:copper_golem_statue" => key(4532, 0),
"minecraft:shelf" => key(4533, 0),
"minecraft:potent_sulfur" => key(4881, 0),
"minecraft:bed" => return k < key(4885, 0),
"minecraft:brushable_block" | "minecraft:calibrated_sculk_sensor" => key(3438, 0),
_ => 0,
};
k >= since && BLOCK_ENTITIES.contains(&id.as_str())
}
/// Block entity types of the schemas from 1.20 on.
const BLOCK_ENTITIES: &[&str] = &[
"minecraft:furnace",
"minecraft:chest",
"minecraft:trapped_chest",
"minecraft:ender_chest",
"minecraft:jukebox",
"minecraft:dispenser",
"minecraft:dropper",
"minecraft:sign",
"minecraft:mob_spawner",
"minecraft:piston",
"minecraft:brewing_stand",
"minecraft:enchanting_table",
"minecraft:end_portal",
"minecraft:beacon",
"minecraft:skull",
"minecraft:daylight_detector",
"minecraft:hopper",
"minecraft:comparator",
"minecraft:banner",
"minecraft:structure_block",
"minecraft:end_gateway",
"minecraft:command_block",
"minecraft:shulker_box",
"minecraft:bed",
"minecraft:conduit",
"minecraft:barrel",
"minecraft:smoker",
"minecraft:blast_furnace",
"minecraft:lectern",
"minecraft:bell",
"minecraft:jigsaw",
"minecraft:campfire",
"minecraft:beehive",
"minecraft:sculk_sensor",
"minecraft:sculk_catalyst",
"minecraft:sculk_shrieker",
"minecraft:hanging_sign",
"minecraft:chiseled_bookshelf",
"minecraft:decorated_pot",
"minecraft:suspicious_sand",
"minecraft:brushable_block",
"minecraft:calibrated_sculk_sensor",
"minecraft:crafter",
"minecraft:trial_spawner",
"minecraft:vault",
"minecraft:creaking_heart",
"minecraft:test_block",
"minecraft:test_instance_block",
"minecraft:copper_golem_statue",
"minecraft:shelf",
"minecraft:potent_sulfur",
];
/// Visit every value of `target` under a `root`-typed value read with schema `k`.
pub fn walk(root: Ty, v: &mut Tag, k: Key, target: Ty, f: &mut dyn FnMut(&mut Tag)) {
Walker { k, target, f }.walk(root, v);
}
+80
View File
@@ -0,0 +1,80 @@
use super::*;
use crate::nbt::parse_snbt;
fn snbt(s: &str) -> Tag {
parse_snbt(s).unwrap().0
}
#[test]
fn current_data_is_left_alone() {
let mut tag = snbt("{DataVersion: 5023, Status: \"minecraft:full\"}");
let before = tag.clone();
update_chunk(&mut tag, "minecraft:overworld", Some("minecraft:noise"));
assert_eq!(tag, before);
}
#[test]
fn item_stacks_of_1_20_take_components() {
let mut player = snbt(
"{DataVersion: 3465, Inventory: [{Slot: 0b, id: \"minecraft:diamond_sword\", Count: 1b, \
tag: {Damage: 5, display: {Name: '{\"text\":\"Blade\"}'}}}]}",
);
update_player(&mut player);
let stack = &dynamic::stream(player.get("Inventory"))[0];
assert_eq!(
dynamic::as_str(stack.get("id")).as_deref(),
Some("minecraft:diamond_sword")
);
assert_eq!(stack.get("count"), Some(&Tag::Int(1)));
let components = stack.get("components").expect("components");
assert_eq!(components.get("minecraft:damage"), Some(&Tag::Int(5)));
assert_eq!(
components.get("minecraft:custom_name"),
Some(&Tag::compound([("text", dynamic::string("Blade"))]))
);
}
#[test]
fn level_data_of_1_20_moves_to_the_new_fields() {
let mut level = snbt(
"{DataVersion: 3465, Difficulty: 3b, DifficultyLocked: 1b, hardcore: 0b, SpawnX: 1, SpawnY: 64, SpawnZ: -3, \
SpawnAngle: 90.0f, GameRules: {doFireTick: \"false\", keepInventory: \"true\", randomTickSpeed: \"5\"}}",
);
update(Ty::Level, &mut level, 3465, CURRENT);
let settings = level
.get("difficulty_settings")
.expect("difficulty settings");
assert_eq!(
dynamic::as_str(settings.get("difficulty")).as_deref(),
Some("hard")
);
assert_eq!(settings.get("locked"), Some(&Tag::Byte(1)));
let rules = level.get("game_rules").expect("game rules");
assert_eq!(rules.get("minecraft:keep_inventory"), Some(&Tag::Byte(1)));
assert_eq!(rules.get("minecraft:random_tick_speed"), Some(&Tag::Int(5)));
assert_eq!(
rules.get("minecraft:fire_spread_radius_around_player"),
Some(&Tag::Int(0))
);
assert_eq!(
level.get("spawn").and_then(|s| s.get("pos")),
Some(&Tag::IntArray(vec![1, 64, -3]))
);
}
#[test]
fn block_states_take_their_new_field_names() {
let mut chunk = snbt(
"{DataVersion: 4903, Status: \"minecraft:full\", sections: [{Y: 0b, block_states: \
{palette: [{Name: \"minecraft:chain\", Properties: {axis: \"y\"}}]}}]}",
);
update_chunk(&mut chunk, "minecraft:the_nether", Some("minecraft:noise"));
let section = &dynamic::stream(chunk.get("sections"))[0];
let state = &dynamic::stream(section.get("block_states").and_then(|b| b.get("palette")))[0];
assert_eq!(
dynamic::as_str(state.get("id")).as_deref(),
Some("minecraft:chain")
);
assert!(state.get("properties").is_some());
assert_eq!(chunk.get("DataVersion"), Some(&Tag::Int(CURRENT)));
}
+252
View File
@@ -0,0 +1,252 @@
//! The text component fixes of 1.21.5 (keys 4290 to 4292): JSON strings become
//! NBT components, legacy hover events are replaced, stringified style flags
//! become booleans and hover/click events take their new field names.
use super::FixFn;
use super::dynamic::{
as_number, as_str, as_string, boolean, empty_map, remove, rename, rename_and_fix, set, string,
};
use super::json;
use super::schema::{Key, Ty, key};
use crate::nbt::Tag;
pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
out.push((key(4290, 0), |cx| cx.each(Ty::TextComponent, unflatten)));
out.push((key(4291, 0), |cx| {
cx.each(Ty::TextComponent, legacy_hover_event)
}));
out.push((key(4291, 0), |cx| {
cx.each(Ty::TextComponent, stringified_flags)
}));
out.push((key(4292, 0), |cx| {
cx.each(Ty::TextComponent, hover_and_click_event)
}));
}
/// `UnflattenTextComponentFix`: the JSON of a string component as NBT.
fn unflatten(v: &mut Tag) {
let Tag::String(s) = v else {
return;
};
if let Some(parsed) = json::parse_lenient(&s.0)
&& let Some(tag) = json::to_nbt(&parsed)
{
*v = tag;
}
}
fn is_full(v: &Tag) -> bool {
matches!(v, Tag::Compound(_))
}
/// The hover event a schema of 4290/4291 reads as typed (a known action).
fn typed_hover(v: &Tag) -> Option<String> {
let h = v.get("hoverEvent")?;
let action = as_str(h.get("action"))?;
matches!(action.as_str(), "show_text" | "show_item" | "show_entity").then_some(action)
}
/// `LegacyHoverEventFix`.
fn legacy_hover_event(v: &mut Tag) {
if !is_full(v) {
return;
}
let Some(hover) = v.get("hoverEvent").cloned() else {
return;
};
if hover.get("value").is_none() {
return;
}
let action = typed_hover(v).unwrap_or_default();
let new = if action == "show_text" {
let mut h = hover;
rename(&mut h, "value", "contents");
h
} else {
let mut text = "Legacy hoverEvent: ".encode_utf16().collect::<Vec<u16>>();
text.extend(json::to_stable_string(&json::from_nbt(&hover)));
Tag::compound([
("action", string("show_text")),
(
"contents",
Tag::compound([("text", Tag::String(crate::nbt::JavaString(text)))]),
),
])
};
set(v, "hoverEvent", new);
}
/// `TextComponentStringifiedFlagsFix`: `Boolean.parseBoolean` of string flags.
fn stringified_flags(v: &mut Tag) {
if !is_full(v) {
return;
}
for flag in [
"bold",
"italic",
"underlined",
"strikethrough",
"obfuscated",
] {
if let Some(s) = as_str(v.get(flag)) {
set(v, flag, boolean(s.eq_ignore_ascii_case("true")));
}
}
}
/// `TextComponentHoverAndClickEventFix`.
fn hover_and_click_event(v: &mut Tag) {
if !is_full(v) {
return;
}
if typed_hover(v).is_none() && v.get("clickEvent").is_none() {
return;
}
rename_and_fix(v, "hoverEvent", "hover_event", |h| Some(fix_hover_event(h)));
rename_and_fix(v, "clickEvent", "click_event", fix_click_event);
}
fn copy_fields(target: &mut Tag, source: &Tag, fields: &[&str]) {
for f in fields {
if let Some(value) = source.get(f) {
set(target, f, value.clone());
}
}
}
fn fix_hover_event(mut h: Tag) -> Tag {
match as_string(h.get("action"), "").as_str() {
"show_text" => rename(&mut h, "contents", "value"),
"show_item" => {
let contents = h.get("contents").cloned().unwrap_or_else(empty_map);
remove(&mut h, "contents");
copy_fields(&mut h, &contents, &["id", "count", "components"]);
}
"show_entity" => {
let contents = h.get("contents").cloned().unwrap_or_else(empty_map);
remove(&mut h, "contents");
copy_fields(&mut h, &contents, &["id", "type", "name"]);
rename(&mut h, "id", "uuid");
rename(&mut h, "type", "id");
}
_ => {}
}
h
}
fn fix_click_event(mut c: Tag) -> Option<Tag> {
let action = as_string(c.get("action"), "");
let value = as_string(c.get("value"), "");
match action.as_str() {
"open_url" => {
if !valid_uri(&value) {
return None;
}
rename(&mut c, "value", "url");
}
"open_file" => rename(&mut c, "value", "path"),
"run_command" | "suggest_command" => {
if !valid_chat(&value) {
return None;
}
rename(&mut c, "value", "command");
}
"change_page" => {
let old = c.get("value").and_then(|v| match as_number(v) {
Some(n) => Some(n.int_value()),
None => parse_int(&as_string(Some(v), "")),
})?;
remove(&mut c, "value");
set(&mut c, "page", Tag::Int(old.max(1)));
}
_ => {}
}
Some(c)
}
/// `Integer.parseInt`.
fn parse_int(s: &str) -> Option<i32> {
let digits = s.strip_prefix(['+', '-']).unwrap_or(s);
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
s.parse().ok()
}
/// `new URI(uri)` succeeds with an http or https scheme.
fn valid_uri(uri: &str) -> bool {
let Some((scheme, rest)) = uri.split_once(':') else {
return false;
};
let mut chars = scheme.chars();
let scheme_ok = chars.next().is_some_and(|c| c.is_ascii_alphabetic())
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
if !scheme_ok || rest.is_empty() {
return false;
}
// Characters java.net.URI refuses anywhere, and escapes it checks.
let bytes: Vec<char> = rest.chars().collect();
let mut hashes = 0;
let mut i = 0;
while i < bytes.len() {
let c = bytes[i];
if c == '%' {
if !bytes.get(i + 1).is_some_and(char::is_ascii_hexdigit)
|| !bytes.get(i + 2).is_some_and(char::is_ascii_hexdigit)
{
return false;
}
i += 3;
continue;
}
if c == '#' {
hashes += 1;
}
if c.is_control()
|| c.is_whitespace()
|| matches!(c, '"' | '<' | '>' | '\\' | '^' | '`' | '{' | '|' | '}')
{
return false;
}
i += 1;
}
hashes <= 1 && matches!(scheme.to_ascii_lowercase().as_str(), "http" | "https")
}
/// `StringUtil.isAllowedChatCharacter` for every character.
fn valid_chat(s: &str) -> bool {
s.encode_utf16().all(|c| c != 167 && c >= 32 && c != 127)
}
#[cfg(test)]
mod tests {
use super::*;
fn j(s: &str) -> Tag {
json::to_nbt(&json::parse_lenient(&s.encode_utf16().collect::<Vec<_>>()).unwrap()).unwrap()
}
#[test]
fn click_events_take_their_new_fields() {
let mut c = j(r#"{"text":"a","clickEvent":{"action":"change_page","value":"0"}}"#);
hover_and_click_event(&mut c);
// The page is written as an int (`createInt`), not as JSON's narrowest number.
let mut expected = j(r#"{"text":"a","click_event":{"action":"change_page"}}"#);
if let Some(click) = expected.get_mut("click_event") {
super::super::dynamic::set(click, "page", Tag::Int(1));
}
assert_eq!(c, expected);
let mut c = j(r#"{"text":"a","clickEvent":{"action":"open_url","value":"ftp://x"}}"#);
hover_and_click_event(&mut c);
assert_eq!(c, j(r#"{"text":"a"}"#));
}
#[test]
fn legacy_hover_events_become_text() {
let mut c = j(r#"{"text":"a","hoverEvent":{"action":"show_item","value":"{id:stone}"}}"#);
legacy_hover_event(&mut c);
let expected = j(
r#"{"text":"a","hoverEvent":{"action":"show_text","contents":{"text":"Legacy hoverEvent: {\"action\":\"show_item\",\"value\":\"{id:stone}\"}"}}}"#,
);
assert_eq!(c, expected);
}
}
+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
+15 -2
View File
@@ -452,9 +452,22 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
// ---- misc helpers ----
/// `BaseFireBlock.onPlace` (portal ignition is not modelled).
/// `BaseFireBlock.onPlace`: a fire inside an empty obsidian frame (in the
/// overworld or the nether) lights it, otherwise one that cannot survive
/// goes out.
fn base_fire_on_place(&mut self, pos: BlockPos, state: BlockStateId, same: bool) {
if !same && !self.can_survive(state, pos) {
if same {
return;
}
if matches!(
self.level.dimension(),
super::Dimension::Overworld | super::Dimension::Nether
) && let Some(shape) = self.find_empty_portal_shape(pos, true)
{
self.create_portal_blocks(&shape);
return;
}
if !self.can_survive(state, pos) {
self.remove_block(pos, false);
}
}
+20
View File
@@ -549,6 +549,26 @@ impl Behaviours {
) -> bool {
self.sim(level, ticks).player_destroy(pos, creative)
}
/// `BaseFireBlock.getState(level, pos)`: soul fire on its base blocks,
/// otherwise fire shaped by its neighbours.
pub fn fire_state_for<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
) -> BlockStateId {
self.sim(level, ticks).fire_state_for(pos)
}
/// `BaseFireBlock.canBePlacedAt(level, pos, forwardDirection)`.
pub fn fire_can_be_placed_at<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
forward: horizon_core::geometry::Direction,
) -> bool {
self.sim(level, ticks).fire_can_be_placed_at(pos, forward)
}
/// `BlockState.canSurvive(level, pos)`.
pub fn can_survive<L: LevelAccess + ?Sized>(
&self,
+23
View File
@@ -1595,6 +1595,29 @@ impl Behaviours {
) -> PlaceOutcome {
self.sim(level, ticks).place(ctx)
}
/// `DirectionalPlaceContext.canPlace`: whether the block at the clicked
/// position can be replaced by the item (a dispenser places only there).
pub fn directional_can_place<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
ctx: &PlaceContext,
) -> bool {
let sim = self.sim(level, ticks);
let inner = Ctx {
pos: ctx.clicked_pos,
hit_pos: ctx.clicked_pos,
face: ctx.face,
hit: ctx.hit,
inside: ctx.inside,
yaw: ctx.yaw,
pitch: ctx.pitch,
sneaking: ctx.sneaking,
item: ctx.item.clone(),
replace_clicked: true,
};
sim.can_be_replaced(sim.state(ctx.clicked_pos), &inner)
}
/// The position and state `BlockItem.place` would place for `ctx`, without
/// writing anything (None when vanilla's placement fails).
pub fn placement_state<L: LevelAccess + ?Sized>(
+56 -1
View File
@@ -1,7 +1,7 @@
//! `PortalShape`: the obsidian frame search used by nether portal blocks.
use super::{LevelAccess, Sim, update::rel};
use crate::registry::BlockStateId;
use horizon_core::{geometry::Direction, position::BlockPos};
use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource};
const MIN_WIDTH: i32 = 2;
const MAX_WIDTH: i32 = 21;
@@ -126,4 +126,59 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
};
shape
}
/// `PortalShape.findEmptyPortalShape`: a valid frame holding no portal
/// block yet, on the preferred axis first.
pub fn find_empty_portal_shape(&self, pos: BlockPos, x_axis: bool) -> Option<PortalShape> {
[x_axis, !x_axis]
.into_iter()
.map(|axis| self.find_portal_shape(pos, axis))
.find(|shape| shape.is_valid() && shape.portal_blocks == 0)
}
/// `PortalShape.createPortalBlocks`: fill the frame (flags 18).
pub fn create_portal_blocks(&mut self, shape: &PortalShape) {
let b = self.b;
let base = b.default_of(b.named.nether_portal);
let state = b
.table
.with_text(base, b.props.axis, if shape.x_axis { "x" } else { "z" })
.unwrap_or(base);
for h in 0..shape.height {
for w in 0..shape.width {
let at = step(step(shape.bottom_left, Direction::Up, h), shape.right, w);
self.set_block(at, state, 18);
}
}
}
/// `BaseFireBlock.canBePlacedAt(level, pos, forwardDirection)`: air where
/// fire would survive, or the inside of an empty portal frame (vertical
/// directions pick the frame axis with the level random).
pub fn fire_can_be_placed_at(&mut self, pos: BlockPos, forward: Direction) -> bool {
if !self.b.is_air(self.state(pos)) {
return false;
}
if self.can_survive(self.fire_state_for(pos), pos) {
return true;
}
// isPortal
if !matches!(
self.level.dimension(),
super::Dimension::Overworld | super::Dimension::Nether
) {
return false;
}
for face in Direction::ALL {
if self.portal_frame(self.state(rel(pos, face))) {
// getCounterClockWise().getAxis(): north/south turn to X.
let x_axis = match forward {
Direction::North | Direction::South => true,
Direction::West | Direction::East => false,
Direction::Up | Direction::Down => {
self.random().next_int_bound(2).unwrap_or(0) == 0
}
};
return self.find_empty_portal_shape(pos, x_axis).is_some();
}
}
false
}
}
+1
View File
@@ -34,6 +34,7 @@ pub mod consume_effect;
pub mod damage_immunity;
pub mod damage_reduction;
pub mod damage_source;
pub mod datafix;
pub mod dynamic_support;
pub mod edge_backoff;
pub mod effect_attribute_modifiers;
+13 -14
View File
@@ -104,14 +104,18 @@ impl RegionFile {
let position = position_from_path(&path)?;
let mut file = File::open(&path)?;
let len = file.metadata()?.len();
if len < HEADER as u64 {
return Err(invalid("truncated region header"));
}
// RegionFile's constructor: a short header (an empty or truncated file)
// reads as far as it goes, the rest stays zero (no chunks).
let mut header = [0; HEADER];
file.read_exact(&mut header)?;
let mut read = 0;
while read < HEADER {
match file.read(&mut header[read..])? {
0 => break,
n => read += n,
}
}
let mut offsets = [0; 1024];
let mut timestamps = [0; 1024];
let mut ranges = Vec::new();
for i in 0..1024 {
offsets[i] = u32::from_be_bytes(header[i * 4..i * 4 + 4].try_into().unwrap());
timestamps[i] = u32::from_be_bytes(
@@ -124,16 +128,11 @@ impl RegionFile {
}
let start = offsets[i] >> 8;
let count = offsets[i] & 255;
if start < 2 || count == 0 || u64::from(start + count) > len.div_ceil(SECTOR as u64) {
return Err(invalid(format!(
"invalid sector allocation at region slot {i}"
)));
// Vanilla drops entries that overlap the header, are empty or start past
// the end of the file (logged as invalid sectors).
if start < 2 || count == 0 || u64::from(start) * SECTOR as u64 > len {
offsets[i] = 0;
}
ranges.push((start, start + count));
}
ranges.sort_unstable();
if ranges.windows(2).any(|r| r[0].1 > r[1].0) {
return Err(invalid("overlapping region sector allocations"));
}
Ok(Self {
file,
+12 -3
View File
@@ -120,12 +120,21 @@ fn malformed_region(path: &Path, first: u32, second: u32, payload_len: u32, code
}
#[test]
fn corrupt_allocations_lengths_codecs_and_missing_external_files_fail() {
fn corrupt_allocations_are_dropped_and_bad_payloads_fail() {
let dir = Directory::new();
for (first, second) in [(257, 0), (512, 0), (1025, 0), (513, 513)] {
// RegionFile's constructor drops (and logs) entries whose sector overlaps the
// header, that have no sectors or that start past the end of the file; it
// does not check overlaps between chunks.
for (first, second, chunks) in [(257, 0, 0), (512, 0, 0), (1025, 0, 0), (513, 513, 2)] {
malformed_region(&dir.region(), first, second, 1, 3);
assert!(RegionFile::open(dir.region()).is_err());
let reader = RegionFile::open(dir.region()).unwrap();
assert_eq!(reader.chunks().count(), chunks);
}
// An empty or truncated file reads as a region without chunks.
fs::write(dir.region(), b"").unwrap();
assert_eq!(RegionFile::open(dir.region()).unwrap().chunks().count(), 0);
fs::write(dir.region(), [0, 0, 2, 1]).unwrap();
assert_eq!(RegionFile::open(dir.region()).unwrap().chunks().count(), 0);
for (len, codec) in [
(0, 3),
(4093, 3),
+1 -4
View File
@@ -68,10 +68,7 @@ The registry loader checks data version, duplicate states, default IDs and
block-name coverage. The local oracle exports all 35,723 state identities and
defaults from vanilla. This imports identities, not block implementations,
shapes or behavior. Registry exports and game-derived fixtures stay in `.local/`.
Chunk access requires data version 5023. The DataFixerUpper chain is not ported:
opening a world whose `level.dat` is older fails with a message pointing at
`tools/upgrade_world.py`, which runs vanilla's own `--forceUpgrade` on a copy
(exercised only against a current-version world; no older server jar is local). `BlockRegistry::resolve` rejects invalid property descriptors. The separate
Chunk access requires data version 5023. A world saved by an older version is upgraded when it is opened, as 26.3 does: the file fixes (`FileFixerUpper`) and level.dat, then vanilla's DataFixers over every chunk, entity chunk, POI chunk, player, saved data, advancements and statistics file (`horizon_world::datafix`; vanilla upgrades each file as it reads it, Horizon all of them on opening). `tools/test_datafix_parity.py` compares the result with vanilla's own upgrade over worlds written by older server jars. Worlds older than the ported fixes are refused with a message pointing at `tools/upgrade_world.py`, which runs vanilla's `--forceUpgrade` on a copy. `BlockRegistry::resolve` rejects invalid property descriptors. The separate
[block-state JSON codec](block-state-codecs.md) reproduces vanilla property
fallback for compact and full JSON forms.
@@ -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,51 @@ 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;
}
}
}
/** ServerLevel.getEntity(id) over the level's entities. */
@Override public Entity getEntity(int id) {
if (entities == null) return null;
for (Entity e : entities) if (e.getId() == id && !e.isRemoved()) return e;
return null;
}
/** Every entity of the level (no area), as ServerLevel's entity getter would. */
@Override public <T extends Entity> void getEntities(net.minecraft.world.level.entity.EntityTypeTest<Entity, T> type, 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() && 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 +249,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 +314,12 @@ public final class VanillaBlockUpdateOracle {
return attributes;
}
@Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return OVERWORLD_TYPE; }
/** The overworld (fire in an obsidian frame lights a portal here). */
@Override public net.minecraft.resources.ResourceKey<net.minecraft.world.level.Level> dimension() { return net.minecraft.world.level.Level.OVERWORLD; }
@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 +407,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 +441,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) {
@@ -441,8 +517,34 @@ public final class VanillaBlockUpdateOracle {
return new BlockPos(a.get(0).getAsInt(), a.get(1).getAsInt(), a.get(2).getAsInt());
}
/**
* The chunk source bone meal reaches for: saplings, grass and moss place
* their features with `getChunkSource().getGenerator()`, which none of
* them reads beyond passing it along.
*/
static final class Chunks extends net.minecraft.server.level.ServerChunkCache {
static net.minecraft.world.level.chunk.ChunkGenerator generator;
private Chunks() {
super(null, null, null, null, null, null, 0, 0, false, null);
}
@Override
public net.minecraft.world.level.chunk.ChunkGenerator getGenerator() {
return generator;
}
/** Leads send entity link packets; nobody is tracking. */
@Override
public void sendToTrackingPlayers(final net.minecraft.world.entity.Entity entity, final net.minecraft.network.protocol.Packet<? super net.minecraft.network.protocol.game.ClientGamePacketListener> packet) {
}
}
static World build(JsonObject f) throws Exception {
World w = make(World.class);
// Saplings, grass and moss place features through the chunk source's generator.
if (Chunks.generator == null) Chunks.generator = make(net.minecraft.world.level.levelgen.FlatLevelSource.class);
set(net.minecraft.server.level.ServerLevel.class, w, "chunkSource", make(Chunks.class));
w.cells = new HashMap<>();
w.log = new StringBuilder();
w.blockEvents = new java.util.LinkedHashSet<>();
@@ -0,0 +1,246 @@
package dev.horizonlab.parity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.mojang.serialization.Dynamic;
import com.mojang.serialization.JsonOps;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Stream;
import net.minecraft.SharedConstants;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.*;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.util.datafix.DataFixTypes;
import net.minecraft.util.datafix.DataFixers;
import net.minecraft.util.worldupdate.UpgradeProgress;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.chunk.storage.RegionFile;
import net.minecraft.world.level.chunk.storage.RegionStorageInfo;
import net.minecraft.world.level.storage.LevelStorageSource;
/**
* Opens a world saved by an older game version the way 26.3 does and writes out
* what 26.3 reads: the file fixes (FileFixerUpper) on the folder, level.dat fixed
* to the current DataVersion, then every chunk, entity chunk and POI chunk
* (SimpleRegionStorage.upgradeChunkTag with ChunkMap's context), player file
* (PlayerDataStorage.load), saved data file (SavedDataStorage.readTagFromDisk),
* advancements and statistics through the real DataFixers.
*
* VanillaDataFixOracle IN_WORLD OUT_WORLD
*
* Files the game rewrites after loading get the current DataVersion so that the
* output compares with what the game would save. Nothing is answered by hand.
*/
public final class VanillaDataFixOracle {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
Path in = Path.of(args[0]);
Path out = Path.of(args[1]);
copy(in, out);
int current = SharedConstants.getCurrentVersion().dataVersion().version();
var fixer = DataFixers.getDataFixer();
// FileFixerUpper.fix through a real level storage access, as the game opens a
// world: the file fixes on a copy-on-write view swapped in, then level.dat
// fixed to the current version and stamped (DataVersion, LastPlayed, Version).
LevelStorageSource source = LevelStorageSource.createDefault(out.getParent());
try (LevelStorageSource.LevelStorageAccess access = source.createAccess(out.getFileName().toString())) {
Dynamic<?> levelData = access.getUnfixedDataTag(false);
Dynamic<?> fixed = DataFixers.getFileFixer().fix(access, levelData, new UpgradeProgress());
access.saveLevelData(fixed);
}
Files.deleteIfExists(out.resolve("level.dat_old"));
Map<String, String> generators = generators(out);
Path dimensions = out.resolve("dimensions");
if (Files.isDirectory(dimensions)) {
List<Path> dims;
try (Stream<Path> s = Files.walk(dimensions, 2)) {
dims = s.filter(p -> dimensions.relativize(p).getNameCount() == 2).sorted().toList();
}
for (Path dim : dims) {
String id = dim.getParent().getFileName() + ":" + dim.getFileName();
ResourceKey<Level> key = ResourceKey.create(Registries.DIMENSION, Identifier.parse(id));
String generator = generators.get(id);
CompoundTag context = ChunkMap.getChunkDataFixContextTag(
key, Optional.ofNullable(generator).map(Identifier::parse));
upgradeRegions(dim.resolve("region"), key, "chunk", DataFixTypes.CHUNK, -1, context, current);
upgradeRegions(dim.resolve("entities"), key, "entities", DataFixTypes.ENTITY_CHUNK, -1, null, current);
upgradeRegions(dim.resolve("poi"), key, "poi", DataFixTypes.POI_CHUNK, 1945, null, current);
upgradeSavedData(dim.resolve("data"), current);
}
}
upgradeSavedData(out.resolve("data"), current);
for (Path file : list(out.resolve("players/data"), ".dat")) {
CompoundTag tag = NbtIo.readCompressed(file, NbtAccounter.unlimitedHeap());
tag = DataFixTypes.PLAYER.updateToCurrentVersion(fixer, tag, NbtUtils.getDataVersion(tag));
NbtIo.writeCompressed(NbtUtils.addDataVersion(tag, current), file);
}
for (Path file : list(out.resolve("players/advancements"), ".json")) {
// PlayerAdvancements: DataFixTypes.ADVANCEMENTS.wrapCodec, default version 1343.
JsonElement json = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8));
var dynamic = new Dynamic<>(JsonOps.INSTANCE, json);
int from = dynamic.get("DataVersion").asInt(1343);
var fixed = DataFixTypes.ADVANCEMENTS.updateToCurrentVersion(fixer, dynamic.remove("DataVersion"), from);
fixed = fixed.set("DataVersion", fixed.createInt(current));
Files.writeString(file, GSON.toJson(fixed.getValue()), StandardCharsets.UTF_8);
}
for (Path file : list(out.resolve("players/stats"), ".json")) {
// ServerStatsCounter.parse: the version field stays in the data.
JsonElement json = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8));
var dynamic = new Dynamic<>(JsonOps.INSTANCE, json);
var fixed = DataFixTypes.STATS.updateToCurrentVersion(fixer, dynamic, NbtUtils.getDataVersion(dynamic, 1343));
fixed = fixed.set("DataVersion", fixed.createInt(current));
Files.writeString(file, GSON.toJson(fixed.getValue()), StandardCharsets.UTF_8);
}
}
/** Chunk generator type per dimension, from the saved world generation settings. */
private static Map<String, String> generators(Path world) throws Exception {
Map<String, String> out = new HashMap<>();
Path file = world.resolve("data/minecraft/world_gen_settings.dat");
if (!Files.exists(file)) {
return out;
}
CompoundTag tag = NbtIo.readCompressed(file, NbtAccounter.unlimitedHeap());
CompoundTag dims = tag.getCompoundOrEmpty("data").getCompoundOrEmpty("dimensions");
for (String dim : dims.keySet()) {
dims.getCompoundOrEmpty(dim).getCompoundOrEmpty("generator").getString("type").ifPresent(t -> out.put(dim, t));
}
return out;
}
private static void upgradeRegions(Path folder, ResourceKey<Level> dimension, String type, DataFixTypes fixType,
int defaultVersion, CompoundTag context, int current) throws Exception {
if (!Files.isDirectory(folder)) {
return;
}
var fixer = DataFixers.getDataFixer();
for (Path file : list(folder, ".mca")) {
String[] parts = file.getFileName().toString().split("\\.");
int rx = Integer.parseInt(parts[1]);
int rz = Integer.parseInt(parts[2]);
RegionStorageInfo info = new RegionStorageInfo("oracle", dimension, type);
Map<ChunkPos, CompoundTag> chunks = new LinkedHashMap<>();
try (RegionFile region = new RegionFile(info, file, folder, false)) {
for (int z = 0; z < 32; z++) {
for (int x = 0; x < 32; x++) {
ChunkPos pos = new ChunkPos(rx * 32 + x, rz * 32 + z);
if (!region.hasChunk(pos)) {
continue;
}
try (DataInputStream in = region.getChunkDataInputStream(pos)) {
if (in != null) {
chunks.put(pos, NbtIo.read(in));
}
}
}
}
}
Files.delete(file);
try (RegionFile region = new RegionFile(info, file, folder, false)) {
for (var entry : chunks.entrySet()) {
CompoundTag tag = entry.getValue();
int version = NbtUtils.getDataVersion(tag, defaultVersion);
if (version < current) {
// SimpleRegionStorage.upgradeChunkTag
if (context != null) {
tag.put("__context", context.copy());
}
tag = fixType.update(fixer, tag, version, current);
tag.remove("__context");
NbtUtils.addDataVersion(tag, current);
}
try (DataOutputStream o = region.getChunkDataOutputStream(entry.getKey())) {
NbtIo.write(tag, o);
}
}
}
}
}
/** SavedDataStorage.readTagFromDisk for every known saved data file under a data folder. */
private static void upgradeSavedData(Path data, int current) throws Exception {
if (!Files.isDirectory(data)) {
return;
}
List<Path> files;
try (Stream<Path> s = Files.walk(data)) {
files = s.filter(p -> p.toString().endsWith(".dat")).sorted().toList();
}
var fixer = DataFixers.getDataFixer();
for (Path file : files) {
String rel = data.relativize(file).toString().replace('\\', '/');
DataFixTypes type = savedDataType(rel);
if (type == null) {
continue;
}
CompoundTag tag = NbtIo.readCompressed(file, NbtAccounter.unlimitedHeap());
int version = NbtUtils.getDataVersion(tag, 1343);
tag = type.update(fixer, tag, version, current);
NbtIo.writeCompressed(NbtUtils.addDataVersion(tag, current), file);
}
}
/** The SavedDataType registered for a file below data/ (namespace/path.dat). */
static DataFixTypes savedDataType(String rel) {
String name = rel.endsWith(".dat") ? rel.substring(0, rel.length() - 4) : rel;
if (name.endsWith("/command_storage")) {
return DataFixTypes.SAVED_DATA_COMMAND_STORAGE;
}
if (name.matches("minecraft/maps/\\d+")) {
return DataFixTypes.SAVED_DATA_MAP_DATA;
}
return switch (name) {
case "minecraft/custom_boss_events" -> DataFixTypes.SAVED_DATA_CUSTOM_BOSS_EVENTS;
case "minecraft/scoreboard" -> DataFixTypes.SAVED_DATA_SCOREBOARD;
case "minecraft/chunk_tickets" -> DataFixTypes.SAVED_DATA_FORCED_CHUNKS;
case "minecraft/world_border" -> DataFixTypes.SAVED_DATA_WORLD_BORDER;
case "minecraft/game_rules" -> DataFixTypes.SAVED_DATA_GAME_RULES;
case "minecraft/ender_dragon_fight" -> DataFixTypes.SAVED_DATA_ENDER_DRAGON_FIGHT;
case "minecraft/wandering_trader" -> DataFixTypes.SAVED_DATA_WANDERING_TRADER;
case "minecraft/maps/last_id" -> DataFixTypes.SAVED_DATA_MAP_INDEX;
case "minecraft/weather" -> DataFixTypes.SAVED_DATA_WEATHER;
case "minecraft/scheduled_events" -> DataFixTypes.SAVED_DATA_SCHEDULED_EVENTS;
case "minecraft/world_gen_settings" -> DataFixTypes.SAVED_DATA_WORLD_GEN_SETTINGS;
case "minecraft/random_sequences" -> DataFixTypes.SAVED_DATA_RANDOM_SEQUENCES;
case "minecraft/stopwatches" -> DataFixTypes.SAVED_DATA_STOPWATCHES;
case "minecraft/raids" -> DataFixTypes.SAVED_DATA_RAIDS;
case "minecraft/world_clocks" -> DataFixTypes.SAVED_DATA_WORLD_CLOCKS;
default -> null;
};
}
private static List<Path> list(Path folder, String suffix) throws Exception {
if (!Files.isDirectory(folder)) {
return List.of();
}
try (Stream<Path> s = Files.list(folder)) {
return s.filter(p -> p.getFileName().toString().endsWith(suffix)).sorted().toList();
}
}
private static void copy(Path from, Path to) throws Exception {
try (Stream<Path> s = Files.walk(from)) {
for (Path p : s.sorted().toList()) {
Path target = to.resolve(from.relativize(p).toString());
if (Files.isDirectory(p)) {
Files.createDirectories(target);
} else if (!p.getFileName().toString().equals("session.lock")) {
Files.copy(p, target, StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
}
@@ -0,0 +1,288 @@
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 three times: 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 1501 -> "minecraft:block.lava.extinguish";
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();
// Three runs: a value from an unseeded random rarely repeats thrice.
List<String> a = attempt(f), b = attempt(f), c = attempt(f);
out.print("case " + index++ + "\n");
for (String s : merge(merge(a, b), c)) 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();
if (System.getenv("ORACLE_TRACE") != null) c.printStackTrace();
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;
}
// A token already marked in an earlier merge stays marked.
for (int j = 0; j < p.length; j++) if (!p[j].equals(q[j]) && !p[j].startsWith("~")) 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")) {
List<Entity> created = new ArrayList<>();
for (var e : f.getAsJsonArray("entities")) {
Entity ent = target(w, e.getAsJsonObject());
created.add(ent);
w.entities.add(ent);
}
var list = f.getAsJsonArray("entities");
for (int i = 0; i < list.size(); i++) {
var e = list.get(i).getAsJsonObject();
if (e.has("leash") && created.get(i) instanceof Leashable leashable) {
leashable.setLeashedTo(created.get(e.get("leash").getAsInt()), true);
}
}
}
// 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");
if (e instanceof Leashable leashable && leashable.isLeashed()) line.append(" leashed");
return line.toString();
}
}
+418
View File
@@ -0,0 +1,418 @@
"""Scenes for tools/datafix_worlds.py: block entities, entities and items in the save
formats of older game versions, placed by console commands of that version.
Three syntax eras matter for the commands:
A before 1.20.5 (DataVersion < 3818): item `tag` NBT, `Count`, JSON text strings
B 1.20.5 to 1.21.4 (< 4325): item components, JSON text strings
C 1.21.5 and later: item components, SNBT text components, `equipment`
Every entry is (minimum DataVersion, command template). `{x} {y} {z}` are filled
with a free position; entities get a fixed UUID so outputs can be matched.
"""
A, B, C = 'A', 'B', 'C'
def era(version):
return A if version < 3818 else B if version < 4325 else C
def text(e, s):
"""A text component value for NBT: JSON string (A/B) or SNBT compound (C)."""
if e == C:
return '{text:"%s"}' % s
return "'{\"text\":\"%s\"}'" % s
# ------------------------------------------------------------------ items, era A
ITEMS_A = [
'{id:"minecraft:diamond_sword",Count:1b,tag:{Damage:5,RepairCost:3,Unbreakable:1b,HideFlags:255,'
'Enchantments:[{id:"minecraft:sharpness",lvl:3s},{id:"minecraft:sweeping",lvl:2s}],'
'display:{Name:\'{"text":"Blade","color":"red","italic":false}\',Lore:[\'{"text":"line one"}\',\'"plain"\']},'
'AttributeModifiers:[{AttributeName:"generic.attack_damage",Name:"x",Amount:2.5d,Operation:0,'
'UUID:[I;1,2,3,4],Slot:"mainhand"}],CustomModelData:7}}',
'{id:"minecraft:enchanted_book",Count:1b,tag:{StoredEnchantments:[{id:"minecraft:mending",lvl:1s}]}}',
'{id:"minecraft:written_book",Count:1b,tag:{title:"Title",author:"Me",generation:1,resolved:1b,'
'pages:[\'{"text":"page one","bold":true}\',\'{"text":"two","clickEvent":{"action":"change_page","value":"2"},'
'"hoverEvent":{"action":"show_text","value":"hi"}}\'],filtered_pages:{"1":\'"f"\'}}}',
'{id:"minecraft:writable_book",Count:1b,tag:{pages:["draft one","draft two"]}}',
'{id:"minecraft:potion",Count:1b,tag:{Potion:"minecraft:strong_healing",CustomPotionColor:255}}',
'{id:"minecraft:splash_potion",Count:1b,tag:{CustomPotionEffects:[{Id:1b,Amplifier:1b,Duration:200}]}}',
'{id:"minecraft:tipped_arrow",Count:5b,tag:{Potion:"minecraft:poison"}}',
'{id:"minecraft:suspicious_stew",Count:1b,tag:{Effects:[{EffectId:3,EffectDuration:160}]}}',
'{id:"minecraft:firework_rocket",Count:3b,tag:{Fireworks:{Flight:2b,Explosions:[{Type:1b,Colors:[I;255],'
'FadeColors:[I;16711680],Trail:1b,Flicker:0b}]}}}',
'{id:"minecraft:firework_star",Count:1b,tag:{Explosion:{Type:3b,Colors:[I;65280]}}}',
'{id:"minecraft:player_head",Count:1b,tag:{SkullOwner:{Name:"Notch",Id:[I;1,2,3,4],'
'Properties:{textures:[{Value:"abc",Signature:"sig"}]}}}}',
'{id:"minecraft:player_head",Count:1b,tag:{SkullOwner:"jeb_"}}',
'{id:"minecraft:filled_map",Count:1b,tag:{map:3,display:{MapColor:255},Decorations:[{id:"x",type:9b,x:1.0d,z:2.0d,rot:180.0d}]}}',
'{id:"minecraft:compass",Count:1b,tag:{LodestonePos:{X:1,Y:2,Z:3},LodestoneDimension:"minecraft:overworld",LodestoneTracked:0b}}',
'{id:"minecraft:crossbow",Count:1b,tag:{Charged:1b,ChargedProjectiles:[{id:"minecraft:arrow",Count:1b}]}}',
'{id:"minecraft:shield",Count:1b,tag:{BlockEntityTag:{Base:4,Patterns:[{Pattern:"cre",Color:15},{Pattern:"bs",Color:1}]}}}',
'{id:"minecraft:white_banner",Count:1b,tag:{BlockEntityTag:{Patterns:[{Pattern:"mr",Color:9}]},'
'display:{Name:\'{"translate":"block.minecraft.ominous_banner","color":"gold"}\'}}}',
'{id:"minecraft:red_shulker_box",Count:1b,tag:{BlockEntityTag:{Items:[{Slot:3b,id:"minecraft:stone",Count:9b},'
'{Slot:0b,id:"minecraft:golden_apple",Count:2b,tag:{display:{Name:\'"Gold"\'}}}],Lock:"key",'
'CustomName:\'{"text":"Box"}\'}}}',
'{id:"minecraft:chest",Count:1b,tag:{BlockEntityTag:{LootTable:"minecraft:chests/simple_dungeon",LootTableSeed:5L}}}',
'{id:"minecraft:pig_spawn_egg",Count:1b,tag:{EntityTag:{CustomName:\'"Babe"\',Age:-24000}}}',
'{id:"minecraft:armor_stand",Count:1b,tag:{EntityTag:{Small:1b}}}',
'{id:"minecraft:pig_spawn_egg",Count:1b,tag:{EntityTag:{id:"minecraft:cow"}}}',
'{id:"minecraft:leather_chestplate",Count:1b,tag:{display:{color:16711680},'
'Trim:{material:"minecraft:gold",pattern:"minecraft:coast"}}}',
'{id:"minecraft:goat_horn",Count:1b,tag:{instrument:"minecraft:sing_goat_horn"}}',
'{id:"minecraft:axolotl_bucket",Count:1b,tag:{Variant:2,Age:-100,Health:7.0f,NoAI:1b}}',
'{id:"minecraft:tropical_fish_bucket",Count:1b,tag:{BucketVariantTag:65536}}',
'{id:"minecraft:knowledge_book",Count:1b,tag:{Recipes:["minecraft:stone"]}}',
'{id:"minecraft:debug_stick",Count:1b,tag:{DebugProperty:{"minecraft:oak_stairs":"facing"}}}',
'{id:"minecraft:diamond_pickaxe",Count:1b,tag:{CanDestroy:["minecraft:stone","#minecraft:logs",'
'"minecraft:oak_stairs[facing=east]"],HideFlags:8}}',
'{id:"minecraft:stone",Count:4b,tag:{CanPlaceOn:["minecraft:dirt"],BlockStateTag:{}}}',
'{id:"minecraft:oak_slab",Count:1b,tag:{BlockStateTag:{type:"top",waterlogged:1b}}}',
'{id:"minecraft:grass",Count:2b}',
'{id:"minecraft:scute",Count:2b}',
'{id:"minecraft:chain",Count:1b}',
'{id:"minecraft:decorated_pot",Count:1b,tag:{BlockEntityTag:{sherds:["minecraft:brick","minecraft:angler_pottery_sherd",'
'"minecraft:brick","minecraft:arms_up_pottery_sherd"]}}}',
'{id:"minecraft:beehive",Count:1b,tag:{BlockEntityTag:{Bees:[{EntityData:{id:"minecraft:bee"},TicksInHive:3,'
'MinOccupationTicks:600}]}}}',
'{id:"minecraft:cooked_beef",Count:64b,tag:{custom:"data",nested:{a:1}}}',
'{id:"minecraft:iron_sword",Count:1b,tag:{Enchantments:[]}}',
'{id:"minecraft:bow",Count:1b,tag:{Enchantments:[{id:"minecraft:power",lvl:0s}],HideFlags:1}}',
]
# ------------------------------------------------------------------ items, era B/C
ITEMS_B = [
'{id:"minecraft:diamond_sword",count:1,components:{"minecraft:damage":5,"minecraft:repair_cost":3,'
'"minecraft:unbreakable":{show_in_tooltip:false},"minecraft:enchantments":{levels:{"minecraft:sharpness":3}},'
'"minecraft:custom_name":\'{"text":"Blade","color":"red"}\',"minecraft:lore":[\'"plain"\'],'
'"minecraft:attribute_modifiers":{modifiers:[{type:"minecraft:generic.attack_damage",id:"minecraft:x",'
'amount:2.5d,operation:"add_value",slot:"mainhand"}]}}}',
'{id:"minecraft:written_book",count:1,components:{"minecraft:written_book_content":{title:{raw:"T"},author:"Me",'
'pages:[{raw:\'{"text":"p1","clickEvent":{"action":"run_command","value":"/say hi"}}\'}]}}}',
'{id:"minecraft:potion",count:1,components:{"minecraft:potion_contents":{potion:"minecraft:healing"}}}',
'{id:"minecraft:white_banner",count:1,components:{"minecraft:banner_patterns":[{pattern:"minecraft:creeper",color:"black"}],'
'"minecraft:item_name":\'{"translate":"block.minecraft.ominous_banner"}\',"minecraft:rarity":"uncommon"}}',
'{id:"minecraft:red_shulker_box",count:1,components:{"minecraft:container":[{slot:0,item:{id:"minecraft:stone",count:3}}],'
'"minecraft:lock":"key"}}',
'{id:"minecraft:apple",count:2,components:{"minecraft:food":{nutrition:4,saturation:2.4f,can_always_eat:true,'
'eat_seconds:1.0f}}}',
'{id:"minecraft:netherite_sword",count:1,components:{"minecraft:fire_resistant":{}}}',
'{id:"minecraft:stick",count:1,components:{"minecraft:custom_model_data":5}}',
'{id:"minecraft:pig_spawn_egg",count:1,components:{"minecraft:entity_data":{id:"minecraft:pig",Age:-200}}}',
'{id:"minecraft:diamond_helmet",count:1,components:{"minecraft:hide_additional_tooltip":{},'
'"minecraft:trim":{material:"minecraft:gold",pattern:"minecraft:coast",show_in_tooltip:false}}}',
'{id:"minecraft:decorated_pot",count:1,components:{"minecraft:pot_decorations":["minecraft:brick",'
'"minecraft:angler_pottery_sherd"]}}',
'{id:"minecraft:chain",count:1}',
]
ITEMS_C = [
'{id:"minecraft:diamond_sword",count:1,components:{"minecraft:damage":5,'
'"minecraft:custom_name":{text:"Blade",color:"red"},"minecraft:tooltip_display":{hidden_components:["minecraft:damage"]}}}',
'{id:"minecraft:written_book",count:1,components:{"minecraft:written_book_content":{title:{raw:"T"},author:"Me",'
'pages:[{raw:{text:"p1",click_event:{action:"change_page",page:2}}}]}}}',
'{id:"minecraft:decorated_pot",count:1,components:{"minecraft:pot_decorations":["minecraft:brick",'
'"minecraft:angler_pottery_sherd"]}}',
'{id:"minecraft:filled_map",count:1,components:{"minecraft:map_id":2,"minecraft:map_color":255}}',
'{id:"minecraft:chain",count:1}',
'{id:"minecraft:name_tag",count:1,components:{"minecraft:custom_name":"Bob"}}',
]
def experiments(version):
"""Experimental data packs a world of `version` turns on, so that the blocks behind
them exist and the feature-flag fixes have flags to remove."""
packs = []
if 3218 <= version < 3440:
packs.append('update_1_20')
if 3698 <= version < 3939:
packs.append('update_1_21')
if 3700 <= version < 4067:
packs.append('bundle')
if 4080 <= version < 4180:
packs.append('winter_drop')
return packs
def items(e, version=None):
"""The sample stacks of an era, in the exact component formats `version` accepts."""
stacks = ITEMS_A if e == A else ITEMS_B if e == B else ITEMS_C
if version is None:
return stacks
return [v for v in (versioned(s, version) for s in stacks) if available(v, version)]
# Items era A worlds older than each DataVersion do not have.
ITEM_SINCE = {
'minecraft:goat_horn': 3105,
'minecraft:decorated_pot': 3327,
}
def available(stack, version):
return all(version >= since for item, since in ITEM_SINCE.items() if f'"{item}"' in stack)
def versioned(stack, version):
"""Rewrite the components whose format changed inside an era."""
if version < 3448: # 1.19.4: pots hold shards, sherds were pottery_shard_*
stack = (stack.replace('sherds:', 'shards:')
.replace('"minecraft:angler_pottery_sherd"', '"minecraft:pottery_shard_prize"')
.replace('"minecraft:arms_up_pottery_sherd"', '"minecraft:pottery_shard_arms_up"')
.replace('"minecraft:skull_pottery_sherd"', '"minecraft:pottery_shard_skull"'))
if version >= 4541: # chain renamed to iron_chain
stack = stack.replace('"minecraft:chain"', '"minecraft:iron_chain"')
if '"minecraft:attribute_modifiers"' in stack:
if version < 3945: # 1.20.5: modifiers are named and carry a UUID
stack = stack.replace('id:"minecraft:x",', 'uuid:[I;1,2,3,4],name:"x",')
if version >= 4055: # 1.21.2: attribute ids lose their generic. prefix
stack = stack.replace('minecraft:generic.attack_damage', 'minecraft:attack_damage')
if version >= 4068: # 1.21.2: a lock is an item predicate
stack = stack.replace('"minecraft:lock":"key"', '"minecraft:lock":{items:"minecraft:stick"}')
if version >= 4064: # 1.21.2: fire_resistant became damage_resistant
stack = stack.replace('"minecraft:fire_resistant":{}', '"minecraft:damage_resistant":{types:"#minecraft:is_fire"}')
if version >= 4059: # 1.21.2: food lost eat_seconds (now in consumable)
stack = stack.replace(',eat_seconds:1.0f', '')
if version >= 4175: # 1.21.4: custom model data holds lists
stack = stack.replace('"minecraft:custom_model_data":5', '"minecraft:custom_model_data":{floats:[5.0f]}')
return stack
def slotted(stacks):
out = []
for i, s in enumerate(stacks[:27]):
out.append(s[:1] + f'Slot:{i}b,' + s[1:])
return '[' + ','.join(out) + ']'
def chests(e, version=None):
"""Chests holding every sample item (27 per chest)."""
st = items(e, version)
return [st[i:i + 27] for i in range(0, len(st), 27)]
# ------------------------------------------------------------------ block entities
def block_entities(e, version):
name = lambda s: text(e, s)
out = []
for group in chests(e, version):
out.append(('chest', f'{{Items:{slotted(group)},CustomName:{name("Stash")}}}'))
sign_a = ('{front_text:{messages:[\'{"text":"one"}\',\'"two"\',\'""\',\'""\'],color:"red",has_glowing_text:1b},'
'back_text:{messages:[\'"b"\',\'""\',\'""\',\'""\'],filtered_messages:[\'"x"\',\'""\',\'""\',\'""\']},'
'is_waxed:1b}')
sign_c = ('{front_text:{messages:[{text:"one"},"two","",""],color:"red",has_glowing_text:1b},'
'back_text:{messages:["b","","",""]},is_waxed:1b}')
# Before 1.20 (3439) a sign has one side of loose Text fields.
sign_old = ('{Text1:\'{"text":"one"}\',Text2:\'"two"\',Text3:\'""\',Text4:\'""\',Color:"red",GlowingText:1b,'
'FilteredText1:\'"x"\'}')
sign = sign_c if e == C else sign_a if version >= 3439 else sign_old
out.append(('oak_sign', sign))
if version >= 3218: # hanging signs: 1.19.3 with the 1.20 experiment
out.append(('oak_hanging_sign', sign))
if e == A:
out += [
('white_banner', '{Patterns:[{Pattern:"cre",Color:15}],CustomName:\'{"translate":"block.minecraft.ominous_banner"}\'}'),
('player_head', '{SkullOwner:{Name:"Notch",Id:[I;1,2,3,4]}}'),
('decorated_pot', '{sherds:["minecraft:brick","minecraft:skull_pottery_sherd","minecraft:brick","minecraft:brick"]}'),
('beehive', '{Bees:[{EntityData:{id:"minecraft:bee",CustomName:\'"Bz"\'},TicksInHive:2,MinOccupationTicks:400}],'
'FlowerPos:{X:1,Y:2,Z:3}}'),
('furnace', '{BurnTime:100s,CookTime:20s,CookTimeTotal:200s,Items:[{Slot:0b,id:"minecraft:iron_ore",Count:3b}],'
'RecipesUsed:{"minecraft:iron_ingot":2}}'),
('jukebox', '{RecordItem:{id:"minecraft:music_disc_cat",Count:1b},RecordStartTick:100L,TickCount:250L,IsPlaying:1b}'),
('suspicious_sand', '{item:{id:"minecraft:emerald",Count:1b}}'),
('lectern', '{Book:{id:"minecraft:written_book",Count:1b,tag:{title:"L",author:"A",pages:[\'"x"\']}},Page:0}'),
('spawner', '{SpawnData:{entity:{id:"minecraft:zombie",ArmorItems:[{},{},{},{id:"minecraft:iron_helmet",Count:1b}]}},'
'SpawnPotentials:[{weight:1,data:{entity:{id:"minecraft:skeleton"}}}]}'),
('command_block', '{Command:"say hi",CustomName:\'"Cmd"\',LastOutput:\'{"text":"out"}\'}'),
('end_gateway', '{ExitPortal:{X:1,Y:70,Z:2},ExactTeleport:1b,Age:5L}'),
('chiseled_bookshelf', '{Items:[{Slot:1b,id:"minecraft:book",Count:1b}],last_interacted_slot:1}'),
('campfire', '{Items:[{Slot:0b,id:"minecraft:beef",Count:1b}],CookingTimes:[I;5,0,0,0],CookingTotalTimes:[I;600,0,0,0]}'),
('hopper', '{Items:[{Slot:0b,id:"minecraft:stone",Count:1b}],Lock:"key"}'),
('structure_block', '{name:"x:y",posX:1,posY:2,posZ:3,sizeX:4,sizeY:5,sizeZ:6,mode:"SAVE"}'),
('skeleton_skull', '{}'),
]
if version >= 3682:
out.append(('crafter', '{Items:[{Slot:0b,id:"minecraft:stone",Count:1b}],triggered:1,crafting_ticks_remaining:2}'))
# Blocks the 1.20 experiment brought in 1.19.3 and 1.19.4.
since = {'decorated_pot': 3327, 'suspicious_sand': 3327, 'chiseled_bookshelf': 3218}
out = [(b, versioned(nbt, version)) for b, nbt in out if version >= since.get(b, 0)]
else:
out += [
('white_banner', '{patterns:[{pattern:"minecraft:creeper",color:"black"}],CustomName:%s}' % name("Flag")),
('player_head', '{profile:{name:"Notch"}}'),
('decorated_pot', '{sherds:["minecraft:brick","minecraft:skull_pottery_sherd","minecraft:brick","minecraft:brick"]}'),
('furnace', '{BurnTime:100s,CookTime:20s,CookTimeTotal:200s,Items:[{Slot:0b,id:"minecraft:iron_ore",count:3}]}'
if version < 4181 else '{lit_time_remaining:100s,cooking_time_spent:20s,cooking_total_time:200s}'),
('jukebox', '{RecordItem:{id:"minecraft:music_disc_cat",count:1},ticks_since_song_started:5L}'),
('trial_spawner', '{required_player_range:10}'),
('vault', '{config:{key_item:{id:"minecraft:trial_key",count:1}}}'),
('crafter', '{Items:[{Slot:0b,id:"minecraft:stone",count:1}],triggered:1}'),
('spawner', '{SpawnData:{entity:{id:"minecraft:zombie"}}}'),
('hopper', '{Items:[{Slot:0b,id:"minecraft:stone",count:1}],lock:{items:"minecraft:stick"}}'
if version >= 4068 else '{Items:[{Slot:0b,id:"minecraft:stone",count:1}],Lock:"key"}'),
]
if version >= 4071:
out.append(('creaking_heart', ''))
if version >= 4533:
out.append(('oak_shelf', '{Items:[{Slot:0b,id:"minecraft:apple",count:1}]}'))
if version >= 4532:
out.append(('copper_golem_statue', ''))
return out
# ------------------------------------------------------------------ entities
def entities(e, version):
"""(id, SNBT fields) for summon; item fields in the era's form."""
if e == A:
sword = '{id:"minecraft:iron_sword",Count:1b,tag:{display:{Name:\'"S"\'}}}'
helmet = '{id:"minecraft:iron_helmet",Count:1b}'
out = [
('zombie', f'ArmorItems:[{{}},{{}},{{}},{helmet}],HandItems:[{sword},{{}}],ArmorDropChances:[0.1f,0.1f,0.1f,2.0f],'
'HandDropChances:[1.0f,0.085f],CustomName:\'"Zed"\''),
('villager', 'VillagerData:{profession:"minecraft:farmer",level:2,type:"minecraft:plains"},Xp:3,'
'Offers:{Recipes:[{buy:{id:"minecraft:wheat",Count:20b},buyB:{id:"minecraft:air",Count:1b},'
'sell:{id:"minecraft:emerald",Count:1b},maxUses:16,uses:1}]},Inventory:[{id:"minecraft:bread",Count:3b}]'),
('horse', 'Tame:1b,SaddleItem:{id:"minecraft:saddle",Count:1b},ArmorItem:{id:"minecraft:iron_horse_armor",Count:1b},'
'Attributes:[{Name:"minecraft:horse.jump_strength",Base:0.7d},{Name:"minecraft:generic.max_health",Base:20.0d,'
'Modifiers:[{Name:"m",Amount:1.0d,Operation:0,UUID:[I;5,6,7,8]}]}]'),
('llama', 'ChestedHorse:1b,Items:[{Slot:2b,id:"minecraft:apple",Count:1b}],DecorItem:{id:"minecraft:red_carpet",Count:1b}'),
('donkey', 'ChestedHorse:1b,Items:[{Slot:2b,id:"minecraft:apple",Count:1b}],SaddleItem:{id:"minecraft:saddle",Count:1b}'),
('wolf', 'Health:15.0f,Owner:[I;1,2,3,4],CollarColor:3b'),
('salmon', ''),
('armor_stand', f'ArmorItems:[{{}},{{}},{{}},{helmet}],HandItems:[{sword},{{}}],Small:1b'),
('item_frame', f'Item:{sword},Facing:3b'),
('item', 'Item:{id:"minecraft:written_book",Count:1b,tag:{pages:[\'"p"\'],title:"t",author:"a"}},PickupDelay:10s'),
('arrow', 'inGround:1b,Potion:"minecraft:poison",CustomPotionEffects:[{Id:19b,Duration:100}]'),
('trident', 'Trident:{id:"minecraft:trident",Count:1b},inGround:1b'),
('area_effect_cloud', 'Potion:"minecraft:healing",Particle:"entity_effect",Radius:2.0f,Duration:600'),
('potion', 'Item:{id:"minecraft:splash_potion",Count:1b,tag:{Potion:"minecraft:swiftness"}}'),
('falling_block', 'BlockState:{Name:"minecraft:sand"},Time:-1000,NoGravity:1b'),
('tnt', 'Fuse:80s'),
('tnt_minecart', 'TNTFuse:40'),
('chest_minecart', 'Items:[{Slot:0b,id:"minecraft:apple",Count:1b}]'),
('boat', 'Type:"spruce"'),
('chest_boat', 'Type:"birch",Items:[{Slot:0b,id:"minecraft:apple",Count:1b}]'),
('text_display', 'text:\'{"text":"Hi","bold":true}\''),
('item_display', 'item:{id:"minecraft:stone",Count:1b}'),
('pig', 'Saddle:1b'),
('cat', 'variant:"minecraft:black"'),
('fox', 'Type:"red"'),
('zombie_villager', 'VillagerData:{profession:"minecraft:none",level:1,type:"minecraft:plains"}'),
('wandering_trader', ''),
('piglin', 'Inventory:[{id:"minecraft:gold_ingot",Count:2b}]'),
('firework_rocket', 'FireworksItem:{id:"minecraft:firework_rocket",Count:1b,tag:{Fireworks:{Flight:1b}}}'),
('allay', 'Inventory:[{id:"minecraft:diamond",Count:1b}]'),
('goat', ''),
]
since = {'allay': 3105, 'chest_boat': 3105, 'text_display': 3325, 'item_display': 3325}
out = [(k, x) for k, x in out if version >= since.get(k, 0)]
if version < 3086: # cats before 1.19 have a numeric CatType
out = [(k, 'CatType:1' if k == 'cat' else x) for k, x in out]
if 3105 <= version < 3322: # darkness counts its factor from a timestamp before 1.19.4
out.append(('pig', 'ActiveEffects:[{Id:33b,Amplifier:0b,Duration:200,ShowParticles:1b,'
'FactorCalculationData:{padding_duration:22,factor_start:0.0f,factor_target:1.0f,'
'factor_current:0.0f,effect_changed_timestamp:5,factor_previous_frame:0.0f,'
'had_effect_last_tick:0b}}]'))
return out
sword = '{id:"minecraft:iron_sword",count:1}'
helmet = '{id:"minecraft:iron_helmet",count:1}'
name = lambda s: text(e, s)
if e == B:
out = [
('zombie', f'ArmorItems:[{{}},{{}},{{}},{helmet}],HandItems:[{sword},{{}}],ArmorDropChances:[0.1f,0.1f,0.1f,2.0f],'
f'CustomName:{name("Zed")}'),
('horse', 'Tame:1b,SaddleItem:{id:"minecraft:saddle",count:1},body_armor_item:{id:"minecraft:iron_horse_armor",count:1}'),
('llama', 'ChestedHorse:1b,Items:[{Slot:2b,id:"minecraft:apple",count:1}],body_armor_item:{id:"minecraft:red_carpet",count:1}'),
('area_effect_cloud', 'potion_contents:{potion:"minecraft:healing"},Particle:{type:"minecraft:entity_effect",color:255},Duration:600'),
('potion', 'Item:{id:"minecraft:lingering_potion",count:1}'),
('tnt_minecart', 'TNTFuse:40' if version < 4173 else 'fuse:40'),
('salmon', ''),
('item_frame', f'Item:{sword},Facing:3b'),
('arrow', 'inGround:1b,item:{id:"minecraft:arrow",count:1}'),
('text_display', f'text:{name("Hi")}'),
('villager', 'VillagerData:{profession:"minecraft:farmer",level:2,type:"minecraft:plains"}'),
('pig', 'Saddle:1b'),
('falling_block', 'BlockState:{Name:"minecraft:sand"},Time:-1000,NoGravity:1b'),
]
if version >= 4067:
out.append(('pale_oak_chest_boat' if version >= 4070 else 'oak_chest_boat', 'Items:[{Slot:0b,id:"minecraft:apple",count:1}]'))
else:
out.append(('chest_boat', 'Type:"birch",Items:[{Slot:0b,id:"minecraft:apple",count:1}]'))
return out
out = [
('zombie', f'equipment:{{head:{helmet},mainhand:{sword}}},drop_chances:{{head:2.0f}},CustomName:{name("Zed")}'),
('horse', 'Tame:1b,equipment:{saddle:{id:"minecraft:saddle",count:1},body:{id:"minecraft:iron_horse_armor",count:1}}'),
('area_effect_cloud', 'potion_contents:{potion:"minecraft:healing"},Duration:600'),
('splash_potion' if version >= 4306 else 'potion', 'Item:{id:"minecraft:splash_potion",count:1}'),
('tnt_minecart', 'fuse:40'),
('text_display', f'text:{name("Hi")}'),
('villager', 'VillagerData:{profession:"minecraft:farmer",level:2,type:"minecraft:plains"}'),
('falling_block', 'BlockState:{Name:"minecraft:sand"},Time:-1000,NoGravity:1b'),
('trident', 'item:{id:"minecraft:trident",count:1},inGround:1b'),
]
if version >= 4531:
out.append(('copper_golem', ''))
if version >= 4543:
out.append(('mannequin', ''))
return out
def player_commands(e, name, version=None):
"""Give the joined bot a varied inventory and ender chest."""
out = []
stacks = items(e, version)
for i, stack in enumerate(stacks[:30]):
out.append(f'item replace entity {name} container.{i} with {give_form(e, stack)}')
out.append(f'item replace entity {name} enderchest.0 with {give_form(e, stacks[0])}')
out.append(f'item replace entity {name} armor.head with minecraft:iron_helmet')
out.append(f'xp set {name} 5 levels')
return out
def give_form(e, stack):
"""`item replace ... with` argument from a stack SNBT: id plus tag/components."""
import re
m = re.match(r'\{id:"([^"]+)",(?:Count:(\d+)b|count:(\d+))(?:,(tag|components):(.*))?\}$', stack, re.S)
item, count = m.group(1), m.group(2) or m.group(3)
if m.group(4) == 'tag':
return f'{item}{m.group(5)} {count}'
if m.group(4) == 'components':
body = m.group(5)[1:-1]
parts = split_top(body)
comps = []
for p in parts:
if p.startswith('"'):
end = p.index('"', 1)
key, value = p[1:end], p[end + 1:].lstrip()[1:]
else:
key, value = p.split(':', 1)
comps.append(f'{key}={value.strip()}')
comps = ','.join(comps)
return f'{item}[{comps}] {count}'
return f'{item} {count}'
def split_top(s):
"""Split SNBT compound contents at top-level commas."""
out, depth, cur, q = [], 0, '', None
for ch in s:
if q:
cur += ch
if ch == q:
q = None
continue
if ch in '"\'':
q = ch
elif ch in '{[':
depth += 1
elif ch in '}]':
depth -= 1
elif ch == ',' and depth == 0:
out.append(cur)
cur = ''
continue
cur += ch
if cur:
out.append(cur)
return out
+342
View File
@@ -0,0 +1,342 @@
#!/usr/bin/env python3
"""Make sample worlds with older vanilla servers, for the DataFixer harness.
For each listed version, the official server jar (cached under
.local/datafix/servers/VERSION/server.jar, beside the shared vanilla data) generates a default world around spawn,
gets a scene of block entities, entities and items in that version's own save
format (tools/datafix_scene.py), and a bot player joins (with its inventory filled)
so that player data exists. The saved world is kept in datafix/worlds/VERSION beside the shared vanilla data
(.local/datafix in a plain checkout), where every worktree finds it.
datafix_worlds.py [--force] [VERSION...] (default: every version below)
"""
import argparse
import hashlib
import json
import os
import queue
import re
import shutil
import socket
import struct
import subprocess
import sys
import threading
import time
import urllib.request
import uuid
import zipfile
import zlib
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import datafix_scene as scene # noqa: E402
ROOT = Path(__file__).resolve().parent.parent
LOCAL = ROOT / '.local' / 'datafix'
# Old server jars and their worlds are inputs, not outputs: keep them beside the
# vanilla data, which parallel worktrees share (.local/minecraft links there).
SHARED = (ROOT / '.local' / 'minecraft').resolve().parent / 'datafix'
VERSIONS = ['1.18.2', '1.19', '1.19.2', '1.19.3', '1.19.4', '1.20.1', '1.20.2', '1.20.4', '1.20.5', '1.20.6', '1.21.1',
'1.21.3', '1.21.4', '1.21.5', '1.21.6', '1.21.8', '1.21.9', '1.21.10', '1.21.11', '26.1', '26.1.2', '26.2']
MANIFEST = 'https://piston-meta.mojang.com/mc/game/version_manifest_v2.json'
BOT = 'Upgrader'
UUID_BASE = 0x6000
def server_jar(version):
path = SHARED / 'servers' / version / 'server.jar'
if not path.exists():
path.parent.mkdir(parents=True, exist_ok=True)
manifest = json.load(urllib.request.urlopen(MANIFEST))
entry = next(v for v in manifest['versions'] if v['id'] == version)
meta = json.load(urllib.request.urlopen(entry['url']))
download = meta['downloads']['server']
data = urllib.request.urlopen(download['url']).read()
if hashlib.sha1(data).hexdigest() != download['sha1']:
sys.exit(f'{version}: server.jar checksum mismatch')
path.write_bytes(data)
info = json.loads(zipfile.ZipFile(path).read('version.json'))
return path, info['world_version'], info['protocol_version']
class Server:
def __init__(self, directory, jar, port, packs=()):
directory.mkdir(parents=True, exist_ok=True)
(directory / 'eula.txt').write_text('eula=true\n')
props = {'server-port': port, 'online-mode': 'false', 'level-name': 'world', 'level-seed': '4242',
'view-distance': '4', 'simulation-distance': '4', 'spawn-protection': '0', 'sync-chunk-writes': 'true',
'enable-rcon': 'false', 'enable-query': 'false', 'max-tick-time': '-1'}
if packs:
props['initial-enabled-packs'] = ','.join(['vanilla', *packs])
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
self.process = subprocess.Popen(['java', '-Xmx2G', '-jar', str(jar), 'nogui'], cwd=directory,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
self.lines = []
self.queue = queue.Queue()
self.counter = 0
threading.Thread(target=self._pump, daemon=True).start()
self.wait('Done (', 600)
def _pump(self):
for line in self.process.stdout:
line = line.rstrip('\n')
self.lines.append(line)
self.queue.put(line)
def wait(self, pattern, timeout=60):
end = time.time() + timeout
seen = []
while time.time() < end:
try:
line = self.queue.get(timeout=1)
except queue.Empty:
if self.process.poll() is not None:
break
continue
seen.append(line)
if pattern in line:
return seen
raise TimeoutError(f'no "{pattern}" in {timeout}s; last lines: {seen[-5:]}')
def run(self, command, timeout=60):
self.counter += 1
marker = f'@@{self.counter}@@'
self.process.stdin.write(command + '\nsay ' + marker + '\n')
self.process.stdin.flush()
out = self.wait(marker, timeout)
return [re.sub(r'^\[[0-9:]+\] \[[^\]]*\]: ', '', l) for l in out[:-1]]
def stop(self):
try:
self.process.stdin.write('stop\n')
self.process.stdin.flush()
self.process.wait(120)
except Exception:
self.process.kill()
def failed(lines):
return [l for l in lines if re.search(r'(Unknown|Expected|Incorrect|Invalid|Could not|Unable|Failed|That block|'
r'error|Malformed|Can\'t)', l, re.I)]
# ------------------------------------------------------------------ minimal bot
def varint(v):
out = b''
v &= 0xFFFFFFFF
while True:
b = v & 0x7F
v >>= 7
out += bytes([b | (0x80 if v else 0)])
if not v:
return out
def mcstring(s):
data = s.encode()
return varint(len(data)) + data
def parse_varint(data, pos):
value = shift = 0
while True:
b = data[pos]
pos += 1
value |= (b & 0x7F) << shift
shift += 7
if not b & 0x80:
return pos, value
def offline_uuid(name):
digest = bytearray(hashlib.md5(('OfflinePlayer:' + name).encode()).digest())
digest[6] = (digest[6] & 0x0F) | 0x30
digest[8] = (digest[8] & 0x3F) | 0x80
return uuid.UUID(bytes=bytes(digest))
class Bot:
"""Logs in (offline mode) with the given protocol and stays until told to leave."""
def __init__(self, port, protocol, name):
self.sock = socket.create_connection(('127.0.0.1', port), timeout=30)
self.threshold = -1
self.buffer = b''
self.protocol = protocol
self.stop = threading.Event()
self.send(0, varint(protocol) + mcstring('127.0.0.1') + struct.pack('>H', port) + varint(2))
if protocol <= 758: # 1.18.2: the name only
self.send(0, mcstring(name))
elif protocol == 759: # 1.19: no signature data
self.send(0, mcstring(name) + b'\x00')
elif protocol == 760: # 1.19.2: no signature data, optional UUID
self.send(0, mcstring(name) + b'\x00' + b'\x01' + offline_uuid(name).bytes)
elif protocol <= 763: # 1.19.3 - 1.20.1: optional UUID
self.send(0, mcstring(name) + b'\x01' + offline_uuid(name).bytes)
else:
self.send(0, mcstring(name) + offline_uuid(name).bytes)
while True:
pid, data = self.receive()
if pid == 3:
self.threshold = parse_varint(data, 0)[1]
elif pid == 2:
break
elif pid == 0:
raise RuntimeError(f'login refused: {data!r}')
if protocol >= 764:
self.send(3) # login acknowledged -> configuration
self.configure()
threading.Thread(target=self.idle, daemon=True).start()
def configure(self):
old = self.protocol < 766 # 1.20.2 - 1.20.4 packet ids
finish, keep_alive, ping, disconnect = (2, 3, 4, 1) if old else (3, 4, 5, 2)
while True:
pid, data = self.receive()
if pid == finish:
self.send(2 if old else 3)
return
if pid == keep_alive:
self.send(3 if old else 4, data)
elif pid == ping:
self.send(4 if old else 5, data)
elif pid == disconnect:
raise RuntimeError(f'disconnected during configuration: {data!r}')
elif not old and self.known_packs(data):
self.send(7, varint(0)) # claim no packs: the server sends full registries
@staticmethod
def known_packs(data):
try:
pos, count = parse_varint(data, 0)
if count < 1:
return False
pos, n = parse_varint(data, pos)
return data[pos:pos + n] == b'minecraft'
except IndexError:
return False
def idle(self):
self.sock.settimeout(1.0)
while not self.stop.is_set():
try:
self.receive()
except socket.timeout:
continue
except (EOFError, OSError):
break
def leave(self):
self.stop.set()
time.sleep(1.5)
self.sock.close()
def read_exact(self, n):
while len(self.buffer) < n:
chunk = self.sock.recv(65536)
if not chunk:
raise EOFError('server closed the connection')
self.buffer += chunk
out, self.buffer = self.buffer[:n], self.buffer[n:]
return out
def read_varint(self):
value = shift = 0
while True:
b = self.read_exact(1)[0]
value |= (b & 0x7F) << shift
shift += 7
if not b & 0x80:
return value
def send(self, packet_id, payload=b''):
body = varint(packet_id) + payload
if self.threshold >= 0:
body = varint(len(body)) + zlib.compress(body) if len(body) >= self.threshold else varint(0) + body
self.sock.sendall(varint(len(body)) + body)
def receive(self):
length = self.read_varint()
body = self.read_exact(length)
if self.threshold >= 0:
pos, size = parse_varint(body, 0)
body = zlib.decompress(body[pos:]) if size else body[pos:]
pos, packet_id = parse_varint(body, 0)
return packet_id, body[pos:]
# ------------------------------------------------------------------ world
def uuid_nbt(i):
return f'[I;{UUID_BASE},0,0,{i}]'
def build(version, force=False):
jar, data_version, protocol = server_jar(version)
target = SHARED / 'worlds' / version
if target.exists() and not force:
print(f'{version}: kept {target}')
return []
era = scene.era(data_version)
work = LOCAL / 'gen' / version
shutil.rmtree(work, ignore_errors=True)
port = 30000 + (os.getpid() + data_version) % 20000
server = Server(work, jar, port, scene.experiments(data_version))
problems = []
def run(command):
out = server.run(command)
bad = failed(out)
if bad:
problems.append((command[:160], bad[:2]))
return out
run('forceload add -48 -48 79 79')
run('fill 0 99 0 47 99 47 minecraft:stone')
run('fill 0 100 0 47 112 47 minecraft:air')
for i, (block, nbt) in enumerate(scene.block_entities(era, data_version)):
x, z = 1 + 3 * (i % 15), 1 + 3 * (i // 15)
run(f'setblock {x} 100 {z} minecraft:{block}{nbt}')
for i, (kind, extra) in enumerate(scene.entities(era, data_version)):
x, z = 1.5 + 3 * (i % 15), 25.5 + 3 * (i // 15)
fields = f'UUID:{uuid_nbt(i)},NoAI:1b,Silent:1b,NoGravity:1b,Invulnerable:1b,PersistenceRequired:1b'
run(f'summon minecraft:{kind} {x} 100 {z} {{{fields}' + (',' + extra if extra else '') + '}')
run('setworldspawn 20 101 20')
bot = Bot(port, protocol, BOT)
time.sleep(3)
for command in scene.player_commands(era, BOT, data_version):
run(command)
time.sleep(3)
run('save-all flush')
time.sleep(2)
bot.leave()
time.sleep(2)
server.stop()
# Copy aside, then rename: an interrupted copy must not look like a finished world.
partial = target.with_name(target.name + '.partial')
shutil.rmtree(partial, ignore_errors=True)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(work / 'world', partial)
(partial / 'datafix-source.json').write_text(json.dumps(
{'version': version, 'data_version': data_version, 'problems': problems}, indent=1))
shutil.rmtree(target, ignore_errors=True)
partial.rename(target)
for command, out in problems:
print(f'{version}: command failed: {command}\n {out}')
print(f'{version}: DataVersion {data_version}, world in {target}')
return problems
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('versions', nargs='*')
p.add_argument('--force', action='store_true')
args = p.parse_args()
for version in args.versions or VERSIONS:
build(version, args.force)
if __name__ == '__main__':
main()
+222
View File
@@ -0,0 +1,222 @@
#!/usr/bin/env python3
"""DataFixer differential test: worlds saved by older game versions, upgraded by
vanilla 26.3 and by Horizon, must give the same data.
For every sample world in datafix/worlds beside the shared vanilla data (made by
tools/datafix_worlds.py with the official server jars of 1.18.2 to 26.2, and
generated automatically when missing), two upgrades run on a copy:
vanilla VanillaDataFixOracle: FileFixerUpper, then DataFixers on level.dat, every
chunk, entity chunk and POI chunk, player, saved data, advancements and
statistics file, exactly as 26.3 does when it opens the world
horizon the `datafix_world` example of horizon-world, which does the same with
horizon_world::datafix
Then every file is compared: region files chunk by chunk, NBT files and JSON
files value by value (compound and object key order does not matter). The only
tolerated differences are listed in IGNORED (wall-clock time).
test_datafix_parity.py [--keep] [--skip-build] [VERSION...]
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import anvil_dump # noqa: E402
ROOT = Path(__file__).resolve().parent.parent
LOCAL = ROOT / '.local' / 'datafix'
WORLDS = (ROOT / '.local' / 'minecraft').resolve().parent / 'datafix' / 'worlds'
RUN = LOCAL / 'run'
IGNORED = {
r'^level\.dat\.Data\.LastPlayed$': 'wall-clock time of the upgrade',
}
def java_classpath():
import oracle_harness as harness
import test_rust_parity as base
import test_model_baking_parity as baking
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = LOCAL / 'build'
build.mkdir(parents=True, exist_ok=True)
classes, dependencies, _ = harness.compile_oracle(build, 'VanillaDataFixOracle', jars, libraries,
lock['minecraft']['java_major'])
return str(classes) + os.pathsep + dependencies
def build_rust():
subprocess.run(['cargo', 'build', '--locked', '--release', '-p', 'horizon-world', '--example', 'datafix_world'],
cwd=ROOT, check=True)
meta = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'],
cwd=ROOT))
return Path(meta['target_directory']) / 'release' / 'examples' / 'datafix_world'
def run_vanilla(classpath, world, out):
shutil.rmtree(out, ignore_errors=True)
log = out.parent / (out.name + '.log')
with log.open('w') as f:
subprocess.run(['java', '-Xmx3g', '-Djava.awt.headless=true', '-cp', classpath,
'dev.horizonlab.parity.VanillaDataFixOracle', str(world), str(out)],
check=True, stdout=f, stderr=subprocess.STDOUT)
def run_horizon(binary, world, out):
shutil.rmtree(out, ignore_errors=True)
log = out.parent / (out.name + '.log')
with log.open('w') as f:
subprocess.run([str(binary), str(world), str(out)], check=True, stdout=f, stderr=subprocess.STDOUT)
# ---------------------------------------------------------------- comparison
def norm(v):
"""Python values from anvil_dump, with 26.3 mixed-list wrappers removed."""
if isinstance(v, dict):
return {k: norm(x) for k, x in v.items()}
if isinstance(v, list):
return [norm(x[''] if isinstance(x, dict) and list(x) == [''] else x) for x in v]
return v
def diff(a, b, path, out):
if type(a) is not type(b):
out.append((path, a, b))
elif isinstance(a, dict):
for k in sorted(set(a) | set(b), key=str):
if k not in a:
out.append((f'{path}.{k}', None, b[k]))
elif k not in b:
out.append((f'{path}.{k}', a[k], None))
else:
diff(a[k], b[k], f'{path}.{k}', out)
elif isinstance(a, list):
if len(a) != len(b):
out.append((f'{path}[len]', len(a), len(b)))
for i, (x, y) in enumerate(zip(a, b)):
diff(x, y, f'{path}[{i}]', out)
elif a != b:
out.append((path, a, b))
def read_json(path):
return json.loads(path.read_text(encoding='utf-8'))
def files(world):
out = set()
for p in world.rglob('*'):
if p.is_file() and p.name not in ('session.lock', 'datafix-source.json') and not p.name.endswith('_old'):
out.add(p.relative_to(world))
return out
def compare(vanilla, horizon):
report = []
a, b = files(vanilla), files(horizon)
for rel in sorted(a | b, key=str):
name = str(rel)
if rel not in b:
report.append((name, 'present', 'missing from Horizon'))
continue
if rel not in a:
report.append((name, 'missing from vanilla', 'present'))
continue
va, ha = vanilla / rel, horizon / rel
if name.endswith('.mca'):
vc, hc = anvil_dump.region_chunks(str(va)), anvil_dump.region_chunks(str(ha))
for key in sorted(set(vc) | set(hc)):
label = f'{name}{list(key)}'
if key not in hc:
report.append((label, 'present', 'missing from Horizon'))
elif key not in vc:
report.append((label, 'missing from vanilla', 'present'))
else:
out = []
diff(norm(vc[key]), norm(hc[key]), 'chunk', out)
report.extend((f'{p} @{label}', x, y) for p, x, y in out)
elif name.endswith('.dat'):
out = []
diff(norm(anvil_dump.read_dat(str(va))), norm(anvil_dump.read_dat(str(ha))), name, out)
report.extend(out)
elif name.endswith('.json'):
out = []
diff(read_json(va), read_json(ha), name, out)
report.extend(out)
elif va.read_bytes() != ha.read_bytes():
report.append((name, 'bytes differ', ''))
return report
def pattern_of(path):
return re.sub(r'\[\d+\]', '[]', path.split(' @')[0])
def summarize(report):
groups = {}
for path, a, b in report:
groups.setdefault(pattern_of(path), []).append((path, a, b))
failures = 0
for pattern, items in groups.items():
why = next((w for p, w in IGNORED.items() if re.search(p, pattern)), None)
if why:
print(f' ignored {pattern} x{len(items)} ({why})')
continue
failures += len(items)
path, a, b = items[0]
short = lambda v: (s := json.dumps(v, default=str))[:200] + ('...' if len(s) > 200 else '')
print(f' DIFF {pattern} x{len(items)}\n e.g. {path}\n vanilla {short(a)}\n horizon {short(b)}')
return failures
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('versions', nargs='*')
p.add_argument('--keep', action='store_true')
p.add_argument('--vanilla-only', action='store_true', help='only run the oracle')
p.add_argument('--binary', help='a prebuilt datafix_world example')
args = p.parse_args()
import datafix_worlds
import fcntl
WORLDS.parent.mkdir(parents=True, exist_ok=True)
with open(WORLDS.parent / 'generate.lock', 'w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX) # another worktree may be generating them
missing = [v for v in datafix_worlds.VERSIONS if not (WORLDS / v / 'level.dat').exists()]
if missing:
print('generating sample worlds:', ' '.join(missing), flush=True)
subprocess.run([sys.executable, str(ROOT / 'tools' / 'datafix_worlds.py'), *missing], cwd=ROOT, check=True)
worlds = sorted(p.name for p in WORLDS.iterdir() if p.is_dir())
versions = args.versions or worlds
classpath = java_classpath()
binary = None if args.vanilla_only else Path(args.binary) if args.binary else build_rust()
total = 0
for version in versions:
world = WORLDS / version
source = json.loads((world / 'datafix-source.json').read_text())
print(f'{version} (DataVersion {source["data_version"]})')
RUN.mkdir(parents=True, exist_ok=True)
run_vanilla(classpath, world, RUN / f'{version}-vanilla')
if binary is None:
continue
run_horizon(binary, world, RUN / f'{version}-horizon')
failures = summarize(compare(RUN / f'{version}-vanilla', RUN / f'{version}-horizon'))
print(f' {version}: {"ok" if not failures else f"{failures} differences"}')
total += failures
if binary is not None:
print('datafix parity', 'FAILED' if total else 'ok', f'({total} differences over {len(versions)} worlds)')
if not total and not args.keep:
shutil.rmtree(RUN, ignore_errors=True)
sys.exit(1 if total else 0)
if __name__ == '__main__':
main()
+468
View File
@@ -0,0 +1,468 @@
#!/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)
WOODS = ['oak', 'spruce', 'birch', 'jungle', 'acacia', 'cherry', 'dark_oak', 'mangrove', 'pale_oak', 'poplar']
# Items with the blocks and entities in front that exercise their behaviour:
# one entry per DispenseItemBehavior.bootStrap registration family, plus the
# defaults of DispenserBlock.getDefaultDispenseMethod (equippables, sulfur
# cube swallowables, spawn eggs, a plain drop).
ITEMS = {
'drop': [plain('stone', 5), plain('diamond'), plain('stick', 64), plain('oak_sapling', 3), plain('redstone', 2), plain('lead'),
plain('wheat_seeds', 7)],
'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('lime_shulker_box'), plain('carved_pumpkin'), plain('wither_skeleton_skull'),
plain('shears'), plain('brush')],
'vehicle': [plain('oak_boat'), plain('bamboo_raft'), plain('bamboo_chest_raft'), plain('minecart'), plain('chest_minecart'),
plain('furnace_minecart'), plain('tnt_minecart'), plain('hopper_minecart'), plain('command_block_minecart'),
plain('armor_stand', 2), 'BOAT', 'CHEST_BOAT'],
'spawn': [plain('pig_spawn_egg'), plain('sheep_spawn_egg', 2), plain('zombie_spawn_egg'), plain('cow_spawn_egg'),
plain('chicken_spawn_egg'), plain('skeleton_spawn_egg'), plain('creeper_spawn_egg'), plain('villager_spawn_egg'),
plain('wolf_spawn_egg'), plain('horse_spawn_egg'), plain('squid_spawn_egg'), plain('slime_spawn_egg')],
'equipment': [plain('iron_helmet'), plain('diamond_chestplate'), plain('leather_leggings'), plain('golden_boots'),
plain('chainmail_helmet'), plain('netherite_boots'), plain('turtle_helmet'), plain('saddle'),
plain('iron_horse_armor'), plain('diamond_horse_armor'), plain('leather_horse_armor'), plain('white_carpet'),
plain('red_carpet'), plain('chest'), plain('carved_pumpkin'), plain('elytra'), plain('wolf_armor'), plain('shears'),
plain('brush'), plain('player_head'), plain('zombie_head'), plain('white_harness')],
'swallow': [plain('slime_block'), plain('oak_planks', 3), plain('packed_ice'), plain('soul_sand'), plain('magma_block'),
plain('white_wool'), plain('mud', 2), plain('andesite'), plain('iron_block'), plain('mushroom_stem'),
plain('honeycomb_block'), plain('tube_coral_block'), plain('tnt'), plain('stone')],
}
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'],
'swallow': ['air'],
}
# The blocks a behaviour reacts to, drawn for that item most of the time.
FRONT_FOR = {
'flint_and_steel': ['air', 'air', 'air', 'campfire', 'soul_campfire', 'candle', 'blue_candle', 'candle_cake',
'red_candle_cake', 'tnt', 'stone', 'obsidian', 'netherrack', 'water'],
'glowstone': ['respawn_anchor', 'respawn_anchor', 'respawn_anchor', 'air', 'stone', 'glowstone'],
'bone_meal': ['grass_block', 'wheat', 'carrots', 'potatoes', 'beetroots', 'oak_sapling', 'birch_sapling', 'spruce_sapling',
'cherry_sapling', 'mangrove_propagule', 'moss_block', 'sweet_berry_bush', 'cocoa', 'bamboo_sapling', 'bamboo',
'pumpkin_stem', 'melon_stem', 'torchflower_crop', 'pitcher_crop', 'rooted_dirt', 'glow_lichen', 'small_dripleaf',
'big_dripleaf', 'crimson_nylium', 'warped_fungus', 'brown_mushroom', 'kelp', 'sea_pickle', 'seagrass', 'water',
'short_grass', 'fern', 'dandelion', 'pink_petals', 'cave_vines', 'twisting_vines', 'weeping_vines', 'azalea',
'pale_moss_block', 'stone', 'air'],
'honeycomb': ['copper_block', 'exposed_copper', 'weathered_cut_copper', 'oxidized_cut_copper_slab', 'copper_door',
'exposed_copper_trapdoor', 'copper_bulb', 'lightning_rod', 'waxed_copper_block', 'copper_grate', 'stone', 'air'],
'glass_bottle': ['beehive', 'beehive', 'bee_nest', 'bee_nest', 'water', 'water', 'air', 'stone', 'seagrass'],
'potion': ['dirt', 'coarse_dirt', 'rooted_dirt', 'dirt', 'stone', 'air', 'mud', 'water'],
'shears': ['beehive', 'bee_nest', 'beehive', 'air', 'air', 'stone', 'pumpkin'],
'brush': ['air', 'air', 'suspicious_sand', 'stone'],
'tnt': ['air', 'air', 'stone', 'water', 'tnt'],
'shulker_box': ['air', 'air', 'stone', 'water', 'short_grass', 'snow'],
'carved_pumpkin': ['air', 'air', 'stone', 'snow'],
'wither_skeleton_skull': ['air', 'air', 'stone'],
'armor_stand': ['air', 'air', 'stone', 'water', 'short_grass'],
}
# Structures a behaviour completes (golems, the wither, a nether portal).
SCENES = {'carved_pumpkin': ['snow_golem', 'iron_golem'], 'wither_skeleton_skull': ['wither'], 'flint_and_steel': ['portal']}
# Plants that need soil (or a log) under them to exist at all.
ROOTED = {'wheat', 'carrots', 'potatoes', 'beetroots', 'oak_sapling', 'birch_sapling', 'spruce_sapling', 'cherry_sapling',
'mangrove_propagule', 'sweet_berry_bush', 'cocoa', 'bamboo_sapling', 'bamboo', 'pumpkin_stem', 'melon_stem',
'torchflower_crop', 'pitcher_crop', 'small_dripleaf', 'big_dripleaf', 'warped_fungus', 'brown_mushroom', 'kelp',
'sea_pickle', 'seagrass', 'short_grass', 'fern', 'dandelion', 'pink_petals', 'twisting_vines', 'azalea'}
BELOW = ['air', 'stone', 'water', 'rail', 'grass_block', 'soul_sand', 'dirt', 'farmland', 'netherrack']
TARGETS = {
'iron_helmet': ['zombie', 'skeleton', 'armor_stand', 'pig'],
'chainmail_helmet': ['zombie', 'armor_stand', 'villager'],
'diamond_chestplate': ['zombie', 'armor_stand'],
'leather_leggings': ['skeleton', 'armor_stand'],
'golden_boots': ['zombie', 'armor_stand'],
'netherite_boots': ['zombie', 'piglin', 'armor_stand'],
'turtle_helmet': ['armor_stand', 'zombie'],
'saddle': ['pig', 'horse', 'strider', 'donkey', 'camel', 'llama', 'mule', 'skeleton_horse', 'nautilus'],
'iron_horse_armor': ['horse', 'donkey'],
'diamond_horse_armor': ['horse', 'zombie_horse'],
'leather_horse_armor': ['horse'],
'white_carpet': ['llama', 'horse', 'trader_llama'],
'red_carpet': ['llama', 'trader_llama'],
'chest': ['donkey', 'mule', 'llama', 'horse', 'trader_llama'],
'carved_pumpkin': ['zombie', 'armor_stand', 'snow_golem'],
'elytra': ['armor_stand', 'zombie'],
'wolf_armor': ['wolf'],
'white_harness': ['happy_ghast'],
'shears': ['sheep', 'sheep', 'mooshroom', 'bogged', 'snow_golem', 'sulfur_cube', 'pig', 'cow'],
'brush': ['armadillo'],
'tnt': ['sulfur_cube'],
'flint_and_steel': ['sulfur_cube'],
'player_head': ['armor_stand', 'zombie'],
'zombie_head': ['armor_stand', 'skeleton'],
}
for _block in ('stone', 'slime_block', 'oak_planks', 'packed_ice', 'soul_sand', 'magma_block', 'white_wool', 'mud', 'andesite',
'iron_block', 'mushroom_stem', 'honeycomb_block', 'tube_coral_block'):
TARGETS[_block] = ['sulfur_cube']
SWALLOWED = ['tnt', 'stone', 'slime_block', 'magma_block', 'white_wool', 'iron_block']
def item_choice(rng, kind):
item = rng.choice(ITEMS[kind])
if item == 'BOAT':
return plain(rng.choice(WOODS) + '_boat')
if item == 'CHEST_BOAT':
return plain(rng.choice(WOODS) + '_chest_boat')
return item
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 build_scene(cells, states, rng, scene, front, facing):
"""Put the rest of a structure the behaviour's block completes around the front."""
x, y, z = front
across = rng.choice([(1, 0, 0), (0, 0, 1)])
def put(at, name, **props):
if at != (0, 0, 0) and at != front:
h.put(cells, at, states.get(name, **props))
def side(at, k):
return (at[0] + across[0] * k, at[1], at[2] + across[2] * k)
if scene == 'snow_golem':
put((x, y - 1, z), 'snow_block')
put((x, y - 2, z), 'snow_block')
elif scene == 'iron_golem':
put((x, y - 1, z), 'iron_block')
put((x, y - 2, z), 'iron_block')
put(side((x, y - 1, z), -1), 'iron_block')
put(side((x, y - 1, z), 1), 'iron_block')
elif scene == 'wither':
put((x, y - 1, z), 'soul_sand')
put((x, y - 2, z), 'soul_sand')
put(side((x, y - 1, z), -1), rng.choice(['soul_sand', 'soul_soil']))
put(side((x, y - 1, z), 1), 'soul_sand')
put(side((x, y, z), -1), 'wither_skeleton_skull')
put(side((x, y, z), 1), rng.choice(['wither_skeleton_skull', 'wither_skeleton_skull', 'skeleton_skull']))
elif scene == 'portal':
# An obsidian frame around a 2x3 inside that holds the front block.
width, height = rng.choice([(2, 3), (2, 3), (3, 4)])
left, low = rng.randrange(width), rng.randrange(height)
for i in range(-1, width + 1):
for j in range(-1, height + 1):
at = side((x, y + j - low, z), i - left)
edge = i in (-1, width) or j in (-1, height)
if edge and not (i in (-1, width) and j in (-1, height)):
put(at, 'obsidian')
elif not edge:
if at not in ((0, 0, 0), front):
h.put(cells, at, states.get('air'))
def halves(states, name):
"""Whether a block comes in an upper and a lower half (tall plants, dripleaves, pitchers)."""
name = name if ':' in name else 'minecraft:' + name
return any(states.facts.states[i][4].get('properties', {}).get('half') == 'upper' for i in states.facts.by_block[name])
def front_state(states, rng, name):
"""Mostly the default state, sometimes a random one (charges, honey, ages, lit...)."""
if halves(states, name):
# A lone half is not a world vanilla makes; the pair is placed by put_front.
return states.get(name)
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 = item_choice(rng, kind)
if only and only not in item:
continue
bare = item.split('"')[1].split(':')[1]
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)
palette = FRONT_FOR[bare] if bare in FRONT_FOR and rng.random() < 0.8 else FRONT[kind]
front_name = rng.choice(palette)
if facing == 'up' and front_name in ROOTED:
# Nothing grows out of a dispenser: vanilla never lets these stand on one.
front_name = 'air'
above = (dx, dy + 1, dz)
if halves(states, front_name) and front_name != 'pitcher_crop':
if above == (0, 0, 0):
front_name = 'air'
else:
# The upper half matches the lower one in everything but its half.
lower = states.facts.states[states.get(front_name)][4].get('properties', {})
h.put(cells, above, states.get(front_name, **{**lower, 'half': 'upper'}))
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))
scene = rng.choice(SCENES[bare]) if bare in SCENES and rng.random() < 0.45 else None
# 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'])))
if scene:
build_scene(cells, states, rng, scene, front, facing)
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}
if kind in ('equipment', 'swallow') 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(SWALLOWED))}
# Leads: tied to an earlier target, or that target holds this one's.
holders = [i for i, e in enumerate(entities) if e['type'] != 'minecraft:armor_stand']
if holders and rng.random() < 0.3:
target['leash'] = rng.choice(holders)
entities.append(target)
if bare == 'shears' and len(entities) == 1 and rng.random() < 0.3:
# A holder out of the dispenser's reach whose lead runs to the target.
entities.append({'type': 'minecraft:' + rng.choice(['cow', 'wolf']), 'pos': [dx + 3.5, dy, dz + 3.5], 'yaw': 0.0})
entities[0]['leash'] = 1
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 spawned_type(case):
item = next(i[4] for i in case['items'] if i[:3] == [0, 0, 0]).split('"')[1].split(':')[1]
return 'minecraft:' + item.removesuffix('_spawn_egg').removesuffix('_bucket')
def rider(line, spawned):
parts = line.split(' ')
return parts[0] == 'N' and parts[1] not in (spawned, 'minecraft:item')
def voice(line):
parts = line.split(' ')
if parts[0] == 'S' and len(parts) == 3 and parts[2].lstrip('~').startswith('minecraft:entity.'):
parts[2] = 'entity-voice'
return ' '.join(parts)
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:
# An item's own motion spans 0.2 per axis, and a shearing
# sheep pushes each wool with its own random by up to 0.1 more.
if abs(float(x[1:]) - float(y)) > 0.4:
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 = 6000
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.cargo_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
# Riders finalizeSpawn adds (a baby zombie's chicken, a spider's
# skeleton) depend on whether the mob came out a baby and on the
# jockey odds, both finalization draws: only the egg's own mob is compared.
spawned = spawned_type(case)
a = [line for line in a if not rider(line, spawned)]
b = [line for line in b if not rider(line, spawned)]
# EntityType.spawn plays the new mob's ambient sound: which one (a
# wolf pants or barks, in its sound variant) comes from the mob's
# own unseeded random, so only that a voice plays, and where, is compared.
a = [voice(line) for line in a if not line.startswith('rng ')]
b = [voice(line) for line in b if not line.startswith('rng ')]
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()
+4 -1
View File
@@ -547,7 +547,10 @@ def main():
failures += 1
volatile = re.compile(r'(cooking_time_spent|lit_time_remaining|ticks_since_song_started|Age|BrewTime|'
r'ticks_in_hive|triggered|state_updating_resumes_at|LastExecution|last_vibration_frequency|warning_level): -?[0-9]+[a-zA-Z]?')
volatile2 = re.compile(r'(RecipesUsed: \{[^}]*\}|listener: \{.*\}(?=, x))')
# A lit campfire keeps cooking while each server runs before `data get`: its
# progress counters advance by however many ticks that took (stage 3 checks
# that Horizon saves them exactly as loaded).
volatile2 = re.compile(r'(RecipesUsed: \{[^}]*\}|listener: \{.*\}(?=, x)|CookingTimes: \[I;[^\]]*\])')
# The lit furnace keeps smelting while each game runs: its slots move on.
volatile_items = re.compile(r'Items: \[[^\]]*\]')
for label in views0: