Expect an int page in the click event fix test, as createInt writes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-11 15:53:55 +02:00
parent 139c5abd1c
commit 0de0379cc7
12 changed files with 1975 additions and 509 deletions
+2 -1
View File
@@ -108,7 +108,8 @@ 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)
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)
+148 -38
View File
@@ -61,7 +61,11 @@ pub fn data_version(tag: &Tag, default: i32) -> i32 {
/// `FileFixerUpper.requiresFileFixing`.
pub fn requires_file_fixing(level_version: i32) -> bool {
let from = if level_version < FILE_FIXER_INTRODUCTION { 0 } else { level_version };
let from = if level_version < FILE_FIXER_INTRODUCTION {
0
} else {
level_version
};
from < *FILE_FIXES.last().unwrap()
}
@@ -82,7 +86,11 @@ fn move_file(base: &Path, from: &str, to: &str) -> io::Result<()> {
if to.exists() {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("cannot move {} to {}: target already exists", from.display(), to.display()),
format!(
"cannot move {} to {}: target already exists",
from.display(),
to.display()
),
));
}
if let Some(parent) = to.parent() {
@@ -112,7 +120,12 @@ fn delete(base: &Path, relative: &str) -> io::Result<()> {
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())
.map(|r| {
r.filter_map(Result::ok)
.map(|e| e.path())
.filter(|p| p.is_dir())
.collect()
})
.unwrap_or_default();
out.sort();
out
@@ -122,12 +135,17 @@ fn subdirectories(path: &Path) -> Vec<PathBuf> {
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()
["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();
let found: Vec<PathBuf> = subdirectories(&root)
.iter()
.flat_map(|ns| subdirectories(ns))
.collect();
if found.is_empty() { defaults() } else { found }
}
@@ -136,7 +154,10 @@ fn dimensions(base: &Path) -> Vec<PathBuf> {
/// `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 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
@@ -148,14 +169,19 @@ fn write_level(base: &Path, mut data: Tag, version: i32) -> io::Result<()> {
}
/// `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))]))
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()))
tag.get("data")
.cloned()
.unwrap_or_else(|| Tag::Compound(Compound::new()))
}))
}
@@ -174,7 +200,10 @@ fn fix_4772(base: &Path) -> io::Result<()> {
}
for (from, to) in [
("data", "dimensions/minecraft/overworld/data/minecraft"),
("DIM-1/data", "dimensions/minecraft/the_nether/data/minecraft"),
(
"DIM-1/data",
"dimensions/minecraft/the_nether/data/minecraft",
),
("DIM1/data", "dimensions/minecraft/the_end/data/minecraft"),
] {
for (a, b) in [
@@ -196,16 +225,26 @@ fn fix_4772(base: &Path) -> io::Result<()> {
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"))
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"))
(!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")?;
move_file(
&data,
"random_sequences.dat",
"minecraft/random_sequences.dat",
)?;
for (from, to) in [
("", "dimensions/minecraft/overworld"),
("DIM-1", "dimensions/minecraft/the_nether"),
@@ -233,7 +272,16 @@ fn fix_4772(base: &Path) -> io::Result<()> {
] {
delete(base, f)?;
}
for s in ["Monument", "Stronghold", "Mineshaft", "Temple", "Mansion", "Village", "Fortress", "EndCity"] {
for s in [
"Monument",
"Stronghold",
"Mineshaft",
"Temple",
"Mansion",
"Village",
"Fortress",
"EndCity",
] {
delete(base, &format!("data/{s}.dat"))?;
delete(base, &format!("data/{s}_index.dat"))?;
}
@@ -264,14 +312,20 @@ fn level_dat_to_saved_data(base: &Path) -> io::Result<()> {
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 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"))?;
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);
@@ -279,16 +333,31 @@ fn level_dat_to_saved_data(base: &Path) -> io::Result<()> {
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)?;
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,
"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"))?;
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();
@@ -326,12 +395,18 @@ fn fix_4899(base: &Path) -> io::Result<()> {
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));
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));
set(
&mut rules,
"minecraft:spectators_generate_chunks",
Tag::Byte(1),
);
}
write_saved_data(&path, rules, V)?;
}
@@ -363,14 +438,21 @@ fn add_versions(data: &mut Tag) {
/// 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 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 };
let start = if loaded < FILE_FIXER_INTRODUCTION {
0
} else {
loaded
};
for version in FILE_FIXES {
if version > start && version <= CURRENT {
match version {
@@ -381,8 +463,12 @@ pub fn fix_world_files(base: &Path) -> io::Result<i32> {
}
}
// `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()));
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"));
@@ -437,7 +523,10 @@ fn upgrade_regions(folder: &Path, mut fix: impl FnMut(&mut Tag)) -> io::Result<(
};
let mut root = record.nbt(limits)?;
fix(&mut root.tag);
records.push((pos, ChunkRecord::from_nbt(&root, record.compression, record.timestamp, limits)?));
records.push((
pos,
ChunkRecord::from_nbt(&root, record.compression, record.timestamp, limits)?,
));
}
drop(region);
let staging = folder.join(".datafix");
@@ -474,7 +563,11 @@ fn upgrade_saved_data(data: &Path) -> io::Result<()> {
}
files.sort();
for file in files {
let relative = file.strip_prefix(data).unwrap_or(&file).to_string_lossy().replace('\\', "/");
let relative = file
.strip_prefix(data)
.unwrap_or(&file)
.to_string_lossy()
.replace('\\', "/");
let Some(ty) = super::saved_data_type(&relative) else {
continue;
};
@@ -493,9 +586,12 @@ 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())
}
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),
}
}
@@ -505,7 +601,11 @@ fn tag_to_json(t: &Tag) -> Json {
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()),
Tag::Compound(c) => Json::Obj(
c.iter()
.map(|(k, v)| (k.0.clone(), tag_to_json(v)))
.collect(),
),
other => json::from_nbt(other),
}
}
@@ -513,7 +613,8 @@ fn tag_to_json(t: &Tag) -> Json {
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 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 {
@@ -538,10 +639,19 @@ pub fn upgrade_world_data(base: &Path) -> io::Result<()> {
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))?;
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"))?;
}
}
+192 -54
View File
@@ -1,7 +1,7 @@
//! Fixes of 1.20.2 to 1.20.6 (keys 3564 to 3833).
use super::dynamic::{
as_double, as_float, as_int, as_number, as_str, as_string, empty_map, int_list, is_list, namespaced, remove,
rename, rename_and_fix, set, stream, string,
as_double, as_float, as_int, as_number, as_str, as_string, empty_map, int_list, is_list,
namespaced, remove, rename, rename_and_fix, set, stream, string,
};
use super::json;
use super::schema::{Key, Ty, key};
@@ -9,32 +9,59 @@ use super::{Cx, FixFn, id_is, items, renamer, reread};
use crate::nbt::Tag;
pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
out.push((key(3564, 0), |cx| drop_invalid_sign_data(cx, "minecraft:sign")));
out.push((key(3564, 1), |cx| drop_invalid_sign_data(cx, "minecraft:hanging_sign")));
out.push((key(3564, 0), |cx| {
drop_invalid_sign_data(cx, "minecraft:sign")
}));
out.push((key(3564, 1), |cx| {
drop_invalid_sign_data(cx, "minecraft:hanging_sign")
}));
out.push((key(3565, 0), random_sequence_settings));
out.push((key(3566, 0), scoreboard_display_slots));
out.push((key(3568, 0), mob_effect_ids));
out.push((key(3683, 0), primed_tnt_block_state));
out.push((key(3685, 0), projectile_stored_item));
out.push((key(3692, 0), |cx| block_rename(cx, &[("minecraft:grass", "minecraft:short_grass")])));
out.push((key(3692, 0), |cx| cx.rename(Ty::ItemName, renamer(&[("minecraft:grass", "minecraft:short_grass")]))));
out.push((key(3800, 0), |cx| cx.rename(Ty::ItemName, renamer(&[("minecraft:scute", "minecraft:turtle_scute")]))));
out.push((key(3692, 0), |cx| {
block_rename(cx, &[("minecraft:grass", "minecraft:short_grass")])
}));
out.push((key(3692, 0), |cx| {
cx.rename(
Ty::ItemName,
renamer(&[("minecraft:grass", "minecraft:short_grass")]),
)
}));
out.push((key(3800, 0), |cx| {
cx.rename(
Ty::ItemName,
renamer(&[("minecraft:scute", "minecraft:turtle_scute")]),
)
}));
out.push((key(3803, 0), rename_sweeping));
out.push((key(3807, 1), map_banner_block_pos));
out.push((key(3808, 0), |cx| horse_body_armor(cx, "minecraft:horse", "ArmorItem", true)));
out.push((key(3808, 1), |cx| horse_body_armor(cx, "minecraft:llama", "DecorItem", false)));
out.push((key(3808, 2), |cx| horse_body_armor(cx, "minecraft:trader_llama", "DecorItem", false)));
out.push((key(3808, 0), |cx| {
horse_body_armor(cx, "minecraft:horse", "ArmorItem", true)
}));
out.push((key(3808, 1), |cx| {
horse_body_armor(cx, "minecraft:llama", "DecorItem", false)
}));
out.push((key(3808, 2), |cx| {
horse_body_armor(cx, "minecraft:trader_llama", "DecorItem", false)
}));
out.push((key(3809, 0), chested_horse_slots));
out.push((key(3812, 0), wolf_health));
out.push((key(3813, 0), block_pos_format));
out.push((key(3814, 0), |cx| {
attributes_rename_legacy(cx, &|id| (namespaced(id) == "minecraft:horse.jump_strength").then_some("minecraft:generic.jump_strength"))
attributes_rename_legacy(cx, &|id| {
(namespaced(id) == "minecraft:horse.jump_strength")
.then_some("minecraft:generic.jump_strength")
})
}));
out.push((key(3818, 0), beehive_fields));
out.push((key(3818, 1), banner_patterns));
out.push((key(3818, 2), tipped_arrow_potion));
out.push((key(3818, 4), particle_unflattening));
out.push((key(3818, 5), |cx| cx.each(Ty::ItemStack, items::componentize)));
out.push((key(3818, 5), |cx| {
cx.each(Ty::ItemStack, items::componentize)
}));
out.push((key(3818, 6), area_effect_cloud_potion));
out.push((key(3820, 0), player_head_profile));
out.push((key(3820, 0), lodestone_compass_component));
@@ -49,7 +76,15 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
/// `BlockEntitySignDoubleSidedEditableTextFix.FIELDS_TO_DROP`.
pub(super) const SIGN_FIELDS_TO_DROP: [&str; 10] = [
"Text1", "Text2", "Text3", "Text4", "FilteredText1", "FilteredText2", "FilteredText3", "FilteredText4", "Color",
"Text1",
"Text2",
"Text3",
"Text4",
"FilteredText1",
"FilteredText2",
"FilteredText3",
"FilteredText4",
"Color",
"GlowingText",
];
@@ -132,7 +167,10 @@ fn scoreboard_display_slots(cx: &mut Cx) {
let old = std::mem::take(slots);
for (k, value) in old {
let name = k.to_string_lossy();
let k = SLOT_RENAMES.iter().find(|(o, _)| *o == name).map_or(k, |(_, n)| (*n).into());
let k = SLOT_RENAMES
.iter()
.find(|(o, _)| *o == name)
.map_or(k, |(_, n)| (*n).into());
slots.insert(k, value);
}
}
@@ -180,7 +218,9 @@ const EFFECT_IDS: [&str; 33] = [
/// `getAndConvertMobEffectId`.
fn effect_id(v: &Tag, field: &str) -> Option<Tag> {
let n = as_number(v.get(field)?)?.int_value();
(1..=33).contains(&n).then(|| string(EFFECT_IDS[(n - 1) as usize]))
(1..=33)
.contains(&n)
.then(|| string(EFFECT_IDS[(n - 1) as usize]))
}
/// `replaceField(old, new, value)`.
fn replace_field(v: &mut Tag, old: &str, new: &str, value: Option<Tag>) {
@@ -206,7 +246,14 @@ fn update_effect_instance(mut v: Tag) -> Tag {
v
}
fn update_effect_list(v: &mut Tag, old: &str, new: &str) {
let value = is_list(v.get(old)).then(|| Tag::List(stream(v.get(old)).into_iter().map(update_effect_instance).collect()));
let value = is_list(v.get(old)).then(|| {
Tag::List(
stream(v.get(old))
.into_iter()
.map(update_effect_instance)
.collect(),
)
});
replace_field(v, old, new, value);
}
fn update_stew_entry(input: &Tag, mut output: Tag) -> Tag {
@@ -241,7 +288,9 @@ fn mob_effect_ids(cx: &mut Cx) {
}
update_effect_list(e, "ActiveEffects", "active_effects");
});
cx.each(Ty::Player, |p| update_effect_list(p, "ActiveEffects", "active_effects"));
cx.each(Ty::Player, |p| {
update_effect_list(p, "ActiveEffects", "active_effects")
});
cx.each(Ty::ItemStack, |s| {
let Some(id) = as_str(s.get("id")).map(|i| namespaced(&i)) else {
return;
@@ -251,12 +300,20 @@ fn mob_effect_ids(cx: &mut Cx) {
};
if id == "minecraft:suspicious_stew" {
let value = is_list(tag.get("Effects")).then(|| {
Tag::List(stream(tag.get("Effects")).into_iter().map(|e| update_stew_entry(&e.clone(), e)).collect())
Tag::List(
stream(tag.get("Effects"))
.into_iter()
.map(|e| update_stew_entry(&e.clone(), e))
.collect(),
)
});
replace_field(tag, "Effects", "effects", value);
} else if matches!(
id.as_str(),
"minecraft:potion" | "minecraft:splash_potion" | "minecraft:lingering_potion" | "minecraft:tipped_arrow"
"minecraft:potion"
| "minecraft:splash_potion"
| "minecraft:lingering_potion"
| "minecraft:tipped_arrow"
) {
update_effect_list(tag, "CustomPotionEffects", "custom_potion_effects");
}
@@ -268,7 +325,11 @@ fn mob_effect_ids(cx: &mut Cx) {
fn primed_tnt_block_state(cx: &mut Cx) {
let k = cx.k;
cx.entity("minecraft:tnt", |e| {
set(e, "block_state", Tag::compound([("Name", string("minecraft:tnt"))]));
set(
e,
"block_state",
Tag::compound([("Name", string("minecraft:tnt"))]),
);
if let Some(fuse) = e.get("Fuse").cloned() {
set(e, "fuse", fuse);
}
@@ -281,7 +342,11 @@ fn projectile_stored_item(cx: &mut Cx) {
cx.each(Ty::Entity, |e| {
let item = if id_is(e, "minecraft:arrow") {
let potion = as_string(e.get("Potion"), "minecraft:empty");
if potion == "minecraft:empty" { "minecraft:arrow" } else { "minecraft:tipped_arrow" }
if potion == "minecraft:empty" {
"minecraft:arrow"
} else {
"minecraft:tipped_arrow"
}
} else if id_is(e, "minecraft:spectral_arrow") {
"minecraft:spectral_arrow"
} else {
@@ -348,7 +413,11 @@ fn rename_sweeping(cx: &mut Cx) {
.into_iter()
.map(|mut e| {
if let Some(id) = as_str(e.get("id")) {
let new = if namespaced(&id) == "minecraft:sweeping" { "minecraft:sweeping_edge".into() } else { id };
let new = if namespaced(&id) == "minecraft:sweeping" {
"minecraft:sweeping_edge".into()
} else {
id
};
set(&mut e, "id", string(&new));
}
e
@@ -364,7 +433,11 @@ fn rename_sweeping(cx: &mut Cx) {
/// `ExtraDataFixUtils.fixBlockPos`.
pub(super) fn fix_block_pos(v: Tag) -> Tag {
let (x, y, z) = (v.get("X").and_then(as_number), v.get("Y").and_then(as_number), v.get("Z").and_then(as_number));
let (x, y, z) = (
v.get("X").and_then(as_number),
v.get("Y").and_then(as_number),
v.get("Z").and_then(as_number),
);
match (x, y, z) {
(Some(x), Some(y), Some(z)) => int_list(&[x.int_value(), y.int_value(), z.int_value()]),
_ => v,
@@ -372,12 +445,20 @@ pub(super) fn fix_block_pos(v: Tag) -> Tag {
}
/// `ExtraDataFixUtils.fixInlineBlockPos`.
pub(super) fn fix_inline_block_pos(v: &mut Tag, fx: &str, fy: &str, fz: &str, new: &str) {
let (x, y, z) = (v.get(fx).and_then(as_number), v.get(fy).and_then(as_number), v.get(fz).and_then(as_number));
let (x, y, z) = (
v.get(fx).and_then(as_number),
v.get(fy).and_then(as_number),
v.get(fz).and_then(as_number),
);
if let (Some(x), Some(y), Some(z)) = (x, y, z) {
remove(v, fx);
remove(v, fy);
remove(v, fz);
set(v, new, int_list(&[x.int_value(), y.int_value(), z.int_value()]));
set(
v,
new,
int_list(&[x.int_value(), y.int_value(), z.int_value()]),
);
}
}
@@ -424,7 +505,13 @@ fn horse_body_armor_entity(e: &mut Tag, field: &str, clear_armor_items: bool) {
stream(Some(&list))
.into_iter()
.enumerate()
.map(|(i, x)| if i == 2 { Tag::Float(0.085f32.to_bits()) } else { x })
.map(|(i, x)| {
if i == 2 {
Tag::Float(0.085f32.to_bits())
} else {
x
}
})
.collect(),
)
});
@@ -436,9 +523,14 @@ fn horse_body_armor_entity(e: &mut Tag, field: &str, clear_armor_items: bool) {
fn chested_horse_slots(cx: &mut Cx) {
cx.each(Ty::Entity, |e| {
if !["minecraft:llama", "minecraft:trader_llama", "minecraft:mule", "minecraft:donkey"]
.iter()
.any(|id| id_is(e, id))
if ![
"minecraft:llama",
"minecraft:trader_llama",
"minecraft:mule",
"minecraft:donkey",
]
.iter()
.any(|id| id_is(e, id))
{
return;
}
@@ -461,7 +553,9 @@ fn wolf_health(cx: &mut Cx) {
stream(Some(&list))
.into_iter()
.map(|mut a| {
if namespaced(&as_string(a.get("Name"), "")) == "minecraft:generic.max_health" {
if namespaced(&as_string(a.get("Name"), ""))
== "minecraft:generic.max_health"
{
super::dynamic::update(&mut a, "Base", |base| {
if as_double(Some(&base), 0.0) == 20.0 {
adjusted = true;
@@ -477,7 +571,9 @@ fn wolf_health(cx: &mut Cx) {
)
});
if adjusted {
super::dynamic::update(e, "Health", |h| Tag::Float((as_float(Some(&h), 0.0) * 2.0).to_bits()));
super::dynamic::update(e, "Health", |h| {
Tag::Float((as_float(Some(&h), 0.0) * 2.0).to_bits())
});
}
});
}
@@ -515,8 +611,12 @@ fn block_pos_format(cx: &mut Cx) {
}
rename_block_pos(e, &[("Leash", "leash")]);
});
cx.block_entity("minecraft:beehive", |be| rename_block_pos(be, &[("FlowerPos", "flower_pos")]));
cx.block_entity("minecraft:end_gateway", |be| rename_block_pos(be, &[("ExitPortal", "exit_portal")]));
cx.block_entity("minecraft:beehive", |be| {
rename_block_pos(be, &[("FlowerPos", "flower_pos")])
});
cx.block_entity("minecraft:end_gateway", |be| {
rename_block_pos(be, &[("ExitPortal", "exit_portal")])
});
cx.each(Ty::SavedMapData, |v| {
if let Some(d) = v.get_mut("data") {
super::dynamic::update(d, "frames", |frames| {
@@ -547,11 +647,14 @@ fn block_pos_format(cx: &mut Cx) {
});
}
});
cx.item(|id| id == "minecraft:compass", |s| {
if let Some(tag) = s.get_mut("tag") {
super::dynamic::update(tag, "LodestonePos", fix_block_pos);
}
});
cx.item(
|id| id == "minecraft:compass",
|s| {
if let Some(tag) = s.get_mut("tag") {
super::dynamic::update(tag, "LodestonePos", fix_block_pos);
}
},
);
}
// ------------------------------------------------------------------ 3814
@@ -677,7 +780,12 @@ pub(super) fn dye_color(id: i32) -> &'static str {
pub(super) fn banner_layer(mut v: Tag) -> Tag {
rename_and_fix(&mut v, "Pattern", "pattern", |p| {
Some(match as_str(Some(&p)) {
Some(id) => string(PATTERN_IDS.iter().find(|(k, _)| *k == id).map_or(id.as_str(), |(_, n)| n)),
Some(id) => string(
PATTERN_IDS
.iter()
.find(|(k, _)| *k == id)
.map_or(id.as_str(), |(_, n)| n),
),
None => p,
})
});
@@ -690,7 +798,9 @@ pub(super) fn banner_layer(mut v: Tag) -> Tag {
fn banner_patterns(cx: &mut Cx) {
cx.block_entity("minecraft:banner", |be| {
rename_and_fix(be, "Patterns", "patterns", |p| {
Some(Tag::List(stream(Some(&p)).into_iter().map(banner_layer).collect()))
Some(Tag::List(
stream(Some(&p)).into_iter().map(banner_layer).collect(),
))
});
});
}
@@ -765,7 +875,10 @@ fn area_effect_cloud_potion(cx: &mut Cx) {
fn player_head_profile(cx: &mut Cx) {
cx.block_entity("minecraft:skull", |be| {
let profile = be.get("SkullOwner").or_else(|| be.get("ExtraType")).cloned();
let profile = be
.get("SkullOwner")
.or_else(|| be.get("ExtraType"))
.cloned();
let Some(profile) = profile else {
return;
};
@@ -787,14 +900,23 @@ pub(super) fn component_fix(cx: &mut Cx, id: &str, new_id: &str, f: impl Fn(Tag)
}
fn lodestone_compass_component(cx: &mut Cx) {
component_fix(cx, "minecraft:lodestone_target", "minecraft:lodestone_tracker", |mut v| {
let pos = remove(&mut v, "pos");
let dimension = remove(&mut v, "dimension");
if let (Some(pos), Some(dimension)) = (pos, dimension) {
set(&mut v, "target", Tag::compound([("pos", pos), ("dimension", dimension)]));
}
Some(v)
});
component_fix(
cx,
"minecraft:lodestone_target",
"minecraft:lodestone_tracker",
|mut v| {
let pos = remove(&mut v, "pos");
let dimension = remove(&mut v, "dimension");
if let (Some(pos), Some(dimension)) = (pos, dimension) {
set(
&mut v,
"target",
Tag::compound([("pos", pos), ("dimension", dimension)]),
);
}
Some(v)
},
);
}
// ------------------------------------------------------------------ 3825
@@ -838,7 +960,9 @@ fn item_custom_name_to_item_name(cx: &mut Cx) {
_ => return,
};
if let Some(c) = s.get_mut("components")
&& c.get("minecraft:custom_name").and_then(translation_key).is_some_and(|k| expected(&k))
&& c.get("minecraft:custom_name")
.and_then(translation_key)
.is_some_and(|k| expected(&k))
{
rename(c, "minecraft:custom_name", "minecraft:item_name");
}
@@ -856,7 +980,10 @@ fn banner_custom_name_to_item_name(cx: &mut Cx) {
set(
be,
"components",
Tag::compound([("minecraft:item_name", name), ("minecraft:hide_additional_tooltip", empty_map())]),
Tag::compound([
("minecraft:item_name", name),
("minecraft:hide_additional_tooltip", empty_map()),
]),
);
remove(be, "CustomName");
});
@@ -921,12 +1048,19 @@ pub(super) fn unpack_objective(v: &mut Tag) {
};
let (ty, id) = match name.find(':') {
None => ("_special".to_owned(), name.clone()),
Some(colon) => match (by_separator(&name[..colon]), by_separator(&name[colon + 1..])) {
Some(colon) => match (
by_separator(&name[..colon]),
by_separator(&name[colon + 1..]),
) {
(Some(t), Some(i)) => (t, i),
_ => ("_special".to_owned(), name.clone()),
},
};
set(v, "CriteriaType", Tag::compound([("type", string(&ty)), ("id", string(&id))]));
set(
v,
"CriteriaType",
Tag::compound([("type", string(&ty)), ("id", string(&id))]),
);
}
/// `Identifier.bySeparator(s, '.')`: namespace before the first dot.
@@ -947,7 +1081,11 @@ pub(super) fn repack_objective(v: &mut Tag) {
let (Some(ty), Some(id)) = (as_str(ct.get("type")), as_str(ct.get("id"))) else {
return;
};
let name = if ty == "_special" { id } else { format!("{}:{}", pack_with_dot(&ty), pack_with_dot(&id)) };
let name = if ty == "_special" {
id
} else {
format!("{}:{}", pack_with_dot(&ty), pack_with_dot(&id))
};
set(v, "CriteriaName", string(&name));
remove(v, "CriteriaType");
}
+420 -111
View File
@@ -1,7 +1,8 @@
//! Fixes of 1.21 to 1.21.5 (keys 3938 to 4314), text components apart.
use super::dynamic::{
as_bool, as_double, as_float, as_int, as_long, as_number, as_str, as_string, empty_map, is_empty_map, is_list,
namespaced, or_empty_map, remove, rename, rename_and_fix, set, stream, string, update,
as_bool, as_double, as_float, as_int, as_long, as_number, as_str, as_string, empty_map,
is_empty_map, is_list, namespaced, or_empty_map, remove, rename, rename_and_fix, set, stream,
string, update,
};
use super::fixes_a::{component_fix, dye_color, fix_inline_block_pos, translation_key};
use super::items::java_hash_order;
@@ -19,23 +20,36 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
}
});
}));
out.push((key(3939, 0), |cx| feature_flag_remove(cx, &["minecraft:update_1_21"])));
out.push((key(3939, 0), |cx| {
feature_flag_remove(cx, &["minecraft:update_1_21"])
}));
out.push((key(3945, 0), attribute_modifier_ids));
out.push((key(3945, 0), jukebox_ticks));
out.push((key(4054, 0), ominous_banner_rarity));
out.push((key(4055, 0), |cx| attributes_rename(cx, true, &attribute_id_prefix)));
out.push((key(4055, 0), |cx| {
attributes_rename(cx, true, &attribute_id_prefix)
}));
out.push((key(4059, 0), food_to_consumable));
out.push((key(4061, 0), trial_spawner_config_in_registry));
out.push((key(4064, 0), |cx| {
component_fix(cx, "minecraft:fire_resistant", "minecraft:damage_resistant", |_| {
Some(Tag::compound([("types", string("#minecraft:is_fire"))]))
});
component_fix(
cx,
"minecraft:fire_resistant",
"minecraft:damage_resistant",
|_| Some(Tag::compound([("types", string("#minecraft:is_fire"))])),
);
}));
out.push((key(4067, 0), boat_split));
out.push((key(4067, 0), |cx| feature_flag_remove(cx, &["minecraft:bundle"])));
out.push((key(4068, 0), |cx| component_fix(cx, "minecraft:lock", "minecraft:lock", fix_lock)));
out.push((key(4067, 0), |cx| {
feature_flag_remove(cx, &["minecraft:bundle"])
}));
out.push((key(4068, 0), |cx| {
cx.each(Ty::BlockEntity, |be| rename_and_fix(be, "Lock", "lock", fix_lock));
component_fix(cx, "minecraft:lock", "minecraft:lock", fix_lock)
}));
out.push((key(4068, 0), |cx| {
cx.each(Ty::BlockEntity, |be| {
rename_and_fix(be, "Lock", "lock", fix_lock)
});
}));
out.push((key(4081, 0), |cx| {
cx.entity("minecraft:salmon", |e| {
@@ -44,7 +58,9 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
}
});
}));
out.push((key(4173, 0), |cx| cx.entity("minecraft:tnt_minecart", |e| rename(e, "TNTFuse", "fuse"))));
out.push((key(4173, 0), |cx| {
cx.entity("minecraft:tnt_minecart", |e| rename(e, "TNTFuse", "fuse"))
}));
out.push((key(4175, 0), |cx| {
cx.each(Ty::DataComponents, |c| {
if let Some(eq) = c.get_mut("minecraft:equippable") {
@@ -70,39 +86,97 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
});
}));
out.push((key(4176, 0), |cx| {
component_fix(cx, "minecraft:lock", "minecraft:lock", |l| (!broken_lock(&l)).then_some(l));
component_fix(cx, "minecraft:lock", "minecraft:lock", |l| {
(!broken_lock(&l)).then_some(l)
});
}));
out.push((key(4180, 0), |cx| feature_flag_remove(cx, &["minecraft:winter_drop"])));
for id in ["minecraft:furnace", "minecraft:smoker", "minecraft:blast_furnace"] {
out.push((key(4180, 0), |cx| {
feature_flag_remove(cx, &["minecraft:winter_drop"])
}));
for id in [
"minecraft:furnace",
"minecraft:smoker",
"minecraft:blast_furnace",
] {
let _ = id;
}
out.push((key(4181, 0), |cx| furnace_burn_time(cx, "minecraft:furnace")));
out.push((key(4181, 0), |cx| {
furnace_burn_time(cx, "minecraft:furnace")
}));
out.push((key(4181, 0), |cx| furnace_burn_time(cx, "minecraft:smoker")));
out.push((key(4181, 0), |cx| furnace_burn_time(cx, "minecraft:blast_furnace")));
out.push((key(4187, 0), |cx| base_value(cx, "minecraft:villager", "minecraft:follow_range", 48.0, 16.0)));
out.push((key(4187, 0), |cx| base_value(cx, "minecraft:bee", "minecraft:follow_range", 48.0, 16.0)));
out.push((key(4187, 0), |cx| base_value(cx, "minecraft:allay", "minecraft:follow_range", 48.0, 16.0)));
out.push((key(4187, 0), |cx| base_value(cx, "minecraft:llama", "minecraft:follow_range", 40.0, 16.0)));
out.push((key(4187, 0), |cx| base_value(cx, "minecraft:piglin_brute", "minecraft:follow_range", 16.0, 12.0)));
out.push((key(4187, 0), |cx| base_value(cx, "minecraft:warden", "minecraft:follow_range", 16.0, 24.0)));
out.push((key(4181, 0), |cx| {
furnace_burn_time(cx, "minecraft:blast_furnace")
}));
out.push((key(4187, 0), |cx| {
base_value(
cx,
"minecraft:villager",
"minecraft:follow_range",
48.0,
16.0,
)
}));
out.push((key(4187, 0), |cx| {
base_value(cx, "minecraft:bee", "minecraft:follow_range", 48.0, 16.0)
}));
out.push((key(4187, 0), |cx| {
base_value(cx, "minecraft:allay", "minecraft:follow_range", 48.0, 16.0)
}));
out.push((key(4187, 0), |cx| {
base_value(cx, "minecraft:llama", "minecraft:follow_range", 40.0, 16.0)
}));
out.push((key(4187, 0), |cx| {
base_value(
cx,
"minecraft:piglin_brute",
"minecraft:follow_range",
16.0,
12.0,
)
}));
out.push((key(4187, 0), |cx| {
base_value(cx, "minecraft:warden", "minecraft:follow_range", 16.0, 24.0)
}));
super::text::register(out);
out.push((key(4293, 0), drop_chances_format));
out.push((key(4294, 0), |cx| {
block_property_rename(cx, "minecraft:creaking_heart", "active", "creaking_heart_state", &|v| {
if v == "true" { "awake".into() } else { "uprooted".into() }
});
block_property_rename(
cx,
"minecraft:creaking_heart",
"active",
"creaking_heart_state",
&|v| {
if v == "true" {
"awake".into()
} else {
"uprooted".into()
}
},
);
}));
out.push((key(4296, 0), |cx| {
cx.entity("minecraft:area_effect_cloud", |e| set(e, "potion_duration_scale", Tag::Float(0.25f32.to_bits())));
cx.entity("minecraft:area_effect_cloud", |e| {
set(e, "potion_duration_scale", Tag::Float(0.25f32.to_bits()))
});
}));
out.push((key(4297, 0), forced_chunk_to_ticket));
out.push((key(4299, 0), entity_spawner_item_variants));
out.push((key(4300, 0), saddle_equipment_slot));
out.push((key(4301, 0), equipment_format));
out.push((key(4303, 0), |cx| cx.each_out(Ty::Entity, fall_distance_to_double)));
out.push((key(4303, 0), |cx| cx.each_out(Ty::Player, fall_distance_to_double)));
out.push((key(4303, 0), |cx| {
cx.each_out(Ty::Entity, fall_distance_to_double)
}));
out.push((key(4303, 0), |cx| {
cx.each_out(Ty::Player, fall_distance_to_double)
}));
out.push((key(4305, 0), |cx| {
block_property_rename(cx, "minecraft:test_block", "test_block_mode", "mode", &|v| v.to_owned());
block_property_rename(
cx,
"minecraft:test_block",
"test_block_mode",
"mode",
&|v| v.to_owned(),
);
}));
out.push((key(4306, 0), thrown_potion_split));
out.push((key(4307, 0), tooltip_display));
@@ -110,7 +184,8 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
out.push((key(4309, 0), chunk_ticket_unpack_pos));
out.push((key(4311, 0), |cx| {
advancements_rename(cx, &|id| {
(namespaced(id) == "minecraft:nether/use_lodestone").then(|| "minecraft:adventure/use_lodestone".into())
(namespaced(id) == "minecraft:nether/use_lodestone")
.then(|| "minecraft:adventure/use_lodestone".into())
});
}));
out.push((key(4312, 0), player_equipment));
@@ -160,60 +235,177 @@ fn uuid_text(u: [i32; 4]) -> String {
}
const MODIFIER_IDS: &[(&str, &str)] = &[
("736565d2-e1a7-403d-a3f8-1aeb3e302542", "minecraft:creative_mode_block_range"),
("98491ef6-97b1-4584-ae82-71a8cc85cf73", "minecraft:creative_mode_entity_range"),
("91aeaa56-376b-4498-935b-2f7f68070635", "minecraft:effect.speed"),
("7107de5e-7ce8-4030-940e-514c1f160890", "minecraft:effect.slowness"),
("af8b6e3f-3328-4c0a-aa36-5ba2bb9dbef3", "minecraft:effect.haste"),
("55fced67-e92a-486e-9800-b47f202c4386", "minecraft:effect.mining_fatigue"),
("648d7064-6a60-4f59-8abe-c2c23a6dd7a9", "minecraft:effect.strength"),
("c0105bf3-aef8-46b0-9ebc-92943757ccbe", "minecraft:effect.jump_boost"),
("22653b89-116e-49dc-9b6b-9971489b5be5", "minecraft:effect.weakness"),
("5d6f0ba2-1186-46ac-b896-c61c5cee99cc", "minecraft:effect.health_boost"),
("eae29cf0-701e-4ed6-883a-96f798f3dab5", "minecraft:effect.absorption"),
("03c3c89d-7037-4b42-869f-b146bcb64d2e", "minecraft:effect.luck"),
("cc5af142-2bd2-4215-b636-2605aed11727", "minecraft:effect.unluck"),
(
"736565d2-e1a7-403d-a3f8-1aeb3e302542",
"minecraft:creative_mode_block_range",
),
(
"98491ef6-97b1-4584-ae82-71a8cc85cf73",
"minecraft:creative_mode_entity_range",
),
(
"91aeaa56-376b-4498-935b-2f7f68070635",
"minecraft:effect.speed",
),
(
"7107de5e-7ce8-4030-940e-514c1f160890",
"minecraft:effect.slowness",
),
(
"af8b6e3f-3328-4c0a-aa36-5ba2bb9dbef3",
"minecraft:effect.haste",
),
(
"55fced67-e92a-486e-9800-b47f202c4386",
"minecraft:effect.mining_fatigue",
),
(
"648d7064-6a60-4f59-8abe-c2c23a6dd7a9",
"minecraft:effect.strength",
),
(
"c0105bf3-aef8-46b0-9ebc-92943757ccbe",
"minecraft:effect.jump_boost",
),
(
"22653b89-116e-49dc-9b6b-9971489b5be5",
"minecraft:effect.weakness",
),
(
"5d6f0ba2-1186-46ac-b896-c61c5cee99cc",
"minecraft:effect.health_boost",
),
(
"eae29cf0-701e-4ed6-883a-96f798f3dab5",
"minecraft:effect.absorption",
),
(
"03c3c89d-7037-4b42-869f-b146bcb64d2e",
"minecraft:effect.luck",
),
(
"cc5af142-2bd2-4215-b636-2605aed11727",
"minecraft:effect.unluck",
),
("6555be74-63b3-41f1-a245-77833b3c2562", "minecraft:evil"),
("1eaf83ff-7207-4596-b37a-d7a07b3ec4ce", "minecraft:powder_snow"),
("662a6b8d-da3e-4c1c-8813-96ea6097278d", "minecraft:sprinting"),
("020e0dfb-87ae-4653-9556-831010e291a0", "minecraft:attacking"),
(
"1eaf83ff-7207-4596-b37a-d7a07b3ec4ce",
"minecraft:powder_snow",
),
(
"662a6b8d-da3e-4c1c-8813-96ea6097278d",
"minecraft:sprinting",
),
(
"020e0dfb-87ae-4653-9556-831010e291a0",
"minecraft:attacking",
),
("766bfa64-11f3-11ea-8d71-362b9e155667", "minecraft:baby"),
("7e0292f2-9434-48d5-a29f-9583af7df27f", "minecraft:covered"),
("9e362924-01de-4ddd-a2b2-d0f7a405a174", "minecraft:suffocating"),
(
"9e362924-01de-4ddd-a2b2-d0f7a405a174",
"minecraft:suffocating",
),
("5cd17e52-a79a-43d3-a529-90fde04b181e", "minecraft:drinking"),
("b9766b59-9566-4402-bc1f-2ee2a276d836", "minecraft:baby"),
("49455a49-7ec5-45ba-b886-3b90b23a1718", "minecraft:attacking"),
("845db27c-c624-495f-8c9f-6020a9a58b6b", "minecraft:armor.boots"),
("d8499b04-0e66-4726-ab29-64469d734e0d", "minecraft:armor.leggings"),
("9f3d476d-c118-4544-8365-64846904b48e", "minecraft:armor.chestplate"),
("2ad3f246-fee1-4e67-b886-69fd380bb150", "minecraft:armor.helmet"),
("c1c72771-8b8e-ba4a-ace0-81a93c8928b2", "minecraft:armor.body"),
("b572ecd2-ac0c-4071-abde-9594af072a37", "minecraft:enchantment.fire_protection"),
("40a9968f-5c66-4e2f-b7f4-2ec2f4b3e450", "minecraft:enchantment.blast_protection"),
("07a65791-f64d-4e79-86c7-f83932f007ec", "minecraft:enchantment.respiration"),
("60b1b7db-fffd-4ad0-817c-d6c6a93d8a45", "minecraft:enchantment.aqua_affinity"),
("11dc269a-4476-46c0-aff3-9e17d7eb6801", "minecraft:enchantment.depth_strider"),
("87f46a96-686f-4796-b035-22e16ee9e038", "minecraft:enchantment.soul_speed"),
("b9716dbd-50df-4080-850e-70347d24e687", "minecraft:enchantment.soul_speed"),
("92437d00-c3a7-4f2e-8f6c-1f21585d5dd0", "minecraft:enchantment.swift_sneak"),
("5d3d087b-debe-4037-b53e-d84f3ff51f17", "minecraft:enchantment.sweeping_edge"),
("3ceb37c0-db62-46b5-bd02-785457b01d96", "minecraft:enchantment.efficiency"),
("cb3f55d3-645c-4f38-a497-9c13a33db5cf", "minecraft:base_attack_damage"),
("fa233e1c-4180-4865-b01b-bcce9785aca3", "minecraft:base_attack_speed"),
(
"49455a49-7ec5-45ba-b886-3b90b23a1718",
"minecraft:attacking",
),
(
"845db27c-c624-495f-8c9f-6020a9a58b6b",
"minecraft:armor.boots",
),
(
"d8499b04-0e66-4726-ab29-64469d734e0d",
"minecraft:armor.leggings",
),
(
"9f3d476d-c118-4544-8365-64846904b48e",
"minecraft:armor.chestplate",
),
(
"2ad3f246-fee1-4e67-b886-69fd380bb150",
"minecraft:armor.helmet",
),
(
"c1c72771-8b8e-ba4a-ace0-81a93c8928b2",
"minecraft:armor.body",
),
(
"b572ecd2-ac0c-4071-abde-9594af072a37",
"minecraft:enchantment.fire_protection",
),
(
"40a9968f-5c66-4e2f-b7f4-2ec2f4b3e450",
"minecraft:enchantment.blast_protection",
),
(
"07a65791-f64d-4e79-86c7-f83932f007ec",
"minecraft:enchantment.respiration",
),
(
"60b1b7db-fffd-4ad0-817c-d6c6a93d8a45",
"minecraft:enchantment.aqua_affinity",
),
(
"11dc269a-4476-46c0-aff3-9e17d7eb6801",
"minecraft:enchantment.depth_strider",
),
(
"87f46a96-686f-4796-b035-22e16ee9e038",
"minecraft:enchantment.soul_speed",
),
(
"b9716dbd-50df-4080-850e-70347d24e687",
"minecraft:enchantment.soul_speed",
),
(
"92437d00-c3a7-4f2e-8f6c-1f21585d5dd0",
"minecraft:enchantment.swift_sneak",
),
(
"5d3d087b-debe-4037-b53e-d84f3ff51f17",
"minecraft:enchantment.sweeping_edge",
),
(
"3ceb37c0-db62-46b5-bd02-785457b01d96",
"minecraft:enchantment.efficiency",
),
(
"cb3f55d3-645c-4f38-a497-9c13a33db5cf",
"minecraft:base_attack_damage",
),
(
"fa233e1c-4180-4865-b01b-bcce9785aca3",
"minecraft:base_attack_speed",
),
];
const MODIFIER_NAMES: &[(&str, &str)] = &[
("Random spawn bonus", "minecraft:random_spawn_bonus"),
("Random zombie-spawn bonus", "minecraft:zombie_random_spawn_bonus"),
(
"Random zombie-spawn bonus",
"minecraft:zombie_random_spawn_bonus",
),
("Leader zombie bonus", "minecraft:leader_zombie_bonus"),
("Zombie reinforcement callee charge", "minecraft:reinforcement_callee_charge"),
("Zombie reinforcement caller charge", "minecraft:reinforcement_caller_charge"),
(
"Zombie reinforcement callee charge",
"minecraft:reinforcement_callee_charge",
),
(
"Zombie reinforcement caller charge",
"minecraft:reinforcement_caller_charge",
),
];
/// `asIntStream` of a UUID field, as `uuidFromIntArray` wants it.
fn uuid_of(v: Option<&Tag>) -> Option<[i32; 4]> {
let ints: Vec<i32> = match v {
Some(Tag::IntArray(a)) => a.clone(),
other => stream(other).iter().map(|t| as_number(t).map_or(0, |n| n.int_value())).collect(),
other => stream(other)
.iter()
.map(|t| as_number(t).map_or(0, |n| n.int_value()))
.collect(),
};
(ints.len() == 4).then(|| [ints[0], ints[1], ints[2], ints[3]])
}
@@ -231,8 +423,13 @@ fn fix_modifiers(modifiers: Vec<Tag>) -> Vec<Tag> {
for mut m in modifiers {
let uuid = uuid_of(m.get("uuid")).map(uuid_text);
let name = as_string(m.get("name"), "");
let from_uuid = uuid.as_deref().and_then(|u| MODIFIER_IDS.iter().find(|(k, _)| *k == u).map(|(_, v)| *v));
let from_name = MODIFIER_NAMES.iter().find(|(k, _)| *k == name).map(|(_, v)| *v);
let from_uuid = uuid
.as_deref()
.and_then(|u| MODIFIER_IDS.iter().find(|(k, _)| *k == u).map(|(_, v)| *v));
let from_name = MODIFIER_NAMES
.iter()
.find(|(k, _)| *k == name)
.map(|(_, v)| *v);
if let Some(id) = from_uuid {
set(&mut m, "id", string(id));
remove(&mut m, "uuid");
@@ -316,7 +513,8 @@ fn attribute_modifier_ids(cx: &mut Cx) {
fn jukebox_ticks(cx: &mut Cx) {
cx.block_entity("minecraft:jukebox", |be| {
let ticks = as_long(be.get("TickCount"), 0).wrapping_sub(as_long(be.get("RecordStartTick"), 0));
let ticks =
as_long(be.get("TickCount"), 0).wrapping_sub(as_long(be.get("RecordStartTick"), 0));
remove(be, "IsPlaying");
remove(be, "TickCount");
remove(be, "RecordStartTick");
@@ -330,13 +528,17 @@ fn jukebox_ticks(cx: &mut Cx) {
fn ominous_banner_rarity(cx: &mut Cx) {
let fix = |c: &mut Tag| {
if c.get("minecraft:item_name").and_then(translation_key).as_deref() == Some("block.minecraft.ominous_banner") {
if c.get("minecraft:item_name")
.and_then(translation_key)
.as_deref()
== Some("block.minecraft.ominous_banner")
{
set(
c,
"minecraft:item_name",
Tag::String(crate::nbt::JavaString(super::json::translatable_component_json(
"block.minecraft.ominous_banner",
))),
Tag::String(crate::nbt::JavaString(
super::json::translatable_component_json("block.minecraft.ominous_banner"),
)),
);
set(c, "minecraft:rarity", string("uncommon"));
}
@@ -346,11 +548,14 @@ fn ominous_banner_rarity(cx: &mut Cx) {
fix(c);
}
});
cx.item(|id| id == "minecraft:white_banner", |s| {
if let Some(c) = s.get_mut("components") {
fix(c);
}
});
cx.item(
|id| id == "minecraft:white_banner",
|s| {
if let Some(c) = s.get_mut("components") {
fix(c);
}
},
);
}
fn attribute_id_prefix(id: &str) -> Option<String> {
@@ -365,7 +570,11 @@ fn attribute_id_prefix(id: &str) -> Option<String> {
}
/// `AttributesRenameFix`.
pub(super) fn attributes_rename(cx: &mut Cx, old_component_format: bool, rename_fn: &dyn Fn(&str) -> Option<String>) {
pub(super) fn attributes_rename(
cx: &mut Cx,
old_component_format: bool,
rename_fn: &dyn Fn(&str) -> Option<String>,
) {
let fix_field = |v: &mut Tag, field: &str| {
if let Some(s) = as_str(v.get(field))
&& let Some(new) = rename_fn(&s)
@@ -377,7 +586,11 @@ pub(super) fn attributes_rename(cx: &mut Cx, old_component_format: bool, rename_
let Some(a) = c.get_mut("minecraft:attribute_modifiers") else {
return;
};
let list = if old_component_format { a.get_mut("modifiers") } else { Some(a) };
let list = if old_component_format {
a.get_mut("modifiers")
} else {
Some(a)
};
if let Some(Tag::List(mods)) = list {
for m in mods {
fix_field(m, "type");
@@ -408,8 +621,14 @@ fn food_to_consumable(cx: &mut Cx) {
.map(|e| {
Tag::compound([
("type", string("minecraft:apply_effects")),
("effects", Tag::List(e.get("effect").cloned().into_iter().collect())),
("probability", Tag::Float(as_float(e.get("probability"), 1.0).to_bits())),
(
"effects",
Tag::List(e.get("effect").cloned().into_iter().collect()),
),
(
"probability",
Tag::Float(as_float(e.get("probability"), 1.0).to_bits()),
),
])
})
.collect();
@@ -504,7 +723,9 @@ const TRIAL_CONFIGS: &[(&str, &str, &str)] = &[
];
fn snbt(s: &str) -> Tag {
crate::nbt::parse_snbt(s).map(|(t, _)| t).unwrap_or_else(|_| empty_map())
crate::nbt::parse_snbt(s)
.map(|(t, _)| t)
.unwrap_or_else(|_| empty_map())
}
/// `CompoundTag.merge`.
fn merge(into: &mut Tag, other: &Tag) {
@@ -560,12 +781,21 @@ fn trial_config_key(normal: &Tag, ominous: &Tag) -> Option<&'static str> {
fn trial_spawner_config_in_registry(cx: &mut Cx) {
cx.block_entity("minecraft:trial_spawner", |be| {
let (Some(normal), Some(ominous)) = (be.get("normal_config"), be.get("ominous_config")) else {
let (Some(normal), Some(ominous)) = (be.get("normal_config"), be.get("ominous_config"))
else {
return;
};
if let Some(name) = trial_config_key(normal, ominous) {
set(be, "normal_config", string(&format!("minecraft:{name}/normal")));
set(be, "ominous_config", string(&format!("minecraft:{name}/ominous")));
set(
be,
"normal_config",
string(&format!("minecraft:{name}/normal")),
);
set(
be,
"ominous_config",
string(&format!("minecraft:{name}/ominous")),
);
}
});
}
@@ -618,10 +848,13 @@ fn fix_lock(v: Tag) -> Option<Tag> {
/// `InvalidLockComponentFix.isBrokenLock`: `{components: {custom_name: '""'}}`.
fn broken_lock(v: &Tag) -> bool {
let one = |t: &Tag, field: &str| matches!(t, Tag::Compound(c) if c.len() == 1) && t.get(field).is_some();
let one = |t: &Tag, field: &str| {
matches!(t, Tag::Compound(c) if c.len() == 1) && t.get(field).is_some()
};
one(v, "components")
&& v.get("components").is_some_and(|c| {
one(c, "minecraft:custom_name") && as_str(c.get("minecraft:custom_name")).as_deref() == Some("\"\"")
one(c, "minecraft:custom_name")
&& as_str(c.get("minecraft:custom_name")).as_deref() == Some("\"\"")
})
}
@@ -662,15 +895,23 @@ fn base_value(cx: &mut Cx, entity: &str, attribute: &str, from: f64, to: f64) {
fn drop_chances_format(cx: &mut Cx) {
cx.each(Ty::Entity, |e| {
let parse = |v: Option<&Tag>| -> Vec<f32> { stream(v).iter().map(|t| as_float(Some(t), 0.085)).collect() };
let parse = |v: Option<&Tag>| -> Vec<f32> {
stream(v).iter().map(|t| as_float(Some(t), 0.085)).collect()
};
let armor = parse(e.get("ArmorDropChances"));
let hands = parse(e.get("HandDropChances"));
let body = e.get("body_armor_drop_chance").and_then(as_number).map_or(0.085, |n| n.float_value());
let body = e
.get("body_armor_drop_chance")
.and_then(as_number)
.map_or(0.085, |n| n.float_value());
remove(e, "ArmorDropChances");
remove(e, "HandDropChances");
remove(e, "body_armor_drop_chance");
let mut chances = empty_map();
for (slots, values) in [(&["feet", "legs", "chest", "head"][..], &armor), (&["mainhand", "offhand"][..], &hands)] {
for (slots, values) in [
(&["feet", "legs", "chest", "head"][..], &armor),
(&["mainhand", "offhand"][..], &hands),
] {
for (slot, chance) in slots.iter().zip(values.iter()) {
if *chance != 0.085 {
set(&mut chances, slot, Tag::Float(chance.to_bits()));
@@ -687,13 +928,21 @@ fn drop_chances_format(cx: &mut Cx) {
}
/// `LegacyBlockPropertyRenameAndFix`.
fn block_property_rename(cx: &mut Cx, block: &str, old: &str, new: &str, f: &dyn Fn(&str) -> String) {
fn block_property_rename(
cx: &mut Cx,
block: &str,
old: &str,
new: &str,
f: &dyn Fn(&str) -> String,
) {
cx.each(Ty::BlockState, |s| {
if as_str(s.get("Name")).map(|n| namespaced(&n)).as_deref() != Some(block) {
return;
}
if let Some(props) = s.get_mut("Properties") {
rename_and_fix(props, old, new, |v| Some(string(&f(&as_string(Some(&v), "")))));
rename_and_fix(props, old, new, |v| {
Some(string(&f(&as_string(Some(&v), ""))))
});
}
});
}
@@ -704,7 +953,10 @@ fn forced_chunk_to_ticket(cx: &mut Cx) {
rename_and_fix(data, "Forced", "tickets", |forced| {
let longs: Vec<i64> = match &forced {
Tag::LongArray(a) => a.clone(),
other => stream(Some(other)).iter().map(|t| as_long(Some(t), 0)).collect(),
other => stream(Some(other))
.iter()
.map(|t| as_long(Some(t), 0))
.collect(),
};
Some(Tag::List(
longs
@@ -787,8 +1039,16 @@ fn entity_spawner_item_variants(cx: &mut Cx) {
b
});
set(c, "minecraft:tropical_fish/pattern", string(pattern));
set(c, "minecraft:tropical_fish/base_color", string(dye_color(packed >> 16 & 0xFF)));
set(c, "minecraft:tropical_fish/pattern_color", string(dye_color(packed >> 24 & 0xFF)));
set(
c,
"minecraft:tropical_fish/base_color",
string(dye_color(packed >> 16 & 0xFF)),
);
set(
c,
"minecraft:tropical_fish/pattern_color",
string(dye_color(packed >> 24 & 0xFF)),
);
}
}
_ => {}
@@ -831,8 +1091,14 @@ fn saddle_equipment_slot(cx: &mut Cx) {
cx.each(Ty::Entity, |e| {
let id = namespaced(&as_str(e.get("id")).unwrap_or_default());
match id.as_str() {
"minecraft:horse" | "minecraft:skeleton_horse" | "minecraft:zombie_horse" | "minecraft:donkey"
| "minecraft:mule" | "minecraft:camel" | "minecraft:llama" | "minecraft:trader_llama" => {
"minecraft:horse"
| "minecraft:skeleton_horse"
| "minecraft:zombie_horse"
| "minecraft:donkey"
| "minecraft:mule"
| "minecraft:camel"
| "minecraft:llama"
| "minecraft:trader_llama" => {
if e.get("SaddleItem").is_some() {
rename(e, "SaddleItem", "saddle");
saddle_drop_chance(e);
@@ -843,7 +1109,11 @@ fn saddle_equipment_slot(cx: &mut Cx) {
let saddled = as_bool(e.get("Saddle"), false);
remove(e, "Saddle");
if saddled {
set(e, "saddle", Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]));
set(
e,
"saddle",
Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]),
);
saddle_drop_chance(e);
}
reread(k, e);
@@ -910,8 +1180,16 @@ fn thrown_potion_split(cx: &mut Cx) {
if !id_is(e, "minecraft:potion") {
return;
}
let item = e.get("Item").and_then(|i| as_str(i.get("id"))).map(|i| namespaced(&i)).unwrap_or_default();
let new = if item == "minecraft:lingering_potion" { "minecraft:lingering_potion" } else { "minecraft:splash_potion" };
let item = e
.get("Item")
.and_then(|i| as_str(i.get("id")))
.map(|i| namespaced(&i))
.unwrap_or_default();
let new = if item == "minecraft:lingering_potion" {
"minecraft:lingering_potion"
} else {
"minecraft:splash_potion"
};
set(e, "id", string(new));
});
}
@@ -969,9 +1247,19 @@ fn tooltip_display(cx: &mut Cx) {
fix_component(c, &mut hidden, "minecraft:trim", None);
fix_component(c, &mut hidden, "minecraft:unbreakable", None);
fix_component(c, &mut hidden, "minecraft:dyed_color", Some("rgb"));
fix_component(c, &mut hidden, "minecraft:attribute_modifiers", Some("modifiers"));
fix_component(
c,
&mut hidden,
"minecraft:attribute_modifiers",
Some("modifiers"),
);
fix_component(c, &mut hidden, "minecraft:enchantments", Some("levels"));
fix_component(c, &mut hidden, "minecraft:stored_enchantments", Some("levels"));
fix_component(
c,
&mut hidden,
"minecraft:stored_enchantments",
Some("levels"),
);
fix_component(c, &mut hidden, "minecraft:jukebox_playable", Some("song"));
let hide_tooltip = remove(c, "minecraft:hide_tooltip").is_some();
let hide_additional = remove(c, "minecraft:hide_additional_tooltip").is_some();
@@ -990,7 +1278,10 @@ fn tooltip_display(cx: &mut Cx) {
"minecraft:tooltip_display",
Tag::compound([
("hide_tooltip", Tag::Byte(i8::from(hide_tooltip))),
("hidden_components", Tag::List(hidden.iter().map(|s| string(s)).collect())),
(
"hidden_components",
Tag::List(hidden.iter().map(|s| string(s)).collect()),
),
]),
);
}
@@ -1111,12 +1402,22 @@ fn inline_block_pos_format(cx: &mut Cx) {
p.get("SpawnZ").and_then(as_number),
);
if let (Some(x), Some(y), Some(z)) = spawn {
let mut respawn = Tag::compound([("pos", Tag::IntArray(vec![x.int_value(), y.int_value(), z.int_value()]))]);
let mut respawn = Tag::compound([(
"pos",
Tag::IntArray(vec![x.int_value(), y.int_value(), z.int_value()]),
)]);
let source = p.clone();
super::dynamic::copy_field(&source, "SpawnAngle", &mut respawn, "angle");
super::dynamic::copy_field(&source, "SpawnDimension", &mut respawn, "dimension");
super::dynamic::copy_field(&source, "SpawnForced", &mut respawn, "forced");
for k in ["SpawnX", "SpawnY", "SpawnZ", "SpawnAngle", "SpawnDimension", "SpawnForced"] {
for k in [
"SpawnX",
"SpawnY",
"SpawnZ",
"SpawnAngle",
"SpawnDimension",
"SpawnForced",
] {
remove(p, k);
}
set(p, "respawn", respawn);
@@ -1126,7 +1427,10 @@ fn inline_block_pos_format(cx: &mut Cx) {
p,
"entered_nether_pos",
Tag::List(
["x", "y", "z"].iter().map(|k| Tag::Double(as_double(pos.get(k), 0.0).to_bits())).collect(),
["x", "y", "z"]
.iter()
.map(|k| Tag::Double(as_double(pos.get(k), 0.0).to_bits()))
.collect(),
),
);
}
@@ -1148,7 +1452,12 @@ fn inline_block_pos_format(cx: &mut Cx) {
fix_inline_block_pos(e, "HomePosX", "HomePosY", "HomePosZ", "home_pos");
rename(e, "HasEgg", "has_egg");
}
for id in ["minecraft:item_frame", "minecraft:glow_item_frame", "minecraft:painting", "minecraft:leash_knot"] {
for id in [
"minecraft:item_frame",
"minecraft:glow_item_frame",
"minecraft:painting",
"minecraft:leash_knot",
] {
if id_is(e, id) {
fix_inline_block_pos(e, "TileX", "TileY", "TileZ", "block_pos");
}
+466 -127
View File
@@ -1,7 +1,7 @@
//! Fixes of 1.21.6 to 26.3 (keys 4424 to 5016).
use super::dynamic::{
as_bool, as_double, as_float, as_int, as_long, as_str, as_string, boolean, empty_map, int_list, namespaced, remove,
rename, rename_and_fix, set, stream, string, update,
as_bool, as_double, as_float, as_int, as_long, as_str, as_string, boolean, empty_map, int_list,
namespaced, remove, rename, rename_and_fix, set, stream, string, update,
};
use super::fixes_a::{block_rename, component_fix};
use super::fixes_b::{advancements_rename, attributes_rename, feature_flag_remove};
@@ -20,9 +20,15 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
super::drop_typed(e, "Particle");
});
}));
out.push((key(4424, 0), |cx| feature_flag_remove(cx, &["minecraft:locator_bar"])));
out.push((key(4424, 0), |cx| cx.each(Ty::Player, add_locator_bar_style)));
out.push((key(4424, 0), |cx| cx.each(Ty::Entity, add_locator_bar_style)));
out.push((key(4424, 0), |cx| {
feature_flag_remove(cx, &["minecraft:locator_bar"])
}));
out.push((key(4424, 0), |cx| {
cx.each(Ty::Player, add_locator_bar_style)
}));
out.push((key(4424, 0), |cx| {
cx.each(Ty::Entity, add_locator_bar_style)
}));
out.push((key(4535, 0), |cx| {
cx.entity("minecraft:copper_golem", |e| {
update(e, "weather_state", |v| {
@@ -46,8 +52,15 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
}
});
}));
out.push((key(4541, 0), |cx| block_rename(cx, &[("minecraft:chain", "minecraft:iron_chain")])));
out.push((key(4541, 0), |cx| cx.rename(Ty::ItemName, renamer(&[("minecraft:chain", "minecraft:iron_chain")]))));
out.push((key(4541, 0), |cx| {
block_rename(cx, &[("minecraft:chain", "minecraft:iron_chain")])
}));
out.push((key(4541, 0), |cx| {
cx.rename(
Ty::ItemName,
renamer(&[("minecraft:chain", "minecraft:iron_chain")]),
)
}));
out.push((key(4544, 0), legacy_world_border));
out.push((key(4548, 0), world_spawn_data));
out.push((key(4548, 0), |cx| {
@@ -64,43 +77,63 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
});
}));
out.push((key(4649, 0), |cx| {
component_fix(cx, "minecraft:consumable", "minecraft:consumable", |mut c| {
if as_str(c.get("animation")).as_deref() == Some("spear") {
set(&mut c, "animation", string("trident"));
}
Some(c)
});
component_fix(
cx,
"minecraft:consumable",
"minecraft:consumable",
|mut c| {
if as_str(c.get("animation")).as_deref() == Some("spear") {
set(&mut c, "animation", string("trident"));
}
Some(c)
},
);
}));
out.push((key(4657, 0), |cx| {
cx.each_out(Ty::SavedWorldBorder, |v| {
if let Some(d) = v.get_mut("data") {
update(d, "warning_time", |t| Tag::Int(as_int(Some(&t), 15).wrapping_mul(20)));
update(d, "warning_time", |t| {
Tag::Int(as_int(Some(&t), 15).wrapping_mul(20))
});
}
});
}));
out.push((key(4658, 0), game_rule_registry));
out.push((key(4763, 0), |cx| {
cx.entity("minecraft:villager", |e| set(e, "VillagerDataFinalized", boolean(true)));
cx.entity("minecraft:villager", |e| {
set(e, "VillagerDataFinalized", boolean(true))
});
}));
out.push((key(4763, 0), |cx| {
cx.entity("minecraft:zombie_villager", |e| set(e, "VillagerDataFinalized", boolean(true)));
cx.entity("minecraft:zombie_villager", |e| {
set(e, "VillagerDataFinalized", boolean(true))
});
}));
out.push((key(4766, 0), day_time_to_clock));
out.push((key(4769, 0), |cx| cx.rename(Ty::Recipe, renamer(STONECUTTER_RECIPES))));
out.push((key(4769, 0), |cx| {
cx.rename(Ty::Recipe, renamer(STONECUTTER_RECIPES))
}));
out.push((key(4769, 0), |cx| {
advancements_rename(cx, &|id| {
let id = namespaced(id);
STONECUTTER_ADVANCEMENTS.iter().find(|(from, _)| *from == id).map(|(_, to)| (*to).to_owned())
STONECUTTER_ADVANCEMENTS
.iter()
.find(|(from, _)| *from == id)
.map(|(_, to)| (*to).to_owned())
});
}));
out.push((key(4771, 0), level_dat_difficulty));
out.push((key(4771, 0), level_dat_to_saved_data_preparation));
out.push((key(4885, 0), remove_bed_block_entities));
out.push((key(4888, 0), |cx| {
attributes_rename(cx, false, &|id| (id == "minecraft:nameplate_distance").then(|| "minecraft:name_tag_distance".into()));
attributes_rename(cx, false, &|id| {
(id == "minecraft:nameplate_distance").then(|| "minecraft:name_tag_distance".into())
});
}));
out.push((key(4996, 0), |cx| {
cx.each_out(Ty::DataComponents, |c| update(c, "minecraft:pot_decorations", unpack_pot_decorations));
cx.each_out(Ty::DataComponents, |c| {
update(c, "minecraft:pot_decorations", unpack_pot_decorations)
});
}));
out.push((key(4996, 1), |cx| {
cx.block_entity("minecraft:decorated_pot", |be| {
@@ -110,10 +143,14 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
}));
out.push((key(4997, 0), |cx| cx.each_out(Ty::Chunk, blending_data)));
out.push((key(5002, 0), |cx| {
cx.block_entity("minecraft:sign", |be| set(be, "allow_op_features", boolean(true)));
cx.block_entity("minecraft:sign", |be| {
set(be, "allow_op_features", boolean(true))
});
}));
out.push((key(5002, 0), |cx| {
cx.block_entity("minecraft:hanging_sign", |be| set(be, "allow_op_features", boolean(true)));
cx.block_entity("minecraft:hanging_sign", |be| {
set(be, "allow_op_features", boolean(true))
});
}));
out.push((key(5006, 0), |cx| {
cx.each(Ty::BlockState, |s| {
@@ -130,7 +167,9 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
});
}));
out.push((key(5008, 0), explorer_map_item));
out.push((key(5008, 0), |cx| component_fix(cx, "minecraft:map_color", "minecraft:map_color", |_| None)));
out.push((key(5008, 0), |cx| {
component_fix(cx, "minecraft:map_color", "minecraft:map_color", |_| None)
}));
out.push((key(5009, 0), |cx| {
cx.each(Ty::Chunk, |c| {
if let Some(b) = c.get_mut("blending_data") {
@@ -153,11 +192,23 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
cx.rename(
Ty::ItemName,
renamer(&[
("minecraft:ocean_explorer_map", "minecraft:ocean_monument_map"),
(
"minecraft:ocean_explorer_map",
"minecraft:ocean_monument_map",
),
("minecraft:swamp_explorer_map", "minecraft:swamp_hut_map"),
("minecraft:trial_explorer_map", "minecraft:buried_trial_chambers_map"),
("minecraft:woodland_explorer_map", "minecraft:woodland_mansion_map"),
("minecraft:jungle_explorer_map", "minecraft:jungle_pyramid_map"),
(
"minecraft:trial_explorer_map",
"minecraft:buried_trial_chambers_map",
),
(
"minecraft:woodland_explorer_map",
"minecraft:woodland_mansion_map",
),
(
"minecraft:jungle_explorer_map",
"minecraft:jungle_pyramid_map",
),
]),
);
}));
@@ -168,14 +219,21 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
});
}));
out.push((key(5016, 0), |cx| {
cx.item(|id| id == "minecraft:map", |s| {
if let Some(c) = s.get_mut("components")
&& let Some(name) = c.get_mut("minecraft:item_name")
&& plain_translation_key(name).as_deref() == Some("filled_map.buried_treasure")
{
set(name, "translate", string("item.minecraft.buried_treasure_map"));
}
});
cx.item(
|id| id == "minecraft:map",
|s| {
if let Some(c) = s.get_mut("components")
&& let Some(name) = c.get_mut("minecraft:item_name")
&& plain_translation_key(name).as_deref() == Some("filled_map.buried_treasure")
{
set(
name,
"translate",
string("item.minecraft.buried_treasure_map"),
);
}
},
);
}));
}
@@ -199,12 +257,21 @@ fn legacy_world_border(cx: &mut Cx) {
("center_x", d(l, "BorderCenterX", 0.0)),
("center_z", d(l, "BorderCenterZ", 0.0)),
("size", d(l, "BorderSize", f64::from(5.999997E7f32))),
("lerp_time", Tag::Long(as_long(l.get("BorderSizeLerpTime"), 0))),
(
"lerp_time",
Tag::Long(as_long(l.get("BorderSizeLerpTime"), 0)),
),
("lerp_target", d(l, "BorderSizeLerpTarget", 0.0)),
("safe_zone", d(l, "BorderSafeZone", 5.0)),
("damage_per_block", d(l, "BorderDamagePerBlock", 0.2)),
("warning_blocks", Tag::Int(as_int(l.get("BorderWarningBlocks"), 5))),
("warning_time", Tag::Int(as_int(l.get("BorderWarningTime"), 15))),
(
"warning_blocks",
Tag::Int(as_int(l.get("BorderWarningBlocks"), 5)),
),
(
"warning_time",
Tag::Int(as_int(l.get("BorderWarningTime"), 15)),
),
]);
for k in [
"BorderCenterX",
@@ -225,7 +292,11 @@ fn legacy_world_border(cx: &mut Cx) {
fn world_spawn_data(cx: &mut Cx) {
cx.each(Ty::Level, |l| {
let pos = [as_int(l.get("SpawnX"), 0), as_int(l.get("SpawnY"), 0), as_int(l.get("SpawnZ"), 0)];
let pos = [
as_int(l.get("SpawnX"), 0),
as_int(l.get("SpawnY"), 0),
as_int(l.get("SpawnZ"), 0),
];
let angle = as_float(l.get("SpawnAngle"), 0.0);
for k in ["SpawnX", "SpawnY", "SpawnZ", "SpawnAngle"] {
remove(l, k);
@@ -244,65 +315,213 @@ fn world_spawn_data(cx: &mut Cx) {
}
const GAME_RULES: &[(&str, &str, Conv)] = &[
("allowEnteringNetherUsingPortals", "minecraft:allow_entering_nether_using_portals", Conv::Bool),
("announceAdvancements", "minecraft:show_advancement_messages", Conv::Bool),
("blockExplosionDropDecay", "minecraft:block_explosion_drop_decay", Conv::Bool),
("commandBlockOutput", "minecraft:command_block_output", Conv::Bool),
("enableCommandBlocks", "minecraft:command_blocks_work", Conv::Bool),
("commandBlocksEnabled", "minecraft:command_blocks_work", Conv::Bool),
("commandModificationBlockLimit", "minecraft:max_block_modifications", Conv::Int(1, i32::MAX)),
("disableElytraMovementCheck", "minecraft:elytra_movement_check", Conv::NotBool),
("disablePlayerMovementCheck", "minecraft:player_movement_check", Conv::NotBool),
(
"allowEnteringNetherUsingPortals",
"minecraft:allow_entering_nether_using_portals",
Conv::Bool,
),
(
"announceAdvancements",
"minecraft:show_advancement_messages",
Conv::Bool,
),
(
"blockExplosionDropDecay",
"minecraft:block_explosion_drop_decay",
Conv::Bool,
),
(
"commandBlockOutput",
"minecraft:command_block_output",
Conv::Bool,
),
(
"enableCommandBlocks",
"minecraft:command_blocks_work",
Conv::Bool,
),
(
"commandBlocksEnabled",
"minecraft:command_blocks_work",
Conv::Bool,
),
(
"commandModificationBlockLimit",
"minecraft:max_block_modifications",
Conv::Int(1, i32::MAX),
),
(
"disableElytraMovementCheck",
"minecraft:elytra_movement_check",
Conv::NotBool,
),
(
"disablePlayerMovementCheck",
"minecraft:player_movement_check",
Conv::NotBool,
),
("disableRaids", "minecraft:raids", Conv::NotBool),
("doDaylightCycle", "minecraft:advance_time", Conv::Bool),
("doEntityDrops", "minecraft:entity_drops", Conv::Bool),
("doImmediateRespawn", "minecraft:immediate_respawn", Conv::Bool),
(
"doImmediateRespawn",
"minecraft:immediate_respawn",
Conv::Bool,
),
("doInsomnia", "minecraft:spawn_phantoms", Conv::Bool),
("doLimitedCrafting", "minecraft:limited_crafting", Conv::Bool),
(
"doLimitedCrafting",
"minecraft:limited_crafting",
Conv::Bool,
),
("doMobLoot", "minecraft:mob_drops", Conv::Bool),
("doMobSpawning", "minecraft:spawn_mobs", Conv::Bool),
("doPatrolSpawning", "minecraft:spawn_patrols", Conv::Bool),
("doTileDrops", "minecraft:block_drops", Conv::Bool),
("doTraderSpawning", "minecraft:spawn_wandering_traders", Conv::Bool),
(
"doTraderSpawning",
"minecraft:spawn_wandering_traders",
Conv::Bool,
),
("doVinesSpread", "minecraft:spread_vines", Conv::Bool),
("doWardenSpawning", "minecraft:spawn_wardens", Conv::Bool),
("doWeatherCycle", "minecraft:advance_weather", Conv::Bool),
("drowningDamage", "minecraft:drowning_damage", Conv::Bool),
("enderPearlsVanishOnDeath", "minecraft:ender_pearls_vanish_on_death", Conv::Bool),
(
"enderPearlsVanishOnDeath",
"minecraft:ender_pearls_vanish_on_death",
Conv::Bool,
),
("fallDamage", "minecraft:fall_damage", Conv::Bool),
("fireDamage", "minecraft:fire_damage", Conv::Bool),
("forgiveDeadPlayers", "minecraft:forgive_dead_players", Conv::Bool),
(
"forgiveDeadPlayers",
"minecraft:forgive_dead_players",
Conv::Bool,
),
("freezeDamage", "minecraft:freeze_damage", Conv::Bool),
("globalSoundEvents", "minecraft:global_sound_events", Conv::Bool),
(
"globalSoundEvents",
"minecraft:global_sound_events",
Conv::Bool,
),
("keepInventory", "minecraft:keep_inventory", Conv::Bool),
("lavaSourceConversion", "minecraft:lava_source_conversion", Conv::Bool),
(
"lavaSourceConversion",
"minecraft:lava_source_conversion",
Conv::Bool,
),
("locatorBar", "minecraft:locator_bar", Conv::Bool),
("logAdminCommands", "minecraft:log_admin_commands", Conv::Bool),
("maxCommandChainLength", "minecraft:max_command_sequence_length", Conv::Int(0, i32::MAX)),
("maxCommandForkCount", "minecraft:max_command_forks", Conv::Int(0, i32::MAX)),
("maxEntityCramming", "minecraft:max_entity_cramming", Conv::Int(0, i32::MAX)),
("minecartMaxSpeed", "minecraft:max_minecart_speed", Conv::Int(i32::MIN, i32::MAX)),
("mobExplosionDropDecay", "minecraft:mob_explosion_drop_decay", Conv::Bool),
(
"logAdminCommands",
"minecraft:log_admin_commands",
Conv::Bool,
),
(
"maxCommandChainLength",
"minecraft:max_command_sequence_length",
Conv::Int(0, i32::MAX),
),
(
"maxCommandForkCount",
"minecraft:max_command_forks",
Conv::Int(0, i32::MAX),
),
(
"maxEntityCramming",
"minecraft:max_entity_cramming",
Conv::Int(0, i32::MAX),
),
(
"minecartMaxSpeed",
"minecraft:max_minecart_speed",
Conv::Int(i32::MIN, i32::MAX),
),
(
"mobExplosionDropDecay",
"minecraft:mob_explosion_drop_decay",
Conv::Bool,
),
("mobGriefing", "minecraft:mob_griefing", Conv::Bool),
("naturalRegeneration", "minecraft:natural_health_regeneration", Conv::Bool),
("playersNetherPortalCreativeDelay", "minecraft:players_nether_portal_creative_delay", Conv::Int(0, i32::MAX)),
("playersNetherPortalDefaultDelay", "minecraft:players_nether_portal_default_delay", Conv::Int(0, i32::MAX)),
("playersSleepingPercentage", "minecraft:players_sleeping_percentage", Conv::Int(0, i32::MAX)),
("projectilesCanBreakBlocks", "minecraft:projectiles_can_break_blocks", Conv::Bool),
(
"naturalRegeneration",
"minecraft:natural_health_regeneration",
Conv::Bool,
),
(
"playersNetherPortalCreativeDelay",
"minecraft:players_nether_portal_creative_delay",
Conv::Int(0, i32::MAX),
),
(
"playersNetherPortalDefaultDelay",
"minecraft:players_nether_portal_default_delay",
Conv::Int(0, i32::MAX),
),
(
"playersSleepingPercentage",
"minecraft:players_sleeping_percentage",
Conv::Int(0, i32::MAX),
),
(
"projectilesCanBreakBlocks",
"minecraft:projectiles_can_break_blocks",
Conv::Bool,
),
("pvp", "minecraft:pvp", Conv::Bool),
("randomTickSpeed", "minecraft:random_tick_speed", Conv::Int(0, i32::MAX)),
("reducedDebugInfo", "minecraft:reduced_debug_info", Conv::Bool),
("sendCommandFeedback", "minecraft:send_command_feedback", Conv::Bool),
("showDeathMessages", "minecraft:show_death_messages", Conv::Bool),
("snowAccumulationHeight", "minecraft:max_snow_accumulation_height", Conv::Int(0, 8)),
(
"randomTickSpeed",
"minecraft:random_tick_speed",
Conv::Int(0, i32::MAX),
),
(
"reducedDebugInfo",
"minecraft:reduced_debug_info",
Conv::Bool,
),
(
"sendCommandFeedback",
"minecraft:send_command_feedback",
Conv::Bool,
),
(
"showDeathMessages",
"minecraft:show_death_messages",
Conv::Bool,
),
(
"snowAccumulationHeight",
"minecraft:max_snow_accumulation_height",
Conv::Int(0, 8),
),
("spawnMonsters", "minecraft:spawn_monsters", Conv::Bool),
("spawnRadius", "minecraft:respawn_radius", Conv::Int(i32::MIN, i32::MAX)),
("spawnerBlocksEnabled", "minecraft:spawner_blocks_work", Conv::Bool),
("spectatorsGenerateChunks", "minecraft:spectators_generate_chunks", Conv::Bool),
(
"spawnRadius",
"minecraft:respawn_radius",
Conv::Int(i32::MIN, i32::MAX),
),
(
"spawnerBlocksEnabled",
"minecraft:spawner_blocks_work",
Conv::Bool,
),
(
"spectatorsGenerateChunks",
"minecraft:spectators_generate_chunks",
Conv::Bool,
),
("tntExplodes", "minecraft:tnt_explodes", Conv::Bool),
("tntExplosionDropDecay", "minecraft:tnt_explosion_drop_decay", Conv::Bool),
(
"tntExplosionDropDecay",
"minecraft:tnt_explosion_drop_decay",
Conv::Bool,
),
("universalAnger", "minecraft:universal_anger", Conv::Bool),
("waterSourceConversion", "minecraft:water_source_conversion", Conv::Bool),
(
"waterSourceConversion",
"minecraft:water_source_conversion",
Conv::Bool,
),
];
#[derive(Clone, Copy)]
@@ -342,7 +561,10 @@ fn game_rule_registry(cx: &mut Cx) {
cx.each(Ty::Level, |l| {
rename_and_fix(l, "GameRules", "game_rules", |mut rules| {
let fire_tick = parse_bool(&as_string(rules.get("doFireTick"), "true"));
let away = parse_bool(&as_string(rules.get("allowFireTicksAwayFromPlayer"), "false"));
let away = parse_bool(&as_string(
rules.get("allowFireTicksAwayFromPlayer"),
"false",
));
let radius = if !fire_tick {
0
} else if !away {
@@ -351,7 +573,11 @@ fn game_rule_registry(cx: &mut Cx) {
-1
};
if radius != 128 {
set(&mut rules, "minecraft:fire_spread_radius_around_player", Tag::Int(radius));
set(
&mut rules,
"minecraft:fire_spread_radius_around_player",
Tag::Int(radius),
);
}
for k in [
"spawnChunkRadius",
@@ -375,15 +601,25 @@ fn day_time_to_clock(cx: &mut Cx) {
let game_time = as_long(l.get("Time"), 0);
let day_time = as_long(l.get("DayTime"), game_time);
remove(l, "DayTime");
let clock = Tag::compound([("total_ticks", Tag::Long(day_time)), ("paused", boolean(false))]);
set(l, "world_clocks", Tag::compound([("minecraft:overworld", clock)]));
let clock = Tag::compound([
("total_ticks", Tag::Long(day_time)),
("paused", boolean(false)),
]);
set(
l,
"world_clocks",
Tag::compound([("minecraft:overworld", clock)]),
);
});
}
// ------------------------------------------------------------------ 4769, 4771
const STONECUTTER_RECIPES: &[(&str, &str)] = &[
("minecraft:chiseled_stone_bricks_stone_from_stonecutting", "minecraft:chiseled_stone_bricks_from_stone_stonecutting"),
(
"minecraft:chiseled_stone_bricks_stone_from_stonecutting",
"minecraft:chiseled_stone_bricks_from_stone_stonecutting",
),
(
"minecraft:end_stone_brick_slab_from_end_stone_brick_stonecutting",
"minecraft:end_stone_brick_slab_from_end_stone_bricks_stonecutting",
@@ -416,8 +652,14 @@ const STONECUTTER_RECIPES: &[(&str, &str)] = &[
"minecraft:prismarine_brick_stairs_from_prismarine_stonecutting",
"minecraft:prismarine_brick_stairs_from_prismarine_bricks_stonecutting",
),
("minecraft:quartz_slab_from_stonecutting", "minecraft:quartz_slab_from_quartz_block_stonecutting"),
("minecraft:stone_brick_walls_from_stone_stonecutting", "minecraft:stone_brick_wall_from_stone_stonecutting"),
(
"minecraft:quartz_slab_from_stonecutting",
"minecraft:quartz_slab_from_quartz_block_stonecutting",
),
(
"minecraft:stone_brick_walls_from_stone_stonecutting",
"minecraft:stone_brick_wall_from_stone_stonecutting",
),
];
const STONECUTTER_ADVANCEMENTS: &[(&str, &str)] = &[
(
@@ -509,21 +751,46 @@ fn level_dat_to_saved_data_preparation(cx: &mut Cx) {
Some(fight)
});
let trader = Tag::compound([
("spawn_delay", Tag::Int(as_int(source.get("WanderingTraderSpawnDelay"), 24000))),
("spawn_chance", Tag::Int(as_int(source.get("WanderingTraderSpawnChance"), 25))),
(
"spawn_delay",
Tag::Int(as_int(source.get("WanderingTraderSpawnDelay"), 24000)),
),
(
"spawn_chance",
Tag::Int(as_int(source.get("WanderingTraderSpawnChance"), 25)),
),
]);
set(l, "wandering_trader_migration_data", trader);
for k in ["WanderingTraderSpawnDelay", "WanderingTraderSpawnChance", "WanderingTraderId"] {
for k in [
"WanderingTraderSpawnDelay",
"WanderingTraderSpawnChance",
"WanderingTraderId",
] {
remove(l, k);
}
let weather = Tag::compound([
("clear_weather_time", Tag::Int(as_int(source.get("clearWeatherTime"), 0))),
(
"clear_weather_time",
Tag::Int(as_int(source.get("clearWeatherTime"), 0)),
),
("rain_time", Tag::Int(as_int(source.get("rainTime"), 0))),
("thunder_time", Tag::Int(as_int(source.get("thunderTime"), 0))),
(
"thunder_time",
Tag::Int(as_int(source.get("thunderTime"), 0)),
),
("raining", boolean(as_bool(source.get("raining"), false))),
("thundering", boolean(as_bool(source.get("thundering"), false))),
(
"thundering",
boolean(as_bool(source.get("thundering"), false)),
),
]);
for k in ["clearWeatherTime", "rainTime", "thunderTime", "raining", "thundering"] {
for k in [
"clearWeatherTime",
"rainTime",
"thunderTime",
"raining",
"thundering",
] {
remove(l, k);
}
set(l, "weather_data", weather);
@@ -542,7 +809,11 @@ fn level_dat_to_saved_data_preparation(cx: &mut Cx) {
})
.collect();
remove(l, "ScheduledEvents");
set(l, "scheduled_events", Tag::compound([("events", Tag::List(events))]));
set(
l,
"scheduled_events",
Tag::compound([("events", Tag::List(events))]),
);
rename_and_fix(l, "WorldGenSettings", "world_gen_settings", |mut s| {
rename(&mut s, "generate_features", "generate_structures");
Some(s)
@@ -580,10 +851,17 @@ fn unpack_pot_decorations(original: Tag) -> Tag {
if !super::dynamic::is_list(Some(&original)) {
return original;
}
let ids: Vec<Option<String>> = stream(Some(&original)).iter().map(|t| as_str(Some(t))).collect();
let ids: Vec<Option<String>> = stream(Some(&original))
.iter()
.map(|t| as_str(Some(t)))
.collect();
let mut result = empty_map();
for (i, side) in ["back", "left", "right", "front"].iter().enumerate() {
let id = ids.get(i).cloned().flatten().unwrap_or_else(|| "minecraft:brick".into());
let id = ids
.get(i)
.cloned()
.flatten()
.unwrap_or_else(|| "minecraft:brick".into());
if id.is_empty() {
return original;
}
@@ -604,10 +882,18 @@ fn blending_data(c: &mut Tag) {
if !overworld {
return;
}
const SKIP: [&str; 4] = ["minecraft:empty", "minecraft:structure_starts", "minecraft:structure_references", "minecraft:biomes"];
const SKIP: [&str; 4] = [
"minecraft:empty",
"minecraft:structure_starts",
"minecraft:structure_references",
"minecraft:biomes",
];
let status = namespaced(&as_string(Some(status), "empty"));
let blending = |height: i32, min_y: i32| {
Tag::compound([("min_section", Tag::Int(min_y >> 4)), ("max_section", Tag::Int((min_y + height) >> 4))])
Tag::compound([
("min_section", Tag::Int(min_y >> 4)),
("max_section", Tag::Int((min_y + height) >> 4)),
])
};
if !SKIP.contains(&status.as_str()) {
set(c, "blending_data", blending(384, -64));
@@ -630,39 +916,89 @@ fn plain_translation_key(v: &Tag) -> Option<String> {
}
const EXPLORER_MAPS: &[(&str, &str, &str)] = &[
("minecraft:mansion", "minecraft:woodland_explorer_map", "filled_map.mansion"),
("minecraft:monument", "minecraft:ocean_explorer_map", "filled_map.monument"),
("minecraft:trial_chambers", "minecraft:trial_explorer_map", "filled_map.trial_chambers"),
("minecraft:jungle_temple", "minecraft:jungle_explorer_map", "filled_map.explorer_jungle"),
("minecraft:swamp_hut", "minecraft:swamp_explorer_map", "filled_map.explorer_swamp"),
("minecraft:village_desert", "minecraft:desert_village_map", "filled_map.village_desert"),
("minecraft:village_plains", "minecraft:plains_village_map", "filled_map.village_plains"),
("minecraft:village_savanna", "minecraft:savanna_village_map", "filled_map.village_savanna"),
("minecraft:village_snowy", "minecraft:snowy_village_map", "filled_map.village_snowy"),
("minecraft:village_taiga", "minecraft:taiga_village_map", "filled_map.village_taiga"),
("minecraft:red_x", "minecraft:buried_treasure_map", "filled_map.buried_treasure"),
(
"minecraft:mansion",
"minecraft:woodland_explorer_map",
"filled_map.mansion",
),
(
"minecraft:monument",
"minecraft:ocean_explorer_map",
"filled_map.monument",
),
(
"minecraft:trial_chambers",
"minecraft:trial_explorer_map",
"filled_map.trial_chambers",
),
(
"minecraft:jungle_temple",
"minecraft:jungle_explorer_map",
"filled_map.explorer_jungle",
),
(
"minecraft:swamp_hut",
"minecraft:swamp_explorer_map",
"filled_map.explorer_swamp",
),
(
"minecraft:village_desert",
"minecraft:desert_village_map",
"filled_map.village_desert",
),
(
"minecraft:village_plains",
"minecraft:plains_village_map",
"filled_map.village_plains",
),
(
"minecraft:village_savanna",
"minecraft:savanna_village_map",
"filled_map.village_savanna",
),
(
"minecraft:village_snowy",
"minecraft:snowy_village_map",
"filled_map.village_snowy",
),
(
"minecraft:village_taiga",
"minecraft:taiga_village_map",
"filled_map.village_taiga",
),
(
"minecraft:red_x",
"minecraft:buried_treasure_map",
"filled_map.buried_treasure",
),
];
fn explorer_map_item(cx: &mut Cx) {
cx.item(|id| id == "minecraft:filled_map", |s| {
let Some(decoration) = s
.get("components")
.and_then(|c| c.get("minecraft:map_decorations"))
.and_then(|d| d.get("+"))
else {
return;
};
let ty = namespaced(&as_string(decoration.get("type"), ""));
let Some((_, item, legacy)) = EXPLORER_MAPS.iter().find(|(t, _, _)| *t == ty) else {
return;
};
set(s, "id", string(item));
if let Some(c) = s.get_mut("components")
&& c.get("minecraft:item_name").and_then(plain_translation_key).as_deref() == Some(*legacy)
{
remove(c, "minecraft:item_name");
}
});
cx.item(
|id| id == "minecraft:filled_map",
|s| {
let Some(decoration) = s
.get("components")
.and_then(|c| c.get("minecraft:map_decorations"))
.and_then(|d| d.get("+"))
else {
return;
};
let ty = namespaced(&as_string(decoration.get("type"), ""));
let Some((_, item, legacy)) = EXPLORER_MAPS.iter().find(|(t, _, _)| *t == ty) else {
return;
};
set(s, "id", string(item));
if let Some(c) = s.get_mut("components")
&& c.get("minecraft:item_name")
.and_then(plain_translation_key)
.as_deref()
== Some(*legacy)
{
remove(c, "minecraft:item_name");
}
},
);
}
fn merge_terrain_chunk_status(cx: &mut Cx) {
@@ -686,14 +1022,17 @@ fn merge_terrain_chunk_status(cx: &mut Cx) {
old_target = Some(target);
}
let status_intermediate = INTERMEDIATE.contains(&old_status.as_str());
let target_intermediate = old_target.as_deref().is_some_and(|t| INTERMEDIATE.contains(&t));
let target_intermediate = old_target
.as_deref()
.is_some_and(|t| INTERMEDIATE.contains(&t));
if status_intermediate || target_intermediate {
let only_below_zero = old_target.is_some() && !target_intermediate;
remove(c, "Heightmaps");
remove(c, "blending_data");
if let Some(Tag::List(sections)) = c.get_mut("sections") {
for s in sections {
let y = super::dynamic::as_number(s.get("Y").unwrap_or(&Tag::End)).map_or(0, |n| n.byte_value());
let y = super::dynamic::as_number(s.get("Y").unwrap_or(&Tag::End))
.map_or(0, |n| n.byte_value());
if !(y >= 0 && only_below_zero) {
remove(s, "block_states");
}
+216 -57
View File
@@ -1,7 +1,9 @@
//! 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::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};
@@ -10,11 +12,18 @@ 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(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())
CAT_TEXTURES
.iter()
.find(|(from, _)| *from == s)
.map(|(_, to)| (*to).to_owned())
});
}));
out.push((key(3087, 0), |cx| {
@@ -54,7 +63,10 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
}));
out.push((key(3097, 0), |cx| {
poi_records(cx, |r| {
!matches!(as_str(r.get("type")).as_deref(), Some("minecraft:unemployed" | "minecraft:nitwit") | None)
!matches!(
as_str(r.get("type")).as_deref(),
Some("minecraft:unemployed" | "minecraft:nitwit") | None
)
})
}));
out.push((key(3108, 0), |cx| {
@@ -82,15 +94,24 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
}
})
}));
out.push((key(3438, 0), |cx| cx.rename(Ty::ItemName, renamer(POTTERY_SHARDS))));
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(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(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)
POTTERY_SHERDS
.iter()
.find(|(from, _)| *from == id)
.map(|(_, to)| *to)
})
}));
// DecoratedPotFieldRenameFix converts unchecked: the typed shards are written
@@ -115,7 +136,10 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) {
/// `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);
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");
@@ -199,7 +223,10 @@ const CAT_TEXTURES: &[(&str, &str)] = &[
("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/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"),
@@ -254,7 +281,11 @@ fn goat_horn_id(cx: &mut 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 }];
let sound = INSTRUMENTS[if (0..8).contains(&variant) {
variant as usize
} else {
0
}];
remove(tag, "SoundVariant");
set(tag, "instrument", string(sound));
},
@@ -294,7 +325,10 @@ fn poi_records(cx: &mut Cx, keep: impl Fn(&Tag) -> bool) {
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();
let kept: Vec<Tag> = stream(Some(records))
.into_iter()
.filter(|r| keep(r))
.collect();
set(section, "Records", Tag::List(kept));
}
}
@@ -309,7 +343,10 @@ 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")));
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()
@@ -329,11 +366,17 @@ const SPAWN_EGGS: &[(&str, &str)] = &[
("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: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: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"),
@@ -353,7 +396,10 @@ const SPAWN_EGGS: &[(&str, &str)] = &[
("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: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"),
@@ -362,21 +408,37 @@ const SPAWN_EGGS: &[(&str, &str)] = &[
("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: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: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"),
(
"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"];
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 {
@@ -389,9 +451,14 @@ fn effect_list(list: Tag) -> Tag {
.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);
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)));
set(
&mut data,
"ticks_active",
Tag::Int(timestamp.wrapping_sub(duration)),
);
data
});
effect
@@ -408,39 +475,115 @@ fn effect_duration(cx: &mut Cx) {
};
cx.each(Ty::Entity, living);
cx.each(Ty::Player, living);
item_tag(cx, |id| POTION_ITEMS.contains(&id), |tag| update(tag, "CustomPotionEffects", effect_list));
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"),
(
"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"),
(
"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
@@ -454,16 +597,32 @@ fn empty_component() -> Tag {
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 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)));
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();
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));
+323 -64
View File
@@ -1,8 +1,8 @@
//! Item stacks: the V705 read hook (`ADD_NAMES`), `ItemStackComponentizationFix`
//! (1.20.5) and `ParticleUnflatteningFix`.
use super::dynamic::{
as_bool, as_bool_opt, as_double, as_int, as_long, as_number, as_str, as_string, empty_map, int_list, is_empty_map,
namespaced, remove, rename, set, stream, string,
as_bool, as_bool_opt, as_double, as_int, as_long, as_number, as_str, as_string, empty_map,
int_list, is_empty_map, namespaced, remove, rename, set, stream, string,
};
use super::json;
use crate::nbt::{JavaString, Tag};
@@ -30,7 +30,10 @@ const ITEM_TO_BLOCK_ENTITY: &[(&str, &str)] = &[
("minecraft:hopper", "minecraft:hopper"),
("minecraft:banner", "minecraft:banner"),
("minecraft:flower_pot", "minecraft:flower_pot"),
("minecraft:repeating_command_block", "minecraft:command_block"),
(
"minecraft:repeating_command_block",
"minecraft:command_block",
),
("minecraft:chain_command_block", "minecraft:command_block"),
("minecraft:shulker_box", "minecraft:shulker_box"),
("minecraft:white_shulker_box", "minecraft:shulker_box"),
@@ -71,7 +74,10 @@ const ITEM_TO_BLOCK_ENTITY: &[(&str, &str)] = &[
("minecraft:standing_sign", "minecraft:sign"),
("minecraft:wall_sign", "minecraft:sign"),
("minecraft:piston_head", "minecraft:piston"),
("minecraft:daylight_detector_inverted", "minecraft:daylight_detector"),
(
"minecraft:daylight_detector_inverted",
"minecraft:daylight_detector",
),
("minecraft:unpowered_comparator", "minecraft:comparator"),
("minecraft:powered_comparator", "minecraft:comparator"),
("minecraft:wall_banner", "minecraft:banner"),
@@ -128,33 +134,118 @@ const ITEM_TO_BLOCK_ENTITY: &[(&str, &str)] = &[
/// `V705.ITEM_TO_ENTITY`: spawn eggs and the items that place an entity.
fn item_to_entity(item: &str) -> Option<String> {
if let Some(mob) = item.strip_suffix("_spawn_egg").and_then(|m| m.strip_prefix("minecraft:"))
if let Some(mob) = item
.strip_suffix("_spawn_egg")
.and_then(|m| m.strip_prefix("minecraft:"))
&& SPAWN_EGG_MOBS.contains(&mob)
{
return Some(format!("minecraft:{mob}"));
}
match item {
"minecraft:armor_stand" | "minecraft:painting" | "minecraft:item_frame" | "minecraft:minecart"
| "minecraft:chest_minecart" | "minecraft:furnace_minecart" | "minecraft:tnt_minecart"
| "minecraft:hopper_minecart" | "minecraft:bamboo_raft" | "minecraft:bamboo_chest_raft" => Some(item.to_owned()),
"minecraft:armor_stand"
| "minecraft:painting"
| "minecraft:item_frame"
| "minecraft:minecart"
| "minecraft:chest_minecart"
| "minecraft:furnace_minecart"
| "minecraft:tnt_minecart"
| "minecraft:hopper_minecart"
| "minecraft:bamboo_raft"
| "minecraft:bamboo_chest_raft" => Some(item.to_owned()),
"minecraft:boat" => Some("minecraft:oak_boat".into()),
_ => {
let wood = item.strip_prefix("minecraft:")?;
let wood = wood.strip_suffix("_chest_boat").or_else(|| wood.strip_suffix("_boat"))?;
let wood = wood
.strip_suffix("_chest_boat")
.or_else(|| wood.strip_suffix("_boat"))?;
BOAT_WOODS.contains(&wood).then(|| item.to_owned())
}
}
}
const BOAT_WOODS: [&str; 8] = ["oak", "spruce", "birch", "jungle", "acacia", "cherry", "dark_oak", "mangrove"];
const BOAT_WOODS: [&str; 8] = [
"oak", "spruce", "birch", "jungle", "acacia", "cherry", "dark_oak", "mangrove",
];
const SPAWN_EGG_MOBS: &[&str] = &[
"armadillo", "allay", "axolotl", "bat", "bee", "blaze", "bogged", "breeze", "cat", "camel", "cave_spider", "chicken",
"cod", "cow", "creeper", "dolphin", "donkey", "drowned", "elder_guardian", "ender_dragon", "enderman", "endermite",
"evoker", "fox", "frog", "ghast", "glow_squid", "goat", "guardian", "hoglin", "horse", "husk", "iron_golem", "llama",
"magma_cube", "mooshroom", "mule", "ocelot", "panda", "parrot", "phantom", "pig", "piglin", "piglin_brute",
"pillager", "polar_bear", "pufferfish", "rabbit", "ravager", "salmon", "sheep", "shulker", "silverfish", "skeleton",
"skeleton_horse", "slime", "sniffer", "snow_golem", "spider", "squid", "stray", "strider", "tadpole", "trader_llama",
"tropical_fish", "turtle", "vex", "villager", "vindicator", "wandering_trader", "warden", "witch", "wither",
"wither_skeleton", "wolf", "zoglin", "zombie", "zombie_horse", "zombie_villager", "zombified_piglin",
"armadillo",
"allay",
"axolotl",
"bat",
"bee",
"blaze",
"bogged",
"breeze",
"cat",
"camel",
"cave_spider",
"chicken",
"cod",
"cow",
"creeper",
"dolphin",
"donkey",
"drowned",
"elder_guardian",
"ender_dragon",
"enderman",
"endermite",
"evoker",
"fox",
"frog",
"ghast",
"glow_squid",
"goat",
"guardian",
"hoglin",
"horse",
"husk",
"iron_golem",
"llama",
"magma_cube",
"mooshroom",
"mule",
"ocelot",
"panda",
"parrot",
"phantom",
"pig",
"piglin",
"piglin_brute",
"pillager",
"polar_bear",
"pufferfish",
"rabbit",
"ravager",
"salmon",
"sheep",
"shulker",
"silverfish",
"skeleton",
"skeleton_horse",
"slime",
"sniffer",
"snow_golem",
"spider",
"squid",
"stray",
"strider",
"tadpole",
"trader_llama",
"tropical_fish",
"turtle",
"vex",
"villager",
"vindicator",
"wandering_trader",
"warden",
"witch",
"wither",
"wither_skeleton",
"wolf",
"zoglin",
"zombie",
"zombie_horse",
"zombie_villager",
"zombified_piglin",
];
/// `V99.addNames` with V704/V705's tables: the read hook of item stacks before 1.20.5.
@@ -195,7 +286,13 @@ impl Stack {
remove(&mut remainder, "Count");
let tag = super::dynamic::or_empty_map(remainder.get("tag"));
remove(&mut remainder, "tag");
Some(Self { item: namespaced(&item), count, components: empty_map(), remainder, tag })
Some(Self {
item: namespaced(&item),
count,
components: empty_map(),
remainder,
tag,
})
}
fn remove_tag(&mut self, key: &str) -> Option<Tag> {
remove(&mut self.tag, key)
@@ -226,7 +323,12 @@ impl Stack {
}
}
/// `fixSubTag`.
fn fix_sub_tag(&mut self, key: &str, skip_missing: bool, f: impl FnOnce(&mut Self, Tag) -> Tag) {
fn fix_sub_tag(
&mut self,
key: &str,
skip_missing: bool,
f: impl FnOnce(&mut Self, Tag) -> Tag,
) {
let value = self.tag.get(key).cloned();
if skip_missing && value.is_none() {
return;
@@ -243,7 +345,8 @@ impl Stack {
self.item == id
}
fn write(mut self) -> Tag {
let mut result = Tag::compound([("id", string(&self.item)), ("count", Tag::Int(self.count))]);
let mut result =
Tag::compound([("id", string(&self.item)), ("count", Tag::Int(self.count))]);
if !is_empty_map(&self.tag) {
let tag = std::mem::replace(&mut self.tag, empty_map());
self.set_component("minecraft:custom_data", tag);
@@ -270,14 +373,66 @@ const BUCKETED_MOBS: [&str; 6] = [
"minecraft:axolotl_bucket",
"minecraft:tadpole_bucket",
];
const BUCKETED_MOB_TAGS: [&str; 10] =
["NoAI", "Silent", "NoGravity", "Glowing", "Invulnerable", "Health", "Age", "Variant", "HuntingCooldown", "BucketVariantTag"];
const BUCKETED_MOB_TAGS: [&str; 10] = [
"NoAI",
"Silent",
"NoGravity",
"Glowing",
"Invulnerable",
"Health",
"Age",
"Variant",
"HuntingCooldown",
"BucketVariantTag",
];
const BOOLEAN_BLOCK_STATE_PROPERTIES: &[&str] = &[
"attached", "bottom", "conditional", "disarmed", "drag", "enabled", "extended", "eye", "falling", "hanging",
"has_bottle_0", "has_bottle_1", "has_bottle_2", "has_record", "has_book", "inverted", "in_wall", "lit", "locked",
"occupied", "open", "persistent", "powered", "short", "signal_fire", "snowy", "triggered", "unstable", "waterlogged",
"berries", "bloom", "shrieking", "can_summon", "up", "down", "north", "east", "south", "west", "slot_0_occupied",
"slot_1_occupied", "slot_2_occupied", "slot_3_occupied", "slot_4_occupied", "slot_5_occupied", "cracked", "crafting",
"attached",
"bottom",
"conditional",
"disarmed",
"drag",
"enabled",
"extended",
"eye",
"falling",
"hanging",
"has_bottle_0",
"has_bottle_1",
"has_bottle_2",
"has_record",
"has_book",
"inverted",
"in_wall",
"lit",
"locked",
"occupied",
"open",
"persistent",
"powered",
"short",
"signal_fire",
"snowy",
"triggered",
"unstable",
"waterlogged",
"berries",
"bloom",
"shrieking",
"can_summon",
"up",
"down",
"north",
"east",
"south",
"west",
"slot_0_occupied",
"slot_1_occupied",
"slot_2_occupied",
"slot_3_occupied",
"slot_4_occupied",
"slot_5_occupied",
"cracked",
"crafting",
];
/// The fix for one item stack (`writeFixAndRead` over ITEM_STACK).
@@ -302,7 +457,11 @@ fn fix_stack(s: &mut Stack) {
let be = fix_block_entity_tag(s, be, &id);
let mut without_id = be.clone();
remove(&mut without_id, "id");
if is_empty_map(&without_id) { without_id } else { be }
if is_empty_map(&without_id) {
without_id
} else {
be
}
});
s.move_to_component("BlockEntityTag", "minecraft:block_entity_data");
if as_bool(s.remove_tag("Unbreakable").as_ref(), false) {
@@ -312,13 +471,28 @@ fn fix_stack(s: &mut Stack) {
}
s.set_component("minecraft:unbreakable", c);
}
fix_enchantments(s, "Enchantments", "minecraft:enchantments", hide_flags & 1 != 0);
fix_enchantments(
s,
"Enchantments",
"minecraft:enchantments",
hide_flags & 1 != 0,
);
if s.is("minecraft:enchanted_book") {
fix_enchantments(s, "StoredEnchantments", "minecraft:stored_enchantments", hide_flags & 32 != 0);
fix_enchantments(
s,
"StoredEnchantments",
"minecraft:stored_enchantments",
hide_flags & 32 != 0,
);
}
s.fix_sub_tag("display", false, |s, d| fix_display(s, d, hide_flags));
fix_block_predicates(s, "CanDestroy", "minecraft:can_break", hide_flags & 8 != 0);
fix_block_predicates(s, "CanPlaceOn", "minecraft:can_place_on", hide_flags & 16 != 0);
fix_block_predicates(
s,
"CanPlaceOn",
"minecraft:can_place_on",
hide_flags & 16 != 0,
);
fix_attribute_modifiers(s, hide_flags);
if let Some(mut trim) = s.remove_tag("Trim") {
if hide_flags & 128 != 0 {
@@ -331,7 +505,11 @@ fn fix_stack(s: &mut Stack) {
}
if s.is("minecraft:crossbow") {
s.remove_tag("Charged");
s.move_to_component_default("ChargedProjectiles", "minecraft:charged_projectiles", &Tag::List(vec![]));
s.move_to_component_default(
"ChargedProjectiles",
"minecraft:charged_projectiles",
&Tag::List(vec![]),
);
}
if s.is("minecraft:bundle") {
s.move_to_component_default("Items", "minecraft:bundle_contents", &Tag::List(vec![]));
@@ -351,10 +529,14 @@ fn fix_stack(s: &mut Stack) {
}
if matches!(
s.item.as_str(),
"minecraft:potion" | "minecraft:splash_potion" | "minecraft:lingering_potion" | "minecraft:tipped_arrow"
"minecraft:potion"
| "minecraft:splash_potion"
| "minecraft:lingering_potion"
| "minecraft:tipped_arrow"
) {
let mut c = empty_map();
if let Some(p) = as_str(s.remove_tag("Potion").as_ref()).filter(|p| p != "minecraft:empty") {
if let Some(p) = as_str(s.remove_tag("Potion").as_ref()).filter(|p| p != "minecraft:empty")
{
set(&mut c, "potion", string(&p));
}
s.move_tag_into("CustomPotionColor", &mut c, "custom_color");
@@ -366,14 +548,21 @@ fn fix_stack(s: &mut Stack) {
if s.is("minecraft:writable_book")
&& let Some(pages) = fix_book_pages(s)
{
s.set_component("minecraft:writable_book_content", Tag::compound([("pages", pages)]));
s.set_component(
"minecraft:writable_book_content",
Tag::compound([("pages", pages)]),
);
}
if s.is("minecraft:written_book") {
let pages = fix_book_pages(s);
let title = as_string(s.remove_tag("title").as_ref(), "");
let filtered_title = as_str(s.remove_tag("filtered_title").as_ref());
let mut c = empty_map();
set(&mut c, "title", filtered_text(&title, filtered_title.as_deref()));
set(
&mut c,
"title",
filtered_text(&title, filtered_title.as_deref()),
);
s.move_tag_into("author", &mut c, "author");
s.move_tag_into("resolved", &mut c, "resolved");
s.move_tag_into("generation", &mut c, "generation");
@@ -408,11 +597,17 @@ fn fix_stack(s: &mut Stack) {
}
if s.is("minecraft:firework_rocket") {
s.fix_sub_tag("Fireworks", true, |s, mut f| {
let explosions: Vec<Tag> = stream(f.get("Explosions")).into_iter().map(fix_firework_explosion).collect();
let explosions: Vec<Tag> = stream(f.get("Explosions"))
.into_iter()
.map(fix_firework_explosion)
.collect();
let flight = as_int(f.get("Flight"), 0);
s.set_component(
"minecraft:fireworks",
Tag::compound([("explosions", Tag::List(explosions)), ("flight_duration", Tag::Byte(flight as i8))]),
Tag::compound([
("explosions", Tag::List(explosions)),
("flight_duration", Tag::Byte(flight as i8)),
]),
);
remove(&mut f, "Explosions");
remove(&mut f, "Flight");
@@ -421,7 +616,10 @@ fn fix_stack(s: &mut Stack) {
}
if s.is("minecraft:firework_star") {
s.fix_sub_tag("Explosion", true, |s, mut e| {
s.set_component("minecraft:firework_explosion", fix_firework_explosion(e.clone()));
s.set_component(
"minecraft:firework_explosion",
fix_firework_explosion(e.clone()),
);
for k in ["Type", "Colors", "FadeColors", "Trail", "Flicker"] {
remove(&mut e, k);
}
@@ -466,7 +664,10 @@ fn fix_display(s: &mut Stack, mut d: Tag, hide_flags: i32) -> Tag {
s.set_component("minecraft:custom_name", name.clone());
}
if d.get("Lore").is_some() {
let lore = stream(d.get("Lore")).into_iter().filter(is_strictly_valid_json).collect();
let lore = stream(d.get("Lore"))
.into_iter()
.filter(is_strictly_valid_json)
.collect();
s.set_component("minecraft:lore", Tag::List(lore));
}
let color = d.get("color").and_then(as_number).map(|n| n.int_value());
@@ -531,19 +732,36 @@ fn fix_block_entity_tag(s: &mut Stack, mut be: Tag, id: &str) -> Tag {
let patterns = be.get("patterns").cloned();
s.set_component_opt("minecraft:banner_patterns", patterns);
if let Some(base) = be.get("Base").and_then(as_number) {
s.set_component("minecraft:base_color", string(super::fixes_a::dye_color(base.int_value())));
s.set_component(
"minecraft:base_color",
string(super::fixes_a::dye_color(base.int_value())),
);
}
remove(&mut be, "patterns");
remove(&mut be, "Base");
}
"minecraft:shulker_box" | "minecraft:chest" | "minecraft:trapped_chest" | "minecraft:furnace"
| "minecraft:ender_chest" | "minecraft:dispenser" | "minecraft:dropper" | "minecraft:brewing_stand"
| "minecraft:hopper" | "minecraft:barrel" | "minecraft:smoker" | "minecraft:blast_furnace"
| "minecraft:campfire" | "minecraft:chiseled_bookshelf" | "minecraft:crafter" => {
"minecraft:shulker_box"
| "minecraft:chest"
| "minecraft:trapped_chest"
| "minecraft:furnace"
| "minecraft:ender_chest"
| "minecraft:dispenser"
| "minecraft:dropper"
| "minecraft:brewing_stand"
| "minecraft:hopper"
| "minecraft:barrel"
| "minecraft:smoker"
| "minecraft:blast_furnace"
| "minecraft:campfire"
| "minecraft:chiseled_bookshelf"
| "minecraft:crafter" => {
let items: Vec<Tag> = stream(be.get("Items"))
.into_iter()
.map(|mut item| {
let slot = item.get("Slot").and_then(as_number).map_or(0, |n| n.byte_value()) as u8;
let slot = item
.get("Slot")
.and_then(as_number)
.map_or(0, |n| n.byte_value()) as u8;
remove(&mut item, "Slot");
Tag::compound([("slot", Tag::Int(i32::from(slot))), ("item", item)])
})
@@ -626,7 +844,11 @@ fn fix_block_predicate(text: &str) -> Tag {
if start < stop {
for property in text[start + 1..stop].split(',') {
if let Some(eq) = property.find('=') {
set(&mut props, property[..eq].trim(), string(property[eq + 1..].trim()));
set(
&mut props,
property[..eq].trim(),
string(property[eq + 1..].trim()),
);
}
}
}
@@ -645,7 +867,10 @@ fn fix_attribute_modifiers(s: &mut Stack, hide_flags: i32) {
let Some(field) = s.remove_tag("AttributeModifiers") else {
return;
};
let modifiers = stream(Some(&field)).into_iter().map(|m| fix_attribute_modifier(&m)).collect();
let modifiers = stream(Some(&field))
.into_iter()
.map(|m| fix_attribute_modifier(&m))
.collect();
let mut c = Tag::compound([("modifiers", Tag::List(modifiers))]);
if hide_flags & 2 != 0 {
set(&mut c, "show_in_tooltip", Tag::Byte(0));
@@ -723,13 +948,19 @@ fn fix_map_decoration(d: &Tag) -> (JavaString, Tag) {
("type", string(ty)),
("x", Tag::Double(as_double(d.get("x"), 0.0).to_bits())),
("z", Tag::Double(as_double(d.get("z"), 0.0).to_bits())),
("rotation", Tag::Float((as_double(d.get("rot"), 0.0) as f32).to_bits())),
(
"rotation",
Tag::Float((as_double(d.get("rot"), 0.0) as f32).to_bits()),
),
]);
(id, value)
}
fn fix_book_pages(s: &mut Stack) -> Option<Tag> {
let pages: Vec<String> = stream(s.remove_tag("pages").as_ref()).iter().map(|p| as_string(Some(p), "")).collect();
let pages: Vec<String> = stream(s.remove_tag("pages").as_ref())
.iter()
.map(|p| as_string(Some(p), ""))
.collect();
let filtered: Vec<(String, String)> = match s.remove_tag("filtered_pages") {
Some(Tag::Compound(c)) => c
.iter()
@@ -744,7 +975,10 @@ fn fix_book_pages(s: &mut Stack) -> Option<Tag> {
.iter()
.enumerate()
.map(|(i, page)| {
let f = filtered.iter().find(|(k, _)| *k == i.to_string()).map(|(_, v)| v.as_str());
let f = filtered
.iter()
.find(|(k, _)| *k == i.to_string())
.map(|(_, v)| v.as_str());
filtered_text(page, f)
})
.collect();
@@ -768,7 +1002,11 @@ fn fix_lodestone_tracker(s: &mut Stack) {
let tracked = as_bool(s.remove_tag("LodestoneTracked").as_ref(), true);
let mut c = empty_map();
if let (Some(p), Some(d)) = (pos, dimension) {
set(&mut c, "target", Tag::compound([("pos", p), ("dimension", d)]));
set(
&mut c,
"target",
Tag::compound([("pos", p), ("dimension", d)]),
);
}
if !tracked {
set(&mut c, "tracked", Tag::Byte(0));
@@ -796,7 +1034,11 @@ fn fix_firework_explosion(mut e: Tag) -> Tag {
/// `ItemStackComponentizationFix.fixProfile`.
pub(super) fn fix_profile(v: &Tag) -> Tag {
if let Some(name) = as_str(Some(v)) {
return if valid_player_name(&name) { Tag::compound([("name", string(&name))]) } else { empty_map() };
return if valid_player_name(&name) {
Tag::compound([("name", string(&name))])
} else {
empty_map()
};
}
let name = as_string(v.get("Name"), "");
let id = v.get("Id").cloned();
@@ -855,7 +1097,8 @@ fn fix_profile_properties(v: Option<&Tag>) -> Option<Tag> {
/// Java `String.hashCode`.
pub(super) fn java_string_hash(s: &str) -> i32 {
s.encode_utf16().fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c)))
s.encode_utf16()
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c)))
}
/// Iteration order of a `java.util.HashMap`/`HashSet` built by inserting the
@@ -903,7 +1146,10 @@ pub(super) fn unflatten_particle(description: &str) -> Tag {
}
set(&mut result, "item", stack);
}
"minecraft:block" | "minecraft:block_marker" | "minecraft:falling_dust" | "minecraft:dust_pillar" => {
"minecraft:block"
| "minecraft:block_marker"
| "minecraft:falling_dust"
| "minecraft:dust_pillar" => {
let mut state = empty_map();
match contents.find('[') {
None => set(&mut state, "Name", string(&namespaced(contents))),
@@ -1023,7 +1269,10 @@ struct Reader {
}
impl Reader {
fn new(s: &str) -> Self {
Self { s: s.chars().collect(), pos: 0 }
Self {
s: s.chars().collect(),
pos: 0,
}
}
fn peek(&self) -> Option<char> {
self.s.get(self.pos).copied()
@@ -1043,7 +1292,10 @@ impl Reader {
}
fn number_text(&mut self) -> String {
let start = self.pos;
while self.peek().is_some_and(|c| c.is_ascii_digit() || c == '.' || c == '-') {
while self
.peek()
.is_some_and(|c| c.is_ascii_digit() || c == '.' || c == '-')
{
self.pos += 1;
}
self.s[start..self.pos].iter().collect()
@@ -1059,7 +1311,11 @@ impl Reader {
while self.peek().is_some_and(|c| c.is_ascii_digit() || c == '-') {
self.pos += 1;
}
self.s[start..self.pos].iter().collect::<String>().parse().ok()
self.s[start..self.pos]
.iter()
.collect::<String>()
.parse()
.ok()
}
fn vector(&mut self) -> Option<Tag> {
let x = self.float()?;
@@ -1071,7 +1327,11 @@ impl Reader {
return None;
}
let z = self.float()?;
Some(Tag::List(vec![Tag::Float(x.to_bits()), Tag::Float(y.to_bits()), Tag::Float(z.to_bits())]))
Some(Tag::List(vec![
Tag::Float(x.to_bits()),
Tag::Float(y.to_bits()),
Tag::Float(z.to_bits()),
]))
}
/// `StringReader.readString`: quoted or unquoted.
fn string(&mut self) -> Option<String> {
@@ -1100,10 +1360,9 @@ impl Reader {
}
_ => {
let start = self.pos;
while self
.peek()
.is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+'))
{
while self.peek().is_some_and(|c| {
c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+')
}) {
self.pos += 1;
}
Some(self.s[start..self.pos].iter().collect())
+44 -10
View File
@@ -76,7 +76,9 @@ impl Reader<'_> {
};
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('/')) => {
0x2F if self.s.get(self.pos + 1) == Some(&u('*'))
|| self.s.get(self.pos + 1) == Some(&u('/')) =>
{
if !self.lenient() {
return Err(());
}
@@ -253,7 +255,21 @@ impl Reader<'_> {
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
0x2F | 0x5C
| 0x3B
| 0x23
| 0x3D
| 0x7B
| 0x7D
| 0x5B
| 0x5D
| 0x3A
| 0x2C
| 0x20
| 0x09
| 0x0C
| 0x0D
| 0x0A
) {
break;
}
@@ -268,11 +284,16 @@ impl Reader<'_> {
return Err(());
}
let text = String::from_utf16_lossy(&lit);
for (word, value) in [("true", Json::Bool(true)), ("false", Json::Bool(false)), ("null", Json::Null)] {
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()
})
&& text
.chars()
.zip(word.chars())
.all(|(a, b)| a == b || self.lenient() && a == b.to_ascii_uppercase())
{
return Ok(value);
}
@@ -505,7 +526,11 @@ pub fn from_nbt(tag: &Tag) -> Json {
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::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()),
@@ -562,7 +587,10 @@ fn java_fp_string(d: f64, sci: String) -> String {
/// 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()))]))
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))]))
@@ -590,12 +618,18 @@ mod tests {
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"))])));
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"}"#);
assert_eq!(
String::from_utf16(&to_stable_string(&j)).unwrap(),
r#"{"color":"red","text":"a"}"#
);
}
#[test]
fn java_floating_point_strings() {
+16 -9
View File
@@ -1,20 +1,20 @@
//! Vanilla's DataFixers from the 1.20 schemas on (`net.minecraft.util.datafix`):
//! the data of worlds saved by 1.20 to 26.2 brought to the 26.3 format exactly
//! 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 the
//! 1.20 schemas (DataVersion 3463) is not supported: the fixes before them are
//! not ported, see [`OLDEST_SUPPORTED`].
//! 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;
pub mod files;
mod items;
pub mod json;
pub mod schema;
@@ -36,7 +36,9 @@ pub fn identifier(id: &str) -> Option<(String, String)> {
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 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'/'));
@@ -157,10 +159,15 @@ pub fn id_is(v: &Tag, id: &str) -> bool {
}
/// `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 {
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)
table
.iter()
.find(|(from, _)| *from == id)
.map(|(_, to)| *to)
}
}
+88 -22
View File
@@ -251,7 +251,10 @@ impl Walker<'_> {
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:crafted"
| "minecraft:used"
| "minecraft:broken"
| "minecraft:picked_up"
| "minecraft:dropped",
) => Some(Ty::ItemName),
Some("minecraft:killed" | "minecraft:killed_by") => Some(Ty::EntityName),
@@ -302,7 +305,9 @@ impl Walker<'_> {
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"] {
for slot in [
"mainhand", "offhand", "feet", "legs", "chest", "head", "body", "saddle",
] {
self.field(Ty::ItemStack, eq, slot);
}
}
@@ -329,7 +334,11 @@ impl Walker<'_> {
};
match id {
"minecraft:area_effect_cloud" => {
let f = if k >= key(4420, 0) { "custom_particle" } else { "Particle" };
let f = if k >= key(4420, 0) {
"custom_particle"
} else {
"Particle"
};
self.field(Ty::Particle, v, f);
}
"minecraft:arrow" | "minecraft:spectral_arrow" => {
@@ -372,7 +381,11 @@ impl Walker<'_> {
if k < key(4300, 0) {
self.field(Ty::ItemStack, v, "SaddleItem");
}
let split = if id == "minecraft:llama" { key(3808, 1) } else { key(3808, 2) };
let split = if id == "minecraft:llama" {
key(3808, 1)
} else {
key(3808, 2)
};
if k < split {
self.field(Ty::ItemStack, v, "DecorItem");
}
@@ -425,8 +438,12 @@ impl Walker<'_> {
"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") => {
"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");
}
_ => {}
@@ -460,8 +477,14 @@ impl Walker<'_> {
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" => {
"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),
@@ -485,7 +508,9 @@ impl Walker<'_> {
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: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" => {
@@ -516,7 +541,9 @@ impl Walker<'_> {
}
self.field(Ty::ItemStack, v, "item");
}
"minecraft:brushable_block" | "minecraft:suspicious_sand" => 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 {
@@ -774,18 +801,57 @@ pub fn block_entity_known(be: &Tag, k: Key) -> bool {
/// 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",
"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`.
+23 -6
View File
@@ -21,7 +21,10 @@ fn item_stacks_of_1_20_take_components() {
);
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!(
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)));
@@ -38,14 +41,25 @@ fn level_data_of_1_20_moves_to_the_new_fields() {
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"));
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])));
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]
@@ -57,7 +71,10 @@ fn block_states_take_their_new_field_names() {
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_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)));
}
+37 -10
View File
@@ -1,17 +1,25 @@
//! 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::dynamic::{as_number, as_str, as_string, boolean, empty_map, remove, rename, rename_and_fix, set, string};
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 super::FixFn;
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)));
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.
@@ -58,7 +66,10 @@ fn legacy_hover_event(v: &mut Tag) {
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)))])),
(
"contents",
Tag::compound([("text", Tag::String(crate::nbt::JavaString(text)))]),
),
])
};
set(v, "hoverEvent", new);
@@ -69,7 +80,13 @@ fn stringified_flags(v: &mut Tag) {
if !is_full(v) {
return;
}
for flag in ["bold", "italic", "underlined", "strikethrough", "obfuscated"] {
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")));
}
@@ -173,7 +190,9 @@ fn valid_uri(uri: &str) -> bool {
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) {
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;
@@ -182,7 +201,10 @@ fn valid_uri(uri: &str) -> bool {
if c == '#' {
hashes += 1;
}
if c.is_control() || c.is_whitespace() || matches!(c, '"' | '<' | '>' | '\\' | '^' | '`' | '{' | '|' | '}') {
if c.is_control()
|| c.is_whitespace()
|| matches!(c, '"' | '<' | '>' | '\\' | '^' | '`' | '{' | '|' | '}')
{
return false;
}
i += 1;
@@ -207,7 +229,12 @@ mod tests {
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);
assert_eq!(c, j(r#"{"text":"a","click_event":{"action":"change_page","page":1}}"#));
// 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"}"#));