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:
Ludovic Marie
2026-10-27 03:38:18 +01:00
192 changed files with 10457 additions and 1048 deletions
+2
View File
@@ -9,6 +9,8 @@ description = "Horizon native development client"
[dependencies]
horizon-assets = { path = "../horizon-assets" }
horizon-client-core = { path = "../horizon-client-core" }
horizon-command = { path = "../horizon-command" }
horizon-core = { path = "../horizon-core" }
# The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority).
horizon-threads = { path = "../horizon-threads" }
+24 -1
View File
@@ -1,7 +1,7 @@
//! Biome colours from the pinned biome definitions and colormaps
//! (`Biome.getGrassColor`/`getFoliageColor`/..., `BlockTintSources`).
use crate::Result;
use horizon_core::{noise::SimplexNoise, random::LegacyRandom};
use horizon_core::{noise::SimplexNoise, position::BlockPos, random::LegacyRandom};
use serde_json::Value;
use std::{collections::HashMap, fs, path::Path};
@@ -33,6 +33,8 @@ pub struct BiomeInfo {
pub increased_fire_burnout: bool,
pub name: String,
pub temperature: f32,
/// `temperature_modifier: frozen` (the frozen oceans).
pub frozen: bool,
pub downfall: f32,
pub precipitation: bool,
pub grass: u32,
@@ -45,6 +47,26 @@ pub struct BiomeInfo {
pub fog: Option<u32>,
pub water_fog: u32,
}
impl BiomeInfo {
/// `Biome.getHeightAdjustedTemperature`: the frozen modifier, then cooler
/// with height above `sea_level + 17`.
pub fn temperature_at(&self, pos: BlockPos, sea_level: i32) -> f32 {
use horizon_world::worldgen::biome_temperature::{
BiomeTemperatureSettings, TemperatureModifier,
};
BiomeTemperatureSettings {
base_temperature: self.temperature,
modifier: if self.frozen {
TemperatureModifier::Frozen
} else {
TemperatureModifier::None
},
has_precipitation: self.precipitation,
downfall: self.downfall,
}
.height_adjusted(pos, sea_level)
}
}
pub struct Biomes {
pub list: Vec<BiomeInfo>,
pub index: HashMap<String, u16>,
@@ -135,6 +157,7 @@ impl Biomes {
.as_bool()
.unwrap_or(false),
temperature,
frozen: v["temperature_modifier"].as_str() == Some("frozen"),
downfall,
precipitation: v["has_precipitation"].as_bool().unwrap_or(true),
grass: color(&effects["grass_color"])
@@ -1,973 +0,0 @@
//! 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(crate) 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, &current);
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, &current);
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)));
}
}
-218
View File
@@ -1,218 +0,0 @@
//! 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());
}
}
File diff suppressed because it is too large Load Diff
-460
View File
@@ -1,460 +0,0 @@
//! BlockStateParser: block states (`stone`, `oak_stairs[facing=up]{...}`)
//! and block predicates (`#logs[axis=y]`), with vanilla's suggestions.
use super::args::{BlockInput, Registries, read_identifier, suggest_resources};
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
#[derive(Clone, Debug)]
enum Sugg {
Nothing,
Item,
BlockIdOrTag,
Tag,
OpenVaguePropertiesOrNbt,
OpenNbt,
OpenPropertiesOrNbt,
PropertyNameOrEnd,
VaguePropertyNameOrEnd,
PropertyName,
VaguePropertyName,
Equals,
PropertyValues(String),
NextPropertyOrEnd,
VaguePropertyValue(String),
}
type Props = Vec<(String, Vec<String>)>;
pub struct BlockParser<'r, 'a> {
reader: &'r mut Reader<'a>,
reg: &'r Registries,
for_testing: bool,
allow_nbt: bool,
id: String,
/// The block's state definition (properties and values).
definition: Option<&'r Props>,
properties: Vec<(String, String)>,
vague: Vec<(String, String)>,
tag: Option<String>,
nbt: Option<String>,
sugg: Sugg,
}
fn is_int_property(values: &[String]) -> bool {
!values.is_empty() && values.iter().all(|v| v.parse::<i32>().is_ok())
}
/// Property.getValue.
fn property_value(values: &[String], raw: &str) -> Option<String> {
if is_int_property(values) {
let v: i32 = super::args::java_parse_int(raw)?;
let s = v.to_string();
return values.contains(&s).then_some(s);
}
values.iter().any(|v| v == raw).then(|| raw.to_owned())
}
/// addSuggestions: every value (integers as integer suggestions).
fn add_values(builder: &mut SuggestionsBuilder, values: &[String]) {
let ints = is_int_property(values);
for v in values {
if ints {
builder.suggest_int(v.parse().unwrap_or(0));
} else {
builder.suggest(v.clone());
}
}
}
impl<'r, 'a> BlockParser<'r, 'a> {
pub fn new(
reader: &'r mut Reader<'a>,
reg: &'r Registries,
for_testing: bool,
allow_nbt: bool,
) -> Self {
Self {
reader,
reg,
for_testing,
allow_nbt,
id: "minecraft:".into(),
definition: None,
properties: Vec::new(),
vague: Vec::new(),
tag: None,
nbt: None,
sugg: Sugg::Nothing,
}
}
fn tag_members(&self) -> &'r [String] {
match &self.tag {
Some(t) => self
.reg
.block_tag_members
.get(t)
.map(Vec::as_slice)
.unwrap_or(&[]),
None => &[],
}
}
fn block_props(&self, id: &str) -> &'r [(String, Vec<String>)] {
self.reg.blocks.get(id).map(Vec::as_slice).unwrap_or(&[])
}
pub fn parse(&mut self) -> CmdResult<BlockInput> {
self.sugg = if self.for_testing {
Sugg::BlockIdOrTag
} else {
Sugg::Item
};
if self.reader.can_read() && self.reader.peek() == '#' {
self.read_tag()?;
self.sugg = Sugg::OpenVaguePropertiesOrNbt;
if self.reader.can_read() && self.reader.peek() == '[' {
self.read_vague_properties()?;
self.sugg = Sugg::OpenNbt;
}
} else {
self.read_block()?;
self.sugg = Sugg::OpenPropertiesOrNbt;
if self.reader.can_read() && self.reader.peek() == '[' {
self.read_properties()?;
self.sugg = Sugg::OpenNbt;
}
}
if self.allow_nbt && self.reader.can_read() && self.reader.peek() == '{' {
self.sugg = Sugg::Nothing;
let start = self.reader.cursor;
super::snbt::parse_compound_argument(self.reader)?;
self.nbt = Some(self.reader.string[start..self.reader.cursor].to_owned());
}
let (id, properties) = match &self.tag {
Some(t) => (t.clone(), self.vague.clone()),
None => (self.id.clone(), self.properties.clone()),
};
Ok(BlockInput {
id,
properties,
tag: self.tag.is_some(),
nbt: self.nbt.clone(),
})
}
fn read_block(&mut self) -> CmdResult<()> {
let start = self.reader.cursor;
self.id = read_identifier(self.reader)?;
match self.reg.blocks.get(&self.id) {
Some(props) => {
self.definition = Some(props);
Ok(())
}
None => {
self.reader.cursor = start;
Err(CommandError::tr_at(
"argument.block.id.invalid",
&[&self.id],
self.reader,
))
}
}
}
fn read_tag(&mut self) -> CmdResult<()> {
if !self.for_testing {
return Err(CommandError::tr_at(
"argument.block.tag.disallowed",
&[],
self.reader,
));
}
let start = self.reader.cursor;
self.reader.expect('#')?;
self.sugg = Sugg::Tag;
let id = read_identifier(self.reader)?;
if !self.reg.tags("minecraft:block").contains(&id) {
self.reader.cursor = start;
return Err(CommandError::tr_at(
"arguments.block.tag.unknown",
&[&id],
self.reader,
));
}
self.tag = Some(id);
Ok(())
}
fn read_properties(&mut self) -> CmdResult<()> {
self.reader.skip();
self.sugg = Sugg::PropertyNameOrEnd;
self.reader.skip_whitespace();
let definition = self.definition.map(Vec::as_slice).unwrap_or(&[]);
while self.reader.can_read() && self.reader.peek() != ']' {
self.reader.skip_whitespace();
let key_start = self.reader.cursor;
let key = self.reader.read_string()?;
let Some((_, values)) = definition.iter().find(|(n, _)| *n == key) else {
self.reader.cursor = key_start;
return Err(CommandError::tr_at(
"argument.block.property.unknown",
&[&self.id, &key],
self.reader,
));
};
if self.properties.iter().any(|(n, _)| *n == key) {
self.reader.cursor = key_start;
return Err(CommandError::tr_at(
"argument.block.property.duplicate",
&[&key, &self.id],
self.reader,
));
}
self.reader.skip_whitespace();
self.sugg = Sugg::Equals;
if !self.reader.can_read() || self.reader.peek() != '=' {
return Err(CommandError::tr_at(
"argument.block.property.novalue",
&[&key, &self.id],
self.reader,
));
}
self.reader.skip();
self.reader.skip_whitespace();
self.sugg = Sugg::PropertyValues(key.clone());
let start = self.reader.cursor;
let raw = self.reader.read_string()?;
match property_value(values, &raw) {
Some(v) => self.properties.push((key, v)),
None => {
self.reader.cursor = start;
return Err(CommandError::tr_at(
"argument.block.property.invalid",
&[&self.id, &raw, &key],
self.reader,
));
}
}
self.sugg = Sugg::NextPropertyOrEnd;
self.reader.skip_whitespace();
if self.reader.can_read() {
if self.reader.peek() != ',' {
if self.reader.peek() != ']' {
return Err(CommandError::tr_at(
"argument.block.property.unclosed",
&[],
self.reader,
));
}
break;
}
self.reader.skip();
self.sugg = Sugg::PropertyName;
}
}
if self.reader.can_read() {
self.reader.skip();
Ok(())
} else {
Err(CommandError::tr_at(
"argument.block.property.unclosed",
&[],
self.reader,
))
}
}
fn read_vague_properties(&mut self) -> CmdResult<()> {
self.reader.skip();
self.sugg = Sugg::VaguePropertyNameOrEnd;
let mut value_start: Option<usize> = None;
self.reader.skip_whitespace();
while self.reader.can_read() && self.reader.peek() != ']' {
self.reader.skip_whitespace();
let key_start = self.reader.cursor;
let key = self.reader.read_string()?;
if self.vague.iter().any(|(n, _)| *n == key) {
self.reader.cursor = key_start;
return Err(CommandError::tr_at(
"argument.block.property.duplicate",
&[&key, &self.id],
self.reader,
));
}
self.reader.skip_whitespace();
if !self.reader.can_read() || self.reader.peek() != '=' {
self.reader.cursor = key_start;
return Err(CommandError::tr_at(
"argument.block.property.novalue",
&[&key, &self.id],
self.reader,
));
}
self.reader.skip();
self.reader.skip_whitespace();
self.sugg = Sugg::VaguePropertyValue(key.clone());
value_start = Some(self.reader.cursor);
let value = self.reader.read_string()?;
self.vague.push((key, value));
self.reader.skip_whitespace();
if self.reader.can_read() {
value_start = None;
if self.reader.peek() != ',' {
if self.reader.peek() != ']' {
return Err(CommandError::tr_at(
"argument.block.property.unclosed",
&[],
self.reader,
));
}
break;
}
self.reader.skip();
self.sugg = Sugg::VaguePropertyName;
}
}
if self.reader.can_read() {
self.reader.skip();
Ok(())
} else {
if let Some(v) = value_start {
self.reader.cursor = v;
}
Err(CommandError::tr_at(
"argument.block.property.unclosed",
&[],
self.reader,
))
}
}
fn has_block_entity(&self) -> bool {
if self.tag.is_none() {
return self.reg.block_entities.contains(&self.id);
}
self.tag_members()
.iter()
.any(|b| self.reg.block_entities.contains(b))
}
pub fn fill_suggestions(&self, builder: &mut SuggestionsBuilder) {
let mut b = builder.offset(self.reader.cursor);
let empty = b.remaining().is_empty();
let definition = self.definition.map(Vec::as_slice).unwrap_or(&[]);
match &self.sugg {
Sugg::Nothing => {}
Sugg::Item => {
let ids: Vec<&String> = self.reg.blocks.keys().collect();
suggest_resources(&mut b, ids, "");
}
Sugg::Tag => suggest_resources(&mut b, self.reg.tags("minecraft:block"), "#"),
Sugg::BlockIdOrTag => {
suggest_resources(&mut b, self.reg.tags("minecraft:block"), "#");
let ids: Vec<&String> = self.reg.blocks.keys().collect();
suggest_resources(&mut b, ids, "");
}
Sugg::OpenVaguePropertiesOrNbt => {
if empty && self.tag.is_some() {
let members = self.tag_members();
if members.iter().any(|m| !self.block_props(m).is_empty()) {
b.suggest("[");
}
if members.iter().any(|m| self.reg.block_entities.contains(m)) {
b.suggest("{");
}
}
}
Sugg::OpenNbt => {
if empty && self.has_block_entity() {
b.suggest("{");
}
}
Sugg::OpenPropertiesOrNbt => {
if empty {
if !definition.is_empty() {
b.suggest("[");
}
if self.reg.block_entities.contains(&self.id) {
b.suggest("{");
}
}
}
Sugg::PropertyNameOrEnd | Sugg::PropertyName => {
if matches!(self.sugg, Sugg::PropertyNameOrEnd) && empty {
b.suggest("]");
}
let prefix = b.remaining_lower();
for (name, _) in definition {
if !self.properties.iter().any(|(n, _)| n == name) && name.starts_with(&prefix)
{
b.suggest(format!("{name}="));
}
}
}
Sugg::VaguePropertyNameOrEnd | Sugg::VaguePropertyName => {
if matches!(self.sugg, Sugg::VaguePropertyNameOrEnd) && empty {
b.suggest("]");
}
let prefix = b.remaining_lower();
for m in self.tag_members() {
for (name, _) in self.block_props(m) {
if !self.vague.iter().any(|(n, _)| n == name) && name.starts_with(&prefix) {
b.suggest(format!("{name}="));
}
}
}
}
Sugg::Equals => {
if empty {
b.suggest("=");
}
}
Sugg::PropertyValues(key) => {
if let Some((_, values)) = definition.iter().find(|(n, _)| n == key) {
add_values(&mut b, values);
}
}
Sugg::NextPropertyOrEnd => {
if empty {
b.suggest("]");
}
if empty && self.properties.len() < definition.len() {
b.suggest(",");
}
}
Sugg::VaguePropertyValue(key) => {
let mut more = false;
for m in self.tag_members() {
let props = self.block_props(m);
if let Some((_, values)) = props.iter().find(|(n, _)| n == key) {
add_values(&mut b, values);
}
if !more {
more = props
.iter()
.any(|(n, _)| !self.vague.iter().any(|(v, _)| v == n));
}
}
if more {
b.suggest(",");
}
b.suggest("]");
}
}
builder.add(b);
}
}
/// BlockStateParser.parseForBlock / parseForTesting (the reader is rewound on errors).
pub fn parse(reader: &mut Reader, reg: &Registries, for_testing: bool) -> CmdResult<BlockInput> {
let cursor = reader.cursor;
let r = BlockParser::new(reader, reg, for_testing, true).parse();
if r.is_err() {
reader.cursor = cursor;
}
r
}
/// BlockStateParser.fillSuggestions.
pub fn suggest(builder: &mut SuggestionsBuilder, reg: &Registries, for_testing: bool) {
let mut reader = Reader {
string: builder.input,
cursor: builder.start,
};
let mut parser = BlockParser::new(&mut reader, reg, for_testing, true);
let _ = parser.parse();
parser.fill_suggestions(builder);
}
-205
View File
@@ -1,205 +0,0 @@
//! ResourceOrIdArgument and the data-fixer-upper decoding of inline values
//! commands accept (loot predicates, item modifiers, slot sources, context
//! providers, dialogs), reproducing the codec error messages vanilla reports.
use super::args::{Registries, is_id_char, parse_identifier};
use super::{CmdResult, CommandError, Reader};
use horizon_world::nbt::{Compound, JavaString, Tag};
pub fn snbt(t: &Tag) -> String {
crate::snbt::to_snbt(t)
}
pub fn not_map(t: &Tag) -> String {
format!("Not a map: {}", snbt(t))
}
pub fn not_list(t: &Tag) -> String {
format!("Not a list: {}", snbt(t))
}
pub fn no_key(key: &str, t: &Tag) -> String {
format!("No key {key} in MapLike[{}]", snbt(t))
}
pub fn either(a: String, b: String) -> String {
format!("Failed to parse either. First: {a}; Second: {b}")
}
pub fn get<'t>(map: &'t Compound, key: &str) -> Option<&'t Tag> {
map.get(&JavaString::from(key))
}
pub fn is_number(t: &Tag) -> bool {
matches!(
t,
Tag::Byte(_) | Tag::Short(_) | Tag::Int(_) | Tag::Long(_) | Tag::Float(_) | Tag::Double(_)
)
}
pub fn as_string(t: &Tag) -> Option<String> {
match t {
Tag::String(s) => Some(s.to_string_lossy()),
_ => None,
}
}
/// KeyDispatchCodec over a type registry: the map, its `type` and the
/// type's own fields (`fields` checks them).
fn dispatch(
t: &Tag,
reg: &Registries,
type_registry: &str,
fields: &dyn Fn(&str, &Compound, &Tag) -> Result<(), String>,
) -> Result<(), String> {
let Tag::Compound(map) = t else {
return Err(not_map(t));
};
let Some(ty) = get(map, "type") else {
return Err(no_key("type", t));
};
let Some(name) = as_string(ty) else {
return Err("Not a string".into());
};
let Some(id) = parse_identifier(&name) else {
return Err(format!("Not a valid resource location: {name}"));
};
let known = reg.ids(type_registry);
if !known.is_empty() && !known.contains(&id) {
return Err(format!(
"Unknown registry key in ResourceKey[minecraft:root / {type_registry}]: {id}"
));
}
fields(&id, map, t)
}
/// Required fields, reported in vanilla's order when missing.
fn require(map: &Compound, t: &Tag, keys: &[&str]) -> Result<(), String> {
let missing: Vec<String> = keys
.iter()
.filter(|k| get(map, k).is_none())
.map(|k| no_key(k, t))
.collect();
if missing.is_empty() {
Ok(())
} else {
Err(missing.join("; "))
}
}
/// The required fields of each context number provider type, in the
/// order DataFixerUpper reports them missing (the reverse of the record's).
fn provider_fields(id: &str, map: &Compound, t: &Tag) -> Result<(), String> {
match id.trim_start_matches("minecraft:") {
"uniform" => require(map, t, &["max", "min"]),
"constant" => require(map, t, &["value"]),
"binomial" => require(map, t, &["p", "n"]),
"add" | "mul" | "avg" | "max" | "min" | "length" => require(map, t, &["inputs"]),
"sub" | "div" | "mod" | "floor_div" | "floor_mod" => require(map, t, &["right", "left"]),
"pow" => require(map, t, &["exponent", "base"]),
"abs" | "negate" | "from_float" | "from_int" | "floor" | "ceil" | "round" | "sqrt"
| "sin" | "cos" | "truncate" => require(map, t, &["input"]),
"conditional" => require(map, t, &["on_true", "condition"]),
"number_dispatcher" => require(map, t, &["cases"]),
"weighted_list" => require(map, t, &["distribution"]),
"enchantment_level" => require(map, t, &["amount"]),
"score" => require(map, t, &["score", "target"]),
_ => Ok(()),
}
}
/// A holder list codec: a single element, a `#tag`, or a list.
fn element_or_list(t: &Tag, element: &dyn Fn(&Tag) -> Result<(), String>) -> Result<(), String> {
let first = match element(t) {
Ok(()) => return Ok(()),
Err(e) => e,
};
let tag_ref = match as_string(t) {
Some(s) if s.starts_with('#') => return Ok(()),
Some(_) => "Not a tag id".to_owned(),
None => "Not a string".to_owned(),
};
let list = match t {
Tag::List(items) => {
let errors: Vec<String> = items.iter().filter_map(|i| element(i).err()).collect();
if errors.is_empty() {
return Ok(());
}
errors.join("; ")
}
_ => not_list(t),
};
let last = element(t).err().unwrap_or_default();
Err(either(first, either(tag_ref, either(list, last))))
}
/// Decode an inline value of a ResourceOrIdArgument registry.
pub fn decode(registry: &str, t: &Tag, reg: &Registries) -> Result<(), String> {
match registry {
"minecraft:context_int_provider" | "minecraft:context_float_provider" => {
if is_number(t) {
return Ok(());
}
let ty = format!("{registry}_type");
let second = dispatch(t, reg, &ty, &provider_fields);
second.map_err(|e| either("Not a number".into(), e))
}
"minecraft:predicate" => {
dispatch(t, reg, "minecraft:loot_condition_type", &|_, _, _| Ok(()))
}
"minecraft:item_modifier" => element_or_list(t, &|x| {
dispatch(x, reg, "minecraft:loot_function_type", &|_, _, _| Ok(()))
}),
"minecraft:slot_source" => element_or_list(t, &|x| {
dispatch(x, reg, "minecraft:slot_source_type", &|_, _, _| Ok(()))
}),
// Dialog types: CommonDialogData's title, then each type's own.
"minecraft:dialog" => dispatch(t, reg, "minecraft:dialog_type", &|id, map, t| {
let own: &[&str] = match id {
"minecraft:confirmation" => &["yes", "no"],
"minecraft:multi_action" => &["actions"],
"minecraft:dialog_list" => &["dialogs"],
_ => &[],
};
let keys: Vec<&str> = std::iter::once("title")
.chain(own.iter().copied())
.collect();
require(map, t, &keys)
}),
"minecraft:worldgen/feature" | "minecraft:loot_table" => match t {
Tag::Compound(_) => Ok(()),
_ => Err(not_map(t)),
},
_ => Ok(()),
}
}
/// Identifier.readNonEmpty (None when empty or invalid).
fn read_non_empty(reader: &mut Reader) -> Option<String> {
let start = reader.cursor;
while reader.can_read() && is_id_char(reader.peek()) {
reader.skip();
}
let raw = &reader.string[start..reader.cursor];
let id = if raw.is_empty() {
None
} else {
parse_identifier(raw)
};
if id.is_none() {
reader.cursor = start;
}
id
}
/// ResourceOrIdArgument.parse: a registry id (checked) or an inline SNBT
/// value decoded with the registry's codec.
pub fn resource_or_id(reader: &mut Reader, reg: &Registries, registry: &str) -> CmdResult<()> {
let start = reader.cursor;
let mut r = reader.clone();
r.skip_whitespace();
if let Some(id) = read_non_empty(&mut r) {
reader.cursor = r.cursor;
if !reg.ids(registry).contains(&id) {
return Err(CommandError::tr_at(
"argument.resource_or_id.no_such_element",
&[&id, &registry],
reader,
));
}
return Ok(());
}
reader.cursor = start;
let tag = super::snbt::parse_tag_argument(reader)?;
decode(registry, &tag, reg)
.map_err(|m| CommandError::tr_at("argument.resource_or_id.failed_to_parse", &[&m], reader))
}
@@ -1,364 +0,0 @@
//! ComponentSerialization.CODEC and Style.Serializer.MAP_CODEC decoding of
//! SNBT text components, with the data-fixer-upper error messages
//! (ComponentArgument, StyleArgument and component-valued item data).
use super::codec::{get, no_key, not_list, not_map};
use horizon_world::nbt::{Compound, Tag};
/// A DataResult error: its message and whether it carries a partial result.
struct E {
msg: String,
partial: bool,
}
type R = Result<(), E>;
fn err(msg: impl Into<String>) -> R {
Err(E {
msg: msg.into(),
partial: false,
})
}
fn partial(msg: impl Into<String>) -> R {
Err(E {
msg: msg.into(),
partial: true,
})
}
/// Codec.either.
fn either(first: R, second: impl FnOnce() -> R) -> R {
let a = match first {
Ok(()) => return Ok(()),
Err(e) => e,
};
let b = match second() {
Ok(()) => return Ok(()),
Err(e) => e,
};
if a.partial {
return Err(a);
}
if b.partial {
return Err(b);
}
err(format!(
"Failed to parse either. First: {}; Second: {}",
a.msg, b.msg
))
}
fn is_string(t: &Tag) -> bool {
matches!(t, Tag::String(_))
}
fn string(t: &Tag) -> R {
if is_string(t) {
Ok(())
} else {
err("Not a string")
}
}
fn string_of(t: &Tag) -> Option<String> {
match t {
Tag::String(s) => Some(s.to_string_lossy()),
_ => None,
}
}
/// ListCodec: element errors (newest first) with the decoded rest as partial.
fn list(t: &Tag, element: &dyn Fn(&Tag) -> R) -> Result<usize, E> {
let Tag::List(items) = t else {
return Err(E {
msg: not_list(t),
partial: false,
});
};
let mut errors: Vec<String> = Vec::new();
let mut ok = 0;
for i in items {
match element(i) {
Ok(()) => ok += 1,
Err(e) => {
if e.partial {
ok += 1;
}
errors.push(e.msg);
}
}
}
if errors.is_empty() {
return Ok(ok);
}
errors.reverse();
Err(E {
msg: errors.join("; "),
partial: true,
})
}
/// ExtraCodecs.nonEmptyList(listOf(element)).
fn non_empty_list(t: &Tag, element: &dyn Fn(&Tag) -> R) -> R {
match list(t, element) {
Ok(0) => err("List must have contents"),
Ok(_) => Ok(()),
Err(e) if !e.partial => Err(e),
Err(e) => {
// The partial result is validated too.
let decoded = match t {
Tag::List(items) => items.iter().filter(|i| element(i).is_ok()).count(),
_ => 0,
};
if decoded == 0 {
err(format!("{}; List must have contents", e.msg))
} else {
Err(e)
}
}
}
}
fn bool_value(t: &Tag) -> R {
if super::codec::is_number(t) {
Ok(())
} else {
err("Not a number")
}
}
/// Identifier.CODEC.
pub fn identifier(t: &Tag) -> Result<(), String> {
let Some(s) = string_of(t) else {
return Err("Not a string".into());
};
let (ns, path) = match s.split_once(':') {
Some(("", p)) => ("minecraft".to_owned(), p.to_owned()),
Some((n, p)) => (n.to_owned(), p.to_owned()),
None => ("minecraft".to_owned(), s.clone()),
};
let ns_ok = ns != ".."
&& ns
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-'));
if !ns_ok {
return Err(format!(
"Not a valid resource location: {s} Non [a-z0-9_.-] character in namespace of location: {ns}:{path}"
));
}
let path_ok = path.chars().all(|c| {
c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/')
});
if !path_ok {
return Err(format!(
"Not a valid resource location: {s} Non [a-z0-9/._-] character in path of location: {ns}:{path}"
));
}
Ok(())
}
/// TextColor.CODEC.
fn color(t: &Tag) -> R {
let Some(s) = string_of(t) else {
return partial("Not a string");
};
if let Some(hex) = s.strip_prefix('#') {
let digits = hex.strip_prefix(['+', '-']).unwrap_or(hex);
let valid = !digits.is_empty() && digits.chars().all(|c| c.is_ascii_hexdigit());
return match i64::from_str_radix(hex, 16) {
Ok(v) if valid && i32::try_from(v).is_ok() => {
if (0..=0xFF_FFFF).contains(&v) {
Ok(())
} else {
partial(format!("Color value out of range: {s}"))
}
}
_ => partial(format!("Invalid color value: {s}")),
};
}
if crate::text::named_color(&s).is_some() {
Ok(())
} else {
partial(format!("Invalid color name: {s}"))
}
}
/// A KeyDispatch over an action enum (`Unknown element name:`), with
/// required fields per action.
fn action_event(t: &Tag, actions: &[(&str, &[&str])]) -> R {
let Tag::Compound(map) = t else {
return partial(not_map(t));
};
let Some(action) = get(map, "action") else {
return partial(no_key("action", t));
};
let Some(name) = string_of(action) else {
return partial("Not a string");
};
let Some((_, fields)) = actions.iter().find(|(a, _)| *a == name) else {
return partial(format!("Unknown element name:{name}"));
};
for f in *fields {
if get(map, f).is_none() {
return partial(no_key(f, t));
}
}
Ok(())
}
const CLICK_ACTIONS: &[(&str, &[&str])] = &[
("open_url", &["url"]),
("open_file", &["path"]),
("run_command", &["command"]),
("suggest_command", &["command"]),
("show_dialog", &["dialog"]),
("change_page", &["page"]),
("copy_to_clipboard", &["value"]),
("custom", &["id"]),
];
const HOVER_ACTIONS: &[(&str, &[&str])] = &[
("show_text", &["value"]),
("show_item", &["id"]),
("show_entity", &["id", "uuid"]),
];
/// Style.Serializer.MAP_CODEC (every field optional; errors keep a partial style).
fn style_fields(map: &Compound) -> R {
if let Some(c) = get(map, "color") {
color(c)?;
}
for key in [
"bold",
"italic",
"underlined",
"strikethrough",
"obfuscated",
] {
if let Some(v) = get(map, key)
&& bool_value(v).is_err()
{
return partial("Not a number");
}
}
if let Some(v) = get(map, "click_event") {
action_event(v, CLICK_ACTIONS)?;
}
if let Some(v) = get(map, "hover_event") {
action_event(v, HOVER_ACTIONS)?;
}
if let Some(v) = get(map, "insertion")
&& !is_string(v)
{
return partial("Not a string");
}
if let Some(v) = get(map, "font")
&& let Err(m) = identifier(v)
{
return partial(m);
}
Ok(())
}
fn selector_string(t: &Tag) -> bool {
let Some(s) = string_of(t) else { return false };
let reg = super::args::Registries {
permission: 4,
..Default::default()
};
let mut r = super::Reader::new(&s);
super::selector::parse(&mut r, &reg, true).is_ok() && !r.can_read()
}
fn optional_component(map: &Compound, key: &str) -> bool {
get(map, key).is_none_or(|v| component(v).is_ok())
}
/// The content codecs (PlainText, Translatable, Keybind, Score, Selector, Nbt, Object).
fn content(kind: &str, map: &Compound) -> bool {
match kind {
"text" => get(map, "text").is_some_and(is_string),
"translatable" => {
get(map, "translate").is_some_and(is_string)
&& get(map, "fallback").is_none_or(is_string)
&& get(map, "with").is_none_or(|w| matches!(w, Tag::List(_)))
}
"keybind" => get(map, "keybind").is_some_and(is_string),
"score" => match get(map, "score") {
Some(Tag::Compound(s)) => {
get(s, "name").is_some_and(is_string) && get(s, "objective").is_some_and(is_string)
}
_ => false,
},
"selector" => {
get(map, "selector").is_some_and(selector_string)
&& optional_component(map, "separator")
}
"nbt" => {
let path_ok = get(map, "nbt")
.and_then(string_of)
.is_some_and(|p| crate::nbt_path::NbtPath::parse(&p).is_ok());
let source = if let Some(e) = get(map, "entity") {
selector_string(e)
} else if let Some(b) = get(map, "block") {
string_of(b).is_some_and(|s| {
let reg = super::args::Registries::default();
let mut r = super::Reader::new(&s);
super::ArgType::BlockPos.parse(&mut r, &reg).is_ok() && !r.can_read()
})
} else if let Some(s) = get(map, "storage") {
identifier(s).is_ok()
} else {
false
};
path_ok && source && optional_component(map, "separator")
}
"object" => {
let kind = get(map, "object").and_then(string_of);
let atlas = || {
get(map, "sprite").is_some_and(|s| identifier(s).is_ok())
&& get(map, "atlas").is_none_or(|a| identifier(a).is_ok())
};
let player = || get(map, "player").is_some();
match kind.as_deref() {
Some("atlas") => atlas(),
Some("player") => player(),
Some(_) => false,
None => atlas() || player(),
}
}
_ => false,
}
}
const CONTENT_TYPES: [&str; 7] = [
"text",
"translatable",
"keybind",
"score",
"selector",
"nbt",
"object",
];
fn full(t: &Tag) -> R {
let Tag::Compound(map) = t else {
return err(not_map(t));
};
let contents_ok = if let Some(ty) = get(map, "type") {
let Some(name) = string_of(ty) else {
return err("Not a string");
};
if !CONTENT_TYPES.contains(&name.as_str()) {
return err(format!("Unknown element id: {name}"));
}
content(&name, map)
} else {
CONTENT_TYPES.iter().any(|k| content(k, map))
};
if !contents_ok {
return err("No matching codec found");
}
if let Some(extra) = get(map, "extra") {
match non_empty_list(extra, &component) {
Ok(()) => {}
Err(e) => return partial(e.msg),
}
}
style_fields(map)
}
fn component(t: &Tag) -> R {
either(either(string(t), || non_empty_list(t, &component)), || {
full(t)
})
}
/// ComponentSerialization.CODEC.parse: the error message on failure.
pub fn decode(t: &Tag) -> Result<(), String> {
component(t).map_err(|e| e.msg)
}
/// Style.Serializer.CODEC.parse.
pub fn decode_style(t: &Tag) -> Result<(), String> {
match t {
Tag::Compound(map) => style_fields(map).map_err(|e| e.msg),
_ => Err(not_map(t)),
}
}
-657
View File
@@ -1,657 +0,0 @@
//! ItemParser (item stacks with components, `stone[damage=5]`) and
//! ItemPredicateArgument (ComponentPredicateParser's packrat grammar:
//! `#logs[count~1..|!damage]`), with vanilla's errors and suggestions.
use super::args::{
ItemInput, Registries, is_id_char, parse_identifier, read_identifier, suggest_resources,
};
use super::codec::{either, is_number, not_map, snbt};
use super::packrat::{Grammar, Reason, State, Sugg, Term, Value, alt, ch, opt, seq};
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
use horizon_world::nbt::Tag;
use std::rc::Rc;
fn int_of(t: &Tag) -> Option<i64> {
Some(match t {
Tag::Byte(v) => i64::from(*v),
Tag::Short(v) => i64::from(*v),
Tag::Int(v) => i64::from(*v),
Tag::Long(v) => *v as i32 as i64,
Tag::Float(v) => f32::from_bits(*v) as i32 as i64,
Tag::Double(v) => f64::from_bits(*v) as i32 as i64,
_ => return None,
})
}
/// The codecs of the item components commands commonly set.
pub fn decode_component(id: &str, t: &Tag) -> Result<(), String> {
match id {
"minecraft:damage" | "minecraft:repair_cost" => {
let v = int_of(t).ok_or("Not a number")?;
if v < 0 {
return Err(format!("Value must be non-negative: {v}"));
}
Ok(())
}
"minecraft:max_damage" => {
let v = int_of(t).ok_or("Not a number")?;
if v <= 0 {
return Err(format!("Value must be positive: {v}"));
}
Ok(())
}
"minecraft:max_stack_size" => {
let v = int_of(t).ok_or("Not a number")?;
if !(1..=99).contains(&v) {
return Err(format!("Value must be within range [1;99]: {v}"));
}
Ok(())
}
"minecraft:rarity" => match t {
Tag::String(s) => {
let s = s.to_string_lossy();
if ["common", "uncommon", "rare", "epic"].contains(&s.as_str()) {
Ok(())
} else {
Err(format!("Unknown element name:{s}"))
}
}
_ => Err("Not a string".into()),
},
"minecraft:enchantments" | "minecraft:stored_enchantments" => match t {
Tag::Compound(_) => Ok(()),
_ => Err(not_map(t)),
},
"minecraft:custom_name" | "minecraft:item_name" => super::component::decode(t),
// TypedEntityData.codec: the type is the compound's id.
"minecraft:block_entity_data" => match t {
Tag::Compound(c) => match c.get(&"id".into()) {
None => Err(format!("Expected 'id' field in {}", snbt(t))),
Some(Tag::String(id)) => {
let id = id.to_string_lossy();
let id = if id.contains(':') {
id
} else {
format!("minecraft:{id}")
};
let known = crate::block_entity_nbt::TYPES
.iter()
.chain(&crate::block_entity_nbt::NEWEST)
.any(|k| *k == id);
if known {
Ok(())
} else {
Err(format!(
"Unknown registry key in ResourceKey[minecraft:root / minecraft:block_entity_type]: {id}"
))
}
}
Some(_) => Ok(()),
},
_ => Ok(()),
},
_ => Ok(()),
}
}
/// MinMaxBounds.Ints.CODEC.
fn int_bounds(t: &Tag) -> Result<(), String> {
match t {
Tag::Compound(_) => Ok(()),
_ if is_number(t) => Ok(()),
_ => Err(either(not_map(t), "Not a number".into())),
}
}
/// DataComponentPredicate type codecs.
pub fn decode_predicate(id: &str, t: &Tag) -> Result<(), String> {
match id {
"minecraft:count" => int_bounds(t),
"minecraft:damage" => match t {
Tag::Compound(_) => Ok(()),
_ => Err(not_map(t)),
},
_ => Ok(()),
}
}
// ---- ItemParser -------------------------------------------------------
#[derive(Clone, Copy, Debug)]
enum ISugg {
Nothing,
Item,
StartComponents,
ComponentAssignmentOrRemoval,
Component,
Assignment,
NextOrEndComponents,
}
struct ItemState<'r, 'a> {
reader: &'r mut Reader<'a>,
reg: &'r Registries,
sugg: ISugg,
}
impl ItemState<'_, '_> {
fn parse(&mut self) -> CmdResult<ItemInput> {
self.sugg = ISugg::Item;
let cursor = self.reader.cursor;
let id = read_identifier(self.reader)?;
if !self.reg.ids("minecraft:item").contains(&id) {
self.reader.cursor = cursor;
return Err(CommandError::tr_at(
"argument.item.id.invalid",
&[&id],
self.reader,
));
}
self.sugg = ISugg::StartComponents;
let mut components = None;
if self.reader.can_read() && self.reader.peek() == '[' {
self.sugg = ISugg::Nothing;
let start = self.reader.cursor;
self.read_components()?;
components = Some(self.reader.string[start..self.reader.cursor].to_owned());
}
Ok(ItemInput {
id,
tag: false,
any: false,
components,
})
}
fn component_type(&mut self) -> CmdResult<String> {
if !self.reader.can_read() {
return Err(CommandError::tr_at(
"arguments.item.component.expected",
&[],
self.reader,
));
}
let cursor = self.reader.cursor;
let id = read_identifier(self.reader)?;
if self.reg.persistent_components.contains(&id) {
return Ok(id);
}
self.reader.cursor = cursor;
Err(CommandError::tr_at(
"arguments.item.component.unknown",
&[&id],
self.reader,
))
}
fn read_components(&mut self) -> CmdResult<()> {
self.reader.expect('[')?;
self.sugg = ISugg::ComponentAssignmentOrRemoval;
let mut visited: Vec<String> = Vec::new();
while self.reader.can_read() && self.reader.peek() != ']' {
self.reader.skip_whitespace();
if self.reader.can_read() && self.reader.peek() == '!' {
self.reader.skip();
self.sugg = ISugg::Component;
let ty = self.component_type()?;
if visited.contains(&ty) {
return Err(CommandError::tr(
"arguments.item.component.repeated",
&[&ty],
));
}
visited.push(ty);
self.sugg = ISugg::Nothing;
self.reader.skip_whitespace();
} else {
let ty = self.component_type()?;
if visited.contains(&ty) {
return Err(CommandError::tr(
"arguments.item.component.repeated",
&[&ty],
));
}
visited.push(ty.clone());
self.sugg = ISugg::Assignment;
self.reader.skip_whitespace();
self.reader.expect('=')?;
self.sugg = ISugg::Nothing;
self.reader.skip_whitespace();
let cursor = self.reader.cursor;
let tag = super::snbt::parse_tag_argument(self.reader)?;
if let Err(m) = decode_component(&ty, &tag) {
self.reader.cursor = cursor;
return Err(CommandError::tr_at(
"arguments.item.component.malformed",
&[&ty, &m],
self.reader,
));
}
self.reader.skip_whitespace();
}
self.sugg = ISugg::NextOrEndComponents;
if !self.reader.can_read() || self.reader.peek() != ',' {
break;
}
self.reader.skip();
self.reader.skip_whitespace();
self.sugg = ISugg::ComponentAssignmentOrRemoval;
if !self.reader.can_read() {
return Err(CommandError::tr_at(
"arguments.item.component.expected",
&[],
self.reader,
));
}
}
self.reader.expect(']')?;
self.sugg = ISugg::Nothing;
Ok(())
}
fn suggest_component(&self, b: &mut SuggestionsBuilder, suffix: &str) {
let contents = b.remaining_lower();
for id in &self.reg.persistent_components {
let matched = if contents.contains(':') {
super::args::matches_sub_str(&contents, id)
} else {
let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
super::args::matches_sub_str(&contents, ns)
|| super::args::matches_sub_str(&contents, path)
};
if matched {
b.suggest(format!("{id}{suffix}"));
}
}
}
fn fill(&self, builder: &mut SuggestionsBuilder) {
let mut b = builder.offset(self.reader.cursor);
let empty = b.remaining().is_empty();
match self.sugg {
ISugg::Nothing => {}
ISugg::Item => suggest_resources(&mut b, self.reg.ids("minecraft:item"), ""),
ISugg::StartComponents => {
if empty {
b.suggest("[");
}
}
ISugg::ComponentAssignmentOrRemoval => {
b.suggest("!");
self.suggest_component(&mut b, "=");
}
ISugg::Component => self.suggest_component(&mut b, ""),
ISugg::Assignment => {
if empty {
b.suggest("=");
}
}
ISugg::NextOrEndComponents => {
if empty {
b.suggest(",");
b.suggest("]");
}
}
}
builder.add(b);
}
}
/// ItemArgument.parse (ItemParser.parse; the reader is rewound on errors).
pub fn parse_stack(reader: &mut Reader, reg: &Registries) -> CmdResult<ItemInput> {
let cursor = reader.cursor;
let r = ItemState {
reader,
reg,
sugg: ISugg::Nothing,
}
.parse();
if r.is_err() {
reader.cursor = cursor;
}
r
}
/// ItemParser.fillSuggestions.
pub fn suggest_stack(builder: &mut SuggestionsBuilder, reg: &Registries) {
let mut reader = Reader {
string: builder.input,
cursor: builder.start,
};
let mut state = ItemState {
reader: &mut reader,
reg,
sugg: ISugg::Nothing,
};
let _ = state.parse();
state.fill(builder);
}
// ---- ItemPredicateArgument ------------------------------------------------
#[derive(Clone, Debug)]
pub enum TypeRes {
Item(String),
Tag(String),
}
#[derive(Clone, Debug)]
pub enum IV {
Id(String),
Type(Option<TypeRes>),
Elem(TypeRes),
Unit,
Test,
Comp(String),
Pred(String),
Tag(Tag),
List(Vec<IV>),
}
impl Value for IV {
fn list(items: Vec<Self>) -> Self {
IV::List(items)
}
}
fn reg<'a>(state: &State<'a, IV>) -> &'a Registries {
state
.ctx
.and_then(|c| c.downcast_ref::<Registries>())
.expect("item predicate grammar needs the registries")
}
/// IdentifierParseRule: skip whitespace, a non-empty identifier (no error).
fn id_rule(state: &mut State<IV>) -> Option<IV> {
let mut r = state.reader();
r.skip_whitespace();
let start = r.cursor;
while r.can_read() && is_id_char(r.peek()) {
r.skip();
}
let raw = &r.string[start..r.cursor];
let id = if raw.is_empty() {
None
} else {
parse_identifier(raw)
};
match id {
Some(id) => {
state.set_reader(&r);
Some(IV::Id(id))
}
None => {
r.cursor = start;
state.set_reader(&r);
None
}
}
}
/// ResourceLookupRule: an identifier validated by `validate`.
fn lookup(
state: &mut State<IV>,
id_rule: usize,
possible: Rc<Vec<String>>,
validate: &dyn Fn(&str, &Reader) -> Result<IV, CommandError>,
) -> Option<IV> {
let mut r = state.reader();
r.skip_whitespace();
state.set_reader(&r);
let mark = state.cursor;
match state.parse(id_rule) {
Some(IV::Id(id)) => match validate(&id, &state.reader()) {
Ok(v) => Some(v),
Err(e) => {
state.store(mark, Sugg::Resources(possible), Reason::Error(e));
None
}
},
_ => {
state.store(
mark,
Sugg::Resources(possible),
Reason::Delayed("argument.id.invalid", Vec::new()),
);
None
}
}
}
fn predicate_grammar() -> Grammar<IV> {
let mut g: Grammar<IV> = Grammar::new();
let id = g.put_custom("id", id_rule);
let ty = g.named("type");
let conditions = g.named("conditions");
let ty2 = g.named("type");
g.put_term(
"top",
alt(vec![
seq(vec![ty, ch('['), Term::Cut, opt(conditions), ch(']')]),
ty2,
]),
|s| {
let mut out = Vec::new();
if let Some(t) = s.scope.get("type") {
out.push(t);
}
if let Some(IV::List(c)) = s.scope.get("conditions") {
out.extend(c);
}
Some(IV::List(out))
},
);
let element = g.named("element_type");
let tag = g.named("tag_type");
let any = g.named("any_type");
g.put_term(
"type",
alt(vec![element, seq(vec![ch('#'), Term::Cut, tag]), any]),
|s| {
Some(IV::Type(
match s.scope.get_any(&["element_type", "tag_type"]) {
Some(IV::Elem(t)) => Some(t),
_ => None,
},
))
},
);
g.put_term("any_type", ch('*'), |_| Some(IV::Unit));
g.put_custom("element_type", move |s| {
let r = reg(s);
let items = Rc::new(r.ids("minecraft:item").to_vec());
lookup(s, id, items, &|id, reader| {
if r.ids("minecraft:item").iter().any(|i| i == id) {
Ok(IV::Elem(TypeRes::Item(id.to_owned())))
} else {
Err(CommandError::tr_at(
"argument.item.id.invalid",
&[&id],
reader,
))
}
})
});
g.put_custom("tag_type", move |s| {
let r = reg(s);
let tags = Rc::new(r.tags("minecraft:item").to_vec());
lookup(s, id, tags, &|id, reader| {
if r.tags("minecraft:item").iter().any(|i| i == id) {
Ok(IV::Elem(TypeRes::Tag(id.to_owned())))
} else {
Err(CommandError::tr_at(
"arguments.item.tag.unknown",
&[&id],
reader,
))
}
})
});
let alternatives = g.named("alternatives");
let rest = g.named("conditions");
g.put_term(
"conditions",
seq(vec![alternatives, opt(seq(vec![ch(','), rest]))]),
|s| {
let mut out = vec![IV::Test];
if let Some(IV::List(c)) = s.scope.get("conditions") {
out.extend(c);
}
Some(IV::List(out))
},
);
let term = g.named("term");
let rest = g.named("alternatives");
g.put_term(
"alternatives",
seq(vec![term, opt(seq(vec![ch('|'), rest]))]),
|s| {
let mut out = vec![s.scope.get("term").unwrap_or(IV::Test)];
if let Some(IV::List(c)) = s.scope.get("alternatives") {
out.extend(c);
}
Some(IV::List(out))
},
);
let test = g.named("test");
let negation = g.named("negation");
g.put_term("term", alt(vec![test, seq(vec![ch('!'), negation])]), |s| {
s.scope.get_any(&["test", "negation"])
});
let test = g.named("test");
g.put_term("negation", test, |_| Some(IV::Test));
let comp = g.named("component_type");
let tag_a = g.named("tag");
let pred = g.named("predicate_type");
let tag_b = g.named("tag");
let comp2 = g.named("component_type");
g.put_term(
"test",
alt(vec![
seq(vec![comp, ch('='), Term::Cut, tag_a]),
seq(vec![pred, ch('~'), Term::Cut, tag_b]),
comp2,
]),
|s| {
let value = match s.scope.get("tag") {
Some(IV::Tag(t)) => Some(t),
_ => None,
};
let reader = s.reader();
let result = if let Some(IV::Pred(p)) = s.scope.get("predicate_type") {
decode_predicate(&p, value.as_ref().unwrap_or(&Tag::End)).map_err(|m| {
CommandError::tr_at("arguments.item.predicate.malformed", &[&p, &m], &reader)
})
} else if let (Some(IV::Comp(c)), Some(v)) = (s.scope.get("component_type"), value) {
decode_component(&c, &v).map_err(|m| {
CommandError::tr_at("arguments.item.component.malformed", &[&c, &m], &reader)
})
} else {
Ok(())
};
match result {
Ok(()) => Some(IV::Test),
Err(e) => {
s.store(s.cursor, Sugg::Empty, Reason::Error(e));
None
}
}
},
);
g.put_custom("component_type", move |s| {
let r = reg(s);
let mut list = vec!["minecraft:count".to_owned()];
list.extend(r.persistent_components.iter().cloned());
lookup(s, id, Rc::new(list), &|id, reader| {
if id == "minecraft:count" {
return Ok(IV::Comp(id.to_owned()));
}
let known = r
.ids("minecraft:data_component_type")
.iter()
.any(|c| c == id);
if known && r.persistent_components.iter().any(|c| c == id) {
Ok(IV::Comp(id.to_owned()))
} else {
Err(CommandError::tr_at(
"arguments.item.component.unknown",
&[&id],
reader,
))
}
})
});
g.put_custom("predicate_type", move |s| {
let r = reg(s);
let mut list = vec!["minecraft:count".to_owned()];
list.extend(
r.ids("minecraft:data_component_predicate_type")
.iter()
.cloned(),
);
lookup(s, id, Rc::new(list), &|id, reader| {
if id == "minecraft:count"
|| r.ids("minecraft:data_component_predicate_type")
.iter()
.any(|c| c == id)
{
return Ok(IV::Pred(id.to_owned()));
}
if r.ids("minecraft:data_component_type")
.iter()
.any(|c| c == id)
{
// A component existence predicate (decodes Unit).
return Ok(IV::Pred(format!("exists:{id}")));
}
Err(CommandError::tr_at(
"arguments.item.predicate.unknown",
&[&id],
reader,
))
})
});
g.put_custom("tag", |s| super::snbt::rule_in(s, IV::Tag));
g.top = g.id("top");
g
}
thread_local! {
static PREDICATE: Grammar<IV> = predicate_grammar();
}
/// ItemPredicateArgument.parse.
pub fn parse_predicate(reader: &mut Reader, reg: &Registries) -> CmdResult<ItemInput> {
let start = reader.cursor;
let result = PREDICATE.with(|g| g.parse_for_commands_with(reader, Some(reg)))?;
let IV::List(items) = result else {
return Err(CommandError::tr_at("argument.id.invalid", &[], reader));
};
let text = &reader.string[start..reader.cursor];
let (id, tag, any) = match items.first() {
Some(IV::Type(Some(TypeRes::Item(i)))) => (i.clone(), false, false),
Some(IV::Type(Some(TypeRes::Tag(t)))) => (t.clone(), true, false),
_ => ("*".to_owned(), false, true),
};
let components = text.find('[').map(|i| text[i..].to_owned());
Ok(ItemInput {
id,
tag,
any,
components,
})
}
/// ItemPredicateArgument.listSuggestions.
pub fn suggest_predicate(builder: &mut SuggestionsBuilder, reg: &Registries) {
PREDICATE.with(|g| g.parse_for_suggestions_with(builder, Some(reg)));
}
#[cfg(test)]
mod tests {
use super::decode_component;
fn check(snbt: &str) -> Result<(), String> {
let tag = horizon_world::nbt::parse_snbt(snbt).expect("snbt").0;
decode_component("minecraft:block_entity_data", &tag)
}
#[test]
fn block_entity_data_needs_a_known_type() {
assert_eq!(check("{id:\"chest\",Lock:1}"), Ok(()));
assert_eq!(
check("{Command:\"say\"}"),
Err("Expected 'id' field in {Command:\"say\"}".into())
);
assert_eq!(
check("{id:\"minecraft:stone\"}"),
Err("Unknown registry key in ResourceKey[minecraft:root / minecraft:block_entity_type]: minecraft:stone".into())
);
}
}
File diff suppressed because it is too large Load Diff
@@ -1,403 +0,0 @@
//! The command tree a server sends (ClientboundCommandsPacket) as a
//! dispatcher the chat parses, colours and completes with
//! (ClientPacketListener.handleCommands).
//!
//! The packet holds each argument's parser and its network properties. A
//! node the client's own vanilla tree has at the same path takes that node's
//! argument type and suggestion provider (the parsers' suggestion lists and
//! the custom providers are the same code on both sides); any other node
//! (another server's or a mod's) gets the type its parser and properties
//! describe.
use super::{ArgType, Dispatcher, Node, NodeKind, Suggests};
use horizon_protocol::packets::play::{ARGUMENT_TYPES, ArgumentProperties, Commands};
use std::{
collections::{HashSet, VecDeque},
sync::{Mutex, OnceLock},
};
/// The command id of every executable node of a server's tree: the chat
/// sends the command, the server runs it.
pub const SERVER_COMMAND: &str = "server";
/// The dispatcher for a server's tree. `local` is the client's own tree
/// (vanilla's), whose matching nodes lend their types and providers.
pub fn from_packet(packet: &Commands, local: &Dispatcher) -> Dispatcher {
let count = packet.nodes.len();
let root = usize::try_from(packet.root)
.ok()
.filter(|&r| r < count)
.unwrap_or(0);
// The packet's root becomes node 0, the others follow in packet order.
let index = |i: usize| -> usize {
if i == root {
0
} else if i < root {
i + 1
} else {
i
}
};
let valid = |c: &i32| usize::try_from(*c).ok().filter(|&c| c < count);
// The local node at the same path, found breadth first from the roots
// along children (redirects are not paths of their own).
let mut matched: Vec<Option<usize>> = vec![None; count];
matched[root] = Some(0);
let mut queue = VecDeque::from([root]);
let mut seen = HashSet::from([root]);
while let Some(n) = queue.pop_front() {
for c in packet.nodes[n].children.iter().filter_map(valid) {
if !seen.insert(c) {
continue;
}
let node = &packet.nodes[c];
matched[c] = matched[n].and_then(|l| {
local.nodes[l].children.iter().copied().find(|&lc| {
let ln = &local.nodes[lc];
ln.name() == node.name
&& matches!(
(&ln.kind, node.kind),
(NodeKind::Literal(_), 1) | (NodeKind::Argument { .. }, 2)
)
})
});
queue.push_back(c);
}
}
let mut nodes = vec![None; count];
for (i, node) in packet.nodes.iter().enumerate() {
let local_node = matched[i].map(|l| &local.nodes[l]);
let kind = match node.kind {
1 => NodeKind::Literal(node.name.clone()),
2 => {
let ty = match local_node.map(|l| &l.kind) {
Some(NodeKind::Argument { ty, .. }) => ty.clone(),
_ => node
.parser
.as_ref()
.map_or(ArgType::Word, |(id, props)| argument_type(*id, props)),
};
NodeKind::Argument {
name: node.name.clone(),
ty,
}
}
_ => NodeKind::Root,
};
// The server's providers, as the client knows them
// (ArgumentNodeStub.build): its own custom ones arrive as `ask_server`.
let suggests = node.suggestions.as_deref().and_then(provider);
nodes[index(i)] = Some(Node {
kind: if i == root { NodeKind::Root } else { kind },
children: node.children.iter().filter_map(valid).map(index).collect(),
command: node.executable.then_some(SERVER_COMMAND),
redirect: node.redirect.as_ref().and_then(valid).map(index),
// The server sent only what the player may use.
permission: 0,
suggests,
});
}
let mut d = Dispatcher::new();
if count > 0 {
d.nodes = nodes.into_iter().flatten().collect();
}
d
}
/// SuggestionProviders by id (`SuggestionProviders.getProvider`).
fn provider(id: &str) -> Option<Suggests> {
match id {
"minecraft:ask_server" => Some(Suggests::AskServer),
"minecraft:summonable_entities" => Some(Suggests::SummonableEntities),
_ => None,
}
}
/// A registry name kept for the life of the game (argument types hold
/// `&'static str`): each distinct name is stored once.
fn intern(name: &str) -> &'static str {
static NAMES: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
let mut names = NAMES
.get_or_init(Default::default)
.lock()
.unwrap_or_else(|e| e.into_inner());
if let Some(&n) = names.get(name) {
return n;
}
let n: &'static str = Box::leak(name.to_owned().into_boxed_str());
names.insert(n);
n
}
/// The argument type a parser and its properties describe
/// (ArgumentTypeInfo.Template.instantiate).
pub fn argument_type(id: i32, props: &[u8]) -> ArgType {
let Some(name) = usize::try_from(id).ok().and_then(|i| ARGUMENT_TYPES.get(i)) else {
return ArgType::Word;
};
let p = ArgumentProperties::decode(id, props).unwrap_or(ArgumentProperties::None);
let registry = || match &p {
ArgumentProperties::Registry(r) => intern(r),
_ => "",
};
match *name {
"brigadier:bool" => ArgType::Bool,
"brigadier:integer" => match p {
ArgumentProperties::Integer { min, max } => ArgType::Integer {
min: min.unwrap_or(i32::MIN),
max: max.unwrap_or(i32::MAX),
},
_ => ArgType::Integer {
min: i32::MIN,
max: i32::MAX,
},
},
// No long type of its own: a double over the same bounds reads
// the same digits.
"brigadier:long" => match p {
ArgumentProperties::Long { min, max } => ArgType::Double {
min: min.map_or(f64::MIN, |v| v as f64),
max: max.map_or(f64::MAX, |v| v as f64),
},
_ => ArgType::Double {
min: f64::MIN,
max: f64::MAX,
},
},
"brigadier:float" => match p {
ArgumentProperties::Float { min, max } => ArgType::Float {
min: min.unwrap_or(f32::MIN),
max: max.unwrap_or(f32::MAX),
},
_ => ArgType::Float {
min: f32::MIN,
max: f32::MAX,
},
},
"brigadier:double" => match p {
ArgumentProperties::Double { min, max } => ArgType::Double {
min: min.unwrap_or(f64::MIN),
max: max.unwrap_or(f64::MAX),
},
_ => ArgType::Double {
min: f64::MIN,
max: f64::MAX,
},
},
"brigadier:string" => match p {
ArgumentProperties::String(1) => ArgType::Str,
ArgumentProperties::String(2) => ArgType::Greedy,
_ => ArgType::Word,
},
"minecraft:entity" => match p {
ArgumentProperties::Entity {
single,
players_only,
} => ArgType::Entity {
single,
players: players_only,
},
_ => ArgType::Entity {
single: false,
players: false,
},
},
"minecraft:game_profile" => ArgType::GameProfile,
"minecraft:block_pos" => ArgType::BlockPos,
"minecraft:column_pos" => ArgType::ColumnPos,
"minecraft:vec3" => ArgType::Vec3 { center: true },
"minecraft:vec2" => ArgType::Vec2,
"minecraft:block_state" => ArgType::BlockState,
"minecraft:block_predicate" => ArgType::BlockPredicate,
"minecraft:item_stack" => ArgType::Item,
"minecraft:item_predicate" => ArgType::ItemPredicate,
"minecraft:team_color" => ArgType::TeamColor,
"minecraft:hex_color" => ArgType::HexColor,
"minecraft:component" => ArgType::Component,
"minecraft:style" => ArgType::Style,
"minecraft:message" => ArgType::Message,
"minecraft:nbt_compound_tag" => ArgType::Nbt,
"minecraft:nbt_tag" => ArgType::NbtTag,
"minecraft:nbt_path" => ArgType::NbtPath,
"minecraft:objective" => ArgType::Objective,
"minecraft:objective_criteria" => ArgType::Criteria,
"minecraft:operation" => ArgType::Operation,
"minecraft:particle" => ArgType::Particle,
"minecraft:angle" => ArgType::Angle,
"minecraft:rotation" => ArgType::Rotation,
"minecraft:scoreboard_slot" => ArgType::ScoreboardSlot,
"minecraft:score_holder" => ArgType::ScoreHolder {
multiple: matches!(p, ArgumentProperties::ScoreHolder { multiple: true }),
},
"minecraft:swizzle" => ArgType::Swizzle,
"minecraft:team" => ArgType::Team,
"minecraft:item_slot" => ArgType::Slot,
"minecraft:item_slots" => ArgType::Slots,
"minecraft:resource_location" => ArgType::Id("none"),
"minecraft:function" => ArgType::Function,
"minecraft:entity_anchor" => ArgType::Anchor,
"minecraft:int_range" => ArgType::IntRange,
"minecraft:float_range" => ArgType::FloatRange,
"minecraft:dimension" => ArgType::Dimension,
"minecraft:gamemode" => ArgType::GameMode,
"minecraft:time" => ArgType::Time {
min: match p {
ArgumentProperties::Time { min } => min,
_ => 0,
},
},
"minecraft:resource_or_tag" => ArgType::ResOrTag(registry()),
"minecraft:resource_or_tag_key" => ArgType::ResOrTagKey(registry()),
"minecraft:resource" => ArgType::Res(registry()),
"minecraft:resource_key" => ArgType::ResKey(registry()),
"minecraft:resource_selector" => ArgType::ResourceSelector(registry()),
"minecraft:template_mirror" => ArgType::Enum(&["none", "front_back", "left_right"]),
"minecraft:template_rotation" => {
ArgType::Enum(&["none", "clockwise_90", "180", "counterclockwise_90"])
}
"minecraft:heightmap" => ArgType::Enum(&[
"world_surface",
"motion_blocking",
"motion_blocking_no_leaves",
"ocean_floor",
]),
"minecraft:swing_animation" => ArgType::Enum(&["none", "whack", "stab"]),
"minecraft:loot_table" => ArgType::ResourceOrId("minecraft:loot_table"),
"minecraft:loot_predicate" => ArgType::ResourceOrId("minecraft:predicate"),
"minecraft:loot_modifier" => ArgType::ResourceOrId("minecraft:item_modifier"),
"minecraft:context_float_provider" => {
ArgType::ResourceOrId("minecraft:context_float_provider")
}
"minecraft:context_int_provider" => ArgType::ResourceOrId("minecraft:context_int_provider"),
"minecraft:slot_source" => ArgType::SlotSource,
"minecraft:dialog" => ArgType::ResourceOrId("minecraft:dialog"),
"minecraft:feature" => ArgType::ResourceOrId("minecraft:worldgen/feature"),
"minecraft:uuid" => ArgType::Uuid,
_ => ArgType::Word,
}
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_protocol::{
buf::{Codec, Reader, Writer},
packets::play::CommandNode,
};
fn literal(name: &str, children: Vec<i32>, executable: bool) -> CommandNode {
CommandNode {
kind: 1,
executable,
restricted: false,
children,
redirect: None,
name: name.into(),
parser: None,
suggestions: None,
}
}
fn argument(name: &str, parser: &str, props: Vec<u8>, executable: bool) -> CommandNode {
let id = ARGUMENT_TYPES.iter().position(|p| *p == parser).unwrap() as i32;
CommandNode {
kind: 2,
executable,
restricted: false,
children: Vec::new(),
redirect: None,
name: name.into(),
parser: Some((id, props)),
suggestions: Some("minecraft:ask_server".into()),
}
}
/// A tree with the root last (as vanilla's numbering need not put it
/// first), a vanilla command and one the client does not know.
fn packet() -> Commands {
let mut range = Writer::new();
range.u8(3);
range.i32(1);
range.i32(64);
Commands {
nodes: vec![
literal("give", vec![2], false),
literal("warp", vec![3], false),
argument("targets", "minecraft:entity", vec![2], false),
argument("count", "brigadier:integer", range.data, true),
CommandNode {
kind: 0,
executable: false,
restricted: false,
children: vec![0, 1],
redirect: None,
name: String::new(),
parser: None,
suggestions: None,
},
],
root: 4,
}
}
#[test]
fn argument_nodes_round_trip() {
let p = packet();
let mut w = Writer::new();
Commands::write(&p, &mut w);
let back = Commands::read(&mut Reader::new(&w.data)).unwrap();
assert_eq!(back, p);
}
#[test]
fn server_tree_becomes_a_dispatcher() {
let local = super::super::vanilla::dispatcher();
let d = from_packet(&packet(), local);
assert!(matches!(d.nodes[0].kind, NodeKind::Root));
let warp = d.find("warp").expect("warp");
let count = d.nodes[warp].children[0];
match &d.nodes[count].kind {
NodeKind::Argument {
ty: ArgType::Integer { min, max },
..
} => assert_eq!((*min, *max), (1, 64)),
other => panic!("count is {other:?}"),
}
assert_eq!(d.nodes[count].command, Some(SERVER_COMMAND));
// `give <targets>` is vanilla's: it keeps the client's type.
let give = d.find("give").expect("give");
let targets = d.nodes[give].children[0];
assert!(matches!(
d.nodes[targets].kind,
NodeKind::Argument {
ty: ArgType::Entity {
single: false,
players: true
},
..
}
));
}
#[test]
fn every_argument_type_decodes() {
for (id, name) in ARGUMENT_TYPES.iter().enumerate() {
let mut w = Writer::new();
match *name {
"brigadier:integer" | "brigadier:long" | "brigadier:float" | "brigadier:double" => {
w.u8(0)
}
"brigadier:string" => w.varint(2),
"minecraft:entity" | "minecraft:score_holder" => w.u8(1),
"minecraft:time" => w.i32(0),
n if n.starts_with("minecraft:resource") && n != "minecraft:resource_location" => {
w.string("minecraft:item")
}
_ => {}
}
let mut r = Reader::new(&w.data);
ArgumentProperties::read(&mut r, id as i32).unwrap();
assert_eq!(r.remaining(), 0, "{name}");
let _ = argument_type(id as i32, &w.data);
}
}
}
@@ -1,627 +0,0 @@
//! A port of vanilla's packrat parsing library (`net.minecraft.util.parsing.packrat`):
//! terms, named rules with per-position memoisation, scopes with frames,
//! cuts, and the "longest only" error collector whose entries become both
//! the parse error and the completion suggestions.
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder, args};
use std::collections::HashMap;
use std::rc::Rc;
pub type Atom = &'static str;
pub type RuleId = usize;
/// A value a rule produces (an element of `Scope`).
pub trait Value: Clone {
fn list(items: Vec<Self>) -> Self;
}
/// Why a term failed (DelayedException or a ready exception).
#[derive(Clone, Debug)]
pub enum Reason {
/// A translatable exception created at the error cursor.
Delayed(&'static str, Vec<String>),
/// An exception with its own cursor.
Error(CommandError),
}
/// SuggestionSupplier.
#[derive(Clone, Debug)]
pub enum Sugg {
Empty,
Values(Rc<Vec<String>>),
/// ResourceSuggestion: ids completed with suggestResource.
Resources(Rc<Vec<String>>),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Key {
Frame(usize),
Atom(Atom),
}
/// Scope: a stack of frames of atom values.
pub struct Scope<V> {
stack: Vec<(Key, Option<V>)>,
top_entry: usize,
top_marker: usize,
}
impl<V: Clone> Scope<V> {
fn new() -> Self {
Self {
stack: vec![(Key::Frame(0), None)],
top_entry: 0,
top_marker: 0,
}
}
fn set(&mut self, i: usize, key: Key, value: Option<V>) {
while self.stack.len() <= i {
self.stack.push((Key::Frame(0), None));
}
self.stack[i] = (key, value);
}
fn value_index(&self, atoms: &[Atom]) -> Option<usize> {
let mut i = self.top_entry;
while i > self.top_marker {
if let Key::Atom(a) = self.stack[i].0
&& atoms.contains(&a)
{
return Some(i);
}
i -= 1;
}
None
}
fn setup_new_frame(&mut self) {
self.top_entry += 1;
let prev = self.top_marker;
self.set(self.top_entry, Key::Frame(prev), None);
self.top_marker = self.top_entry;
}
fn previous_marker(&self, marker: usize) -> usize {
match self.stack[marker].0 {
Key::Frame(p) => p,
Key::Atom(_) => 0,
}
}
pub fn push_frame(&mut self) {
self.setup_new_frame();
}
pub fn pop_frame(&mut self) {
let marker = self.top_marker;
self.top_entry = marker - 1;
self.top_marker = self.previous_marker(marker);
}
fn split_frame(&mut self) {
let current = self.top_marker;
let n = self.top_entry - self.top_marker;
self.setup_new_frame();
let mut target = self.top_entry;
for source in current + 1..current + 1 + n {
target += 1;
let key = self.stack[source].0;
self.set(target, key, None);
}
self.top_entry = target;
}
fn clear_frame_values(&mut self) {
let mut i = self.top_entry;
while i > self.top_marker {
self.stack[i].1 = None;
i -= 1;
}
}
fn merge_frame(&mut self) {
let previous_marker = self.previous_marker(self.top_marker);
let mut previous = previous_marker;
let mut current = self.top_marker;
while current < self.top_entry {
previous += 1;
current += 1;
let (new_key, new_value) = self.stack[current].clone();
let old_key = self.stack.get(previous).map(|e| e.0);
if old_key != Some(new_key) {
self.set(previous, new_key, new_value);
} else if new_value.is_some() {
self.stack[previous].1 = new_value;
}
}
self.top_entry = previous;
self.top_marker = previous_marker;
}
pub fn put(&mut self, atom: Atom, value: V) {
match self.value_index(&[atom]) {
Some(i) => self.stack[i].1 = Some(value),
None => {
self.top_entry += 1;
self.set(self.top_entry, Key::Atom(atom), Some(value));
}
}
}
pub fn get(&self, atom: Atom) -> Option<V> {
self.value_index(&[atom])
.and_then(|i| self.stack[i].1.clone())
}
/// Scope.getAny: the newest of several atoms.
pub fn get_any(&self, atoms: &[Atom]) -> Option<V> {
self.value_index(atoms)
.and_then(|i| self.stack[i].1.clone())
}
/// Whether the atom has an entry (even a null one).
pub fn has(&self, atom: Atom) -> bool {
self.value_index(&[atom]).is_some()
}
}
/// A rule: a term with an action, or hand-written parsing.
pub enum Rule<V> {
Term(Term<V>, Rc<dyn Fn(&mut State<V>) -> Option<V>>),
Custom(Rc<dyn Fn(&mut State<V>) -> Option<V>>),
}
pub enum Term<V> {
Seq(Vec<Term<V>>),
Alt(Vec<Term<V>>),
Opt(Box<Term<V>>),
Repeated {
rule: RuleId,
list: Atom,
min: usize,
},
RepeatedSep {
rule: RuleId,
list: Atom,
sep: Box<Term<V>>,
min: usize,
trailing: bool,
},
Look(Box<Term<V>>, bool),
Marker(Atom, V),
Cut,
Empty,
Fail(Reason),
Named {
rule: RuleId,
store: Atom,
},
/// StringReaderTerms.TerminalCharacters: one of `values` (or `accept`).
Chars {
values: Vec<char>,
accept: Option<fn(char) -> bool>,
},
/// StringReaderTerms.TerminalWord.
Word(String),
}
pub fn seq<V>(t: Vec<Term<V>>) -> Term<V> {
Term::Seq(t)
}
pub fn alt<V>(t: Vec<Term<V>>) -> Term<V> {
Term::Alt(t)
}
pub fn opt<V>(t: Term<V>) -> Term<V> {
Term::Opt(Box::new(t))
}
pub fn ch<V>(c: char) -> Term<V> {
Term::Chars {
values: vec![c],
accept: None,
}
}
pub fn chs<V>(a: char, b: char) -> Term<V> {
Term::Chars {
values: vec![a, b],
accept: None,
}
}
pub fn look<V>(t: Term<V>) -> Term<V> {
Term::Look(Box::new(t), true)
}
/// Dictionary: named rules, with forward references.
pub struct Grammar<V> {
names: Vec<Atom>,
rules: Vec<Option<Rule<V>>>,
pub top: RuleId,
}
impl<V: Value> Default for Grammar<V> {
fn default() -> Self {
Self::new()
}
}
impl<V: Value> Grammar<V> {
pub fn new() -> Self {
Self {
names: Vec::new(),
rules: Vec::new(),
top: 0,
}
}
/// Dictionary.forward / getOrCreateEntry.
pub fn id(&mut self, name: Atom) -> RuleId {
if let Some(i) = self.names.iter().position(|n| *n == name) {
return i;
}
self.names.push(name);
self.rules.push(None);
self.names.len() - 1
}
pub fn put(&mut self, name: Atom, rule: Rule<V>) -> RuleId {
let id = self.id(name);
assert!(self.rules[id].is_none(), "Trying to override rule: {name}");
self.rules[id] = Some(rule);
id
}
pub fn put_term(
&mut self,
name: Atom,
term: Term<V>,
action: impl Fn(&mut State<V>) -> Option<V> + 'static,
) -> RuleId {
self.put(name, Rule::Term(term, Rc::new(action)))
}
pub fn put_custom(
&mut self,
name: Atom,
f: impl Fn(&mut State<V>) -> Option<V> + 'static,
) -> RuleId {
self.put(name, Rule::Custom(Rc::new(f)))
}
/// Dictionary.named: parse the rule and store it under its own name.
pub fn named(&mut self, name: Atom) -> Term<V> {
let rule = self.id(name);
Term::Named { rule, store: name }
}
/// Dictionary.namedWithAlias.
pub fn named_as(&mut self, name: Atom, store: Atom) -> Term<V> {
let rule = self.id(name);
Term::Named { rule, store }
}
/// Grammar.parseForCommands: parse at the reader's cursor; on failure
/// the first error stored at the furthest position.
pub fn parse_for_commands(&self, reader: &mut Reader) -> CmdResult<V> {
self.parse_for_commands_with(reader, None)
}
/// parse_for_commands with a context value the rules can read (`State::ctx`).
pub fn parse_for_commands_with(
&self,
reader: &mut Reader,
ctx: Option<&dyn std::any::Any>,
) -> CmdResult<V> {
let mut state = State::new(self, reader.string, reader.cursor);
state.ctx = ctx;
let result = state.parse_top();
reader.cursor = state.cursor;
match result {
Some(v) => Ok(v),
None => Err(state.first_error()),
}
}
/// Grammar.parseForSuggestions.
pub fn parse_for_suggestions(&self, builder: &mut SuggestionsBuilder) {
self.parse_for_suggestions_with(builder, None)
}
pub fn parse_for_suggestions_with(
&self,
builder: &mut SuggestionsBuilder,
ctx: Option<&dyn std::any::Any>,
) {
let mut state = State::new(self, builder.input, builder.start);
state.ctx = ctx;
state.parse_top();
if state.errors.is_empty() {
return;
}
let mut offset = builder.offset(state.last_cursor.max(0) as usize);
for (sugg, _) in &state.errors {
match sugg {
Sugg::Empty => {}
Sugg::Values(v) => offset.suggest_matching(v.iter().map(String::as_str)),
Sugg::Resources(ids) => args::suggest_resources(&mut offset, ids.iter(), ""),
}
}
builder.add(offset);
}
}
/// CachedParseState over a string (StringReaderParserState) with a
/// LongestOnly error collector.
pub struct State<'g, V> {
grammar: &'g Grammar<V>,
pub input: &'g str,
pub cursor: usize,
cache: HashMap<(usize, RuleId), Option<(V, usize)>>,
pub scope: Scope<V>,
controls: Vec<bool>,
errors: Vec<(Sugg, Reason)>,
last_cursor: isize,
/// Context for the rules (e.g. the registries a lookup checks).
pub ctx: Option<&'g dyn std::any::Any>,
}
const UNBOUND: usize = usize::MAX;
impl<'g, V: Value> State<'g, V> {
pub fn new(grammar: &'g Grammar<V>, input: &'g str, cursor: usize) -> Self {
Self {
grammar,
input,
cursor,
cache: HashMap::new(),
scope: Scope::new(),
controls: Vec::new(),
errors: Vec::new(),
last_cursor: -1,
ctx: None,
}
}
pub fn reader(&self) -> Reader<'g> {
Reader {
string: self.input,
cursor: self.cursor,
}
}
pub fn set_reader(&mut self, r: &Reader) {
self.cursor = r.cursor;
}
fn discard_shorter(&mut self, cursor: usize) {
if cursor as isize > self.last_cursor {
self.last_cursor = cursor as isize;
self.errors.clear();
}
}
/// ErrorCollector.store.
pub fn store(&mut self, cursor: usize, sugg: Sugg, reason: Reason) {
self.discard_shorter(cursor);
if cursor as isize == self.last_cursor {
self.errors.push((sugg, reason));
}
}
pub fn store_at_mark(&mut self, reason: Reason) {
self.store(self.cursor, Sugg::Empty, reason);
}
fn parse_top(&mut self) -> Option<V> {
let r = self.parse(self.grammar.top);
if r.is_some() {
self.discard_shorter(self.cursor);
}
r
}
fn first_error(&self) -> CommandError {
if let Some((_, reason)) = self.errors.first() {
return match reason {
Reason::Delayed(key, args) => {
let args: Vec<&dyn std::fmt::Display> =
args.iter().map(|a| a as &dyn std::fmt::Display).collect();
CommandError::tr_at(
key,
&args,
&Reader {
string: self.input,
cursor: self.last_cursor.max(0) as usize,
},
)
}
Reason::Error(e) => e.clone(),
};
}
CommandError::new(crate::text::Text::literal("Failed to parse"))
}
/// CachedParseState.parse: a named rule, memoised per position.
pub fn parse(&mut self, rule: RuleId) -> Option<V> {
let mark = self.cursor;
if let Some(entry) = self.cache.get(&(mark, rule)) {
return match entry {
None => None,
Some((v, after)) => {
let v = v.clone();
self.cursor = *after;
Some(v)
}
};
}
let result = match self.grammar.rules[rule].as_ref() {
Some(Rule::Term(term, action)) => {
let action = action.clone();
self.scope.push_frame();
let ok = self.term(term, UNBOUND, false);
let r = if ok { action(self) } else { None };
self.scope.pop_frame();
r
}
Some(Rule::Custom(f)) => {
let f = f.clone();
f(self)
}
None => panic!("Unbound rule {}", self.grammar.names[rule]),
};
let entry = result.clone().map(|v| (v, self.cursor));
self.cache.insert((mark, rule), entry);
result
}
fn skip_whitespace(&mut self) {
let mut r = self.reader();
r.skip_whitespace();
self.cursor = r.cursor;
}
fn term(&mut self, term: &'g Term<V>, control: usize, silent: bool) -> bool {
match term {
Term::Seq(items) => {
let mark = self.cursor;
for t in items {
if !self.term(t, control, silent) {
self.cursor = mark;
return false;
}
}
true
}
Term::Alt(items) => {
self.controls.push(false);
let ctl = self.controls.len() - 1;
let mark = self.cursor;
self.scope.split_frame();
let mut ok = false;
for t in items {
if self.term(t, ctl, silent) {
self.scope.merge_frame();
ok = true;
break;
}
self.scope.clear_frame_values();
self.cursor = mark;
if self.controls[ctl] {
break;
}
}
if !ok {
self.scope.pop_frame();
}
self.controls.pop();
ok
}
Term::Opt(t) => {
let mark = self.cursor;
if !self.term(t, control, silent) {
self.cursor = mark;
}
true
}
Term::Repeated { rule, list, min } => {
let mark = self.cursor;
let mut items = Vec::new();
loop {
let entry = self.cursor;
match self.parse(*rule) {
Some(v) => items.push(v),
None => {
self.cursor = entry;
if items.len() < *min {
self.cursor = mark;
return false;
}
self.scope.put(list, V::list(items));
return true;
}
}
}
}
Term::RepeatedSep {
rule,
list,
sep,
min,
trailing,
} => {
let list_mark = self.cursor;
let mut items = Vec::new();
let mut first = true;
loop {
let before = self.cursor;
if !first && !self.term(sep, control, silent) {
self.cursor = before;
break;
}
let after = self.cursor;
match self.parse(*rule) {
Some(v) => items.push(v),
None => {
if first {
self.cursor = after;
} else {
if !*trailing {
self.cursor = list_mark;
return false;
}
self.cursor = after;
}
break;
}
}
first = false;
}
if items.len() < *min {
self.cursor = list_mark;
return false;
}
self.scope.put(list, V::list(items));
true
}
Term::Look(t, positive) => {
let mark = self.cursor;
let r = self.term(t, control, true);
self.cursor = mark;
*positive == r
}
Term::Marker(atom, v) => {
self.scope.put(atom, v.clone());
true
}
Term::Cut => {
if control != UNBOUND {
self.controls[control] = true;
}
true
}
Term::Empty => true,
Term::Fail(reason) => {
if !silent {
self.store(self.cursor, Sugg::Empty, reason.clone());
}
false
}
Term::Named { rule, store } => match self.parse(*rule) {
Some(v) => {
self.scope.put(store, v);
true
}
None => false,
},
Term::Chars { values, accept } => {
self.skip_whitespace();
let cursor = self.cursor;
let mut r = self.reader();
if r.can_read() {
let c = r.read();
self.cursor = r.cursor;
let ok = match accept {
Some(f) => f(c),
None => values.contains(&c),
};
if ok {
return true;
}
}
if !silent {
let joined = values
.iter()
.map(char::to_string)
.collect::<Vec<_>>()
.join("|");
let sugg = Sugg::Values(Rc::new(values.iter().map(char::to_string).collect()));
self.store(
cursor,
sugg,
Reason::Delayed("argument.literal.incorrect", vec![joined]),
);
}
false
}
Term::Word(word) => {
self.skip_whitespace();
let cursor = self.cursor;
let mut r = self.reader();
let value = r.read_unquoted_string();
self.cursor = r.cursor;
if value != word {
if !silent {
self.store(
cursor,
Sugg::Values(Rc::new(vec![word.clone()])),
Reason::Delayed("argument.literal.incorrect", vec![word.clone()]),
);
}
return false;
}
true
}
}
}
}
@@ -1,813 +0,0 @@
//! EntitySelectorParser and EntitySelectorOptions: `@e[...]` selectors,
//! player names and UUIDs, with the suggestion state vanilla keeps while
//! parsing (`fillSuggestions`).
use super::args::{
AdvCondition, GameMode, Registries, Selector, Sort, read_double_bounds, read_float_bounds,
read_identifier, read_int_bounds, suggest_resources,
};
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
/// The option names in vanilla's registration order.
const OPTIONS: [&str; 21] = [
"name",
"distance",
"level",
"x",
"y",
"z",
"dx",
"dy",
"dz",
"x_rotation",
"y_rotation",
"limit",
"sort",
"gamemode",
"team",
"type",
"tag",
"nbt",
"scores",
"advancements",
"predicate",
];
const SELECTOR_KINDS: [(&str, &str); 6] = [
("@p", "argument.entity.selector.nearestPlayer"),
("@a", "argument.entity.selector.allPlayers"),
("@r", "argument.entity.selector.randomPlayer"),
("@s", "argument.entity.selector.self"),
("@e", "argument.entity.selector.allEntities"),
("@n", "argument.entity.selector.nearestEntity"),
];
/// InvertableSetOptionState.
#[derive(Clone, Debug, Default)]
struct InvertableSet {
/// 0 none, 1 single, 2 multiple.
state: u8,
tags: Vec<String>,
}
impl InvertableSet {
fn can_parse_positive(&self) -> bool {
self.state == 0
}
fn can_parse_negative(&self) -> bool {
self.state != 1
}
fn can_parse_any_tag(&self) -> bool {
self.can_parse_negative()
}
fn can_parse_tag(&self, tag: &str) -> bool {
self.can_parse_any_tag() && !self.tags.iter().any(|t| t == tag)
}
fn can_parse_any(&self) -> bool {
self.state != 1
}
fn can_parse_element(&self, inverted: bool) -> bool {
if inverted {
self.can_parse_negative()
} else {
self.can_parse_positive()
}
}
fn mark_element(&mut self, inverted: bool) {
self.state = if inverted { 2 } else { 1 };
}
fn mark_tag(&mut self, tag: String) {
self.state = 2;
self.tags.push(tag);
}
}
/// The suggestion function the parser last set.
#[derive(Clone, Debug)]
enum Sugg {
Nothing,
NameOrSelector,
Name,
Selector,
OpenOptions,
OptionsKeyOrClose,
OptionsKey,
OptionsNextOrClose,
Sort,
GameMode,
Type,
}
/// EntitySelectorParser over a reader.
pub struct SelectorParser<'r, 'a> {
pub reader: &'r mut Reader<'a>,
reg: &'r Registries,
allow_selectors: bool,
s: Selector,
sugg: Sugg,
start_position: usize,
current_entity: bool,
has_distance: bool,
has_level: bool,
has_rot_x: bool,
has_rot_y: bool,
name_option: InvertableSet,
limited: bool,
sorted: bool,
gamemode_option: InvertableSet,
team_option: InvertableSet,
type_option: InvertableSet,
scores_option: bool,
advancements_option: bool,
}
/// UUID.fromString.
pub fn java_uuid(name: &str) -> Option<u128> {
if name.encode_utf16().count() > 36 {
return None;
}
let parts: Vec<&str> = name.split('-').collect();
if parts.len() != 5 {
return None;
}
let mut v: [i64; 5] = [0; 5];
for (i, p) in parts.iter().enumerate() {
// Long.parseLong(s, 16): an optional sign then hex digits.
let digits = p.strip_prefix(['+', '-']).unwrap_or(p);
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
v[i] = i64::from_str_radix(p, 16).ok()?;
}
let msb = (((v[0] as u64) & 0xffff_ffff) << 32)
| (((v[1] as u64) & 0xffff) << 16)
| ((v[2] as u64) & 0xffff);
let lsb = (((v[3] as u64) & 0xffff) << 48) | ((v[4] as u64) & 0xffff_ffff_ffff);
Some((u128::from(msb) << 64) | u128::from(lsb))
}
fn rollback(
reader: &mut Reader,
start: usize,
key: &str,
args: &[&dyn std::fmt::Display],
) -> CommandError {
reader.cursor = start;
CommandError::tr_at(key, args, reader)
}
impl<'r, 'a> SelectorParser<'r, 'a> {
pub fn new(reader: &'r mut Reader<'a>, reg: &'r Registries, allow_selectors: bool) -> Self {
Self {
reader,
reg,
allow_selectors,
s: Selector::default(),
sugg: Sugg::Nothing,
start_position: 0,
current_entity: false,
has_distance: false,
has_level: false,
has_rot_x: false,
has_rot_y: false,
name_option: InvertableSet::default(),
limited: false,
sorted: false,
gamemode_option: InvertableSet::default(),
team_option: InvertableSet::default(),
type_option: InvertableSet::default(),
scores_option: false,
advancements_option: false,
}
}
/// EntitySelectorParser.parse.
pub fn parse(&mut self) -> CmdResult<Selector> {
self.start_position = self.reader.cursor;
self.sugg = Sugg::NameOrSelector;
if self.reader.can_read() && self.reader.peek() == '@' {
if !self.allow_selectors {
return Err(CommandError::tr_at(
"argument.entity.selector.not_allowed",
&[],
self.reader,
));
}
self.reader.skip();
self.parse_selector()?;
} else {
self.parse_name_or_uuid()?;
}
Ok(self.s.clone())
}
fn parse_selector(&mut self) -> CmdResult<()> {
self.sugg = Sugg::Selector;
if !self.reader.can_read() {
return Err(CommandError::tr_at(
"argument.entity.selector.missing",
&[],
self.reader,
));
}
let start = self.reader.cursor;
let kind = self.reader.read();
let s = &mut self.s;
s.kind = kind;
match kind {
'a' => {
s.limit = usize::MAX;
s.include_entities = false;
s.types.push(("minecraft:player".into(), false));
}
'e' => {
s.limit = usize::MAX;
s.include_entities = true;
}
'n' => {
s.limit = 1;
s.include_entities = true;
s.sort = Sort::Nearest;
}
'p' => {
s.limit = 1;
s.include_entities = false;
s.sort = Sort::Nearest;
s.types.push(("minecraft:player".into(), false));
}
'r' => {
s.limit = 1;
s.include_entities = false;
s.sort = Sort::Random;
s.types.push(("minecraft:player".into(), false));
}
's' => {
s.limit = 1;
s.include_entities = true;
self.current_entity = true;
}
other => {
self.reader.cursor = start;
return Err(CommandError::tr_at(
"argument.entity.selector.unknown",
&[&format!("@{other}")],
self.reader,
));
}
}
self.sugg = Sugg::OpenOptions;
if self.reader.can_read() && self.reader.peek() == '[' {
self.reader.skip();
self.sugg = Sugg::OptionsKeyOrClose;
self.parse_options()?;
}
Ok(())
}
fn parse_name_or_uuid(&mut self) -> CmdResult<()> {
if self.reader.can_read() {
self.sugg = Sugg::Name;
}
let start = self.reader.cursor;
let name = self.reader.read_string()?;
if let Some(uuid) = java_uuid(&name) {
self.s.uuid = Some(uuid);
self.s.include_entities = true;
self.s.player_name = Some(name);
} else {
if name.is_empty() || name.encode_utf16().count() > 16 {
self.reader.cursor = start;
return Err(CommandError::tr_at(
"argument.entity.invalid",
&[],
self.reader,
));
}
self.s.include_entities = false;
self.s.player_name = Some(name);
}
self.s.kind = '\0';
self.s.limit = 1;
Ok(())
}
fn can_use(&self, option: &str) -> bool {
match option {
"name" => self.name_option.can_parse_any(),
"distance" => !self.has_distance,
"level" => !self.has_level,
"x" => self.s.pos[0].is_none(),
"y" => self.s.pos[1].is_none(),
"z" => self.s.pos[2].is_none(),
"dx" => self.s.delta[0].is_none(),
"dy" => self.s.delta[1].is_none(),
"dz" => self.s.delta[2].is_none(),
"x_rotation" => !self.has_rot_x,
"y_rotation" => !self.has_rot_y,
"limit" => !self.current_entity && !self.limited,
"sort" => !self.current_entity && !self.sorted,
"gamemode" => self.gamemode_option.can_parse_any(),
"team" => self.team_option.can_parse_any(),
"type" => self.type_option.can_parse_any(),
"scores" => !self.scores_option,
"advancements" => !self.advancements_option,
_ => true,
}
}
fn parse_options(&mut self) -> CmdResult<()> {
self.sugg = Sugg::OptionsKey;
self.reader.skip_whitespace();
while self.reader.can_read() && self.reader.peek() != ']' {
self.reader.skip_whitespace();
let start = self.reader.cursor;
let key = self.reader.read_string()?;
if !OPTIONS.contains(&key.as_str()) {
return Err(rollback(
self.reader,
start,
"argument.entity.options.unknown",
&[&key],
));
}
if !self.can_use(&key) {
return Err(rollback(
self.reader,
start,
"argument.entity.options.inapplicable",
&[&key],
));
}
self.reader.skip_whitespace();
if !self.reader.can_read() || self.reader.peek() != '=' {
return Err(rollback(
self.reader,
start,
"argument.entity.options.valueless",
&[&key],
));
}
self.reader.skip();
self.reader.skip_whitespace();
self.sugg = Sugg::Nothing;
self.handle(&key)?;
self.reader.skip_whitespace();
self.sugg = Sugg::OptionsNextOrClose;
if self.reader.can_read() {
if self.reader.peek() != ',' {
if self.reader.peek() != ']' {
return Err(CommandError::tr_at(
"argument.entity.options.unterminated",
&[],
self.reader,
));
}
break;
}
self.reader.skip();
self.sugg = Sugg::OptionsKey;
}
}
if self.reader.can_read() {
self.reader.skip();
self.sugg = Sugg::Nothing;
Ok(())
} else {
Err(CommandError::tr_at(
"argument.entity.options.unterminated",
&[],
self.reader,
))
}
}
fn should_invert(&mut self) -> bool {
self.reader.skip_whitespace();
if self.reader.can_read() && self.reader.peek() == '!' {
self.reader.skip();
self.reader.skip_whitespace();
true
} else {
false
}
}
fn is_tag(&mut self) -> bool {
self.reader.skip_whitespace();
if self.reader.can_read() && self.reader.peek() == '#' {
self.reader.skip();
self.reader.skip_whitespace();
true
} else {
false
}
}
fn handle(&mut self, key: &str) -> CmdResult<()> {
match key {
"name" => {
let start = self.reader.cursor;
let inverted = self.should_invert();
let name = self.reader.read_string()?;
if !self.name_option.can_parse_element(inverted) {
return Err(rollback(
self.reader,
start,
"argument.entity.options.inapplicable",
&[&"name"],
));
}
self.name_option.mark_element(inverted);
self.s.names.push((name, inverted));
}
"distance" => {
let start = self.reader.cursor;
let value = read_double_bounds(self.reader)?;
if value.0.is_some_and(|v| v < 0.0) || value.1.is_some_and(|v| v < 0.0) {
return Err(rollback(
self.reader,
start,
"argument.entity.options.distance.negative",
&[],
));
}
self.s.distance = Some(value);
self.has_distance = true;
}
"level" => {
let start = self.reader.cursor;
let value = read_int_bounds(self.reader)?;
if value.0.is_some_and(|v| v < 0) || value.1.is_some_and(|v| v < 0) {
return Err(rollback(
self.reader,
start,
"argument.entity.options.level.negative",
&[],
));
}
self.s.level = Some(value);
self.has_level = true;
self.s.include_entities = false;
}
"x" | "y" | "z" => {
let i = usize::from(key.as_bytes()[0] - b'x');
self.s.pos[i] = Some(self.reader.read_double()?);
}
"dx" | "dy" | "dz" => {
let i = usize::from(key.as_bytes()[1] - b'x');
self.s.delta[i] = Some(self.reader.read_double()?);
}
"x_rotation" | "y_rotation" => {
let (lo, hi) = read_float_bounds(self.reader)?;
let range = (lo.map(f64::from), hi.map(f64::from));
if key == "x_rotation" {
self.s.x_rotation = Some(range);
self.has_rot_x = true;
} else {
self.s.y_rotation = Some(range);
self.has_rot_y = true;
}
}
"limit" => {
let start = self.reader.cursor;
let count = self.reader.read_int()?;
if count < 1 {
return Err(rollback(
self.reader,
start,
"argument.entity.options.limit.toosmall",
&[],
));
}
self.s.limit = count as usize;
self.limited = true;
}
"sort" => {
let start = self.reader.cursor;
let name = self.reader.read_unquoted_string();
self.sugg = Sugg::Sort;
self.s.sort = match name {
"nearest" => Sort::Nearest,
"furthest" => Sort::Furthest,
"random" => Sort::Random,
"arbitrary" => Sort::Arbitrary,
_ => {
return Err(rollback(
self.reader,
start,
"argument.entity.options.sort.irreversible",
&[&name],
));
}
};
self.sorted = true;
}
"gamemode" => {
self.sugg = Sugg::GameMode;
let start = self.reader.cursor;
let inverted = self.should_invert();
if !self.gamemode_option.can_parse_element(inverted) {
return Err(rollback(
self.reader,
start,
"argument.entity.options.inapplicable",
&[&"gamemode"],
));
}
let name = self.reader.read_unquoted_string();
if GameMode::from_name(name).is_none() {
return Err(rollback(
self.reader,
start,
"argument.entity.options.mode.invalid",
&[&name],
));
}
self.s.include_entities = false;
self.s.gamemodes.push((name.to_owned(), inverted));
self.gamemode_option.mark_element(inverted);
}
"team" => {
let start = self.reader.cursor;
let inverted = self.should_invert();
let name = self.reader.read_unquoted_string().to_owned();
if !self.team_option.can_parse_element(inverted) {
return Err(rollback(
self.reader,
start,
"argument.entity.options.inapplicable",
&[&"team"],
));
}
self.s.teams.push((name, inverted));
self.team_option.mark_element(inverted);
}
"type" => {
self.sugg = Sugg::Type;
let start = self.reader.cursor;
let inverted = self.should_invert();
if self.is_tag() {
if !self.type_option.can_parse_any_tag() {
return Err(rollback(
self.reader,
start,
"argument.entity.options.inapplicable",
&[&"type"],
));
}
let id = read_identifier(self.reader)?;
if !self.type_option.can_parse_tag(&id) {
return Err(rollback(
self.reader,
start,
"argument.entity.options.inapplicable",
&[&"type"],
));
}
self.s.types.push((format!("#{id}"), inverted));
self.type_option.mark_tag(id);
} else {
if !self.type_option.can_parse_element(inverted) {
return Err(rollback(
self.reader,
start,
"argument.entity.options.inapplicable",
&[&"type"],
));
}
let id = read_identifier(self.reader)?;
let types = self.reg.ids("minecraft:entity_type");
if !types.is_empty() && !types.contains(&id) {
return Err(rollback(
self.reader,
start,
"argument.entity.options.type.invalid",
&[&id],
));
}
if id == "minecraft:player" && !inverted {
self.s.include_entities = false;
}
if !inverted {
// limitToType replaces the player type of @a/@p/@r.
self.s.types.retain(|(t, n)| *n || t.starts_with('#'));
}
self.s.types.push((id, inverted));
self.type_option.mark_element(inverted);
}
}
"tag" => {
let inverted = self.should_invert();
let tag = self.reader.read_unquoted_string().to_owned();
self.s.tags.push((tag, inverted));
}
"nbt" => {
let inverted = self.should_invert();
let start = self.reader.cursor;
super::snbt::parse_compound_argument(self.reader)?;
let text = self.reader.string[start..self.reader.cursor].to_owned();
self.s.nbt.push((text, inverted));
}
"scores" => {
let r = &mut *self.reader;
r.expect('{')?;
r.skip_whitespace();
let mut expected = Vec::new();
while r.can_read() && r.peek() != '}' {
r.skip_whitespace();
let name = r.read_unquoted_string().to_owned();
r.skip_whitespace();
r.expect('=')?;
r.skip_whitespace();
let value = read_int_bounds(r)?;
expected.push((name, value));
r.skip_whitespace();
if r.can_read() && r.peek() == ',' {
r.skip();
}
}
r.expect('}')?;
self.s.scores.extend(expected);
self.scores_option = true;
}
"advancements" => {
let r = &mut *self.reader;
r.expect('{')?;
r.skip_whitespace();
let mut expected = Vec::new();
while r.can_read() && r.peek() != '}' {
r.skip_whitespace();
let name = read_identifier(r)?;
r.skip_whitespace();
r.expect('=')?;
r.skip_whitespace();
if r.can_read() && r.peek() == '{' {
let mut progress = Vec::new();
r.skip_whitespace();
r.expect('{')?;
r.skip_whitespace();
while r.can_read() && r.peek() != '}' {
r.skip_whitespace();
let criterion = r.read_unquoted_string().to_owned();
r.skip_whitespace();
r.expect('=')?;
r.skip_whitespace();
let value = r.read_boolean()?;
progress.push((criterion, value));
r.skip_whitespace();
if r.can_read() && r.peek() == ',' {
r.skip();
}
}
r.skip_whitespace();
r.expect('}')?;
r.skip_whitespace();
expected.push((name, AdvCondition::Criteria(progress)));
} else {
let value = r.read_boolean()?;
expected.push((name, AdvCondition::Done(value)));
}
r.skip_whitespace();
if r.can_read() && r.peek() == ',' {
r.skip();
}
}
r.expect('}')?;
if !expected.is_empty() {
self.s.include_entities = false;
}
self.s.advancements.extend(expected);
self.advancements_option = true;
}
"predicate" => {
let inverted = self.should_invert();
let id = read_identifier(self.reader)?;
self.s.predicates.push((id, inverted));
}
_ => {}
}
Ok(())
}
fn fill_selectors(builder: &mut SuggestionsBuilder) {
for (s, tip) in SELECTOR_KINDS {
builder.suggest_tooltip(s, crate::lang::get(tip));
}
}
/// EntitySelectorParser.fillSuggestions: `names` adds the name
/// candidates (online players for most arguments).
pub fn fill_suggestions(
&self,
builder: &mut SuggestionsBuilder,
names: &dyn Fn(&mut SuggestionsBuilder),
) {
let mut b = builder.offset(self.reader.cursor);
match self.sugg {
Sugg::Nothing => {}
Sugg::NameOrSelector => {
names(&mut b);
if self.allow_selectors {
Self::fill_selectors(&mut b);
}
}
Sugg::Name => {
let mut sub = b.offset(self.start_position);
names(&mut sub);
b.add(sub);
}
Sugg::Selector => {
let mut sub = b.offset(b.start - 1);
Self::fill_selectors(&mut sub);
b.add(sub);
}
Sugg::OpenOptions => b.suggest("["),
Sugg::OptionsKeyOrClose => {
b.suggest("]");
self.suggest_names(&mut b);
}
Sugg::OptionsKey => self.suggest_names(&mut b),
Sugg::OptionsNextOrClose => {
b.suggest(",");
b.suggest("]");
}
Sugg::Sort => b.suggest_matching(["nearest", "furthest", "random", "arbitrary"]),
Sugg::GameMode => {
let state = &self.gamemode_option;
let mut prefix = b.remaining_lower();
let mut add_normal = state.can_parse_positive();
let mut add_inverted = state.can_parse_negative();
if !prefix.is_empty() {
if prefix.starts_with('!') {
add_normal = false;
prefix.remove(0);
} else {
add_inverted = false;
}
}
for mode in GameMode::ALL {
if mode.name().starts_with(&prefix) {
if add_inverted {
b.suggest(format!("!{}", mode.name()));
}
if add_normal {
b.suggest(mode.name());
}
}
}
}
Sugg::Type => {
let state = &self.type_option;
let types = self.reg.ids("minecraft:entity_type");
if state.can_parse_negative() {
suggest_resources(&mut b, types, "!");
}
if state.can_parse_positive() {
suggest_resources(&mut b, types, "");
}
if state.can_parse_any_tag() {
let tags: Vec<String> = self
.reg
.tags("minecraft:entity_type")
.iter()
.filter(|t| state.can_parse_tag(t))
.cloned()
.collect();
if !tags.is_empty() {
suggest_resources(&mut b, &tags, "#");
suggest_resources(&mut b, &tags, "!#");
}
}
}
}
builder.add(b);
}
fn suggest_names(&self, b: &mut SuggestionsBuilder) {
let lower = b.remaining_lower();
for o in OPTIONS {
if self.can_use(o) && o.starts_with(&lower) {
b.suggest_tooltip(
format!("{o}="),
crate::lang::get(&format!("argument.entity.options.{o}.description")),
);
}
}
}
}
/// Parse a selector from `reader` (EntitySelectorParser.parse).
pub fn parse(reader: &mut Reader, reg: &Registries, allow_selectors: bool) -> CmdResult<Selector> {
SelectorParser::new(reader, reg, allow_selectors).parse()
}
/// Re-parse the text from `builder.start` and fill the selector suggestions.
pub fn suggest(
builder: &mut SuggestionsBuilder,
reg: &Registries,
names: &dyn Fn(&mut SuggestionsBuilder),
) {
let mut reader = Reader {
string: builder.input,
cursor: builder.start,
};
let mut parser = SelectorParser::new(&mut reader, reg, reg.permission >= 2);
let _ = parser.parse();
parser.fill_suggestions(builder, names);
}
-981
View File
@@ -1,981 +0,0 @@
//! SnbtGrammar and TagParser: vanilla's packrat SNBT grammar, with its
//! error messages and completion suggestions, producing NBT tags.
use super::packrat::{Grammar, Reason, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq};
use super::{CmdResult, CommandError, Reader, SuggestionsBuilder};
use horizon_world::nbt::{Compound, JavaString, Tag};
use std::rc::Rc;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TypeSuffix {
Float,
Double,
Byte,
Short,
Int,
Long,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Base {
Binary,
Decimal,
Hex,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArrayPrefix {
Byte,
Int,
Long,
}
#[derive(Clone, Debug)]
pub struct IntLit {
minus: bool,
base: Base,
digits: String,
/// Some(true) signed, Some(false) unsigned.
signed: Option<bool>,
ty: Option<TypeSuffix>,
}
/// The values SnbtGrammar's rules produce.
#[derive(Clone, Debug)]
pub enum SV {
Tag(Tag),
Str(String),
/// A sign: true for minus.
Sign(bool),
Suffix(Option<bool>, Option<TypeSuffix>),
Type(TypeSuffix),
Int(IntLit),
/// float exponent: (minus, digits)
Exp(bool, String),
Prefix(ArrayPrefix),
List(Vec<SV>),
Entry(String, Tag),
}
impl Value for SV {
fn list(items: Vec<Self>) -> Self {
SV::List(items)
}
}
fn delayed(key: &'static str) -> Reason {
Reason::Delayed(key, Vec::new())
}
fn can_start_number(c: char) -> bool {
matches!(c, '+' | '-' | '.' | '0'..='9')
}
/// NumberRunParseRule.
fn number_run(
state: &mut State<SV>,
accept: fn(char) -> bool,
no_value: &'static str,
) -> Option<SV> {
let mut r = state.reader();
r.skip_whitespace();
state.set_reader(&r);
let start = state.cursor;
let rest = &state.input[start..];
let len: usize = rest
.chars()
.take_while(|c| accept(*c))
.map(char::len_utf8)
.sum();
if len == 0 {
state.store_at_mark(delayed(no_value));
return None;
}
let s = &rest[..len];
if s.starts_with('_') || s.ends_with('_') {
state.store_at_mark(delayed("snbt.parser.underscore_not_allowed"));
return None;
}
state.cursor = start + len;
Some(SV::Str(s.to_owned()))
}
/// GreedyPredicateParseRule (no whitespace skipping).
fn greedy(
state: &mut State<SV>,
accept: fn(char) -> bool,
min: usize,
max: usize,
error: Reason,
) -> Option<SV> {
let start = state.cursor;
let rest = &state.input[start..];
let mut len = 0;
let mut count = 0;
for c in rest.chars() {
if !accept(c) || count >= max {
break;
}
len += c.len_utf8();
count += c.len_utf16();
}
if count < min {
state.store_at_mark(error);
return None;
}
state.cursor = start + len;
Some(SV::Str(rest[..len].to_owned()))
}
fn number_error(message: String) -> Reason {
Reason::Delayed("snbt.parser.number_parse_failure", vec![message])
}
fn for_input(s: &str, radix: u32) -> String {
if radix == 10 {
format!("For input string: \"{s}\"")
} else {
format!("For input string: \"{s}\" under radix {radix}")
}
}
/// Long.parseLong(s, radix) with its NumberFormatException messages.
fn parse_long(s: &str, radix: u32) -> Result<i64, String> {
let digits = s.strip_prefix(['-', '+']).unwrap_or(s);
if digits.is_empty() {
return Err(for_input(s, radix));
}
i64::from_str_radix(s.strip_prefix('+').unwrap_or(s), radix).map_err(|_| for_input(s, radix))
}
fn parse_int(s: &str, radix: u32) -> Result<i32, String> {
let v = parse_long(s, radix).map_err(|_| for_input(s, radix))?;
i32::try_from(v).map_err(|_| for_input(s, radix))
}
fn parse_small(s: &str, radix: u32, lo: i32, hi: i32) -> Result<i32, String> {
let v = parse_int(s, radix)?;
if v < lo || v > hi {
return Err(format!("Value out of range. Value:\"{s}\" Radix:{radix}"));
}
Ok(v)
}
fn parse_unsigned_int(s: &str, radix: u32) -> Result<i32, String> {
if s.starts_with('-') {
return Err(format!(
"Illegal leading minus sign on unsigned string {s}."
));
}
let len = s.chars().count();
if len <= 5 || (radix == 10 && len <= 9) {
return parse_int(s, radix);
}
let v = parse_long(s, radix)?;
if (v as u64) & 0xffff_ffff_0000_0000 == 0 {
Ok(v as u32 as i32)
} else {
Err(format!("String value {s} exceeds range of unsigned int."))
}
}
fn parse_unsigned_long(s: &str, radix: u32) -> Result<i64, String> {
if s.starts_with('-') {
return Err(format!(
"Illegal leading minus sign on unsigned string {s}."
));
}
let digits = s.strip_prefix('+').unwrap_or(s);
match u64::from_str_radix(digits, radix) {
Ok(v) => Ok(v as i64),
Err(_) => {
if digits.chars().all(|c| c.is_digit(radix)) && !digits.is_empty() {
Err(format!("String value {s} exceeds range of unsigned long."))
} else {
Err(for_input(s, radix))
}
}
}
}
impl IntLit {
fn signed_or_default(&self) -> bool {
self.signed.unwrap_or(self.base == Base::Decimal)
}
fn cleaned(&self) -> String {
let mut out = String::new();
if self.minus {
out.push('-');
}
out.extend(self.digits.chars().filter(|c| *c != '_'));
out
}
/// IntegerLiteral.create with the given type.
fn create(&self, ty: TypeSuffix, state: &mut State<SV>) -> Option<Tag> {
let signed = self.signed_or_default();
if !signed && self.minus {
state.store_at_mark(delayed("snbt.parser.expected_non_negative_number"));
return None;
}
let s = self.cleaned();
let radix = match self.base {
Base::Binary => 2,
Base::Decimal => 10,
Base::Hex => 16,
};
let r = if signed {
match ty {
TypeSuffix::Byte => parse_small(&s, radix, -128, 127).map(|v| Tag::Byte(v as i8)),
TypeSuffix::Short => {
parse_small(&s, radix, -32768, 32767).map(|v| Tag::Short(v as i16))
}
TypeSuffix::Int => parse_int(&s, radix).map(Tag::Int),
TypeSuffix::Long => parse_long(&s, radix).map(Tag::Long),
_ => {
state.store_at_mark(delayed("snbt.parser.expected_integer_type"));
return None;
}
}
} else {
match ty {
TypeSuffix::Byte => parse_int(&s, radix).and_then(|v| {
if v >> 8 == 0 {
Ok(Tag::Byte(v as u8 as i8))
} else {
Err(format!("out of range: {v}"))
}
}),
TypeSuffix::Short => parse_int(&s, radix).and_then(|v| {
if v >> 16 == 0 {
Ok(Tag::Short(v as u16 as i16))
} else {
Err(format!("out of range: {v}"))
}
}),
TypeSuffix::Int => parse_unsigned_int(&s, radix).map(Tag::Int),
TypeSuffix::Long => parse_unsigned_long(&s, radix).map(Tag::Long),
_ => {
state.store_at_mark(delayed("snbt.parser.expected_integer_type"));
return None;
}
}
};
match r {
Ok(t) => Some(t),
Err(m) => {
state.store_at_mark(number_error(m));
None
}
}
}
}
fn float_tag(text: &str, ty: Option<TypeSuffix>, state: &mut State<SV>) -> Option<Tag> {
match ty {
Some(TypeSuffix::Float) => {
let v: f32 = text.parse().unwrap_or(f32::NAN);
if !v.is_finite() {
state.store_at_mark(delayed("snbt.parser.infinity_not_allowed"));
return None;
}
Some(Tag::Float(v.to_bits()))
}
None | Some(TypeSuffix::Double) => {
let v: f64 = text.parse().unwrap_or(f64::NAN);
if !v.is_finite() {
state.store_at_mark(delayed("snbt.parser.infinity_not_allowed"));
return None;
}
Some(Tag::Double(v.to_bits()))
}
_ => {
state.store_at_mark(delayed("snbt.parser.expected_float_type"));
None
}
}
}
fn get_str(state: &State<SV>, atom: &'static str) -> Option<String> {
match state.scope.get(atom) {
Some(SV::Str(s)) => Some(s),
_ => None,
}
}
fn get_tag(state: &State<SV>, atom: &'static str) -> Option<Tag> {
match state.scope.get(atom) {
Some(SV::Tag(t)) => Some(t),
_ => None,
}
}
fn get_list(state: &State<SV>, atom: &'static str) -> Vec<SV> {
match state.scope.get(atom) {
Some(SV::List(l)) => l,
_ => Vec::new(),
}
}
fn hex(c: char) -> bool {
c.is_ascii_hexdigit()
}
/// SnbtGrammar.createParser over NBT.
pub fn grammar() -> Grammar<SV> {
let mut g: Grammar<SV> = Grammar::new();
g.put_term(
"sign",
alt(vec![
seq(vec![ch('+'), Term::Marker("sign", SV::Sign(false))]),
seq(vec![ch('-'), Term::Marker("sign", SV::Sign(true))]),
]),
|s| s.scope.get("sign"),
);
let suffix = |signed: Option<bool>, ty: TypeSuffix| {
Term::Marker("integer_suffix", SV::Suffix(signed, Some(ty)))
};
let types = |signed: Option<bool>| {
alt(vec![
seq(vec![chs('b', 'B'), suffix(signed, TypeSuffix::Byte)]),
seq(vec![chs('s', 'S'), suffix(signed, TypeSuffix::Short)]),
seq(vec![chs('i', 'I'), suffix(signed, TypeSuffix::Int)]),
seq(vec![chs('l', 'L'), suffix(signed, TypeSuffix::Long)]),
])
};
g.put_term(
"integer_suffix",
alt(vec![
seq(vec![chs('u', 'U'), types(Some(false))]),
seq(vec![chs('s', 'S'), types(Some(true))]),
seq(vec![chs('b', 'B'), suffix(None, TypeSuffix::Byte)]),
seq(vec![chs('s', 'S'), suffix(None, TypeSuffix::Short)]),
seq(vec![chs('i', 'I'), suffix(None, TypeSuffix::Int)]),
seq(vec![chs('l', 'L'), suffix(None, TypeSuffix::Long)]),
]),
|s| s.scope.get("integer_suffix"),
);
g.put_custom("binary_numeral", |s| {
number_run(
s,
|c| matches!(c, '0' | '1' | '_'),
"snbt.parser.expected_binary_numeral",
)
});
g.put_custom("decimal_numeral", |s| {
number_run(
s,
|c| c.is_ascii_digit() || c == '_',
"snbt.parser.expected_decimal_numeral",
)
});
g.put_custom("hex_numeral", |s| {
number_run(
s,
|c| c.is_ascii_hexdigit() || c == '_',
"snbt.parser.expected_hex_numeral",
)
});
let sign = g.named("sign");
let hex_numeral = g.named("hex_numeral");
let binary_numeral = g.named("binary_numeral");
let decimal = g.named("decimal_numeral");
let decimal2 = g.named("decimal_numeral");
let isuffix = g.named("integer_suffix");
g.put_term(
"integer_literal",
seq(vec![
opt(sign),
alt(vec![
seq(vec![
ch('0'),
Term::Cut,
alt(vec![
seq(vec![chs('x', 'X'), Term::Cut, hex_numeral]),
seq(vec![chs('b', 'B'), binary_numeral]),
seq(vec![
decimal,
Term::Cut,
Term::Fail(delayed("snbt.parser.leading_zero_not_allowed")),
]),
Term::Marker("decimal_numeral", SV::Str("0".into())),
]),
]),
decimal2,
]),
opt(isuffix),
]),
|s| {
let (signed, ty) = match s.scope.get("integer_suffix") {
Some(SV::Suffix(a, b)) => (a, b),
_ => (None, None),
};
let minus = matches!(s.scope.get("sign"), Some(SV::Sign(true)));
let (base, digits) = if let Some(d) = get_str(s, "decimal_numeral") {
(Base::Decimal, d)
} else if let Some(h) = get_str(s, "hex_numeral") {
(Base::Hex, h)
} else {
(
Base::Binary,
get_str(s, "binary_numeral").unwrap_or_default(),
)
};
Some(SV::Int(IntLit {
minus,
base,
digits,
signed,
ty,
}))
},
);
g.put_term(
"float_type_suffix",
alt(vec![
seq(vec![
chs('f', 'F'),
Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Float)),
]),
seq(vec![
chs('d', 'D'),
Term::Marker("float_type_suffix", SV::Type(TypeSuffix::Double)),
]),
]),
|s| s.scope.get("float_type_suffix"),
);
let sign = g.named("sign");
let decimal = g.named("decimal_numeral");
g.put_term(
"float_exponent_part",
seq(vec![chs('e', 'E'), opt(sign), decimal]),
|s| {
let minus = matches!(s.scope.get("sign"), Some(SV::Sign(true)));
Some(SV::Exp(
minus,
get_str(s, "decimal_numeral").unwrap_or_default(),
))
},
);
let sign = g.named("sign");
let mut whole = || g.named_as("decimal_numeral", "float_whole_part");
let (w1, w2, w3) = (whole(), whole(), whole());
let f1 = g.named_as("decimal_numeral", "float_fraction_part");
let f2 = g.named_as("decimal_numeral", "float_fraction_part");
let mut exp = || g.named("float_exponent_part");
let (e1, e2, e3, e4) = (exp(), exp(), exp(), exp());
let mut fs = || g.named("float_type_suffix");
let (s1, s2, s3, s4) = (fs(), fs(), fs(), fs());
g.put_term(
"float_literal",
seq(vec![
opt(sign),
alt(vec![
seq(vec![w1, ch('.'), Term::Cut, opt(f1), opt(e1), opt(s1)]),
seq(vec![ch('.'), Term::Cut, f2, opt(e2), opt(s2)]),
seq(vec![w2, e3, Term::Cut, opt(s3)]),
seq(vec![w3, opt(e4), s4]),
]),
]),
|s| {
let minus = matches!(s.scope.get("sign"), Some(SV::Sign(true)));
let mut text = String::new();
if minus {
text.push('-');
}
if let Some(w) = get_str(s, "float_whole_part") {
text.extend(w.chars().filter(|c| *c != '_'));
}
if let Some(f) = get_str(s, "float_fraction_part") {
text.push('.');
text.extend(f.chars().filter(|c| *c != '_'));
}
if let Some(SV::Exp(m, d)) = s.scope.get("float_exponent_part") {
text.push('e');
if m {
text.push('-');
}
text.extend(d.chars().filter(|c| *c != '_'));
}
let ty = match s.scope.get("float_type_suffix") {
Some(SV::Type(t)) => Some(t),
_ => None,
};
float_tag(&text, ty, s).map(SV::Tag)
},
);
for (name, n) in [
("string_hex_2", 2),
("string_hex_4", 4),
("string_hex_8", 8),
] {
g.put_custom(name, move |s| {
greedy(
s,
hex,
n,
n,
Reason::Delayed("snbt.parser.expected_hex_escape", vec![n.to_string()]),
)
});
}
g.put_custom("string_unicode_name", |s| {
greedy(
s,
|c| c.is_ascii_alphanumeric() || c == '-' || c == ' ',
1,
usize::MAX,
delayed("snbt.parser.invalid_character_name"),
)
});
let esc = |c: char, v: &str| {
seq(vec![
ch(c),
Term::Marker("string_escape_sequence", SV::Str(v.into())),
])
};
let h2 = g.named("string_hex_2");
let h4 = g.named("string_hex_4");
let h8 = g.named("string_hex_8");
let un = g.named("string_unicode_name");
g.put_term(
"string_escape_sequence",
alt(vec![
esc('b', "\u{8}"),
esc('s', " "),
esc('t', "\t"),
esc('n', "\n"),
esc('f', "\u{c}"),
esc('r', "\r"),
esc('\\', "\\"),
esc('\'', "'"),
esc('"', "\""),
seq(vec![ch('x'), h2]),
seq(vec![ch('u'), h4]),
seq(vec![ch('U'), h8]),
seq(vec![ch('N'), ch('{'), un, ch('}')]),
]),
|s| {
if let Some(SV::Str(plain)) = s.scope.get_any(&["string_escape_sequence"]) {
return Some(SV::Str(plain));
}
if let Some(SV::Str(h)) =
s.scope
.get_any(&["string_hex_2", "string_hex_4", "string_hex_8"])
{
let cp = u32::from_str_radix(&h, 16).unwrap_or(u32::MAX);
if cp > 0x10ffff {
s.store_at_mark(Reason::Delayed(
"snbt.parser.invalid_codepoint",
vec![format!("U+{cp:08X}")],
));
return None;
}
return Some(SV::Str(
char::from_u32(cp).unwrap_or('\u{fffd}').to_string(),
));
}
// Character.codePointOf: Unicode names are not tabulated here.
s.store_at_mark(delayed("snbt.parser.invalid_character_name"));
None
},
);
g.put_custom("string_plain_contents", |s| {
greedy(
s,
|c| !matches!(c, '"' | '\'' | '\\'),
1,
usize::MAX,
delayed("snbt.parser.invalid_string_contents"),
)
});
for (chunk, contents, other) in [
(
"single_quoted_string_chunk",
"single_quoted_string_contents",
'"',
),
(
"double_quoted_string_chunk",
"double_quoted_string_contents",
'\'',
),
] {
let plain = g.named_as("string_plain_contents", "string_contents");
let escape = g.named_as("string_escape_sequence", "string_contents");
g.put_term(
chunk,
alt(vec![
plain,
seq(vec![ch('\\'), escape]),
seq(vec![
ch(other),
Term::Marker("string_contents", SV::Str(other.to_string())),
]),
]),
|s| s.scope.get("string_contents"),
);
let rule = g.id(chunk);
g.put_term(
contents,
Term::Repeated {
rule,
list: "string_chunks",
min: 0,
},
|s| {
let mut out = String::new();
for v in get_list(s, "string_chunks") {
if let SV::Str(x) = v {
out.push_str(&x);
}
}
Some(SV::Str(out))
},
);
}
let dq = g.named_as("double_quoted_string_contents", "string_contents");
let sq = g.named_as("single_quoted_string_contents", "string_contents");
g.put_term(
"quoted_string_literal",
alt(vec![
seq(vec![ch('"'), Term::Cut, opt(dq), ch('"')]),
seq(vec![ch('\''), opt(sq), ch('\'')]),
]),
|s| s.scope.get("string_contents"),
);
g.put_custom("unquoted_string", |s| {
let mut r = s.reader();
r.skip_whitespace();
s.set_reader(&r);
let cursor = s.cursor;
let v = r.read_unquoted_string();
s.set_reader(&r);
if v.is_empty() {
s.store(
cursor,
Sugg::Empty,
delayed("snbt.parser.expected_unquoted_string"),
);
return None;
}
Some(SV::Str(v.to_owned()))
});
let literal = g.id("literal");
g.put_term(
"arguments",
Term::RepeatedSep {
rule: literal,
list: "arguments",
sep: Box::new(ch(',')),
min: 0,
trailing: true,
},
|s| s.scope.get("arguments"),
);
let uq = g.named("unquoted_string");
let args = g.named("arguments");
g.put_term(
"unquoted_string_or_builtin",
seq(vec![uq, opt(seq(vec![ch('('), args, ch(')')]))]),
|s| {
let contents = get_str(s, "unquoted_string").unwrap_or_default();
let first = contents.chars().next();
if first.is_some_and(|c| !can_start_number(c)) {
if let Some(SV::List(arguments)) = s.scope.get("arguments") {
return builtin(&contents, arguments, s);
}
if contents.eq_ignore_ascii_case("true") {
return Some(SV::Tag(Tag::Byte(1)));
}
if contents.eq_ignore_ascii_case("false") {
return Some(SV::Tag(Tag::Byte(0)));
}
return Some(SV::Tag(Tag::String(JavaString::from(contents.as_str()))));
}
let ids = ["false", "true", "bool", "uuid"].map(String::from).to_vec();
s.store(
s.cursor,
Sugg::Values(Rc::new(ids)),
delayed("snbt.parser.invalid_unquoted_start"),
);
None
},
);
let qs = g.named("quoted_string_literal");
let uq = g.named("unquoted_string");
g.put_term("map_key", alt(vec![qs, uq]), |s| {
s.scope
.get_any(&["quoted_string_literal", "unquoted_string"])
});
let key = g.named("map_key");
let lit = g.named("literal");
g.put_term("map_entry", seq(vec![key, ch(':'), lit]), |s| {
let key = get_str(s, "map_key").unwrap_or_default();
if key.is_empty() {
s.store_at_mark(delayed("snbt.parser.empty_key"));
return None;
}
let value = get_tag(s, "literal")?;
Some(SV::Entry(key, value))
});
let entry = g.id("map_entry");
g.put_term(
"map_entries",
Term::RepeatedSep {
rule: entry,
list: "map_entries",
sep: Box::new(ch(',')),
min: 0,
trailing: true,
},
|s| s.scope.get("map_entries"),
);
let entries = g.named("map_entries");
g.put_term("map_literal", seq(vec![ch('{'), entries, ch('}')]), |s| {
let mut map = Compound::new();
for e in get_list(s, "map_entries") {
if let SV::Entry(k, v) = e {
map.insert(JavaString::from(k.as_str()), v);
}
}
Some(SV::Tag(Tag::Compound(map)))
});
g.put_term(
"list_entries",
Term::RepeatedSep {
rule: literal,
list: "list_entries",
sep: Box::new(ch(',')),
min: 0,
trailing: true,
},
|s| s.scope.get("list_entries"),
);
g.put_term(
"array_prefix",
alt(vec![
seq(vec![
ch('B'),
Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Byte)),
]),
seq(vec![
ch('L'),
Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Long)),
]),
seq(vec![
ch('I'),
Term::Marker("array_prefix", SV::Prefix(ArrayPrefix::Int)),
]),
]),
|s| s.scope.get("array_prefix"),
);
let int_lit = g.id("integer_literal");
g.put_term(
"int_array_entries",
Term::RepeatedSep {
rule: int_lit,
list: "int_array_entries",
sep: Box::new(ch(',')),
min: 0,
trailing: true,
},
|s| s.scope.get("int_array_entries"),
);
let prefix = g.named("array_prefix");
let ia = g.named("int_array_entries");
let le = g.named("list_entries");
g.put_term(
"list_literal",
seq(vec![
ch('['),
alt(vec![seq(vec![prefix, ch(';'), ia]), le]),
ch(']'),
]),
|s| {
if let Some(SV::Prefix(p)) = s.scope.get("array_prefix") {
let entries = get_list(s, "int_array_entries");
return array(p, entries, s).map(SV::Tag);
}
let items: Vec<Tag> = get_list(s, "list_entries")
.into_iter()
.filter_map(|v| match v {
SV::Tag(t) => Some(t),
_ => None,
})
.collect();
Some(SV::Tag(Tag::List(items)))
},
);
let float_lit = g.named_as("float_literal", "literal");
let int_named = g.named("integer_literal");
let quoted = g.named("quoted_string_literal");
let map = g.named_as("map_literal", "literal");
let list = g.named_as("list_literal", "literal");
let builtin_term = g.named_as("unquoted_string_or_builtin", "literal");
g.put_term(
"literal",
alt(vec![
seq(vec![
look(Term::Chars {
values: Vec::new(),
accept: Some(can_start_number),
}),
alt(vec![float_lit, int_named]),
]),
seq(vec![look(chs('"', '\'')), Term::Cut, quoted]),
seq(vec![look(ch('{')), Term::Cut, map]),
seq(vec![look(ch('[')), Term::Cut, list]),
builtin_term,
]),
|s| {
if let Some(q) = get_str(s, "quoted_string_literal") {
return Some(SV::Tag(Tag::String(JavaString::from(q.as_str()))));
}
if let Some(SV::Int(i)) = s.scope.get("integer_literal") {
let ty = i.ty.unwrap_or(TypeSuffix::Int);
return i.create(ty, s).map(SV::Tag);
}
s.scope.get("literal")
},
);
g.top = literal;
g
}
fn array(p: ArrayPrefix, entries: Vec<SV>, s: &mut State<SV>) -> Option<Tag> {
let (default, allowed): (TypeSuffix, &[TypeSuffix]) = match p {
ArrayPrefix::Byte => (TypeSuffix::Byte, &[]),
ArrayPrefix::Int => (TypeSuffix::Int, &[TypeSuffix::Byte, TypeSuffix::Short]),
ArrayPrefix::Long => (
TypeSuffix::Long,
&[TypeSuffix::Byte, TypeSuffix::Short, TypeSuffix::Int],
),
};
let mut values: Vec<i64> = Vec::new();
for e in entries {
let SV::Int(lit) = e else { continue };
let ty = match lit.ty {
None => default,
Some(t) if t == default || allowed.contains(&t) => t,
Some(_) => {
s.store_at_mark(delayed("snbt.parser.invalid_array_element_type"));
return None;
}
};
let v = match lit.create(ty, s)? {
Tag::Byte(v) => i64::from(v),
Tag::Short(v) => i64::from(v),
Tag::Int(v) => i64::from(v),
Tag::Long(v) => v,
_ => 0,
};
values.push(v);
}
Some(match p {
ArrayPrefix::Byte => Tag::ByteArray(values.iter().map(|v| *v as i8 as u8).collect()),
ArrayPrefix::Int => Tag::IntArray(values.iter().map(|v| *v as i32).collect()),
ArrayPrefix::Long => Tag::LongArray(values),
})
}
fn builtin(id: &str, arguments: Vec<SV>, s: &mut State<SV>) -> Option<SV> {
let args: Vec<Tag> = arguments
.into_iter()
.filter_map(|v| match v {
SV::Tag(t) => Some(t),
_ => None,
})
.collect();
match (id, args.len()) {
("bool", 1) => {
let b = match &args[0] {
Tag::Byte(v) => Some(*v != 0),
Tag::Short(v) => Some(*v != 0),
Tag::Int(v) => Some(*v != 0),
Tag::Long(v) => Some(*v != 0),
Tag::Float(v) => Some(f32::from_bits(*v) != 0.0),
Tag::Double(v) => Some(f64::from_bits(*v) != 0.0),
_ => None,
};
match b {
Some(b) => Some(SV::Tag(Tag::Byte(i8::from(b)))),
None => {
s.store_at_mark(delayed("snbt.parser.expected_number_or_boolean"));
None
}
}
}
("uuid", 1) => {
let parsed = match &args[0] {
Tag::String(text) => super::selector::java_uuid(&text.to_string_lossy()),
_ => None,
};
match parsed {
Some(u) => Some(SV::Tag(Tag::IntArray(vec![
(u >> 96) as u32 as i32,
(u >> 64) as u32 as i32,
(u >> 32) as u32 as i32,
u as u32 as i32,
]))),
None => {
s.store_at_mark(delayed("snbt.parser.expected_string_uuid"));
None
}
}
}
_ => {
s.store_at_mark(Reason::Delayed(
"snbt.parser.no_such_operation",
vec![format!("{id}/{}", args.len())],
));
None
}
}
}
thread_local! {
static GRAMMAR: Grammar<SV> = grammar();
}
/// TagParser.parseAsArgument: one SNBT value at the reader's cursor.
pub fn parse_tag_argument(reader: &mut Reader) -> CmdResult<Tag> {
GRAMMAR.with(|g| match g.parse_for_commands(reader)? {
SV::Tag(t) => Ok(t),
_ => Err(CommandError::tr_at(
"argument.nbt.expected.compound",
&[],
reader,
)),
})
}
/// TagParser.parseCompoundAsArgument.
pub fn parse_compound_argument(reader: &mut Reader) -> CmdResult<Compound> {
match parse_tag_argument(reader)? {
Tag::Compound(c) => Ok(c),
_ => Err(CommandError::tr_at(
"argument.nbt.expected.compound",
&[],
reader,
)),
}
}
/// TagParser.parseFully.
pub fn parse_fully(text: &str) -> CmdResult<Tag> {
let mut reader = Reader::new(text);
let tag = parse_tag_argument(&mut reader)?;
reader.skip_whitespace();
if reader.can_read() {
return Err(CommandError::tr_at("argument.nbt.trailing", &[], &reader));
}
Ok(tag)
}
/// The grammar's completion suggestions (ParserBasedArgument.listSuggestions).
pub fn suggest(builder: &mut SuggestionsBuilder) {
GRAMMAR.with(|g| g.parse_for_suggestions(builder));
}
/// Parse with an outer state (TagParseRule inside another grammar).
pub fn rule_in<V: super::packrat::Value>(
state: &mut State<V>,
wrap: impl Fn(Tag) -> V,
) -> Option<V> {
let mut r = state.reader();
r.skip_whitespace();
state.set_reader(&r);
let mark = state.cursor;
let mut reader = state.reader();
match parse_tag_argument(&mut reader) {
Ok(t) => {
state.set_reader(&reader);
Some(wrap(t))
}
Err(e) => {
state.store(mark, Sugg::Empty, Reason::Error(e));
None
}
}
}
-612
View File
@@ -1,612 +0,0 @@
use super::{args::*, vanilla, *};
fn reg() -> Registries {
let mut r = Registries {
permission: 4,
..Registries::default()
};
r.items = vec![
"minecraft:diamond".into(),
"minecraft:diamond_sword".into(),
"minecraft:stone".into(),
];
r.blocks.insert("minecraft:stone".into(), vec![]);
r.blocks.insert(
"minecraft:oak_stairs".into(),
vec![
("facing".into(), vec!["north".into(), "south".into()]),
("half".into(), vec!["top".into(), "bottom".into()]),
],
);
r.summonable = vec!["minecraft:pig".into(), "minecraft:zombie".into()];
r.entity_types = vec![
"minecraft:pig".into(),
"minecraft:player".into(),
"minecraft:zombie".into(),
];
r.players = vec!["Player".into()];
r.dimensions = vec!["minecraft:overworld".into()];
r.time_markers = vec!["minecraft:day".into(), "minecraft:noon".into()];
// The registry elements the commands below name (vanilla checks them while parsing).
let mut registry = |name: &str, ids: &[&str]| {
r.by_registry.insert(
name.into(),
RegistryIds {
ids: ids.iter().map(|s| (*s).to_owned()).collect(),
tags: Vec::new(),
},
);
};
registry(
"minecraft:worldgen/biome",
&["minecraft:desert", "minecraft:plains"],
);
registry(
"minecraft:damage_type",
&["minecraft:fall", "minecraft:magic"],
);
registry(
"minecraft:attribute",
&["minecraft:max_health", "minecraft:scale"],
);
registry("minecraft:item_modifier", &["a:b"]);
registry("minecraft:predicate", &["a:b"]);
registry(
"minecraft:loot_table",
&[
"minecraft:chests/simple_dungeon",
"minecraft:chests/x",
"minecraft:gameplay/fishing",
],
);
registry(
"minecraft:entity_type",
&["minecraft:pig", "minecraft:player", "minecraft:zombie"],
);
registry(
"minecraft:item",
&[
"minecraft:diamond",
"minecraft:diamond_sword",
"minecraft:stone",
],
);
r
}
fn run(input: &str) -> CmdResult<(String, Vec<String>)> {
let reg = reg();
let parse = vanilla::dispatcher().parse(input, &reg);
let (ctx, id) = parse.executable()?;
Ok((
id.to_owned(),
ctx.args.iter().map(|a| a.name.clone()).collect(),
))
}
fn suggestions(input: &str) -> Vec<String> {
let reg = reg();
let d = vanilla::dispatcher();
let parse = d.parse(input, &reg);
d.suggestions(&parse, input.len(), &reg)
.1
.into_iter()
.map(|s| s.text)
.collect()
}
#[test]
fn reader_matches_brigadier() {
let mut r = Reader::new("12 -3.5 abc \"q\\\"x\" true");
assert_eq!(r.read_int().unwrap(), 12);
r.skip();
assert_eq!(r.read_double().unwrap(), -3.5);
r.skip();
assert_eq!(r.read_unquoted_string(), "abc");
r.skip();
assert_eq!(r.read_string().unwrap(), "q\"x");
r.skip();
assert!(r.read_boolean().unwrap());
let e = Reader::new("1.5").read_int().unwrap_err();
assert_eq!(e.message.plain(), "parsing.int.invalid");
assert_eq!(e.context().unwrap(), "<--[HERE]");
}
#[test]
fn parses_vanilla_commands() {
assert_eq!(run("gamemode creative").unwrap().0, "gamemode");
assert_eq!(
run("gamemode creative @s").unwrap().1,
["gamemode", "target"]
);
assert_eq!(
run("give @s minecraft:diamond 64").unwrap().1,
["targets", "item", "count"]
);
assert_eq!(run("tp 1 2 3").unwrap().0, "teleport.location");
assert_eq!(run("tp Player").unwrap().0, "teleport.destination");
assert_eq!(run("tp @s ~ ~10 ~").unwrap().0, "teleport.targets.location");
assert_eq!(
run("teleport @e[type=pig,limit=2] ^ ^ ^5 90 0").unwrap().0,
"teleport.targets.location"
);
assert_eq!(run("time set 1000").unwrap().0, "time.set");
assert_eq!(run("time set 1d").unwrap().0, "time.set");
assert_eq!(run("time set day").unwrap().0, "time.set.marker");
assert_eq!(run("time query gametime").unwrap().0, "time.query.gametime");
assert_eq!(run("weather rain 10s").unwrap().0, "weather");
assert_eq!(run("xp add @s 5 levels").unwrap().0, "experience");
assert_eq!(run("gamerule keep_inventory true").unwrap().0, "gamerule");
assert_eq!(
run("gamerule minecraft:random_tick_speed 10").unwrap().0,
"gamerule"
);
assert_eq!(run("fill ~ ~ ~ ~1 ~1 ~1 stone hollow").unwrap().0, "fill");
assert_eq!(
run("fill 0 0 0 1 1 1 minecraft:oak_stairs[facing=north] replace stone")
.unwrap()
.0,
"fill"
);
assert_eq!(
run("clone 0 0 0 1 1 1 5 5 5 masked move").unwrap().0,
"clone"
);
assert_eq!(
run("setblock ~ ~1 ~ oak_stairs[half=top] keep").unwrap().0,
"setblock"
);
assert_eq!(run("summon zombie ~ ~ ~ {NoAI:1b}").unwrap().0, "summon");
assert_eq!(run("difficulty hard").unwrap().0, "difficulty");
assert_eq!(run("say hello @p").unwrap().0, "say");
let reg = reg();
let parse =
vanilla::dispatcher().parse("clone 0 0 0 1 1 1 5 5 5 strict filtered stone force", &reg);
let (ctx, _) = parse.executable().unwrap();
assert!(ctx.has("strict") && ctx.has("filtered") && ctx.has("force") && !ctx.has("move"));
}
#[test]
fn vanilla_error_messages() {
let e = run("foo").unwrap_err();
assert_eq!(e.message.plain(), "command.unknown.command");
assert_eq!(e.cursor, 0);
let e = run("gamemode").unwrap_err();
assert_eq!(e.message.plain(), "command.unknown.command");
let e = run("gamemode creatve").unwrap_err();
assert_eq!(e.message.plain(), "argument.gamemode.invalid");
// GameModeArgument reports the error after the word.
assert_eq!(e.cursor, 16);
let e = run("give @s minecraft:dirt").unwrap_err();
assert_eq!(e.message.plain(), "argument.item.id.invalid");
let e = run("give @s diamond 0").unwrap_err();
assert_eq!(e.message.plain(), "argument.integer.low");
let e = run("gamemode creative @e").unwrap_err();
assert_eq!(e.message.plain(), "argument.player.entities");
let e = run("setblock 1 2").unwrap_err();
assert_eq!(e.message.plain(), "argument.pos3d.incomplete");
let e = run("setblock 1 2 3 oak_stairs[facing=up]").unwrap_err();
assert_eq!(e.message.plain(), "argument.block.property.invalid");
}
#[test]
fn commands_need_allow_commands() {
// IntegratedServer.getProfilePermissions: the owner of a world without
// Allow Commands is at LevelBasedPermissionSet.ALL.
let reg = Registries {
permission: 0,
..reg()
};
let d = vanilla::game_dispatcher();
let e = d.parse("gamemode creative", &reg).executable().unwrap_err();
assert_eq!(e.message.plain(), "command.unknown.command");
assert!(d.parse("me waves", &reg).executable().is_ok());
let parse = d.parse("", &reg);
// Brigadier itself lists every literal; the chat's (client tree) only
// the ones the player may use.
assert!(
d.suggestions(&parse, 0, &reg)
.1
.iter()
.any(|s| s.text == "gamemode")
);
let root: Vec<String> = d
.client_suggestions(&parse, 0, &reg)
.1
.into_iter()
.map(|s| s.text)
.collect();
// Commands.java with CommandSelection.INTEGRATED: seed and version need no level.
assert_eq!(
root,
[
"help", "list", "me", "msg", "random", "seed", "teammsg", "tell", "tm", "trigger",
"version", "w"
]
);
}
#[test]
fn suggestions_like_vanilla() {
let root = suggestions("");
assert!(root.contains(&"gamemode".to_owned()) && root.contains(&"tp".to_owned()));
assert_eq!(suggestions("game"), ["gamemode", "gamerule"]);
assert_eq!(
suggestions("gamemode "),
["adventure", "creative", "spectator", "survival"]
);
assert_eq!(suggestions("gamemode c"), ["creative"]);
assert_eq!(
suggestions("give @s dia"),
["minecraft:diamond", "minecraft:diamond_sword"]
);
// Underscore-separated parts match too (SharedSuggestionProvider.matchesSubStr).
assert_eq!(suggestions("give @s sword"), ["minecraft:diamond_sword"]);
assert_eq!(suggestions("kill @"), ["@a", "@e", "@n", "@p", "@r", "@s"]);
assert_eq!(suggestions("kill @e"), ["["]);
assert_eq!(suggestions("kill @e[ty"), ["type="]);
assert!(suggestions("kill @e[type=").contains(&"minecraft:zombie".to_owned()));
assert_eq!(suggestions("kill @e[type=pig"), [",", "]"]);
assert_eq!(suggestions("setblock 0 0 0 oak_stairs[fa"), ["facing="]);
// BlockStateParser suggests every value of the property, unfiltered.
assert_eq!(
suggestions("setblock 0 0 0 oak_stairs[facing=n"),
["north", "south"]
);
assert_eq!(
suggestions("tp "),
[
"@a", "@e", "@n", "@p", "@r", "@s", "Player", "~", "~ ~", "~ ~ ~"
]
);
assert_eq!(suggestions("time set 5"), ["d", "s", "t"]);
assert!(suggestions("time set ").contains(&"minecraft:day".to_owned()));
}
#[test]
fn smart_usage_matches_brigadier() {
let d = vanilla::dispatcher();
let usage = |name: &str| {
d.smart_usage(0, 4)
.into_iter()
.find(|(n, _)| d.nodes[*n].name() == name)
.unwrap()
.1
};
assert_eq!(usage("gamemode"), "gamemode <gamemode> [<target>]");
assert_eq!(usage("give"), "give <targets> <item> [<count>]");
assert_eq!(usage("kill"), "kill [<targets>]");
assert_eq!(usage("weather"), "weather (clear|rain|thunder)");
assert_eq!(usage("tp"), "tp -> teleport");
assert_eq!(
usage("difficulty"),
"difficulty [peaceful|easy|normal|hard]"
);
}
#[test]
fn local_coordinates_follow_view() {
// Facing south (yaw 0) moves +Z.
let p = Coordinates::Local([0.0, 0.0, 2.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]);
assert!((p[2] - 2.0).abs() < 1e-6 && p[0].abs() < 1e-6);
// ^1 (left) while facing south is +X.
let p = Coordinates::Local([1.0, 0.0, 0.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]);
assert!((p[0] - 1.0).abs() < 1e-6, "{p:?}");
let w = Coordinates::World([
Coord {
relative: true,
value: 1.0,
},
Coord {
relative: false,
value: 5.0,
},
Coord {
relative: true,
value: 0.0,
},
]);
assert_eq!(w.position([10.0, 64.0, 3.0], [0.0, 0.0]), [11.0, 5.0, 3.0]);
}
#[test]
fn data_and_tag_commands_parse() {
let (id, args) = run("data get entity @s Pos 2.5").unwrap();
assert_eq!(id, "data.get");
assert_eq!(args, ["target", "path", "scale"]);
assert_eq!(run("data get block ~ ~ ~ Items[0]").unwrap().0, "data.get");
assert_eq!(
run("item modify entity @s weapon.mainhand a:b").unwrap().0,
"item.modify"
);
assert_eq!(
run("item modify block 1 2 3 container.0 a:b").unwrap().0,
"item.modify"
);
assert_eq!(run("data get storage my:store").unwrap().0, "data.get");
assert_eq!(run("data merge storage a:b {x:1}").unwrap().0, "data.merge");
assert_eq!(
run("data remove entity @s foo.bar[1]").unwrap().0,
"data.remove"
);
let (id, args) = run("data modify storage a:b x.y insert 2 from entity @s Pos[0]").unwrap();
assert_eq!(id, "data.modify");
assert_eq!(
args,
["target", "targetPath", "index", "source", "sourcePath"]
);
assert_eq!(
run("data modify block 1 2 3 Text1 set string storage a:b x 1 3")
.unwrap()
.0,
"data.modify"
);
assert_eq!(
run("data modify storage a:b l append value [1,2]")
.unwrap()
.0,
"data.modify"
);
assert!(run("data modify storage a:b l explode value 1").is_err());
assert!(run("data get storage a:b {broken").is_err());
assert!(run("data merge storage a:b 5").is_err());
assert_eq!(run("tag @e[tag=!x] add foo").unwrap().0, "tag.add");
assert_eq!(run("tag @s list").unwrap().0, "tag.list");
// Selector options added for scoreboards and NBT.
assert!(run("kill @e[scores={a=1..},team=red,nbt={x:1b},tag=t]").is_ok());
assert!(run("kill @e[scores={a=1..]").is_err());
}
#[test]
fn smoke_commands_parse() {
for line in [
"tag @s list",
"random value 1..6",
"team list",
"data get storage a:b",
"scoreboard objectives list",
"function test:a",
"execute store result score #r t run function test:a",
"schedule function test:a 20t",
"datapack list",
"bossbar list",
"item replace entity @s hotbar.0 with minecraft:stone 3",
] {
assert!(run(line).is_ok(), "{line}: {:?}", run(line).err());
}
}
#[test]
fn execute_tree_covers_vanilla_forms() {
for line in [
"execute as @a at @s run say hi",
"execute store result score @s x run data get entity @s Health",
"execute store success bossbar minecraft:b value run say hi",
"execute store result storage a:b out int 1.5 run time query gametime",
"execute store result entity @s Air short 1 run say hi",
"execute if score @s a = @s b run say hi",
"execute unless score @s a matches ..5 run say hi",
"execute if block ~ ~ ~ minecraft:stone",
"execute if blocks 0 0 0 1 1 1 5 5 5 masked run say hi",
"execute if biome ~ ~ ~ minecraft:plains",
"execute if loaded ~ ~ ~",
"execute if dimension minecraft:overworld",
"execute if data entity @s Inventory[0]",
"execute unless data storage a:b x run say hi",
"execute if predicate a:b",
"execute if function a:b run say hi",
"execute if items entity @s hotbar.* minecraft:stone",
"execute if slots block 0 0 0 container.*",
"execute positioned over world_surface run say hi",
"execute summon minecraft:pig run say hi",
"execute on vehicle run say hi",
"execute on passengers as @s run say hi",
"execute rotated as @s facing entity @s eyes align xyz anchored feet in minecraft:overworld run say hi",
] {
assert!(run(line).is_ok(), "{line}: {:?}", run(line).err());
}
assert!(run("execute positioned over nothing run say hi").is_err());
assert!(run("execute on nobody run say hi").is_err());
assert!(run("execute store result score @s").is_err());
}
#[test]
fn function_and_misc_trees() {
assert_eq!(run("function a:b").unwrap().0, "function");
assert_eq!(run("function #a:tag {x:1}").unwrap().0, "function");
assert_eq!(
run("function a:b with storage c:d path.x").unwrap().0,
"function"
);
assert_eq!(run("return 5").unwrap().0, "return.value");
assert_eq!(run("return fail").unwrap().0, "return.fail");
assert_eq!(run("return run say hi").unwrap().0, "say");
assert_eq!(
run("schedule function a:b 5s append").unwrap().0,
"schedule.function"
);
assert_eq!(run("schedule clear a:b").unwrap().0, "schedule.clear");
assert_eq!(run("random roll 1..20").unwrap().0, "random.roll");
assert_eq!(
run("random reset * 5 true false").unwrap().0,
"random.reset"
);
assert_eq!(run("teammsg hi there").unwrap().0, "teammsg");
assert_eq!(run("tm hi").unwrap().0, "teammsg");
assert_eq!(
run("bossbar set a:b color pink").unwrap().0,
"bossbar.set.color"
);
assert_eq!(
run("bossbar set a:b players @a").unwrap().0,
"bossbar.set.players"
);
assert_eq!(run("bossbar get a:b max").unwrap().0, "bossbar.get");
assert_eq!(
run("item fill block 1 2 3 container.* with minecraft:stone 5")
.unwrap()
.0,
"item"
);
assert_eq!(
run("item replace entity @s armor.head from block 0 0 0 container.3")
.unwrap()
.0,
"item"
);
assert_eq!(run("tick rate 40").unwrap().0, "tick.rate");
assert_eq!(run("tick step 1s").unwrap().0, "tick.step");
assert_eq!(run("reload").unwrap().0, "reload");
assert_eq!(
run("datapack enable \"file/x\" after \"file/y\"")
.unwrap()
.0,
"datapack.enable"
);
assert!(run("bossbar set a:b value -1").is_err());
assert!(run("item replace entity @s nowhere.0 with minecraft:stone").is_err());
}
#[test]
fn world_command_trees() {
for (line, id) in [
("recipe give @s *", "recipe.give"),
("recipe take @a minecraft:stick", "recipe.take"),
("damage @e[limit=1] 5", "damage"),
(
"damage @s 3.5 minecraft:magic by @e[limit=1] from @s",
"damage",
),
("damage @s 3 minecraft:fall at ~ ~ ~", "damage"),
("rotate @s 90 0", "rotate"),
("rotate @s facing entity @e[limit=1] eyes", "rotate"),
("rotate @s facing 0 64 0", "rotate"),
("swing", "swing"),
("swing @e offhand whack 10", "swing"),
("playsound minecraft:entity.cow.ambient", "playsound"),
(
"playsound minecraft:block.stone.break block @s ~ ~ ~ 1 1 0.5",
"playsound",
),
("stopsound @s", "stopsound"),
("stopsound @s * minecraft:ambient.cave", "stopsound"),
("stopsound @s music minecraft:music.game", "stopsound"),
("particle minecraft:smoke", "particle"),
(
"particle minecraft:dust{color:[1.0,0.0,0.0],scale:2.0} ~ ~ ~ 0.1 0.1 0.1 0 10 force @a",
"particle",
),
(
"particle minecraft:block{block_state:\"minecraft:stone\"} ~ ~ ~",
"particle",
),
("attribute @s minecraft:max_health get 2", "attribute.get"),
(
"attribute @s minecraft:max_health base set 40",
"attribute.base.set",
),
(
"attribute @s minecraft:scale modifier add a:b 1.5 add_multiplied_base",
"attribute.modifier.add",
),
(
"attribute @s minecraft:scale modifier remove a:b",
"attribute.modifier.remove",
),
(
"attribute @s minecraft:scale modifier value get a:b 2",
"attribute.modifier.get",
),
("ride @s mount @e[limit=1]", "ride.mount"),
("ride @s dismount", "ride.dismount"),
("spreadplayers 0 0 5 20 false @a", "spreadplayers"),
("spreadplayers ~ ~ 5 20 under 100 true @e", "spreadplayers"),
("forceload add 0 0 100 100", "forceload.add"),
("forceload remove all", "forceload.remove.all"),
("forceload query", "forceload.query"),
("forceload query ~ ~", "forceload.query"),
(
"fillbiome 0 0 0 10 10 10 minecraft:plains replace minecraft:desert",
"fillbiome",
),
("worldborder set 100 5s", "worldborder.set"),
("worldborder add -10", "worldborder.add"),
("worldborder center 5 5", "worldborder.center"),
("worldborder damage amount 1", "worldborder.damage.amount"),
("worldborder warning time 10s", "worldborder.warning.time"),
("worldborder get", "worldborder.get"),
(
"loot give @s loot minecraft:chests/simple_dungeon",
"loot.loot",
),
("loot spawn ~ ~ ~ kill @e[limit=1]", "loot.kill"),
("loot insert 0 0 0 mine 1 2 3 mainhand", "loot.mine"),
(
"loot replace entity @s hotbar.0 3 fish minecraft:gameplay/fishing 0 0 0",
"loot.fish",
),
(
"loot replace block 1 2 3 container.5 loot minecraft:chests/x",
"loot.loot",
),
] {
assert_eq!(
run(line).unwrap_or_else(|e| panic!("{line}: {e:?}")).0,
id,
"{line}"
);
}
assert!(run("playsound minecraft:x invalid_source").is_err());
assert!(run("particle minecraft:not_a_particle").is_err());
assert!(run("damage @s -1").is_err());
assert!(run("spreadplayers 0 0 5 0 false @a").is_err());
assert!(run("worldborder warning distance -1").is_err());
}
#[test]
fn place_template_tree() {
for line in [
"place template minecraft:igloo/top",
"place template minecraft:igloo/top ~ ~ ~",
"place template minecraft:igloo/top 1 2 3 clockwise_90 left_right 0.5 12 strict",
] {
assert_eq!(
run(line).unwrap_or_else(|e| panic!("{line}: {e:?}")).0,
"place"
);
}
assert!(run("place template minecraft:x ~ ~ ~ sideways").is_err());
assert!(run("place template minecraft:x ~ ~ ~ none none 2").is_err());
}
#[test]
fn mod_commands_join_the_tree_for_every_player() {
let reg = Registries {
permission: 0,
..reg()
};
let d = vanilla::game_dispatcher().with_mod_commands(["where"]);
for line in ["where", "where north 12"] {
let parse = d.parse(line, &reg);
assert_eq!(parse.executable().unwrap().1, MOD_COMMAND, "{line}");
}
let parse = d.parse("w", &reg);
let names: Vec<String> = d
.client_suggestions(&parse, 1, &reg)
.1
.into_iter()
.map(|s| s.text)
.collect();
assert!(names.contains(&"where".to_owned()), "{names:?}");
// The game's own tree is left as it was.
assert!(vanilla::game_dispatcher().find("where").is_none());
}
#[test]
fn horizon_commands_are_off_unless_the_server_turns_them_on() {
// By default the game runs vanilla's tree: /help lists no /pregen.
assert!(vanilla::game_dispatcher().find("pregen").is_none());
for dev in [false, true] {
let vanilla_tree = vanilla::game_tree(dev, false);
assert!(vanilla_tree.find("pregen").is_none());
let d = vanilla::game_tree(dev, true);
let parse = d.parse("pregen start 100 circle", &reg());
assert_eq!(parse.executable().unwrap().1, "pregen.start");
// Vanilla's commands are the same with or without it.
assert_eq!(
d.nodes[0].children.len(),
vanilla_tree.nodes[0].children.len() + 1
);
}
}
@@ -1,181 +0,0 @@
//! The `/data` and `/tag` command trees (DataCommands, TagCommand).
use super::{
Dispatcher,
args::ArgType,
vanilla::{ENTITIES, GAMEMASTERS},
};
const ENTITY: ArgType = ArgType::Entity {
single: true,
players: false,
};
/// `ArgProvider.wrap` for each of entity, block and storage: calls `then`
/// with the node holding the provider's argument.
fn providers(
d: &mut Dispatcher,
parent: usize,
role: &str,
mut then: impl FnMut(&mut Dispatcher, usize),
) {
let e = d.literal(parent, "entity");
let a = d.argument(e, role, ENTITY);
then(d, a);
let b = d.literal(parent, "block");
let a = d.argument(b, &format!("{role}Pos"), ArgType::BlockPos);
then(d, a);
let s = d.literal(parent, "storage");
let a = d.argument(s, role, ArgType::Id("storages"));
then(d, a);
}
/// LootContextSources.addContextSources: `default`, `block <computePos>`
/// and `entity <computeTarget>`, each completed by `then`.
pub fn context_sources(
d: &mut Dispatcher,
node: usize,
then: &mut dyn FnMut(&mut Dispatcher, usize),
) {
let default = d.literal(node, "default");
then(d, default);
let block = d.literal(node, "block");
let pos = d.argument(block, "computePos", ArgType::BlockPos);
then(d, pos);
let entity = d.literal(node, "entity");
let target = d.argument(entity, "computeTarget", ENTITY);
then(d, target);
}
pub fn register(d: &mut Dispatcher, root: usize) {
// compute (default | block <pos> | entity <target>) (float <provider> [<scale>] | integer <provider>)
let compute = d.literal(root, "compute");
d.requires(compute, GAMEMASTERS);
context_sources(d, compute, &mut |d, node| {
let f = d.literal(node, "float");
let p = d.argument(
f,
"provider",
ArgType::ResourceOrId("minecraft:context_float_provider"),
);
d.executes(p, "compute");
let scale = d.argument(
p,
"scale",
ArgType::Float {
min: f32::MIN,
max: f32::MAX,
},
);
d.executes(scale, "compute");
let i = d.literal(node, "integer");
let p = d.argument(
i,
"provider",
ArgType::ResourceOrId("minecraft:context_int_provider"),
);
d.executes(p, "compute");
});
let data = d.literal(root, "data");
d.requires(data, GAMEMASTERS);
let merge = d.literal(data, "merge");
providers(d, merge, "target", |d, a| {
let nbt = d.argument(a, "nbt", ArgType::Nbt);
d.executes(nbt, "data.merge");
});
let get = d.literal(data, "get");
providers(d, get, "target", |d, a| {
d.executes(a, "data.get");
let path = d.argument(a, "path", ArgType::NbtPath);
d.executes(path, "data.get");
let scale = d.argument(
path,
"scale",
ArgType::Double {
min: f64::MIN,
max: f64::MAX,
},
);
d.executes(scale, "data.get");
});
let remove = d.literal(data, "remove");
providers(d, remove, "target", |d, a| {
let path = d.argument(a, "path", ArgType::NbtPath);
d.executes(path, "data.remove");
});
let modify = d.literal(data, "modify");
providers(d, modify, "target", |d, a| {
let target_path = d.argument(a, "targetPath", ArgType::NbtPath);
// insert <index> | prepend | append | set | merge, then the source.
let mut ops = Vec::new();
let insert = d.literal(target_path, "insert");
let index = d.argument(
insert,
"index",
ArgType::Integer {
min: i32::MIN,
max: i32::MAX,
},
);
ops.push(index);
for op in ["prepend", "append", "set", "merge"] {
ops.push(d.literal(target_path, op));
}
for op in ops {
let from = d.literal(op, "from");
providers(d, from, "source", |d, s| {
d.executes(s, "data.modify");
let sp = d.argument(s, "sourcePath", ArgType::NbtPath);
d.executes(sp, "data.modify");
});
let string = d.literal(op, "string");
providers(d, string, "source", |d, s| {
d.executes(s, "data.modify");
let sp = d.argument(s, "sourcePath", ArgType::NbtPath);
d.executes(sp, "data.modify");
let int = || ArgType::Integer {
min: i32::MIN,
max: i32::MAX,
};
let start = d.argument(sp, "start", int());
d.executes(start, "data.modify");
let end = d.argument(start, "end", int());
d.executes(end, "data.modify");
});
let compute = d.literal(op, "compute");
context_sources(d, compute, &mut |d, node| {
for (kind, registry) in [
("float", "minecraft:context_float_provider"),
("integer", "minecraft:context_int_provider"),
] {
let k = d.literal(node, kind);
let p = d.argument(k, "provider", ArgType::ResourceOrId(registry));
d.executes(p, "data.modify");
}
});
let value = d.literal(op, "value");
let v = d.argument(value, "value", ArgType::NbtTag);
d.executes(v, "data.modify");
}
});
// tag <targets> add|remove <name> | list
let tag = d.literal(root, "tag");
d.requires(tag, GAMEMASTERS);
let targets = d.argument(tag, "targets", ENTITIES);
for word in ["add", "remove"] {
let w = d.literal(targets, word);
let name = d.argument(w, "name", ArgType::Word);
d.executes(
name,
if word == "add" {
"tag.add"
} else {
"tag.remove"
},
);
}
let list = d.literal(targets, "list");
d.executes(list, "tag.list");
}
@@ -1,249 +0,0 @@
//! The `/execute` tree (ExecuteCommand): modifiers redirect back to
//! `execute`, `run` to the root; conditions both execute (as a test) and
//! continue the chain; `store` redirects with a result callback.
use super::{
Dispatcher,
args::{ArgType, Resource},
vanilla::{ENTITIES, GAMEMASTERS},
};
/// HeightmapTypeArgument: the types kept after world generation.
pub const HEIGHTMAPS: &[&str] = &[
"world_surface",
"ocean_floor",
"motion_blocking",
"motion_blocking_no_leaves",
];
pub const RELATIONS: [&str; 8] = [
"owner",
"leasher",
"target",
"attacker",
"vehicle",
"controller",
"origin",
"passengers",
];
/// A conditional's end: it runs as a test and continues the chain.
fn conditional(d: &mut Dispatcher, node: usize, ex: usize) {
d.executes(node, "execute");
d.redirect(node, ex);
}
pub fn register(d: &mut Dispatcher, root: usize) {
let ex = d.literal(root, "execute");
d.requires(ex, GAMEMASTERS);
let run = d.literal(ex, "run");
d.redirect(run, root);
for name in ["as", "at"] {
let l = d.literal(ex, name);
let t = d.argument(l, "targets", ENTITIES);
d.redirect(t, ex);
}
let positioned = d.literal(ex, "positioned");
let pos = d.argument(positioned, "pos", ArgType::Vec3 { center: true });
d.redirect(pos, ex);
let as_ = d.literal(positioned, "as");
let t = d.argument(as_, "targets", ENTITIES);
d.redirect(t, ex);
let over = d.literal(positioned, "over");
let hm = d.argument(
over,
"heightmap",
ArgType::StrEnum(HEIGHTMAPS, "argument.enum.invalid"),
);
d.redirect(hm, ex);
let rotated = d.literal(ex, "rotated");
let rot = d.argument(rotated, "rot", ArgType::Rotation);
d.redirect(rot, ex);
let as_ = d.literal(rotated, "as");
let t = d.argument(as_, "targets", ENTITIES);
d.redirect(t, ex);
let facing = d.literal(ex, "facing");
let pos = d.argument(facing, "pos", ArgType::Vec3 { center: true });
d.redirect(pos, ex);
let entity = d.literal(facing, "entity");
let t = d.argument(entity, "targets", ENTITIES);
let anchor = d.argument(t, "anchor", ArgType::Anchor);
d.redirect(anchor, ex);
let align = d.literal(ex, "align");
let axes = d.argument(align, "axes", ArgType::Swizzle);
d.redirect(axes, ex);
let anchored = d.literal(ex, "anchored");
let anchor = d.argument(anchored, "anchor", ArgType::Anchor);
d.redirect(anchor, ex);
let in_ = d.literal(ex, "in");
let dim = d.argument(in_, "dimension", ArgType::Dimension);
d.redirect(dim, ex);
let summon = d.literal(ex, "summon");
let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType));
d.suggests(e, super::Suggests::SummonableEntities);
d.redirect(e, ex);
let on = d.literal(ex, "on");
for r in RELATIONS {
let l = d.literal(on, r);
d.redirect(l, ex);
}
store(d, ex);
for mode in ["if", "unless"] {
let m = d.literal(ex, mode);
conditionals(d, m, ex);
}
}
fn store(d: &mut Dispatcher, ex: usize) {
let store = d.literal(ex, "store");
for kind in ["result", "success"] {
let k = d.literal(store, kind);
let score = d.literal(k, "score");
let targets = d.argument(score, "targets", ArgType::ScoreHolder { multiple: true });
let objective = d.argument(targets, "objective", ArgType::Objective);
d.redirect(objective, ex);
let bossbar = d.literal(k, "bossbar");
let id = d.argument(bossbar, "id", ArgType::Id("bossbars"));
for what in ["value", "max"] {
let w = d.literal(id, what);
d.redirect(w, ex);
}
for provider in ["entity", "block", "storage"] {
let p = d.literal(k, provider);
let a = match provider {
"entity" => d.argument(
p,
"target",
ArgType::Entity {
single: true,
players: false,
},
),
"block" => d.argument(p, "targetPos", ArgType::BlockPos),
_ => d.argument(p, "target", ArgType::Id("storages")),
};
let path = d.argument(a, "path", ArgType::NbtPath);
for ty in ["int", "float", "short", "long", "double", "byte"] {
let t = d.literal(path, ty);
let scale = d.argument(
t,
"scale",
ArgType::Double {
min: f64::MIN,
max: f64::MAX,
},
);
d.redirect(scale, ex);
}
}
}
}
fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) {
let block = d.literal(m, "block");
let pos = d.argument(block, "pos", ArgType::BlockPos);
let predicate = d.argument(pos, "block", ArgType::BlockPredicate);
conditional(d, predicate, ex);
let biome = d.literal(m, "biome");
let pos = d.argument(biome, "pos", ArgType::BlockPos);
let b = d.argument(pos, "biome", ArgType::ResOrTag("minecraft:worldgen/biome"));
conditional(d, b, ex);
let loaded = d.literal(m, "loaded");
let pos = d.argument(loaded, "pos", ArgType::BlockPos);
conditional(d, pos, ex);
let dimension = d.literal(m, "dimension");
let dim = d.argument(dimension, "dimension", ArgType::Dimension);
conditional(d, dim, ex);
let score = d.literal(m, "score");
let target = d.argument(score, "target", ArgType::ScoreHolder { multiple: false });
let objective = d.argument(target, "targetObjective", ArgType::Objective);
for op in ["=", "<", "<=", ">", ">="] {
let o = d.literal(objective, op);
let source = d.argument(o, "source", ArgType::ScoreHolder { multiple: false });
let so = d.argument(source, "sourceObjective", ArgType::Objective);
conditional(d, so, ex);
}
let matches = d.literal(objective, "matches");
let range = d.argument(matches, "range", ArgType::IntRange);
conditional(d, range, ex);
let blocks = d.literal(m, "blocks");
let start = d.argument(blocks, "start", ArgType::BlockPos);
let end = d.argument(start, "end", ArgType::BlockPos);
let dest = d.argument(end, "destination", ArgType::BlockPos);
for mode in ["all", "masked"] {
let l = d.literal(dest, mode);
conditional(d, l, ex);
}
let entity = d.literal(m, "entity");
let targets = d.argument(entity, "entities", ENTITIES);
conditional(d, targets, ex);
let predicate = d.literal(m, "predicate");
let p = d.argument(
predicate,
"predicate",
ArgType::ResourceOrId("minecraft:predicate"),
);
conditional(d, p, ex);
let stopwatch = d.literal(m, "stopwatch");
let id = d.argument(stopwatch, "id", ArgType::Id("stopwatches"));
let range = d.argument(id, "range", ArgType::FloatRange);
conditional(d, range, ex);
let function = d.literal(m, "function");
let name = d.argument(function, "name", ArgType::Function);
d.suggests(name, super::Suggests::Functions);
// ExecuteIfFunctionCustomModifier: a fork only (not a test command).
d.redirect(name, ex);
let data = d.literal(m, "data");
for provider in ["entity", "block", "storage"] {
let p = d.literal(data, provider);
let a = match provider {
"entity" => d.argument(
p,
"source",
ArgType::Entity {
single: true,
players: false,
},
),
"block" => d.argument(p, "sourcePos", ArgType::BlockPos),
_ => d.argument(p, "source", ArgType::Id("storages")),
};
let path = d.argument(a, "path", ArgType::NbtPath);
conditional(d, path, ex);
}
// items / slots (entity|block) <slots> [<predicate>]
for kind in ["items", "slots"] {
let k = d.literal(m, kind);
for provider in ["entity", "block"] {
let p = d.literal(k, provider);
let a = if provider == "entity" {
d.argument(
p,
"source",
ArgType::Entity {
single: false,
players: false,
},
)
} else {
d.argument(p, "sourcePos", ArgType::BlockPos)
};
let slots = d.argument(a, "slots", ArgType::SlotSource);
if kind == "items" {
let item = d.argument(slots, "item_predicate", ArgType::ItemPredicate);
conditional(d, item, ex);
} else {
conditional(d, slots, ex);
}
}
}
}
@@ -1,208 +0,0 @@
//! Commands of the hosted game rather than the world: `/dialog`, `/kick`,
//! `/posteffect`, `/fetchprofile`, `/spectate`, `/publish`, `/unpublish`,
//! `/waypoint`, `/debug`, `/jfr` and `/test`.
use super::{
Dispatcher,
args::ArgType,
vanilla::{ENTITY, GAMEMASTERS, PLAYER, PLAYERS},
};
const ADMINS: u8 = 3;
const OWNERS: u8 = 4;
pub fn register(d: &mut Dispatcher, root: usize) {
// DialogCommand
let dialog = d.literal(root, "dialog");
d.requires(dialog, GAMEMASTERS);
let show = d.literal(dialog, "show");
let t = d.argument(show, "targets", PLAYERS);
let dl = d.argument(t, "dialog", ArgType::ResourceOrId("minecraft:dialog"));
d.executes(dl, "dialog.show");
let clear = d.literal(dialog, "clear");
let t = d.argument(clear, "targets", PLAYERS);
d.executes(t, "dialog.clear");
// KickCommand
let kick = d.literal(root, "kick");
d.requires(kick, ADMINS);
let t = d.argument(kick, "targets", PLAYERS);
d.executes(t, "kick");
let reason = d.argument(t, "reason", ArgType::Message);
d.executes(reason, "kick");
// PostEffectCommand
let pe = d.literal(root, "posteffect");
d.requires(pe, GAMEMASTERS);
let add = d.literal(pe, "add");
let t = d.argument(add, "targets", PLAYERS);
let id = d.argument(t, "posteffect", ArgType::Id("post_effects"));
d.executes(id, "posteffect.add");
let clear = d.literal(pe, "clear");
let t = d.argument(clear, "targets", PLAYERS);
d.executes(t, "posteffect.clear");
let list = d.literal(pe, "list");
let t = d.argument(list, "target", PLAYER);
d.executes(t, "posteffect.list");
let remove = d.literal(pe, "remove");
let t = d.argument(remove, "targets", PLAYERS);
let id = d.argument(t, "posteffect", ArgType::Id("post_effects"));
d.executes(id, "posteffect.remove");
// FetchProfileCommand
let fp = d.literal(root, "fetchprofile");
d.requires(fp, GAMEMASTERS);
let name = d.literal(fp, "name");
let n = d.argument(name, "name", ArgType::Greedy);
d.executes(n, "fetchprofile");
let id = d.literal(fp, "id");
let u = d.argument(id, "id", ArgType::Uuid);
d.executes(u, "fetchprofile");
let entity = d.literal(fp, "entity");
let e = d.argument(entity, "entity", ENTITY);
d.executes(e, "fetchprofile");
// SpectateCommand
let spectate = d.literal(root, "spectate");
d.requires(spectate, GAMEMASTERS);
d.executes(spectate, "spectate");
let target = d.argument(spectate, "target", ENTITY);
d.executes(target, "spectate");
let player = d.argument(target, "player", PLAYER);
d.executes(player, "spectate");
// PublishCommand / UnpublishCommand
let publish = d.literal(root, "publish");
d.requires(publish, OWNERS);
d.executes(publish, "publish");
let allow = d.argument(publish, "allowCommands", ArgType::Bool);
d.executes(allow, "publish");
let port = d.argument(allow, "port", ArgType::Integer { min: 0, max: 65535 });
d.executes(port, "publish");
let unpublish = d.literal(root, "unpublish");
d.requires(unpublish, OWNERS);
d.executes(unpublish, "unpublish");
// WaypointCommand
let wp = d.literal(root, "waypoint");
d.requires(wp, GAMEMASTERS);
let list = d.literal(wp, "list");
d.executes(list, "waypoint.list");
let modify = d.literal(wp, "modify");
let w = d.argument(modify, "waypoint", ENTITY);
let color = d.literal(w, "color");
let c = d.argument(color, "color", ArgType::TeamColor);
d.executes(c, "waypoint.modify");
let hex = d.literal(color, "hex");
let h = d.argument(hex, "color", ArgType::HexColor);
d.executes(h, "waypoint.modify");
let reset = d.literal(color, "reset");
d.executes(reset, "waypoint.modify");
let style = d.literal(w, "style");
let reset = d.literal(style, "reset");
d.executes(reset, "waypoint.modify");
let set = d.literal(style, "set");
let st = d.argument(set, "style", ArgType::Id("none"));
d.executes(st, "waypoint.modify");
// DebugCommand
let debug = d.literal(root, "debug");
d.requires(debug, ADMINS);
for name in ["start", "stop"] {
let l = d.literal(debug, name);
d.executes(l, "debug");
}
let function = d.literal(debug, "function");
d.requires(function, ADMINS);
let n = d.argument(function, "name", ArgType::Function);
d.suggests(n, super::Suggests::Functions);
d.executes(n, "debug");
// JfrCommand (registered when the JVM profiler is available)
let jfr = d.literal(root, "jfr");
d.requires(jfr, OWNERS);
for name in ["start", "stop"] {
let l = d.literal(jfr, name);
d.executes(l, "jfr");
}
// TestCommand (release build: no export subcommands)
let test = d.literal(root, "test");
d.requires(test, GAMEMASTERS);
let tests = ArgType::ResourceSelector("minecraft:test_instance");
let int0 = ArgType::Integer {
min: 0,
max: i32::MAX,
};
let int = ArgType::Integer {
min: i32::MIN,
max: i32::MAX,
};
// numberOfTimes [untilFailed [rotationSteps [testsPerRow]]], or only
// the first two.
let retry = |d: &mut Dispatcher, node: usize, id: &'static str, build_info: bool| {
let n = d.argument(node, "numberOfTimes", int0.clone());
d.executes(n, id);
let u = d.argument(n, "untilFailed", ArgType::Bool);
d.executes(u, id);
if build_info {
let r = d.argument(u, "rotationSteps", int.clone());
d.executes(r, id);
let t = d.argument(r, "testsPerRow", int.clone());
d.executes(t, id);
}
};
let run = d.literal(test, "run");
let t = d.argument(run, "tests", tests.clone());
d.executes(t, "test.run");
retry(d, t, "test.run", true);
let multiple = d.literal(test, "runmultiple");
let t = d.argument(multiple, "tests", tests.clone());
d.executes(t, "test.run");
let a = d.argument(t, "amount", int.clone());
d.executes(a, "test.run");
for name in ["runthese", "runclosest", "runthat"] {
let l = d.literal(test, name);
d.executes(l, "test.run.found");
retry(d, l, "test.run.found", false);
}
let failed = d.literal(test, "runfailed");
d.executes(failed, "test.run.found");
let only = d.argument(failed, "onlyRequiredTests", ArgType::Bool);
d.executes(only, "test.run.found");
retry(d, only, "test.run.found", true);
retry(d, failed, "test.run.found", true);
let verify = d.literal(test, "verify");
let t = d.argument(verify, "tests", tests.clone());
d.executes(t, "test.verify");
let locate = d.literal(test, "locate");
let t = d.argument(locate, "tests", tests);
d.executes(t, "test.locate");
for name in [
"resetclosest",
"resetthese",
"resetthat",
"clearthat",
"clearthese",
] {
let l = d.literal(test, name);
d.executes(l, "test.clear");
}
let all = d.literal(test, "clearall");
d.executes(all, "test.clear");
let r = d.argument(all, "radius", int.clone());
d.executes(r, "test.clear");
let stop = d.literal(test, "stop");
d.executes(stop, "test.stop");
let pos = d.literal(test, "pos");
d.executes(pos, "test.pos");
let var = d.argument(pos, "var", ArgType::Word);
d.executes(var, "test.pos");
let create = d.literal(test, "create");
let id = d.argument(create, "id", ArgType::Id("none"));
d.executes(id, "test.create");
let w = d.argument(id, "width", int.clone());
d.executes(w, "test.create");
let h = d.argument(w, "height", int.clone());
let depth = d.argument(h, "depth", int);
d.executes(depth, "test.create");
}
@@ -1,319 +0,0 @@
//! Smaller command trees: `/bossbar`, `/function`, `/return`, `/schedule`,
//! `/random`, `/tick`, `/teammsg`, `/reload` and `/datapack`.
use super::{
Dispatcher,
args::ArgType,
vanilla::{ENTITIES, GAMEMASTERS, PLAYERS},
};
fn int() -> ArgType {
ArgType::Integer {
min: i32::MIN,
max: i32::MAX,
}
}
fn int_min(min: i32) -> ArgType {
ArgType::Integer { min, max: i32::MAX }
}
pub const ADMINS: u8 = 3;
pub fn register(d: &mut Dispatcher, root: usize) {
item(d, root);
bossbar(d, root);
function(d, root);
stopwatch(d, root);
// return <value> | fail | run <command>
let ret = d.literal(root, "return");
d.requires(ret, GAMEMASTERS);
let v = d.argument(ret, "value", int());
d.executes(v, "return.value");
let fail = d.literal(ret, "fail");
d.executes(fail, "return.fail");
let run = d.literal(ret, "run");
d.redirect(run, root);
// schedule function <function> <time> [append|replace] | clear <function>
let schedule = d.literal(root, "schedule");
d.requires(schedule, GAMEMASTERS);
let f = d.literal(schedule, "function");
let name = d.argument(f, "function", ArgType::Function);
d.suggests(name, super::Suggests::Functions);
let time = d.argument(name, "time", ArgType::Time { min: 0 });
d.executes(time, "schedule.function");
for mode in ["append", "replace"] {
let m = d.literal(time, mode);
d.executes(m, "schedule.function");
}
let clear = d.literal(schedule, "clear");
let id = d.argument(clear, "function", ArgType::Id("schedules"));
d.executes(id, "schedule.clear");
// random (value|roll) <range> [<sequence>] | reset (*|<sequence>) ...
let random = d.literal(root, "random");
for kind in ["value", "roll"] {
let k = d.literal(random, kind);
let range = d.argument(k, "range", ArgType::IntRange);
let id = if kind == "value" {
"random.value"
} else {
"random.roll"
};
d.executes(range, id);
let seq = d.argument(range, "sequence", ArgType::Id("random_sequences"));
d.requires(seq, GAMEMASTERS);
d.executes(seq, id);
}
let reset = d.literal(random, "reset");
d.requires(reset, GAMEMASTERS);
let all = d.literal(reset, "*");
d.executes(all, "random.reset");
let seq = d.argument(reset, "sequence", ArgType::Id("random_sequences"));
d.executes(seq, "random.reset");
for parent in [all, seq] {
let seed = d.argument(parent, "seed", int());
d.executes(seed, "random.reset");
let world = d.argument(seed, "includeWorldSeed", ArgType::Bool);
d.executes(world, "random.reset");
let seq_id = d.argument(world, "includeSequenceId", ArgType::Bool);
d.executes(seq_id, "random.reset");
}
// tick query | rate <rate> | step [stop|<time>] | sprint (stop|<time>) | freeze | unfreeze
let tick = d.literal(root, "tick");
d.requires(tick, ADMINS);
let q = d.literal(tick, "query");
d.executes(q, "tick.query");
let rate = d.literal(tick, "rate");
let r = d.argument(
rate,
"rate",
ArgType::Float {
min: 1.0,
max: 10000.0,
},
);
d.suggests(r, super::Suggests::Fixed(&["20"]));
d.executes(r, "tick.rate");
let step = d.literal(tick, "step");
d.executes(step, "tick.step");
let stop = d.literal(step, "stop");
d.executes(stop, "tick.step.stop");
let t = d.argument(step, "time", ArgType::Time { min: 1 });
d.suggests(t, super::Suggests::Fixed(&["1t", "1s"]));
d.executes(t, "tick.step");
let sprint = d.literal(tick, "sprint");
let stop = d.literal(sprint, "stop");
d.executes(stop, "tick.sprint.stop");
let t = d.argument(sprint, "time", ArgType::Time { min: 1 });
d.suggests(t, super::Suggests::Fixed(&["60s", "1d", "3d"]));
d.executes(t, "tick.sprint");
let unfreeze = d.literal(tick, "unfreeze");
d.executes(unfreeze, "tick.unfreeze");
let freeze = d.literal(tick, "freeze");
d.executes(freeze, "tick.freeze");
// teammsg / tm <message>
let teammsg = d.literal(root, "teammsg");
let m = d.argument(teammsg, "message", ArgType::Message);
d.executes(m, "teammsg");
let tm = d.literal(root, "tm");
d.redirect(tm, teammsg);
// reload
let reload = d.literal(root, "reload");
d.requires(reload, GAMEMASTERS);
d.executes(reload, "reload");
// datapack list [available|enabled] | enable|disable <name> ...
let datapack = d.literal(root, "datapack");
d.requires(datapack, GAMEMASTERS);
let list = d.literal(datapack, "list");
d.executes(list, "datapack.list");
for w in ["available", "enabled"] {
let l = d.literal(list, w);
d.executes(l, "datapack.list");
}
let enable = d.literal(datapack, "enable");
let name = d.argument(enable, "name", ArgType::Name("datapacks_disabled"));
d.executes(name, "datapack.enable");
for w in ["first", "last"] {
let l = d.literal(name, w);
d.executes(l, "datapack.enable");
}
for w in ["before", "after"] {
let l = d.literal(name, w);
let other = d.argument(l, "existing", ArgType::Name("datapacks_enabled"));
d.executes(other, "datapack.enable");
}
let create = d.literal(datapack, "create");
d.requires(create, 4);
let id = d.argument(create, "id", ArgType::Str);
let description = d.argument(id, "description", ArgType::Component);
d.executes(description, "datapack.create");
let disable = d.literal(datapack, "disable");
let name = d.argument(disable, "name", ArgType::Name("datapacks_enabled"));
d.executes(name, "datapack.disable");
}
/// `item (replace|fill|override) (entity|block) <target> <slots> (with <item> [<count>] | from ...)`.
fn item(d: &mut Dispatcher, root: usize) {
let item = d.literal(root, "item");
d.requires(item, GAMEMASTERS);
let modify = d.literal(item, "modify");
for provider in ["entity", "block"] {
let p = d.literal(modify, provider);
let target = if provider == "entity" {
d.argument(p, "target", ENTITIES)
} else {
d.argument(p, "targetPos", ArgType::BlockPos)
};
let slot = d.argument(target, "slot", ArgType::SlotSource);
let modifier = d.argument(
slot,
"modifier",
ArgType::ResourceOrId("minecraft:item_modifier"),
);
d.executes(modifier, "item.modify");
}
for mode in ["replace", "fill", "override"] {
let m = d.literal(item, mode);
for provider in ["entity", "block"] {
let p = d.literal(m, provider);
let target = if provider == "entity" {
d.argument(p, "target", ENTITIES)
} else {
d.argument(p, "targetPos", ArgType::BlockPos)
};
let slots = d.argument(target, "slots", ArgType::SlotSource);
let with = d.literal(slots, "with");
let it = d.argument(with, "item", ArgType::Item);
d.executes(it, "item");
let count = d.argument(it, "count", ArgType::Integer { min: 1, max: 99 });
d.executes(count, "item");
let from = d.literal(slots, "from");
for src in ["entity", "block"] {
let s = d.literal(from, src);
let source = if src == "entity" {
d.argument(s, "source", ENTITIES)
} else {
d.argument(s, "sourcePos", ArgType::BlockPos)
};
let source_slots = d.argument(source, "sourceSlots", ArgType::SlotSource);
d.executes(source_slots, "item");
let modifier = d.argument(
source_slots,
"modifier",
ArgType::ResourceOrId("minecraft:item_modifier"),
);
d.executes(modifier, "item");
}
}
}
}
fn bossbar(d: &mut Dispatcher, root: usize) {
let b = d.literal(root, "bossbar");
d.requires(b, GAMEMASTERS);
let add = d.literal(b, "add");
let id = d.argument(add, "id", ArgType::Id("bossbars_new"));
let name = d.argument(id, "name", ArgType::Component);
d.executes(name, "bossbar.add");
let remove = d.literal(b, "remove");
let id = d.argument(remove, "id", ArgType::Id("bossbars"));
d.executes(id, "bossbar.remove");
let list = d.literal(b, "list");
d.executes(list, "bossbar.list");
let set = d.literal(b, "set");
let id = d.argument(set, "id", ArgType::Id("bossbars"));
let name_l = d.literal(id, "name");
let name = d.argument(name_l, "name", ArgType::Component);
d.executes(name, "bossbar.set.name");
let color = d.literal(id, "color");
for c in crate::bossbar::COLORS {
let l = d.literal(color, c);
d.executes(l, "bossbar.set.color");
}
let style = d.literal(id, "style");
for s in crate::bossbar::STYLES {
let l = d.literal(style, s);
d.executes(l, "bossbar.set.style");
}
let value = d.literal(id, "value");
let v = d.argument(value, "value", int_min(0));
d.executes(v, "bossbar.set.value");
let max = d.literal(id, "max");
let v = d.argument(max, "max", int_min(1));
d.executes(v, "bossbar.set.max");
let visible = d.literal(id, "visible");
let v = d.argument(visible, "visible", ArgType::Bool);
d.executes(v, "bossbar.set.visible");
let players = d.literal(id, "players");
d.executes(players, "bossbar.set.players");
let t = d.argument(players, "targets", PLAYERS);
d.executes(t, "bossbar.set.players");
let get = d.literal(b, "get");
let id = d.argument(get, "id", ArgType::Id("bossbars"));
for w in ["value", "max", "visible", "players"] {
let l = d.literal(id, w);
d.executes(l, "bossbar.get");
}
}
fn function(d: &mut Dispatcher, root: usize) {
let f = d.literal(root, "function");
d.requires(f, GAMEMASTERS);
let name = d.argument(f, "name", ArgType::Function);
d.suggests(name, super::Suggests::Functions);
d.executes(name, "function");
let args = d.argument(name, "arguments", ArgType::Nbt);
d.executes(args, "function");
let with = d.literal(name, "with");
for provider in ["entity", "block", "storage"] {
let p = d.literal(with, provider);
let a = match provider {
"entity" => d.argument(
p,
"source",
ArgType::Entity {
single: true,
players: false,
},
),
"block" => d.argument(p, "sourcePos", ArgType::BlockPos),
_ => d.argument(p, "source", ArgType::Id("storages")),
};
d.executes(a, "function");
let path = d.argument(a, "path", ArgType::NbtPath);
d.executes(path, "function");
}
}
/// stopwatch create <id> | query <id> [<scale>] | restart <id> | remove <id>
fn stopwatch(d: &mut Dispatcher, root: usize) {
let sw = d.literal(root, "stopwatch");
d.requires(sw, GAMEMASTERS);
let create = d.literal(sw, "create");
let id = d.argument(create, "id", ArgType::Id("none"));
d.executes(id, "stopwatch.create");
let query = d.literal(sw, "query");
let id = d.argument(query, "id", ArgType::Id("stopwatches"));
d.executes(id, "stopwatch.query");
let scale = d.argument(
id,
"scale",
ArgType::Double {
min: f64::MIN,
max: f64::MAX,
},
);
d.executes(scale, "stopwatch.query");
for (name, command) in [
("restart", "stopwatch.restart"),
("remove", "stopwatch.remove"),
] {
let l = d.literal(sw, name);
let id = d.argument(l, "id", ArgType::Id("stopwatches"));
d.executes(id, command);
}
}
@@ -1,216 +0,0 @@
//! The `/scoreboard`, `/team` and `/trigger` command trees
//! (ScoreboardCommand, TeamCommand, TriggerCommand).
use super::{Dispatcher, args::ArgType, vanilla::GAMEMASTERS};
const HOLDERS: ArgType = ArgType::ScoreHolder { multiple: true };
const HOLDER: ArgType = ArgType::ScoreHolder { multiple: false };
/// `addNumberFormats`: blank | fixed <contents> | styled <style>, and the
/// node itself clears the format.
fn number_formats(d: &mut Dispatcher, top: usize, id: &'static str) {
d.executes(top, id);
let blank = d.literal(top, "blank");
d.executes(blank, id);
let fixed = d.literal(top, "fixed");
let contents = d.argument(fixed, "contents", ArgType::Component);
d.executes(contents, id);
let styled = d.literal(top, "styled");
let style = d.argument(styled, "style", ArgType::Style);
d.executes(style, id);
}
pub fn register(d: &mut Dispatcher, root: usize) {
scoreboard(d, root);
team(d, root);
// trigger <objective> [add|set <value>]
let trigger = d.literal(root, "trigger");
let objective = d.argument(trigger, "objective", ArgType::Objective);
d.suggests(objective, super::Suggests::Triggers);
d.executes(objective, "trigger");
for mode in ["add", "set"] {
let m = d.literal(objective, mode);
let v = d.argument(
m,
"value",
ArgType::Integer {
min: i32::MIN,
max: i32::MAX,
},
);
d.executes(
v,
if mode == "add" {
"trigger.add"
} else {
"trigger.set"
},
);
}
}
fn scoreboard(d: &mut Dispatcher, root: usize) {
let sb = d.literal(root, "scoreboard");
d.requires(sb, GAMEMASTERS);
let objectives = d.literal(sb, "objectives");
let list = d.literal(objectives, "list");
d.executes(list, "scoreboard.objectives.list");
let add = d.literal(objectives, "add");
let name = d.argument(add, "objective", ArgType::Word);
let criteria = d.argument(name, "criteria", ArgType::Criteria);
d.executes(criteria, "scoreboard.objectives.add");
let display = d.argument(criteria, "displayName", ArgType::Component);
d.executes(display, "scoreboard.objectives.add");
let modify = d.literal(objectives, "modify");
let objective = d.argument(modify, "objective", ArgType::Objective);
let dn = d.literal(objective, "displayname");
let display = d.argument(dn, "displayName", ArgType::Component);
d.executes(display, "scoreboard.objectives.modify.displayname");
let rt = d.literal(objective, "rendertype");
for kind in ["integer", "hearts"] {
let k = d.literal(rt, kind);
d.executes(k, "scoreboard.objectives.modify.rendertype");
}
let au = d.literal(objective, "displayautoupdate");
let v = d.argument(au, "value", ArgType::Bool);
d.executes(v, "scoreboard.objectives.modify.displayautoupdate");
let nf = d.literal(objective, "numberformat");
number_formats(d, nf, "scoreboard.objectives.modify.numberformat");
let remove = d.literal(objectives, "remove");
let objective = d.argument(remove, "objective", ArgType::Objective);
d.executes(objective, "scoreboard.objectives.remove");
let setdisplay = d.literal(objectives, "setdisplay");
let slot = d.argument(setdisplay, "slot", ArgType::ScoreboardSlot);
d.executes(slot, "scoreboard.objectives.setdisplay");
let objective = d.argument(slot, "objective", ArgType::Objective);
d.executes(objective, "scoreboard.objectives.setdisplay");
let players = d.literal(sb, "players");
let list = d.literal(players, "list");
d.executes(list, "scoreboard.players.list");
let target = d.argument(list, "target", HOLDER);
d.executes(target, "scoreboard.players.list");
// set / add / remove <targets> <objective> <score>
for (word, min, id) in [
("set", i32::MIN, "scoreboard.players.set"),
("add", 0, "scoreboard.players.add"),
("remove", 0, "scoreboard.players.remove"),
] {
let w = d.literal(players, word);
let t = d.argument(w, "targets", HOLDERS);
let o = d.argument(t, "objective", ArgType::Objective);
let s = d.argument(o, "score", ArgType::Integer { min, max: i32::MAX });
d.executes(s, id);
}
let get = d.literal(players, "get");
let t = d.argument(get, "target", HOLDER);
let o = d.argument(t, "objective", ArgType::Objective);
d.executes(o, "scoreboard.players.get");
let reset = d.literal(players, "reset");
let t = d.argument(reset, "targets", HOLDERS);
d.executes(t, "scoreboard.players.reset");
let o = d.argument(t, "objective", ArgType::Objective);
d.executes(o, "scoreboard.players.reset");
let enable = d.literal(players, "enable");
let t = d.argument(enable, "targets", HOLDERS);
let o = d.argument(t, "objective", ArgType::Objective);
d.suggests(o, super::Suggests::EnableTriggers);
d.executes(o, "scoreboard.players.enable");
let display = d.literal(players, "display");
let name = d.literal(display, "name");
let t = d.argument(name, "targets", HOLDERS);
let o = d.argument(t, "objective", ArgType::Objective);
d.executes(o, "scoreboard.players.display.name");
let n = d.argument(o, "name", ArgType::Component);
d.executes(n, "scoreboard.players.display.name");
let nf = d.literal(display, "numberformat");
let t = d.argument(nf, "targets", HOLDERS);
let o = d.argument(t, "objective", ArgType::Objective);
number_formats(d, o, "scoreboard.players.display.numberformat");
let operation = d.literal(players, "operation");
let t = d.argument(operation, "targets", HOLDERS);
let to = d.argument(t, "targetObjective", ArgType::Objective);
let op = d.argument(to, "operation", ArgType::Operation);
let source = d.argument(op, "source", HOLDERS);
let so = d.argument(source, "sourceObjective", ArgType::Objective);
d.executes(so, "scoreboard.players.operation");
}
fn team(d: &mut Dispatcher, root: usize) {
let team = d.literal(root, "team");
d.requires(team, GAMEMASTERS);
let list = d.literal(team, "list");
d.executes(list, "team.list");
let t = d.argument(list, "team", ArgType::Team);
d.executes(t, "team.list");
let add = d.literal(team, "add");
let t = d.argument(add, "team", ArgType::Word);
d.executes(t, "team.add");
let dn = d.argument(t, "displayName", ArgType::Component);
d.executes(dn, "team.add");
let remove = d.literal(team, "remove");
let t = d.argument(remove, "team", ArgType::Team);
d.executes(t, "team.remove");
let empty = d.literal(team, "empty");
let t = d.argument(empty, "team", ArgType::Team);
d.executes(t, "team.empty");
let join = d.literal(team, "join");
let t = d.argument(join, "team", ArgType::Team);
d.executes(t, "team.join");
let m = d.argument(t, "members", HOLDERS);
d.executes(m, "team.join");
let leave = d.literal(team, "leave");
let m = d.argument(leave, "members", HOLDERS);
d.executes(m, "team.leave");
let modify = d.literal(team, "modify");
let t = d.argument(modify, "team", ArgType::Team);
let dn = d.literal(t, "displayName");
let v = d.argument(dn, "displayName", ArgType::Component);
d.executes(v, "team.modify.displayname");
let color = d.literal(t, "color");
let reset = d.literal(color, "reset");
d.executes(reset, "team.modify.color.reset");
let v = d.argument(color, "value", ArgType::TeamColor);
d.executes(v, "team.modify.color");
for (word, id) in [
("friendlyFire", "team.modify.friendlyfire"),
("seeFriendlyInvisibles", "team.modify.seefriendlyinvisibles"),
] {
let w = d.literal(t, word);
let v = d.argument(w, "allowed", ArgType::Bool);
d.executes(v, id);
}
for (word, id, values) in [
(
"nametagVisibility",
"team.modify.nametagvisibility",
["never", "hideForOtherTeams", "hideForOwnTeam", "always"],
),
(
"deathMessageVisibility",
"team.modify.deathmessagevisibility",
["never", "hideForOtherTeams", "hideForOwnTeam", "always"],
),
(
"collisionRule",
"team.modify.collisionrule",
["never", "pushOwnTeam", "pushOtherTeams", "always"],
),
] {
let w = d.literal(t, word);
for value in values {
let v = d.literal(w, value);
d.executes(v, id);
}
}
for (word, id) in [
("prefix", "team.modify.prefix"),
("suffix", "team.modify.suffix"),
] {
let w = d.literal(t, word);
let v = d.argument(w, word, ArgType::Component);
d.executes(v, id);
}
}
@@ -1,419 +0,0 @@
//! Command trees that act on entities and the world: `/recipe`, `/damage`,
//! `/rotate`, `/swing`, `/playsound`, `/stopsound`, `/particle`,
//! `/attribute`, `/ride`, `/spreadplayers`, `/loot`, `/forceload`,
//! `/fillbiome`, `/worldborder`.
use super::{
Dispatcher,
args::{ArgType, integer},
vanilla::{ENTITIES, ENTITY, GAMEMASTERS, PLAYERS},
};
use crate::settings::SOUND_SOURCES;
fn float(min: f32) -> ArgType {
ArgType::Float { min, max: f32::MAX }
}
fn double() -> ArgType {
ArgType::Double {
min: f64::MIN,
max: f64::MAX,
}
}
pub fn register(d: &mut Dispatcher, root: usize) {
recipe(d, root);
damage(d, root);
rotate_swing(d, root);
sounds(d, root);
particle(d, root);
attribute(d, root);
// ride <target> (mount <vehicle> | dismount)
let ride = d.literal(root, "ride");
d.requires(ride, GAMEMASTERS);
let target = d.argument(ride, "target", ENTITY);
let mount = d.literal(target, "mount");
let vehicle = d.argument(mount, "vehicle", ENTITY);
d.executes(vehicle, "ride.mount");
let dismount = d.literal(target, "dismount");
d.executes(dismount, "ride.dismount");
// spreadplayers <center> <spreadDistance> <maxRange> [under <maxHeight>] <respectTeams> <targets>
let spread = d.literal(root, "spreadplayers");
d.requires(spread, GAMEMASTERS);
let center = d.argument(spread, "center", ArgType::Vec2);
let dist = d.argument(center, "spreadDistance", float(0.0));
let range = d.argument(dist, "maxRange", float(1.0));
let respect = d.argument(range, "respectTeams", ArgType::Bool);
let targets = d.argument(respect, "targets", ENTITIES);
d.executes(targets, "spreadplayers");
let under = d.literal(range, "under");
let height = d.argument(under, "maxHeight", integer(i32::MIN));
let respect = d.argument(height, "respectTeams", ArgType::Bool);
let targets = d.argument(respect, "targets", ENTITIES);
d.executes(targets, "spreadplayers");
// place template <template> [<pos> [<rotation> [<mirror> [<integrity> [<seed> [strict]]]]]]
let place = d.literal(root, "place");
d.requires(place, GAMEMASTERS);
let feature = d.literal(place, "feature");
let f = d.argument(
feature,
"feature",
ArgType::ResourceOrId("minecraft:worldgen/feature"),
);
d.executes(f, "place.feature");
let pos = d.argument(f, "pos", ArgType::BlockPos);
d.executes(pos, "place.feature");
let jigsaw = d.literal(place, "jigsaw");
let pool = d.argument(
jigsaw,
"pool",
ArgType::ResKey("minecraft:worldgen/template_pool"),
);
let target = d.argument(pool, "target", ArgType::Id("none"));
let depth = d.argument(target, "max_depth", ArgType::Integer { min: 1, max: 20 });
d.executes(depth, "place.jigsaw");
let position = d.argument(depth, "position", ArgType::BlockPos);
d.executes(position, "place.jigsaw");
let structure = d.literal(place, "structure");
let st = d.argument(
structure,
"structure",
ArgType::ResKey("minecraft:worldgen/structure"),
);
d.executes(st, "place.structure");
let pos = d.argument(st, "pos", ArgType::BlockPos);
d.executes(pos, "place.structure");
let template = d.literal(place, "template");
let id = d.argument(template, "template", ArgType::Id("templates"));
d.executes(id, "place");
let pos = d.argument(id, "pos", ArgType::BlockPos);
d.executes(pos, "place");
let rotation = d.argument(
pos,
"rotation",
ArgType::StrEnum(
&["none", "clockwise_90", "180", "counterclockwise_90"],
"argument.enum.invalid",
),
);
d.executes(rotation, "place");
let mirror = d.argument(
rotation,
"mirror",
ArgType::StrEnum(
&["none", "left_right", "front_back"],
"argument.enum.invalid",
),
);
d.executes(mirror, "place");
let integrity = d.argument(mirror, "integrity", ArgType::Float { min: 0.0, max: 1.0 });
d.executes(integrity, "place");
let seed = d.argument(integrity, "seed", integer(i32::MIN));
d.executes(seed, "place");
let strict = d.literal(seed, "strict");
d.executes(strict, "place");
forceload(d, root);
fillbiome(d, root);
worldborder(d, root);
loot(d, root);
}
fn recipe(d: &mut Dispatcher, root: usize) {
let recipe = d.literal(root, "recipe");
d.requires(recipe, GAMEMASTERS);
for (word, id) in [("give", "recipe.give"), ("take", "recipe.take")] {
let w = d.literal(recipe, word);
let t = d.argument(w, "targets", PLAYERS);
let r = d.argument(t, "recipe", ArgType::ResKey("minecraft:recipe"));
d.executes(r, id);
let all = d.literal(t, "*");
d.executes(all, id);
}
}
fn damage(d: &mut Dispatcher, root: usize) {
let damage = d.literal(root, "damage");
d.requires(damage, GAMEMASTERS);
let target = d.argument(damage, "target", ENTITY);
let amount = d.argument(target, "amount", float(0.0));
d.executes(amount, "damage");
let ty = d.argument(amount, "damageType", ArgType::Res("minecraft:damage_type"));
d.executes(ty, "damage");
let at = d.literal(ty, "at");
let loc = d.argument(at, "location", ArgType::Vec3 { center: true });
d.executes(loc, "damage");
let by = d.literal(ty, "by");
let entity = d.argument(by, "entity", ENTITY);
d.executes(entity, "damage");
let from = d.literal(entity, "from");
let cause = d.argument(from, "cause", ENTITY);
d.executes(cause, "damage");
}
fn rotate_swing(d: &mut Dispatcher, root: usize) {
let rotate = d.literal(root, "rotate");
d.requires(rotate, GAMEMASTERS);
let target = d.argument(rotate, "target", ENTITY);
let rot = d.argument(target, "rotation", ArgType::Rotation);
d.executes(rot, "rotate");
let facing = d.literal(target, "facing");
let entity = d.literal(facing, "entity");
let fe = d.argument(entity, "facingEntity", ENTITY);
d.executes(fe, "rotate");
let anchor = d.argument(fe, "facingAnchor", ArgType::Anchor);
d.executes(anchor, "rotate");
let loc = d.argument(facing, "facingLocation", ArgType::Vec3 { center: true });
d.executes(loc, "rotate");
let swing = d.literal(root, "swing");
d.requires(swing, GAMEMASTERS);
d.executes(swing, "swing");
let targets = d.argument(swing, "targets", ENTITIES);
d.executes(targets, "swing");
for hand in ["mainhand", "offhand"] {
let h = d.literal(targets, hand);
d.executes(h, "swing");
let animation = d.argument(
h,
"animation",
ArgType::StrEnum(
&["none", "whack", "stab"],
"argument.swing_animation.invalid",
),
);
d.executes(animation, "swing");
let duration = d.argument(animation, "duration", ArgType::Time { min: 1 });
d.executes(duration, "swing");
}
}
fn sounds(d: &mut Dispatcher, root: usize) {
let play = d.literal(root, "playsound");
d.requires(play, GAMEMASTERS);
let sound = d.argument(play, "sound", ArgType::Id("sounds"));
d.executes(sound, "playsound");
let stop = d.literal(root, "stopsound");
d.requires(stop, GAMEMASTERS);
let stop_targets = d.argument(stop, "targets", PLAYERS);
d.executes(stop_targets, "stopsound");
let any = d.literal(stop_targets, "*");
let any_sound = d.argument(any, "sound", ArgType::Id("sounds"));
d.executes(any_sound, "stopsound");
for source in SOUND_SOURCES {
let s = d.literal(sound, source);
d.executes(s, "playsound");
let targets = d.argument(s, "targets", PLAYERS);
d.executes(targets, "playsound");
let pos = d.argument(targets, "pos", ArgType::Vec3 { center: true });
d.executes(pos, "playsound");
let volume = d.argument(pos, "volume", float(0.0));
d.executes(volume, "playsound");
let pitch = d.argument(volume, "pitch", ArgType::Float { min: 0.0, max: 2.0 });
d.executes(pitch, "playsound");
let min = d.argument(pitch, "minVolume", ArgType::Float { min: 0.0, max: 1.0 });
d.executes(min, "playsound");
let ls = d.literal(stop_targets, source);
d.executes(ls, "stopsound");
let lsound = d.argument(ls, "sound", ArgType::Id("sounds"));
d.executes(lsound, "stopsound");
}
}
fn particle(d: &mut Dispatcher, root: usize) {
let particle = d.literal(root, "particle");
d.requires(particle, GAMEMASTERS);
let name = d.argument(particle, "name", ArgType::Particle);
d.executes(name, "particle");
let pos = d.argument(name, "pos", ArgType::Vec3 { center: true });
d.executes(pos, "particle");
let delta = d.argument(pos, "delta", ArgType::Vec3 { center: false });
let speed = d.argument(delta, "speed", float(0.0));
let count = d.argument(speed, "count", integer(0));
d.executes(count, "particle");
for mode in ["force", "normal"] {
let m = d.literal(count, mode);
d.executes(m, "particle");
let viewers = d.argument(m, "viewers", PLAYERS);
d.executes(viewers, "particle");
}
}
fn attribute(d: &mut Dispatcher, root: usize) {
let attribute = d.literal(root, "attribute");
d.requires(attribute, GAMEMASTERS);
let target = d.argument(attribute, "target", ENTITY);
let attr = d.argument(target, "attribute", ArgType::Res("minecraft:attribute"));
let get = d.literal(attr, "get");
d.executes(get, "attribute.get");
let scale = d.argument(get, "scale", double());
d.executes(scale, "attribute.get");
let base = d.literal(attr, "base");
let set = d.literal(base, "set");
let value = d.argument(set, "value", double());
d.executes(value, "attribute.base.set");
let bget = d.literal(base, "get");
d.executes(bget, "attribute.base.get");
let bscale = d.argument(bget, "scale", double());
d.executes(bscale, "attribute.base.get");
let reset = d.literal(base, "reset");
d.executes(reset, "attribute.base.reset");
let modifier = d.literal(attr, "modifier");
let add = d.literal(modifier, "add");
let id = d.argument(add, "id", ArgType::Id("attribute_modifiers"));
let value = d.argument(id, "value", double());
for op in ["add_value", "add_multiplied_base", "add_multiplied_total"] {
let o = d.literal(value, op);
d.executes(o, "attribute.modifier.add");
}
let remove = d.literal(modifier, "remove");
let rid = d.argument(remove, "id", ArgType::Id("attribute_modifiers"));
d.executes(rid, "attribute.modifier.remove");
let value_l = d.literal(modifier, "value");
let vget = d.literal(value_l, "get");
let vid = d.argument(vget, "id", ArgType::Id("attribute_modifiers"));
d.executes(vid, "attribute.modifier.get");
let vscale = d.argument(vid, "scale", double());
d.executes(vscale, "attribute.modifier.get");
}
fn forceload(d: &mut Dispatcher, root: usize) {
let f = d.literal(root, "forceload");
d.requires(f, GAMEMASTERS);
for (word, id) in [("add", "forceload.add"), ("remove", "forceload.remove")] {
let w = d.literal(f, word);
let from = d.argument(w, "from", ArgType::ColumnPos);
d.executes(from, id);
let to = d.argument(from, "to", ArgType::ColumnPos);
d.executes(to, id);
if word == "remove" {
let all = d.literal(w, "all");
d.executes(all, "forceload.remove.all");
}
}
let query = d.literal(f, "query");
d.executes(query, "forceload.query");
let pos = d.argument(query, "pos", ArgType::ColumnPos);
d.executes(pos, "forceload.query");
}
fn fillbiome(d: &mut Dispatcher, root: usize) {
let f = d.literal(root, "fillbiome");
d.requires(f, GAMEMASTERS);
let from = d.argument(f, "from", ArgType::BlockPos);
let to = d.argument(from, "to", ArgType::BlockPos);
let biome = d.argument(to, "biome", ArgType::Res("minecraft:worldgen/biome"));
d.executes(biome, "fillbiome");
let replace = d.literal(biome, "replace");
let filter = d.argument(
replace,
"filter",
ArgType::ResOrTag("minecraft:worldgen/biome"),
);
d.executes(filter, "fillbiome");
}
fn worldborder(d: &mut Dispatcher, root: usize) {
let w = d.literal(root, "worldborder");
d.requires(w, GAMEMASTERS);
let dist = || ArgType::Double {
min: -5.999_996_8e7,
max: 5.999_996_8e7,
};
for word in ["add", "set"] {
let l = d.literal(w, word);
let distance = d.argument(l, "distance", dist());
let id = if word == "add" {
"worldborder.add"
} else {
"worldborder.set"
};
d.executes(distance, id);
let time = d.argument(distance, "time", ArgType::Time { min: 0 });
d.executes(time, id);
}
let center = d.literal(w, "center");
let pos = d.argument(center, "pos", ArgType::Vec2);
d.executes(pos, "worldborder.center");
let damage = d.literal(w, "damage");
let amount = d.literal(damage, "amount");
let per = d.argument(amount, "damagePerBlock", float(0.0));
d.executes(per, "worldborder.damage.amount");
let buffer = d.literal(damage, "buffer");
let b = d.argument(buffer, "distance", float(0.0));
d.executes(b, "worldborder.damage.buffer");
let get = d.literal(w, "get");
d.executes(get, "worldborder.get");
let warning = d.literal(w, "warning");
let wd = d.literal(warning, "distance");
let v = d.argument(wd, "distance", integer(0));
d.executes(v, "worldborder.warning.distance");
let wt = d.literal(warning, "time");
let v = d.argument(wt, "time", ArgType::Time { min: 0 });
d.executes(v, "worldborder.warning.time");
}
/// `loot (replace|insert|give|spawn) ... (fish|loot|kill|mine)`.
fn loot(d: &mut Dispatcher, root: usize) {
let loot = d.literal(root, "loot");
d.requires(loot, GAMEMASTERS);
// Targets.
let mut targets = Vec::new();
let replace = d.literal(loot, "replace");
for provider in ["entity", "block"] {
let p = d.literal(replace, provider);
let a = if provider == "entity" {
d.argument(p, "entities", ENTITIES)
} else {
d.argument(p, "targetPos", ArgType::BlockPos)
};
let slot = d.argument(a, "slot", ArgType::Slot);
targets.push(slot);
let count = d.argument(slot, "count", integer(0));
targets.push(count);
}
let insert = d.literal(loot, "insert");
targets.push(d.argument(insert, "targetPos", ArgType::BlockPos));
let give = d.literal(loot, "give");
targets.push(d.argument(give, "players", PLAYERS));
let spawn = d.literal(loot, "spawn");
targets.push(d.argument(spawn, "targetPos", ArgType::Vec3 { center: true }));
// Sources.
for t in targets {
let fish = d.literal(t, "fish");
let table = d.argument(
fish,
"loot_table",
ArgType::ResourceOrId("minecraft:loot_table"),
);
let pos = d.argument(table, "pos", ArgType::BlockPos);
d.executes(pos, "loot.fish");
for hand in ["mainhand", "offhand"] {
let h = d.literal(pos, hand);
d.executes(h, "loot.fish");
}
let tool = d.argument(pos, "tool", ArgType::Item);
d.executes(tool, "loot.fish");
let l = d.literal(t, "loot");
let lt = d.argument(
l,
"loot_table",
ArgType::ResourceOrId("minecraft:loot_table"),
);
d.executes(lt, "loot.loot");
let kill = d.literal(t, "kill");
let target = d.argument(kill, "target", ENTITY);
d.executes(target, "loot.kill");
let mine = d.literal(t, "mine");
let pos = d.argument(mine, "pos", ArgType::BlockPos);
d.executes(pos, "loot.mine");
for hand in ["mainhand", "offhand"] {
let h = d.literal(pos, hand);
d.executes(h, "loot.mine");
}
let tool = d.argument(pos, "tool", ArgType::Item);
d.executes(tool, "loot.mine");
}
}
@@ -1,614 +0,0 @@
//! The vanilla command tree (Commands.java registrations) for the commands
//! Horizon implements. Leaves carry command ids that the game executes;
//! mode keywords are read back from the parsed literals.
use super::{
Dispatcher,
args::{ArgType, Resource, integer},
};
use crate::gamerules::{RULES, Value};
/// Permission levels (Commands.LEVEL_*).
pub const ALL: u8 = 0;
pub const GAMEMASTERS: u8 = 2;
pub const PLAYERS: ArgType = ArgType::Entity {
single: false,
players: true,
};
pub const PLAYER: ArgType = ArgType::Entity {
single: true,
players: true,
};
pub const ENTITIES: ArgType = ArgType::Entity {
single: false,
players: false,
};
pub const ENTITY: ArgType = ArgType::Entity {
single: true,
players: false,
};
pub const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"];
pub fn build() -> Dispatcher {
build_with(true)
}
/// The tree Commands registers; `dev` adds the commands vanilla only
/// registers in development builds (raid, warden_spawn_tracker).
pub fn build_with(dev: bool) -> Dispatcher {
let mut d = registered(dev);
apply_vanilla_order(&mut d);
d
}
/// The tree in the order Horizon's code registers it, before
/// [`vanilla_order`](super::vanilla_order) puts children in vanilla's order
/// (tools/generate_command_order.py compares the two).
pub fn registered(dev: bool) -> Dispatcher {
let mut d = Dispatcher::new();
let root = 0;
advancement(&mut d, root);
// help [<command>]
let help = d.literal(root, "help");
d.executes(help, "help");
let c = d.argument(help, "command", ArgType::Greedy);
d.executes(c, "help");
// gamemode <gamemode> [<target>]
let gm = d.literal(root, "gamemode");
d.requires(gm, GAMEMASTERS);
let mode = d.argument(gm, "gamemode", ArgType::GameMode);
d.executes(mode, "gamemode");
let t = d.argument(mode, "target", PLAYERS);
d.executes(t, "gamemode");
let dgm = d.literal(root, "defaultgamemode");
d.requires(dgm, GAMEMASTERS);
let mode = d.argument(dgm, "gamemode", ArgType::GameMode);
d.executes(mode, "defaultgamemode");
// give <targets> <item> [<count>]
let give = d.literal(root, "give");
d.requires(give, GAMEMASTERS);
let targets = d.argument(give, "targets", PLAYERS);
let item = d.argument(targets, "item", ArgType::Item);
d.executes(item, "give");
let count = d.argument(item, "count", integer(1));
d.executes(count, "give");
// teleport / tp
let tp = d.literal(root, "teleport");
d.requires(tp, GAMEMASTERS);
let loc = d.argument(tp, "location", ArgType::Vec3 { center: true });
d.executes(loc, "teleport.location");
let dest = d.argument(tp, "destination", ENTITY);
d.executes(dest, "teleport.destination");
let targets = d.argument(tp, "targets", ENTITIES);
let loc = d.argument(targets, "location", ArgType::Vec3 { center: true });
d.executes(loc, "teleport.targets.location");
let rot = d.argument(loc, "rotation", ArgType::Rotation);
d.executes(rot, "teleport.targets.location");
let facing = d.literal(loc, "facing");
let fe = d.literal(facing, "entity");
let fent = d.argument(fe, "facingEntity", ENTITY);
d.executes(fent, "teleport.targets.location");
let anchor = d.argument(fent, "facingAnchor", ArgType::Anchor);
d.executes(anchor, "teleport.targets.location");
let floc = d.argument(facing, "facingLocation", ArgType::Vec3 { center: true });
d.executes(floc, "teleport.targets.location");
let dest = d.argument(targets, "destination", ENTITY);
d.executes(dest, "teleport.targets.destination");
let alias = d.literal(root, "tp");
d.requires(alias, GAMEMASTERS);
d.redirect(alias, tp);
// time: clock nodes for the dimension's default clock, plus `of <clock>`.
let time = d.literal(root, "time");
d.requires(time, GAMEMASTERS);
clock_nodes(&mut d, time);
let query = d.literal(time, "query");
let gt = d.literal(query, "gametime");
d.executes(gt, "time.query.gametime");
let of = d.literal(time, "of");
let clock = d.argument(of, "clock", ArgType::Resource(Resource::Clock));
clock_nodes(&mut d, clock);
// weather (clear|rain|thunder) [<duration>]
let weather = d.literal(root, "weather");
d.requires(weather, GAMEMASTERS);
for kind in ["clear", "rain", "thunder"] {
let k = d.literal(weather, kind);
d.executes(k, "weather");
let dur = d.argument(k, "duration", ArgType::Time { min: 1 });
d.executes(dur, "weather");
}
if dev {
// raid start <omenlvl> | stop | check | sound <type> | spawnleader | setomen <level> | glow
let raid = d.literal(root, "raid");
d.requires(raid, 3);
let start = d.literal(raid, "start");
let level = d.argument(start, "omenlvl", integer(0));
d.executes(level, "raid.start");
for (name, id) in [
("stop", "raid.stop"),
("check", "raid.check"),
("spawnleader", "raid.spawnleader"),
("glow", "raid.glow"),
] {
let n = d.literal(raid, name);
d.executes(n, id);
}
let sound = d.literal(raid, "sound");
let kind = d.argument(sound, "type", ArgType::Greedy);
d.executes(kind, "raid.sound");
let setomen = d.literal(raid, "setomen");
let level = d.argument(setomen, "level", integer(0));
d.executes(level, "raid.setomen");
}
// kill [<targets>]
let kill = d.literal(root, "kill");
d.requires(kill, GAMEMASTERS);
d.executes(kill, "kill");
let t = d.argument(kill, "targets", ENTITIES);
d.executes(t, "kill");
// effect clear [<targets> [<effect>]] | give <targets> <effect> [<seconds>|infinite [<amplifier> [<hideParticles>]]]
let effect = d.literal(root, "effect");
d.requires(effect, GAMEMASTERS);
let clear = d.literal(effect, "clear");
d.executes(clear, "effect.clear");
let t = d.argument(clear, "targets", ENTITIES);
d.executes(t, "effect.clear");
let e = d.argument(t, "effect", ArgType::Resource(Resource::Effect));
d.executes(e, "effect.clear");
let give = d.literal(effect, "give");
let t = d.argument(give, "targets", ENTITIES);
let e = d.argument(t, "effect", ArgType::Resource(Resource::Effect));
d.executes(e, "effect.give");
let seconds = d.argument(
e,
"seconds",
ArgType::Integer {
min: 1,
max: 1_000_000,
},
);
let infinite = d.literal(e, "infinite");
for duration in [seconds, infinite] {
d.executes(duration, "effect.give");
let amp = d.argument(duration, "amplifier", ArgType::Integer { min: 0, max: 255 });
d.executes(amp, "effect.give");
let hide = d.argument(amp, "hideParticles", ArgType::Bool);
d.executes(hide, "effect.give");
}
// enchant <targets> <enchantment> [<level>]
let enchant = d.literal(root, "enchant");
d.requires(enchant, GAMEMASTERS);
let t = d.argument(enchant, "targets", ENTITIES);
let e = d.argument(t, "enchantment", ArgType::Resource(Resource::Enchantment));
d.executes(e, "enchant");
let level = d.argument(e, "level", integer(0));
d.executes(level, "enchant");
// summon <entity> [<pos>] [<nbt>]
let summon = d.literal(root, "summon");
d.requires(summon, GAMEMASTERS);
let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType));
d.suggests(e, super::Suggests::SummonableEntities);
d.executes(e, "summon");
let pos = d.argument(e, "pos", ArgType::Vec3 { center: true });
d.executes(pos, "summon");
let nbt = d.argument(pos, "nbt", ArgType::Nbt);
d.executes(nbt, "summon");
// setblock <pos> <block> [destroy|keep|replace|strict]
let sb = d.literal(root, "setblock");
d.requires(sb, GAMEMASTERS);
let pos = d.argument(sb, "pos", ArgType::BlockPos);
let block = d.argument(pos, "block", ArgType::BlockState);
d.executes(block, "setblock");
for m in ["destroy", "keep", "replace", "strict"] {
let l = d.literal(block, m);
d.executes(l, "setblock");
}
// fill <from> <to> <block> [modes]
let fill = d.literal(root, "fill");
d.requires(fill, GAMEMASTERS);
let from = d.argument(fill, "from", ArgType::BlockPos);
let to = d.argument(from, "to", ArgType::BlockPos);
let block = d.argument(to, "block", ArgType::BlockState);
fill_modes(&mut d, block);
let replace = d.literal(block, "replace");
d.executes(replace, "fill");
let filter = d.argument(replace, "filter", ArgType::BlockPredicate);
fill_modes(&mut d, filter);
let keep = d.literal(block, "keep");
d.executes(keep, "fill");
// clone [from <dim>] <begin> <end> [to <dim>] <destination> [strict] [mask] [mode]
let clone = d.literal(root, "clone");
d.requires(clone, GAMEMASTERS);
clone_begin(&mut d, clone);
let from = d.literal(clone, "from");
let dim = d.argument(from, "sourceDimension", ArgType::Dimension);
clone_begin(&mut d, dim);
// experience / xp
let xp = d.literal(root, "experience");
d.requires(xp, GAMEMASTERS);
for (op, min) in [("add", i32::MIN), ("set", 0)] {
let o = d.literal(xp, op);
let t = d.argument(o, "target", PLAYERS);
let amount = d.argument(t, "amount", integer(min));
d.executes(amount, "experience");
for unit in ["points", "levels"] {
let u = d.literal(amount, unit);
d.executes(u, "experience");
}
}
let q = d.literal(xp, "query");
let t = d.argument(q, "target", PLAYER);
for unit in ["points", "levels"] {
let u = d.literal(t, unit);
d.executes(u, "experience");
}
let alias = d.literal(root, "xp");
d.requires(alias, GAMEMASTERS);
d.redirect(alias, xp);
// gamerule <rule> [<value>] (short and namespaced names)
let gr = d.literal(root, "gamerule");
d.requires(gr, GAMEMASTERS);
for rule in RULES {
for name in [rule.name.to_owned(), format!("minecraft:{}", rule.name)] {
let r = d.literal(gr, &name);
d.executes(r, "gamerule");
let ty = match rule.default {
Value::Bool(_) => ArgType::Bool,
Value::Int(_) => ArgType::Integer {
min: rule.min,
max: rule.max,
},
};
let v = d.argument(r, "value", ty);
d.executes(v, "gamerule");
}
}
// difficulty [<difficulty>]
let diff = d.literal(root, "difficulty");
d.requires(diff, GAMEMASTERS);
d.executes(diff, "difficulty");
for name in DIFFICULTIES {
let l = d.literal(diff, name);
d.executes(l, "difficulty");
}
// seed and version: everyone in the integrated server.
let seed = d.literal(root, "seed");
d.executes(seed, "seed");
let version = d.literal(root, "version");
d.executes(version, "version");
// spawnpoint [<targets>] [<pos>] [<rotation>]
let sp = d.literal(root, "spawnpoint");
d.requires(sp, GAMEMASTERS);
d.executes(sp, "spawnpoint");
let t = d.argument(sp, "targets", PLAYERS);
d.executes(t, "spawnpoint");
let pos = d.argument(t, "pos", ArgType::BlockPos);
d.executes(pos, "spawnpoint");
let rot = d.argument(pos, "rotation", ArgType::Rotation);
d.executes(rot, "spawnpoint");
// setworldspawn [<pos>] [<rotation>]
let ws = d.literal(root, "setworldspawn");
d.requires(ws, GAMEMASTERS);
d.executes(ws, "setworldspawn");
let pos = d.argument(ws, "pos", ArgType::BlockPos);
d.executes(pos, "setworldspawn");
let rot = d.argument(pos, "rotation", ArgType::Rotation);
d.executes(rot, "setworldspawn");
// clear [<targets>] [<item>] [<maxCount>]
let clear = d.literal(root, "clear");
d.requires(clear, GAMEMASTERS);
d.executes(clear, "clear");
let t = d.argument(clear, "targets", PLAYERS);
d.executes(t, "clear");
let item = d.argument(t, "item", ArgType::ItemPredicate);
d.executes(item, "clear");
let max = d.argument(item, "maxCount", integer(0));
d.executes(max, "clear");
// locate (structure|biome) <...>
let locate = d.literal(root, "locate");
d.requires(locate, GAMEMASTERS);
let s = d.literal(locate, "structure");
let a = d.argument(
s,
"structure",
ArgType::ResOrTagKey("minecraft:worldgen/structure"),
);
d.executes(a, "locate.structure");
let b = d.literal(locate, "biome");
let a = d.argument(b, "biome", ArgType::ResOrTag("minecraft:worldgen/biome"));
d.executes(a, "locate.biome");
let p = d.literal(locate, "poi");
let a = d.argument(
p,
"poi",
ArgType::ResOrTag("minecraft:point_of_interest_type"),
);
d.executes(a, "locate.poi");
if dev {
// warden_spawn_tracker (clear | set <warning_level>)
let tracker = d.literal(root, "warden_spawn_tracker");
d.requires(tracker, GAMEMASTERS);
let clear = d.literal(tracker, "clear");
d.executes(clear, "warden_spawn_tracker.clear");
let set = d.literal(tracker, "set");
let level = d.argument(set, "warning_level", ArgType::Integer { min: 0, max: 4 });
d.executes(level, "warden_spawn_tracker.set");
}
// say / me / msg / list
let say = d.literal(root, "say");
d.requires(say, GAMEMASTERS);
let m = d.argument(say, "message", ArgType::Message);
d.executes(m, "say");
let me = d.literal(root, "me");
let m = d.argument(me, "action", ArgType::Message);
d.executes(m, "me");
let msg = d.literal(root, "msg");
let t = d.argument(msg, "targets", PLAYERS);
let m = d.argument(t, "message", ArgType::Message);
d.executes(m, "msg");
for alias in ["tell", "w"] {
let a = d.literal(root, alias);
d.redirect(a, msg);
}
let list = d.literal(root, "list");
d.executes(list, "list");
let uuids = d.literal(list, "uuids");
d.executes(uuids, "list");
// tellraw <targets> <message>
let tellraw = d.literal(root, "tellraw");
d.requires(tellraw, GAMEMASTERS);
let t = d.argument(tellraw, "targets", PLAYERS);
let m = d.argument(t, "message", ArgType::Component);
d.executes(m, "tellraw");
// title <targets> clear|reset|title|subtitle|actionbar <title>|times <in> <stay> <out>
let title = d.literal(root, "title");
d.requires(title, GAMEMASTERS);
let t = d.argument(title, "targets", PLAYERS);
for mode in ["clear", "reset"] {
let l = d.literal(t, mode);
d.executes(l, "title");
}
for mode in ["title", "subtitle", "actionbar"] {
let l = d.literal(t, mode);
let c = d.argument(l, "title", ArgType::Component);
d.executes(c, "title");
}
let times = d.literal(t, "times");
let fade_in = d.argument(times, "fadeIn", ArgType::Time { min: 0 });
let stay = d.argument(fade_in, "stay", ArgType::Time { min: 0 });
let fade_out = d.argument(stay, "fadeOut", ArgType::Time { min: 0 });
d.executes(fade_out, "title");
super::tree_scoreboard::register(&mut d, root);
super::tree_data::register(&mut d, root);
super::tree_execute::register(&mut d, root);
super::tree_misc::register(&mut d, root);
super::tree_world::register(&mut d, root);
super::tree_extra::register(&mut d, root);
d
}
/// AdvancementCommands: grant|revoke <targets> only|from|until|through
/// <advancement> | everything; `only` takes an optional criterion.
fn advancement(d: &mut Dispatcher, root: usize) {
let adv = d.literal(root, "advancement");
d.requires(adv, GAMEMASTERS);
for action in ["grant", "revoke"] {
let a = d.literal(adv, action);
let t = d.argument(a, "targets", PLAYERS);
for mode in ["only", "from", "until", "through"] {
let m = d.literal(t, mode);
let id = d.argument(m, "advancement", ArgType::ResKey("minecraft:advancement"));
d.executes(id, "advancement");
if mode == "only" {
let c = d.argument(id, "criterion", ArgType::Greedy);
d.suggests(c, super::Suggests::AdvancementCriteria);
d.executes(c, "advancement");
}
}
let e = d.literal(t, "everything");
d.executes(e, "advancement");
}
}
/// TimeCommand.addClockNodes.
fn clock_nodes(d: &mut Dispatcher, node: usize) {
let set = d.literal(node, "set");
let t = d.argument(set, "time", ArgType::Time { min: 0 });
d.executes(t, "time.set");
let marker = d.argument(set, "timemarker", ArgType::Id("time_markers"));
d.suggests(marker, super::Suggests::TimeMarkers);
d.executes(marker, "time.set.marker");
let add = d.literal(node, "add");
let t = d.argument(add, "time", ArgType::Time { min: i32::MIN });
d.executes(t, "time.add");
let pause = d.literal(node, "pause");
d.executes(pause, "time.pause");
let resume = d.literal(node, "resume");
d.executes(resume, "time.resume");
let rate = d.literal(node, "rate");
let r = d.argument(
rate,
"rate",
ArgType::Float {
min: 1.0e-5,
max: 1000.0,
},
);
d.executes(r, "time.rate");
let query = d.literal(node, "query");
let time = d.literal(query, "time");
d.executes(time, "time.query.time");
let tl = d.argument(query, "timeline", ArgType::Resource(Resource::Timeline));
d.executes(tl, "time.query.timeline");
let rep = d.literal(tl, "repetition");
d.executes(rep, "time.query.repetition");
}
/// FillCommand.wrapWithMode.
fn fill_modes(d: &mut Dispatcher, node: usize) {
d.executes(node, "fill");
for m in ["outline", "hollow", "destroy", "strict"] {
let l = d.literal(node, m);
d.executes(l, "fill");
}
}
fn clone_begin(d: &mut Dispatcher, node: usize) {
let begin = d.argument(node, "begin", ArgType::BlockPos);
let end = d.argument(begin, "end", ArgType::BlockPos);
clone_destination(d, end);
let to = d.literal(end, "to");
let dim = d.argument(to, "targetDimension", ArgType::Dimension);
clone_destination(d, dim);
}
fn clone_destination(d: &mut Dispatcher, node: usize) {
let dest = d.argument(node, "destination", ArgType::BlockPos);
clone_mask(d, dest);
let strict = d.literal(dest, "strict");
clone_mask(d, strict);
}
fn clone_mask(d: &mut Dispatcher, node: usize) {
d.executes(node, "clone");
for m in ["replace", "masked"] {
let l = d.literal(node, m);
clone_mode(d, l);
}
let filtered = d.literal(node, "filtered");
let filter = d.argument(filtered, "filter", ArgType::BlockPredicate);
clone_mode(d, filter);
}
fn clone_mode(d: &mut Dispatcher, node: usize) {
d.executes(node, "clone");
for m in ["force", "move", "normal"] {
let l = d.literal(node, m);
d.executes(l, "clone");
}
}
/// The shared vanilla tree.
/// Reorder node children as vanilla registers them (Brigadier keeps
/// children in registration order; smart usage lists them that way).
fn apply_vanilla_order(d: &mut Dispatcher) {
for (path, order) in super::vanilla_order::ORDER {
let mut node = Some(0usize);
for name in path.split(' ').filter(|n| !n.is_empty()) {
node = node.and_then(|n| {
d.nodes[n]
.children
.iter()
.copied()
.find(|&c| d.nodes[c].name() == name)
});
}
let Some(n) = node else { continue };
let mut children = d.nodes[n].children.clone();
let rank = |c: usize| {
order
.iter()
.position(|o| *o == d.nodes[c].name())
.unwrap_or(order.len())
};
children.sort_by_key(|&c| rank(c));
d.nodes[n].children = children;
}
}
/// The tree the game runs: a release integrated server's, or with
/// `HORIZON_DEV_COMMANDS` set the development one
/// (SharedConstants.DEBUG_DEV_COMMANDS), plus Horizon's own commands when
/// the server turned them on (`set_horizon_commands`).
pub fn game_dispatcher() -> &'static Dispatcher {
game_tree(
std::env::var_os("HORIZON_DEV_COMMANDS").is_some(),
HORIZON_COMMANDS.load(std::sync::atomic::Ordering::Relaxed),
)
}
/// Whether this process's server has Horizon's own commands (`/pregen`). Off
/// by default, so `/help` and the command tree are vanilla's; a dedicated
/// server turns them on with `horizon-pregen=true` in server.properties, the
/// game with `--pregen` (docs/pregeneration.md).
static HORIZON_COMMANDS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Turns Horizon's own commands on or off for the trees `game_dispatcher`
/// returns from now on.
pub fn set_horizon_commands(on: bool) {
HORIZON_COMMANDS.store(on, std::sync::atomic::Ordering::Relaxed);
}
/// The server.properties key that turns `/pregen` on (Horizon's own; vanilla
/// ignores keys it doesn't know).
pub const PREGEN_PROPERTY: &str = "horizon-pregen";
pub(crate) fn game_tree(dev: bool, horizon: bool) -> &'static Dispatcher {
static HORIZON: [std::sync::OnceLock<Dispatcher>; 2] =
[const { std::sync::OnceLock::new() }; 2];
match (dev, horizon) {
(true, false) => dispatcher(),
(false, false) => release_dispatcher(),
(dev, true) => HORIZON[usize::from(dev)].get_or_init(|| {
let mut d = build_with(dev);
horizon_commands(&mut d, 0);
d
}),
}
}
/// Commands vanilla doesn't have, after its own: `/pregen`
/// (docs/pregeneration.md).
fn horizon_commands(d: &mut Dispatcher, root: usize) {
let pregen = d.literal(root, "pregen");
d.requires(pregen, GAMEMASTERS);
let start = d.literal(pregen, "start");
let radius = d.argument(
start,
"radius",
ArgType::Integer {
min: 0,
max: 30_000_000,
},
);
d.executes(radius, "pregen.start");
for shape in ["square", "circle"] {
let shape = d.literal(radius, shape);
d.executes(shape, "pregen.start");
let center = d.argument(shape, "center", ArgType::ColumnPos);
d.executes(center, "pregen.start");
}
for (word, id) in [
("pause", "pregen.pause"),
("continue", "pregen.continue"),
("cancel", "pregen.cancel"),
("status", "pregen.status"),
] {
let w = d.literal(pregen, word);
d.executes(w, id);
}
}
pub fn dispatcher() -> &'static Dispatcher {
static TREE: std::sync::OnceLock<Dispatcher> = std::sync::OnceLock::new();
TREE.get_or_init(build)
}
/// The tree of a release integrated server (no development commands).
pub fn release_dispatcher() -> &'static Dispatcher {
static TREE: std::sync::OnceLock<Dispatcher> = std::sync::OnceLock::new();
TREE.get_or_init(|| build_with(false))
}
@@ -1,234 +0,0 @@
//! The order of node children in vanilla's command tree, for the nodes
//! where Horizon's tree registers them differently (path of node names
//! from the root, children in vanilla's order). Generated by
//! tools/generate_command_order.py; do not edit by hand.
pub const ORDER: &[(&str, &[&str])] = &[
(
"",
&[
"advancement",
"attribute",
"execute",
"bossbar",
"clear",
"clone",
"compute",
"damage",
"data",
"datapack",
"debug",
"defaultgamemode",
"dialog",
"difficulty",
"effect",
"me",
"enchant",
"experience",
"xp",
"fill",
"fillbiome",
"forceload",
"function",
"gamemode",
"gamerule",
"give",
"help",
"item",
"kick",
"kill",
"list",
"locate",
"loot",
"msg",
"tell",
"w",
"swing",
"particle",
"place",
"playsound",
"posteffect",
"random",
"reload",
"recipe",
"fetchprofile",
"return",
"ride",
"rotate",
"say",
"schedule",
"scoreboard",
"seed",
"version",
"setblock",
"spawnpoint",
"setworldspawn",
"spectate",
"spreadplayers",
"stopsound",
"stopwatch",
"summon",
"tag",
"team",
"teammsg",
"tm",
"teleport",
"tp",
"tellraw",
"test",
"tick",
"time",
"title",
"trigger",
"waypoint",
"weather",
"worldborder",
"jfr",
"publish",
"unpublish",
],
),
(
"execute",
&[
"run",
"if",
"unless",
"as",
"at",
"store",
"positioned",
"rotated",
"facing",
"align",
"anchored",
"in",
"summon",
"on",
],
),
(
"execute if",
&[
"block",
"biome",
"loaded",
"dimension",
"score",
"blocks",
"entity",
"predicate",
"function",
"stopwatch",
"data",
"items",
"slots",
],
),
(
"execute unless",
&[
"block",
"biome",
"loaded",
"dimension",
"score",
"blocks",
"entity",
"predicate",
"function",
"stopwatch",
"data",
"items",
"slots",
],
),
("execute facing", &["entity", "pos"]),
("datapack", &["enable", "disable", "list", "create"]),
(
"datapack enable name",
&["after", "before", "last", "first"],
),
("item", &["replace", "fill", "override", "modify"]),
("item replace entity target slots", &["from", "with"]),
("item fill entity target slots", &["from", "with"]),
("item override entity target slots", &["from", "with"]),
(
"loot replace entity entities slot",
&["fish", "loot", "kill", "mine", "count"],
),
(
"loot replace entity entities slot fish loot_table pos",
&["tool", "mainhand", "offhand"],
),
(
"loot replace entity entities slot mine pos",
&["tool", "mainhand", "offhand"],
),
(
"loot replace entity entities slot count fish loot_table pos",
&["tool", "mainhand", "offhand"],
),
(
"loot replace entity entities slot count mine pos",
&["tool", "mainhand", "offhand"],
),
(
"loot replace block targetPos slot",
&["fish", "loot", "kill", "mine", "count"],
),
(
"loot replace block targetPos slot fish loot_table pos",
&["tool", "mainhand", "offhand"],
),
(
"loot replace block targetPos slot mine pos",
&["tool", "mainhand", "offhand"],
),
(
"loot replace block targetPos slot count fish loot_table pos",
&["tool", "mainhand", "offhand"],
),
(
"loot replace block targetPos slot count mine pos",
&["tool", "mainhand", "offhand"],
),
(
"loot insert targetPos fish loot_table pos",
&["tool", "mainhand", "offhand"],
),
(
"loot insert targetPos mine pos",
&["tool", "mainhand", "offhand"],
),
(
"loot give players fish loot_table pos",
&["tool", "mainhand", "offhand"],
),
(
"loot give players mine pos",
&["tool", "mainhand", "offhand"],
),
(
"loot spawn targetPos fish loot_table pos",
&["tool", "mainhand", "offhand"],
),
(
"loot spawn targetPos mine pos",
&["tool", "mainhand", "offhand"],
),
(
"scoreboard players",
&[
"list",
"set",
"get",
"add",
"remove",
"reset",
"enable",
"display",
"operation",
],
),
];
-327
View File
@@ -1,327 +0,0 @@
//! 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::keybinds::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);
}
}
+18
View File
@@ -370,6 +370,12 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
"minecraft:bat" => {
map.insert("BatFlags".into(), Tag::Byte(i8::from(m.extra.flag)));
}
"minecraft:turtle" => {
map.insert("has_egg".into(), Tag::Byte(i8::from(m.extra.flag)));
if let Some(home) = m.extra.home {
map.insert("home_pos".into(), Tag::IntArray(home.to_vec()));
}
}
"minecraft:creaking" => {
// home_pos: the heart it is bound to.
if let Some(home) = m.extra.home {
@@ -876,6 +882,18 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
{
crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]);
}
if m.species() == crate::mobs::Species::Turtle {
// Turtle.readAdditionalSaveData: `home_pos` (else where it stands) and `has_egg`.
m.extra.flag = flag(tag, "has_egg");
m.extra.home = Some(match tag.get("home_pos") {
Some(Tag::IntArray(home)) if home.len() == 3 => [home[0], home[1], home[2]],
_ => [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
],
});
}
if m.species() == crate::mobs::Species::Wither {
m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32;
}
-270
View File
@@ -1,270 +0,0 @@
//! 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"]);
}
}
+86 -21
View File
@@ -102,7 +102,12 @@ mod maps;
mod minecarts;
mod mob_blocks;
mod mob_gear;
mod mod_browser;
#[cfg(feature = "mods")]
mod mod_browser_recipes;
mod mod_input;
#[cfg(feature = "mods")]
mod mod_recipes;
mod mod_render;
mod mods;
mod mount_menu;
@@ -370,7 +375,7 @@ impl Options {
match arg.as_str() {
"--help" | "-h" => {
println!(
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --quickPlaySingleplayer WORLD Open this world of saves/ at start, only if it exists (vanilla's)\n --quickPlayMultiplayer HOST[:PORT] The same as --server (vanilla's name)\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
horizon_core::VANILLA_VERSION
);
return Ok(None);
@@ -425,6 +430,16 @@ impl Options {
"--width" => o.window_size[0] = value.parse::<u32>()?.max(1),
"--height" => o.window_size[1] = value.parse::<u32>()?.max(1),
"--world" => o.world = Some(value),
// Vanilla's quick play (Main, QuickPlay.joinSingleplayerWorld): only a
// world that exists opens; else the title screen. --world also creates one.
"--quickPlaySingleplayer" => {
let folder = std::env::current_dir()?.join("saves").join(&value);
if folder.join("level.dat").is_file() {
o.world = Some(value);
} else {
eprintln!("Quick play: there is no world {value} in saves/");
}
}
"--dev-mod" => o.dev_mods.push(std::path::absolute(&value)?),
"--benchmark" => {
if horizon_client::benchmark::scenes(&value).is_none() {
@@ -435,7 +450,7 @@ impl Options {
}
o.benchmark = Some(value);
}
"--server" => o.server = Some(value),
"--server" | "--quickPlayMultiplayer" => o.server = Some(value),
"--name" => o.player_name = Some(value),
"--session-file" => session_file = Some(value),
"--control-socket" => o.control = Some(value.into()),
@@ -3115,6 +3130,11 @@ impl Game<'_> {
kind: "hatch_sniffer",
..
} => self.hatch_sniffer([pos.x, pos.y, pos.z]),
LevelEvent::BlockEvent {
pos,
state,
kind: "hatch_turtles",
} => self.hatch_turtles([pos.x, pos.y, pos.z], state),
LevelEvent::BlockEvent {
pos,
kind: "portal_spawn",
@@ -4512,6 +4532,22 @@ impl Game<'_> {
};
self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5;
let crouching = player.pose == horizon_client::pose::Pose::Crouching;
// `LivingEntity.baseTick` (Soul Speed) comes before `aiStep` (the
// glide's wear): both draw from the level random.
if let Some((at, velocity)) = self.tick_soul_speed() {
self.particles.send_particles(
&horizon_client::particles::ParticleOptions::simple(
horizon_client::particles::ParticleType::Soul,
),
at,
velocity,
1.0,
0,
);
if let Some(host) = self.lan.as_ref() {
lan_particles::send_soul_particle(host, at, velocity);
}
}
// `ItemStack.hurtAndBreak` for the glide: Unbreaking can save the wear.
if glider_wear > 0
&& !self.creative
@@ -5402,6 +5438,7 @@ impl Game<'_> {
Screen::CommandBlock => self.draw_command_block(&mut batch),
Screen::Inventory => {
self.draw_inventory(&mut batch);
self.draw_mod_browser(&mut batch);
}
Screen::Creative => {
self.draw_creative(&mut batch);
@@ -5794,6 +5831,7 @@ impl Game<'_> {
self.last_inv_click = None;
}
pub(super) fn close_container(&mut self) {
self.mod_browser_closed();
self.reset_inventory_clicks();
self.close_station();
self.mount_closed();
@@ -6521,6 +6559,9 @@ impl Game<'_> {
fn inventory_press(&mut self, right: bool) {
use horizon_client::container_screen::Target;
use horizon_client::menu::Input;
if self.mod_browser_press(right) {
return;
}
if !right && self.sort_press() {
return;
}
@@ -6704,24 +6745,8 @@ impl Game<'_> {
}
/// `hasClickedOutside` of the open screen at the cursor.
fn clicked_outside(&self, batch: &HudBatch) -> bool {
use horizon_client::container_screen::{Book, Image, clicked_outside};
let (ox, oy) = self.inventory_origin(batch);
let (shift, width, height) = if self.screen == Screen::Creative {
(0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32)
} else {
let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
Some(stations::Kind::Merchant) => (-50.0, 276),
Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
_ => (0.0, 176),
};
(shift, width, self.screen_height() as i32)
};
let image = Image {
left: (ox + shift) as i32,
top: oy as i32,
width,
height,
};
use horizon_client::container_screen::{Book, clicked_outside};
let image = self.container_image(batch);
let book = self
.recipe_book_area(batch)
.map(|(visible, tab_hovered)| Book {
@@ -6735,6 +6760,26 @@ impl Game<'_> {
book,
)
}
/// The open container screen's window: its place and size.
fn container_image(&self, batch: &HudBatch) -> horizon_client::container_screen::Image {
let (ox, oy) = self.inventory_origin(batch);
let (shift, width, height) = if self.screen == Screen::Creative {
(0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32)
} else {
let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
Some(stations::Kind::Merchant) => (-50.0, 276),
Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
_ => (0.0, 176),
};
(shift, width, self.screen_height() as i32)
};
horizon_client::container_screen::Image {
left: (ox + shift) as i32,
top: oy as i32,
width,
height,
}
}
/// A click outside the window (slot id -999): `THROW` does nothing; a
/// `PICKUP` drops the carried stack (left) or one of it (right), thrown
/// from the hand (`AbstractContainerMenu.doClick`, `LivingEntity.drop`).
@@ -6895,7 +6940,7 @@ impl Game<'_> {
}
}
fn click_inventory(&mut self, right: bool) {
if self.mount_click(right) {
if self.mod_browser_press(right) || self.mount_click(right) {
return;
}
if self.recipe_book_click(right) {
@@ -8067,6 +8112,7 @@ impl Game<'_> {
creative: bool,
create: Option<&horizon_client::title::WorldOptions>,
) -> Result<()> {
world_loading::world_data_used();
if self.defer_world_entry(PendingWorldEntry::Local {
folder: folder.to_owned(),
name: name.map(str::to_owned),
@@ -12127,6 +12173,14 @@ impl ApplicationHandler for Game<'_> {
// The recipe book's search box takes every key but Escape.
self.recipe_key(&event);
}
WindowEvent::KeyboardInput { event, .. }
if self.mod_browser_typing()
&& event.state == ElementState::Pressed
&& !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) =>
{
// A mod's item panel's search box, as the recipe book's.
self.mod_browser_key(&event);
}
WindowEvent::KeyboardInput { event, .. }
if self.station_typing()
&& event.state == ElementState::Pressed
@@ -13036,6 +13090,17 @@ impl Game<'_> {
if self.rest_loader.is_some() {
return Ok(());
}
let on_world_screens = self.title.as_ref().is_some_and(|title| {
!matches!(
title.mode,
horizon_client::title::Mode::Main | horizon_client::title::Mode::Multiplayer(_)
)
});
world_loading::preload_world_data(
on_world_screens,
&self.options.resources,
self.pack.assets.registry,
);
if std::mem::take(&mut self.pending_pack_reload) {
self.reload_packs();
}
@@ -115,6 +115,7 @@ impl Game<'_> {
"in_fire" | "campfire" | "hot_floor" => DamageKind::InFire,
"lava" => DamageKind::Lava,
"drown" => DamageKind::Drown,
"dry_out" => DamageKind::DryOut,
"magic" | "indirect_magic" | "dragon_breath" => DamageKind::Magic,
"sting" => DamageKind::Sting,
"cactus" | "sweet_berry_bush" => DamageKind::Cactus,
@@ -628,6 +628,9 @@ impl Game<'_> {
// The port, or the game rules' search and number boxes.
Screen::WorldOptions if text == "\\b" => self.world_options_text(None),
Screen::WorldOptions => self.world_options_text(Some(text)),
Screen::Inventory if self.mod_browser_typing() => {
self.mod_browser_text((text != "\\b").then_some(text), text == "\\b")
}
Screen::Inventory if self.recipe_search_focused() => {
self.recipe_text(Some(text), false)
}
+71 -2
View File
@@ -1289,6 +1289,10 @@ impl Game<'_> {
self.mob_vibration_particle(from, to, ticks)
}
MobEvent::DigParticles { at } => self.warden_dig_particles(at),
MobEvent::BlockBreakEffect { pos, block } => {
let state = self.world.block(block[0], block[1], block[2]);
self.destroy_particles(pos, state);
}
MobEvent::Darkness { at, radius } => self.apply_darkness(at, radius),
MobEvent::CreakingHurt {
home,
@@ -1327,11 +1331,51 @@ impl Game<'_> {
m.ai.aggressive |= aggressive;
}
}
MobEvent::GiftLoot { mob, table, at } => self.drop_gift_loot(mob, table, at),
MobEvent::GiftLoot { mob, table, at } => {
// Turtle.ageBoundaryReached: only with mob loot on.
if table == "minecraft:gameplay/turtle_grow" && !self.ui.rules.bool("mob_drops")
{
continue;
}
self.drop_gift_loot(mob, table, at);
}
}
}
Ok(())
}
/// `TurtleEggBlock.randomTick` at the last hatch stage: one baby turtle
/// per egg, a day from grown, with the egg as its home (the sound, the
/// crumbs and the block's removal came from the level).
pub(super) fn hatch_turtles(
&mut self,
pos: [i32; 3],
state: horizon_world::registry::BlockStateId,
) {
let eggs = self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("eggs"))
.and_then(|v| v.parse::<i32>().ok())
.unwrap_or(1);
for i in 0..eggs {
let at = [
f64::from(pos[0]) + 0.3 + f64::from(i) * 0.2,
f64::from(pos[1]),
f64::from(pos[2]) + 0.3,
];
if let Some(id) = self.spawn_mob("minecraft:turtle", at, true)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
m.extra.age = -24000;
m.extra.home = Some(pos);
m.yaw = 0.0;
m.body_yaw = 0.0;
m.head_yaw = 0.0;
}
}
}
fn apply_setup(&mut self, id: u32, setup: &SpawnSetup) {
let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else {
return;
@@ -1394,6 +1438,8 @@ impl Game<'_> {
.unwrap_or_else(|| parent.clone());
let mut child = parent.clone();
child.baby = true;
// TurtleBreedGoal.breed triggers it without a child.
let turtle = p.species() == Species::Turtle;
if matches!(
(
p.species(),
@@ -1406,7 +1452,7 @@ impl Game<'_> {
) {
child.kind = "minecraft:mule".into();
}
self.trigger_bred(&parent, &partner_view, Some(&child));
self.trigger_bred(&parent, &partner_view, (!turtle).then_some(&child));
}
if let Some(q) = self.mobs.iter_mut().find(|m| m.id == partner) {
q.extra.age = 6000;
@@ -1418,6 +1464,19 @@ impl Game<'_> {
self.lay_sniffer_egg(&p);
return;
}
// TurtleBreedGoal.breed: the goal gave the mother her egg; only the
// experience is left, and only with mob loot on.
if p.species() == Species::Turtle {
// One `new ExperienceOrb` of 1 to 7 from the mother's random (not
// split up as `ExperienceOrb.award` does).
if self.ui.rules.bool("mob_drops")
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == parent)
{
let xp = 1 + m.random.next_int_bound(7).unwrap_or(0) as u32;
self.add_orb([p.position.x, p.position.y, p.position.z], xp);
}
return;
}
let coin = self.world.random.next_int_bound(2).unwrap_or(0) == 0;
let coin2 = self.world.random.next_int_bound(2).unwrap_or(0) == 0;
// A horse and a donkey have a mule.
@@ -2695,6 +2754,7 @@ impl Game<'_> {
let mut handled = true;
let mut drops: Vec<(String, u32)> = Vec::new();
let is_food = m.kind.food.contains(&item);
let baby_turtle = species == Species::Turtle && m.is_baby();
match species {
Species::Cow | Species::Mooshroom if item == "minecraft:bucket" && !m.is_baby() => {
give = Some("minecraft:milk_bucket");
@@ -2984,6 +3044,14 @@ impl Game<'_> {
if !handled {
return Ok(false);
}
// Turtle.ageBoundaryReached: food that finishes a baby's growth.
if baby_turtle && !self.mobs[index].is_baby() {
self.handle_mob_events(vec![MobEvent::GiftLoot {
mob: self.mobs[index].id,
table: "minecraft:gameplay/turtle_grow",
at: feet,
}])?;
}
self.swing_arm();
if let Some(s) = sound {
let pitch =
@@ -3456,6 +3524,7 @@ pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool)
K::InFire => "minecraft:in_fire",
K::Lava => "minecraft:lava",
K::Drown => "minecraft:drown",
K::DryOut => "minecraft:dry_out",
K::Magic => "minecraft:magic",
K::Sting => "minecraft:sting",
K::Cactus => "minecraft:cactus",
@@ -3,10 +3,14 @@
//! unbreaking (`minecraft:item_damage`), sharpness/smite/bane and power
//! (`minecraft:damage`), knockback, fire aspect, infinity (`minecraft:ammo_use`),
//! thorns (`minecraft:post_attack`), mending (`minecraft:repair_with_xp`) and
//! the armor attribute effects (respiration, depth strider, ...).
//! the armor attribute effects (respiration, depth strider, ...) and Soul
//! Speed's `location_changed` and `tick` effects.
use super::Game;
use horizon_client::{enchant::EffectContext, items::ItemStack};
use horizon_core::random::RandomSource;
use horizon_client::{
enchant::{EffectContext, Enchantments, level_value},
items::ItemStack,
};
use horizon_core::{position::BlockPos, random::RandomSource};
/// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`).
#[derive(Clone, Copy)]
@@ -458,6 +462,134 @@ impl Game<'_> {
}
ignite
}
/// Soul Speed (`data/minecraft/enchantment/soul_speed.json`), the parts of
/// `Enchantment.runLocationChangedEffects` and `tick` that file uses. The
/// `location_changed` effects run when the player enters a new block, lands,
/// or its boots change:
/// - the speed and movement efficiency modifiers turn on over a soul speed
/// block (not flying, not riding) and stay on while airborne, then off
/// (`enchantment_active_check`);
/// - the boots lose 1 durability with a 4% chance when on such a block.
///
/// Every fifth tick the player walking on one also gets a soul particle
/// (returned as its position and velocity, for the caller to show or send
/// to the players around) and sometimes a sound. Runs for the window's own
/// player and for each guest on the server (`guest_server_tick`); a remote
/// client leaves it to its server.
pub(super) fn tick_soul_speed(&mut self) -> Option<([f64; 3], [f64; 3])> {
const ID: &str = "minecraft:soul_speed";
let player = self.player.as_mut()?;
if player.client_side {
return None;
}
let level = self.armor[3]
.as_ref()
.map_or(0, |s| s.enchantment_level(ID));
let position = player.position;
let (on_ground, flying) = (player.ground.on_ground, player.flying);
let moved = position.subtract(player.old_position);
let (tick, width) = (player.health.tick_count, player.dimensions.width);
let fx = &mut player.location_effects;
let on_soul = fx.on_soul_speed_block;
let block = BlockPos::containing(position);
let changed_block = fx.block.replace(block) != Some(block);
let landed = std::mem::take(&mut fx.landed);
// Changed boots: `stopLocationBasedEffects`, then the effects run again.
let equipped = std::mem::replace(&mut fx.boots_level, level) != level;
let was_active = fx.applied_level;
let mut active = was_active > 0 && !equipped;
let mut wear = false;
if level > 0 && (changed_block || landed || equipped) {
let riding = self.riding.is_some();
let wanted = !riding && !flying && (on_soul || (active && !on_ground));
active = wanted;
// `random_chance` is the first term of the wear's `all_of`: it
// draws from the level random before the block is looked at.
let roll = self.world.random.next_float() < 0.04;
wear = roll && on_ground && on_soul;
}
fx.applied_level = if active { level } else { 0 };
// `Entity.getKnownMovement` horizontal speed of at least 1.0E-5.
let walking = moved.x * moved.x + moved.z * moved.z >= 1.0e-10;
let tick_effects = level > 0 && !flying && on_ground && walking && on_soul && tick % 5 == 0;
// The attribute effects were applied to the player before: swap them.
if was_active > 0 && (!active || equipped) {
for (attribute, id, _, op) in
soul_speed_modifiers(&self.res.stations().enchantments, was_active)
{
let _ = player.set_modifier(&attribute, &id, 0.0, &op, false);
}
}
if active && (was_active == 0 || equipped) {
for (attribute, id, amount, op) in
soul_speed_modifiers(&self.res.stations().enchantments, level)
{
let _ = player.set_modifier(&attribute, &id, amount, &op, true);
}
}
if wear && !self.creative {
self.wear_boots(1);
}
if level == 0 {
return None;
}
let r = &mut self.world.random;
// `spawn_particles`: in the bounding box, 0.1 above the feet, thrown
// back against the movement (-0.2) and up (0.1).
let particle = tick_effects.then(|| {
let x = position.x + (r.next_double() - 0.5) * f64::from(width);
let z = position.z + (r.next_double() - 0.5) * f64::from(width);
(
[x, position.y + 0.1, z],
[moved.x * -0.2, 0.1, moved.z * -0.2],
)
});
// `play_sound`: its `random_chance` (35%) comes first in its `all_of`,
// so the level random is drawn every tick the boots are worn; volume
// 0.6, pitch 0.6 to 1.0.
if r.next_float() < 0.35 && tick_effects {
let pitch = r.next_float() * 0.4 + 0.6;
self.audio.play(
"minecraft:particle.soul_escape",
Some([position.x, position.y, position.z]),
0.6,
pitch,
);
}
particle
}
/// `ItemStack.hurtAndBreak` on the worn boots (`change_item_damage`):
/// Unbreaking applies, and they break when worn out.
fn wear_boots(&mut self, amount: u32) {
let Some(stack) = self.armor[3].clone() else {
return;
};
let loss = self.durability_loss(&stack, amount);
let max = self
.res
.items()
.get(&stack.item)
.map_or(0, |info| info.max_damage);
if max == 0 {
return;
}
let Some(boots) = self.armor[3].as_mut() else {
return;
};
boots.damage += loss;
if boots.damage >= max {
self.armor[3] = None;
if let Some(eye) = self.eye_position() {
self.audio.play(
"minecraft:entity.item.break",
Some(eye),
0.8,
0.8 + self.world.random.next_float() * 0.4,
);
}
self.apply_equipment();
}
}
/// Enchantment attribute modifiers of worn armor (respiration, depth strider...).
/// Each piece's modifier id ends with its slot (`EnchantmentAttributeEffect.idForSlot`),
/// so the same enchantment on two pieces stacks instead of replacing itself.
@@ -481,3 +613,28 @@ impl Game<'_> {
self.potions.enchant_modifiers = wanted;
}
}
/// Soul Speed's `attribute` effects at `level` (attribute, id, amount, operation),
/// the id taking the boots slot like `EnchantmentAttributeEffect.idForSlot`.
fn soul_speed_modifiers(
enchantments: &Enchantments,
level: u32,
) -> Vec<(String, String, f64, String)> {
let Some(e) = enchantments.get("minecraft:soul_speed") else {
return Vec::new();
};
e.effects["minecraft:location_changed"][0]["effect"]["effects"]
.as_array()
.into_iter()
.flatten()
.filter(|a| a["type"] == "minecraft:attribute")
.map(|a| {
(
a["attribute"].as_str().unwrap_or("").to_owned(),
format!("{}/feet", a["id"].as_str().unwrap_or("")),
f64::from(level_value(&a["amount"], level)),
a["operation"].as_str().unwrap_or("add_value").to_owned(),
)
})
.collect()
}
+53 -22
View File
@@ -126,28 +126,7 @@ impl Game<'_> {
pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result<Option<Vec3>> {
let mut finder = match self.player_spawn {
Some(finder) => finder,
None if self.level.game_mode == 2 => {
// Adventure mode: the suggestion itself.
let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0);
finder.next_candidate();
finder
}
None => {
let mut radius = self.ui.rules.int("respawn_radius").max(0);
let to_border = self
.border
.distance(f64::from(suggestion[0]), f64::from(suggestion[2]))
.floor() as i32;
if to_border < radius {
radius = to_border;
}
if to_border <= 1 {
radius = 1;
}
PlayerSpawnFinder::new(suggestion, radius, |n| {
entity_random().next_int_bound(n).unwrap_or(0)
})
}
None => self.spawn_finder(suggestion),
};
let found = loop {
let Some(candidate) = finder.next_candidate() else {
@@ -176,6 +155,58 @@ impl Game<'_> {
self.player_spawn = found.is_none().then_some(finder);
Ok(found)
}
/// A new PlayerSpawnFinder around `suggestion`: the respawn radius, cut
/// by the world border; the suggestion itself in adventure mode.
fn spawn_finder(&self, suggestion: [i32; 3]) -> PlayerSpawnFinder {
if self.level.game_mode == 2 {
let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0);
finder.next_candidate();
return finder;
}
let mut radius = self.ui.rules.int("respawn_radius").max(0);
let to_border = self
.border
.distance(f64::from(suggestion[0]), f64::from(suggestion[2]))
.floor() as i32;
if to_border < radius {
radius = to_border;
}
if to_border <= 1 {
radius = 1;
}
PlayerSpawnFinder::new(suggestion, radius, |n| {
entity_random().next_int_bound(n).unwrap_or(0)
})
}
/// ServerPlayer.adjustSpawnLocation for a server's new player: where
/// PlayerSpawnFinder.findSpawn puts their feet around the world spawn
/// (`spawn`, the feet there), so that players new to a world don't all
/// stand in one spot. Vanilla waits for each candidate's chunk; a server
/// tick can't, so a candidate in a chunk not loaded yet is passed over,
/// and `spawn` stays when the search never reaches a loaded column.
pub(super) fn server_player_spawn(&self, spawn: [f64; 3]) -> [f64; 3] {
let suggestion = spawn.map(|v| v.floor() as i32);
let mut finder = self.spawn_finder(suggestion);
while let Some(candidate) = finder.next_candidate() {
let (x, z) = match candidate {
SpawnCandidate::Column(x, z) => (x, z),
SpawnCandidate::Suggestion => (suggestion[0], suggestion[2]),
};
if !self.streaming.is_lit(x >> 4, z >> 4) {
continue;
}
let feet = match candidate {
SpawnCandidate::Column(x, z) => level_respawn_pos(&self.spawn_columns(), x, z)
.filter(|&pos| self.player_fits(pos))
.map(bottom_center),
SpawnCandidate::Suggestion => Some(self.fixup_spawn_height(suggestion)),
};
if let Some(feet) = feet {
return [feet.x, feet.y, feet.z];
}
}
spawn
}
/// PlayerSpawnFinder.noCollisionNoLiquid: a player's box standing at the
/// block's bottom centre touches no block or liquid.
fn player_fits(&self, pos: [i32; 3]) -> bool {
+27 -8
View File
@@ -24,11 +24,24 @@ use horizon_protocol::{
};
use std::{
collections::HashMap,
sync::{Arc, OnceLock},
sync::{Arc, Mutex},
};
/// The registries and tags are the same for every world: load them once.
static SYNC: OnceLock<std::result::Result<Arc<SyncData>, String>> = OnceLock::new();
static SYNC: Mutex<Option<std::result::Result<Arc<SyncData>, String>>> = Mutex::new(None);
/// The registries and tags a server sends, loaded from `root` the first time.
pub(super) fn sync_data(root: &std::path::Path) -> std::result::Result<Arc<SyncData>, String> {
let mut sync = SYNC.lock().unwrap_or_else(|e| e.into_inner());
sync.get_or_insert_with(|| SyncData::load(root).map(Arc::new))
.clone()
}
/// Let go of what `sync_data` loaded: for a preload no world used
/// (game/world_loading.rs).
pub(super) fn forget_sync_data() {
*SYNC.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
/// The settings of the open world (WorldOptionsScreen's multiplayer section).
#[derive(Clone, Copy, Debug)]
@@ -562,10 +575,7 @@ impl Game<'_> {
config: HubConfig,
host: Option<u128>,
) -> Result<()> {
let root = self.options.resources.clone();
let sync = SYNC
.get_or_init(|| SyncData::load(&root).map(Arc::new))
.clone()?;
let sync = sync_data(&self.options.resources)?;
let biome_names: Vec<String> = self
.res
.biomes()
@@ -1128,8 +1138,17 @@ impl Game<'_> {
g.game_mode = default_mode;
}
if !known {
g.position = spawn;
g.previous_position = spawn;
// ServerPlayer.adjustSpawnLocation: a player new to the world
// stands where PlayerSpawnFinder puts them, not all on one spot
// (it reads the loaded level, which holds the spawn when it is
// the overworld).
let feet = if self.dim == super::Dim::Overworld {
self.server_player_spawn(spawn)
} else {
spawn
};
g.position = feet;
g.previous_position = feet;
g.health = 20.0;
g.food = 20;
g.dimension = super::Dim::Overworld.id().to_owned();
@@ -2183,6 +2183,7 @@ impl Game<'_> {
let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height());
let at = g.position;
let sneaking = g.sneaking;
let mut soul = None;
let events = self.as_guest(host, conn, |game| {
let (rules, motion) = (game.world.health_rules, game.motion);
let health = &motion.health;
@@ -2252,6 +2253,7 @@ impl Game<'_> {
w.player.shift_key_down = sneaking;
w.player.freeze_immune = freeze_immune;
let _ = w.server_block_damage(start);
let _ = w.update_soul_speed_block();
let _ = w.tick_environment_damage();
let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall);
@@ -2279,6 +2281,9 @@ impl Game<'_> {
// LivingEntity.baseTick: outside the world border, then tickEffects.
game.border_damage();
game.tick_mob_effects();
// Soul Speed's effects (LivingEntity.baseTick's location_changed
// and tick effects); its particle goes to the players around.
soul = game.tick_soul_speed();
let Some(player) = game.player.as_mut() else {
return (Vec::new(), None);
};
@@ -2307,6 +2312,9 @@ impl Game<'_> {
let Some((events, marked)) = events else {
return;
};
if let Some((at, velocity)) = soul {
super::lan_particles::send_soul_particle(host, at, velocity);
}
self.as_guest(host, conn, |game| game.tick_player_sculk_events());
for event in events {
match event {
@@ -24,6 +24,35 @@ fn rgb(c: [f32; 4]) -> [f32; 3] {
[c[0], c[1], c[2]]
}
/// `ServerLevel.sendParticles` of one soul particle moving by `velocity`
/// (Soul Speed's `spawn_particles`): sent to the players within 32 blocks.
pub(super) fn send_soul_particle(host: &super::lan::LanHost, at: [f64; 3], velocity: [f64; 3]) {
let Some(id) = host
.hub
.registry_id("minecraft:particle_type", "minecraft:soul")
else {
return;
};
let packet = C::LevelParticles(play::LevelParticles {
particle: Particle { id, data: None },
override_limiter: false,
always_show: false,
pos: at,
dist: velocity.map(|v| v as f32),
max_speed: [1.0; 3],
count: 0,
randomization: 0,
});
for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) {
let distance: f64 = (0..3)
.map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2))
.sum();
if distance < 32.0 * 32.0 {
g.send(&packet);
}
}
}
impl Game<'_> {
/// `SonicBoom.tick` uses `ServerLevel.sendParticles` for each ray point.
/// Keep the local event's rendering; connected players receive one at rest.
+15
View File
@@ -109,6 +109,19 @@ pub(super) struct Levels {
parked: HashMap<Dim, Parked>,
}
impl Levels {
/// The chunks of each level not in place (capability `world` lends
/// them to server mods for a call).
#[cfg_attr(not(feature = "mods"), allow(dead_code))]
pub(super) fn parked_chunks(
&mut self,
) -> impl Iterator<Item = (Dim, &mut horizon_client::chunk_map::ChunkMap)> {
self.parked
.iter_mut()
.map(|(d, p)| (*d, &mut p.world.chunks))
}
}
impl Game<'_> {
/// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`).
fn open_level(&self, dim: Dim) -> Result<Parked> {
@@ -314,6 +327,8 @@ impl Game<'_> {
};
self.update_dedicated_streaming();
self.update_world();
// What server mods set in this level since its last tick.
self.apply_mod_block_writes();
result = if paused {
self.tick_lan(true);
Ok(())
@@ -0,0 +1,485 @@
//! Capability `ui`'s panel beside container screens (WIT `interface
//! browser`, docs/mods.md): the items a recipe viewer mod lists, drawn as
//! the game's own item slots in pages right of the screen's window, with a
//! search box under them. The mod says what the panel holds; the game pages
//! it and tells the mod what the player clicked, typed, and which of the
//! mod's keys went down over an item. With no mod showing a panel, each
//! hook here returns after one check.
use super::Game;
#[cfg(feature = "mods")]
use {
super::Screen,
horizon_client::{
hud::{HudBatch, rgba},
items::ItemStack,
ui::EditBox,
},
horizon_mods::{BrowserClick, BrowserEvent, BrowserStack},
};
#[cfg(not(feature = "mods"))]
impl Game<'_> {
pub(super) fn draw_mod_browser(&mut self, _batch: &mut horizon_client::hud::HudBatch) {}
pub(super) fn mod_browser_press(&mut self, _right: bool) -> bool {
false
}
pub(super) fn mod_browser_typing(&self) -> bool {
false
}
pub(super) fn mod_browser_key(&mut self, _event: &winit::event::KeyEvent) {}
pub(super) fn mod_browser_text(&mut self, _text: Option<&str>, _backspace: bool) {}
pub(super) fn mod_browser_closed(&mut self) {}
}
/// One slot of the panel, in GUI pixels.
#[cfg(feature = "mods")]
const SLOT: f32 = 18.0;
/// The most columns the panel takes, and the fewest it shows with.
#[cfg(feature = "mods")]
const COLUMNS: (usize, usize) = (12, 2);
/// The gap between the window and the panel, and the screen's edges.
#[cfg(feature = "mods")]
const MARGIN: f32 = 8.0;
/// The panel's state in the game.
#[cfg(feature = "mods")]
#[derive(Default)]
pub(super) struct Browser {
/// The items' owner and version they were made from.
of: Option<(usize, u64)>,
/// The mod's items as stacks; `None` for an item the game doesn't have.
stacks: Vec<Option<ItemStack>>,
page: usize,
search: Option<EditBox>,
/// The search text the mod last heard.
sent: String,
/// `set-recipes`' recipes, shown instead of the items.
pub(super) recipes: Option<super::mod_browser_recipes::Pages>,
}
/// Where the panel's parts are this frame.
#[cfg(feature = "mods")]
pub(super) struct Layout {
/// The panel's whole area, for clicks that hit none of its parts.
pub(super) area: [f32; 4],
/// The grid's top left corner, its columns and rows.
pub(super) grid: (f32, f32),
pub(super) columns: usize,
pub(super) rows: usize,
/// The page arrows' row.
pub(super) arrows_y: f32,
pub(super) search: [f32; 4],
}
#[cfg(feature = "mods")]
impl Layout {
fn per_page(&self) -> usize {
self.columns * self.rows
}
pub(super) fn width(&self) -> f32 {
self.columns as f32 * SLOT
}
fn slot(&self, n: usize) -> (f32, f32) {
(
self.grid.0 + (n % self.columns) as f32 * SLOT,
self.grid.1 + (n / self.columns) as f32 * SLOT,
)
}
/// The page arrows: backward, then forward.
pub(super) fn arrows(&self) -> [(f32, f32); 2] {
[
(self.grid.0, self.arrows_y),
(self.grid.0 + self.width() - 12.0, self.arrows_y),
]
}
}
#[cfg(feature = "mods")]
pub(super) fn inside(p: (f32, f32), [x, y, w, h]: [f32; 4]) -> bool {
p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h
}
#[cfg(feature = "mods")]
impl Game<'_> {
fn browser_batch(&self) -> Option<HudBatch> {
let r = self.renderer.as_ref()?;
Some(HudBatch::new([r.config.width, r.config.height]))
}
/// The mod showing a panel, with its items made into stacks once per
/// `set-items`; none while no mod shows one or no container screen is up.
fn browser_sync(&mut self) -> Option<usize> {
if self.screen != Screen::Inventory || self.title.is_some() {
return None;
}
let Some((owner, version)) = self.mods.mods.browser_items().map(|(o, v, _)| (o, v)) else {
self.mods.browser.of = None;
self.mods.browser.stacks.clear();
return None;
};
if self.mods.browser.of != Some((owner, version)) {
let items = self.res.items();
let stacks = self
.mods
.mods
.browser_items()
.map_or_else(Vec::new, |(_, _, list)| {
list.iter().map(|s| browser_stack(items, s)).collect()
});
self.mods.browser.stacks = stacks;
// The same title again (the mod updating its buttons) keeps the page.
let old = self.mods.browser.recipes.take();
self.mods.browser.recipes = self
.mods
.mods
.browser_recipes(owner)
.map(|shown| super::mod_browser_recipes::Pages::new(items, shown, old));
self.mods.browser.of = Some((owner, version));
}
Some(owner)
}
/// The panel's parts: right of the window, from the top of the screen to
/// the search box at its foot. None when the screen has no room for it.
fn browser_layout(&self, batch: &HudBatch) -> Option<Layout> {
let image = self.container_image(batch);
let left = (image.left + image.width) as f32 + MARGIN;
let right = batch.width - MARGIN;
let columns = (((right - left) / SLOT).floor().max(0.0) as usize).min(COLUMNS.0);
if columns < COLUMNS.1 {
return None;
}
let x = (left + (right - left - columns as f32 * SLOT) / 2.0).floor();
let arrows_y = MARGIN;
let top = arrows_y + 17.0 + 4.0;
let search = [x, batch.height - MARGIN - 16.0, columns as f32 * SLOT, 16.0];
let rows = ((search[1] - 4.0 - top) / SLOT).floor().max(0.0) as usize;
(rows > 0).then_some(Layout {
area: [left, 0.0, right - left, batch.height],
grid: (x, top),
columns,
rows,
arrows_y,
search,
})
}
fn browser_pages(&self, layout: &Layout) -> usize {
self.mods
.browser
.stacks
.len()
.div_ceil(layout.per_page())
.max(1)
}
/// The stack under the pointer on the panel, an item's or a recipe's,
/// as the mod sent it and as a stack.
fn browser_pointed_stack(&self, layout: &Layout) -> Option<(BrowserStack, ItemStack)> {
if self.mods.browser.recipes.is_some() {
if let Some((_, sent, stack)) = self.recipe_tab_hovered(layout) {
return Some((sent, stack));
}
let (_, _, sent, stack) = self.recipe_slot_hovered(layout)?;
return Some((sent, stack));
}
let (index, stack) = self.browser_hovered(layout)?;
let (_, _, items) = self.mods.mods.browser_items()?;
Some((items.get(index)?.clone(), stack))
}
/// The panel's item under the pointer: its index and stack.
fn browser_hovered(&self, layout: &Layout) -> Option<(usize, ItemStack)> {
if self.mods.browser.recipes.is_some() {
return None;
}
let first = self.mods.browser.page * layout.per_page();
(0..layout.per_page()).find_map(|n| {
let (x, y) = layout.slot(n);
if !inside(self.cursor, [x, y, SLOT, SLOT]) {
return None;
}
let stack = self.mods.browser.stacks.get(first + n)?.clone()?;
Some((first + n, stack))
})
}
fn browser_search(&mut self, layout: &Layout) -> &mut EditBox {
let search = self.mods.browser.search.get_or_insert_with(|| {
let mut edit = EditBox::new(0.0, 0.0, 0.0, 0.0);
edit.max_length = 50;
edit.focused = false;
edit
});
[search.x, search.y, search.width, search.height] = layout.search;
search
}
/// The items' page arrows and grid.
fn draw_browser_items(&mut self, batch: &mut HudBatch, layout: &Layout) {
let pages = self.browser_pages(layout);
self.mods.browser.page = self.mods.browser.page.min(pages - 1);
let page = self.mods.browser.page;
let cursor = self.cursor;
if pages > 1 {
let labels = [
self.translate("gui.recipebook.previous_page", "Previous Page"),
self.translate("gui.recipebook.next_page", "Next Page"),
];
let shown = [page > 0, page + 1 < pages];
let atlas = &self.gui.atlas;
for (((x, y), name), (label, shown)) in layout
.arrows()
.into_iter()
.zip(["page_backward", "page_forward"])
.zip(labels.iter().zip(shown))
{
if !shown {
continue;
}
let hover = inside(cursor, [x, y, 12.0, 17.0]);
let suffix = if hover { "_highlighted" } else { "" };
batch.sprite(
atlas,
&format!("gui/sprites/recipe_book/{name}{suffix}"),
x,
y,
);
horizon_client::widgets::record(label, [x, y, 12.0, 17.0], true);
}
let text = format!("{}/{pages}", page + 1);
let w = HudBatch::text_width(atlas, &text);
let x = (layout.grid.0 + (layout.width() - w) / 2.0).floor();
batch.text(atlas, &text, x, layout.arrows_y + 5.0, u32::MAX, true);
}
let first = page * layout.per_page();
for n in 0..layout.per_page() {
let Some(stack) = self.mods.browser.stacks.get(first + n) else {
break;
};
let Some(stack) = stack.clone() else {
continue;
};
let (x, y) = layout.slot(n);
self.draw_item(batch, &stack, x + 1.0, y + 1.0);
let rect = [x + 1.0, y + 1.0, 16.0, 16.0];
if inside(cursor, [x, y, SLOT, SLOT]) {
batch.fill(
&self.gui.atlas,
x + 1.0,
y + 1.0,
16.0,
16.0,
rgba(255, 255, 255, 128),
);
}
let name = self.pack.names.display_item(&stack.item);
horizon_client::widgets::record_as(
&name,
rect,
true,
horizon_client::widgets::Kind::Button,
);
}
}
/// Draws the panel over the open container screen, then the carried
/// stack or the tooltip again so they stay on top of it.
pub(super) fn draw_mod_browser(&mut self, batch: &mut HudBatch) {
if self.browser_sync().is_none() {
return;
}
let Some(layout) = self.browser_layout(batch) else {
return;
};
let cursor = self.cursor;
if self.mods.browser.recipes.is_some() {
self.draw_browser_recipes(batch, &layout);
} else {
self.draw_browser_items(batch, &layout);
}
let hint = self.translate("gui.recipebook.search_hint", "Search...");
let search = self.browser_search(&layout);
// The hint shows in an empty box without focus, as the recipe book's.
search.suggestion = (search.value.is_empty() && !search.focused).then_some(hint);
let mut search = search.clone();
search.draw(batch, &self.gui.atlas, None);
self.mods.browser.search = Some(search);
if self.carried.is_some() {
self.draw_carried(batch);
} else if let Some(stack) = self.browser_pointed_stack(&layout) {
let lines = self.stack_tooltip(&stack.1);
self.draw_tooltip_lines(batch, &lines, cursor.0, cursor.1);
} else {
self.draw_slot_tooltip(batch);
}
}
/// A mouse press on a container screen: true when the panel took it
/// (its search box, page arrows, items or empty space; a click there
/// never throws the carried stack).
pub(super) fn mod_browser_press(&mut self, right: bool) -> bool {
let Some(owner) = self.browser_sync() else {
return false;
};
let Some(batch) = self.browser_batch() else {
return false;
};
let Some(layout) = self.browser_layout(&batch) else {
return false;
};
let cursor = self.cursor;
let shift = self.has_shift_down();
let atlas = &self.gui.atlas;
let search = self.mods.browser.search.get_or_insert_with(|| {
let mut edit = EditBox::new(0.0, 0.0, 0.0, 0.0);
edit.max_length = 50;
edit
});
[search.x, search.y, search.width, search.height] = layout.search;
if inside(cursor, layout.search) {
search.focused = true;
search.click(atlas, cursor.0, shift, false);
search.reset_blink();
return true;
}
search.focused = false;
if self.mods.browser.recipes.is_some() {
return self.browser_recipes_press(&layout, owner, right)
|| inside(cursor, layout.area);
}
let pages = self.browser_pages(&layout);
let page = self.mods.browser.page;
let [back, forward] = layout.arrows();
let step = if pages > 1 && page > 0 && inside(cursor, [back.0, back.1, 12.0, 17.0]) {
Some(page - 1)
} else if pages > 1
&& page + 1 < pages
&& inside(cursor, [forward.0, forward.1, 12.0, 17.0])
{
Some(page + 1)
} else {
None
};
if let Some(to) = step {
self.mods.browser.page = to;
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
return true;
}
if let Some((index, _)) = self.browser_hovered(&layout) {
let event = BrowserEvent::Clicked(BrowserClick {
index: index as u32,
right,
});
self.mods.mods.browser_event(owner, event);
return true;
}
inside(cursor, layout.area)
}
/// Whether keys go to the panel's search box.
pub(super) fn mod_browser_typing(&self) -> bool {
self.screen == Screen::Inventory
&& self.mods.browser.of.is_some()
&& self.mods.browser.search.as_ref().is_some_and(|s| s.focused)
}
/// A key press while the search box has focus.
pub(super) fn mod_browser_key(&mut self, event: &winit::event::KeyEvent) {
use winit::keyboard::PhysicalKey;
let shortcut = self.edit_shortcut(event);
let ctrl = self.has_control_down();
let shift = self.has_shift_down();
let Some(search) = self.mods.browser.search.as_mut() else {
return;
};
if let Some(shortcut) = shortcut {
search.shortcut(shortcut, &mut self.clipboard);
} else {
let handled = match event.physical_key {
PhysicalKey::Code(code) => search.key(code, ctrl, shift),
_ => false,
};
if !handled
&& !ctrl
&& let Some(text) = &event.text
{
let text: String = text.chars().filter(|c| !c.is_control()).collect();
search.insert_text(&text);
}
}
search.reset_blink();
self.browser_searched();
}
/// Text typed (or one backspace) into the search box (`horizon-ctl type`).
pub(super) fn mod_browser_text(&mut self, text: Option<&str>, backspace: bool) {
let Some(search) = self.mods.browser.search.as_mut() else {
return;
};
if backspace {
search.delete_chars(-1);
} else if let Some(text) = text {
search.insert_text(text);
}
self.browser_searched();
}
/// The mod hears the search text when it changed.
fn browser_searched(&mut self) {
let (Some((owner, _)), Some(search)) = (self.mods.browser.of, &self.mods.browser.search)
else {
return;
};
if search.value != self.mods.browser.sent {
let value = search.value.clone();
self.mods.browser.sent.clone_from(&value);
self.mods.browser.page = 0;
self.mods
.mods
.browser_event(owner, BrowserEvent::Search(value));
}
}
/// The container screen closed: the search box lets go of the keys.
pub(super) fn mod_browser_closed(&mut self) {
if let Some(search) = self.mods.browser.search.as_mut() {
search.focused = false;
}
}
/// The item under the pointer on a container screen, for the mods' keys
/// (`browser`'s `key` event): the panel's, else a slot's.
pub(super) fn mod_browser_pointed(&mut self) -> Option<BrowserStack> {
let batch = self.browser_batch()?;
let stack = match self
.browser_sync()
.and_then(|_| self.browser_layout(&batch))
{
// The panel's stacks as the mod sent them.
Some(layout) if inside(self.cursor, layout.area) => {
return Some(self.browser_pointed_stack(&layout)?.0);
}
_ => {
let slot = self.slot_at(&batch, self.cursor.0, self.cursor.1)?;
self.slot_view(slot)?
}
};
Some(BrowserStack {
item: stack.item.to_string(),
count: stack.count,
components: super::mod_recipes::components(&stack),
})
}
}
/// A mod's item as a stack: an item the game has, its components read as
/// `/give` reads them (ones it can't read are left out).
#[cfg(feature = "mods")]
pub(super) fn browser_stack(
items: &horizon_client::items::Items,
s: &BrowserStack,
) -> Option<ItemStack> {
items.get(&s.item)?;
let (damage, extra) = if s.components.is_empty() {
(0, None)
} else {
horizon_client::item_data::command_components(&s.components).map_or((0, None), |tag| {
horizon_client::item_data::decode_components(Some(&tag))
})
};
Some(ItemStack {
item: s.item.as_str().into(),
count: s.count.clamp(1, 99),
damage,
extra,
})
}
@@ -0,0 +1,523 @@
//! `browser.set-recipes` (docs/mods.md): a mod's recipes shown in its item
//! panel's place, laid out by the game with its own slots, arrows and
//! buttons, paged to the panel's height, under a title and a back button.
//! The mod hears clicks on their slots, their action buttons, the back
//! button and page turns.
use super::{
Game,
mod_browser::{Layout, browser_stack, inside},
};
use horizon_client::{
hud::{HudBatch, rgba},
items::ItemStack,
};
use horizon_mods::{BrowserEvent, BrowserLayout, BrowserSlotClick, BrowserStack, RecipePage};
use std::time::Instant;
const SLOT: f32 = 18.0;
/// The title row's height, and the gap under each recipe.
const TITLE: f32 = 18.0;
/// A tab's step: an 18 px slot and a gap.
const TAB: f32 = 20.0;
const GAP: f32 = 6.0;
/// One recipe as the game draws it.
pub(super) struct Shown {
layout: BrowserLayout,
width: usize,
height: usize,
/// Each slot's stacks (the result last), as the mod sent them and as
/// stacks; a stack the game doesn't have is left out of the cycle.
slots: Vec<Vec<(BrowserStack, ItemStack)>>,
note: String,
action: Option<bool>,
}
/// The recipes a panel shows, and its page.
pub(super) struct Pages {
title: String,
/// The tabs' icons and the selected one.
tabs: Vec<(BrowserStack, Option<ItemStack>)>,
tab: usize,
recipes: Vec<Shown>,
page: usize,
since: Instant,
}
impl Pages {
pub(super) fn new(
items: &horizon_client::items::Items,
shown: &RecipePage,
old: Option<Pages>,
) -> Self {
let (title, list, tab) = (&shown.title, &shown.recipes, shown.tab as usize);
let kept = old.filter(|o| o.title == *title && o.tab == tab);
let cycle = |stacks: &[BrowserStack]| -> Vec<(BrowserStack, ItemStack)> {
stacks
.iter()
.filter_map(|s| Some((s.clone(), browser_stack(items, s)?)))
.collect()
};
let recipes = list
.iter()
.map(|r| {
let mut slots: Vec<_> = r.slots.iter().map(|s| cycle(s)).collect();
slots.push(cycle(&r.results));
Shown {
layout: r.layout,
width: r.width as usize,
height: r.height as usize,
slots,
note: r.note.clone(),
action: r.action,
}
})
.collect();
Self {
title: title.clone(),
tabs: shown
.tabs
.iter()
.map(|t| (t.clone(), browser_stack(items, t)))
.collect(),
tab,
recipes,
page: kept.as_ref().map_or(0, |o| o.page),
since: kept.map_or_else(Instant::now, |o| o.since),
}
}
}
impl Shown {
/// The inputs' block: its size and each input slot's place in it.
fn inputs(&self) -> ((f32, f32), Vec<(f32, f32)>) {
let row = |n: usize| (0..n).map(|i| (i as f32 * SLOT, 0.0)).collect();
match self.layout {
BrowserLayout::Grid => {
let (w, h) = (self.width.max(1), self.height.max(1));
let at = (0..w * h)
.map(|i| ((i % w) as f32 * SLOT, (i / w) as f32 * SLOT))
.collect();
((w as f32 * SLOT, h as f32 * SLOT), at)
}
// The input over the flame.
BrowserLayout::Cooking => ((SLOT, 2.0 * SLOT), vec![(0.0, 0.0)]),
BrowserLayout::Single => ((SLOT, SLOT), row(1)),
BrowserLayout::Smithing => ((3.0 * SLOT, SLOT), row(3)),
BrowserLayout::Brewing => ((2.0 * SLOT, SLOT), row(2)),
}
}
/// The height of its slots, arrow and button, `room` wide.
fn block(&self, room: f32) -> f32 {
let h = self.inputs().0.1;
let (_, _, action) = self.places(room);
match self.action {
Some(_) => h.max(action.1 + 12.0),
None => h,
}
}
fn height(&self, room: f32) -> f32 {
let note = if self.note.is_empty() { 0.0 } else { 11.0 };
self.block(room) + note + GAP
}
/// Every slot's place from the recipe's corner (the result last), the
/// arrow's and the action button's: beside the result, or under it
/// when the panel is `room` wide and that doesn't fit.
fn places(&self, room: f32) -> (Vec<(f32, f32)>, (f32, f32), (f32, f32)) {
let ((w, h), mut at) = self.inputs();
// The mod's slots beyond the layout's are not shown.
at.truncate(self.slots.len() - 1);
let arrow = (w + 4.0, ((h - 16.0) / 2.0).floor());
let result = (w + 32.0, ((h - SLOT) / 2.0).floor());
let action = if result.0 + SLOT + 16.0 <= room {
(result.0 + SLOT + 4.0, ((h - 12.0) / 2.0).floor())
} else {
(result.0 + 3.0, result.1 + SLOT + 2.0)
};
while at.len() < self.slots.len() - 1 {
at.push((f32::NAN, f32::NAN));
}
at.push(result);
(at, arrow, action)
}
}
/// The tabs' places, in rows under the title row.
fn tab_places(pages: &Pages, layout: &Layout) -> Vec<(f32, f32)> {
let per_row = ((layout.width() / TAB).floor() as usize).max(1);
(0..pages.tabs.len())
.map(|i| {
(
layout.grid.0 + (i % per_row) as f32 * TAB,
layout.grid.1 + TITLE + 3.0 + (i / per_row) as f32 * TAB,
)
})
.collect()
}
/// Where the recipes start: under the title row and the tabs.
fn recipes_top(pages: &Pages, layout: &Layout) -> f32 {
let tabs = tab_places(pages, layout);
tabs.last()
.map_or(layout.grid.1 + TITLE, |&(_, y)| y + TAB + 3.0)
}
impl Game<'_> {
/// The first recipe of each page, filling the panel from the tabs to
/// the search box.
fn recipe_pages(pages: &Pages, layout: &Layout) -> Vec<usize> {
let room = layout.search[1] - 4.0 - recipes_top(pages, layout);
let mut starts = vec![0];
let mut used = 0.0;
for (i, r) in pages.recipes.iter().enumerate() {
let h = r.height(layout.width());
if used > 0.0 && used + h > room {
starts.push(i);
used = 0.0;
}
used += h;
}
starts
}
/// The recipes on the open page, each with its corner.
fn recipes_shown(&self, layout: &Layout) -> Vec<(usize, (f32, f32))> {
let Some(pages) = &self.mods.browser.recipes else {
return Vec::new();
};
let starts = Self::recipe_pages(pages, layout);
let page = pages.page.min(starts.len() - 1);
let end = starts.get(page + 1).copied().unwrap_or(pages.recipes.len());
let mut y = recipes_top(pages, layout);
(starts[page]..end)
.map(|i| {
let at = (layout.grid.0, y);
y += pages.recipes[i].height(layout.width());
(i, at)
})
.collect()
}
fn back_button(&self, layout: &Layout) -> ([f32; 4], String) {
let label = self.translate("gui.back", "Back");
let w = HudBatch::text_width(&self.gui.atlas, &label) + 8.0;
([layout.grid.0, layout.grid.1, w, 14.0], label)
}
/// What a slot of a shown recipe holds now: its stacks cycle once a second.
fn recipe_slot_now(&self, recipe: usize, slot: usize) -> Option<&(BrowserStack, ItemStack)> {
let pages = self.mods.browser.recipes.as_ref()?;
let stacks = pages.recipes.get(recipe)?.slots.get(slot)?;
let n = pages.since.elapsed().as_secs() as usize;
stacks.get(n % stacks.len().max(1))
}
/// The tab under the pointer: its index and icon.
pub(super) fn recipe_tab_hovered(
&self,
layout: &Layout,
) -> Option<(usize, BrowserStack, ItemStack)> {
let pages = self.mods.browser.recipes.as_ref()?;
let places = tab_places(pages, layout);
places.iter().enumerate().find_map(|(i, &(x, y))| {
if !inside(self.cursor, [x, y, SLOT, SLOT]) {
return None;
}
let (sent, stack) = pages.tabs.get(i)?;
Some((i, sent.clone(), stack.clone()?))
})
}
/// The recipe slot under the pointer: recipe, slot, and its stack now.
pub(super) fn recipe_slot_hovered(
&self,
layout: &Layout,
) -> Option<(usize, usize, BrowserStack, ItemStack)> {
let pages = self.mods.browser.recipes.as_ref()?;
self.recipes_shown(layout)
.into_iter()
.find_map(|(i, (x, y))| {
let (at, _, _) = pages.recipes[i].places(layout.width());
at.iter().enumerate().find_map(|(k, &(sx, sy))| {
if !inside(self.cursor, [x + sx, y + sy, SLOT, SLOT]) {
return None;
}
let (mod_stack, stack) = self.recipe_slot_now(i, k)?.clone();
Some((i, k, mod_stack, stack))
})
})
}
/// Draws the title row, the page's recipes and the page arrows.
pub(super) fn draw_browser_recipes(&mut self, batch: &mut HudBatch, layout: &Layout) {
let Some(pages) = &self.mods.browser.recipes else {
return;
};
let cursor = self.cursor;
let starts = Self::recipe_pages(pages, layout);
let page = pages.page.min(starts.len() - 1);
let (title, pages_n) = (pages.title.clone(), starts.len());
let (back, label) = self.back_button(layout);
let atlas = &self.gui.atlas;
let hover = inside(cursor, back);
let sprite = if hover {
"gui/sprites/widget/button_highlighted"
} else {
"gui/sprites/widget/button"
};
horizon_client::ui::nine_slice(
batch,
atlas,
sprite,
back[0],
back[1],
back[2],
back[3],
u32::MAX,
);
batch.text(atlas, &label, back[0] + 4.0, back[1] + 3.0, u32::MAX, true);
horizon_client::widgets::record(&label, back, true);
let room = layout.width() - back[2] - 4.0;
// Cut to the panel with vanilla's ellipsis (CommonComponents.ELLIPSIS).
let shown = if atlas.font.fit(&title, room) >= title.chars().count() {
title
} else {
let fit = atlas.font.fit(&title, room - atlas.font.width("..."));
let kept: String = title.chars().take(fit).collect();
format!("{}...", kept.trim_end())
};
batch.text(
atlas,
&shown,
back[0] + back[2] + 4.0,
back[1] + 3.0,
u32::MAX,
true,
);
self.draw_recipe_tabs(batch, layout);
if pages_n > 1 {
let labels = [
self.translate("gui.recipebook.previous_page", "Previous Page"),
self.translate("gui.recipebook.next_page", "Next Page"),
];
let visible = [page > 0, page + 1 < pages_n];
let atlas = &self.gui.atlas;
for (((x, y), name), (label, visible)) in layout
.arrows()
.into_iter()
.zip(["page_backward", "page_forward"])
.zip(labels.iter().zip(visible))
{
if !visible {
continue;
}
let suffix = if inside(cursor, [x, y, 12.0, 17.0]) {
"_highlighted"
} else {
""
};
batch.sprite(
atlas,
&format!("gui/sprites/recipe_book/{name}{suffix}"),
x,
y,
);
horizon_client::widgets::record(label, [x, y, 12.0, 17.0], true);
}
let text = format!("{}/{pages_n}", page + 1);
let w = HudBatch::text_width(atlas, &text);
let x = (layout.grid.0 + (layout.width() - w) / 2.0).floor();
batch.text(atlas, &text, x, layout.arrows_y + 5.0, u32::MAX, true);
}
for (i, (x, y)) in self.recipes_shown(layout) {
let Some(r) = self.mods.browser.recipes.as_ref().map(|p| &p.recipes[i]) else {
break;
};
let (at, arrow, action) = r.places(layout.width());
let h = r.block(layout.width());
let (cooking, note, button) =
(r.layout == BrowserLayout::Cooking, r.note.clone(), r.action);
let atlas = &self.gui.atlas;
for &(sx, sy) in at.iter().filter(|p| p.0.is_finite()) {
batch.sprite(atlas, "gui/sprites/container/slot", x + sx, y + sy);
}
if cooking {
batch.sprite(
atlas,
"gui/sprites/container/furnace/lit_progress",
x + 2.0,
y + SLOT + 2.0,
);
}
batch.sprite(
atlas,
"gui/sprites/container/furnace/burn_progress",
x + arrow.0,
y + arrow.1,
);
if let Some(enabled) = button {
let rect = [x + action.0, y + action.1, 12.0, 12.0];
let sprite = match (enabled, inside(cursor, rect)) {
(false, _) => "gui/sprites/widget/button_disabled",
(true, true) => "gui/sprites/widget/button_highlighted",
(true, false) => "gui/sprites/widget/button",
};
horizon_client::ui::nine_slice(
batch,
atlas,
sprite,
rect[0],
rect[1],
12.0,
12.0,
u32::MAX,
);
let color = if enabled {
u32::MAX
} else {
rgba(160, 160, 160, 255)
};
batch.text(atlas, "+", rect[0] + 3.0, rect[1] + 2.0, color, true);
horizon_client::widgets::record(&format!("+ {i}"), rect, enabled);
}
if !note.is_empty() {
batch.text(atlas, &note, x, y + h + 2.0, rgba(224, 224, 224, 255), true);
}
for (k, &(sx, sy)) in at.iter().enumerate().filter(|(_, p)| p.0.is_finite()) {
let Some((_, stack)) = self.recipe_slot_now(i, k).cloned() else {
continue;
};
self.draw_item(batch, &stack, x + sx + 1.0, y + sy + 1.0);
if inside(cursor, [x + sx, y + sy, SLOT, SLOT]) {
batch.fill(
&self.gui.atlas,
x + sx + 1.0,
y + sy + 1.0,
16.0,
16.0,
rgba(255, 255, 255, 128),
);
}
let name = self.pack.names.display_item(&stack.item);
horizon_client::widgets::record_as(
&format!("{name} {i}:{k}"),
[x + sx + 1.0, y + sy + 1.0, 16.0, 16.0],
true,
horizon_client::widgets::Kind::Button,
);
}
}
}
/// The tabs, on slots; the selected one framed.
fn draw_recipe_tabs(&mut self, batch: &mut HudBatch, layout: &Layout) {
let Some(pages) = &self.mods.browser.recipes else {
return;
};
let places = tab_places(pages, layout);
let tabs: Vec<Option<ItemStack>> = pages.tabs.iter().map(|t| t.1.clone()).collect();
let selected = pages.tab;
for (i, (&(x, y), stack)) in places.iter().zip(tabs).enumerate() {
let atlas = &self.gui.atlas;
batch.sprite(atlas, "gui/sprites/container/slot", x, y);
let Some(stack) = stack else {
continue;
};
self.draw_item(batch, &stack, x + 1.0, y + 1.0);
// The selected tab: a white frame around its slot.
if i == selected {
let white = rgba(255, 255, 255, 255);
let atlas = &self.gui.atlas;
batch.fill(atlas, x - 1.0, y - 1.0, SLOT + 2.0, 1.0, white);
batch.fill(atlas, x - 1.0, y + SLOT, SLOT + 2.0, 1.0, white);
batch.fill(atlas, x - 1.0, y, 1.0, SLOT, white);
batch.fill(atlas, x + SLOT, y, 1.0, SLOT, white);
}
if inside(self.cursor, [x, y, SLOT, SLOT]) {
batch.fill(
&self.gui.atlas,
x + 1.0,
y + 1.0,
16.0,
16.0,
rgba(255, 255, 255, 128),
);
}
let name = self.pack.names.display_item(&stack.item);
horizon_client::widgets::record_as(
&format!("{name} tab"),
[x + 1.0, y + 1.0, 16.0, 16.0],
true,
horizon_client::widgets::Kind::Tab(i == selected),
);
}
}
/// A press on the recipes: true when it hit one of their parts.
pub(super) fn browser_recipes_press(
&mut self,
layout: &Layout,
owner: usize,
right: bool,
) -> bool {
let Some(pages) = &self.mods.browser.recipes else {
return false;
};
let cursor = self.cursor;
let starts = Self::recipe_pages(pages, layout);
let page = pages.page.min(starts.len() - 1);
let [back_arrow, forward] = layout.arrows();
let turn = if page > 0 && inside(cursor, [back_arrow.0, back_arrow.1, 12.0, 17.0]) {
Some(page - 1)
} else if page + 1 < starts.len() && inside(cursor, [forward.0, forward.1, 12.0, 17.0]) {
Some(page + 1)
} else {
None
};
if let Some(to) = turn {
if let Some(p) = self.mods.browser.recipes.as_mut() {
p.page = to;
}
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.mods
.mods
.browser_event(owner, BrowserEvent::Page(starts[to] as u32));
return true;
}
if let Some((tab, _, _)) = self.recipe_tab_hovered(layout) {
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.mods
.mods
.browser_event(owner, BrowserEvent::Tab(tab as u32));
return true;
}
if inside(cursor, self.back_button(layout).0) {
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.mods.mods.browser_event(owner, BrowserEvent::Back);
return true;
}
if let Some((recipe, slot, stack, _)) = self.recipe_slot_hovered(layout) {
let event = BrowserEvent::SlotClicked(BrowserSlotClick {
recipe: recipe as u32,
slot: slot as u32,
stack,
right,
});
self.mods.mods.browser_event(owner, event);
return true;
}
let action = self.recipes_shown(layout).into_iter().find(|&(i, (x, y))| {
let r = &pages.recipes[i];
let (_, _, (ax, ay)) = r.places(layout.width());
r.action.is_some() && inside(cursor, [x + ax, y + ay, 12.0, 12.0])
});
if let Some((i, _)) = action {
if pages.recipes[i].action == Some(true) {
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.mods
.mods
.browser_event(owner, BrowserEvent::Action(i as u32));
}
return true;
}
false
}
}
@@ -111,6 +111,18 @@ impl Game<'_> {
if repeat || !self.mods.mods.has_keys() {
return;
}
// Over an item on a container screen, the mods' keys are `browser`
// events (a recipe viewer's R and U).
if pressed
&& self.screen == Screen::Inventory
&& self.title.is_none()
&& !self.mod_browser_typing()
&& let Some(name) = horizon_client::keybinds::key_name(key)
&& let Some(stack) = self.mod_browser_pointed()
{
self.mods.mods.browser_key(name, &stack);
return;
}
if pressed && (self.screen != Screen::Playing || self.title.is_some()) {
return;
}
@@ -0,0 +1,274 @@
//! Capability `recipes` (docs/mods.md): every item and recipe the game
//! knows, made once for the mods that read them, and the recipe book's
//! known displays. The recipes are the window's own data: the world's in
//! single player, vanilla's on a server (a client is sent no others), while
//! the known displays follow the server's book as the recipe book does.
use super::Game;
use horizon_client::{
crafting::Ingredient,
items::ItemStack,
recipe_book::{Category, Display},
stations::Smithing,
};
use horizon_mods::{Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes};
use std::{collections::HashMap, sync::Arc};
/// Item id -> its index in [`Recipes::items`].
struct Index(HashMap<Arc<str>, u32>);
impl Index {
fn stack(&self, item: &str, count: u32, components: String) -> Option<RecipeStack> {
Some(RecipeStack {
item: *self.0.get(item)?,
count,
components,
})
}
fn of(&self, s: &ItemStack) -> Option<RecipeStack> {
self.stack(&s.item, s.count, components(s))
}
fn any(&self, i: &Ingredient) -> Vec<RecipeStack> {
i.1.iter()
.filter_map(|id| self.stack(id, 1, String::new()))
.collect()
}
}
/// A stack's components beyond its item's, as vanilla's item syntax writes
/// them (`[minecraft:potion_contents={potion:"minecraft:swiftness"}]`), or "".
pub(super) fn components(s: &ItemStack) -> String {
use horizon_world::nbt::Tag;
let Some(Tag::Compound(entries)) = horizon_client::item_data::encode_components(s) else {
return String::new();
};
let parts: Vec<String> = entries
.iter()
.map(|(k, v)| {
format!(
"{}={}",
k.to_string_lossy(),
horizon_client::snbt::to_snbt(v)
)
})
.collect();
format!("[{}]", parts.join(","))
}
fn recipe(id: String, kind: RecipeKind) -> Recipe {
Recipe {
id,
kind,
category: String::new(),
group: String::new(),
width: 0,
height: 0,
slots: Vec::new(),
results: Vec::new(),
cooking_time: 0,
experience: 0.0,
book_id: -1,
}
}
impl Game<'_> {
/// `recipes.give`: a creative player takes the stack as from the
/// creative inventory; a server hears it as `SetCreativeModeSlot`
/// through the inventory's sync, and refuses it unless creative.
pub(super) fn mod_give(&mut self, item: &str, count: u32, components: &str) {
let Some(max) = self.res.items().get(item).map(|i| i.max_stack) else {
return;
};
if !self.creative {
return;
}
let (damage, extra) = horizon_client::item_data::command_components(components)
.map_or((0, None), |tag| {
horizon_client::item_data::decode_components(Some(&tag))
});
let _ = self.give(ItemStack {
item: item.into(),
// One stack at most, as the creative inventory hands out.
count: count.min(max),
damage,
extra,
});
}
/// Capability `recipes`'s tables and known displays for this tick's
/// snapshot; nothing while no running mod reads them.
pub(super) fn mod_recipes(&mut self) -> (Option<Arc<Recipes>>, Arc<[i32]>) {
if !self.mods.mods.wants_recipes() {
return (None, Arc::from([]));
}
if self.mods.recipes.is_none() {
self.mods.recipes = Some(Arc::new(self.make_mod_recipes()));
}
let (version, known) = self.recipe_book_displays();
if self.mods.known_recipes.0 != Some(version) {
self.mods.known_recipes = (Some(version), known.into());
}
(self.mods.recipes.clone(), self.mods.known_recipes.1.clone())
}
fn make_mod_recipes(&mut self) -> Recipes {
let names = &self.pack.names;
let items = self.res.items();
let mut tags: HashMap<&str, Vec<String>> = HashMap::new();
for (tag, members) in &items.item_tags {
for m in members {
tags.entry(m).or_default().push(tag.clone());
}
}
let table: Vec<RecipeItem> = items
.registry_order
.iter()
.map(|id| RecipeItem {
id: id.to_string(),
name: names.display_item(id),
tags: tags.remove(&**id).map_or_else(Vec::new, |mut t| {
t.sort();
t
}),
})
.collect();
let index = Index(
items
.registry_order
.iter()
.enumerate()
.map(|(i, id)| (id.clone(), i as u32))
.collect(),
);
let mut out = Vec::new();
let cooking: HashMap<String, (u32, f32)> = self
.res
.recipes()
.cooking
.iter()
.map(|c| (format!("minecraft:{}", c.id), (c.time, c.experience)))
.collect();
for e in self.recipe_book_entries() {
let furnace = |c: Category| match c.name().split('_').next() {
Some("blast") => RecipeKind::Blasting,
Some("smoker") => RecipeKind::Smoking,
_ => RecipeKind::Smelting,
};
let kind = match &e.display {
Display::Shaped { .. } => RecipeKind::CraftingShaped,
Display::Shapeless(_) => RecipeKind::CraftingShapeless,
Display::Furnace(_) => furnace(e.category),
};
let mut r = recipe(e.id.clone(), kind);
r.category = e.category.name().to_owned();
r.group = e.group.clone().unwrap_or_default();
r.book_id = e.display_id;
r.slots = match &e.display {
Display::Shaped {
width,
height,
cells,
} => {
(r.width, r.height) = (*width as u32, *height as u32);
cells
.iter()
.map(|c| c.as_ref().map_or_else(Vec::new, |i| index.any(i)))
.collect()
}
Display::Shapeless(list) => list.iter().map(|i| index.any(i)).collect(),
Display::Furnace(i) => vec![index.any(i)],
};
// Requirements shown as other stacks (an arrow's potions): the
// requirement's index counts the filled slots only.
let filled: Vec<usize> = (0..r.slots.len())
.filter(
|&k| !matches!(&e.display, Display::Shaped { cells, .. } if cells[k].is_none()),
)
.collect();
for (req, stacks) in &e.stacks {
if let Some(&k) = filled.get(*req) {
r.slots[k] = stacks.iter().filter_map(|s| index.of(s)).collect();
}
}
r.results = e.results().iter().filter_map(|s| index.of(s)).collect();
if let Some(&(time, xp)) = cooking.get(&e.id) {
(r.cooking_time, r.experience) = (time, xp);
}
out.push(r);
}
for c in &self.res.recipes().cooking {
if c.kind == "minecraft:campfire_cooking" {
let mut r = recipe(format!("minecraft:{}", c.id), RecipeKind::Campfire);
r.group = c.group.clone();
r.slots = vec![index.any(&c.ingredient)];
r.results = index.of(&c.result).into_iter().collect();
(r.cooking_time, r.experience) = (c.time, c.experience);
out.push(r);
}
}
let stations = self.res.stations();
for s in &stations.recipes.stonecutting {
let mut r = recipe(s.id.clone(), RecipeKind::Stonecutting);
r.slots = vec![index.any(&s.input)];
r.results = index.of(&s.result).into_iter().collect();
out.push(r);
}
for s in &stations.recipes.smithing {
let (id, template, base, addition, results) = match s {
Smithing::Transform {
id,
template,
base,
addition,
result,
} => (
id,
template,
base,
addition,
index.stack(result, 1, String::new()).into_iter().collect(),
),
Smithing::Trim {
id,
template,
base,
addition,
..
} => (id, template, base, addition, index.any(base)),
};
let mut r = recipe(id.clone(), RecipeKind::Smithing);
r.slots = vec![index.any(template), index.any(base), index.any(addition)];
r.results = results;
out.push(r);
}
for b in &stations.brewing.recipes {
let potion = |p: &horizon_client::brewing::PotionIngredient| -> Vec<RecipeStack> {
let mut item_ids: Vec<&String> = p.items.iter().collect();
item_ids.sort();
let mut potions: Vec<&String> = p.potions.iter().flatten().collect();
potions.sort();
item_ids
.into_iter()
.flat_map(|item| {
let one = |c: String| index.stack(item, 1, c);
if potions.is_empty() {
one(String::new()).into_iter().collect::<Vec<_>>()
} else {
potions
.iter()
.filter_map(|p| {
one(format!("[minecraft:potion_contents={{potion:\"{p}\"}}]"))
})
.collect()
}
})
.collect()
};
let mut r = recipe(b.id.clone(), RecipeKind::Brewing);
r.slots = vec![potion(&b.input), potion(&b.reagent)];
r.results = index.of(&b.output).into_iter().collect();
out.push(r);
}
Recipes {
items: table,
recipes: out,
}
}
}
+41 -2
View File
@@ -63,6 +63,14 @@ pub(super) struct ModsState {
/// What players did this tick, for server mods at its end.
#[cfg(feature = "mods")]
pub(super) events: Vec<ModEvent>,
/// A running server mod has capability `world`: its calls get the
/// levels' chunks to read.
#[cfg(feature = "mods")]
pub(super) world: bool,
/// Blocks server mods set, by dimension, made before that level's next
/// tick.
#[cfg(feature = "mods")]
pub(super) block_writes: Vec<(String, horizon_mods::BlockChange)>,
/// `command.run` lines for this window's own world, run on the next tick:
/// run at once, their chat lines would reach the mods while their output
/// is still being shown, and a mod answering its own lines would recurse.
@@ -81,6 +89,15 @@ pub(super) struct ModsState {
/// The HUD font's advances for `render.text-width`, made once.
#[cfg(feature = "mods")]
font_widths: std::sync::Arc<[f32]>,
/// Capability `recipes`'s tables, made once a mod reads them.
#[cfg(feature = "mods")]
pub(super) recipes: Option<std::sync::Arc<horizon_mods::Recipes>>,
/// The recipe book's known displays, and the book's version they are of.
#[cfg(feature = "mods")]
pub(super) known_recipes: (Option<u64>, std::sync::Arc<[i32]>),
/// Capability `ui`'s item panel beside container screens.
#[cfg(feature = "mods")]
pub(super) browser: super::mod_browser::Browser,
/// Extras that are official mods now, being installed.
#[cfg(feature = "mods")]
pub(super) moved: super::moved_extras::MovedState,
@@ -293,6 +310,8 @@ impl Game<'_> {
self.mods.mods.set_bindings(|id| chosen.keys_of(id));
// Entries were replaced wholesale: a screen's owner index is stale.
self.mods.screen = None;
// Content mods may have changed the items: remade on the next read.
self.mods.recipes = None;
self.list_mods();
self.sync_mod_commands();
self.show_mod_output();
@@ -309,6 +328,7 @@ impl Game<'_> {
/// The Mods page's rows, from what loaded.
fn list_mods(&mut self) {
self.mods.server = self.mods.mods.runs_server();
self.mods.world = self.mods.mods.wants_world();
let dev = &self.mods.dev;
self.settings.mods.installed = self
.mods
@@ -440,6 +460,7 @@ impl Game<'_> {
.map(|c| char::from_u32(c).map_or(6.0, |c| atlas.glyph_cell(c).1))
.collect();
}
let (recipes, known_recipes) = self.mod_recipes();
Snapshot {
player,
clock,
@@ -451,6 +472,10 @@ impl Game<'_> {
font_widths: self.mods.font_widths.clone(),
players,
view_hit: self.mod_view_hit(),
recipes,
known_recipes,
placing: self.mod_recipe_screen(),
creative: self.creative,
}
}
/// The first block along the player's view within
@@ -673,8 +698,10 @@ impl Game<'_> {
}
Text::literal(line).with_color(text::RED)
}
server
@ (Output::Tell { .. } | Output::Broadcast { .. } | Output::Reply { .. }) => {
server @ (Output::Tell { .. }
| Output::Broadcast { .. }
| Output::Reply { .. }
| Output::SetBlocks { .. }) => {
self.route_server_output(host.as_deref_mut(), server);
continue;
}
@@ -686,6 +713,18 @@ impl Game<'_> {
self.mods.shake.add(strength, seconds);
continue;
}
Output::PlaceRecipe { book_id, all } => {
self.mod_place_recipe(book_id, all);
continue;
}
Output::Give {
item,
count,
components,
} => {
self.mod_give(&item, count, &components);
continue;
}
Output::CloseScreen { owner } => {
if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) {
self.close_mod_screen(false);
@@ -338,6 +338,25 @@ impl Game<'_> {
ui.client_known = Some(known.clone());
ui.client_version += 1;
}
/// Every entry of the book, in its order (capability `recipes`).
#[cfg(feature = "mods")]
pub(super) fn recipe_book_entries(&mut self) -> Vec<Entry> {
self.ensure_book();
self.recipe_ui
.book
.as_ref()
.map_or_else(Vec::new, |b| b.entries.clone())
}
/// The display ids the player's book holds, and a number that changes
/// whenever they do (capability `recipes`).
#[cfg(feature = "mods")]
pub(super) fn recipe_book_displays(&mut self) -> (u64, Vec<i32>) {
self.sync_client_book();
(
self.recipe_ui.client_version,
self.recipe_ui.client.displays(),
)
}
fn ensure_book(&mut self) {
if self.recipe_ui.book.is_none() {
let mut book = Book::build(self.res.recipes(), self.res.items());
@@ -826,6 +845,34 @@ impl Game<'_> {
self.recipe_ui.ghost.clear();
self.place_recipe(book_type, entry_index, use_max);
}
/// Whether the open screen takes `recipes.place`: a crafting grid's
/// book (the inventory's or a crafting table's).
#[cfg(feature = "mods")]
pub(super) fn mod_recipe_screen(&self) -> bool {
self.screen == Screen::Inventory
&& self.active_book() == Some(BookType::Crafting)
&& !self.spectator()
}
/// `recipes.place`: the book's click on the recipe with this display
/// id, refused as `handlePlaceRecipe` refuses it (no crafting screen,
/// not in the player's book; an impossible one in `place_recipe`).
#[cfg(feature = "mods")]
pub(super) fn mod_place_recipe(&mut self, display_id: i32, all: bool) {
if !self.mod_recipe_screen() || !self.recipe_ui.client.displays().contains(&display_id) {
return;
}
self.ensure_book();
let Some(index) = self
.recipe_ui
.book
.as_ref()
.and_then(|b| b.entries.iter().position(|e| e.display_id == display_id))
else {
return;
};
self.recipe_ui.ghost.clear();
self.place_recipe(BookType::Crafting, index, all);
}
/// `ServerboundPlaceRecipePacket`: the server places the recipe
/// (`ServerPlaceRecipe` on the menu engine) and answers with a ghost
/// recipe when the items are missing.
@@ -19,33 +19,7 @@ pub const HELP: &[&str] = &[
impl Game<'_> {
/// Parse `name[k=v,...]` into a registry state (defaults for missing properties).
fn parse_state(&self, text: &str) -> Result<BlockStateId> {
let (name, props) = match text.split_once('[') {
Some((n, rest)) => (n, rest.trim_end_matches(']')),
None => (text, ""),
};
let name = if name.contains(':') {
name.to_owned()
} else {
format!("minecraft:{name}")
};
let registry = &self.pack.assets.registry;
let default = registry
.default_state(&name)
.ok_or_else(|| format!("unknown block {name}"))?;
let mut state = registry
.state(default)
.ok_or("missing default state")?
.clone();
for pair in props.split(',').filter(|p| !p.is_empty()) {
let (k, v) = pair
.split_once('=')
.ok_or_else(|| format!("bad property {pair}"))?;
if !state.properties.contains_key(k) {
return Err(format!("{name} has no property {k}").into());
}
state.properties.insert(k.to_owned(), v.to_owned());
}
Ok(registry.resolve(&state)?)
parse_state(self.pack.assets.registry, text)
}
pub(super) fn render_command(&mut self, words: &[&str]) -> Result<Option<Value>> {
let int = |i: usize| -> Result<i32> {
@@ -137,3 +111,36 @@ impl Game<'_> {
}
}
}
/// Parse `name[k=v,...]` into a registry state (defaults for missing properties).
pub(super) fn parse_state(
registry: &horizon_world::registry::BlockRegistry,
text: &str,
) -> Result<BlockStateId> {
let (name, props) = match text.split_once('[') {
Some((n, rest)) => (n, rest.trim_end_matches(']')),
None => (text, ""),
};
let name = if name.contains(':') {
name.to_owned()
} else {
format!("minecraft:{name}")
};
let default = registry
.default_state(&name)
.ok_or_else(|| format!("unknown block {name}"))?;
let mut state = registry
.state(default)
.ok_or("missing default state")?
.clone();
for pair in props.split(',').filter(|p| !p.is_empty()) {
let (k, v) = pair
.split_once('=')
.ok_or_else(|| format!("bad property {pair}"))?;
if !state.properties.contains_key(k) {
return Err(format!("{name} has no property {k}").into());
}
state.properties.insert(k.to_owned(), v.to_owned());
}
Ok(registry.resolve(&state)?)
}
+151 -3
View File
@@ -47,19 +47,72 @@ impl Game<'_> {
) -> bool {
false
}
pub(super) fn apply_mod_block_writes(&mut self) {}
}
#[cfg(feature = "mods")]
mod run {
use super::{Game, LanHost, ModEvent, Who};
use horizon_client::chunk_map::ChunkMap;
use horizon_client::{
command::args::GameMode as Mode,
lan::data::component_nbt,
text::{self, Text},
};
use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer};
use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer, WorldView};
use horizon_protocol::packets::play::{self, Clientbound as C};
use horizon_world::registry::BlockStateId;
use horizon_world::registry::{BlockRegistry, BlockStateId};
/// Blocks queued for levels that don't tick (another dimension, in-frame)
/// are kept up to this many; the oldest go first.
const MAX_QUEUED_WRITES: usize = 1 << 16;
/// Capability `world`'s view during a call: the levels' chunks, moved out
/// of the game for the call and back after it (no copy).
struct LentWorld {
registry: &'static BlockRegistry,
biomes: std::sync::Arc<horizon_client::biome::Biomes>,
dims: Vec<(&'static str, ChunkMap)>,
}
impl WorldView for LentWorld {
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?;
let chunk = chunks.get(&(x >> 4, z >> 4))?;
Some(state_string(self.registry, chunk.block(x & 15, y, z & 15)))
}
fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?;
let chunk = chunks.get(&(x >> 4, z >> 4))?;
Some(self.biomes.get(chunk.biome(x, y, z)).name.clone())
}
fn has_dimension(&self, dimension: &str) -> bool {
matches!(
dimension,
"minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end"
)
}
fn check_state(&self, state: &str) -> Result<(), String> {
crate::game::render_control::parse_state(self.registry, state)
.map(drop)
.map_err(|e| format!("{state}: {e}"))
}
}
/// `minecraft:oak_log[axis=y]`.
fn state_string(registry: &BlockRegistry, state: BlockStateId) -> String {
let Some(s) = registry.state(state) else {
return "minecraft:air".into();
};
if s.properties.is_empty() {
return s.name.clone();
}
let props: Vec<String> = s
.properties
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect();
format!("{}[{}]", s.name, props.join(","))
}
/// `UUID.toString()`.
fn uuid_string(u: u128) -> String {
@@ -144,6 +197,7 @@ mod run {
let players = self.server_players(None);
let snapshot = self.mod_snapshot_with(players.clone());
self.mods.mods.set_snapshot(snapshot);
self.lend_world();
let before = std::mem::take(&mut self.mods.players);
for p in before
.iter()
@@ -197,8 +251,80 @@ mod run {
}
}
self.mods.mods.server_tick(self.ticks);
self.return_world();
self.mods.players = players;
self.show_mod_output();
self.apply_mod_block_writes();
}
/// Lends the levels' chunks to capability `world` for the calls up to
/// [`Game::return_world`], when a running server mod has it.
fn lend_world(&mut self) {
if !self.mods.world {
return;
}
let mut dims = vec![(self.dim.id(), std::mem::take(&mut self.world.chunks))];
for (dim, chunks) in self.levels.parked_chunks() {
dims.push((dim.id(), std::mem::take(chunks)));
}
let registry = self.pack.assets.registry;
let biomes = self.res.biomes().clone();
self.mods.mods.lend_world(Box::new(LentWorld {
registry,
biomes,
dims,
}));
}
/// Puts back the chunks [`Game::lend_world`] lent.
fn return_world(&mut self) {
let Some(view) = self.mods.mods.take_world() else {
return;
};
let view: Box<dyn std::any::Any> = view;
let Ok(lent) = view.downcast::<LentWorld>() else {
return;
};
let mut dims = lent.dims;
if let Some(i) = dims.iter().position(|(d, _)| *d == self.dim.id()) {
self.world.chunks = dims.swap_remove(i).1;
}
for (dim, chunks) in self.levels.parked_chunks() {
if let Some(i) = dims.iter().position(|(d, _)| *d == dim.id()) {
*chunks = dims.swap_remove(i).1;
}
}
}
/// Makes the blocks server mods set in the level in place, in order,
/// as `/setblock` does. Those of other dimensions wait for their level.
pub(in crate::game) fn apply_mod_block_writes(&mut self) {
if self.mods.block_writes.is_empty() {
return;
}
let dim = self.dim.id();
let (now, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.mods.block_writes)
.into_iter()
.partition(|(d, _)| d == dim);
self.mods.block_writes = later;
let registry = self.pack.assets.registry;
for (_, b) in now {
let state = match crate::game::render_control::parse_state(registry, &b.state) {
Ok(state) => state,
Err(e) => {
log::warn!("Horizon: a server mod set {}: {e}", b.state);
continue;
}
};
if let Err(e) = self.place_state([b.x, b.y, b.z], state, false) {
log::debug!(
"Horizon: a server mod's block at {} {} {}: {e:?}",
b.x,
b.y,
b.z
);
}
}
}
/// A player broke (or placed) `state` at `pos`: the player acting now.
@@ -240,8 +366,11 @@ mod run {
};
let snapshot = self.mod_snapshot_with(players);
self.mods.mods.set_snapshot(snapshot);
self.lend_world();
let owned = self.mods.mods.server_command(&me, line);
self.return_world();
self.show_mod_output();
self.apply_mod_block_writes();
owned
}
@@ -266,10 +395,14 @@ mod run {
};
let snapshot = self.mod_snapshot_with(players);
self.mods.mods.set_snapshot(snapshot);
if !self.mods.mods.server_command(&me, line) {
self.lend_world();
let owned = self.mods.mods.server_command(&me, line);
self.return_world();
if !owned {
return false;
}
self.route_mod_output(Some(host));
self.apply_mod_block_writes();
true
}
@@ -349,6 +482,21 @@ mod run {
self.tell_server_player(host.as_deref_mut(), &p.id, line);
}
}
Output::SetBlocks {
name,
dimension,
blocks,
} => {
let queued = &mut self.mods.block_writes;
queued.extend(blocks.into_iter().map(|b| (dimension.clone(), b)));
if queued.len() > MAX_QUEUED_WRITES {
let over = queued.len() - MAX_QUEUED_WRITES;
queued.drain(..over);
log::warn!(
"Horizon: mod {name} set more blocks than wait for their level: {over} dropped"
);
}
}
_ => {}
}
}
@@ -196,6 +196,82 @@ impl WorldLoader {
}
}
/// How long the preloaded world data outlives the world screens: a player
/// who goes back to the title or to Multiplayer and opens no world for this
/// long gets the memory back.
const PRELOAD_KEPT: std::time::Duration = std::time::Duration::from_secs(60);
enum Preload {
Idle,
/// Read, or being read, on the "World data preload" thread. `left`: when
/// the player last left the world screens.
Started {
thread: std::thread::JoinHandle<()>,
left: Option<std::time::Instant>,
},
/// A world opened: the data is the world's now, and stays.
Used,
}
static PRELOAD: std::sync::Mutex<Preload> = std::sync::Mutex::new(Preload::Idle);
/// Each frame of the title: read what every world opening loads and keeps
/// for the rest of the process (the worldgen bundle, the loot tables and the
/// registries the server sends) on a helper thread while the player is on the
/// world screens (`on_world_screens`: Singleplayer, Create World and their
/// dialogs), so it overlaps the time spent choosing a world. A world opened
/// meanwhile waits for the part being read instead of reading it again. Not
/// at the title screen itself: many players only go to Multiplayer, and
/// small machines need the memory. Dropped after `PRELOAD_KEPT` away from
/// the world screens without a world opening.
pub(super) fn preload_world_data(
on_world_screens: bool,
resources: &std::path::Path,
registry: &'static horizon_world::registry::BlockRegistry,
) {
let mut preload = PRELOAD.lock().unwrap_or_else(|e| e.into_inner());
match &mut *preload {
Preload::Used => {}
Preload::Idle if on_world_screens => {
let resources = resources.to_owned();
let spawned = std::thread::Builder::new()
.name("World data preload".into())
.spawn(move || {
horizon_threads::behind_server();
// Errors are left for the world opening to report.
let _ = horizon_client::vanillagen::shared_data(
&resources.join("worldgen"),
registry,
);
let _ = horizon_client::structure_blocks::loot_data(&resources);
let _ = super::lan::sync_data(&resources);
});
match spawned {
Ok(thread) => *preload = Preload::Started { thread, left: None },
Err(e) => log::warn!("Horizon: world data preload: {e}"),
}
}
Preload::Idle => {}
Preload::Started { left, .. } if on_world_screens => *left = None,
Preload::Started { thread, left } => {
let left = *left.get_or_insert_with(std::time::Instant::now);
if left.elapsed() >= PRELOAD_KEPT && thread.is_finished() {
horizon_client::vanillagen::forget_shared_data();
horizon_client::structure_blocks::forget_loot_data();
super::lan::forget_sync_data();
horizon_threads::release_free_memory();
*preload = Preload::Idle;
log::info!("Horizon: preloaded world data dropped, no world opened");
}
}
}
}
/// A world opens: what `preload_world_data` read is the world's from now on.
pub(super) fn world_data_used() {
*PRELOAD.lock().unwrap_or_else(|e| e.into_inner()) = Preload::Used;
}
pub(super) fn make_streaming(
res: &Resources,
pack: &PackResources,
-318
View File
@@ -1,318 +0,0 @@
//! 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);
}
/// The world's save (Level.write) writes the rules as they are now, and a
/// world opened again reads them back (#74).
#[test]
fn level_save_keeps_changed_rules() {
let dir =
std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let mut level = crate::save::Level::default();
level.write(&dir).unwrap();
// Rules changed while playing, then saved and loaded again.
let mut rules = GameRules::load(&dir);
assert_eq!(rules, GameRules::default());
assert!(rules.set("advance_time", Value::Bool(false)));
assert!(rules.set("advance_weather", Value::Bool(false)));
assert!(rules.set("random_tick_speed", Value::Int(0)));
level.game_rules = rules.by_name();
level.write(&dir).unwrap();
assert_eq!(GameRules::load(&dir), rules);
let read = crate::save::Level::read(&dir).unwrap();
assert_eq!(read.game_rules, rules.by_name());
assert_eq!(read.game_rule("advance_time"), 0);
let _ = fs::remove_dir_all(dir);
}
}
+1 -35
View File
@@ -2,7 +2,6 @@
//! defaults, `key_<name>:key.keyboard.x` persistence, display names, and the
//! translation of rebound physical keys back to the default keys the game
//! logic listens for.
use crate::text::Text;
use std::collections::BTreeMap;
use winit::{event::MouseButton, keyboard::KeyCode};
@@ -225,40 +224,7 @@ pub fn mouse_button(name: &str) -> Option<MouseButton> {
_ => return None,
})
}
/// 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, &[])
}
pub use horizon_client_core::key_display::display_name;
/// Current bindings by mapping name.
#[derive(Clone, Debug, PartialEq, Eq)]
-266
View File
@@ -1,266 +0,0 @@
//! 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!("../assets/horizon/lang/en_us.json"),
"assets/horizon/lang/ru_ru.json" => include_str!("../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)");
}
}
+12 -12
View File
@@ -19,13 +19,11 @@ pub mod biome;
pub mod block_entities;
pub mod block_entity_anim;
pub mod block_entity_item;
pub mod block_entity_nbt;
pub mod block_entity_render;
pub mod block_transform;
pub mod blocks;
pub mod border_render;
pub mod boss_overlay;
pub mod bossbar;
pub mod breaking;
pub mod brewing;
pub mod bundle;
@@ -38,10 +36,8 @@ pub mod clipboard;
pub mod clock;
pub mod clouds;
pub mod collisions;
pub mod command;
pub mod command_block;
pub mod command_storage;
pub mod component;
pub mod confirm_screen;
pub mod container_screen;
pub mod containers;
@@ -71,7 +67,6 @@ pub mod extras;
pub mod extras_hud;
pub mod falling_block;
pub mod fast_hash;
pub mod fastutil_order;
pub mod fire_render;
pub mod first_person;
pub mod flatgen;
@@ -80,7 +75,6 @@ pub mod font;
pub mod friends_screen;
pub mod game_mode_switcher;
pub mod gamepad;
pub mod gamerules;
pub mod gfx;
pub mod gizmos;
pub mod gossip;
@@ -109,7 +103,6 @@ pub mod keybinds;
pub mod keymapping;
pub mod lan;
pub mod landing;
pub mod lang;
pub mod level_loading;
pub mod light;
pub mod locator_bar;
@@ -131,7 +124,6 @@ pub mod mouse;
pub mod moved_extras;
pub mod multiplayer;
pub mod music;
pub mod nbt_path;
pub mod net;
pub mod nether_portal;
pub mod offline_name;
@@ -160,7 +152,6 @@ pub mod recipe_book;
pub mod recipe_book_screen;
pub mod reconnect;
pub mod save;
pub mod scoreboard;
pub mod scoreboard_cmd;
pub mod screen_draw;
pub mod screen_effects;
@@ -173,7 +164,6 @@ pub mod shader_pack_list;
pub mod shadows;
pub mod signs;
pub mod skins;
pub mod snbt;
pub mod sound_engine;
pub mod sound_events;
pub mod spans;
@@ -186,7 +176,6 @@ pub mod structure_blocks;
pub mod tab_list;
pub mod telemetry;
pub mod testgen;
pub mod text;
pub mod text_display;
pub mod tick_chunk_membership;
pub mod ticket_levels;
@@ -206,4 +195,15 @@ pub mod world;
pub mod world_spawn;
pub mod worldborder;
pub mod zip;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
pub use horizon_client_core::Result;
pub use horizon_client_core::block_entity_nbt;
pub use horizon_client_core::bossbar;
pub use horizon_client_core::component;
pub use horizon_client_core::fastutil_order;
pub use horizon_client_core::gamerules;
pub use horizon_client_core::lang;
pub use horizon_client_core::nbt_path;
pub use horizon_client_core::scoreboard;
pub use horizon_client_core::snbt;
pub use horizon_client_core::text;
pub use horizon_command as command;
+21 -1
View File
@@ -69,6 +69,7 @@ pub mod tame;
pub mod trader;
pub mod transport_items;
pub mod trial_spawner;
pub mod turtle;
pub mod undead;
pub mod vex;
pub mod villager;
@@ -516,6 +517,8 @@ pub enum DamageKind {
InFire,
Lava,
Drown,
/// `dry_out`: an axolotl out of water for too long.
DryOut,
Magic,
Sting,
Cactus,
@@ -574,7 +577,11 @@ impl Damage {
pub fn causes_panic(&self) -> bool {
!matches!(
self.kind,
DamageKind::Fall | DamageKind::Drown | DamageKind::Generic | DamageKind::InWall
DamageKind::Fall
| DamageKind::Drown
| DamageKind::DryOut
| DamageKind::Generic
| DamageKind::InWall
)
}
/// DamageTypeTags.BYPASSES_ARMOR
@@ -607,6 +614,7 @@ impl Damage {
| DamageKind::InFire
| DamageKind::Lava
| DamageKind::Drown
| DamageKind::DryOut
| DamageKind::Magic
| DamageKind::Cactus
| DamageKind::Generic
@@ -1203,6 +1211,12 @@ pub enum MobEvent {
mob: u32,
target: Who,
},
/// `LevelEvent.PARTICLES_DESTROY_BLOCK` (2001) at `pos` for the block at
/// `block`: a turtle's digging.
BlockBreakEffect {
pos: [i32; 3],
block: [i32; 3],
},
/// `Warden.applyDarknessAround`: darkness for survival players nearby.
Darkness {
at: [f64; 3],
@@ -1873,6 +1887,12 @@ impl Mob {
}
}
}
// Squid.hurtServer: a squid hurt after a living entity hit it squirts ink.
if matches!(self.species(), Species::Squid | Species::GlowSquid)
&& self.ai.last_hurt_by.is_some()
{
aquatic::spawn_ink(self);
}
true
}
/// LivingEntity.knockback(power, xd, zd) towards the negative direction.
+43 -1
View File
@@ -183,6 +183,9 @@ pub fn register(m: &mut Mob) {
if m.species() == Species::Rabbit {
super::rabbit::register(m);
}
if m.species() == Species::Turtle {
super::turtle::register(m);
}
}
Family::Inert => {}
Family::Witch => super::witch::register(m),
@@ -441,6 +444,34 @@ pub fn tick_swing(m: &mut Mob) {
}
m.anim.attack_anim = m.ai.swing_time as f32 / 6.0;
}
/// `LivingEntity.baseTick` refills a breather's air by 4, then
/// `Axolotl.handleAirSupply` (unless the mob has no AI): water or rain fills
/// it, anywhere else it runs down from the pre-tick value, and at -20 the
/// axolotl dries out.
fn axolotl_air_supply(m: &mut Mob, w: &MobWorld) {
let before = m.air;
m.air = (m.air + 4).min(super::axolotl::MAX_AIR);
if m.no_ai {
return;
}
// Entity.isInRain: rain at the block, or at the top of the box.
let (x, y, z) = (
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
let top = (m.position.y + f64::from(m.height())).floor() as i32;
let in_rain = w.raining_at(x, y, z) || w.raining_at(x, top, z);
if m.fluids.in_water || in_rain {
m.air = super::axolotl::MAX_AIR;
} else {
m.air = before - 1;
if m.air <= -20 {
m.air = 0;
m.damage(2.0, Damage::of(DamageKind::DryOut));
}
}
}
/// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick.
fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.was_eye_in_water = m.fluids.eye_in_water;
@@ -500,7 +531,9 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.damage(1.0, Damage::of(DamageKind::InWall));
}
// Air supply and drowning (WaterAnimal.handleAirSupply for aquatic mobs).
if m.kind.flags.needs_water {
if m.species() == Species::Axolotl {
axolotl_air_supply(m, w);
} else if m.kind.flags.needs_water {
if !m.fluids.in_water {
m.air -= 1;
if m.air == -20 {
@@ -712,6 +745,14 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
// setAge at the age boundary: refreshDimensions.
if m.extra.age >= 0 {
m.fudge_position_after_size_change(w, bw, bh);
// Turtle.ageBoundaryReached: a grown turtle drops a scute.
if m.species() == Species::Turtle {
events.push(MobEvent::GiftLoot {
mob: m.id,
table: "minecraft:gameplay/turtle_grow",
at: [m.position.x, m.position.y, m.position.z],
});
}
}
} else if m.extra.age > 0 {
m.extra.age -= 1;
@@ -1005,6 +1046,7 @@ fn species_ai_step(
}
Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events),
Species::Chicken => farm::chicken_ai_step(m, w, events),
Species::Turtle => super::turtle::ai_step(m, w, events),
Species::Sheep if m.extra.anim_ticks > 0 => {
m.extra.anim_ticks -= 1;
}
+53
View File
@@ -24,6 +24,58 @@ const Z_BODY_ROT: usize = 3;
const TENTACLE_SPEED: usize = 4;
const ROTATE_SPEED: usize = 5;
/// `Squid.spawnInk`: the squirt sound and 30 ink particles shot from under
/// the squid, turned by its body rotation.
pub fn spawn_ink(m: &mut Mob) {
let sound = if m.species() == Species::GlowSquid {
"entity.glow_squid.squirt"
} else {
"entity.squid.squirt"
};
let kind = if m.species() == Species::GlowSquid {
"glow_squid_ink"
} else {
"squid_ink"
};
// makeSound draws the voice pitch even for a silent squid.
let pitch = m.voice_pitch();
if !m.silent {
let at = [m.position.x, m.position.y, m.position.z];
m.outbox.push(MobEvent::Sound(
sound,
at,
super::ai::sound_volume(m),
pitch,
));
}
// rotateVector: xRot(xBodyRotO), then yRot(-yBodyRotO).
let to_radians = (std::f64::consts::PI / 180.0) as f32;
let (x_rot, y_rot) = (
m.anim.vo[X_BODY_ROT] * to_radians,
-m.previous_body_yaw * to_radians,
);
let rotate = |v: Vec3| v.rotate_x(x_rot).rotate_y(y_rot);
let pos = rotate(Vec3::new(0.0, -1.0, 0.0)).add_vector(m.position);
let offset_scale: f32 = if m.is_baby() { 0.1 } else { 0.3 };
for _ in 0..30 {
let x = f64::from(m.random.next_float()) * 0.6 - 0.3;
let z = f64::from(m.random.next_float()) * 0.6 - 0.3;
let dir = rotate(Vec3::new(x, -1.0, z));
let d = dir.scale(f64::from(offset_scale + m.random.next_float() * 2.0));
// ServerLevel.sendParticles with a count of 0 and speed 0.1: one
// particle moving at the float offset times the float speed.
let speed = f64::from(0.1f32);
m.outbox.push(MobEvent::ParticleAt {
kind,
at: [pos.x, pos.y + 0.5, pos.z],
velocity: [
speed * f64::from(d.x as f32),
speed * f64::from(d.y as f32),
speed * f64::from(d.z as f32),
],
});
}
}
pub fn register(m: &mut Mob) {
use Species as S;
match m.species() {
@@ -36,6 +88,7 @@ pub fn register(m: &mut Mob) {
m.anim.v[TENTACLE_SPEED] = speed;
}
S::Axolotl => {
m.air = super::axolotl::MAX_AIR;
// Native controller scaling is essential: the base speed attribute is 1.0.
m.ai.mov.kind = MoveKind::SmoothSwimming {
max_turn_x: 85.0,
@@ -3,6 +3,8 @@ use super::{Mob, MobEvent, MobWorld, Species, Who, animal_brain, keyframes::Anim
use horizon_core::random::RandomSource;
pub const PLAY_DEAD_TICKS: i32 = 200;
pub const HUNTING_COOLDOWN: i64 = 2400;
/// `Axolotl.getMaxAirSupply`.
pub const MAX_AIR: i32 = 6000;
/// AxolotlAttackablesSensor: always-hostile targets bypass the hunting cooldown.
pub fn prey_eligible(
+2 -2
View File
@@ -969,8 +969,8 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool {
s,
&Turtle {
on_land: !m.fluids.in_water && m.on_ground,
laying_egg: false,
has_egg: false,
laying_egg: m.extra.flag2,
has_egg: m.extra.flag,
},
),
Species::Strider => strider(p, s, m.rider.is_some()),
+8
View File
@@ -1791,6 +1791,10 @@ impl Goal for Breed {
if tamable && (!m.extra.tame || m.extra.sitting) {
return false;
}
// TurtleBreedGoal.canUse: not while carrying an egg.
if species == Species::Turtle && super::turtle::has_egg(m) {
return false;
}
let id = m.id;
// Horses and donkeys breed together (AbstractHorse.canParent: tame).
// Sniffer.canMate: calm states only.
@@ -1869,6 +1873,10 @@ impl Goal for Breed {
});
m.extra.in_love = 0;
m.extra.age = 6000;
// TurtleBreedGoal.breed: the mother carries an egg, not a baby.
if m.species() == Species::Turtle {
m.extra.flag = true;
}
cx.events.push(MobEvent::Breed {
parent: m.id,
partner: p.id,
@@ -153,6 +153,14 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index,
S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random),
S::Mooshroom => m.extra.variant = 0,
// Turtle.finalizeSpawn: home is where it spawned.
S::Turtle => {
m.extra.home = Some([
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
])
}
S::Frog => m.extra.variant = biome.frog,
S::Wolf => m.extra.variant = biome.wolf,
S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon),
+209
View File
@@ -0,0 +1,209 @@
//! Turtles (`Turtle`): the egg a bred mother carries (`TurtleBreedGoal`), her
//! walk home (`TurtleGoHomeGoal`) and the egg she digs into the sand
//! (`TurtleLayEggGoal`). `extra.flag` is `hasEgg`, `extra.flag2` `isLayingEgg`,
//! `extra.counter` `layEggCounter` and `extra.home` `homePos`.
use super::{
Mob, MobEvent, MobWorld,
goals::{Breed, Cx, Goal, JUMP, MOVE, MoveToBlock, goal_clone, reduced},
};
use horizon_core::random::RandomSource;
pub fn register(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(1, Breed::new(1.0));
g.add(1, LayEgg(MoveToBlock::new(1.0, 16, 1)));
g.add(4, GoHome::default());
}
/// `Turtle.hasEgg`.
pub fn has_egg(m: &Mob) -> bool {
m.extra.flag
}
/// `Turtle.setLayingEgg`.
fn set_laying_egg(m: &mut Mob, on: bool) {
m.extra.counter = i32::from(on);
m.extra.flag2 = on;
}
/// `homePos.closerToCenterThan(position, distance)`. Spawning, hatching and
/// loading all set a home; one made any other way is at home where it stands.
fn close_to_home(m: &Mob, distance: f64) -> bool {
let home = m.extra.home.unwrap_or([
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
]);
let d = [
f64::from(home[0]) + 0.5 - m.position.x,
f64::from(home[1]) + 0.5 - m.position.y,
f64::from(home[2]) + 0.5 - m.position.z,
];
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < distance * distance
}
fn block_of(m: &Mob) -> [i32; 3] {
[
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
]
}
/// `TurtleEggBlock.isSand`.
fn is_sand(w: &MobWorld, p: [i32; 3]) -> bool {
w.has_tag("minecraft:sand", w.block_name(p[0], p[1], p[2]))
}
/// `Turtle.aiStep`: while digging, sand crumbs fly every fifth tick.
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if m.alive() && m.extra.flag2 && m.extra.counter >= 1 && m.extra.counter % 5 == 0 {
let at = block_of(m);
let below = [at[0], at[1] - 1, at[2]];
if is_sand(w, below) {
events.push(MobEvent::BlockBreakEffect {
pos: at,
block: below,
});
}
}
}
/// `Turtle.TurtleLayEggGoal`: a mother with an egg within 9 blocks of home
/// walks to sand with air above, digs for 200 ticks and lays it.
#[derive(Clone, Debug)]
struct LayEgg(MoveToBlock);
impl LayEgg {
/// `isValidTarget`: sand with air above it.
fn valid(w: &MobWorld, p: [i32; 3]) -> bool {
w.facts.is_air(w.world.block(p[0], p[1] + 1, p[2])) && is_sand(w, p)
}
}
impl Goal for LayEgg {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | JUMP
}
fn name(&self) -> &'static str {
"TurtleLayEggGoal"
}
fn every_tick(&self) -> bool {
true
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !(has_egg(m) && close_to_home(m, 9.0)) {
return false;
}
// MoveToBlockGoal.canUse.
if self.0.next_start > 0 {
self.0.next_start -= 1;
return false;
}
self.0.next_start = reduced(200 + m.random.next_int_bound(200).unwrap_or(0));
self.0.find_nearest(m, cx.w, Self::valid)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.0.can_continue(cx.w, Self::valid) && has_egg(m) && close_to_home(m, 9.0)
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.start(m, cx.w);
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.tick(m, cx.w);
if m.fluids.in_water || !self.0.reached {
return;
}
if m.extra.counter < 1 {
set_laying_egg(m, true);
} else if m.extra.counter > 200 {
let at = [m.position.x, m.position.y, m.position.z];
let pitch = 0.9 + m.random.next_float() * 0.2;
cx.events
.push(MobEvent::Sound("entity.turtle.lay_egg", at, 0.3, pitch));
// Blocks.TURTLE_EGG with EGGS = nextInt(4) + 1 above the sand.
let eggs = m.random.next_int_bound(4).unwrap_or(0) + 1;
let registry = cx.w.registry;
let state = registry
.default_state("minecraft:turtle_egg")
.and_then(|d| registry.state(d).cloned())
.and_then(|mut s| {
s.properties.insert("eggs".into(), eggs.to_string());
registry.resolve(&s).ok()
});
let b = self.0.block;
if let Some(state) = state {
cx.events.push(MobEvent::SetBlock {
pos: [b[0], b[1] + 1, b[2]],
state,
});
}
m.extra.flag = false;
set_laying_egg(m, false);
m.extra.in_love = 600;
}
if m.extra.flag2 {
m.extra.counter += 1;
}
}
}
/// `Turtle.TurtleGoHomeGoal`: a mother with an egg heads home; any adult
/// that strayed 64 blocks away does now and then.
#[derive(Clone, Debug, Default)]
struct GoHome {
stuck: bool,
close_to_home_try_ticks: i32,
}
impl Goal for GoHome {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn name(&self) -> &'static str {
"TurtleGoHomeGoal"
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
if m.is_baby() {
false
} else if has_egg(m) {
true
} else {
m.random.next_int_bound(reduced(700)).unwrap_or(1) == 0 && !close_to_home(m, 64.0)
}
}
fn start(&mut self, _m: &mut Mob, _cx: &mut Cx) {
self.stuck = false;
self.close_to_home_try_ticks = 0;
}
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
!close_to_home(m, 7.0) && !self.stuck && self.close_to_home_try_ticks <= reduced(600)
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let home = m.extra.home.unwrap_or(block_of(m));
let close = close_to_home(m, 16.0);
if close {
self.close_to_home_try_ticks += 1;
}
if !m.ai.nav.is_done() {
return;
}
let to = [
f64::from(home[0]) + 0.5,
f64::from(home[1]),
f64::from(home[2]) + 0.5,
];
let mut next = m
.default_random_pos_towards(cx.w, 16, 3, to, std::f64::consts::PI / 10.0)
.or_else(|| m.default_random_pos_towards(cx.w, 8, 7, to, std::f64::consts::FRAC_PI_2));
if let Some(at) = next
&& !close
&& cx.w.block_name(
at[0].floor() as i32,
at[1].floor() as i32,
at[2].floor() as i32,
) != "minecraft:water"
{
next = m.default_random_pos_towards(cx.w, 16, 5, to, std::f64::consts::FRAC_PI_2);
}
match next {
Some(at) => {
m.nav_move_to(cx.w, at, 1.0);
}
None => self.stuck = true,
}
}
}
+13
View File
@@ -206,6 +206,19 @@ impl MobWorld<'_> {
}
self.world.light(x, y, z) >> 4 == 15
}
/// Level.isRainingAt: raining, open to the sky, nothing motion blocking
/// above, and the biome's precipitation at the position is rain, not snow
/// or none.
pub fn raining_at(&self, x: i32, y: i32, z: i32) -> bool {
if !self.raining || !self.can_see_sky(x, y, z) || self.motion_blocking_height(x, z) > y {
return false;
}
let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else {
return false;
};
let biome = self.biomes.get(chunk.biome(x, y, z));
biome.precipitation && biome.temperature_at(BlockPos::new(x, y, z), self.sea_level) >= 0.15
}
/// Level.getLightLevelDependentMagicValue: the dimension's brightness curve
/// at the raw (sky darkened) light level.
pub fn brightness(&self, x: i32, y: i32, z: i32) -> f32 {
+44
View File
@@ -52,6 +52,8 @@ pub struct MotionResources {
pub climbable: BTreeSet<String>,
/// `BlockTags.CAN_GLIDE_THROUGH`: climbable blocks a gliding player passes.
pub glide_through: BTreeSet<String>,
/// `BlockTags.SOUL_SPEED_BLOCKS`: what Soul Speed's effects look for.
pub soul_speed_blocks: BTreeSet<String>,
pub fall_reset: BTreeSet<String>,
pub landing: BlockLandingRegistry,
pub health: crate::health::HealthResources,
@@ -111,11 +113,29 @@ impl MotionResources {
})?,
climbable: tag("minecraft:climbable")?,
glide_through: tag("minecraft:can_glide_through")?,
soul_speed_blocks: tag("minecraft:soul_speed_blocks")?,
fall_reset: tag("minecraft:fall_damage_resetting")?,
})
}
}
/// What the `location_changed` enchantment effects (Soul Speed) need to know
/// between ticks.
#[derive(Clone, Debug, Default)]
pub struct LocationEffects {
/// `MovementAffectedByPredicate`: the block under the player
/// (`getBlockPosBelowThatAffectsMyMovement`) is in `#minecraft:soul_speed_blocks`.
pub on_soul_speed_block: bool,
/// `LivingEntity.lastPos`: the block the player was in last tick.
pub block: Option<BlockPos>,
/// A landing ran `onChangedBlock` (`LivingEntity.checkFallDamage`).
pub landed: bool,
/// The Soul Speed level of the boots seen last tick (0: none).
pub boots_level: u32,
/// The Soul Speed level whose attribute modifiers are on the player (0: none).
pub applied_level: u32,
}
/// Ordered requests and phase records for world/audio/network consumers. Landing
/// hurt dispatch updates stored health synchronously before these are drained.
#[derive(Clone, Copy, Debug)]
@@ -258,6 +278,8 @@ pub struct PlayerMotion {
pub glide_ending: bool,
/// Glider durability to take this tick (updateFallFlying).
pub glider_wear: u32,
/// Soul Speed's `location_changed` bookkeeping.
pub location_effects: LocationEffects,
/// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's
/// spin. The damage stays until the game has dealt the hit.
pub auto_spin_attack_ticks: i32,
@@ -449,6 +471,7 @@ impl PlayerMotion {
fall_fly_ticks: 0,
glide_ending: false,
glider_wear: 0,
location_effects: LocationEffects::default(),
auto_spin_attack_ticks: 0,
auto_spin_attack_dmg: 0.0,
spin_targets: Vec::new(),
@@ -1006,6 +1029,7 @@ impl MotionWorld<'_, '_, '_> {
)
});
self.player.try_add_frost(on_air)?;
self.update_soul_speed_block()?;
if self.player.health.tick_count % 40 == 0
&& self.player.is_fully_frozen()
&& self.player.can_freeze()
@@ -1018,6 +1042,22 @@ impl MotionWorld<'_, '_, '_> {
}
Ok(())
}
/// Refresh whether the player stands on a soul speed block, for the
/// `location_changed` enchantment effects (a server's player too, whose
/// client does the walking).
pub fn update_soul_speed_block(&mut self) -> Result<()> {
self.player.location_effects.on_soul_speed_block = self.on_soul_speed_block()?;
Ok(())
}
/// `MovementAffectedByPredicate` for `#minecraft:soul_speed_blocks`.
fn on_soul_speed_block(&mut self) -> Result<bool> {
let on = self.support(movement_support::MOVEMENT_SUPPORT_OFFSET)?;
Ok(self
.assets
.registry
.state(self.block(on))
.is_some_and(|s| self.resources.soul_speed_blocks.contains(&s.name)))
}
/// Player.travel: swim steering, then LivingEntity.travel (fluids first,
/// then gliding, then air), keeping 0.6 of the vertical speed while flying.
fn player_travel(&mut self, input: Vec3) -> Result<()> {
@@ -1915,6 +1955,10 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> {
if self.player.status.slow_falling || self.player.status.levitation.is_some() {
self.player.fall_distance = 0.0;
}
// LivingEntity.checkFallDamage: a landing runs onChangedBlock.
if grounded && self.player.fall_distance > 0.0 {
self.player.location_effects.landed = true;
}
if self.player.spawn_extra_particles_on_fall && grounded && self.player.fall_distance > 0.0
{
self.player.events.push(MotionEvent::SmashLanding {
-901
View File
@@ -1,901 +0,0 @@
//! 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 &current {
// 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)));
}
}
+1 -206
View File
@@ -23,212 +23,7 @@ use std::{
path::Path,
};
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,
}
}
}
pub use horizon_client_core::particle_type::ParticleType;
/// `ParticleOptions` with the parameters of the option classes used here.
#[derive(Clone, Debug)]
+25 -22
View File
@@ -2435,28 +2435,7 @@ fn write_saved_data(world: &Path, name: &str, data: Tag) -> Result<()> {
Tag::compound([("data", data), ("DataVersion", Tag::Int(DATA_VERSION))]),
)
}
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)
}
pub use horizon_client_core::uuid::{uuid_from_text, uuid_text};
/// A random (version 4) UUID as vanilla's four-int form.
pub fn random_uuid() -> [i32; 4] {
let t = std::time::SystemTime::now()
@@ -5125,6 +5104,30 @@ mod tests {
};
assert_eq!(back.recipes_used.get("minecraft:cooked_porkchop"), Some(&3));
}
/// The world's save (Level.write) writes the rules as they are now, and a
/// world opened again reads them back (#74).
#[test]
fn level_save_keeps_changed_rules() {
use crate::gamerules::{GameRules, Value};
let dir =
std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut level = super::Level::default();
level.write(&dir).unwrap();
// Rules changed while playing, then saved and loaded again.
let mut rules = GameRules::load(&dir);
assert_eq!(rules, GameRules::default());
assert!(rules.set("advance_time", Value::Bool(false)));
assert!(rules.set("advance_weather", Value::Bool(false)));
assert!(rules.set("random_tick_speed", Value::Int(0)));
level.game_rules = rules.by_name();
level.write(&dir).unwrap();
assert_eq!(GameRules::load(&dir), rules);
let read = super::Level::read(&dir).unwrap();
assert_eq!(read.game_rules, rules.by_name());
assert_eq!(read.game_rule("advance_time"), 0);
let _ = std::fs::remove_dir_all(dir);
}
/// A save written before the key was namespaced holds an id twice, once bare: vanilla
/// refuses such a furnace, so a load merges them under the full id.
File diff suppressed because it is too large Load Diff
+1 -5
View File
@@ -5,11 +5,7 @@ use crate::keybinds::KeyBinds;
use crate::options_file::{OptionsFile, V};
use std::{fs, path::Path};
/// SoundSource names in vanilla order.
pub const SOUND_SOURCES: [&str; 11] = [
"master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient",
"voice", "ui",
];
pub use horizon_client_core::sound_source::SOUND_SOURCES;
/// Per-source volumes for the mixer (soundCategory_* except master).
static SOURCE_VOLUMES: std::sync::RwLock<[f32; 11]> = std::sync::RwLock::new([1.0; 11]);
-513
View File
@@ -1,513 +0,0 @@
//! 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, &quote.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(&quote_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(&quote_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}]}");
}
}
+3
View File
@@ -448,6 +448,7 @@ pub fn grindstone_experience(
#[derive(Clone, Debug)]
pub enum Smithing {
Transform {
id: String,
template: Ingredient,
base: Ingredient,
addition: Ingredient,
@@ -527,6 +528,7 @@ impl StationRecipes {
);
match v["type"].as_str().unwrap_or("") {
"minecraft:smithing_transform" => smithing.push(Smithing::Transform {
id,
template: ingredient(&v["template"], items),
base: ingredient(&v["base"], items),
addition: ingredient(&v["addition"], items),
@@ -630,6 +632,7 @@ impl StationRecipes {
base: b,
addition: a,
result,
..
} => {
if t.test(template) && b.test(base) && a.test(addition) {
// SmithingTransformRecipe: transmute the base keeping its components.
+113 -9
View File
@@ -175,6 +175,11 @@ pub enum Done {
}
struct Queued {
priority: i64,
/// The column the job is for and what it adds to the column's distance
/// (`Streaming::submit`): the priority is computed again from them when
/// the centre moves (`Streaming::requeue`). None for saves, which go first.
at: Option<(i32, i32)>,
bias: i64,
order: u64,
job: Job,
}
@@ -222,6 +227,9 @@ pub struct Streaming {
/// radius it was last ranked for.
decoration_order: DecorationOrder,
order_area: Option<((i32, i32), i32)>,
/// What the queued jobs' priorities were computed from (`requeue`): the
/// centre, the loading screen, the band, and the extra areas.
queue_basis: (((i32, i32), bool, Option<Band>), Vec<((i32, i32), i32)>),
finishing: FxHashSet<(i32, i32)>,
decorates: bool,
lighting: FxHashMap<(i32, i32), u64>,
@@ -544,6 +552,7 @@ impl Streaming {
saving: 0,
decoration_order: DecorationOrder::default(),
order_area: None,
queue_basis: Default::default(),
finishing: Default::default(),
decorates: generator.decorates(),
lighting: Default::default(),
@@ -648,15 +657,39 @@ impl Streaming {
world.dirty_sections.take_column(x, z);
world.chunks.remove(&(x, z))
}
fn submit(&mut self, priority: i64, job: Job) {
/// Queue a job for the column `at`, nearest first: its distance (`distance`)
/// times four plus `bias`, which orders a column's jobs. A job without a
/// column (a save) goes ahead of every other.
fn submit(&mut self, at: Option<(i32, i32)>, bias: i64, job: Job) {
self.order += 1;
let priority = at.map_or(i64::MIN, |(x, z)| self.distance(x, z) * 4 + bias);
self.shared.queue.lock().unwrap().push(Queued {
priority,
at,
bias,
order: self.order,
job,
});
self.shared.ready.notify_one();
}
/// Rank the queued jobs again when what their priorities were computed
/// from changed: the centre, the extra areas, the band, or the loading
/// screen (ring order, `Ranges::rings`, whose values are far above the
/// distances used after it). Vanilla's chunk task queue follows the
/// current ticket levels in the same way. Without it, generation queued
/// while the loading screen was up waited behind every job queued after
/// it, and with it the decoration of the chunks around the player: at
/// render distance 32 nothing was decorated until every proto chunk had
/// been generated.
fn requeue(&mut self) {
let basis = (self.center, self.loading, self.band);
if self.queue_basis.0 == basis && self.queue_basis.1 == self.extra {
return;
}
self.queue_basis = (basis, self.extra.clone());
let mut queue = self.shared.queue.lock().unwrap();
rank_again(&mut queue, |x, z| self.distance(x, z));
}
fn receive_decorated(&mut self, x: i32, z: i32, region: [Proto; 9]) {
self.generation_scan.exhausted = false;
self.decorating -= 1;
@@ -686,7 +719,7 @@ impl Streaming {
self.saving += 1;
// Ahead of every other job: a column generated again meanwhile
// would not find them saved.
self.submit(i64::MIN, Job::Save(protos));
self.submit(None, 0, Job::Save(protos));
}
}
fn receive_generated(&mut self, mut chunk: Chunk, world: &mut World) {
@@ -829,6 +862,7 @@ impl Streaming {
return (uploads, Vec::new());
}
ExtraCover::refresh(&mut self.cover, &self.extra);
self.requeue();
self.relight_edits(world);
let deferred = std::mem::take(&mut self.deferred);
let received = std::iter::from_fn(|| self.results.try_recv().ok());
@@ -984,7 +1018,7 @@ impl Streaming {
.expect("present proto");
self.finishing.insert((x, z));
self.written.remove(&(x, z));
self.submit(self.distance(x, z) * 4, Job::Finish(proto));
self.submit(Some((x, z)), 0, Job::Finish(proto));
}
}
// Decorate chunks whose 3x3 proto neighbourhood is available, in
@@ -1052,7 +1086,7 @@ impl Streaming {
w.0 = self.decoration_order.rank_or_append(w.2, w.3);
}
wanted.sort_unstable();
for (_, d, x, z) in wanted {
for (_, _, x, z) in wanted {
if self.decorating >= workers * 2 {
break;
}
@@ -1091,7 +1125,7 @@ impl Streaming {
Err(_) => continue,
};
self.decorating += 1;
self.submit(d * 4 + 1, Job::Decorate(x, z, region));
self.submit(Some((x, z)), 1, Job::Decorate(x, z, region));
}
}
self.schedule_generation(world, workers);
@@ -1111,7 +1145,8 @@ impl Streaming {
self.light_snapshots
.insert((x, z), self.light_edit_sequence);
self.submit(
self.distance(x, z) * 4 + 1,
Some((x, z)),
1,
Job::Light(x, z, region, self.sequence, self.sky_light),
);
}
@@ -1183,7 +1218,8 @@ impl Streaming {
self.sequence += 1;
self.meshing.insert((x, sy, z), self.sequence);
self.submit(
self.distance(x, z) * 4 + if first { 2 } else { 0 },
Some((x, z)),
if first { 2 } else { 0 },
Job::Mesh(
x,
sy,
@@ -1222,9 +1258,9 @@ impl Streaming {
loading: self.loading,
};
if let Some(wanted) = self.generation_scan.candidates(input, workers * 3) {
for (d, x, z) in wanted {
for (_, x, z) in wanted {
self.generating.insert((x, z));
self.submit(d * 4, Job::Generate(x, z));
self.submit(Some((x, z)), 0, Job::Generate(x, z));
}
}
}
@@ -1738,10 +1774,78 @@ fn section_indexes(mut bits: u32) -> impl Iterator<Item = i32> {
})
})
}
/// The queued jobs' priorities computed again from each one's column
/// `distance` (`Streaming::submit`).
fn rank_again(queue: &mut BinaryHeap<Queued>, distance: impl Fn(i32, i32) -> i64) {
if queue.is_empty() {
return;
}
let mut jobs = std::mem::take(queue).into_vec();
for job in &mut jobs {
if let Some((x, z)) = job.at {
job.priority = distance(x, z) * 4 + job.bias;
}
}
*queue = BinaryHeap::from(jobs);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn queued_jobs_follow_the_centre_and_the_loading_screen() {
let forced = HashSet::new();
let ranges = |center| Ranges {
center,
radius: 32,
extra: &[],
forced: &forced,
cover: None,
band: None,
};
let generate = |x, z, priority, order| Queued {
priority,
at: Some((x, z)),
bias: 0,
order,
job: Job::Generate(x, z),
};
let loading = ranges((0, 0));
let queued = || {
BinaryHeap::from(vec![
// Queued while the loading screen was up: ring order.
generate(3, 1, loading.priority(3, 1, true) * 4, 1),
// Queued after it closed: plain distances, far below any ring past the first.
generate(20, 0, loading.priority(20, 0, false) * 4, 2),
Queued {
priority: i64::MIN,
at: None,
bias: 0,
order: 3,
job: Job::Save(Vec::new()),
},
])
};
let pops = |mut queue: BinaryHeap<Queued>| {
std::iter::from_fn(move || queue.pop())
.map(|q| q.at)
.collect::<Vec<_>>()
};
assert_eq!(
pops(queued()),
[None, Some((20, 0)), Some((3, 1))],
"the stale order"
);
let mut queue = queued();
rank_again(&mut queue, |x, z| loading.priority(x, z, false));
assert_eq!(pops(queue), [None, Some((3, 1)), Some((20, 0))]);
// The player moved: the job near the new centre goes first.
let mut queue = BinaryHeap::from(vec![generate(3, 1, 0, 1), generate(20, 0, 1, 2)]);
let moved = ranges((19, 0));
rank_again(&mut queue, |x, z| moved.priority(x, z, false));
assert_eq!(queue.pop().and_then(|q| q.at), Some((20, 0)));
}
#[test]
fn view_distance_is_vanillas_shape() {
// ChunkTrackingView.isInViewDistance at render distance 12: a column
+15 -4
View File
@@ -9,7 +9,7 @@ use horizon_world::{
};
use std::{
path::Path,
sync::{Arc, OnceLock},
sync::{Arc, Mutex},
};
/// The `custom_data` key holding an exploration map's search until the game
@@ -114,11 +114,13 @@ pub fn has_pending_map(item: &ItemStack) -> bool {
})
}
static LOOT: OnceLock<Option<Arc<LootData>>> = OnceLock::new();
/// None until `loot_data` runs; `Some(None)` when the tables failed to load.
static LOOT: Mutex<Option<Option<Arc<LootData>>>> = Mutex::new(None);
/// Loot data of the resource root, loaded once per process.
pub fn loot_data(root: &Path) -> Option<Arc<LootData>> {
LOOT.get_or_init(|| match LootData::load(root) {
let mut loot = LOOT.lock().unwrap_or_else(|e| e.into_inner());
loot.get_or_insert_with(|| match LootData::load(root) {
Ok(data) => Some(Arc::new(data)),
Err(e) => {
log::warn!("Horizon: loot tables unavailable, structure containers stay empty: {e}");
@@ -130,7 +132,16 @@ pub fn loot_data(root: &Path) -> Option<Arc<LootData>> {
/// The loot data `loot_data` loaded, if it ran.
pub fn loaded_loot_data() -> Option<Arc<LootData>> {
LOOT.get().cloned().flatten()
LOOT.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
.flatten()
}
/// Let go of the loot data: for a preload no world used
/// (game/world_loading.rs). The next `loot_data` loads it again.
pub fn forget_loot_data() {
*LOOT.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
/// `RandomizableContainer.unpackLootTable` of a container at `pos`: `table`
-729
View File
@@ -1,729 +0,0 @@
//! 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::command::args::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));
}
}
+11 -3
View File
@@ -333,15 +333,23 @@ impl VanillaTerrain {
u64::try_from(self.created.elapsed().as_millis()).unwrap_or(u64::MAX)
}
}
static SHARED_DATA: std::sync::Mutex<Vec<(std::path::PathBuf, Arc<GeneratorData>)>> =
std::sync::Mutex::new(Vec::new());
/// Let go of the bundles `shared_data` loaded: for a preload no world used
/// (game/world_loading.rs). A generator that holds one keeps it.
pub fn forget_shared_data() {
SHARED_DATA
.lock()
.unwrap_or_else(|e| e.into_inner())
.clear();
}
/// The worldgen bundle at `dir`, loaded once and shared by every generator
/// and by live feature placement (sapling growth, bone meal).
pub fn shared_data(
dir: &Path,
registry: &'static BlockRegistry,
) -> crate::Result<Arc<GeneratorData>> {
static CACHE: std::sync::Mutex<Vec<(std::path::PathBuf, Arc<GeneratorData>)>> =
std::sync::Mutex::new(Vec::new());
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
let mut cache = SHARED_DATA.lock().unwrap_or_else(|e| e.into_inner());
if let Some((_, data)) = cache.iter().find(|(path, _)| path == dir) {
return Ok(data.clone());
}