Merge main into fix branch (resolves the conflict with main)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,973 @@
|
||||
//! Vanilla 26.3 block entity NBT for every block entity type.
|
||||
//!
|
||||
//! [`canonical`] is `loadAdditional` followed by `saveWithFullMetadata` for each of
|
||||
//! the 47 `BlockEntityType`s: it reads the fields the type reads (with vanilla's
|
||||
//! defaults and clamps), drops everything else and writes the fields `saveAdditional`
|
||||
//! writes (including its omit-when-empty rules). Nested codec values that Horizon does
|
||||
//! not simulate (spawner entity data, vibration listeners, trial spawner configuration,
|
||||
//! vault data, sculk cursors, sign and banner components, profiles) are carried as
|
||||
//! loaded. The common `BaseContainerBlockEntity` fields (`CustomName`, `lock`) and the
|
||||
//! `RandomizableContainer` loot table fields are handled for every container type.
|
||||
//!
|
||||
//! [`overlay`] merges a block entity Horizon models (and re-encodes from its own,
|
||||
//! partial state) with the NBT it was loaded from, so fields Horizon does not model
|
||||
//! survive and only what the game changed is replaced.
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
|
||||
fn string(s: &str) -> Tag {
|
||||
Tag::String(s.into())
|
||||
}
|
||||
fn text(tag: Option<&Tag>) -> Option<String> {
|
||||
match tag {
|
||||
Some(Tag::String(s)) => Some(s.to_string_lossy()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `CompoundTag.getIntOr`: any numeric tag (floats floor).
|
||||
fn int(tag: Option<&Tag>) -> Option<i32> {
|
||||
Some(match tag? {
|
||||
Tag::Byte(v) => i32::from(*v),
|
||||
Tag::Short(v) => i32::from(*v),
|
||||
Tag::Int(v) => *v,
|
||||
Tag::Long(v) => *v as i32,
|
||||
Tag::Float(b) => f32::from_bits(*b).floor() as i32,
|
||||
Tag::Double(b) => f64::from_bits(*b).floor() as i32,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
fn long(tag: Option<&Tag>) -> Option<i64> {
|
||||
Some(match tag? {
|
||||
Tag::Long(v) => *v,
|
||||
Tag::Float(b) => f32::from_bits(*b).floor() as i64,
|
||||
Tag::Double(b) => f64::from_bits(*b).floor() as i64,
|
||||
other => i64::from(int(Some(other))?),
|
||||
})
|
||||
}
|
||||
fn float(tag: Option<&Tag>) -> Option<f32> {
|
||||
Some(match tag? {
|
||||
Tag::Float(b) => f32::from_bits(*b),
|
||||
Tag::Double(b) => f64::from_bits(*b) as f32,
|
||||
Tag::Long(v) => *v as f32,
|
||||
other => int(Some(other))? as f32,
|
||||
})
|
||||
}
|
||||
fn flag(tag: Option<&Tag>) -> Option<bool> {
|
||||
Some(int(tag)? != 0)
|
||||
}
|
||||
fn boolean(v: bool) -> Tag {
|
||||
Tag::Byte(i8::from(v))
|
||||
}
|
||||
fn f32_tag(v: f32) -> Tag {
|
||||
Tag::Float(v.to_bits())
|
||||
}
|
||||
|
||||
/// What a block entity reads and writes, in `saveAdditional` order.
|
||||
struct Fields<'a> {
|
||||
input: &'a Tag,
|
||||
out: Compound,
|
||||
}
|
||||
impl<'a> Fields<'a> {
|
||||
fn put(&mut self, key: &str, value: Tag) {
|
||||
self.out.insert(key.into(), value);
|
||||
}
|
||||
fn int(&mut self, key: &str, default: i32) {
|
||||
let v = int(self.input.get(key)).unwrap_or(default);
|
||||
self.put(key, Tag::Int(v));
|
||||
}
|
||||
fn int_clamped(&mut self, key: &str, default: i32, min: i32, max: i32) {
|
||||
let v = int(self.input.get(key)).unwrap_or(default).clamp(min, max);
|
||||
self.put(key, Tag::Int(v));
|
||||
}
|
||||
fn short(&mut self, key: &str, default: i16) {
|
||||
let v = int(self.input.get(key)).map_or(default, |v| v as i16);
|
||||
self.put(key, Tag::Short(v));
|
||||
}
|
||||
fn long(&mut self, key: &str, default: i64) {
|
||||
let v = long(self.input.get(key)).unwrap_or(default);
|
||||
self.put(key, Tag::Long(v));
|
||||
}
|
||||
fn float(&mut self, key: &str, default: f32) {
|
||||
let v = float(self.input.get(key)).unwrap_or(default);
|
||||
self.put(key, f32_tag(v));
|
||||
}
|
||||
fn flag(&mut self, key: &str, default: bool) {
|
||||
let v = flag(self.input.get(key)).unwrap_or(default);
|
||||
self.put(key, boolean(v));
|
||||
}
|
||||
fn string(&mut self, key: &str, default: &str) {
|
||||
let v = text(self.input.get(key)).unwrap_or_else(|| default.to_owned());
|
||||
self.put(key, string(&v));
|
||||
}
|
||||
/// An optional value written as loaded, when it has the expected shape.
|
||||
fn keep(&mut self, key: &str, valid: impl Fn(&Tag) -> bool) {
|
||||
if let Some(t) = self.input.get(key).filter(|t| valid(t)) {
|
||||
self.put(key, t.clone());
|
||||
}
|
||||
}
|
||||
fn keep_compound(&mut self, key: &str) {
|
||||
self.keep(key, |t| matches!(t, Tag::Compound(_)));
|
||||
}
|
||||
/// A compound that is always written (`default` when absent).
|
||||
fn compound_or(&mut self, key: &str, default: Compound) {
|
||||
let v = match self.input.get(key) {
|
||||
Some(Tag::Compound(c)) => c.clone(),
|
||||
_ => default,
|
||||
};
|
||||
self.put(key, Tag::Compound(v));
|
||||
}
|
||||
/// An optional text component (`storeNullable("CustomName", ComponentSerialization.CODEC)`).
|
||||
fn component(&mut self, key: &str) {
|
||||
if let Some(c) = self.input.get(key).and_then(component) {
|
||||
self.put(key, c);
|
||||
}
|
||||
}
|
||||
/// `LockCode.addToTag`.
|
||||
fn lock(&mut self) {
|
||||
self.keep_compound("lock");
|
||||
}
|
||||
/// `BaseContainerBlockEntity`: the custom name and the lock.
|
||||
fn base_container(&mut self) {
|
||||
self.component("CustomName");
|
||||
self.lock();
|
||||
}
|
||||
/// `RandomizableContainer.tryLoadLootTable` / `trySaveLootTable`; true when the
|
||||
/// block entity has a loot table (and so saves no items).
|
||||
fn loot_table(&mut self) -> bool {
|
||||
let Some(table) = text(self.input.get("LootTable")) else {
|
||||
return false;
|
||||
};
|
||||
self.put("LootTable", string(&table));
|
||||
let seed = long(self.input.get("LootTableSeed")).unwrap_or(0);
|
||||
if seed != 0 {
|
||||
self.put("LootTableSeed", Tag::Long(seed));
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `ContainerHelper.loadAllItems` + `saveAllItems`.
|
||||
fn items(&mut self, size: usize, also_when_empty: bool) {
|
||||
let items = items(self.input.get("Items"), size);
|
||||
if !items.is_empty() || also_when_empty {
|
||||
self.put("Items", Tag::List(items));
|
||||
}
|
||||
}
|
||||
/// A container: loot table or items.
|
||||
fn container(&mut self, size: usize, also_when_empty: bool) {
|
||||
if !self.loot_table() {
|
||||
self.items(size, also_when_empty);
|
||||
}
|
||||
}
|
||||
/// An optional `ItemStack` (`RecordItem`, `Book`, `item`).
|
||||
fn item(&mut self, key: &str) -> bool {
|
||||
match self.input.get(key).and_then(stack) {
|
||||
Some(item) => {
|
||||
self.put(key, item);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ComponentSerialization.CODEC` on loaded NBT: a literal without style is a plain
|
||||
/// string; anything else is kept as loaded.
|
||||
pub fn component(tag: &Tag) -> Option<Tag> {
|
||||
match tag {
|
||||
Tag::String(_) | Tag::List(_) => Some(tag.clone()),
|
||||
Tag::Compound(c) => {
|
||||
if c.len() == 1
|
||||
&& let Some(t @ Tag::String(_)) = c.get(&"text".into())
|
||||
{
|
||||
return Some(t.clone());
|
||||
}
|
||||
Some(tag.clone())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `ItemStack.CODEC`: `id`, `count` (1..=99, default 1) and a non-empty `components`
|
||||
/// patch kept as loaded. None for the empty stack and for invalid stacks.
|
||||
pub fn stack(tag: &Tag) -> Option<Tag> {
|
||||
let id = text(tag.get("id"))?;
|
||||
if id.is_empty() || id == "minecraft:air" {
|
||||
return None;
|
||||
}
|
||||
let count = int(tag.get("count")).unwrap_or(1);
|
||||
if !(1..=99).contains(&count) {
|
||||
return None;
|
||||
}
|
||||
let mut out = vec![("id", string(&id)), ("count", Tag::Int(count))];
|
||||
if let Some(c @ Tag::Compound(map)) = tag.get("components")
|
||||
&& !map.is_empty()
|
||||
{
|
||||
out.push(("components", c.clone()));
|
||||
}
|
||||
Some(Tag::compound(out))
|
||||
}
|
||||
/// `ItemStackTemplate.CODEC`: an item id or `{id, count?, components?}`.
|
||||
fn template(tag: &Tag) -> Option<Tag> {
|
||||
match tag {
|
||||
Tag::String(_) => Some(tag.clone()),
|
||||
Tag::Compound(_) => {
|
||||
let mut out = vec![("id", string(&text(tag.get("id"))?))];
|
||||
if let Some(count) = int(tag.get("count")).filter(|c| *c != 1) {
|
||||
out.push(("count", Tag::Int(count)));
|
||||
}
|
||||
if let Some(c @ Tag::Compound(map)) = tag.get("components")
|
||||
&& !map.is_empty()
|
||||
{
|
||||
out.push(("components", c.clone()));
|
||||
}
|
||||
Some(Tag::compound(out))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `ItemStackWithSlot` entries of a container of `size` slots, by ascending slot.
|
||||
fn items(tag: Option<&Tag>, size: usize) -> Vec<Tag> {
|
||||
let mut slots: Vec<Option<Tag>> = vec![None; size];
|
||||
if let Some(Tag::List(list)) = tag {
|
||||
for entry in list {
|
||||
let (Some(slot), Some(item)) = (int(entry.get("Slot")), stack(entry)) else {
|
||||
continue;
|
||||
};
|
||||
if (0..size as i32).contains(&slot) {
|
||||
slots[slot as usize] = Some(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
slots
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, item)| {
|
||||
let Tag::Compound(mut c) = item? else {
|
||||
return None;
|
||||
};
|
||||
c.insert("Slot".into(), Tag::Byte(i as i8));
|
||||
Some(Tag::Compound(c))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn int_array(tag: Option<&Tag>) -> Option<&Vec<i32>> {
|
||||
match tag {
|
||||
Some(Tag::IntArray(v)) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// A saved `BlockPos` (`[I; x, y, z]`).
|
||||
fn is_pos(tag: &Tag) -> bool {
|
||||
matches!(tag, Tag::IntArray(v) if v.len() == 3)
|
||||
}
|
||||
/// The loaded `SignText` of one side, or the empty text.
|
||||
pub fn sign_side(tag: Option<&Tag>) -> Tag {
|
||||
let empty = || string("");
|
||||
let mut messages: Vec<Tag> = match tag.and_then(|t| t.get("messages")) {
|
||||
Some(Tag::List(list)) => list.iter().filter_map(component).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
messages.resize_with(4, empty);
|
||||
messages.truncate(4);
|
||||
let mut out = vec![
|
||||
("messages", Tag::List(messages)),
|
||||
(
|
||||
"color",
|
||||
string(
|
||||
&tag.and_then(|t| text(t.get("color")))
|
||||
.unwrap_or_else(|| "black".into()),
|
||||
),
|
||||
),
|
||||
(
|
||||
"has_glowing_text",
|
||||
boolean(
|
||||
tag.and_then(|t| flag(t.get("has_glowing_text")))
|
||||
.unwrap_or(false),
|
||||
),
|
||||
),
|
||||
];
|
||||
if let Some(filtered @ Tag::List(list)) = tag.and_then(|t| t.get("filtered_messages"))
|
||||
&& list.len() == 4
|
||||
{
|
||||
out.push(("filtered_messages", filtered.clone()));
|
||||
}
|
||||
Tag::compound(out)
|
||||
}
|
||||
|
||||
/// The id of a block entity compound.
|
||||
pub fn id(tag: &Tag) -> Option<String> {
|
||||
text(tag.get("id"))
|
||||
}
|
||||
|
||||
/// Every `BlockEntityType` id this module knows.
|
||||
pub const TYPES: [&str; 47] = [
|
||||
"minecraft:furnace",
|
||||
"minecraft:chest",
|
||||
"minecraft:trapped_chest",
|
||||
"minecraft:ender_chest",
|
||||
"minecraft:jukebox",
|
||||
"minecraft:dispenser",
|
||||
"minecraft:dropper",
|
||||
"minecraft:sign",
|
||||
"minecraft:hanging_sign",
|
||||
"minecraft:mob_spawner",
|
||||
"minecraft:creaking_heart",
|
||||
"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:conduit",
|
||||
"minecraft:barrel",
|
||||
"minecraft:smoker",
|
||||
"minecraft:blast_furnace",
|
||||
"minecraft:lectern",
|
||||
"minecraft:bell",
|
||||
"minecraft:jigsaw",
|
||||
"minecraft:campfire",
|
||||
"minecraft:beehive",
|
||||
"minecraft:sculk_sensor",
|
||||
"minecraft:calibrated_sculk_sensor",
|
||||
"minecraft:sculk_catalyst",
|
||||
"minecraft:sculk_shrieker",
|
||||
"minecraft:chiseled_bookshelf",
|
||||
"minecraft:shelf",
|
||||
"minecraft:brushable_block",
|
||||
"minecraft:decorated_pot",
|
||||
"minecraft:crafter",
|
||||
"minecraft:trial_spawner",
|
||||
"minecraft:vault",
|
||||
"minecraft:test_block",
|
||||
"minecraft:test_instance_block",
|
||||
];
|
||||
/// The two types added after the ones above in 26.3.
|
||||
pub const NEWEST: [&str; 2] = ["minecraft:copper_golem_statue", "minecraft:potent_sulfur"];
|
||||
|
||||
/// The block entity as vanilla would save it after loading `tag` (a full block
|
||||
/// entity compound with `id`, `x`, `y`, `z`); None for an unknown type or a tag
|
||||
/// without a position.
|
||||
pub fn canonical(tag: &Tag) -> Option<Tag> {
|
||||
let id = id(tag)?;
|
||||
let (x, y, z) = (int(tag.get("x"))?, int(tag.get("y"))?, int(tag.get("z"))?);
|
||||
let mut f = Fields {
|
||||
input: tag,
|
||||
out: Compound::new(),
|
||||
};
|
||||
match id.as_str() {
|
||||
"minecraft:furnace" | "minecraft:smoker" | "minecraft:blast_furnace" => {
|
||||
f.base_container();
|
||||
f.int("cooking_time_spent", 0);
|
||||
f.int("cooking_total_time", 0);
|
||||
f.int("lit_time_remaining", 0);
|
||||
f.int("lit_total_time", 0);
|
||||
f.float("speed_multiplier", 1.0);
|
||||
f.items(3, true);
|
||||
let used: Compound = match tag.get("RecipesUsed") {
|
||||
Some(Tag::Compound(c)) => c
|
||||
.iter()
|
||||
.filter_map(|(k, v)| Some((k.clone(), Tag::Int(int(Some(v))?))))
|
||||
.collect(),
|
||||
_ => Compound::new(),
|
||||
};
|
||||
f.put("RecipesUsed", Tag::Compound(used));
|
||||
}
|
||||
"minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => {
|
||||
f.base_container();
|
||||
f.container(27, true);
|
||||
}
|
||||
"minecraft:dispenser" | "minecraft:dropper" => {
|
||||
f.base_container();
|
||||
f.container(9, true);
|
||||
}
|
||||
"minecraft:hopper" => {
|
||||
f.base_container();
|
||||
f.container(5, true);
|
||||
f.int("TransferCooldown", -1);
|
||||
}
|
||||
"minecraft:shulker_box" => {
|
||||
f.base_container();
|
||||
f.container(27, false);
|
||||
}
|
||||
"minecraft:crafter" => {
|
||||
f.base_container();
|
||||
f.int("crafting_ticks_remaining", 0);
|
||||
f.container(9, true);
|
||||
let disabled: Vec<i32> = int_array(tag.get("disabled_slots"))
|
||||
.map(|v| v.iter().copied().filter(|s| (0..9).contains(s)).collect())
|
||||
.unwrap_or_default();
|
||||
// `addDisabledSlots`: the slots whose container data is 1, ascending.
|
||||
let mut slots = disabled;
|
||||
slots.sort_unstable();
|
||||
slots.dedup();
|
||||
f.put("disabled_slots", Tag::IntArray(slots));
|
||||
f.put(
|
||||
"triggered",
|
||||
Tag::Int(int(tag.get("triggered")).unwrap_or(0)),
|
||||
);
|
||||
}
|
||||
"minecraft:ender_chest"
|
||||
| "minecraft:end_portal"
|
||||
| "minecraft:daylight_detector"
|
||||
| "minecraft:bell"
|
||||
| "minecraft:conduit"
|
||||
| "minecraft:copper_golem_statue" => {
|
||||
if id == "minecraft:conduit" {
|
||||
f.keep("Target", |t| matches!(t, Tag::IntArray(v) if v.len() == 4));
|
||||
}
|
||||
}
|
||||
"minecraft:end_gateway" => {
|
||||
f.long("Age", 0);
|
||||
f.keep("exit_portal", |t| {
|
||||
is_pos(t)
|
||||
&& matches!(t, Tag::IntArray(v) if v[1].abs() <= 30_000_000 && v[0].abs() <= 30_000_000 && v[2].abs() <= 30_000_000)
|
||||
});
|
||||
if flag(tag.get("ExactTeleport")) == Some(true) {
|
||||
f.put("ExactTeleport", boolean(true));
|
||||
}
|
||||
}
|
||||
"minecraft:jukebox" => {
|
||||
let has_song = f.item("RecordItem");
|
||||
if has_song
|
||||
&& let Some(ticks) = tag
|
||||
.get("ticks_since_song_started")
|
||||
.and_then(|t| long(Some(t)))
|
||||
&& let Some(Tag::Compound(c)) = f.out.get(&"RecordItem".into())
|
||||
&& is_record(c)
|
||||
{
|
||||
f.put("ticks_since_song_started", Tag::Long(ticks));
|
||||
}
|
||||
}
|
||||
"minecraft:sign" | "minecraft:hanging_sign" => {
|
||||
if flag(tag.get("allow_op_features")) == Some(true) {
|
||||
f.put("allow_op_features", boolean(true));
|
||||
}
|
||||
f.put("front_text", sign_side(tag.get("front_text")));
|
||||
f.put("back_text", sign_side(tag.get("back_text")));
|
||||
f.flag("is_waxed", false);
|
||||
}
|
||||
"minecraft:mob_spawner" => {
|
||||
f.short("Delay", 20);
|
||||
f.short("MinSpawnDelay", 200);
|
||||
f.short("MaxSpawnDelay", 800);
|
||||
f.short("SpawnCount", 4);
|
||||
f.short("MaxNearbyEntities", 6);
|
||||
f.short("RequiredPlayerRange", 16);
|
||||
f.short("SpawnRange", 4);
|
||||
f.keep_compound("SpawnData");
|
||||
let potentials = match tag.get("SpawnPotentials") {
|
||||
Some(t @ Tag::List(_)) => t.clone(),
|
||||
_ => match f.out.get(&"SpawnData".into()) {
|
||||
Some(data) => Tag::List(vec![Tag::compound([
|
||||
("data", data.clone()),
|
||||
("weight", Tag::Int(1)),
|
||||
])]),
|
||||
None => Tag::List(Vec::new()),
|
||||
},
|
||||
};
|
||||
f.put("SpawnPotentials", potentials);
|
||||
}
|
||||
"minecraft:creaking_heart" => {
|
||||
f.keep(
|
||||
"creaking",
|
||||
|t| matches!(t, Tag::IntArray(v) if v.len() == 4),
|
||||
);
|
||||
}
|
||||
"minecraft:piston" => {
|
||||
f.put(
|
||||
"blockState",
|
||||
match tag.get("blockState") {
|
||||
Some(t @ (Tag::String(_) | Tag::Compound(_))) => t.clone(),
|
||||
_ => string("minecraft:air"),
|
||||
},
|
||||
);
|
||||
f.put("facing", Tag::Int(int(tag.get("facing")).unwrap_or(0)));
|
||||
f.float("progress", 0.0);
|
||||
f.flag("extending", false);
|
||||
f.flag("source", false);
|
||||
}
|
||||
"minecraft:brewing_stand" => {
|
||||
f.base_container();
|
||||
f.int("BrewTime", 0);
|
||||
f.int("total_brew_time", 400);
|
||||
f.items(5, true);
|
||||
f.int("Fuel", 0);
|
||||
f.int("total_fuel", 20);
|
||||
f.float("speed_multiplier", 1.0);
|
||||
}
|
||||
"minecraft:enchanting_table" => f.component("CustomName"),
|
||||
"minecraft:beacon" => {
|
||||
for key in ["primary_effect", "secondary_effect"] {
|
||||
if let Some(effect) = text(tag.get(key)) {
|
||||
f.put(key, string(&effect));
|
||||
}
|
||||
}
|
||||
f.int("Levels", 0);
|
||||
f.component("CustomName");
|
||||
f.lock();
|
||||
}
|
||||
"minecraft:skull" => {
|
||||
f.keep("profile", |t| {
|
||||
matches!(t, Tag::Compound(_) | Tag::String(_))
|
||||
});
|
||||
if let Some(sound) = text(tag.get("note_block_sound")) {
|
||||
f.put("note_block_sound", string(&sound));
|
||||
}
|
||||
f.component("custom_name");
|
||||
}
|
||||
"minecraft:comparator" => f.int("OutputSignal", 0),
|
||||
"minecraft:banner" => {
|
||||
if let Some(patterns @ Tag::List(list)) = tag.get("patterns")
|
||||
&& !list.is_empty()
|
||||
{
|
||||
f.put("patterns", patterns.clone());
|
||||
}
|
||||
f.component("CustomName");
|
||||
}
|
||||
"minecraft:structure_block" => {
|
||||
f.string("name", "");
|
||||
f.string("author", "");
|
||||
f.string("metadata", "");
|
||||
f.int_clamped("posX", 0, -48, 48);
|
||||
f.int_clamped("posY", 1, -48, 48);
|
||||
f.int_clamped("posZ", 0, -48, 48);
|
||||
f.int_clamped("sizeX", 0, 0, 48);
|
||||
f.int_clamped("sizeY", 0, 0, 48);
|
||||
f.int_clamped("sizeZ", 0, 0, 48);
|
||||
f.string("rotation", "NONE");
|
||||
f.string("mirror", "NONE");
|
||||
f.string("mode", "DATA");
|
||||
f.flag("ignoreEntities", true);
|
||||
f.flag("strict", false);
|
||||
f.flag("powered", false);
|
||||
f.flag("showair", false);
|
||||
f.flag("showboundingbox", true);
|
||||
f.float("integrity", 1.0);
|
||||
f.long("seed", 0);
|
||||
}
|
||||
"minecraft:command_block" => {
|
||||
f.string("Command", "");
|
||||
f.int("SuccessCount", 0);
|
||||
f.component("CustomName");
|
||||
let track = flag(tag.get("TrackOutput")).unwrap_or(true);
|
||||
f.put("TrackOutput", boolean(track));
|
||||
if track {
|
||||
f.component("LastOutput");
|
||||
}
|
||||
let update = flag(tag.get("UpdateLastExecution")).unwrap_or(true);
|
||||
f.put("UpdateLastExecution", boolean(update));
|
||||
if update && let Some(last) = long(tag.get("LastExecution")).filter(|l| *l != -1) {
|
||||
f.put("LastExecution", Tag::Long(last));
|
||||
}
|
||||
f.flag("powered", false);
|
||||
f.flag("conditionMet", false);
|
||||
f.flag("auto", false);
|
||||
}
|
||||
"minecraft:lectern" => {
|
||||
if f.item("Book") {
|
||||
f.int("Page", 0);
|
||||
}
|
||||
}
|
||||
"minecraft:jigsaw" => {
|
||||
f.string("name", "minecraft:empty");
|
||||
f.string("target", "minecraft:empty");
|
||||
f.string("pool", "minecraft:empty");
|
||||
f.string("final_state", "minecraft:air");
|
||||
f.string("joint", "rollable");
|
||||
f.int("placement_priority", 0);
|
||||
f.int("selection_priority", 0);
|
||||
}
|
||||
"minecraft:campfire" => {
|
||||
f.items(4, true);
|
||||
for key in ["CookingTimes", "CookingTotalTimes"] {
|
||||
let mut times = [0; 4];
|
||||
if let Some(v) = int_array(tag.get(key)) {
|
||||
for (slot, t) in times.iter_mut().zip(v) {
|
||||
*slot = *t;
|
||||
}
|
||||
}
|
||||
f.put(key, Tag::IntArray(times.to_vec()));
|
||||
}
|
||||
}
|
||||
"minecraft:beehive" => {
|
||||
let bees = match tag.get("bees") {
|
||||
Some(Tag::List(list)) => list
|
||||
.iter()
|
||||
.filter_map(|bee| {
|
||||
let data = bee
|
||||
.get("entity_data")
|
||||
.filter(|d| matches!(d, Tag::Compound(_)))?;
|
||||
Some(Tag::compound([
|
||||
("entity_data", data.clone()),
|
||||
("ticks_in_hive", Tag::Int(int(bee.get("ticks_in_hive"))?)),
|
||||
(
|
||||
"min_ticks_in_hive",
|
||||
Tag::Int(int(bee.get("min_ticks_in_hive"))?),
|
||||
),
|
||||
]))
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
f.put("bees", Tag::List(bees));
|
||||
f.keep("flower_pos", is_pos);
|
||||
}
|
||||
"minecraft:sculk_sensor" | "minecraft:calibrated_sculk_sensor" => {
|
||||
f.int("last_vibration_frequency", 0);
|
||||
f.compound_or("listener", listener());
|
||||
}
|
||||
"minecraft:sculk_shrieker" => {
|
||||
f.int("warning_level", 0);
|
||||
f.compound_or("listener", listener());
|
||||
}
|
||||
"minecraft:sculk_catalyst" => {
|
||||
let cursors = match tag.get("cursors") {
|
||||
Some(t @ Tag::List(_)) => t.clone(),
|
||||
_ => Tag::List(Vec::new()),
|
||||
};
|
||||
f.put("cursors", cursors);
|
||||
}
|
||||
"minecraft:chiseled_bookshelf" => {
|
||||
f.items(6, true);
|
||||
f.int("last_interacted_slot", -1);
|
||||
}
|
||||
"minecraft:shelf" => {
|
||||
f.items(3, true);
|
||||
f.flag("align_items_to_bottom", false);
|
||||
}
|
||||
"minecraft:brushable_block" => {
|
||||
if !f.loot_table() {
|
||||
f.item("item");
|
||||
}
|
||||
}
|
||||
"minecraft:decorated_pot" => {
|
||||
if let Some(Tag::Compound(sherds)) = tag.get("sherds") {
|
||||
let kept: Compound = ["back", "left", "right", "front"]
|
||||
.iter()
|
||||
.filter_map(|side| {
|
||||
Some(((*side).into(), template(sherds.get(&(*side).into())?)?))
|
||||
})
|
||||
.collect();
|
||||
if !kept.is_empty() {
|
||||
f.put("sherds", Tag::Compound(kept));
|
||||
}
|
||||
}
|
||||
if !f.loot_table() {
|
||||
f.item("item");
|
||||
}
|
||||
}
|
||||
"minecraft:trial_spawner" => {
|
||||
// `TrialSpawnerStateData.Packed` and `FullConfig`: every key is optional
|
||||
// and defaulted by vanilla; they are kept as loaded. No `spawn_data` is
|
||||
// added: an absent one loads as Optional.empty and is not stored, and
|
||||
// an empty entity would keep the spawner from ever picking a mob.
|
||||
if let Tag::Compound(c) = tag {
|
||||
for (k, v) in c {
|
||||
let key = k.to_string_lossy();
|
||||
if !matches!(
|
||||
key.as_str(),
|
||||
"id" | "x" | "y" | "z" | "keepPacked" | "components"
|
||||
) {
|
||||
f.out.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"minecraft:vault" => {
|
||||
// `VaultConfig.DEFAULT` (when the config is absent): the trial key and the
|
||||
// default reward table, which is not saved.
|
||||
f.compound_or(
|
||||
"config",
|
||||
[(
|
||||
"key_item".into(),
|
||||
Tag::compound([
|
||||
("count", Tag::Int(1)),
|
||||
("id", string("minecraft:trial_key")),
|
||||
]),
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
);
|
||||
f.compound_or("shared_data", Compound::new());
|
||||
f.compound_or("server_data", Compound::new());
|
||||
}
|
||||
"minecraft:test_block" => {
|
||||
f.string("mode", "fail");
|
||||
f.string("message", "");
|
||||
f.flag("powered", false);
|
||||
}
|
||||
"minecraft:test_instance_block" => {
|
||||
f.compound_or(
|
||||
"data",
|
||||
[
|
||||
("ignore_entities".into(), boolean(false)),
|
||||
("rotation".into(), string("none")),
|
||||
("size".into(), Tag::IntArray(vec![0, 0, 0])),
|
||||
("status".into(), string("cleared")),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
);
|
||||
if let Some(errors @ Tag::List(list)) = tag.get("errors")
|
||||
&& !list.is_empty()
|
||||
{
|
||||
f.put("errors", errors.clone());
|
||||
}
|
||||
}
|
||||
"minecraft:potent_sulfur" => f.int("countdown", -1),
|
||||
_ => return None,
|
||||
}
|
||||
let mut out = f.out;
|
||||
out.insert("id".into(), string(&id));
|
||||
out.insert("x".into(), Tag::Int(x));
|
||||
out.insert("y".into(), Tag::Int(y));
|
||||
out.insert("z".into(), Tag::Int(z));
|
||||
out.insert("keepPacked".into(), Tag::Byte(0));
|
||||
out.insert(
|
||||
"components".into(),
|
||||
match tag.get("components") {
|
||||
Some(c @ Tag::Compound(_)) => c.clone(),
|
||||
_ => Tag::Compound(Compound::new()),
|
||||
},
|
||||
);
|
||||
Some(Tag::Compound(out))
|
||||
}
|
||||
|
||||
/// `VibrationSystem.Data` for a sensor with no pending vibration.
|
||||
fn listener() -> Compound {
|
||||
[
|
||||
("event_delay".into(), Tag::Int(0)),
|
||||
("selector".into(), Tag::compound([("tick", Tag::Long(-1))])),
|
||||
]
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
/// Whether a stack plays a song (`JukeboxSong.fromStack`): a music disc or an item
|
||||
/// with the `jukebox_playable` component.
|
||||
fn is_record(item: &Compound) -> bool {
|
||||
let id = match item.get(&"id".into()) {
|
||||
Some(Tag::String(s)) => s.to_string_lossy(),
|
||||
_ => return false,
|
||||
};
|
||||
id.starts_with("minecraft:music_disc_")
|
||||
|| matches!(item.get(&"components".into()), Some(Tag::Compound(c)) if c.contains_key(&"minecraft:jukebox_playable".into()))
|
||||
}
|
||||
|
||||
/// Three-way merge of a block entity: `original` is the NBT it was loaded from,
|
||||
/// `loaded` what Horizon encodes right after decoding it, and `current` what Horizon
|
||||
/// encodes now. Whatever the game left unchanged since loading keeps its original
|
||||
/// form (including the detail Horizon does not model, such as styled text), what it
|
||||
/// changed takes the current value, and keys Horizon never models stay.
|
||||
pub fn overlay(original: &Tag, loaded: &Tag, current: &Tag) -> Tag {
|
||||
if current == loaded {
|
||||
return original.clone();
|
||||
}
|
||||
match (original, loaded, current) {
|
||||
(Tag::Compound(o), Tag::Compound(l), Tag::Compound(c)) => {
|
||||
let mut out = Compound::new();
|
||||
for (key, cv) in c {
|
||||
let value = match (o.get(key), l.get(key)) {
|
||||
(Some(ov), Some(lv)) => overlay(ov, lv, cv),
|
||||
_ => cv.clone(),
|
||||
};
|
||||
out.insert(key.clone(), value);
|
||||
}
|
||||
// Keys the game never models (or models only when present) survive;
|
||||
// keys it removed are gone.
|
||||
for (key, ov) in o {
|
||||
if !c.contains_key(key) && !l.contains_key(key) {
|
||||
out.insert(key.clone(), ov.clone());
|
||||
}
|
||||
}
|
||||
Tag::Compound(out)
|
||||
}
|
||||
(Tag::List(o), Tag::List(l), Tag::List(c)) if keyed_by_slot(c) && keyed_by_slot(l) => {
|
||||
let slot = |t: &Tag| int(t.get("Slot"));
|
||||
Tag::List(
|
||||
c.iter()
|
||||
.map(|cv| {
|
||||
let s = slot(cv);
|
||||
fn find(list: &[Tag], slot: Option<i32>) -> Option<&Tag> {
|
||||
list.iter().find(|t| int(t.get("Slot")) == slot)
|
||||
}
|
||||
match (find(o, s), find(l, s)) {
|
||||
(Some(ov), Some(lv)) => overlay(ov, lv, cv),
|
||||
_ => cv.clone(),
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
_ => current.clone(),
|
||||
}
|
||||
}
|
||||
fn keyed_by_slot(list: &[Tag]) -> bool {
|
||||
list.iter().all(|t| t.get("Slot").is_some())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_world::nbt::parse_snbt;
|
||||
|
||||
fn snbt(s: &str) -> Tag {
|
||||
parse_snbt(s).expect("snbt").0
|
||||
}
|
||||
fn canon(s: &str) -> Tag {
|
||||
canonical(&snbt(s)).expect("known type")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trial_spawner_without_spawn_data_saves_none() {
|
||||
let fresh = canon(
|
||||
r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,normal_config:"minecraft:trial_chamber/ranged/skeleton/normal"}"#,
|
||||
);
|
||||
assert_eq!(fresh.get("spawn_data"), None);
|
||||
let picked = canon(
|
||||
r#"{id:"minecraft:trial_spawner",x:1,y:2,z:3,spawn_data:{entity:{id:"minecraft:skeleton"}}}"#,
|
||||
);
|
||||
assert_eq!(
|
||||
picked.get("spawn_data"),
|
||||
Some(&snbt(r#"{entity:{id:"minecraft:skeleton"}}"#))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_type_has_defaults() {
|
||||
for id in TYPES.iter().chain(NEWEST.iter()) {
|
||||
let tag = snbt(&format!("{{id:\"{id}\",x:1,y:2,z:3}}"));
|
||||
let out = canonical(&tag).unwrap_or_else(|| panic!("{id}"));
|
||||
assert_eq!(out.get("id"), tag.get("id"));
|
||||
assert_eq!(out.get("keepPacked"), Some(&Tag::Byte(0)), "{id}");
|
||||
assert_eq!(
|
||||
out.get("components"),
|
||||
Some(&Tag::Compound(Compound::new())),
|
||||
"{id}"
|
||||
);
|
||||
}
|
||||
assert!(canonical(&snbt("{id:\"minecraft:nope\",x:1,y:2,z:3}")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn furnace_defaults_match_vanilla() {
|
||||
let out = canon("{id:\"minecraft:furnace\",x:1,y:2,z:3}");
|
||||
assert_eq!(out.get("cooking_total_time"), Some(&Tag::Int(0)));
|
||||
assert_eq!(out.get("speed_multiplier"), Some(&f32_tag(1.0)));
|
||||
assert_eq!(out.get("Items"), Some(&Tag::List(vec![])));
|
||||
assert_eq!(
|
||||
out.get("RecipesUsed"),
|
||||
Some(&Tag::Compound(Compound::new()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loot_table_replaces_items_and_zero_seed_is_omitted() {
|
||||
let out = canon(
|
||||
"{id:\"minecraft:chest\",x:1,y:2,z:3,LootTable:\"minecraft:chests/x\",LootTableSeed:0L,\
|
||||
Items:[{Slot:0b,id:\"minecraft:stone\",count:1}]}",
|
||||
);
|
||||
assert!(out.get("Items").is_none());
|
||||
assert!(out.get("LootTableSeed").is_none());
|
||||
assert_eq!(out.get("LootTable"), Some(&string("minecraft:chests/x")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_are_validated_and_sorted_by_slot() {
|
||||
let out = canon(
|
||||
"{id:\"minecraft:hopper\",x:1,y:2,z:3,Items:[\
|
||||
{Slot:4b,id:\"minecraft:stone\",count:2},{Slot:5b,id:\"minecraft:stone\",count:1},\
|
||||
{Slot:0b,id:\"minecraft:air\",count:1},{Slot:1b,id:\"minecraft:dirt\"},\
|
||||
{Slot:2b,id:\"minecraft:dirt\",count:100}]}",
|
||||
);
|
||||
let Some(Tag::List(items)) = out.get("Items") else {
|
||||
panic!("items")
|
||||
};
|
||||
let slots: Vec<_> = items.iter().map(|i| i.get("Slot").cloned()).collect();
|
||||
assert_eq!(slots, vec![Some(Tag::Byte(1)), Some(Tag::Byte(4))]);
|
||||
assert_eq!(items[0].get("count"), Some(&Tag::Int(1)));
|
||||
assert_eq!(out.get("TransferCooldown"), Some(&Tag::Int(-1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_text_components_become_strings() {
|
||||
let out =
|
||||
canon("{id:\"minecraft:banner\",x:1,y:2,z:3,CustomName:{text:\"Flag\"},patterns:[]}");
|
||||
assert_eq!(out.get("CustomName"), Some(&string("Flag")));
|
||||
assert!(out.get("patterns").is_none());
|
||||
let styled =
|
||||
canon("{id:\"minecraft:banner\",x:1,y:2,z:3,CustomName:{text:\"F\",color:\"red\"}}");
|
||||
assert!(matches!(styled.get("CustomName"), Some(Tag::Compound(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shulker_box_omits_empty_items_and_structure_block_clamps() {
|
||||
let shulker = canon("{id:\"minecraft:shulker_box\",x:1,y:2,z:3}");
|
||||
assert!(shulker.get("Items").is_none());
|
||||
let structure = canon("{id:\"minecraft:structure_block\",x:1,y:2,z:3,posX:99,sizeY:-4}");
|
||||
assert_eq!(structure.get("posX"), Some(&Tag::Int(48)));
|
||||
assert_eq!(structure.get("sizeY"), Some(&Tag::Int(0)));
|
||||
assert_eq!(structure.get("posY"), Some(&Tag::Int(1)));
|
||||
assert_eq!(structure.get("showboundingbox"), Some(&Tag::Byte(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_is_idempotent() {
|
||||
for id in TYPES.iter().chain(NEWEST.iter()) {
|
||||
let once = canonical(&snbt(&format!("{{id:\"{id}\",x:1,y:2,z:3}}"))).expect("known");
|
||||
assert_eq!(canonical(&once).as_ref(), Some(&once), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlay_keeps_unchanged_detail_and_takes_changes() {
|
||||
let original = snbt(
|
||||
"{id:\"minecraft:sign\",front_text:{messages:[{text:\"a\",color:\"red\"},\"\",\"\",\"\"]},\
|
||||
back_text:{messages:[\"x\",\"\",\"\",\"\"]},extra:1b}",
|
||||
);
|
||||
let loaded = snbt(
|
||||
"{id:\"minecraft:sign\",front_text:{messages:[\"a\",\"\",\"\",\"\"]},\
|
||||
back_text:{messages:[\"x\",\"\",\"\",\"\"]}}",
|
||||
);
|
||||
let current = snbt(
|
||||
"{id:\"minecraft:sign\",front_text:{messages:[\"a\",\"\",\"\",\"\"]},\
|
||||
back_text:{messages:[\"y\",\"\",\"\",\"\"]}}",
|
||||
);
|
||||
let merged = overlay(&original, &loaded, ¤t);
|
||||
assert_eq!(merged.get("front_text"), original.get("front_text"));
|
||||
assert_eq!(merged.get("back_text"), current.get("back_text"));
|
||||
assert_eq!(merged.get("extra"), original.get("extra"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlay_merges_container_slots() {
|
||||
let item = |slot: i8, count: i32, extra: &str| {
|
||||
snbt(&format!(
|
||||
"{{Slot:{slot}b,id:\"minecraft:stone\",count:{count}{extra}}}"
|
||||
))
|
||||
};
|
||||
let original = Tag::compound([(
|
||||
"Items",
|
||||
Tag::List(vec![
|
||||
item(0, 1, ",components:{\"minecraft:lore\":[\"x\"]}"),
|
||||
item(1, 1, ""),
|
||||
]),
|
||||
)]);
|
||||
let loaded = Tag::compound([("Items", Tag::List(vec![item(0, 1, ""), item(1, 1, "")]))]);
|
||||
let current = Tag::compound([("Items", Tag::List(vec![item(0, 1, ""), item(1, 5, "")]))]);
|
||||
let merged = overlay(&original, &loaded, ¤t);
|
||||
let Some(Tag::List(items)) = merged.get("Items") else {
|
||||
panic!("items")
|
||||
};
|
||||
assert!(
|
||||
items[0].get("components").is_some(),
|
||||
"slot 0 keeps its lore"
|
||||
);
|
||||
assert_eq!(items[1].get("count"), Some(&Tag::Int(5)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//! Custom boss bars (`CustomBossEvents`): the `/bossbar` store, its saved
|
||||
//! form (`data/minecraft/custom_boss_events.dat`) and how a bar is shown.
|
||||
use crate::{
|
||||
scoreboard::{Comp, bracketed, comp_text, json_to_tag, literal, tag_to_json},
|
||||
text::{self, Style, Text},
|
||||
};
|
||||
use horizon_world::nbt::{Compound, Tag};
|
||||
|
||||
pub const COLORS: [&str; 7] = ["pink", "blue", "red", "green", "yellow", "purple", "white"];
|
||||
pub const STYLES: [&str; 5] = [
|
||||
"progress",
|
||||
"notched_6",
|
||||
"notched_10",
|
||||
"notched_12",
|
||||
"notched_20",
|
||||
];
|
||||
/// `BossBarColor.getFormatting`. Purple is dark blue in 26.3.
|
||||
pub fn color_rgb(color: &str) -> u32 {
|
||||
let name = match color {
|
||||
"pink" => "red",
|
||||
"red" => "dark_red",
|
||||
"purple" => "dark_blue",
|
||||
other => other,
|
||||
};
|
||||
text::named_color(name).unwrap_or(text::WHITE)
|
||||
}
|
||||
|
||||
/// A version-4 shaped id from a resource id. Saved boss events do not keep
|
||||
/// their UUID (`CustomBossEvents` mints a new one on load).
|
||||
pub fn stable_uuid(id: &str) -> u128 {
|
||||
let mut h = 0xcbf29ce484222325u64;
|
||||
for b in id.as_bytes() {
|
||||
h ^= u64::from(*b);
|
||||
h = h.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
let most = (h as i64) & -61441 | 16384;
|
||||
let least = (h.rotate_left(17) as i64) & 4_611_686_018_427_387_903 | i64::MIN;
|
||||
((most as u64 as u128) << 64) | (least as u64 as u128)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BossBar {
|
||||
pub id: String,
|
||||
/// The `ServerBossEvent` UUID. Not saved.
|
||||
pub uuid: u128,
|
||||
pub name: Comp,
|
||||
pub color: String,
|
||||
pub style: String,
|
||||
pub value: i32,
|
||||
pub max: i32,
|
||||
/// `ServerBossEvent.visible`. A new bar is visible; nobody sees it until
|
||||
/// a player is added.
|
||||
pub visible: bool,
|
||||
pub darken: bool,
|
||||
pub music: bool,
|
||||
pub fog: bool,
|
||||
/// `CustomBossEvent.players`, the UUIDs told about the bar.
|
||||
pub players: Vec<[i32; 4]>,
|
||||
}
|
||||
impl BossBar {
|
||||
pub fn new(id: &str, name: Comp) -> Self {
|
||||
Self {
|
||||
id: id.to_owned(),
|
||||
uuid: stable_uuid(id),
|
||||
name,
|
||||
color: "white".into(),
|
||||
style: "progress".into(),
|
||||
value: 0,
|
||||
max: 100,
|
||||
visible: true,
|
||||
darken: false,
|
||||
music: false,
|
||||
fog: false,
|
||||
players: Vec::new(),
|
||||
}
|
||||
}
|
||||
/// `CustomBossEvent.getDisplayName`.
|
||||
pub fn display_name(&self) -> Text {
|
||||
let style = Style {
|
||||
color: Some(color_rgb(&self.color)),
|
||||
hover: Some(Box::new(Text::literal(self.id.clone()))),
|
||||
..Style::default()
|
||||
};
|
||||
// ComponentUtils.wrapInSquareBrackets(name).withStyle(...): the
|
||||
// brackets take the colour too.
|
||||
bracketed(comp_text(&self.name)).with_style(&style)
|
||||
}
|
||||
/// The filled fraction of the bar (`BossEvent.getProgress`).
|
||||
pub fn progress(&self) -> f32 {
|
||||
(self.value as f32 / self.max.max(1) as f32).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BossBars {
|
||||
pub bars: Vec<BossBar>,
|
||||
}
|
||||
impl BossBars {
|
||||
pub fn get(&self, id: &str) -> Option<&BossBar> {
|
||||
self.bars.iter().find(|b| b.id == id)
|
||||
}
|
||||
pub fn get_mut(&mut self, id: &str) -> Option<&mut BossBar> {
|
||||
self.bars.iter_mut().find(|b| b.id == id)
|
||||
}
|
||||
pub fn add(&mut self, id: &str, name: Comp) -> bool {
|
||||
if self.get(id).is_some() {
|
||||
return false;
|
||||
}
|
||||
self.bars.push(BossBar::new(id, name));
|
||||
true
|
||||
}
|
||||
pub fn remove(&mut self, id: &str) {
|
||||
self.bars.retain(|b| b.id != id);
|
||||
}
|
||||
pub fn ids(&self) -> Vec<String> {
|
||||
self.bars.iter().map(|b| b.id.clone()).collect()
|
||||
}
|
||||
/// The saved compound (`CustomBossEvent.Packed`).
|
||||
pub fn pack(&self) -> Tag {
|
||||
let mut c = Compound::new();
|
||||
for b in &self.bars {
|
||||
let players = b
|
||||
.players
|
||||
.iter()
|
||||
.map(|u| Tag::IntArray(u.to_vec()))
|
||||
.collect();
|
||||
c.insert(
|
||||
b.id.as_str().into(),
|
||||
Tag::compound([
|
||||
("Name", json_to_tag(&b.name)),
|
||||
("Visible", Tag::Byte(i8::from(b.visible))),
|
||||
("Value", Tag::Int(b.value)),
|
||||
("Max", Tag::Int(b.max)),
|
||||
("Color", Tag::String(b.color.as_str().into())),
|
||||
("Overlay", Tag::String(b.style.as_str().into())),
|
||||
("DarkenScreen", Tag::Byte(i8::from(b.darken))),
|
||||
("PlayBossMusic", Tag::Byte(i8::from(b.music))),
|
||||
("CreateWorldFog", Tag::Byte(i8::from(b.fog))),
|
||||
("Players", Tag::List(players)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
Tag::Compound(c)
|
||||
}
|
||||
pub fn unpack(data: &Tag) -> Self {
|
||||
let mut bars = Vec::new();
|
||||
if let Tag::Compound(c) = data {
|
||||
for (id, e) in c {
|
||||
let get = |k: &str| e.get(k);
|
||||
let text = |k: &str, d: &str| match get(k) {
|
||||
Some(Tag::String(s)) => s.to_string_lossy(),
|
||||
_ => d.to_owned(),
|
||||
};
|
||||
let num = |k: &str, d: i32| match get(k) {
|
||||
Some(Tag::Int(v)) => *v,
|
||||
Some(Tag::Short(v)) => i32::from(*v),
|
||||
Some(Tag::Byte(v)) => i32::from(*v),
|
||||
_ => d,
|
||||
};
|
||||
let players = match get("Players") {
|
||||
Some(Tag::List(l)) => l
|
||||
.iter()
|
||||
.filter_map(|t| match t {
|
||||
Tag::IntArray(a) if a.len() == 4 => Some([a[0], a[1], a[2], a[3]]),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let id = id.to_string_lossy();
|
||||
bars.push(BossBar {
|
||||
uuid: stable_uuid(&id),
|
||||
id,
|
||||
name: get("Name").map_or_else(|| literal(""), tag_to_json),
|
||||
color: text("Color", "white"),
|
||||
style: text("Overlay", "progress"),
|
||||
value: num("Value", 0),
|
||||
max: num("Max", 100),
|
||||
visible: num("Visible", 0) != 0,
|
||||
darken: num("DarkenScreen", 0) != 0,
|
||||
music: num("PlayBossMusic", 0) != 0,
|
||||
fog: num("CreateWorldFog", 0) != 0,
|
||||
players,
|
||||
});
|
||||
}
|
||||
}
|
||||
Self { bars }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bars_round_trip_and_show() {
|
||||
let mut b = BossBars::default();
|
||||
assert!(b.add("test:x", literal("Hello")));
|
||||
assert!(!b.add("test:x", literal("Again")));
|
||||
let bar = b.get_mut("test:x").unwrap();
|
||||
bar.color = "pink".into();
|
||||
bar.style = "notched_10".into();
|
||||
bar.value = 25;
|
||||
bar.max = 50;
|
||||
bar.visible = true;
|
||||
bar.darken = true;
|
||||
bar.players = vec![[1, 2, 3, 4]];
|
||||
let back = BossBars::unpack(&b.pack());
|
||||
assert_eq!(back, b);
|
||||
let bar = b.get("test:x").unwrap();
|
||||
assert_eq!(bar.progress(), 0.5);
|
||||
assert_eq!(bar.display_name().plain(), "chat.square_brackets");
|
||||
assert_eq!(color_rgb("pink"), text::RED);
|
||||
assert_eq!(color_rgb("purple"), text::named_color("dark_blue").unwrap());
|
||||
b.remove("test:x");
|
||||
assert!(b.bars.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
//! Text components from commands: `ComponentArgument` reads an SNBT (or JSON)
|
||||
//! value, `ComponentSerialization` turns it into styled text.
|
||||
use crate::text::{Style, Text, named_color};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
/// `SnbtGrammar`, enough for components: compounds, lists, quoted and
|
||||
/// unquoted strings, numbers (with type suffixes) and booleans. Returns the
|
||||
/// value and the bytes consumed.
|
||||
pub fn parse_snbt(input: &str) -> Result<(Value, usize), String> {
|
||||
let mut p = Parser {
|
||||
s: input.as_bytes(),
|
||||
i: 0,
|
||||
};
|
||||
let v = p.value()?;
|
||||
Ok((v, p.i))
|
||||
}
|
||||
struct Parser<'a> {
|
||||
s: &'a [u8],
|
||||
i: usize,
|
||||
}
|
||||
impl Parser<'_> {
|
||||
fn ws(&mut self) {
|
||||
while self.i < self.s.len() && self.s[self.i].is_ascii_whitespace() {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.s.get(self.i).copied()
|
||||
}
|
||||
fn expect(&mut self, c: u8) -> Result<(), String> {
|
||||
self.ws();
|
||||
if self.peek() == Some(c) {
|
||||
self.i += 1;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("expected '{}'", c as char))
|
||||
}
|
||||
}
|
||||
fn value(&mut self) -> Result<Value, String> {
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
Some(b'{') => {
|
||||
self.i += 1;
|
||||
let mut map = Map::new();
|
||||
self.ws();
|
||||
if self.peek() == Some(b'}') {
|
||||
self.i += 1;
|
||||
return Ok(Value::Object(map));
|
||||
}
|
||||
loop {
|
||||
self.ws();
|
||||
let key = self.string()?;
|
||||
self.expect(b':')?;
|
||||
map.insert(key, self.value()?);
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
Some(b',') => self.i += 1,
|
||||
Some(b'}') => {
|
||||
self.i += 1;
|
||||
return Ok(Value::Object(map));
|
||||
}
|
||||
_ => return Err("expected ',' or '}'".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(b'[') => {
|
||||
self.i += 1;
|
||||
let mut list = Vec::new();
|
||||
self.ws();
|
||||
// Typed arrays [B;...], [I;...], [L;...].
|
||||
if matches!(
|
||||
self.s.get(self.i..self.i + 2),
|
||||
Some([b'B' | b'I' | b'L', b';'])
|
||||
) {
|
||||
self.i += 2;
|
||||
}
|
||||
self.ws();
|
||||
if self.peek() == Some(b']') {
|
||||
self.i += 1;
|
||||
return Ok(Value::Array(list));
|
||||
}
|
||||
loop {
|
||||
list.push(self.value()?);
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
Some(b',') => self.i += 1,
|
||||
Some(b']') => {
|
||||
self.i += 1;
|
||||
return Ok(Value::Array(list));
|
||||
}
|
||||
_ => return Err("expected ',' or ']'".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(b'"' | b'\'') => Ok(Value::String(self.string()?)),
|
||||
Some(_) => {
|
||||
let word = self.unquoted();
|
||||
if word.is_empty() {
|
||||
return Err("expected a value".into());
|
||||
}
|
||||
Ok(match word.as_str() {
|
||||
"true" => Value::Bool(true),
|
||||
"false" => Value::Bool(false),
|
||||
_ => {
|
||||
let digits = word
|
||||
.trim_end_matches(['b', 'B', 's', 'S', 'l', 'L', 'f', 'F', 'd', 'D']);
|
||||
match (digits.parse::<i64>(), digits.parse::<f64>()) {
|
||||
(Ok(n), _) if digits.len() + 1 >= word.len() => Value::from(n),
|
||||
(_, Ok(f)) if digits.len() + 1 >= word.len() => Value::from(f),
|
||||
_ => Value::String(word),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
None => Err("expected a value".into()),
|
||||
}
|
||||
}
|
||||
fn unquoted(&mut self) -> String {
|
||||
let start = self.i;
|
||||
while let Some(c) = self.peek() {
|
||||
if c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.' | b'+') {
|
||||
self.i += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&self.s[start..self.i]).into_owned()
|
||||
}
|
||||
fn string(&mut self) -> Result<String, String> {
|
||||
self.ws();
|
||||
let Some(q @ (b'"' | b'\'')) = self.peek() else {
|
||||
return Ok(self.unquoted());
|
||||
};
|
||||
self.i += 1;
|
||||
let mut out = Vec::new();
|
||||
while let Some(c) = self.peek() {
|
||||
self.i += 1;
|
||||
match c {
|
||||
b'\\' => {
|
||||
let Some(e) = self.peek() else { break };
|
||||
self.i += 1;
|
||||
out.push(match e {
|
||||
b'n' => b'\n',
|
||||
b't' => b'\t',
|
||||
other => other,
|
||||
});
|
||||
}
|
||||
c if c == q => return Ok(String::from_utf8_lossy(&out).into_owned()),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
Err("unterminated string".into())
|
||||
}
|
||||
}
|
||||
/// The style fields of a component object.
|
||||
fn object_style(o: &serde_json::Map<String, Value>) -> Style {
|
||||
let mut style = Style::default();
|
||||
if let Some(c) = o.get("color").and_then(Value::as_str) {
|
||||
style.color = named_color(c).or_else(|| {
|
||||
c.strip_prefix('#')
|
||||
.and_then(|h| u32::from_str_radix(h, 16).ok())
|
||||
});
|
||||
}
|
||||
let flag = |k: &str| o.get(k).and_then(Value::as_bool);
|
||||
style.bold = flag("bold");
|
||||
style.italic = flag("italic");
|
||||
style.underlined = flag("underlined");
|
||||
style.strikethrough = flag("strikethrough");
|
||||
style.obfuscated = flag("obfuscated");
|
||||
style.font = o.get("font").and_then(crate::text::font_id);
|
||||
// ClickEvent.CODEC: the actions a chat line acts on here. A component
|
||||
// from a server never opens a file.
|
||||
if let Some(e) = o.get("click_event").and_then(Value::as_object) {
|
||||
let text = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_owned);
|
||||
style.click = match e.get("action").and_then(Value::as_str) {
|
||||
// ClickEvent.OpenUrl.CODEC: ExtraCodecs.UNTRUSTED_URI allows http and
|
||||
// https only, the scheme in any case (Util.parseAndValidateUntrustedUri).
|
||||
Some("open_url") => text("url")
|
||||
.filter(|u| {
|
||||
u.split_once(':').is_some_and(|(scheme, _)| {
|
||||
scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")
|
||||
})
|
||||
})
|
||||
.map(crate::text::ClickEvent::OpenUrl),
|
||||
// ClickEvent.ChangePage.CODEC: ExtraCodecs.POSITIVE_INT.
|
||||
Some("change_page") => e
|
||||
.get("page")
|
||||
.and_then(Value::as_i64)
|
||||
.and_then(|p| i32::try_from(p).ok())
|
||||
.filter(|p| *p >= 1)
|
||||
.map(crate::text::ClickEvent::ChangePage),
|
||||
Some("suggest_command") => text("command").map(crate::text::ClickEvent::SuggestCommand),
|
||||
Some("copy_to_clipboard") => {
|
||||
text("value").map(crate::text::ClickEvent::CopyToClipboard)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
// HoverEvent.ShowText.
|
||||
if let Some(e) = o.get("hover_event").and_then(Value::as_object)
|
||||
&& e.get("action").and_then(Value::as_str) == Some("show_text")
|
||||
&& let Some(value) = e.get("value")
|
||||
{
|
||||
style.hover = Some(Box::new(to_text(value, &mut |s| Text::literal(s))));
|
||||
}
|
||||
style
|
||||
}
|
||||
/// `ComponentSerialization.CODEC` decoding into text. `selector` components
|
||||
/// are resolved by `resolve` (ComponentUtils.updateForEntity).
|
||||
pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
|
||||
to_text_with(v, resolve, &mut |_| None)
|
||||
}
|
||||
/// `to_text` with a hook resolving other contents (`nbt`) from the object.
|
||||
pub fn to_text_with(
|
||||
v: &Value,
|
||||
resolve: &mut dyn FnMut(&str) -> Text,
|
||||
contents: &mut dyn FnMut(&serde_json::Map<String, Value>) -> Option<Text>,
|
||||
) -> Text {
|
||||
match v {
|
||||
Value::String(s) => Text::literal(s.clone()),
|
||||
Value::Number(n) => Text::literal(n.to_string()),
|
||||
Value::Bool(b) => Text::literal(b.to_string()),
|
||||
// A list is its first element with the rest as siblings.
|
||||
Value::Array(list) => {
|
||||
let Some((first, rest)) = list.split_first() else {
|
||||
return Text::empty();
|
||||
};
|
||||
let mut base = to_text_with(first, resolve, contents);
|
||||
// The siblings take the first component's own style, even when
|
||||
// its text is empty.
|
||||
let style = match first {
|
||||
Value::Object(o) => object_style(o),
|
||||
_ => base
|
||||
.spans
|
||||
.first()
|
||||
.map(|s| s.style.clone())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
for sibling in rest {
|
||||
base.push(to_text_with(sibling, resolve, contents).with_style(&style));
|
||||
}
|
||||
base
|
||||
}
|
||||
Value::Object(o) => {
|
||||
let style = object_style(o);
|
||||
let content = if let Some(t) = contents(o) {
|
||||
t
|
||||
} else if let Some(t) = o.get("text") {
|
||||
match t {
|
||||
Value::String(s) => Text::literal(s.clone()),
|
||||
other => Text::literal(other.to_string()),
|
||||
}
|
||||
} else if let Some(key) = o.get("translate").and_then(Value::as_str) {
|
||||
let args: Vec<Text> = o
|
||||
.get("with")
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.map(|x| to_text_with(x, resolve, contents))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let translated = Text::translate(key, &args);
|
||||
match o.get("fallback").and_then(Value::as_str) {
|
||||
Some(fallback) if translated.plain() == key => Text::translate(fallback, &args),
|
||||
_ => translated,
|
||||
}
|
||||
} else if let Some(sel) = o.get("selector").and_then(Value::as_str) {
|
||||
resolve(sel)
|
||||
} else if let Some(key) = o.get("keybind").and_then(Value::as_str) {
|
||||
crate::key_display::display_name(key)
|
||||
} else {
|
||||
Text::empty()
|
||||
};
|
||||
let mut out = content.with_style(&style);
|
||||
for extra in o
|
||||
.get("extra")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
out.push(to_text_with(extra, resolve, contents).with_style(&style));
|
||||
}
|
||||
out
|
||||
}
|
||||
Value::Null => Text::empty(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn snbt_and_json_components() {
|
||||
let input = "{text:'Hi ',color:red,extra:[{text:\"there\",bold:1b}]} rest";
|
||||
let (v, n) = parse_snbt(input).unwrap();
|
||||
assert_eq!(&input[n..], " rest");
|
||||
let t = to_text(&v, &mut |_| Text::empty());
|
||||
assert_eq!(t.plain(), "Hi there");
|
||||
assert_eq!(t.spans[1].style.color, named_color("red"));
|
||||
let (v, _) = parse_snbt("[\"a\",{\"text\":\"b\"}]").unwrap();
|
||||
assert_eq!(to_text(&v, &mut |_| Text::empty()).plain(), "ab");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_font_is_inherited_and_kept() {
|
||||
let (v, _) =
|
||||
parse_snbt(r#"{text:"a",font:"alt",extra:["b",{text:"c",font:"minecraft:uniform"}]}"#)
|
||||
.unwrap();
|
||||
let t = to_text(&v, &mut |_| Text::empty());
|
||||
let fonts: Vec<_> = t.chars().map(|(_, s)| s.font.clone()).collect();
|
||||
let (alt, uniform) = (
|
||||
Some("minecraft:alt".into()),
|
||||
Some("minecraft:uniform".into()),
|
||||
);
|
||||
assert_eq!(fonts, [alt.clone(), alt, uniform]);
|
||||
// Back to JSON with the field, which a re-read keeps.
|
||||
let again = to_text(&t.component(), &mut |_| Text::empty());
|
||||
let kept: Vec<_> = again.chars().map(|(_, s)| s.font.clone()).collect();
|
||||
assert_eq!(kept, fonts);
|
||||
// Not an identifier: no font.
|
||||
let (v, _) = parse_snbt(r#"{text:"a",font:"Bad Font"}"#).unwrap();
|
||||
let t = to_text(&v, &mut |_| Text::empty());
|
||||
assert_eq!(t.spans[0].style.font, None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
//! Iteration order of the Java hash collections vanilla's scoreboard keeps
|
||||
//! its names in: fastutil's `Object2ObjectOpenHashMap<String, _>` (open
|
||||
//! addressing with linear probing, backward-shift deletion and rehashing at
|
||||
//! the load factor) and `java.util.HashSet<String>` (chained buckets split on
|
||||
//! resize). Commands list, and `scoreboard.dat` saves, in these orders.
|
||||
|
||||
/// The keys of a fastutil open hash map in their table slots.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OpenOrder {
|
||||
keys: Vec<Option<String>>,
|
||||
size: usize,
|
||||
min_n: usize,
|
||||
load: f32,
|
||||
}
|
||||
impl Default for OpenOrder {
|
||||
/// `new Object2ObjectOpenHashMap<>()`: 16 expected entries, load 0.75.
|
||||
fn default() -> Self {
|
||||
Self::new(16, 0.75)
|
||||
}
|
||||
}
|
||||
/// `String.hashCode`.
|
||||
pub fn java_hash(s: &str) -> i32 {
|
||||
s.encode_utf16()
|
||||
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c)))
|
||||
}
|
||||
/// `HashCommon.mix`.
|
||||
fn mix(x: i32) -> usize {
|
||||
let h = (x as u32).wrapping_mul(0x9E37_79B9);
|
||||
(h ^ (h >> 16)) as usize
|
||||
}
|
||||
/// `HashCommon.arraySize`.
|
||||
fn array_size(expected: usize, f: f32) -> usize {
|
||||
let wanted = (expected as f64 / f64::from(f)).ceil() as usize;
|
||||
wanted.max(2).next_power_of_two()
|
||||
}
|
||||
/// `HashCommon.maxFill`.
|
||||
fn max_fill(n: usize, f: f32) -> usize {
|
||||
((n as f64 * f64::from(f)).ceil() as usize).min(n - 1)
|
||||
}
|
||||
impl OpenOrder {
|
||||
pub fn new(expected: usize, load: f32) -> Self {
|
||||
let n = array_size(expected, load);
|
||||
Self {
|
||||
keys: vec![None; n],
|
||||
size: 0,
|
||||
min_n: n,
|
||||
load,
|
||||
}
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.size == 0
|
||||
}
|
||||
fn slot(&self, key: &str) -> usize {
|
||||
mix(java_hash(key)) & (self.keys.len() - 1)
|
||||
}
|
||||
pub fn contains(&self, key: &str) -> bool {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
while let Some(k) = &self.keys[pos] {
|
||||
if k == key {
|
||||
return true;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
false
|
||||
}
|
||||
/// `put`: false when the key was already there.
|
||||
pub fn insert(&mut self, key: &str) -> bool {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
while let Some(k) = &self.keys[pos] {
|
||||
if k == key {
|
||||
return false;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
self.keys[pos] = Some(key.to_owned());
|
||||
// `if (size++ >= maxFill) rehash(arraySize(size + 1, f))`.
|
||||
let old = self.size;
|
||||
self.size += 1;
|
||||
if old >= max_fill(self.keys.len(), self.load) {
|
||||
self.rehash(array_size(self.size + 1, self.load));
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `remove`: false when the key was not there.
|
||||
pub fn remove(&mut self, key: &str) -> bool {
|
||||
let mask = self.keys.len() - 1;
|
||||
let mut pos = self.slot(key);
|
||||
loop {
|
||||
match &self.keys[pos] {
|
||||
None => return false,
|
||||
Some(k) if k == key => break,
|
||||
Some(_) => pos = (pos + 1) & mask,
|
||||
}
|
||||
}
|
||||
self.size -= 1;
|
||||
self.shift_keys(pos);
|
||||
let n = self.keys.len();
|
||||
if n > self.min_n && self.size < max_fill(n, self.load) / 4 && n > 16 {
|
||||
self.rehash(n / 2);
|
||||
}
|
||||
true
|
||||
}
|
||||
fn shift_keys(&mut self, mut pos: usize) {
|
||||
let mask = self.keys.len() - 1;
|
||||
loop {
|
||||
let last = pos;
|
||||
pos = (last + 1) & mask;
|
||||
loop {
|
||||
let Some(curr) = self.keys[pos].clone() else {
|
||||
self.keys[last] = None;
|
||||
return;
|
||||
};
|
||||
let slot = self.slot(&curr);
|
||||
let stop = if last <= pos {
|
||||
last >= slot || slot > pos
|
||||
} else {
|
||||
last >= slot && slot > pos
|
||||
};
|
||||
if stop {
|
||||
self.keys[last] = Some(curr);
|
||||
break;
|
||||
}
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
}
|
||||
}
|
||||
fn rehash(&mut self, new_n: usize) {
|
||||
let old = std::mem::replace(&mut self.keys, vec![None; new_n]);
|
||||
let mask = new_n - 1;
|
||||
// `for (int j = realSize(); j-- != 0;) { while (key[--i] == null); ... }`
|
||||
for key in old.into_iter().rev().flatten() {
|
||||
let mut pos = mix(java_hash(&key)) & mask;
|
||||
while self.keys[pos].is_some() {
|
||||
pos = (pos + 1) & mask;
|
||||
}
|
||||
self.keys[pos] = Some(key);
|
||||
}
|
||||
}
|
||||
/// `iterator()` and `forEach`: from the last slot down.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &str> {
|
||||
self.keys.iter().rev().flatten().map(String::as_str)
|
||||
}
|
||||
/// `spliterator()` (what `stream()` uses): from the first slot up.
|
||||
pub fn stream(&self) -> impl Iterator<Item = &str> {
|
||||
self.keys.iter().flatten().map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys of a `java.util.HashSet<String>` in their buckets.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct HashSetOrder {
|
||||
/// Empty until the first insertion (`HashMap.resize` on first `put`).
|
||||
table: Vec<Vec<String>>,
|
||||
size: usize,
|
||||
}
|
||||
/// `HashMap.hash`.
|
||||
fn spread(s: &str) -> usize {
|
||||
let h = java_hash(s) as u32;
|
||||
(h ^ (h >> 16)) as usize
|
||||
}
|
||||
impl HashSetOrder {
|
||||
pub fn len(&self) -> usize {
|
||||
self.size
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.size == 0
|
||||
}
|
||||
pub fn contains(&self, key: &str) -> bool {
|
||||
if self.table.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let i = spread(key) & (self.table.len() - 1);
|
||||
self.table[i].iter().any(|k| k == key)
|
||||
}
|
||||
pub fn insert(&mut self, key: &str) -> bool {
|
||||
if self.table.is_empty() {
|
||||
self.table = vec![Vec::new(); 16];
|
||||
}
|
||||
let i = spread(key) & (self.table.len() - 1);
|
||||
if self.table[i].iter().any(|k| k == key) {
|
||||
return false;
|
||||
}
|
||||
self.table[i].push(key.to_owned());
|
||||
self.size += 1;
|
||||
if self.size > self.table.len() * 3 / 4 {
|
||||
self.resize();
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Doubles the table; each bucket splits into its low and high halves in order.
|
||||
fn resize(&mut self) {
|
||||
let old = std::mem::take(&mut self.table);
|
||||
let n = old.len() * 2;
|
||||
self.table = vec![Vec::new(); n];
|
||||
for bucket in old {
|
||||
for key in bucket {
|
||||
let i = spread(&key) & (n - 1);
|
||||
self.table[i].push(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn remove(&mut self, key: &str) -> bool {
|
||||
if self.table.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let i = spread(key) & (self.table.len() - 1);
|
||||
let Some(at) = self.table[i].iter().position(|k| k == key) else {
|
||||
return false;
|
||||
};
|
||||
self.table[i].remove(at);
|
||||
self.size -= 1;
|
||||
true
|
||||
}
|
||||
pub fn iter(&self) -> impl Iterator<Item = &String> {
|
||||
self.table.iter().flatten()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hash_and_order() {
|
||||
assert_eq!(java_hash("harness"), {
|
||||
"harness"
|
||||
.chars()
|
||||
.fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(c as i32))
|
||||
});
|
||||
let mut o = OpenOrder::new(16, 0.5);
|
||||
for k in ["harness", "harness_h"] {
|
||||
o.insert(k);
|
||||
}
|
||||
assert_eq!(o.iter().count(), 2);
|
||||
let mut asc: Vec<&str> = o.stream().collect();
|
||||
asc.reverse();
|
||||
assert_eq!(asc, o.iter().collect::<Vec<_>>());
|
||||
o.remove("harness");
|
||||
assert_eq!(o.iter().collect::<Vec<_>>(), vec!["harness_h"]);
|
||||
for i in 0..40 {
|
||||
o.insert(&format!("k{i}"));
|
||||
}
|
||||
assert_eq!(o.iter().count(), 41);
|
||||
for i in 0..40 {
|
||||
o.remove(&format!("k{i}"));
|
||||
}
|
||||
assert_eq!(o.iter().collect::<Vec<_>>(), vec!["harness_h"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_set_buckets() {
|
||||
let mut s = HashSetOrder::default();
|
||||
for i in 0..30 {
|
||||
assert!(s.insert(&format!("p{i}")));
|
||||
}
|
||||
assert!(!s.insert("p3"));
|
||||
assert_eq!(s.len(), 30);
|
||||
assert!(s.remove("p3") && !s.contains("p3"));
|
||||
// "Aa" and "BB" share a hash: insertion order within the bucket.
|
||||
let mut t = HashSetOrder::default();
|
||||
t.insert("BB");
|
||||
t.insert("Aa");
|
||||
assert_eq!(t.iter().collect::<Vec<_>>(), vec!["BB", "Aa"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
//! Game rules (26.3 `GameRules`): the registered rules with their category,
|
||||
//! type, default and bounds, a value map, and persistence in the world's
|
||||
//! `data/minecraft/game_rules.dat` saved-data file.
|
||||
use horizon_world::{
|
||||
DATA_VERSION,
|
||||
compression::Compression,
|
||||
nbt::{self, Limits, NamedTag, Tag},
|
||||
};
|
||||
use std::{collections::BTreeMap, fs, path::Path};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Value {
|
||||
Bool(bool),
|
||||
Int(i32),
|
||||
}
|
||||
impl std::fmt::Display for Value {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Value::Bool(b) => write!(f, "{b}"),
|
||||
Value::Int(i) => write!(f, "{i}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct Rule {
|
||||
pub name: &'static str,
|
||||
pub category: &'static str,
|
||||
pub default: Value,
|
||||
pub min: i32,
|
||||
pub max: i32,
|
||||
}
|
||||
const fn b(name: &'static str, category: &'static str, default: bool) -> Rule {
|
||||
Rule {
|
||||
name,
|
||||
category,
|
||||
default: Value::Bool(default),
|
||||
min: 0,
|
||||
max: 0,
|
||||
}
|
||||
}
|
||||
const fn i(name: &'static str, category: &'static str, default: i32, min: i32, max: i32) -> Rule {
|
||||
Rule {
|
||||
name,
|
||||
category,
|
||||
default: Value::Int(default),
|
||||
min,
|
||||
max,
|
||||
}
|
||||
}
|
||||
/// Every rule available without experimental features, in registration order.
|
||||
pub const RULES: &[Rule] = &[
|
||||
b("advance_time", "updates", true),
|
||||
b("advance_weather", "updates", true),
|
||||
b("allow_entering_nether_using_portals", "misc", true),
|
||||
b("block_drops", "drops", true),
|
||||
b("block_explosion_drop_decay", "drops", true),
|
||||
b("command_blocks_work", "misc", true),
|
||||
b("command_block_output", "chat", true),
|
||||
b("drowning_damage", "player", true),
|
||||
b("elytra_movement_check", "player", true),
|
||||
b("ender_pearls_vanish_on_death", "player", true),
|
||||
b("entity_drops", "drops", true),
|
||||
b("fall_damage", "player", true),
|
||||
b("fire_damage", "player", true),
|
||||
i(
|
||||
"fire_spread_radius_around_player",
|
||||
"updates",
|
||||
128,
|
||||
-1,
|
||||
i32::MAX,
|
||||
),
|
||||
b("forgive_dead_players", "mobs", true),
|
||||
b("freeze_damage", "player", true),
|
||||
b("global_sound_events", "misc", true),
|
||||
b("immediate_respawn", "player", false),
|
||||
b("keep_inventory", "player", false),
|
||||
b("lava_source_conversion", "updates", false),
|
||||
b("limited_crafting", "player", false),
|
||||
b("locator_bar", "player", true),
|
||||
b("log_admin_commands", "chat", true),
|
||||
i("max_block_modifications", "misc", 32768, 1, i32::MAX),
|
||||
i("max_command_forks", "misc", 65536, 0, i32::MAX),
|
||||
i("max_command_sequence_length", "misc", 65536, 0, i32::MAX),
|
||||
i("max_entity_cramming", "mobs", 24, 0, i32::MAX),
|
||||
i("max_snow_accumulation_height", "updates", 1, 0, 8),
|
||||
b("mob_drops", "drops", true),
|
||||
b("mob_explosion_drop_decay", "drops", true),
|
||||
b("mob_griefing", "mobs", true),
|
||||
b("natural_health_regeneration", "player", true),
|
||||
b("player_movement_check", "player", true),
|
||||
i(
|
||||
"players_nether_portal_creative_delay",
|
||||
"player",
|
||||
0,
|
||||
0,
|
||||
i32::MAX,
|
||||
),
|
||||
i(
|
||||
"players_nether_portal_default_delay",
|
||||
"player",
|
||||
80,
|
||||
0,
|
||||
i32::MAX,
|
||||
),
|
||||
i("players_sleeping_percentage", "player", 100, 0, i32::MAX),
|
||||
b("projectiles_can_break_blocks", "drops", true),
|
||||
b("pvp", "player", true),
|
||||
b("raids", "mobs", true),
|
||||
i("random_tick_speed", "updates", 3, 0, i32::MAX),
|
||||
b("reduced_debug_info", "misc", false),
|
||||
i("respawn_radius", "player", 10, 0, i32::MAX),
|
||||
b("send_command_feedback", "chat", true),
|
||||
b("show_advancement_messages", "chat", true),
|
||||
b("show_death_messages", "chat", true),
|
||||
b("spawner_blocks_work", "misc", true),
|
||||
b("spawn_mobs", "spawning", true),
|
||||
b("spawn_monsters", "spawning", true),
|
||||
b("spawn_patrols", "spawning", true),
|
||||
b("spawn_phantoms", "spawning", true),
|
||||
b("spawn_wandering_traders", "spawning", true),
|
||||
b("spawn_wardens", "spawning", true),
|
||||
b("spectators_generate_chunks", "player", true),
|
||||
b("spread_vines", "updates", true),
|
||||
b("tnt_explodes", "misc", true),
|
||||
b("tnt_explosion_drop_decay", "drops", false),
|
||||
b("universal_anger", "mobs", false),
|
||||
b("water_source_conversion", "updates", true),
|
||||
];
|
||||
pub fn rule(name: &str) -> Option<&'static Rule> {
|
||||
let name = name.strip_prefix("minecraft:").unwrap_or(name);
|
||||
RULES.iter().find(|r| r.name == name)
|
||||
}
|
||||
|
||||
/// Current values (defaults unless set).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct GameRules {
|
||||
values: BTreeMap<&'static str, Value>,
|
||||
}
|
||||
impl GameRules {
|
||||
pub fn get(&self, name: &str) -> Option<Value> {
|
||||
let r = rule(name)?;
|
||||
Some(self.values.get(r.name).copied().unwrap_or(r.default))
|
||||
}
|
||||
pub fn bool(&self, name: &str) -> bool {
|
||||
matches!(self.get(name), Some(Value::Bool(true)))
|
||||
}
|
||||
/// Parse a network rule value, retaining type and range validation.
|
||||
pub fn set_string(&mut self, name: &str, text: &str) -> bool {
|
||||
let value = match self.get(name) {
|
||||
Some(Value::Bool(_)) => text.parse::<bool>().ok().map(Value::Bool),
|
||||
Some(Value::Int(_)) => text.parse::<i32>().ok().map(Value::Int),
|
||||
None => None,
|
||||
};
|
||||
value.is_some_and(|v| self.set(name, v))
|
||||
}
|
||||
pub fn int(&self, name: &str) -> i32 {
|
||||
match self.get(name) {
|
||||
Some(Value::Int(v)) => v,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
/// Set a rule; false if the name or value type is wrong.
|
||||
pub fn set(&mut self, name: &str, value: Value) -> bool {
|
||||
let Some(r) = rule(name) else { return false };
|
||||
let ok = match (r.default, value) {
|
||||
(Value::Bool(_), Value::Bool(_)) => true,
|
||||
(Value::Int(_), Value::Int(v)) => (r.min..=r.max).contains(&v),
|
||||
_ => false,
|
||||
};
|
||||
if ok && value == r.default {
|
||||
self.values.remove(r.name);
|
||||
} else if ok {
|
||||
self.values.insert(r.name, value);
|
||||
}
|
||||
ok
|
||||
}
|
||||
/// Every rule's value by name without namespace, as `save::Level` holds
|
||||
/// them (booleans as 0 or 1).
|
||||
pub fn by_name(&self) -> BTreeMap<String, i32> {
|
||||
RULES
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let v = match self.values.get(r.name).copied().unwrap_or(r.default) {
|
||||
Value::Bool(b) => i32::from(b),
|
||||
Value::Int(i) => i,
|
||||
};
|
||||
(r.name.to_owned(), v)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
/// GameRuleMap codec: `{data: {"minecraft:<rule>": value...}, DataVersion}`.
|
||||
pub fn to_nbt(&self) -> NamedTag {
|
||||
let data: Vec<(horizon_world::nbt::JavaString, Tag)> = RULES
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let v = self.values.get(r.name).copied().unwrap_or(r.default);
|
||||
let tag = match v {
|
||||
Value::Bool(b) => Tag::Byte(i8::from(b)),
|
||||
Value::Int(i) => Tag::Int(i),
|
||||
};
|
||||
(
|
||||
horizon_world::nbt::JavaString::from(format!("minecraft:{}", r.name).as_str()),
|
||||
tag,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
NamedTag {
|
||||
name: "".into(),
|
||||
tag: Tag::compound([
|
||||
("data", Tag::compound(data)),
|
||||
("DataVersion", Tag::Int(DATA_VERSION)),
|
||||
]),
|
||||
}
|
||||
}
|
||||
pub fn from_nbt(root: &Tag) -> Self {
|
||||
let mut rules = Self::default();
|
||||
let Some(data) = root.get("data") else {
|
||||
return rules;
|
||||
};
|
||||
for r in RULES {
|
||||
let key = format!("minecraft:{}", r.name);
|
||||
let value = data.get(&key).or_else(|| data.get(r.name));
|
||||
match (r.default, value) {
|
||||
(Value::Bool(_), Some(Tag::Byte(v))) => {
|
||||
rules.set(r.name, Value::Bool(*v != 0));
|
||||
}
|
||||
(Value::Int(_), Some(Tag::Int(v))) => {
|
||||
rules.set(r.name, Value::Int(*v));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
rules
|
||||
}
|
||||
pub fn load(world: &Path) -> Self {
|
||||
let Ok(bytes) = fs::read(world.join("data/minecraft/game_rules.dat")) else {
|
||||
return Self::default();
|
||||
};
|
||||
let Ok(raw) = Compression::Gzip.decode(&bytes, 16 << 20) else {
|
||||
return Self::default();
|
||||
};
|
||||
match nbt::read_named(&raw, Limits::default()) {
|
||||
Ok((root, _)) => Self::from_nbt(&root.tag),
|
||||
Err(_) => Self::default(),
|
||||
}
|
||||
}
|
||||
pub fn save(&self, world: &Path) -> crate::Result<()> {
|
||||
let dir = world.join("data/minecraft");
|
||||
fs::create_dir_all(&dir)?;
|
||||
let bytes =
|
||||
nbt::write_named(&self.to_nbt(), Limits::default()).map_err(|e| e.to_string())?;
|
||||
fs::write(
|
||||
dir.join("game_rules.dat"),
|
||||
Compression::Gzip.encode(&bytes)?,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn network_values_validate_rule_names_types_and_bounds() {
|
||||
let mut rules = GameRules::default();
|
||||
assert!(rules.set_string("minecraft:keep_inventory", "true"));
|
||||
assert!(rules.bool("keep_inventory"));
|
||||
assert!(!rules.set_string("minecraft:keep_inventory", "1"));
|
||||
assert!(rules.bool("keep_inventory"));
|
||||
assert!(rules.set_string("minecraft:random_tick_speed", "7"));
|
||||
assert_eq!(rules.int("random_tick_speed"), 7);
|
||||
assert!(!rules.set_string("minecraft:random_tick_speed", "-1"));
|
||||
assert!(!rules.set_string("minecraft:random_tick_speed", "999999999999"));
|
||||
assert!(!rules.set_string("minecraft:unknown", "true"));
|
||||
assert!(!rules.set_string("other:keep_inventory", "false"));
|
||||
assert_eq!(rules.int("random_tick_speed"), 7);
|
||||
}
|
||||
#[test]
|
||||
fn defaults_bounds_and_round_trip() {
|
||||
let mut rules = GameRules::default();
|
||||
assert!(rules.bool("advance_time"));
|
||||
assert_eq!(rules.int("random_tick_speed"), 3);
|
||||
assert!(!rules.set("random_tick_speed", Value::Bool(true)));
|
||||
assert!(!rules.set("max_snow_accumulation_height", Value::Int(9)));
|
||||
assert!(rules.set("keep_inventory", Value::Bool(true)));
|
||||
assert!(rules.set("minecraft:random_tick_speed", Value::Int(10)));
|
||||
let back = GameRules::from_nbt(&rules.to_nbt().tag);
|
||||
assert_eq!(back, rules);
|
||||
assert!(back.bool("keep_inventory"));
|
||||
let dir = std::env::temp_dir().join(format!("horizon-gamerules-{}", std::process::id()));
|
||||
rules.save(&dir).unwrap();
|
||||
assert_eq!(GameRules::load(&dir), rules);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//! Resource identifiers (`Identifier`).
|
||||
|
||||
/// Identifier.parse: `ns:path` or `path`, validated.
|
||||
pub fn parse_identifier(raw: &str) -> Option<String> {
|
||||
let (ns, path) = match raw.split_once(':') {
|
||||
Some(("", path)) => ("minecraft", path),
|
||||
Some((ns, path)) => (ns, path),
|
||||
None => ("minecraft", raw),
|
||||
};
|
||||
let ns_ok = ns != ".."
|
||||
&& ns
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-'));
|
||||
let path_ok = path.chars().all(|c| {
|
||||
c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/')
|
||||
});
|
||||
(ns_ok && path_ok).then(|| format!("{ns}:{path}"))
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! Key display names (`InputConstants.Key.getDisplayName`), shared by key
|
||||
//! mappings and `keybind` text components.
|
||||
use crate::text::Text;
|
||||
|
||||
/// InputConstants.Key.getDisplayName: one-character keys as the upper-case
|
||||
/// character, others by translation.
|
||||
pub fn display_name(key: &str) -> Text {
|
||||
if let Some(rest) = key.strip_prefix("key.keyboard.")
|
||||
&& rest.chars().count() == 1
|
||||
{
|
||||
let c = rest.to_uppercase();
|
||||
return Text::literal(c);
|
||||
}
|
||||
let symbol = match key {
|
||||
"key.keyboard.minus" => Some("-"),
|
||||
"key.keyboard.equal" => Some("="),
|
||||
"key.keyboard.left.bracket" => Some("["),
|
||||
"key.keyboard.right.bracket" => Some("]"),
|
||||
"key.keyboard.backslash" => Some("\\"),
|
||||
"key.keyboard.semicolon" => Some(";"),
|
||||
"key.keyboard.apostrophe" => Some("'"),
|
||||
"key.keyboard.grave.accent" => Some("`"),
|
||||
"key.keyboard.comma" => Some(","),
|
||||
"key.keyboard.period" => Some("."),
|
||||
"key.keyboard.slash" => Some("/"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(s) = symbol {
|
||||
return Text::literal(s);
|
||||
}
|
||||
if let Some(n) = key.strip_prefix("key.mouse.")
|
||||
&& n.parse::<u32>().is_ok()
|
||||
&& !crate::lang::has(key)
|
||||
{
|
||||
return Text::translate("key.mouse", &[Text::literal(n)]);
|
||||
}
|
||||
Text::translate(key, &[])
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
//! Languages (ClientLanguage / LanguageManager): `lang/<code>.json` from the
|
||||
//! resource root and enabled packs layered over `en_us`, the language list
|
||||
//! from `pack.mcmeta` `language` sections, and a process-wide current
|
||||
//! language used by every screen.
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::{Arc, RwLock},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LanguageInfo {
|
||||
pub code: String,
|
||||
pub name: String,
|
||||
pub region: String,
|
||||
pub bidirectional: bool,
|
||||
}
|
||||
impl LanguageInfo {
|
||||
/// LanguageInfo.toComponent: "Name (Region)".
|
||||
pub fn label(&self) -> String {
|
||||
format!("{} ({})", self.name, self.region)
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct Language {
|
||||
pub code: String,
|
||||
map: HashMap<String, String>,
|
||||
}
|
||||
pub const DEFAULT: &str = "en_us";
|
||||
|
||||
static CURRENT: RwLock<Option<Arc<Language>>> = RwLock::new(None);
|
||||
|
||||
/// A source of resource files: the prepared root plus packs, highest priority last.
|
||||
pub trait ResourceSource {
|
||||
fn read(&self, path: &str) -> Option<Vec<u8>>;
|
||||
/// The namespaces under `assets/` (resource packs may add their own).
|
||||
fn namespaces(&self) -> Vec<String> {
|
||||
vec!["minecraft".into()]
|
||||
}
|
||||
}
|
||||
/// Horizon's own strings, compiled in so they need no prepared resources.
|
||||
struct Bundled;
|
||||
impl ResourceSource for Bundled {
|
||||
fn read(&self, path: &str) -> Option<Vec<u8>> {
|
||||
let body = match path {
|
||||
"assets/horizon/lang/en_us.json" => {
|
||||
include_str!("../../horizon-client/assets/horizon/lang/en_us.json")
|
||||
}
|
||||
"assets/horizon/lang/ru_ru.json" => {
|
||||
include_str!("../../horizon-client/assets/horizon/lang/ru_ru.json")
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(body.as_bytes().to_vec())
|
||||
}
|
||||
fn namespaces(&self) -> Vec<String> {
|
||||
vec!["horizon".into()]
|
||||
}
|
||||
}
|
||||
impl ResourceSource for std::path::PathBuf {
|
||||
fn read(&self, path: &str) -> Option<Vec<u8>> {
|
||||
std::fs::read(self.join(path)).ok()
|
||||
}
|
||||
fn namespaces(&self) -> Vec<String> {
|
||||
std::fs::read_dir(self.join("assets"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter(|e| e.path().is_dir())
|
||||
.filter_map(|e| e.file_name().to_str().map(str::to_owned))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// DeprecatedTranslationsInfo.applyToMap: drop removed keys, then move each
|
||||
/// renamed key's text to its new key (a missing old key removes the new one).
|
||||
pub fn apply_deprecated(map: &mut HashMap<String, String>, json: &[u8]) {
|
||||
let Ok(info) = serde_json::from_slice::<serde_json::Value>(json) else {
|
||||
return;
|
||||
};
|
||||
for key in info["removed"].as_array().into_iter().flatten() {
|
||||
if let Some(k) = key.as_str() {
|
||||
map.remove(k);
|
||||
}
|
||||
}
|
||||
for (from, to) in info["renamed"].as_object().into_iter().flatten() {
|
||||
let Some(to) = to.as_str() else { continue };
|
||||
match map.remove(from) {
|
||||
Some(value) => {
|
||||
map.insert(to.to_owned(), value);
|
||||
}
|
||||
None => {
|
||||
map.remove(to);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Language {
|
||||
/// ClientLanguage.loadFrom: en_us first, then the selected language, each
|
||||
/// from every namespace and every source in priority order (later sources
|
||||
/// override).
|
||||
pub fn load(sources: &[&dyn ResourceSource], code: &str) -> Self {
|
||||
let mut map = HashMap::new();
|
||||
let mut codes = vec![DEFAULT];
|
||||
if code != DEFAULT {
|
||||
codes.push(code);
|
||||
}
|
||||
// Horizon's own strings first, so a pack or the prepared root can still
|
||||
// override them. Vanilla has no key for "Controller vibration".
|
||||
let bundled = Bundled;
|
||||
let mut all: Vec<&dyn ResourceSource> = vec![&bundled];
|
||||
all.extend_from_slice(sources);
|
||||
let sources = all.as_slice();
|
||||
let namespaces: std::collections::BTreeSet<String> =
|
||||
sources.iter().flat_map(|s| s.namespaces()).collect();
|
||||
for c in codes {
|
||||
for namespace in &namespaces {
|
||||
for source in sources {
|
||||
let Some(bytes) = source.read(&format!("assets/{namespace}/lang/{c}.json"))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let Ok(entries) = serde_json::from_slice::<HashMap<String, String>>(&bytes) {
|
||||
map.extend(entries);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// DeprecatedTranslationsInfo.loadFromDefaultResource().applyToMap: the
|
||||
// game's own deprecated.json, not a resource pack's.
|
||||
if let Some(bytes) = sources
|
||||
.iter()
|
||||
.find_map(|s| s.read("assets/minecraft/lang/deprecated.json"))
|
||||
{
|
||||
apply_deprecated(&mut map, &bytes);
|
||||
}
|
||||
Self {
|
||||
code: code.to_owned(),
|
||||
map,
|
||||
}
|
||||
}
|
||||
pub fn get(&self, key: &str) -> Option<&str> {
|
||||
self.map.get(key).map(String::as_str)
|
||||
}
|
||||
/// The resolved map, for `horizon_protocol::text::plain`: a server's
|
||||
/// components carry keys, and the network layer resolves them with this.
|
||||
pub fn map(&self) -> &HashMap<String, String> {
|
||||
&self.map
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.map.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Languages declared by `pack.mcmeta` files (the vanilla asset root first).
|
||||
pub fn available(sources: &[&dyn ResourceSource]) -> Vec<LanguageInfo> {
|
||||
let mut found: BTreeMap<String, LanguageInfo> = BTreeMap::new();
|
||||
found.insert(
|
||||
DEFAULT.into(),
|
||||
LanguageInfo {
|
||||
code: DEFAULT.into(),
|
||||
name: "English".into(),
|
||||
region: "US".into(),
|
||||
bidirectional: false,
|
||||
},
|
||||
);
|
||||
for source in sources {
|
||||
for path in ["assets/pack.mcmeta", "pack.mcmeta"] {
|
||||
let Some(bytes) = source.read(path) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
|
||||
continue;
|
||||
};
|
||||
for (code, info) in value["language"].as_object().into_iter().flatten() {
|
||||
// Only languages whose file exists somewhere are selectable.
|
||||
let file = format!("assets/minecraft/lang/{code}.json");
|
||||
if code != DEFAULT && !sources.iter().any(|s| s.read(&file).is_some()) {
|
||||
continue;
|
||||
}
|
||||
found.insert(
|
||||
code.clone(),
|
||||
LanguageInfo {
|
||||
code: code.clone(),
|
||||
name: info["name"].as_str().unwrap_or(code).to_owned(),
|
||||
region: info["region"].as_str().unwrap_or("").to_owned(),
|
||||
bidirectional: info["bidirectional"].as_bool().unwrap_or(false),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
found.into_values().collect()
|
||||
}
|
||||
|
||||
pub fn set(language: Language) {
|
||||
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(language));
|
||||
}
|
||||
pub fn current() -> Option<Arc<Language>> {
|
||||
CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone()
|
||||
}
|
||||
pub fn code() -> String {
|
||||
current().map_or_else(|| DEFAULT.to_owned(), |l| l.code.clone())
|
||||
}
|
||||
/// Language.getOrDefault: the translation, or the key itself.
|
||||
pub fn get(key: &str) -> String {
|
||||
current()
|
||||
.and_then(|l| l.get(key).map(str::to_owned))
|
||||
.unwrap_or_else(|| key.to_owned())
|
||||
}
|
||||
/// The translation, or `fallback` when the key is missing.
|
||||
pub fn get_or(key: &str, fallback: &str) -> String {
|
||||
current()
|
||||
.and_then(|l| l.get(key).map(str::to_owned))
|
||||
.unwrap_or_else(|| fallback.to_owned())
|
||||
}
|
||||
pub fn has(key: &str) -> bool {
|
||||
current().is_some_and(|l| l.get(key).is_some())
|
||||
}
|
||||
/// I18n.get with plain string arguments.
|
||||
pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> String {
|
||||
crate::text::Text::tr(key, args).plain()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
struct Mem(HashMap<String, Vec<u8>>);
|
||||
impl ResourceSource for Mem {
|
||||
fn read(&self, path: &str) -> Option<Vec<u8>> {
|
||||
self.0.get(path).cloned()
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn bundled_horizon_strings_follow_the_language() {
|
||||
// No prepared resources at all: the namespace is compiled in.
|
||||
let empty = Mem(HashMap::new());
|
||||
let en = Language::load(&[&empty], "en_us");
|
||||
assert_eq!(en.get("horizon.options.controller"), Some("Controller"));
|
||||
let ru = Language::load(&[&empty], "ru_ru");
|
||||
assert_eq!(ru.get("horizon.options.controller"), Some("Геймпад"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_selected_language_over_english() {
|
||||
let base = Mem(HashMap::from([
|
||||
("assets/minecraft/lang/en_us.json".into(), br#"{"a":"Apple","b":"Banana"}"#.to_vec()),
|
||||
("assets/minecraft/lang/fr_fr.json".into(), br#"{"a":"Pomme"}"#.to_vec()),
|
||||
("assets/pack.mcmeta".into(), r#"{"language":{"fr_fr":{"name":"Français","region":"France"},"de_de":{"name":"Deutsch","region":"Deutschland"}}}"#.as_bytes().to_vec()),
|
||||
]));
|
||||
let pack = Mem(HashMap::from([(
|
||||
"assets/minecraft/lang/fr_fr.json".into(),
|
||||
br#"{"b":"Banane"}"#.to_vec(),
|
||||
)]));
|
||||
let sources: [&dyn ResourceSource; 2] = [&base, &pack];
|
||||
let fr = Language::load(&sources, "fr_fr");
|
||||
assert_eq!(fr.get("a"), Some("Pomme"));
|
||||
assert_eq!(fr.get("b"), Some("Banane"));
|
||||
let langs = available(&sources);
|
||||
// de_de has no file, so only English and French are offered.
|
||||
assert_eq!(
|
||||
langs.iter().map(|l| l.code.as_str()).collect::<Vec<_>>(),
|
||||
["en_us", "fr_fr"]
|
||||
);
|
||||
assert_eq!(langs[1].label(), "Français (France)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! The client's lowest layer, below commands and gameplay: chat text and
|
||||
//! translations, SNBT and NBT paths, text components, the scoreboard, boss
|
||||
//! bars, game rules, block entity NBT tables, and the registry, particle and
|
||||
//! sound source tables commands name. horizon-client re-exports each module
|
||||
//! under its old path (`horizon_client::text`, ...).
|
||||
#![forbid(unsafe_code)]
|
||||
pub mod block_entity_nbt;
|
||||
pub mod bossbar;
|
||||
pub mod component;
|
||||
pub mod fastutil_order;
|
||||
pub mod gamerules;
|
||||
pub mod identifier;
|
||||
pub mod key_display;
|
||||
pub mod lang;
|
||||
pub mod nbt_path;
|
||||
pub mod particle_type;
|
||||
pub mod registries;
|
||||
pub mod scoreboard;
|
||||
pub mod snbt;
|
||||
pub mod sound_source;
|
||||
pub mod text;
|
||||
pub mod uuid;
|
||||
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
@@ -0,0 +1,901 @@
|
||||
//! NBT paths (`NbtPathArgument`): `foo.bar[0]`, `[]`, `list[{id:1}]`,
|
||||
//! `{root:match}`, with get, set, insert and remove on a tag tree, and the
|
||||
//! partial NBT comparison (`NbtUtils.compareNbt`) selectors and conditions use.
|
||||
use horizon_world::nbt::{Compound, JavaString, Tag, parse_snbt};
|
||||
|
||||
/// An error carrying the translation key and its arguments.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PathError {
|
||||
pub key: &'static str,
|
||||
pub args: Vec<String>,
|
||||
/// Byte offset in the path text (parse errors).
|
||||
pub cursor: usize,
|
||||
}
|
||||
impl PathError {
|
||||
fn new(key: &'static str, args: Vec<String>, cursor: usize) -> Self {
|
||||
Self { key, args, cursor }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Node {
|
||||
/// `name`
|
||||
Child(String),
|
||||
/// `name{pattern}`
|
||||
MatchChild(String, Tag),
|
||||
/// `[]`
|
||||
AllElements,
|
||||
/// `[n]`
|
||||
Index(i32),
|
||||
/// `[{pattern}]`
|
||||
MatchElement(Tag),
|
||||
/// `{pattern}` at the start.
|
||||
MatchRoot(Tag),
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct NbtPath {
|
||||
original: String,
|
||||
nodes: Vec<Node>,
|
||||
/// Byte offset just after each node in `original`.
|
||||
ends: Vec<usize>,
|
||||
}
|
||||
|
||||
fn key(s: &str) -> JavaString {
|
||||
JavaString::from(s)
|
||||
}
|
||||
fn get_child<'a>(c: &'a Compound, name: &str) -> Option<&'a Tag> {
|
||||
c.get(&key(name))
|
||||
}
|
||||
|
||||
/// `NbtUtils.compareNbt(expected, actual, true)`.
|
||||
pub fn compare_nbt(expected: &Tag, actual: Option<&Tag>) -> bool {
|
||||
let Some(actual) = actual else { return false };
|
||||
if std::mem::discriminant(expected) != std::mem::discriminant(actual) {
|
||||
return false;
|
||||
}
|
||||
match (expected, actual) {
|
||||
(Tag::Compound(e), Tag::Compound(a)) => {
|
||||
a.len() >= e.len() && e.iter().all(|(k, v)| compare_nbt(v, a.get(k)))
|
||||
}
|
||||
(Tag::List(e), Tag::List(a)) => {
|
||||
if e.is_empty() {
|
||||
return a.is_empty();
|
||||
}
|
||||
a.len() >= e.len() && e.iter().all(|x| a.iter().any(|y| compare_nbt(x, Some(y))))
|
||||
}
|
||||
_ => expected == actual,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- list-like tags ----------------------------------------------------------
|
||||
|
||||
/// The elements of a list or array tag.
|
||||
fn elements(tag: &Tag) -> Option<Vec<Tag>> {
|
||||
Some(match tag {
|
||||
Tag::List(l) => l.clone(),
|
||||
Tag::ByteArray(a) => a.iter().map(|b| Tag::Byte(*b as i8)).collect(),
|
||||
Tag::IntArray(a) => a.iter().map(|v| Tag::Int(*v)).collect(),
|
||||
Tag::LongArray(a) => a.iter().map(|v| Tag::Long(*v)).collect(),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
fn number(t: &Tag) -> Option<i64> {
|
||||
match t {
|
||||
Tag::Byte(v) => Some(i64::from(*v)),
|
||||
Tag::Short(v) => Some(i64::from(*v)),
|
||||
Tag::Int(v) => Some(i64::from(*v)),
|
||||
Tag::Long(v) => Some(*v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Run `f` over the elements of a list/array, writing array results back.
|
||||
/// None when `tag` is not list-like.
|
||||
fn with_elements<R>(tag: &mut Tag, f: impl FnOnce(&mut Vec<Tag>) -> R) -> Option<R> {
|
||||
match tag {
|
||||
Tag::List(l) => Some(f(l)),
|
||||
Tag::ByteArray(_) | Tag::IntArray(_) | Tag::LongArray(_) => {
|
||||
let mut v = elements(tag)?;
|
||||
let r = f(&mut v);
|
||||
let nums: Vec<i64> = v.iter().filter_map(number).collect();
|
||||
match tag {
|
||||
Tag::ByteArray(a) => *a = nums.iter().map(|n| *n as u8).collect(),
|
||||
Tag::IntArray(a) => *a = nums.iter().map(|n| *n as i32).collect(),
|
||||
Tag::LongArray(a) => *a = nums,
|
||||
_ => {}
|
||||
}
|
||||
Some(r)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl NbtPath {
|
||||
/// `NbtPathArgument.parse` from the start of `text`; returns the path and
|
||||
/// the bytes consumed (it stops at a space).
|
||||
pub fn parse_prefix(text: &str) -> Result<(NbtPath, usize), PathError> {
|
||||
let b = text.as_bytes();
|
||||
let mut i = 0;
|
||||
let mut nodes = Vec::new();
|
||||
let mut ends = Vec::new();
|
||||
let mut first = true;
|
||||
while i < b.len() && b[i] != b' ' {
|
||||
let (node, next) = parse_node(text, i, first)?;
|
||||
nodes.push(node);
|
||||
i = next;
|
||||
ends.push(i);
|
||||
first = false;
|
||||
if i < b.len() && !matches!(b[i], b' ' | b'[' | b'{') {
|
||||
if b[i] != b'.' {
|
||||
return Err(PathError::new("parsing.expected", vec![".".into()], i));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
Ok((
|
||||
NbtPath {
|
||||
original: text[..i].to_owned(),
|
||||
nodes,
|
||||
ends,
|
||||
},
|
||||
i,
|
||||
))
|
||||
}
|
||||
pub fn parse(text: &str) -> Result<NbtPath, PathError> {
|
||||
let (p, used) = Self::parse_prefix(text)?;
|
||||
if used != text.len() {
|
||||
return Err(PathError::new(
|
||||
"arguments.nbtpath.node.invalid",
|
||||
vec![],
|
||||
used,
|
||||
));
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.original
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty()
|
||||
}
|
||||
fn not_found(&self, node: usize) -> PathError {
|
||||
let end = self.ends[node];
|
||||
PathError::new(
|
||||
"arguments.nbtpath.nothing_found",
|
||||
vec![self.original[..end.min(self.original.len())].to_owned()],
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
// ---- reading --------------------------------------------------------
|
||||
|
||||
fn step<'a>(node: &Node, parent: &'a Tag, out: &mut Vec<&'a Tag>) {
|
||||
match node {
|
||||
Node::Child(name) => {
|
||||
if let Tag::Compound(c) = parent
|
||||
&& let Some(t) = get_child(c, name)
|
||||
{
|
||||
out.push(t);
|
||||
}
|
||||
}
|
||||
Node::MatchChild(name, pattern) => {
|
||||
if let Tag::Compound(c) = parent
|
||||
&& let Some(t) = get_child(c, name)
|
||||
&& compare_nbt(pattern, Some(t))
|
||||
{
|
||||
out.push(t);
|
||||
}
|
||||
}
|
||||
Node::AllElements => {
|
||||
if let Tag::List(l) = parent {
|
||||
out.extend(l.iter());
|
||||
}
|
||||
}
|
||||
Node::Index(i) => {
|
||||
if let Tag::List(l) = parent {
|
||||
let n = l.len() as i64;
|
||||
let idx = if *i < 0 {
|
||||
n + i64::from(*i)
|
||||
} else {
|
||||
i64::from(*i)
|
||||
};
|
||||
if (0..n).contains(&idx) {
|
||||
out.push(&l[idx as usize]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::MatchElement(pattern) => {
|
||||
if let Tag::List(l) = parent {
|
||||
out.extend(l.iter().filter(|t| compare_nbt(pattern, Some(t))));
|
||||
}
|
||||
}
|
||||
Node::MatchRoot(pattern) => {
|
||||
if matches!(parent, Tag::Compound(_)) && compare_nbt(pattern, Some(parent)) {
|
||||
out.push(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Array tags read as lists of their elements.
|
||||
fn read_steps(&self, root: &Tag) -> Result<Vec<Tag>, PathError> {
|
||||
let mut current: Vec<Tag> = vec![root.clone()];
|
||||
for (i, node) in self.nodes.iter().enumerate() {
|
||||
let mut next = Vec::new();
|
||||
for parent in ¤t {
|
||||
// Arrays expose their elements to element nodes.
|
||||
let list;
|
||||
let p = if matches!(node, Node::AllElements | Node::Index(_)) {
|
||||
match elements(parent) {
|
||||
Some(l) if !matches!(parent, Tag::List(_)) => {
|
||||
list = Tag::List(l);
|
||||
&list
|
||||
}
|
||||
_ => parent,
|
||||
}
|
||||
} else {
|
||||
parent
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
Self::step(node, p, &mut out);
|
||||
next.extend(out.into_iter().cloned());
|
||||
}
|
||||
if next.is_empty() {
|
||||
return Err(self.not_found(i));
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
Ok(current)
|
||||
}
|
||||
/// `get`: every matching tag (an error when nothing matches).
|
||||
pub fn get(&self, root: &Tag) -> Result<Vec<Tag>, PathError> {
|
||||
self.read_steps(root)
|
||||
}
|
||||
/// `countMatching`.
|
||||
pub fn count(&self, root: &Tag) -> usize {
|
||||
self.read_steps(root).map_or(0, |v| v.len())
|
||||
}
|
||||
|
||||
// ---- writing --------------------------------------------------------
|
||||
|
||||
/// The parents of the last node, creating the missing ones (`getOrCreateParents`).
|
||||
fn visit_parents(
|
||||
&self,
|
||||
root: &mut Tag,
|
||||
create: bool,
|
||||
f: &mut dyn FnMut(&mut Tag),
|
||||
) -> Result<(), PathError> {
|
||||
self.descend(0, self.nodes.len().saturating_sub(1), root, create, None, f)
|
||||
}
|
||||
/// Walk `nodes[from..to]` from `tag`, calling `f` on every tag reached.
|
||||
fn descend(
|
||||
&self,
|
||||
from: usize,
|
||||
to: usize,
|
||||
tag: &mut Tag,
|
||||
create: bool,
|
||||
last_value: Option<&dyn Fn() -> Tag>,
|
||||
f: &mut dyn FnMut(&mut Tag),
|
||||
) -> Result<(), PathError> {
|
||||
if from >= to {
|
||||
f(tag);
|
||||
return Ok(());
|
||||
}
|
||||
let node = &self.nodes[from];
|
||||
// What a created child should be: the next node's preferred parent,
|
||||
// or the caller's value for the last node.
|
||||
let default_child = || -> Tag {
|
||||
match (self.nodes.get(from + 1), last_value) {
|
||||
(Some(next), _) if from + 1 < to => preferred_parent(next),
|
||||
(_, Some(v)) => v(),
|
||||
(Some(next), None) => preferred_parent(next),
|
||||
_ => Tag::Compound(Compound::new()),
|
||||
}
|
||||
};
|
||||
let mut found = false;
|
||||
let mut error = None;
|
||||
let mut visit = |child: &mut Tag| {
|
||||
found = true;
|
||||
if error.is_none()
|
||||
&& let Err(e) = self.descend(from + 1, to, child, create, last_value, f)
|
||||
{
|
||||
error = Some(e);
|
||||
}
|
||||
};
|
||||
step_mut(
|
||||
node,
|
||||
tag,
|
||||
create.then_some(&default_child as &dyn Fn() -> Tag),
|
||||
&mut visit,
|
||||
);
|
||||
if let Some(e) = error {
|
||||
return Err(e);
|
||||
}
|
||||
if !found {
|
||||
return Err(self.not_found(from));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `getOrCreate`: the tags at the path, creating missing ones as
|
||||
/// `new_value` (used for the last node).
|
||||
pub fn get_or_create(
|
||||
&self,
|
||||
root: &mut Tag,
|
||||
new_value: &dyn Fn() -> Tag,
|
||||
f: &mut dyn FnMut(&mut Tag),
|
||||
) -> Result<(), PathError> {
|
||||
self.descend(0, self.nodes.len(), root, true, Some(new_value), f)
|
||||
}
|
||||
/// `set`: returns how many tags changed.
|
||||
pub fn set(&self, root: &mut Tag, value: &Tag) -> Result<usize, PathError> {
|
||||
if too_deep(value, self.nodes.len()) {
|
||||
return Err(PathError::new("arguments.nbtpath.too_deep", vec![], 0));
|
||||
}
|
||||
let Some(last) = self.nodes.last() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let mut changed = 0;
|
||||
self.visit_parents(root, true, &mut |parent| {
|
||||
changed += set_tag(last, parent, value);
|
||||
})?;
|
||||
Ok(changed)
|
||||
}
|
||||
/// `remove`: returns how many tags were removed.
|
||||
pub fn remove(&self, root: &mut Tag) -> usize {
|
||||
let Some(last) = self.nodes.last() else {
|
||||
return 0;
|
||||
};
|
||||
let mut removed = 0;
|
||||
let _ = self.visit_parents(root, false, &mut |parent| {
|
||||
removed += remove_tag(last, parent);
|
||||
});
|
||||
removed
|
||||
}
|
||||
/// `insert` (also append and prepend): into every list the path reaches.
|
||||
pub fn insert(
|
||||
&self,
|
||||
index: i32,
|
||||
root: &mut Tag,
|
||||
values: &[Tag],
|
||||
) -> Result<usize, CollectionError> {
|
||||
for v in values {
|
||||
if too_deep(v, self.nodes.len()) {
|
||||
return Err(CollectionError::Path(PathError::new(
|
||||
"arguments.nbtpath.too_deep",
|
||||
vec![],
|
||||
0,
|
||||
)));
|
||||
}
|
||||
}
|
||||
let mut modified = 0;
|
||||
let mut error: Option<CollectionError> = None;
|
||||
self.get_or_create(root, &|| Tag::List(Vec::new()), &mut |target| {
|
||||
if error.is_some() {
|
||||
return;
|
||||
}
|
||||
let shown = crate::snbt::to_snbt(target);
|
||||
let result = with_elements(target, |list| {
|
||||
let start = if index < 0 {
|
||||
list.len() as i64 + i64::from(index) + 1
|
||||
} else {
|
||||
i64::from(index)
|
||||
};
|
||||
let mut any = false;
|
||||
for (n, v) in values.iter().enumerate() {
|
||||
let at = start + n as i64;
|
||||
if at < 0 || at as usize > list.len() {
|
||||
return Err(CollectionError::InvalidIndex(at as i32));
|
||||
}
|
||||
list.insert(at as usize, v.clone());
|
||||
any = true;
|
||||
}
|
||||
Ok(any)
|
||||
});
|
||||
match result {
|
||||
None => error = Some(CollectionError::ExpectedList(shown)),
|
||||
Some(Err(e)) => error = Some(e),
|
||||
Some(Ok(any)) => modified += usize::from(any),
|
||||
}
|
||||
})
|
||||
.map_err(CollectionError::Path)?;
|
||||
match error {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(modified),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum CollectionError {
|
||||
Path(PathError),
|
||||
/// `commands.data.modify.expected_list` with the offending tag.
|
||||
ExpectedList(String),
|
||||
/// `commands.data.modify.invalid_index`.
|
||||
InvalidIndex(i32),
|
||||
}
|
||||
|
||||
/// `isTooDeep`.
|
||||
pub fn too_deep(tag: &Tag, depth: usize) -> bool {
|
||||
if depth >= 512 {
|
||||
return true;
|
||||
}
|
||||
match tag {
|
||||
Tag::Compound(c) => c.values().any(|t| too_deep(t, depth + 1)),
|
||||
Tag::List(l) => l.iter().any(|t| too_deep(t, depth + 1)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn preferred_parent(node: &Node) -> Tag {
|
||||
match node {
|
||||
Node::AllElements | Node::Index(_) | Node::MatchElement(_) => Tag::List(Vec::new()),
|
||||
_ => Tag::Compound(Compound::new()),
|
||||
}
|
||||
}
|
||||
/// `getOrCreateTag` (or `getTag` without `create`): the children of `parent`.
|
||||
fn step_mut(
|
||||
node: &Node,
|
||||
parent: &mut Tag,
|
||||
create: Option<&dyn Fn() -> Tag>,
|
||||
out: &mut dyn FnMut(&mut Tag),
|
||||
) {
|
||||
match node {
|
||||
Node::Child(name) => {
|
||||
if let Tag::Compound(c) = parent {
|
||||
let k = key(name);
|
||||
if !c.contains_key(&k) {
|
||||
let Some(make) = create else { return };
|
||||
c.insert(k.clone(), make());
|
||||
}
|
||||
if let Some(t) = c.get_mut(&k) {
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::MatchChild(name, pattern) => {
|
||||
if let Tag::Compound(c) = parent {
|
||||
let k = key(name);
|
||||
if !c.contains_key(&k) {
|
||||
if create.is_none() {
|
||||
return;
|
||||
}
|
||||
c.insert(k.clone(), pattern.clone());
|
||||
if let Some(t) = c.get_mut(&k) {
|
||||
out(t);
|
||||
}
|
||||
} else if let Some(t) = c.get_mut(&k)
|
||||
&& compare_nbt(pattern, Some(t))
|
||||
{
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::AllElements => {
|
||||
let make = create;
|
||||
let _ = with_elements(parent, |list| {
|
||||
if list.is_empty() {
|
||||
if let Some(make) = make {
|
||||
list.push(make());
|
||||
out(&mut list[0]);
|
||||
}
|
||||
} else {
|
||||
for t in list.iter_mut() {
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Node::Index(i) => {
|
||||
let _ = with_elements(parent, |list| {
|
||||
let n = list.len() as i64;
|
||||
let idx = if *i < 0 {
|
||||
n + i64::from(*i)
|
||||
} else {
|
||||
i64::from(*i)
|
||||
};
|
||||
if (0..n).contains(&idx) {
|
||||
out(&mut list[idx as usize]);
|
||||
}
|
||||
});
|
||||
}
|
||||
Node::MatchElement(pattern) => {
|
||||
if let Tag::List(list) = parent {
|
||||
let mut any = false;
|
||||
for t in list.iter_mut() {
|
||||
if compare_nbt(pattern, Some(t)) {
|
||||
any = true;
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
if !any && create.is_some() {
|
||||
list.push(pattern.clone());
|
||||
if let Some(t) = list.last_mut() {
|
||||
out(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Node::MatchRoot(pattern) => {
|
||||
if matches!(parent, Tag::Compound(_)) && compare_nbt(pattern, Some(parent)) {
|
||||
out(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Node.setTag`: replace the child(ren) of `parent` with `value`.
|
||||
fn set_tag(node: &Node, parent: &mut Tag, value: &Tag) -> usize {
|
||||
match node {
|
||||
Node::Child(name) => {
|
||||
if let Tag::Compound(c) = parent {
|
||||
let prev = c.insert(key(name), value.clone());
|
||||
return usize::from(prev.as_ref() != Some(value));
|
||||
}
|
||||
0
|
||||
}
|
||||
Node::MatchChild(name, pattern) => {
|
||||
if let Tag::Compound(c) = parent {
|
||||
let k = key(name);
|
||||
if compare_nbt(pattern, c.get(&k)) && c.get(&k) != Some(value) {
|
||||
c.insert(k, value.clone());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
Node::AllElements => with_elements(parent, |list| {
|
||||
if list.is_empty() {
|
||||
list.push(value.clone());
|
||||
return 1;
|
||||
}
|
||||
let changed = list.iter().filter(|t| *t != value).count();
|
||||
if changed == 0 {
|
||||
return 0;
|
||||
}
|
||||
for t in list.iter_mut() {
|
||||
*t = value.clone();
|
||||
}
|
||||
changed
|
||||
})
|
||||
.unwrap_or(0),
|
||||
Node::Index(i) => with_elements(parent, |list| {
|
||||
let n = list.len() as i64;
|
||||
let idx = if *i < 0 {
|
||||
n + i64::from(*i)
|
||||
} else {
|
||||
i64::from(*i)
|
||||
};
|
||||
if (0..n).contains(&idx) && list[idx as usize] != *value {
|
||||
list[idx as usize] = value.clone();
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
})
|
||||
.unwrap_or(0),
|
||||
Node::MatchElement(pattern) => {
|
||||
let Tag::List(list) = parent else { return 0 };
|
||||
if list.is_empty() {
|
||||
list.push(value.clone());
|
||||
return 1;
|
||||
}
|
||||
let mut changed = 0;
|
||||
for t in list.iter_mut() {
|
||||
if compare_nbt(pattern, Some(t)) && t != value {
|
||||
*t = value.clone();
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
Node::MatchRoot(_) => 0,
|
||||
}
|
||||
}
|
||||
fn remove_tag(node: &Node, parent: &mut Tag) -> usize {
|
||||
match node {
|
||||
Node::Child(name) => match parent {
|
||||
Tag::Compound(c) => usize::from(c.remove(&key(name)).is_some()),
|
||||
_ => 0,
|
||||
},
|
||||
Node::MatchChild(name, pattern) => match parent {
|
||||
Tag::Compound(c) => {
|
||||
let k = key(name);
|
||||
if compare_nbt(pattern, c.get(&k)) {
|
||||
usize::from(c.remove(&k).is_some())
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
_ => 0,
|
||||
},
|
||||
Node::AllElements => with_elements(parent, |l| {
|
||||
let n = l.len();
|
||||
l.clear();
|
||||
n
|
||||
})
|
||||
.unwrap_or(0),
|
||||
Node::Index(i) => with_elements(parent, |l| {
|
||||
let n = l.len() as i64;
|
||||
let idx = if *i < 0 {
|
||||
n + i64::from(*i)
|
||||
} else {
|
||||
i64::from(*i)
|
||||
};
|
||||
if (0..n).contains(&idx) {
|
||||
l.remove(idx as usize);
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
})
|
||||
.unwrap_or(0),
|
||||
Node::MatchElement(pattern) => match parent {
|
||||
Tag::List(l) => {
|
||||
let before = l.len();
|
||||
l.retain(|t| !compare_nbt(pattern, Some(t)));
|
||||
before - l.len()
|
||||
}
|
||||
_ => 0,
|
||||
},
|
||||
Node::MatchRoot(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- parsing -------------------------------------------------------------------
|
||||
|
||||
fn parse_node(text: &str, i: usize, first: bool) -> Result<(Node, usize), PathError> {
|
||||
let b = text.as_bytes();
|
||||
let invalid = |at: usize| PathError::new("arguments.nbtpath.node.invalid", vec![], at);
|
||||
match b[i] {
|
||||
b'"' | b'\'' => {
|
||||
let (name, next) = read_quoted(text, i)?;
|
||||
read_object_node(text, name, next)
|
||||
}
|
||||
b'[' => {
|
||||
let mut j = i + 1;
|
||||
match b.get(j) {
|
||||
Some(b'{') => {
|
||||
let (pattern, next) = parse_compound(text, j)?;
|
||||
j = next;
|
||||
expect(text, j, b']')?;
|
||||
Ok((Node::MatchElement(pattern), j + 1))
|
||||
}
|
||||
Some(b']') => Ok((Node::AllElements, j + 1)),
|
||||
_ => {
|
||||
let start = j;
|
||||
if b.get(j) == Some(&b'-') {
|
||||
j += 1;
|
||||
}
|
||||
while b.get(j).is_some_and(u8::is_ascii_digit) {
|
||||
j += 1;
|
||||
}
|
||||
let n: i32 = text[start..j].parse().map_err(|_| {
|
||||
PathError::new(
|
||||
"parsing.int.invalid",
|
||||
vec![text[start..j].to_owned()],
|
||||
start,
|
||||
)
|
||||
})?;
|
||||
expect(text, j, b']')?;
|
||||
Ok((Node::Index(n), j + 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
b'{' => {
|
||||
if !first {
|
||||
return Err(invalid(i));
|
||||
}
|
||||
let (pattern, next) = parse_compound(text, i)?;
|
||||
Ok((Node::MatchRoot(pattern), next))
|
||||
}
|
||||
_ => {
|
||||
let mut j = i;
|
||||
while j < b.len()
|
||||
&& !matches!(b[j], b' ' | b'"' | b'\'' | b'[' | b']' | b'.' | b'{' | b'}')
|
||||
{
|
||||
j += 1;
|
||||
}
|
||||
if j == i {
|
||||
return Err(invalid(i));
|
||||
}
|
||||
read_object_node(text, text[i..j].to_owned(), j)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn read_object_node(text: &str, name: String, i: usize) -> Result<(Node, usize), PathError> {
|
||||
if name.is_empty() {
|
||||
return Err(PathError::new("arguments.nbtpath.node.invalid", vec![], i));
|
||||
}
|
||||
if text.as_bytes().get(i) == Some(&b'{') {
|
||||
let (pattern, next) = parse_compound(text, i)?;
|
||||
return Ok((Node::MatchChild(name, pattern), next));
|
||||
}
|
||||
Ok((Node::Child(name), i))
|
||||
}
|
||||
fn expect(text: &str, i: usize, c: u8) -> Result<(), PathError> {
|
||||
if text.as_bytes().get(i) == Some(&c) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(PathError::new(
|
||||
"parsing.expected",
|
||||
vec![(c as char).to_string()],
|
||||
i,
|
||||
))
|
||||
}
|
||||
}
|
||||
fn read_quoted(text: &str, i: usize) -> Result<(String, usize), PathError> {
|
||||
let quote = text.as_bytes()[i] as char;
|
||||
let mut out = String::new();
|
||||
let mut escaped = false;
|
||||
for (o, c) in text[i + 1..].char_indices() {
|
||||
if escaped {
|
||||
out.push(c);
|
||||
escaped = false;
|
||||
} else if c == '\\' {
|
||||
escaped = true;
|
||||
} else if c == quote {
|
||||
return Ok((out, i + 1 + o + c.len_utf8()));
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
Err(PathError::new(
|
||||
"parsing.quote.expected.end",
|
||||
vec![],
|
||||
text.len(),
|
||||
))
|
||||
}
|
||||
fn parse_compound(text: &str, i: usize) -> Result<(Tag, usize), PathError> {
|
||||
// Find the balanced end of the braces, then parse the SNBT inside.
|
||||
let b = text.as_bytes();
|
||||
let mut depth = 0;
|
||||
let mut quote: Option<u8> = None;
|
||||
let mut j = i;
|
||||
while j < b.len() {
|
||||
let c = b[j];
|
||||
match quote {
|
||||
Some(_) if c == b'\\' => j += 1,
|
||||
Some(q) if c == q => quote = None,
|
||||
Some(_) => {}
|
||||
None if c == b'"' || c == b'\'' => quote = Some(c),
|
||||
None if c == b'{' || c == b'[' => depth += 1,
|
||||
None if c == b'}' || c == b']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
let (tag, _) = parse_snbt(&text[i..=j])
|
||||
.map_err(|e| PathError::new("argument.nbt.invalid", vec![e], i))?;
|
||||
return Ok((tag, j + 1));
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
Err(PathError::new("argument.nbt.expected.compound", vec![], i))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tag(s: &str) -> Tag {
|
||||
parse_snbt(s).unwrap().0
|
||||
}
|
||||
fn path(s: &str) -> NbtPath {
|
||||
NbtPath::parse(s).unwrap_or_else(|e| panic!("{s}: {e:?}"))
|
||||
}
|
||||
fn show(v: &[Tag]) -> Vec<String> {
|
||||
v.iter().map(crate::snbt::to_snbt).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_follows_the_path() {
|
||||
let root = tag("{a:{b:[{id:1,n:\"x\"},{id:2,n:\"y\"},{id:3}]},c:5,\"d e\":7}");
|
||||
assert_eq!(show(&path("c").get(&root).unwrap()), ["5"]);
|
||||
assert_eq!(show(&path("\"d e\"").get(&root).unwrap()), ["7"]);
|
||||
assert_eq!(show(&path("a.b[0].n").get(&root).unwrap()), ["\"x\""]);
|
||||
assert_eq!(show(&path("a.b[-1]").get(&root).unwrap()), ["{id:3}"]);
|
||||
assert_eq!(show(&path("a.b[].id").get(&root).unwrap()), ["1", "2", "3"]);
|
||||
assert_eq!(show(&path("a.b[{id:2}].n").get(&root).unwrap()), ["\"y\""]);
|
||||
assert_eq!(
|
||||
show(&path("a{b:[{id:1}]}.b[0].id").get(&root).unwrap()),
|
||||
["1"]
|
||||
);
|
||||
assert_eq!(show(&path("{c:5}.c").get(&root).unwrap()), ["5"]);
|
||||
assert!(path("{c:6}.c").get(&root).is_err());
|
||||
let e = path("a.zzz.q").get(&root).unwrap_err();
|
||||
assert_eq!(e.key, "arguments.nbtpath.nothing_found");
|
||||
assert_eq!(e.args, ["a.zzz"]);
|
||||
assert_eq!(path("a.b[].id").count(&root), 3);
|
||||
assert_eq!(path("a.nope").count(&root), 0);
|
||||
// Arrays act like lists.
|
||||
let arr = tag("{v:[I;4,5,6]}");
|
||||
assert_eq!(show(&path("v[1]").get(&arr).unwrap()), ["5"]);
|
||||
assert_eq!(show(&path("v[]").get(&arr).unwrap()), ["4", "5", "6"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_errors() {
|
||||
assert_eq!(
|
||||
NbtPath::parse("a..b").unwrap_err().key,
|
||||
"arguments.nbtpath.node.invalid"
|
||||
);
|
||||
assert_eq!(
|
||||
NbtPath::parse("a.{b:1}").unwrap_err().key,
|
||||
"arguments.nbtpath.node.invalid"
|
||||
);
|
||||
assert_eq!(NbtPath::parse("a[1").unwrap_err().key, "parsing.expected");
|
||||
assert_eq!(NbtPath::parse("a]").unwrap_err().key, "parsing.expected");
|
||||
let (p, used) = NbtPath::parse_prefix("a.b[0] rest").unwrap();
|
||||
assert_eq!((p.as_str(), used), ("a.b[0]", 6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_creates_and_reports_changes() {
|
||||
let mut root = tag("{a:{x:1}}");
|
||||
assert_eq!(path("a.x").set(&mut root, &tag("2")).unwrap(), 1);
|
||||
assert_eq!(path("a.x").set(&mut root, &tag("2")).unwrap(), 0);
|
||||
assert_eq!(path("b.c.d").set(&mut root, &tag("\"deep\"")).unwrap(), 1);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{a:{x:2},b:{c:{d:\"deep\"}}}");
|
||||
let mut root = tag("{l:[1,2,3]}");
|
||||
assert_eq!(path("l[1]").set(&mut root, &tag("9")).unwrap(), 1);
|
||||
assert_eq!(path("l[7]").set(&mut root, &tag("9")).unwrap(), 0);
|
||||
assert_eq!(path("l[]").set(&mut root, &tag("0")).unwrap(), 3);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{l:[0,0,0]}");
|
||||
let mut root = tag("{l:[{id:1,v:0},{id:2,v:0}]}");
|
||||
assert_eq!(path("l[{id:2}].v").set(&mut root, &tag("5")).unwrap(), 1);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{l:[{id:1,v:0},{id:2,v:5}]}");
|
||||
// A missing match is created from the pattern.
|
||||
assert_eq!(path("l[{id:3}].v").set(&mut root, &tag("1")).unwrap(), 1);
|
||||
assert_eq!(path("l[{id:3}].v").count(&root), 1);
|
||||
// New lists come from index nodes.
|
||||
let mut root = tag("{}");
|
||||
assert_eq!(path("x[].y").set(&mut root, &tag("1")).unwrap(), 1);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{x:[{y:1}]}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_counts() {
|
||||
let mut root = tag("{a:1,l:[1,2,3,2],c:{d:1}}");
|
||||
assert_eq!(path("a").remove(&mut root), 1);
|
||||
assert_eq!(path("a").remove(&mut root), 0);
|
||||
assert_eq!(path("l[1]").remove(&mut root), 1);
|
||||
assert_eq!(path("c.d").remove(&mut root), 1);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{c:{},l:[1,3,2]}");
|
||||
let mut root = tag("{l:[{k:1},{k:2},{k:1}]}");
|
||||
assert_eq!(path("l[{k:1}]").remove(&mut root), 2);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{l:[{k:2}]}");
|
||||
assert_eq!(path("l[]").remove(&mut root), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_positions() {
|
||||
let mut root = tag("{l:[1,2]}");
|
||||
assert_eq!(path("l").insert(0, &mut root, &[tag("0")]).unwrap(), 1);
|
||||
assert_eq!(path("l").insert(-1, &mut root, &[tag("9")]).unwrap(), 1);
|
||||
assert_eq!(
|
||||
path("l")
|
||||
.insert(1, &mut root, &[tag("5"), tag("6")])
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(crate::snbt::to_snbt(&root), "{l:[0,5,6,1,2,9]}");
|
||||
assert_eq!(
|
||||
path("l").insert(99, &mut root, &[tag("1")]).unwrap_err(),
|
||||
CollectionError::InvalidIndex(99)
|
||||
);
|
||||
// A missing list is created.
|
||||
assert_eq!(path("n").insert(-1, &mut root, &[tag("1")]).unwrap(), 1);
|
||||
assert!(matches!(
|
||||
path("l[0]").insert(0, &mut root, &[tag("1")]).unwrap_err(),
|
||||
CollectionError::ExpectedList(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_comparison() {
|
||||
let actual = tag("{a:1,b:{c:[1,2,3],d:\"x\"},e:2}");
|
||||
assert!(compare_nbt(&tag("{b:{c:[2]}}"), Some(&actual)));
|
||||
assert!(compare_nbt(&tag("{a:1}"), Some(&actual)));
|
||||
assert!(!compare_nbt(&tag("{a:2}"), Some(&actual)));
|
||||
assert!(!compare_nbt(&tag("{a:1L}"), Some(&actual)));
|
||||
assert!(!compare_nbt(&tag("{z:1}"), Some(&actual)));
|
||||
assert!(compare_nbt(&tag("{b:{c:[]}}"), Some(&tag("{b:{c:[]}}"))));
|
||||
assert!(!compare_nbt(&tag("{b:{c:[]}}"), Some(&actual)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//! Particle types (`ParticleTypes`): the vanilla particle types with a client
|
||||
//! implementation, by registry name, and their per-type flags.
|
||||
|
||||
macro_rules! particle_types {
|
||||
($($variant:ident = $name:literal),* $(,)?) => {
|
||||
/// Vanilla particle types with a client implementation here.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ParticleType { $($variant),* }
|
||||
impl ParticleType {
|
||||
pub const ALL: &'static [ParticleType] = &[$(ParticleType::$variant),*];
|
||||
/// Registry path (`minecraft:<name>`), also the sprite-set file name.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self { $(ParticleType::$variant => $name),* }
|
||||
}
|
||||
pub fn from_name(name: &str) -> Option<Self> {
|
||||
let name = name.strip_prefix("minecraft:").unwrap_or(name);
|
||||
match name { $($name => Some(ParticleType::$variant),)* _ => None }
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
particle_types! {
|
||||
Block = "block",
|
||||
BlockCrumble = "block_crumble",
|
||||
Trail = "trail",
|
||||
DustPillar = "dust_pillar",
|
||||
FallingDust = "falling_dust",
|
||||
Smoke = "smoke",
|
||||
LargeSmoke = "large_smoke",
|
||||
WhiteSmoke = "white_smoke",
|
||||
Flame = "flame",
|
||||
SoulFireFlame = "soul_fire_flame",
|
||||
CopperFireFlame = "copper_fire_flame",
|
||||
SmallFlame = "small_flame",
|
||||
Lava = "lava",
|
||||
DrippingWater = "dripping_water",
|
||||
FallingWater = "falling_water",
|
||||
DrippingLava = "dripping_lava",
|
||||
FallingLava = "falling_lava",
|
||||
LandingLava = "landing_lava",
|
||||
DrippingHoney = "dripping_honey",
|
||||
FallingHoney = "falling_honey",
|
||||
LandingHoney = "landing_honey",
|
||||
FallingNectar = "falling_nectar",
|
||||
FallingSporeBlossom = "falling_spore_blossom",
|
||||
SporeBlossomAir = "spore_blossom_air",
|
||||
DrippingObsidianTear = "dripping_obsidian_tear",
|
||||
FallingObsidianTear = "falling_obsidian_tear",
|
||||
LandingObsidianTear = "landing_obsidian_tear",
|
||||
DrippingDripstoneWater = "dripping_dripstone_water",
|
||||
FallingDripstoneWater = "falling_dripstone_water",
|
||||
DrippingDripstoneLava = "dripping_dripstone_lava",
|
||||
FallingDripstoneLava = "falling_dripstone_lava",
|
||||
Splash = "splash",
|
||||
Rain = "rain",
|
||||
Bubble = "bubble",
|
||||
SulfurBubbles = "sulfur_bubbles",
|
||||
BubblePop = "bubble_pop",
|
||||
BubbleColumnUp = "bubble_column_up",
|
||||
CurrentDown = "current_down",
|
||||
Underwater = "underwater",
|
||||
Portal = "portal",
|
||||
ReversePortal = "reverse_portal",
|
||||
Enchant = "enchant",
|
||||
Nautilus = "nautilus",
|
||||
VaultConnection = "vault_connection",
|
||||
Crit = "crit",
|
||||
EnchantedHit = "enchanted_hit",
|
||||
DamageIndicator = "damage_indicator",
|
||||
Heart = "heart",
|
||||
AngryVillager = "angry_villager",
|
||||
HappyVillager = "happy_villager",
|
||||
Composter = "composter",
|
||||
Mycelium = "mycelium",
|
||||
Dolphin = "dolphin",
|
||||
EggCrack = "egg_crack",
|
||||
Poof = "poof",
|
||||
Explosion = "explosion",
|
||||
ExplosionEmitter = "explosion_emitter",
|
||||
CampfireCosySmoke = "campfire_cosy_smoke",
|
||||
CampfireSignalSmoke = "campfire_signal_smoke",
|
||||
Note = "note",
|
||||
Dust = "dust",
|
||||
TotemOfUndying = "totem_of_undying",
|
||||
Firework = "firework",
|
||||
EndRod = "end_rod",
|
||||
Ash = "ash",
|
||||
WhiteAsh = "white_ash",
|
||||
CrimsonSpore = "crimson_spore",
|
||||
WarpedSpore = "warped_spore",
|
||||
CherryLeaves = "cherry_leaves",
|
||||
PaleOakLeaves = "pale_oak_leaves",
|
||||
TintedLeaves = "tinted_leaves",
|
||||
Effect = "effect",
|
||||
InstantEffect = "instant_effect",
|
||||
EntityEffect = "entity_effect",
|
||||
Witch = "witch",
|
||||
Infested = "infested",
|
||||
Cloud = "cloud",
|
||||
Sneeze = "sneeze",
|
||||
Snowflake = "snowflake",
|
||||
Soul = "soul",
|
||||
SculkSoul = "sculk_soul",
|
||||
DragonBreath = "dragon_breath",
|
||||
Gust = "gust",
|
||||
SmallGust = "small_gust",
|
||||
GustEmitterLarge = "gust_emitter_large",
|
||||
GustEmitterSmall = "gust_emitter_small",
|
||||
DustColorTransition = "dust_color_transition",
|
||||
SculkCharge = "sculk_charge",
|
||||
SculkChargePop = "sculk_charge_pop",
|
||||
Shriek = "shriek",
|
||||
SonicBoom = "sonic_boom",
|
||||
Vibration = "vibration",
|
||||
SweepAttack = "sweep_attack",
|
||||
Glow = "glow",
|
||||
WaxOn = "wax_on",
|
||||
WaxOff = "wax_off",
|
||||
ElectricSpark = "electric_spark",
|
||||
Scrape = "scrape",
|
||||
SquidInk = "squid_ink",
|
||||
GlowSquidInk = "glow_squid_ink",
|
||||
Item = "item",
|
||||
ItemSlime = "item_slime",
|
||||
ItemSnowball = "item_snowball",
|
||||
ItemCobweb = "item_cobweb",
|
||||
SulfurCubeGoo = "sulfur_cube_goo",
|
||||
Flash = "flash",
|
||||
Firefly = "firefly",
|
||||
TrialSpawnerDetection = "trial_spawner_detection",
|
||||
TrialSpawnerDetectionOminous = "trial_spawner_detection_ominous",
|
||||
TrialOmen = "trial_omen",
|
||||
RaidOmen = "raid_omen",
|
||||
OminousSpawning = "ominous_spawning",
|
||||
Spit = "spit",
|
||||
Fishing = "fishing",
|
||||
DustPlume = "dust_plume",
|
||||
RedPoplarLeaves = "red_poplar_leaves",
|
||||
OrangePoplarLeaves = "orange_poplar_leaves",
|
||||
YellowPoplarLeaves = "yellow_poplar_leaves",
|
||||
PauseMobGrowth = "pause_mob_growth",
|
||||
ResetMobGrowth = "reset_mob_growth",
|
||||
BlockMarker = "block_marker",
|
||||
}
|
||||
impl ParticleType {
|
||||
/// `ParticleType.getOverrideLimiter` (`ParticleTypes.register(name, true)`):
|
||||
/// spawned regardless of distance.
|
||||
pub fn override_limiter(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::BlockMarker
|
||||
| Self::DamageIndicator
|
||||
| Self::ExplosionEmitter
|
||||
| Self::Explosion
|
||||
| Self::Gust
|
||||
| Self::GustEmitterLarge
|
||||
| Self::GustEmitterSmall
|
||||
| Self::SonicBoom
|
||||
| Self::SculkCharge
|
||||
| Self::SculkChargePop
|
||||
| Self::Vibration
|
||||
| Self::Poof
|
||||
| Self::Spit
|
||||
| Self::SquidInk
|
||||
| Self::SweepAttack
|
||||
| Self::CampfireCosySmoke
|
||||
| Self::CampfireSignalSmoke
|
||||
| Self::GlowSquidInk
|
||||
| Self::Glow
|
||||
| Self::WaxOn
|
||||
| Self::WaxOff
|
||||
| Self::ElectricSpark
|
||||
| Self::Scrape
|
||||
| Self::TrialSpawnerDetection
|
||||
| Self::TrialSpawnerDetectionOminous
|
||||
| Self::VaultConnection
|
||||
| Self::OminousSpawning
|
||||
)
|
||||
}
|
||||
/// `SingleQuadParticle.Layer.translucent`: types whose vanilla particle class
|
||||
/// hardcodes the translucent layer, drawn after translucent terrain.
|
||||
/// `TerrainParticle`, `BreakingItemParticle` and `BlockMarker` resolve their
|
||||
/// layer from the sprite instead (`Layer.bySprite`); see the `translucent`
|
||||
/// sprite set on the engine.
|
||||
pub fn translucent_layer(self) -> bool {
|
||||
match self {
|
||||
// CampfireSmokeParticle.
|
||||
Self::CampfireCosySmoke | Self::CampfireSignalSmoke
|
||||
// PlayerCloudParticle.
|
||||
| Self::Cloud | Self::Sneeze
|
||||
// SpellParticle.
|
||||
| Self::Effect | Self::InstantEffect | Self::EntityEffect
|
||||
| Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen
|
||||
// EmissiveRisingParticle.
|
||||
| Self::Soul | Self::SculkSoul
|
||||
// SculkChargeParticle, SculkChargePopParticle, ShriekParticle,
|
||||
// VibrationSignalParticle, FireflyParticle, OverlayParticle.
|
||||
| Self::SculkCharge | Self::SculkChargePop | Self::Shriek
|
||||
| Self::Vibration | Self::Firefly | Self::Flash
|
||||
// SimpleAnimatedParticle and its subclasses: EndRodParticle,
|
||||
// SparkParticle (firework), SquidInkParticle, TotemParticle.
|
||||
| Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk
|
||||
| Self::TotemOfUndying
|
||||
// FlyTowardsPositionParticle: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque.
|
||||
| Self::VaultConnection => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Registry contents and source state that commands validate and complete
|
||||
//! arguments against (what the server's registry access holds).
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Registry contents and source state used to validate and complete arguments.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Registries {
|
||||
/// Permission level of the command source.
|
||||
pub permission: u8,
|
||||
pub items: Vec<String>,
|
||||
pub item_tags: Vec<String>,
|
||||
/// Block id -> (property, allowed values).
|
||||
pub blocks: BTreeMap<String, Vec<(String, Vec<String>)>>,
|
||||
pub block_tags: Vec<String>,
|
||||
/// Entity types that `summon` can create.
|
||||
pub summonable: Vec<String>,
|
||||
/// Every entity type (selector `type=`).
|
||||
pub entity_types: Vec<String>,
|
||||
pub effects: Vec<String>,
|
||||
pub enchantments: Vec<String>,
|
||||
pub structures: Vec<String>,
|
||||
pub biomes: Vec<String>,
|
||||
pub dimensions: Vec<String>,
|
||||
pub clocks: Vec<String>,
|
||||
pub timelines: Vec<String>,
|
||||
pub time_markers: Vec<String>,
|
||||
pub advancements: Vec<String>,
|
||||
/// Game rule name -> integer-valued.
|
||||
pub game_rules: Vec<(String, bool)>,
|
||||
pub players: Vec<String>,
|
||||
/// Scoreboard objective names, team names and tracked score holders.
|
||||
pub objectives: Vec<String>,
|
||||
pub teams: Vec<String>,
|
||||
pub tracked: Vec<String>,
|
||||
/// Loaded datapack functions (`ns:path`) and function tags (`ns:path`).
|
||||
pub functions: Vec<String>,
|
||||
/// `/data ... storage` ids.
|
||||
pub storages: Vec<String>,
|
||||
/// Boss bar ids and datapack predicate ids.
|
||||
pub bossbars: Vec<String>,
|
||||
pub predicates: Vec<String>,
|
||||
pub item_modifiers: Vec<String>,
|
||||
pub schedules: Vec<String>,
|
||||
pub stopwatches: Vec<String>,
|
||||
pub recipes: Vec<String>,
|
||||
pub sounds: Vec<String>,
|
||||
pub damage_types: Vec<String>,
|
||||
pub attributes: Vec<String>,
|
||||
pub loot_tables: Vec<String>,
|
||||
pub templates: Vec<String>,
|
||||
pub random_sequences: Vec<String>,
|
||||
pub datapacks_enabled: Vec<String>,
|
||||
pub datapacks_disabled: Vec<String>,
|
||||
pub function_tags: Vec<String>,
|
||||
/// The block the source is looking at (relevant coordinates).
|
||||
pub target_block: Option<[i32; 3]>,
|
||||
/// Every registry's element and tag ids (`minecraft:item` -> ...), as
|
||||
/// the server's registry access and reloadable registries hold them.
|
||||
pub by_registry: BTreeMap<String, RegistryIds>,
|
||||
/// Blocks whose default state has a block entity.
|
||||
pub block_entities: std::collections::BTreeSet<String>,
|
||||
/// Block tag -> member blocks.
|
||||
pub block_tag_members: BTreeMap<String, Vec<String>>,
|
||||
/// Data component types with a codec (not transient).
|
||||
pub persistent_components: Vec<String>,
|
||||
/// Recipes `/recipe` can give (not special).
|
||||
pub learnable_recipes: Vec<String>,
|
||||
/// Advancement id -> criterion names.
|
||||
pub advancement_criteria: BTreeMap<String, Vec<String>>,
|
||||
/// World clock -> time markers shown in commands.
|
||||
pub clock_time_markers: BTreeMap<String, Vec<String>>,
|
||||
/// Trigger objectives the source may use (`/trigger` suggestions).
|
||||
pub trigger_objectives: Vec<String>,
|
||||
/// Objectives with the `trigger` criterion -> holder -> whether its score is locked.
|
||||
pub trigger_scores: BTreeMap<String, BTreeMap<String, bool>>,
|
||||
}
|
||||
/// The ids and tag ids of one registry.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RegistryIds {
|
||||
pub ids: Vec<String>,
|
||||
pub tags: Vec<String>,
|
||||
}
|
||||
const EMPTY: &[String] = &[];
|
||||
impl Registries {
|
||||
/// Fill what the game did not build itself from vanilla's exported
|
||||
/// registries (`command-registries.json`, written by
|
||||
/// `VanillaCommandParseOracle registries`): built-in registries such as
|
||||
/// mob effects, data component types and dialogs, block entities and tag
|
||||
/// members. Registries that data packs reload stay with the game.
|
||||
pub fn fill_from_export(&mut self, r: &serde_json::Value) {
|
||||
fn strings(v: &serde_json::Value) -> Vec<String> {
|
||||
v.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.as_str().map(str::to_owned))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
let fill = |field: &mut Vec<String>, key: &str| {
|
||||
if field.is_empty() {
|
||||
*field = strings(&r[key]);
|
||||
}
|
||||
};
|
||||
fill(&mut self.effects, "effects");
|
||||
fill(&mut self.enchantments, "enchantments");
|
||||
fill(&mut self.attributes, "attributes");
|
||||
fill(&mut self.damage_types, "damage_types");
|
||||
fill(&mut self.templates, "templates");
|
||||
fill(&mut self.persistent_components, "persistent_components");
|
||||
fill(&mut self.learnable_recipes, "learnable_recipes");
|
||||
const RELOADED: [&str; 5] = [
|
||||
"minecraft:advancement",
|
||||
"minecraft:recipe",
|
||||
"minecraft:loot_table",
|
||||
"minecraft:predicate",
|
||||
"minecraft:item_modifier",
|
||||
];
|
||||
for (name, entry) in r["by_registry"].as_object().into_iter().flatten() {
|
||||
if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) {
|
||||
continue;
|
||||
}
|
||||
self.by_registry.insert(
|
||||
name.clone(),
|
||||
RegistryIds {
|
||||
ids: strings(&entry["ids"]),
|
||||
tags: strings(&entry["tags"]),
|
||||
},
|
||||
);
|
||||
}
|
||||
if self.block_entities.is_empty() {
|
||||
self.block_entities = strings(&r["block_entities"]).into_iter().collect();
|
||||
}
|
||||
if self.block_tag_members.is_empty() {
|
||||
for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() {
|
||||
self.block_tag_members.insert(tag.clone(), strings(members));
|
||||
}
|
||||
}
|
||||
if self.clock_time_markers.is_empty() {
|
||||
for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() {
|
||||
self.clock_time_markers
|
||||
.insert(clock.clone(), strings(markers));
|
||||
}
|
||||
}
|
||||
if self.advancement_criteria.is_empty() {
|
||||
for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() {
|
||||
self.advancement_criteria
|
||||
.insert(id.clone(), strings(criteria));
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The element ids of a registry (sorted).
|
||||
pub fn ids(&self, registry: &str) -> &[String] {
|
||||
if let Some(r) = self.by_registry.get(registry) {
|
||||
return &r.ids;
|
||||
}
|
||||
match registry {
|
||||
"minecraft:item" => &self.items,
|
||||
"minecraft:entity_type" => &self.entity_types,
|
||||
"minecraft:mob_effect" => &self.effects,
|
||||
"minecraft:enchantment" => &self.enchantments,
|
||||
"minecraft:worldgen/structure" => &self.structures,
|
||||
"minecraft:worldgen/biome" => &self.biomes,
|
||||
"minecraft:world_clock" => &self.clocks,
|
||||
"minecraft:timeline" => &self.timelines,
|
||||
"minecraft:attribute" => &self.attributes,
|
||||
"minecraft:damage_type" => &self.damage_types,
|
||||
"minecraft:sound_event" => &self.sounds,
|
||||
"minecraft:predicate" => &self.predicates,
|
||||
"minecraft:item_modifier" => &self.item_modifiers,
|
||||
"minecraft:loot_table" => &self.loot_tables,
|
||||
"minecraft:recipe" => &self.recipes,
|
||||
"minecraft:advancement" => &self.advancements,
|
||||
_ => EMPTY,
|
||||
}
|
||||
}
|
||||
/// The tag ids of a registry (sorted).
|
||||
pub fn tags(&self, registry: &str) -> &[String] {
|
||||
if let Some(r) = self.by_registry.get(registry) {
|
||||
return &r.tags;
|
||||
}
|
||||
match registry {
|
||||
"minecraft:item" => &self.item_tags,
|
||||
"minecraft:block" => &self.block_tags,
|
||||
_ => EMPTY,
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,513 @@
|
||||
//! Tag text output: `StringTagVisitor` (compact SNBT) and
|
||||
//! `TextComponentTagVisitor` (the coloured form commands print), plus Java's
|
||||
//! number formatting.
|
||||
use crate::text::{self, Style, Text};
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
/// `Double.toString`.
|
||||
pub fn java_double(v: f64) -> String {
|
||||
java_float_text(v, &format!("{v}"), &format!("{v:e}"))
|
||||
}
|
||||
/// `Float.toString`.
|
||||
pub fn java_float(v: f32) -> String {
|
||||
java_float_text(f64::from(v), &format!("{v}"), &format!("{v:e}"))
|
||||
}
|
||||
fn java_float_text(v: f64, plain: &str, sci: &str) -> String {
|
||||
if v.is_nan() {
|
||||
return "NaN".into();
|
||||
}
|
||||
if v.is_infinite() {
|
||||
return if v > 0.0 { "Infinity" } else { "-Infinity" }.into();
|
||||
}
|
||||
if v == 0.0 {
|
||||
return if v.is_sign_negative() { "-0.0" } else { "0.0" }.into();
|
||||
}
|
||||
let a = v.abs();
|
||||
if (1.0e-3..1.0e7).contains(&a) {
|
||||
if plain.contains('.') {
|
||||
plain.to_owned()
|
||||
} else {
|
||||
format!("{plain}.0")
|
||||
}
|
||||
} else {
|
||||
let (mantissa, exponent) = sci.split_once('e').unwrap_or((sci, "0"));
|
||||
let mantissa = if mantissa.contains('.') {
|
||||
mantissa.to_owned()
|
||||
} else {
|
||||
format!("{mantissa}.0")
|
||||
};
|
||||
format!("{mantissa}E{exponent}")
|
||||
}
|
||||
}
|
||||
|
||||
/// `SnbtGrammar.escapeControlCharacters`.
|
||||
fn escape_control(c: char) -> Option<&'static str> {
|
||||
Some(match c {
|
||||
'\u{8}' => "b",
|
||||
'\u{c}' => "f",
|
||||
'\n' => "n",
|
||||
'\r' => "r",
|
||||
'\t' => "t",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// `StringTag.quoteAndEscape`.
|
||||
pub fn quote_and_escape(input: &str) -> String {
|
||||
let mut out = String::from(" ");
|
||||
let mut quote = '\0';
|
||||
for c in input.chars() {
|
||||
if c == '\\' {
|
||||
out.push_str("\\\\");
|
||||
} else if c != '"' && c != '\'' {
|
||||
match escape_control(c) {
|
||||
Some(e) => {
|
||||
out.push('\\');
|
||||
out.push_str(e);
|
||||
}
|
||||
None => out.push(c),
|
||||
}
|
||||
} else {
|
||||
if quote == '\0' {
|
||||
quote = if c == '"' { '\'' } else { '"' };
|
||||
}
|
||||
if quote == c {
|
||||
out.push('\\');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
if quote == '\0' {
|
||||
quote = '"';
|
||||
}
|
||||
out.replace_range(0..1, "e.to_string());
|
||||
out.push(quote);
|
||||
out
|
||||
}
|
||||
fn unquoted_key(key: &str) -> bool {
|
||||
if key.eq_ignore_ascii_case("true") || key.eq_ignore_ascii_case("false") {
|
||||
return false;
|
||||
}
|
||||
let mut chars = key.chars();
|
||||
let first_ok = chars
|
||||
.next()
|
||||
.is_some_and(|c| c.is_ascii_alphabetic() || c == '.' || c == '_');
|
||||
// `[A-Za-z._]+[A-Za-z0-9._+-]*`
|
||||
first_ok && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-'))
|
||||
}
|
||||
fn string_of(t: &horizon_world::nbt::JavaString) -> String {
|
||||
t.to_string_lossy()
|
||||
}
|
||||
|
||||
/// `Tag.toString` (StringTagVisitor).
|
||||
pub fn to_snbt(tag: &Tag) -> String {
|
||||
let mut out = String::new();
|
||||
visit(tag, &mut out);
|
||||
out
|
||||
}
|
||||
fn visit(tag: &Tag, out: &mut String) {
|
||||
match tag {
|
||||
Tag::End => out.push_str("END"),
|
||||
Tag::Byte(v) => out.push_str(&format!("{v}b")),
|
||||
Tag::Short(v) => out.push_str(&format!("{v}s")),
|
||||
Tag::Int(v) => out.push_str(&v.to_string()),
|
||||
Tag::Long(v) => out.push_str(&format!("{v}L")),
|
||||
Tag::Float(v) => {
|
||||
out.push_str(&java_float(f32::from_bits(*v)));
|
||||
out.push('f');
|
||||
}
|
||||
Tag::Double(v) => {
|
||||
out.push_str(&java_double(f64::from_bits(*v)));
|
||||
out.push('d');
|
||||
}
|
||||
Tag::String(s) => out.push_str("e_and_escape(&string_of(s))),
|
||||
Tag::ByteArray(a) => {
|
||||
out.push_str("[B;");
|
||||
out.push_str(
|
||||
&a.iter()
|
||||
.map(|v| format!("{}B", *v as i8))
|
||||
.collect::<Vec<_>>()
|
||||
.join(","),
|
||||
);
|
||||
out.push(']');
|
||||
}
|
||||
Tag::IntArray(a) => {
|
||||
out.push_str("[I;");
|
||||
out.push_str(&a.iter().map(i32::to_string).collect::<Vec<_>>().join(","));
|
||||
out.push(']');
|
||||
}
|
||||
Tag::LongArray(a) => {
|
||||
out.push_str("[L;");
|
||||
out.push_str(
|
||||
&a.iter()
|
||||
.map(|v| format!("{v}L"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(","),
|
||||
);
|
||||
out.push(']');
|
||||
}
|
||||
Tag::List(l) => {
|
||||
out.push('[');
|
||||
for (i, t) in l.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
visit(t, out);
|
||||
}
|
||||
out.push(']');
|
||||
}
|
||||
Tag::Compound(c) => {
|
||||
out.push('{');
|
||||
let mut entries: Vec<(String, &Tag)> =
|
||||
c.iter().map(|(k, v)| (string_of(k), v)).collect();
|
||||
entries.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
for (i, (k, v)) in entries.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(',');
|
||||
}
|
||||
if unquoted_key(k) {
|
||||
out.push_str(k);
|
||||
} else {
|
||||
out.push_str("e_and_escape(k));
|
||||
}
|
||||
out.push(':');
|
||||
visit(v, out);
|
||||
}
|
||||
out.push('}');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the coloured form -----------------------------------------------------
|
||||
|
||||
struct Pretty {
|
||||
indentation: String,
|
||||
result: Text,
|
||||
indent_depth: usize,
|
||||
depth: usize,
|
||||
}
|
||||
fn is_numeric(t: &Tag) -> bool {
|
||||
matches!(
|
||||
t,
|
||||
Tag::Byte(_) | Tag::Short(_) | Tag::Int(_) | Tag::Long(_) | Tag::Float(_) | Tag::Double(_)
|
||||
)
|
||||
}
|
||||
impl Pretty {
|
||||
fn lit(&mut self, s: &str, color: Option<u32>) {
|
||||
let t = match color {
|
||||
Some(c) => Text::styled(s, Style::color(c)),
|
||||
None => Text::literal(s),
|
||||
};
|
||||
self.result.push(t);
|
||||
}
|
||||
fn number(&mut self, s: &str, suffix: &str) {
|
||||
self.lit(s, Some(text::GOLD));
|
||||
if !suffix.is_empty() {
|
||||
self.lit(suffix, Some(text::RED));
|
||||
}
|
||||
}
|
||||
fn quoted(&mut self, input: &str, color: u32) {
|
||||
let q = quote_and_escape(input);
|
||||
let (open, inner) = (&q[..1], &q[1..q.len() - 1]);
|
||||
self.lit(open, None);
|
||||
self.lit(inner, Some(color));
|
||||
self.lit(open, None);
|
||||
}
|
||||
fn array<T: std::fmt::Display>(&mut self, prefix: &str, items: &[T], suffix: &str) {
|
||||
self.lit("[", None);
|
||||
self.lit(prefix, Some(text::RED));
|
||||
self.lit(";", None);
|
||||
for (i, v) in items.iter().enumerate().take(128) {
|
||||
self.lit(" ", None);
|
||||
self.number(&v.to_string(), suffix);
|
||||
if i != items.len() - 1 {
|
||||
self.lit(",", None);
|
||||
}
|
||||
}
|
||||
if items.len() > 128 {
|
||||
self.lit("<...>", Some(text::GRAY));
|
||||
}
|
||||
self.lit("]", None);
|
||||
}
|
||||
fn sub(&mut self, tag: &Tag, indent: bool) {
|
||||
if indent {
|
||||
self.indent_depth += 1;
|
||||
}
|
||||
self.depth += 1;
|
||||
self.visit(tag);
|
||||
if indent {
|
||||
self.indent_depth -= 1;
|
||||
}
|
||||
self.depth -= 1;
|
||||
}
|
||||
fn visit(&mut self, tag: &Tag) {
|
||||
match tag {
|
||||
Tag::End => {}
|
||||
Tag::Byte(v) => self.number(&v.to_string(), "b"),
|
||||
Tag::Short(v) => self.number(&v.to_string(), "s"),
|
||||
Tag::Int(v) => self.number(&v.to_string(), ""),
|
||||
Tag::Long(v) => self.number(&v.to_string(), "L"),
|
||||
Tag::Float(v) => self.number(&java_float(f32::from_bits(*v)), "f"),
|
||||
Tag::Double(v) => self.number(&java_double(f64::from_bits(*v)), "d"),
|
||||
Tag::String(s) => self.quoted(&string_of(s), text::GREEN),
|
||||
Tag::ByteArray(a) => {
|
||||
let v: Vec<i8> = a.iter().map(|b| *b as i8).collect();
|
||||
self.array("B", &v, "b");
|
||||
}
|
||||
Tag::IntArray(a) => self.array("I", a, ""),
|
||||
Tag::LongArray(a) => self.array("L", a, "L"),
|
||||
Tag::List(l) => self.list(l),
|
||||
Tag::Compound(c) => self.compound(c),
|
||||
}
|
||||
}
|
||||
fn list(&mut self, l: &[Tag]) {
|
||||
if l.is_empty() {
|
||||
self.lit("[", None);
|
||||
self.lit("]", None);
|
||||
} else if self.depth >= 64 {
|
||||
self.lit("[", None);
|
||||
self.lit("<...>", Some(text::GRAY));
|
||||
self.lit("]", None);
|
||||
} else if l.len() >= 8 || l.iter().all(is_numeric) {
|
||||
self.lit("[", None);
|
||||
for (i, t) in l.iter().enumerate() {
|
||||
if i != 0 {
|
||||
self.lit(",", None);
|
||||
self.lit(" ", None);
|
||||
}
|
||||
self.sub(t, false);
|
||||
}
|
||||
self.lit("]", None);
|
||||
} else {
|
||||
self.lit("[", None);
|
||||
if !self.indentation.is_empty() {
|
||||
self.lit("\n", None);
|
||||
}
|
||||
let entry = self.indentation.repeat(self.indent_depth + 1);
|
||||
let spacing = if self.indentation.is_empty() {
|
||||
" "
|
||||
} else {
|
||||
"\n"
|
||||
};
|
||||
for (i, t) in l.iter().enumerate().take(128) {
|
||||
self.lit(&entry, None);
|
||||
self.sub(t, true);
|
||||
if i != l.len() - 1 {
|
||||
self.lit(",", None);
|
||||
self.lit(spacing, None);
|
||||
}
|
||||
}
|
||||
if l.len() > 128 {
|
||||
self.lit(&entry, None);
|
||||
self.lit("<...>", Some(text::GRAY));
|
||||
}
|
||||
if !self.indentation.is_empty() {
|
||||
self.lit("\n", None);
|
||||
let close = self.indentation.repeat(self.indent_depth);
|
||||
self.lit(&close, None);
|
||||
}
|
||||
self.lit("]", None);
|
||||
}
|
||||
}
|
||||
fn compound(&mut self, c: &horizon_world::nbt::Compound) {
|
||||
if c.is_empty() {
|
||||
self.lit("{", None);
|
||||
self.lit("}", None);
|
||||
} else if self.depth >= 64 {
|
||||
self.lit("{", None);
|
||||
self.lit("<...>", Some(text::GRAY));
|
||||
self.lit("}", None);
|
||||
} else {
|
||||
self.lit("{", None);
|
||||
if !self.indentation.is_empty() {
|
||||
self.lit("\n", None);
|
||||
}
|
||||
let entry = self.indentation.repeat(self.indent_depth + 1);
|
||||
let spacing = if self.indentation.is_empty() {
|
||||
" "
|
||||
} else {
|
||||
"\n"
|
||||
};
|
||||
let n = c.len();
|
||||
for (i, (k, v)) in java_hash_order(c).into_iter().enumerate() {
|
||||
self.lit(&entry, None);
|
||||
let key = string_of(k);
|
||||
if !key.is_empty()
|
||||
&& key
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '+' | '-'))
|
||||
{
|
||||
self.lit(&key, Some(text::AQUA));
|
||||
} else {
|
||||
self.quoted(&key, text::AQUA);
|
||||
}
|
||||
self.lit(":", None);
|
||||
self.lit(" ", None);
|
||||
self.sub(v, true);
|
||||
if i + 1 < n {
|
||||
self.lit(",", None);
|
||||
self.lit(spacing, None);
|
||||
}
|
||||
}
|
||||
if !self.indentation.is_empty() {
|
||||
self.lit("\n", None);
|
||||
let close = self.indentation.repeat(self.indent_depth);
|
||||
self.lit(&close, None);
|
||||
}
|
||||
self.lit("}", None);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The iteration order of the `HashMap<String, Tag>` a `CompoundTag` holds,
|
||||
/// for a map that grew to its size by insertion: buckets by
|
||||
/// `HashMap.hash(String.hashCode())`, keys sharing a bucket in key order.
|
||||
pub fn java_hash_order(
|
||||
c: &horizon_world::nbt::Compound,
|
||||
) -> Vec<(&horizon_world::nbt::JavaString, &Tag)> {
|
||||
let mut capacity = 16usize;
|
||||
while c.len() > capacity * 3 / 4 {
|
||||
capacity *= 2;
|
||||
}
|
||||
let bucket = |k: &horizon_world::nbt::JavaString| {
|
||||
let h = string_of(k)
|
||||
.encode_utf16()
|
||||
.fold(0u32, |h, ch| h.wrapping_mul(31).wrapping_add(u32::from(ch)));
|
||||
((h ^ (h >> 16)) as usize) & (capacity - 1)
|
||||
};
|
||||
// Keys sharing a bucket iterate in insertion order: the order vanilla's
|
||||
// savers write them, as far as it is known here.
|
||||
const WRITE_ORDER: &[&str] = &[
|
||||
// ItemStack.CODEC.
|
||||
"id",
|
||||
"count",
|
||||
"components",
|
||||
// Entity.saveWithoutId.
|
||||
"Pos",
|
||||
"Motion",
|
||||
"Rotation",
|
||||
"fall_distance",
|
||||
"Fire",
|
||||
"Air",
|
||||
"OnGround",
|
||||
"Invulnerable",
|
||||
"PortalCooldown",
|
||||
"UUID",
|
||||
"CustomName",
|
||||
"CustomNameVisible",
|
||||
"Silent",
|
||||
"NoGravity",
|
||||
"Glowing",
|
||||
"TicksFrozen",
|
||||
"HasVisualFire",
|
||||
"Tags",
|
||||
"data",
|
||||
"Passengers",
|
||||
// LivingEntity.addAdditionalSaveData.
|
||||
"Health",
|
||||
"HurtTime",
|
||||
"DeathTime",
|
||||
"AbsorptionAmount",
|
||||
"current_impulse_context_reset_grace_time",
|
||||
"current_explosion_impact_pos",
|
||||
"attributes",
|
||||
"active_effects",
|
||||
"FallFlying",
|
||||
"sleeping_pos",
|
||||
"Brain",
|
||||
"equipment",
|
||||
// ArmorStand.
|
||||
"Invisible",
|
||||
"Small",
|
||||
"ShowArms",
|
||||
"DisabledSlots",
|
||||
"NoBasePlate",
|
||||
"Marker",
|
||||
"Pose",
|
||||
];
|
||||
// BlockEntity.saveMetadata writes the position after the entity's data.
|
||||
const AFTER: &[&str] = &["x", "y", "z"];
|
||||
let rank = |k: &horizon_world::nbt::JavaString| {
|
||||
let k = string_of(k);
|
||||
WRITE_ORDER
|
||||
.iter()
|
||||
.position(|w| *w == k)
|
||||
.or_else(|| {
|
||||
AFTER
|
||||
.iter()
|
||||
.position(|w| *w == k)
|
||||
.map(|i| WRITE_ORDER.len() + 1 + i)
|
||||
})
|
||||
.unwrap_or(WRITE_ORDER.len())
|
||||
};
|
||||
let mut entries: Vec<_> = c.iter().collect();
|
||||
entries.sort_by_key(|(k, _)| (bucket(k), rank(k)));
|
||||
entries
|
||||
}
|
||||
/// `NbtUtils.toPrettyComponent`: the coloured, unindented form.
|
||||
pub fn pretty(tag: &Tag) -> Text {
|
||||
pretty_indented(tag, "")
|
||||
}
|
||||
pub fn pretty_indented(tag: &Tag, indentation: &str) -> Text {
|
||||
let mut p = Pretty {
|
||||
indentation: indentation.to_owned(),
|
||||
result: Text::empty(),
|
||||
indent_depth: 0,
|
||||
depth: 0,
|
||||
};
|
||||
p.visit(tag);
|
||||
p.result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_world::nbt::parse_snbt;
|
||||
|
||||
fn rt(s: &str) -> String {
|
||||
to_snbt(&parse_snbt(s).unwrap().0)
|
||||
}
|
||||
#[test]
|
||||
fn compact_form_matches_vanilla() {
|
||||
assert_eq!(
|
||||
rt("{b:1b,a:\"x\",c:[1,2],d:1.5f,e:2d,f:3L,g:4s}"),
|
||||
"{a:\"x\",b:1b,c:[1,2],d:1.5f,e:2.0d,f:3L,g:4s}"
|
||||
);
|
||||
assert_eq!(rt("{\"a b\":1}"), "{\"a b\":1}");
|
||||
assert_eq!(rt("{true:1}"), "{\"true\":1}");
|
||||
assert_eq!(rt("[B;1b,2b]"), "[B;1B,2B]");
|
||||
assert_eq!(rt("[I;1,2]"), "[I;1,2]");
|
||||
assert_eq!(rt("[L;1L]"), "[L;1L]");
|
||||
assert_eq!(quote_and_escape("say \"hi\""), "'say \"hi\"'");
|
||||
assert_eq!(quote_and_escape("it's \"x\""), "\"it's \\\"x\\\"\"");
|
||||
assert_eq!(quote_and_escape("a\nb\\"), "\"a\\nb\\\\\"");
|
||||
}
|
||||
#[test]
|
||||
fn java_number_text() {
|
||||
assert_eq!(java_double(1.0), "1.0");
|
||||
assert_eq!(java_double(0.1), "0.1");
|
||||
assert_eq!(java_double(1.0e7), "1.0E7");
|
||||
assert_eq!(java_double(12345678.9), "1.23456789E7");
|
||||
assert_eq!(java_double(0.0001), "1.0E-4");
|
||||
assert_eq!(java_double(-3.5), "-3.5");
|
||||
assert_eq!(java_float(0.3), "0.3");
|
||||
assert_eq!(java_float(100.0), "100.0");
|
||||
assert_eq!(java_double(f64::NAN), "NaN");
|
||||
}
|
||||
#[test]
|
||||
fn pretty_form_is_coloured_without_changing_text() {
|
||||
let tag = parse_snbt("{Pos:[1.5d,2.0d],id:\"minecraft:pig\",n:3b}")
|
||||
.unwrap()
|
||||
.0;
|
||||
let t = pretty(&tag);
|
||||
assert_eq!(
|
||||
t.plain(),
|
||||
"{Pos: [1.5d, 2.0d], id: \"minecraft:pig\", n: 3b}"
|
||||
);
|
||||
// keys aqua, strings green, numbers gold.
|
||||
let colors: Vec<_> = t.spans.iter().filter_map(|s| s.style.color).collect();
|
||||
assert!(colors.contains(&text::AQUA));
|
||||
assert!(colors.contains(&text::GREEN));
|
||||
assert!(colors.contains(&text::GOLD));
|
||||
let long = parse_snbt("{l:[{a:1},{b:2}]}").unwrap().0;
|
||||
assert_eq!(pretty(&long).plain(), "{l: [{a: 1}, {b: 2}]}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//! Sound sources (`SoundSource`), by name.
|
||||
|
||||
/// SoundSource names in vanilla order.
|
||||
pub const SOUND_SOURCES: [&str; 11] = [
|
||||
"master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient",
|
||||
"voice", "ui",
|
||||
];
|
||||
@@ -0,0 +1,729 @@
|
||||
//! Styled text (a flattened `Component`): spans with ChatFormatting colours
|
||||
//! and decorations, translatable messages formatted like
|
||||
//! `TranslatableContents` (`%s`, `%1$s`, `%%`), and legacy `§` codes.
|
||||
use crate::lang;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
/// ChatFormatting colours by legacy code index 0..=15.
|
||||
pub const COLORS: [(char, &str, u32); 16] = [
|
||||
('0', "black", 0x000000),
|
||||
('1', "dark_blue", 0x0000AA),
|
||||
('2', "dark_green", 0x00AA00),
|
||||
('3', "dark_aqua", 0x00AAAA),
|
||||
('4', "dark_red", 0xAA0000),
|
||||
('5', "dark_purple", 0xAA00AA),
|
||||
('6', "gold", 0xFFAA00),
|
||||
('7', "gray", 0xAAAAAA),
|
||||
('8', "dark_gray", 0x555555),
|
||||
('9', "blue", 0x5555FF),
|
||||
('a', "green", 0x55FF55),
|
||||
('b', "aqua", 0x55FFFF),
|
||||
('c', "red", 0xFF5555),
|
||||
('d', "light_purple", 0xFF55FF),
|
||||
('e', "yellow", 0xFFFF55),
|
||||
('f', "white", 0xFFFFFF),
|
||||
];
|
||||
pub const BLACK: u32 = 0x000000;
|
||||
pub const GRAY: u32 = 0xAAAAAA;
|
||||
pub const DARK_GRAY: u32 = 0x555555;
|
||||
pub const GREEN: u32 = 0x55FF55;
|
||||
pub const AQUA: u32 = 0x55FFFF;
|
||||
pub const RED: u32 = 0xFF5555;
|
||||
pub const YELLOW: u32 = 0xFFFF55;
|
||||
pub const GOLD: u32 = 0xFFAA00;
|
||||
pub const WHITE: u32 = 0xFFFFFF;
|
||||
pub const LIGHT_PURPLE: u32 = 0xFF55FF;
|
||||
pub const DARK_PURPLE: u32 = 0xAA00AA;
|
||||
|
||||
pub fn named_color(name: &str) -> Option<u32> {
|
||||
COLORS.iter().find(|c| c.1 == name).map(|c| c.2)
|
||||
}
|
||||
|
||||
/// Click actions carried by locally constructed text components.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ClickEvent {
|
||||
/// `ClickEvent.OpenUrl`: an http or https link.
|
||||
OpenUrl(String),
|
||||
/// `ClickEvent.ChangePage`: a book's page, counted from 1.
|
||||
ChangePage(i32),
|
||||
SuggestCommand(String),
|
||||
CopyToClipboard(String),
|
||||
/// A local file to open with the system handler.
|
||||
/// Only allow this in locally constructed messages, never server/LAN text.
|
||||
OpenFile(String),
|
||||
}
|
||||
|
||||
/// Text style; `None` fields inherit from the enclosing style.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Style {
|
||||
pub color: Option<u32>,
|
||||
pub bold: Option<bool>,
|
||||
pub italic: Option<bool>,
|
||||
pub underlined: Option<bool>,
|
||||
pub strikethrough: Option<bool>,
|
||||
pub obfuscated: Option<bool>,
|
||||
pub click: Option<ClickEvent>,
|
||||
/// Hover text.
|
||||
pub hover: Option<Box<Text>>,
|
||||
/// The font (`FontDescription.Resource`), a full id like
|
||||
/// `minecraft:alt`; the default font when unset.
|
||||
pub font: Option<String>,
|
||||
}
|
||||
/// A style's `font` field: an identifier (`alt` is `minecraft:alt`).
|
||||
pub fn font_id(v: &Value) -> Option<String> {
|
||||
crate::identifier::parse_identifier(v.as_str()?)
|
||||
}
|
||||
impl Style {
|
||||
pub fn color(c: u32) -> Self {
|
||||
Self {
|
||||
color: Some(c),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
/// Fill unset fields from `base` (Style.applyTo).
|
||||
pub fn inherit(&mut self, base: &Style) {
|
||||
self.color = self.color.or(base.color);
|
||||
self.bold = self.bold.or(base.bold);
|
||||
self.italic = self.italic.or(base.italic);
|
||||
self.underlined = self.underlined.or(base.underlined);
|
||||
self.strikethrough = self.strikethrough.or(base.strikethrough);
|
||||
self.obfuscated = self.obfuscated.or(base.obfuscated);
|
||||
if self.click.is_none() {
|
||||
self.click.clone_from(&base.click);
|
||||
}
|
||||
if self.hover.is_none() {
|
||||
self.hover.clone_from(&base.hover);
|
||||
}
|
||||
if self.font.is_none() {
|
||||
self.font.clone_from(&base.font);
|
||||
}
|
||||
}
|
||||
pub fn is_bold(&self) -> bool {
|
||||
self.bold == Some(true)
|
||||
}
|
||||
pub fn is_italic(&self) -> bool {
|
||||
self.italic == Some(true)
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Span {
|
||||
pub text: String,
|
||||
pub style: Style,
|
||||
}
|
||||
/// A run of styled spans, and the `Component` they came from (its JSON form)
|
||||
/// when it was built through the constructors below, for sending to vanilla
|
||||
/// clients. Equality compares the spans only.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Text {
|
||||
pub spans: Vec<Span>,
|
||||
source: Option<std::sync::Arc<Value>>,
|
||||
}
|
||||
impl PartialEq for Text {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.spans == other.spans
|
||||
}
|
||||
}
|
||||
impl Eq for Text {}
|
||||
impl From<&str> for Text {
|
||||
fn from(s: &str) -> Self {
|
||||
Text::literal(s)
|
||||
}
|
||||
}
|
||||
impl From<String> for Text {
|
||||
fn from(s: String) -> Self {
|
||||
Text::literal(s)
|
||||
}
|
||||
}
|
||||
impl Text {
|
||||
pub fn empty() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
pub fn literal(s: impl Into<String>) -> Self {
|
||||
let text = s.into();
|
||||
if text.is_empty() {
|
||||
return Self::default();
|
||||
}
|
||||
Self {
|
||||
source: Some(json!({ "text": text }).into()),
|
||||
spans: vec![Span {
|
||||
text,
|
||||
style: Style::default(),
|
||||
}],
|
||||
}
|
||||
}
|
||||
pub fn styled(s: impl Into<String>, style: Style) -> Self {
|
||||
Self::literal(s).with_style(&style)
|
||||
}
|
||||
pub fn colored(s: impl Into<String>, color: u32) -> Self {
|
||||
Self::styled(s, Style::color(color))
|
||||
}
|
||||
/// ComponentUtils.copyOnClickText: a green, bracketed clipboard link.
|
||||
pub fn copyable(s: impl Into<String>) -> Self {
|
||||
let s = s.into();
|
||||
Self::literal("[")
|
||||
.append(Self::styled(
|
||||
s.clone(),
|
||||
Style {
|
||||
click: Some(ClickEvent::CopyToClipboard(s)),
|
||||
hover: Some(Box::new(Self::translate("chat.copy.click", &[]))),
|
||||
..Style::color(GREEN)
|
||||
},
|
||||
))
|
||||
.append("]")
|
||||
}
|
||||
/// LocateCommand's coordinate link: suggest a teleport without executing it.
|
||||
/// Structure and POI results preserve the player's current height (`~`).
|
||||
pub fn teleport_link(x: i32, y: Option<i32>, z: i32) -> Self {
|
||||
let y = y.map_or_else(|| "~".to_owned(), |y| y.to_string());
|
||||
let coords = Self::tr("chat.coordinates", &[&x, &y, &z]);
|
||||
Self::literal("[")
|
||||
.append(coords)
|
||||
.append("]")
|
||||
.with_style(&Style {
|
||||
click: Some(ClickEvent::SuggestCommand(format!("/tp @s {x} {y} {z}"))),
|
||||
hover: Some(Box::new(Self::translate("chat.coordinates.tooltip", &[]))),
|
||||
..Style::color(GREEN)
|
||||
})
|
||||
}
|
||||
/// Component.translatable(key, args) in the current language.
|
||||
pub fn translate(key: &str, args: &[Text]) -> Self {
|
||||
let mut t = format_translation(&lang::get(key), args);
|
||||
let mut c = Map::new();
|
||||
c.insert("translate".into(), key.into());
|
||||
if !args.is_empty() {
|
||||
c.insert("with".into(), args.iter().map(Text::argument).collect());
|
||||
}
|
||||
t.source = Some(Value::Object(c).into());
|
||||
t
|
||||
}
|
||||
/// A translatable message whose arguments are plain strings.
|
||||
pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> Self {
|
||||
let args: Vec<Text> = args.iter().map(|a| Text::literal(a.to_string())).collect();
|
||||
Self::translate(key, &args)
|
||||
}
|
||||
pub fn append(mut self, other: impl Into<Text>) -> Self {
|
||||
self.push(other);
|
||||
self
|
||||
}
|
||||
/// MutableComponent.append: `other` becomes a sibling. A styled text is
|
||||
/// wrapped first, as its style doesn't reach what is appended here.
|
||||
pub fn push(&mut self, other: impl Into<Text>) {
|
||||
let other = other.into();
|
||||
let sibling = other.component();
|
||||
let mut root = if self.spans.is_empty() && self.source.is_none() {
|
||||
json!({ "text": "" })
|
||||
} else {
|
||||
let c = self.component();
|
||||
if STYLE_KEYS.iter().any(|k| c.get(*k).is_some()) {
|
||||
json!({ "text": "", "extra": [c] })
|
||||
} else {
|
||||
c
|
||||
}
|
||||
};
|
||||
if let Value::Object(o) = &mut root {
|
||||
match o.get_mut("extra") {
|
||||
Some(Value::Array(a)) => a.push(sibling),
|
||||
_ => {
|
||||
o.insert("extra".into(), Value::Array(vec![sibling]));
|
||||
}
|
||||
}
|
||||
}
|
||||
self.source = Some(root.into());
|
||||
self.spans.extend(other.spans);
|
||||
}
|
||||
/// Apply `style` underneath every span (MutableComponent.withStyle on a parent).
|
||||
pub fn with_style(mut self, style: &Style) -> Self {
|
||||
for span in &mut self.spans {
|
||||
span.style.inherit(style);
|
||||
}
|
||||
let mut c = self.component();
|
||||
if let Value::Object(o) = &mut c {
|
||||
for (k, v) in style_json(style) {
|
||||
o.entry(k).or_insert(v);
|
||||
}
|
||||
}
|
||||
self.source = Some(c.into());
|
||||
self
|
||||
}
|
||||
/// The `Component` as vanilla's JSON (ComponentSerialization): the one
|
||||
/// built through the constructors, else the spans as literal siblings.
|
||||
/// The key of a `Component.translatable` built through [`Text::translate`].
|
||||
pub fn translation_key(&self) -> Option<&str> {
|
||||
self.source.as_deref()?.get("translate")?.as_str()
|
||||
}
|
||||
pub fn component(&self) -> Value {
|
||||
if let Some(c) = &self.source {
|
||||
return (**c).clone();
|
||||
}
|
||||
let span = |s: &Span| {
|
||||
let mut o = Map::new();
|
||||
o.insert("text".into(), s.text.clone().into());
|
||||
o.extend(style_json(&s.style));
|
||||
Value::Object(o)
|
||||
};
|
||||
match self.spans.as_slice() {
|
||||
[] => json!({ "text": "" }),
|
||||
[one] => span(one),
|
||||
many => json!({ "text": "", "extra": many.iter().map(span).collect::<Vec<_>>() }),
|
||||
}
|
||||
}
|
||||
/// A translation argument: vanilla passes numbers as numbers, which
|
||||
/// Horizon formats into unstyled literals.
|
||||
fn argument(&self) -> Value {
|
||||
let c = self.component();
|
||||
match c
|
||||
.as_object()
|
||||
.and_then(|o| o.get("text").filter(|_| o.len() == 1))
|
||||
{
|
||||
Some(Value::String(s)) if s.parse::<i64>().is_ok_and(|n| n.to_string() == *s) => {
|
||||
s.parse::<i64>().map_or(c.clone(), Value::from)
|
||||
}
|
||||
_ => c,
|
||||
}
|
||||
}
|
||||
/// Style fields the spans don't model (an entity hover, an insertion),
|
||||
/// set on the component sent to vanilla only.
|
||||
pub fn with_component_fields(mut self, fields: Vec<(String, Value)>) -> Self {
|
||||
let mut c = self.component();
|
||||
if let Value::Object(o) = &mut c {
|
||||
for (k, v) in fields {
|
||||
o.entry(k).or_insert(v);
|
||||
}
|
||||
}
|
||||
self.source = Some(c.into());
|
||||
self
|
||||
}
|
||||
/// The same spans, sent to vanilla as `component` (a shape the spans'
|
||||
/// own JSON would not take, such as a styled root with siblings).
|
||||
pub fn with_component(mut self, component: Value) -> Self {
|
||||
self.source = Some(component.into());
|
||||
self
|
||||
}
|
||||
pub fn with_color(self, color: u32) -> Self {
|
||||
self.with_style(&Style::color(color))
|
||||
}
|
||||
pub fn italic(self) -> Self {
|
||||
self.with_style(&Style {
|
||||
italic: Some(true),
|
||||
..Style::default()
|
||||
})
|
||||
}
|
||||
pub fn underlined(self) -> Self {
|
||||
self.with_style(&Style {
|
||||
underlined: Some(true),
|
||||
..Style::default()
|
||||
})
|
||||
}
|
||||
pub fn bold(self) -> Self {
|
||||
self.with_style(&Style {
|
||||
bold: Some(true),
|
||||
..Style::default()
|
||||
})
|
||||
}
|
||||
/// Component.getString: the plain characters.
|
||||
pub fn plain(&self) -> String {
|
||||
self.spans.iter().map(|s| s.text.as_str()).collect()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.spans.iter().all(|s| s.text.is_empty())
|
||||
}
|
||||
/// Parse legacy formatting codes (`§a`, `§l`, `§r`...) as the font does.
|
||||
pub fn legacy(s: &str) -> Self {
|
||||
let mut out = Text::default();
|
||||
let mut style = Style::default();
|
||||
let mut current = String::new();
|
||||
let mut chars = s.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c != '§' {
|
||||
current.push(c);
|
||||
continue;
|
||||
}
|
||||
let Some(code) = chars.next() else { break };
|
||||
if !current.is_empty() {
|
||||
out.spans.push(Span {
|
||||
text: std::mem::take(&mut current),
|
||||
style: style.clone(),
|
||||
});
|
||||
}
|
||||
let code = code.to_ascii_lowercase();
|
||||
if let Some(c) = COLORS.iter().find(|c| c.0 == code) {
|
||||
// Colour codes reset decorations (Style.applyLegacyFormat).
|
||||
style = Style::color(c.2);
|
||||
} else {
|
||||
match code {
|
||||
'k' => style.obfuscated = Some(true),
|
||||
'l' => style.bold = Some(true),
|
||||
'm' => style.strikethrough = Some(true),
|
||||
'n' => style.underlined = Some(true),
|
||||
'o' => style.italic = Some(true),
|
||||
'r' => style = Style::default(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !current.is_empty() {
|
||||
out.spans.push(Span {
|
||||
text: current,
|
||||
style,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `StringDecomposer.iterateFormatted` on every span: legacy `§` codes
|
||||
/// inside the span contents restyle what follows them (colour codes
|
||||
/// clear the decorations, `§r` returns to the span's own style) and are
|
||||
/// not drawn.
|
||||
pub fn resolve_legacy(&self) -> Text {
|
||||
if !self.spans.iter().any(|s| s.text.contains('§')) {
|
||||
return self.clone();
|
||||
}
|
||||
let mut out = Text::default();
|
||||
for span in &self.spans {
|
||||
let mut style = span.style.clone();
|
||||
let mut current = String::new();
|
||||
let mut chars = span.text.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c != '§' {
|
||||
current.push(c);
|
||||
continue;
|
||||
}
|
||||
let Some(code) = chars.next() else { break };
|
||||
let code = code.to_ascii_lowercase();
|
||||
let next = if let Some(c) = COLORS.iter().find(|c| c.0 == code) {
|
||||
// Style.applyLegacyFormat: a colour clears the decorations.
|
||||
Style {
|
||||
color: Some(c.2),
|
||||
bold: Some(false),
|
||||
italic: Some(false),
|
||||
underlined: Some(false),
|
||||
strikethrough: Some(false),
|
||||
obfuscated: Some(false),
|
||||
..style.clone()
|
||||
}
|
||||
} else {
|
||||
let mut s = style.clone();
|
||||
match code {
|
||||
'k' => s.obfuscated = Some(true),
|
||||
'l' => s.bold = Some(true),
|
||||
'm' => s.strikethrough = Some(true),
|
||||
'n' => s.underlined = Some(true),
|
||||
'o' => s.italic = Some(true),
|
||||
'r' => s = span.style.clone(),
|
||||
_ => {}
|
||||
}
|
||||
s
|
||||
};
|
||||
if next != style {
|
||||
if !current.is_empty() {
|
||||
out.spans.push(Span {
|
||||
text: std::mem::take(&mut current),
|
||||
style: style.clone(),
|
||||
});
|
||||
}
|
||||
style = next;
|
||||
}
|
||||
}
|
||||
if !current.is_empty() {
|
||||
out.spans.push(Span {
|
||||
text: current,
|
||||
style,
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `resolve_legacy` borrowing `self` when no span holds a `§` code (the
|
||||
/// common case).
|
||||
pub fn resolved(&self) -> std::borrow::Cow<'_, Text> {
|
||||
if self.spans.iter().any(|s| s.text.contains('§')) {
|
||||
std::borrow::Cow::Owned(self.resolve_legacy())
|
||||
} else {
|
||||
std::borrow::Cow::Borrowed(self)
|
||||
}
|
||||
}
|
||||
/// The text without its legacy `§` codes (ChatFormatting.stripFormatting:
|
||||
/// a `§` and a code character, `0`-`9`, `a`-`f`, `k`-`o` or `r`).
|
||||
pub fn strip_legacy(&self) -> Text {
|
||||
if !self.spans.iter().any(|s| s.text.contains('§')) {
|
||||
return self.clone();
|
||||
}
|
||||
let code =
|
||||
|c: char| matches!(c.to_ascii_lowercase(), '0'..='9' | 'a'..='f' | 'k'..='o' | 'r');
|
||||
let mut out = Text::default();
|
||||
for span in &self.spans {
|
||||
let mut text = String::with_capacity(span.text.len());
|
||||
let mut chars = span.text.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '§' && chars.peek().is_some_and(|&n| code(n)) {
|
||||
chars.next();
|
||||
} else {
|
||||
text.push(c);
|
||||
}
|
||||
}
|
||||
if !text.is_empty() {
|
||||
out.spans.push(Span {
|
||||
text,
|
||||
style: span.style.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Characters with their effective styles.
|
||||
pub fn chars(&self) -> impl Iterator<Item = (char, &Style)> {
|
||||
self.spans
|
||||
.iter()
|
||||
.flat_map(|s| s.text.chars().map(move |c| (c, &s.style)))
|
||||
}
|
||||
/// Sub-range of characters [from, to) keeping styles.
|
||||
pub fn slice(&self, from: usize, to: usize) -> Text {
|
||||
let mut out = Text::default();
|
||||
let mut index = 0;
|
||||
for span in &self.spans {
|
||||
let mut part = String::new();
|
||||
for c in span.text.chars() {
|
||||
if index >= from && index < to {
|
||||
part.push(c);
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
if !part.is_empty() {
|
||||
out.spans.push(Span {
|
||||
text: part,
|
||||
style: span.style.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The style fields of a component's JSON.
|
||||
const STYLE_KEYS: [&str; 9] = [
|
||||
"color",
|
||||
"bold",
|
||||
"italic",
|
||||
"underlined",
|
||||
"strikethrough",
|
||||
"obfuscated",
|
||||
"click_event",
|
||||
"hover_event",
|
||||
"font",
|
||||
];
|
||||
/// Style.Serializer: the fields a style sets.
|
||||
fn style_json(style: &Style) -> Vec<(String, Value)> {
|
||||
let mut out = Vec::new();
|
||||
if let Some(c) = style.color {
|
||||
let name = COLORS
|
||||
.iter()
|
||||
.find(|n| n.2 == c)
|
||||
.map_or_else(|| format!("#{c:06X}"), |n| n.1.to_owned());
|
||||
out.push(("color".to_owned(), name.into()));
|
||||
}
|
||||
for (key, flag) in [
|
||||
("bold", style.bold),
|
||||
("italic", style.italic),
|
||||
("underlined", style.underlined),
|
||||
("strikethrough", style.strikethrough),
|
||||
("obfuscated", style.obfuscated),
|
||||
] {
|
||||
if let Some(f) = flag {
|
||||
out.push((key.to_owned(), f.into()));
|
||||
}
|
||||
}
|
||||
if let Some(click) = &style.click {
|
||||
let event = match click {
|
||||
ClickEvent::OpenUrl(url) => json!({ "action": "open_url", "url": url }),
|
||||
ClickEvent::ChangePage(page) => json!({ "action": "change_page", "page": page }),
|
||||
ClickEvent::SuggestCommand(command) => {
|
||||
json!({ "action": "suggest_command", "command": command })
|
||||
}
|
||||
ClickEvent::CopyToClipboard(value) => {
|
||||
json!({ "action": "copy_to_clipboard", "value": value })
|
||||
}
|
||||
ClickEvent::OpenFile(path) => json!({ "action": "open_file", "path": path }),
|
||||
};
|
||||
out.push(("click_event".to_owned(), event));
|
||||
}
|
||||
if let Some(hover) = &style.hover {
|
||||
out.push((
|
||||
"hover_event".to_owned(),
|
||||
json!({ "action": "show_text", "value": hover.component() }),
|
||||
));
|
||||
}
|
||||
if let Some(font) = &style.font {
|
||||
out.push(("font".to_owned(), font.clone().into()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// TranslatableContents.decomposeTemplate: `%s` takes the next argument,
|
||||
/// `%n$s` a numbered one and `%%` is a percent sign. Malformed templates are
|
||||
/// shown verbatim.
|
||||
pub fn format_translation(template: &str, args: &[Text]) -> Text {
|
||||
let mut out = Text::default();
|
||||
let mut literal = String::new();
|
||||
let mut next = 0usize;
|
||||
let chars: Vec<char> = template.chars().collect();
|
||||
let mut i = 0;
|
||||
while i < chars.len() {
|
||||
if chars[i] != '%' {
|
||||
literal.push(chars[i]);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// %(?:(\d+)\$)?([A-Za-z%]|$)
|
||||
let mut j = i + 1;
|
||||
let mut number = None;
|
||||
let digits_start = j;
|
||||
while j < chars.len() && chars[j].is_ascii_digit() {
|
||||
j += 1;
|
||||
}
|
||||
if j > digits_start && j < chars.len() && chars[j] == '$' {
|
||||
number = chars[digits_start..j]
|
||||
.iter()
|
||||
.collect::<String>()
|
||||
.parse::<usize>()
|
||||
.ok();
|
||||
j += 1;
|
||||
} else {
|
||||
j = digits_start;
|
||||
}
|
||||
let conversion = chars.get(j).copied();
|
||||
match conversion {
|
||||
Some('%') if number.is_none() => {
|
||||
literal.push('%');
|
||||
i = j + 1;
|
||||
}
|
||||
// Not a format specifier at all: the percent sign is literal.
|
||||
Some(c) if !c.is_ascii_alphabetic() && c != '%' => {
|
||||
literal.push('%');
|
||||
i += 1;
|
||||
}
|
||||
Some('s') => {
|
||||
let index = match number {
|
||||
Some(n) => n.wrapping_sub(1),
|
||||
None => {
|
||||
next += 1;
|
||||
next - 1
|
||||
}
|
||||
};
|
||||
let Some(arg) = args.get(index) else {
|
||||
return Text::literal(template);
|
||||
};
|
||||
if !literal.is_empty() {
|
||||
out.spans.push(Span {
|
||||
text: std::mem::take(&mut literal),
|
||||
style: Style::default(),
|
||||
});
|
||||
}
|
||||
out.spans.extend(arg.spans.iter().cloned());
|
||||
i = j + 1;
|
||||
}
|
||||
_ => return Text::literal(template),
|
||||
}
|
||||
}
|
||||
if !literal.is_empty() {
|
||||
out.spans.push(Span {
|
||||
text: literal,
|
||||
style: Style::default(),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn click_events_serialize_and_inherit_as_one_style_field() {
|
||||
for (event, json) in [
|
||||
(
|
||||
ClickEvent::SuggestCommand("/seed".into()),
|
||||
json!({"action": "suggest_command", "command": "/seed"}),
|
||||
),
|
||||
(
|
||||
ClickEvent::CopyToClipboard("-9223372036854775808".into()),
|
||||
json!({"action": "copy_to_clipboard", "value": "-9223372036854775808"}),
|
||||
),
|
||||
(
|
||||
ClickEvent::OpenFile("/tmp/My screenshots/世界.png".into()),
|
||||
json!({"action": "open_file", "path": "/tmp/My screenshots/世界.png"}),
|
||||
),
|
||||
] {
|
||||
let style = Style {
|
||||
click: Some(event.clone()),
|
||||
..Style::default()
|
||||
};
|
||||
let text = Text::literal("link").with_style(&style);
|
||||
assert_eq!(text.component()["click_event"], json);
|
||||
assert_eq!(text.spans[0].style.click, Some(event));
|
||||
let child = Text::copyable("42").with_style(&style);
|
||||
assert_eq!(
|
||||
child.spans[1].style.click,
|
||||
Some(ClickEvent::CopyToClipboard("42".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
child.component()["extra"][0]["click_event"],
|
||||
json!({"action": "copy_to_clipboard", "value": "42"})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_like_translatable_contents() {
|
||||
let a = [Text::literal("Steve"), Text::colored("Zombie", RED)];
|
||||
assert_eq!(
|
||||
format_translation("%s was slain by %s", &a).plain(),
|
||||
"Steve was slain by Zombie"
|
||||
);
|
||||
assert_eq!(
|
||||
format_translation("%2$s then %1$s", &a).plain(),
|
||||
"Zombie then Steve"
|
||||
);
|
||||
assert_eq!(
|
||||
format_translation("100%% sure %s", &a).plain(),
|
||||
"100% sure Steve"
|
||||
);
|
||||
// Missing arguments or unknown conversions show the template.
|
||||
assert_eq!(format_translation("%s %s %s", &a).plain(), "%s %s %s");
|
||||
assert_eq!(format_translation("%d", &a).plain(), "%d");
|
||||
assert_eq!(
|
||||
format_translation("50% off %s", &a).plain(),
|
||||
"50% off Steve"
|
||||
);
|
||||
assert_eq!(format_translation("end %", &a).plain(), "end %");
|
||||
let t = format_translation("%s was slain by %s", &a);
|
||||
assert_eq!(t.spans.last().unwrap().style.color, Some(RED));
|
||||
}
|
||||
#[test]
|
||||
fn legacy_codes_and_inheritance() {
|
||||
let t = Text::legacy("§aGreen §lbold§r plain");
|
||||
assert_eq!(t.plain(), "Green bold plain");
|
||||
assert_eq!(t.spans[0].style.color, Some(GREEN));
|
||||
assert!(t.spans[1].style.is_bold());
|
||||
assert_eq!(t.spans[2].style, Style::default());
|
||||
let t = Text::literal("x")
|
||||
.append(Text::colored("y", GOLD))
|
||||
.with_color(RED);
|
||||
assert_eq!(t.spans[0].style.color, Some(RED));
|
||||
assert_eq!(t.spans[1].style.color, Some(GOLD));
|
||||
assert_eq!(t.slice(1, 2).plain(), "y");
|
||||
}
|
||||
#[test]
|
||||
fn resolved_borrows_clean_text_and_restyles_codes() {
|
||||
let clean = Text::colored("Steve", GOLD);
|
||||
assert!(matches!(clean.resolved(), std::borrow::Cow::Borrowed(_)));
|
||||
// A colour code inside a span clears its decorations (a bold
|
||||
// "§cSteve" draws "Steve" red, not bold).
|
||||
let styled = Style {
|
||||
bold: Some(true),
|
||||
..Style::default()
|
||||
};
|
||||
let styled = Text::styled("§cSteve", styled);
|
||||
let resolved = styled.resolved();
|
||||
assert_eq!(resolved.plain(), "Steve");
|
||||
assert_eq!(resolved.spans[0].style.color, Some(RED));
|
||||
assert_eq!(resolved.spans[0].style.bold, Some(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//! UUIDs as vanilla's four-int form, to and from their text form.
|
||||
|
||||
pub fn uuid_text(u: [i32; 4]) -> String {
|
||||
let hex: String = u.iter().map(|v| format!("{:08x}", *v as u32)).collect();
|
||||
format!(
|
||||
"{}-{}-{}-{}-{}",
|
||||
&hex[0..8],
|
||||
&hex[8..12],
|
||||
&hex[12..16],
|
||||
&hex[16..20],
|
||||
&hex[20..32]
|
||||
)
|
||||
}
|
||||
pub fn uuid_from_text(s: &str) -> Option<[i32; 4]> {
|
||||
let hex: String = s.chars().filter(|c| *c != '-').collect();
|
||||
if hex.len() != 32 {
|
||||
return None;
|
||||
}
|
||||
let mut out = [0i32; 4];
|
||||
for (i, v) in out.iter_mut().enumerate() {
|
||||
*v = u32::from_str_radix(&hex[i * 8..i * 8 + 8], 16).ok()? as i32;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
Reference in New Issue
Block a user