Merge branch 'parity/server-leftovers' into parity-base
This commit is contained in:
@@ -140,7 +140,7 @@ impl Game<'_> {
|
||||
if self.command_source.is_some_and(|s| s.silent) {
|
||||
return;
|
||||
}
|
||||
self.system_message(message.with_color(text::RED));
|
||||
self.system_message(Text::empty().append(message).with_color(text::RED));
|
||||
}
|
||||
/// sendSuccess honouring `send_command_feedback`.
|
||||
pub(super) fn feedback(&mut self, message: Text) {
|
||||
|
||||
@@ -544,14 +544,14 @@ impl Game<'_> {
|
||||
.take()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(horizon_client::text::Text::plain)
|
||||
.collect::<Vec<String>>()
|
||||
.map(|t| horizon_client::lan::data::component_nbt(&t.component()))
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
for line in lines.unwrap_or_default() {
|
||||
for content in lines.unwrap_or_default() {
|
||||
host.hub.send_to(
|
||||
conn,
|
||||
&C::SystemChat(play::SystemChat {
|
||||
content: literal(&line),
|
||||
content,
|
||||
overlay: false,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
//! A player's advancements on a server (PlayerAdvancements): on the
|
||||
//! player's first tick the `minecraft:tick` criteria are met, the
|
||||
//! advancements they complete grant their recipes (ServerRecipeBook.addRecipes:
|
||||
//! ClientboundRecipeBookAddPacket) and the advancements the player may see go
|
||||
//! out in ClientboundUpdateAdvancementsPacket (PlayerAdvancements.flushDirty).
|
||||
use super::data::{SyncData, json_to_nbt};
|
||||
use crate::{advancements::Tree, recipe_book::RecipeIndex};
|
||||
use horizon_protocol::buf::Writer;
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
pub struct ServerAdvancements {
|
||||
tree: Tree,
|
||||
kids: Vec<Vec<usize>>,
|
||||
layout: Vec<Option<(i32, f32)>>,
|
||||
/// Recipe files by id.
|
||||
recipes: BTreeMap<String, Value>,
|
||||
displays: RecipeIndex,
|
||||
/// RecipeManager.unpackRecipeInfo's group numbers.
|
||||
groups: HashMap<String, i32>,
|
||||
}
|
||||
|
||||
/// What the first tick sends: ClientboundRecipeBookAddPacket's payload (when
|
||||
/// recipes were unlocked) and ClientboundUpdateAdvancementsPacket's.
|
||||
pub struct FirstTick {
|
||||
pub recipe_book_add: Option<Vec<u8>>,
|
||||
pub update_advancements: Vec<u8>,
|
||||
}
|
||||
|
||||
impl ServerAdvancements {
|
||||
pub fn load(resources: &Path) -> Self {
|
||||
let tree = Tree::load(&resources.join("data"));
|
||||
let kids = tree.children();
|
||||
let layout = tree.layout();
|
||||
let mut recipes = BTreeMap::new();
|
||||
super::recipes::recipes(&resources.join("data/minecraft/recipe"), "", &mut recipes);
|
||||
let mut groups = HashMap::new();
|
||||
for r in recipes.values() {
|
||||
if let Some(g) = r["group"].as_str().filter(|g| !g.is_empty()) {
|
||||
let next = groups.len() as i32;
|
||||
groups.entry(g.to_owned()).or_insert(next);
|
||||
}
|
||||
}
|
||||
Self {
|
||||
tree,
|
||||
kids,
|
||||
layout,
|
||||
recipes,
|
||||
displays: RecipeIndex::load(resources),
|
||||
groups,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first tick of a player without advancements.
|
||||
pub fn first_tick(&self, sync: &SyncData, now_millis: i64) -> FirstTick {
|
||||
// CriteriaTriggers.TICK: the criteria it meets, and what they complete.
|
||||
let mut obtained: Vec<Vec<&str>> = vec![Vec::new(); self.tree.list.len()];
|
||||
for (i, a) in self.tree.list.iter().enumerate() {
|
||||
for c in &a.criteria {
|
||||
if c.trigger == "minecraft:tick" && c.conditions.is_null() {
|
||||
obtained[i].push(&c.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
let done: Vec<bool> = self
|
||||
.tree
|
||||
.list
|
||||
.iter()
|
||||
.zip(&obtained)
|
||||
.map(|(a, got)| {
|
||||
!a.requirements.is_empty()
|
||||
&& a.requirements
|
||||
.iter()
|
||||
.all(|group| group.iter().any(|c| got.contains(&c.as_str())))
|
||||
})
|
||||
.collect();
|
||||
// AdvancementRewards.grant: the recipes, in the advancements' order.
|
||||
let mut entries = Vec::new();
|
||||
for (i, a) in self.tree.list.iter().enumerate() {
|
||||
if !done[i] {
|
||||
continue;
|
||||
}
|
||||
for id in &a.rewards.recipes {
|
||||
entries.extend(self.book_entries(id, sync));
|
||||
}
|
||||
}
|
||||
let recipe_book_add = (!entries.is_empty()).then(|| {
|
||||
let mut w = Writer::new();
|
||||
w.varint(entries.len() as i32);
|
||||
for e in entries {
|
||||
w.data.extend(e);
|
||||
}
|
||||
w.bool(false); // not a replacement
|
||||
w.data
|
||||
});
|
||||
// flushDirty: every advancement the player may see, and its progress.
|
||||
let visible = self.tree.visible(&self.kids, |i| done[i]);
|
||||
let shown: Vec<usize> = (0..self.tree.list.len()).filter(|i| visible[*i]).collect();
|
||||
let mut w = Writer::new();
|
||||
w.bool(true); // the first packet resets the client's advancements
|
||||
w.varint(shown.len() as i32);
|
||||
for &i in &shown {
|
||||
let a = &self.tree.list[i];
|
||||
w.string(&a.id);
|
||||
w.bool(a.parent.is_some());
|
||||
if let Some(p) = &a.parent {
|
||||
w.string(p);
|
||||
}
|
||||
w.bool(a.display.is_some());
|
||||
if let Some(d) = &a.display {
|
||||
w.nbt(&json_to_nbt(&d.title));
|
||||
w.nbt(&json_to_nbt(&d.description));
|
||||
w.varint(sync.id("minecraft:item", &d.icon).unwrap_or(0));
|
||||
w.varint(1);
|
||||
w.varint(0);
|
||||
w.varint(0);
|
||||
w.varint(match d.frame {
|
||||
crate::advancements::Frame::Task => 0,
|
||||
crate::advancements::Frame::Challenge => 1,
|
||||
crate::advancements::Frame::Goal => 2,
|
||||
});
|
||||
w.i32(
|
||||
i32::from(d.background.is_some())
|
||||
| i32::from(d.show_toast) << 1
|
||||
| i32::from(d.hidden) << 2,
|
||||
);
|
||||
if let Some(b) = &d.background {
|
||||
w.string(b);
|
||||
}
|
||||
}
|
||||
w.varint(a.requirements.len() as i32);
|
||||
for group in &a.requirements {
|
||||
w.varint(group.len() as i32);
|
||||
for c in group {
|
||||
w.string(c);
|
||||
}
|
||||
}
|
||||
w.bool(false); // sends_telemetry_event
|
||||
let (x, y) = self.layout[i].unwrap_or((0, 0.0));
|
||||
w.f32(x as f32);
|
||||
w.f32(y);
|
||||
}
|
||||
w.varint(0); // nothing removed
|
||||
w.varint(shown.len() as i32);
|
||||
for &i in &shown {
|
||||
let a = &self.tree.list[i];
|
||||
w.string(&a.id);
|
||||
w.varint(a.criteria.len() as i32);
|
||||
for c in &a.criteria {
|
||||
w.string(&c.name);
|
||||
let got = obtained[i].contains(&c.name.as_str());
|
||||
w.bool(got);
|
||||
if got {
|
||||
w.i64(now_millis);
|
||||
}
|
||||
}
|
||||
}
|
||||
w.bool(true); // show the advancements
|
||||
FirstTick {
|
||||
recipe_book_add,
|
||||
update_advancements: w.data,
|
||||
}
|
||||
}
|
||||
|
||||
/// ClientboundRecipeBookAddPacket.Entry for each display of a recipe:
|
||||
/// highlighted, and with a notification unless the recipe turns it off.
|
||||
fn book_entries(&self, id: &str, sync: &SyncData) -> Vec<Vec<u8>> {
|
||||
let Some(r) = self.recipes.get(id) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let ids = self.displays.display_ids(id);
|
||||
if ids.len() != 1 {
|
||||
// Special recipes have no display; transmutations aren't unlocked on joining.
|
||||
return Vec::new();
|
||||
}
|
||||
let kind = r["type"].as_str().unwrap_or("");
|
||||
let item = |n: &str| sync.id("minecraft:item", n).unwrap_or(0);
|
||||
let slot = |n: &str| sync.id("minecraft:slot_display", n).unwrap_or(0);
|
||||
let mut w = Writer::new();
|
||||
w.varint(ids.start);
|
||||
let (ingredients, category): (Vec<Option<&Value>>, &str) = match kind {
|
||||
"minecraft:crafting_shaped" => {
|
||||
let pattern = shrink(r["pattern"].as_array().map_or(&[][..], |p| p));
|
||||
let (width, height) = (pattern.first().map_or(0, Vec::len), pattern.len());
|
||||
w.varint(sync.id("minecraft:recipe_display", kind).unwrap_or(0));
|
||||
w.varint(width as i32);
|
||||
w.varint(height as i32);
|
||||
let cells: Vec<Option<&Value>> = pattern
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|c| (*c != ' ').then(|| &r["key"][c.to_string()]))
|
||||
.collect();
|
||||
(cells, "misc")
|
||||
}
|
||||
"minecraft:crafting_shapeless" => {
|
||||
w.varint(sync.id("minecraft:recipe_display", kind).unwrap_or(0));
|
||||
let cells = r["ingredients"]
|
||||
.as_array()
|
||||
.map_or(Vec::new(), |a| a.iter().map(Some).collect());
|
||||
(cells, "misc")
|
||||
}
|
||||
_ => return Vec::new(),
|
||||
};
|
||||
// ShapedCraftingRecipeDisplay / ShapelessCraftingRecipeDisplay:
|
||||
// the ingredients' TagSlotDisplays, the result, the crafting table.
|
||||
w.varint(ingredients.len() as i32);
|
||||
for cell in &ingredients {
|
||||
match cell {
|
||||
Some(v) => {
|
||||
w.varint(slot("minecraft:tag"));
|
||||
holder_set(&mut w, v, &item);
|
||||
}
|
||||
None => w.varint(slot("minecraft:empty")),
|
||||
}
|
||||
}
|
||||
w.varint(slot("minecraft:item_stack"));
|
||||
w.varint(item(r["result"]["id"].as_str().unwrap_or("minecraft:air")));
|
||||
w.varint(r["result"]["count"].as_i64().unwrap_or(1) as i32);
|
||||
w.varint(0);
|
||||
w.varint(0);
|
||||
w.varint(slot("minecraft:item"));
|
||||
w.varint(item("minecraft:crafting_table"));
|
||||
// The group, the recipe book category and the placement's ingredients.
|
||||
match r["group"].as_str().and_then(|g| self.groups.get(g)) {
|
||||
Some(g) => w.varint(g + 1),
|
||||
None => w.varint(0),
|
||||
}
|
||||
let category = format!(
|
||||
"minecraft:crafting_{}",
|
||||
match r["category"].as_str().unwrap_or(category) {
|
||||
"building" => "building_blocks",
|
||||
c => c,
|
||||
}
|
||||
);
|
||||
w.varint(
|
||||
sync.id("minecraft:recipe_book_category", &category)
|
||||
.unwrap_or(0),
|
||||
);
|
||||
let placed: Vec<&Value> = ingredients.iter().flatten().copied().collect();
|
||||
w.bool(true);
|
||||
w.varint(placed.len() as i32);
|
||||
for v in placed {
|
||||
holder_set(&mut w, v, &item);
|
||||
}
|
||||
let notify = r["show_notification"].as_bool().unwrap_or(true);
|
||||
w.i8(i8::from(notify) | 2);
|
||||
vec![w.data]
|
||||
}
|
||||
}
|
||||
|
||||
/// ShapedRecipePattern.shrink: the pattern without blank border rows and columns.
|
||||
fn shrink(rows: &[Value]) -> Vec<Vec<char>> {
|
||||
let rows: Vec<Vec<char>> = rows
|
||||
.iter()
|
||||
.map(|r| r.as_str().unwrap_or("").chars().collect())
|
||||
.collect();
|
||||
let used = |r: &Vec<char>| r.iter().any(|c| *c != ' ');
|
||||
let (Some(top), Some(bottom)) = (rows.iter().position(used), rows.iter().rposition(used))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let rows = &rows[top..=bottom];
|
||||
let left = rows
|
||||
.iter()
|
||||
.filter_map(|r| r.iter().position(|c| *c != ' '))
|
||||
.min()
|
||||
.unwrap_or(0);
|
||||
let right = rows
|
||||
.iter()
|
||||
.filter_map(|r| r.iter().rposition(|c| *c != ' '))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
rows.iter()
|
||||
.map(|r| {
|
||||
(left..=right)
|
||||
.map(|x| r.get(x).copied().unwrap_or(' '))
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// ByteBufCodecs.holderSet for an ingredient: a tag by name, or the items.
|
||||
fn holder_set(w: &mut Writer, v: &Value, item: &dyn Fn(&str) -> i32) {
|
||||
match v {
|
||||
Value::String(s) if s.starts_with('#') => {
|
||||
w.varint(0);
|
||||
w.string(&s[1..]);
|
||||
}
|
||||
Value::String(s) => {
|
||||
w.varint(2);
|
||||
w.varint(item(s));
|
||||
}
|
||||
Value::Array(a) => {
|
||||
w.varint(a.len() as i32 + 1);
|
||||
for s in a {
|
||||
w.varint(item(s.as_str().unwrap_or("")));
|
||||
}
|
||||
}
|
||||
_ => w.varint(1),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,892 @@
|
||||
//! The order of the children of each node of vanilla's command tree
|
||||
//! (path of node names from the root, children in registration order),
|
||||
//! for nodes with several children. Generated by
|
||||
//! tools/generate_lan_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 ban-ip banlist ban deop op pardon pardon-ip perf save-all save-off save-on setidletimeout stop transfer whitelist publish unpublish",
|
||||
),
|
||||
("advancement", "grant revoke"),
|
||||
(
|
||||
"advancement grant targets",
|
||||
"only from until through everything",
|
||||
),
|
||||
(
|
||||
"advancement revoke targets",
|
||||
"only from until through everything",
|
||||
),
|
||||
("attribute target attribute", "get base modifier"),
|
||||
("attribute target attribute base", "set get reset"),
|
||||
("attribute target attribute modifier", "add remove value"),
|
||||
(
|
||||
"attribute target attribute modifier add id value",
|
||||
"add_value add_multiplied_base add_multiplied_total",
|
||||
),
|
||||
(
|
||||
"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 if score target targetObjective",
|
||||
"= < <= > >= matches",
|
||||
),
|
||||
("execute if blocks start end destination", "all masked"),
|
||||
("execute if data", "entity block storage"),
|
||||
("execute if items", "entity block"),
|
||||
("execute if slots", "entity block"),
|
||||
(
|
||||
"execute unless",
|
||||
"block biome loaded dimension score blocks entity predicate function stopwatch data items slots",
|
||||
),
|
||||
(
|
||||
"execute unless score target targetObjective",
|
||||
"= < <= > >= matches",
|
||||
),
|
||||
("execute unless blocks start end destination", "all masked"),
|
||||
("execute unless data", "entity block storage"),
|
||||
("execute unless items", "entity block"),
|
||||
("execute unless slots", "entity block"),
|
||||
("execute store", "result success"),
|
||||
("execute store result", "score bossbar entity block storage"),
|
||||
("execute store result bossbar id", "value max"),
|
||||
(
|
||||
"execute store result entity target path",
|
||||
"int float short long double byte",
|
||||
),
|
||||
(
|
||||
"execute store result block target path",
|
||||
"int float short long double byte",
|
||||
),
|
||||
(
|
||||
"execute store result storage target path",
|
||||
"int float short long double byte",
|
||||
),
|
||||
(
|
||||
"execute store success",
|
||||
"score bossbar entity block storage",
|
||||
),
|
||||
("execute store success bossbar id", "value max"),
|
||||
(
|
||||
"execute store success entity target path",
|
||||
"int float short long double byte",
|
||||
),
|
||||
(
|
||||
"execute store success block target path",
|
||||
"int float short long double byte",
|
||||
),
|
||||
(
|
||||
"execute store success storage target path",
|
||||
"int float short long double byte",
|
||||
),
|
||||
("execute positioned", "pos as over"),
|
||||
("execute rotated", "rot as"),
|
||||
("execute facing", "entity pos"),
|
||||
(
|
||||
"execute on",
|
||||
"owner leasher target attacker vehicle controller origin passengers",
|
||||
),
|
||||
("bossbar", "add remove list set get"),
|
||||
(
|
||||
"bossbar set id",
|
||||
"name color style value max visible players",
|
||||
),
|
||||
(
|
||||
"bossbar set id color",
|
||||
"pink blue red green yellow purple white",
|
||||
),
|
||||
(
|
||||
"bossbar set id style",
|
||||
"progress notched_6 notched_10 notched_12 notched_20",
|
||||
),
|
||||
("bossbar get id", "value max visible players"),
|
||||
("clone", "begin from"),
|
||||
("clone begin end", "destination to"),
|
||||
(
|
||||
"clone begin end destination",
|
||||
"replace masked filtered strict",
|
||||
),
|
||||
("clone begin end destination replace", "force move normal"),
|
||||
("clone begin end destination masked", "force move normal"),
|
||||
(
|
||||
"clone begin end destination filtered filter",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone begin end destination strict",
|
||||
"replace masked filtered",
|
||||
),
|
||||
(
|
||||
"clone begin end destination strict replace",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone begin end destination strict masked",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone begin end destination strict filtered filter",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone begin end to targetDimension destination",
|
||||
"replace masked filtered strict",
|
||||
),
|
||||
(
|
||||
"clone begin end to targetDimension destination replace",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone begin end to targetDimension destination masked",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone begin end to targetDimension destination filtered filter",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone begin end to targetDimension destination strict",
|
||||
"replace masked filtered",
|
||||
),
|
||||
(
|
||||
"clone begin end to targetDimension destination strict replace",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone begin end to targetDimension destination strict masked",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone begin end to targetDimension destination strict filtered filter",
|
||||
"force move normal",
|
||||
),
|
||||
("clone from sourceDimension begin end", "destination to"),
|
||||
(
|
||||
"clone from sourceDimension begin end destination",
|
||||
"replace masked filtered strict",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end destination replace",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end destination masked",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end destination filtered filter",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end destination strict",
|
||||
"replace masked filtered",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end destination strict replace",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end destination strict masked",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end destination strict filtered filter",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end to targetDimension destination",
|
||||
"replace masked filtered strict",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end to targetDimension destination replace",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end to targetDimension destination masked",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end to targetDimension destination filtered filter",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end to targetDimension destination strict",
|
||||
"replace masked filtered",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end to targetDimension destination strict replace",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end to targetDimension destination strict masked",
|
||||
"force move normal",
|
||||
),
|
||||
(
|
||||
"clone from sourceDimension begin end to targetDimension destination strict filtered filter",
|
||||
"force move normal",
|
||||
),
|
||||
("compute", "default block entity"),
|
||||
("compute default", "float integer"),
|
||||
("compute block computePos", "float integer"),
|
||||
("compute entity computeTarget", "float integer"),
|
||||
("damage target amount damageType", "at by"),
|
||||
("data", "merge get remove modify"),
|
||||
("data merge", "entity block storage"),
|
||||
("data get", "entity block storage"),
|
||||
("data remove", "entity block storage"),
|
||||
("data modify", "entity block storage"),
|
||||
(
|
||||
"data modify entity target targetPath",
|
||||
"insert prepend append set merge",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath insert index",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath insert index from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath insert index string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath insert index compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath insert index compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath insert index compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath insert index compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath prepend",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath prepend from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath prepend string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath prepend compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath prepend compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath prepend compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath prepend compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath append",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath append from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath append string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath append compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath append compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath append compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath append compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath set",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath set from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath set string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath set compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath set compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath set compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath set compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath merge",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath merge from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath merge string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath merge compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath merge compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath merge compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify entity target targetPath merge compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath",
|
||||
"insert prepend append set merge",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath insert index",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath insert index from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath insert index string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath insert index compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath insert index compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath insert index compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath insert index compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath prepend",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath prepend from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath prepend string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath prepend compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath prepend compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath prepend compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath prepend compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath append",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath append from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath append string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath append compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath append compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath append compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath append compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath set",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath set from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath set string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath set compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath set compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath set compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath set compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath merge",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath merge from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath merge string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath merge compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath merge compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath merge compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify block target targetPath merge compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath",
|
||||
"insert prepend append set merge",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath insert index",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath insert index from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath insert index string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath insert index compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath insert index compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath insert index compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath insert index compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath prepend",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath prepend from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath prepend string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath prepend compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath prepend compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath prepend compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath prepend compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath append",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath append from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath append string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath append compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath append compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath append compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath append compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath set",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath set from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath set string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath set compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath set compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath set compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath set compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath merge",
|
||||
"from string compute value",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath merge from",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath merge string",
|
||||
"entity block storage",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath merge compute",
|
||||
"default block entity",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath merge compute default",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath merge compute block computePos",
|
||||
"float integer",
|
||||
),
|
||||
(
|
||||
"data modify storage target targetPath merge compute entity computeTarget",
|
||||
"float integer",
|
||||
),
|
||||
("datapack", "enable disable list create"),
|
||||
("datapack enable name", "after before last first"),
|
||||
("datapack list", "available enabled"),
|
||||
("debug", "start stop function"),
|
||||
("dialog", "show clear"),
|
||||
("difficulty", "peaceful easy normal hard"),
|
||||
("effect", "clear give"),
|
||||
("effect give targets effect", "seconds infinite"),
|
||||
("experience", "add set query"),
|
||||
("experience add target amount", "points levels"),
|
||||
("experience set target amount", "points levels"),
|
||||
("experience query target", "points levels"),
|
||||
(
|
||||
"fill from to block",
|
||||
"outline hollow destroy strict replace keep",
|
||||
),
|
||||
(
|
||||
"fill from to block replace filter",
|
||||
"outline hollow destroy strict",
|
||||
),
|
||||
("forceload", "add remove query"),
|
||||
("forceload remove", "from all"),
|
||||
("function name", "arguments with"),
|
||||
("function name with", "entity block storage"),
|
||||
("item", "replace fill override modify"),
|
||||
("item replace", "entity block"),
|
||||
("item replace entity target slots", "from with"),
|
||||
("item replace entity target slots from", "entity block"),
|
||||
("item replace block target slots", "from with"),
|
||||
("item replace block target slots from", "entity block"),
|
||||
("item fill", "entity block"),
|
||||
("item fill entity target slots", "from with"),
|
||||
("item fill entity target slots from", "entity block"),
|
||||
("item fill block target slots", "from with"),
|
||||
("item fill block target slots from", "entity block"),
|
||||
("item override", "entity block"),
|
||||
("item override entity target slots", "from with"),
|
||||
("item override entity target slots from", "entity block"),
|
||||
("item override block target slots", "from with"),
|
||||
("item override block target slots from", "entity block"),
|
||||
("item modify", "entity block"),
|
||||
("locate", "structure biome poi"),
|
||||
("loot", "replace insert give spawn"),
|
||||
("loot replace", "entity block"),
|
||||
(
|
||||
"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 kill mine",
|
||||
),
|
||||
(
|
||||
"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 kill mine",
|
||||
),
|
||||
(
|
||||
"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 kill mine"),
|
||||
(
|
||||
"loot insert targetPos fish loot_table pos",
|
||||
"tool mainhand offhand",
|
||||
),
|
||||
("loot insert targetPos mine pos", "tool mainhand offhand"),
|
||||
("loot give players", "fish loot kill mine"),
|
||||
(
|
||||
"loot give players fish loot_table pos",
|
||||
"tool mainhand offhand",
|
||||
),
|
||||
("loot give players mine pos", "tool mainhand offhand"),
|
||||
("loot spawn targetPos", "fish loot kill mine"),
|
||||
(
|
||||
"loot spawn targetPos fish loot_table pos",
|
||||
"tool mainhand offhand",
|
||||
),
|
||||
("loot spawn targetPos mine pos", "tool mainhand offhand"),
|
||||
("swing targets", "mainhand offhand"),
|
||||
("particle name pos delta speed count", "force normal"),
|
||||
("place", "feature jigsaw structure template"),
|
||||
(
|
||||
"playsound sound",
|
||||
"master music record weather block hostile neutral player ambient voice ui",
|
||||
),
|
||||
("posteffect", "add clear list remove"),
|
||||
("random", "value roll reset"),
|
||||
("random reset", "* sequence"),
|
||||
("recipe", "give take"),
|
||||
("recipe give targets", "recipe *"),
|
||||
("recipe take targets", "recipe *"),
|
||||
("fetchprofile", "name id entity"),
|
||||
("return", "value fail run"),
|
||||
("ride target", "mount dismount"),
|
||||
("rotate target", "rotation facing"),
|
||||
("rotate target facing", "entity facingLocation"),
|
||||
("schedule", "function clear"),
|
||||
("schedule function function time", "append replace"),
|
||||
("scoreboard", "objectives players"),
|
||||
("scoreboard objectives", "list add modify remove setdisplay"),
|
||||
(
|
||||
"scoreboard objectives modify objective",
|
||||
"displayname rendertype displayautoupdate numberformat",
|
||||
),
|
||||
(
|
||||
"scoreboard objectives modify objective rendertype",
|
||||
"integer hearts",
|
||||
),
|
||||
(
|
||||
"scoreboard objectives modify objective numberformat",
|
||||
"blank fixed styled",
|
||||
),
|
||||
(
|
||||
"scoreboard players",
|
||||
"list set get add remove reset enable display operation",
|
||||
),
|
||||
("scoreboard players display", "name numberformat"),
|
||||
(
|
||||
"scoreboard players display numberformat targets objective",
|
||||
"blank fixed styled",
|
||||
),
|
||||
("setblock pos block", "destroy keep replace strict"),
|
||||
(
|
||||
"spreadplayers center spreadDistance maxRange",
|
||||
"respectTeams under",
|
||||
),
|
||||
(
|
||||
"stopsound targets",
|
||||
"* master music record weather block hostile neutral player ambient voice ui",
|
||||
),
|
||||
("stopwatch", "create query restart remove"),
|
||||
("tag targets", "add remove list"),
|
||||
("team", "list add remove empty join leave modify"),
|
||||
(
|
||||
"team modify team",
|
||||
"displayName color friendlyFire seeFriendlyInvisibles nametagVisibility deathMessageVisibility collisionRule prefix suffix",
|
||||
),
|
||||
("team modify team color", "reset value"),
|
||||
(
|
||||
"team modify team nametagVisibility",
|
||||
"never hideForOtherTeams hideForOwnTeam always",
|
||||
),
|
||||
(
|
||||
"team modify team deathMessageVisibility",
|
||||
"never hideForOtherTeams hideForOwnTeam always",
|
||||
),
|
||||
(
|
||||
"team modify team collisionRule",
|
||||
"never pushOwnTeam pushOtherTeams always",
|
||||
),
|
||||
("teleport", "location destination targets"),
|
||||
("teleport targets", "location destination"),
|
||||
("teleport targets location", "rotation facing"),
|
||||
("teleport targets location facing", "entity facingLocation"),
|
||||
(
|
||||
"test",
|
||||
"run runmultiple runthese runclosest runthat runfailed verify locate resetclosest resetthese resetthat clearthat clearthese clearall stop pos create",
|
||||
),
|
||||
("test runfailed", "onlyRequiredTests numberOfTimes"),
|
||||
("tick", "query rate step sprint unfreeze freeze"),
|
||||
("tick step", "stop time"),
|
||||
("tick sprint", "stop time"),
|
||||
("time", "set add pause resume rate query of"),
|
||||
("time set", "time timemarker"),
|
||||
("time query", "time timeline gametime"),
|
||||
("time of clock", "set add pause resume rate query"),
|
||||
("time of clock set", "time timemarker"),
|
||||
("time of clock query", "time timeline"),
|
||||
(
|
||||
"title targets",
|
||||
"clear reset title subtitle actionbar times",
|
||||
),
|
||||
("trigger objective", "add set"),
|
||||
("waypoint", "list modify"),
|
||||
("waypoint modify waypoint", "color style"),
|
||||
("waypoint modify waypoint color", "color hex reset"),
|
||||
("waypoint modify waypoint style", "reset set"),
|
||||
("weather", "clear rain thunder"),
|
||||
("worldborder", "add set center damage get warning"),
|
||||
("worldborder damage", "amount buffer"),
|
||||
("worldborder warning", "distance time"),
|
||||
("jfr", "start stop"),
|
||||
("banlist", "ips players"),
|
||||
("perf", "start stop"),
|
||||
("whitelist", "on off list add remove reload"),
|
||||
];
|
||||
@@ -4,8 +4,10 @@
|
||||
//! use and the commands of the server kind (dedicated servers have `op`,
|
||||
//! `ban`, `stop` ...; an integrated server `publish`), numbered breadth first
|
||||
//! as vanilla does, with the argument parsers' network properties and the
|
||||
//! custom suggestion providers (`command_suggestions`).
|
||||
use super::command_suggestions::SUGGESTIONS;
|
||||
//! custom suggestion providers (`command_suggestions`). The report sorts each
|
||||
//! node's children; the tree keeps vanilla's registration order
|
||||
//! (`command_order`).
|
||||
use super::{command_order::ORDER, command_suggestions::SUGGESTIONS};
|
||||
use horizon_protocol::{
|
||||
buf::Writer,
|
||||
packets::play::{CommandNode, Commands},
|
||||
@@ -15,6 +17,7 @@ use serde_json::Value;
|
||||
use std::{
|
||||
collections::{HashMap, VecDeque},
|
||||
path::Path,
|
||||
sync::OnceLock,
|
||||
};
|
||||
|
||||
/// Commands.CommandSelection: registered only on dedicated servers.
|
||||
@@ -107,7 +110,7 @@ impl CommandTree {
|
||||
&mut paths,
|
||||
);
|
||||
// enumerateNodes: breadth first from the root, each node's children
|
||||
// (in name order) then its redirect target.
|
||||
// (in registration order) then its redirect target.
|
||||
let mut ids = vec![None; nodes.len()];
|
||||
let mut order = Vec::new();
|
||||
let mut queue = VecDeque::from([0usize]);
|
||||
@@ -170,6 +173,18 @@ fn fill(
|
||||
};
|
||||
let mut names: Vec<&String> = children.keys().collect();
|
||||
names.sort();
|
||||
// Vanilla's registration order; names it doesn't list (the game rules,
|
||||
// registered in an identity-hashed order) keep the report's.
|
||||
static ORDERS: OnceLock<HashMap<&str, Vec<&str>>> = OnceLock::new();
|
||||
let orders = ORDERS.get_or_init(|| {
|
||||
ORDER
|
||||
.iter()
|
||||
.map(|(path, names)| (*path, names.split(' ').collect()))
|
||||
.collect()
|
||||
});
|
||||
if let Some(order) = orders.get(path.join(" ").as_str()) {
|
||||
names.sort_by_key(|n| order.iter().position(|o| o == n).unwrap_or(order.len()));
|
||||
}
|
||||
for name in names {
|
||||
let child = &children[name];
|
||||
let required =
|
||||
@@ -343,10 +358,11 @@ mod tests {
|
||||
assert_eq!(guest.nodes[2].redirect, Some(1));
|
||||
let op = tree.packet(2, true, &builtin);
|
||||
let names: Vec<_> = op.nodes.iter().map(|n| n.name.as_str()).collect();
|
||||
// The root's children in vanilla's registration order.
|
||||
assert_eq!(
|
||||
names,
|
||||
["", "me", "say", "stop", "tell", "action", "message"]
|
||||
["", "me", "tell", "say", "stop", "action", "message"]
|
||||
);
|
||||
assert!(op.nodes[2].restricted);
|
||||
assert!(op.nodes[3].restricted);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +66,9 @@ pub struct SyncData {
|
||||
pub features: Vec<String>,
|
||||
/// Vanilla's command tree (the commands report), when found.
|
||||
pub commands: Option<super::commands::CommandTree>,
|
||||
/// ClientboundUpdateRecipesPacket's payload.
|
||||
pub recipes: Vec<u8>,
|
||||
pub advancements: super::advancements::ServerAdvancements,
|
||||
}
|
||||
|
||||
/// Every `*.json` under `dir`, as (path without extension relative to dir, value), sorted.
|
||||
@@ -106,6 +109,29 @@ pub fn json_to_nbt(v: &Value) -> Tag {
|
||||
}
|
||||
}
|
||||
|
||||
/// A component's JSON as NbtOps writes it: a list whose elements differ in
|
||||
/// type (translation arguments mixing numbers and components) holds each
|
||||
/// element that isn't a compound wrapped in one under the empty key.
|
||||
pub fn component_nbt(v: &Value) -> Tag {
|
||||
match v {
|
||||
Value::Array(a) => {
|
||||
let kind = |v: &Value| std::mem::discriminant(&json_to_nbt(v));
|
||||
let mixed = a.windows(2).any(|w| kind(&w[0]) != kind(&w[1]));
|
||||
Tag::List(
|
||||
a.iter()
|
||||
.map(|e| match component_nbt(e) {
|
||||
t @ Tag::Compound(_) => t,
|
||||
t if mixed => Tag::compound([("", t)]),
|
||||
t => t,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
Value::Object(o) => Tag::compound(o.iter().map(|(k, v)| (k.as_str(), component_nbt(v)))),
|
||||
other => json_to_nbt(other),
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncData {
|
||||
pub fn load(resources: &Path) -> Result<Self, String> {
|
||||
let builtin = Builtin::find(resources)
|
||||
@@ -129,14 +155,18 @@ impl SyncData {
|
||||
registries.push(((*key).to_owned(), Entries { names, json }));
|
||||
}
|
||||
let tags = Self::load_tags(&root, &builtin, &dynamic);
|
||||
Ok(Self {
|
||||
let mut sync = Self {
|
||||
builtin,
|
||||
dynamic,
|
||||
registries,
|
||||
tags,
|
||||
features: vec!["minecraft:vanilla".to_owned()],
|
||||
commands: super::commands::CommandTree::load(resources),
|
||||
})
|
||||
recipes: Vec::new(),
|
||||
advancements: super::advancements::ServerAdvancements::load(resources),
|
||||
};
|
||||
sync.recipes = super::recipes::update_recipes(resources, &sync);
|
||||
Ok(sync)
|
||||
}
|
||||
|
||||
/// The id of a name in a built-in or synchronized registry.
|
||||
|
||||
@@ -104,8 +104,6 @@ pub struct Hub {
|
||||
last_rate: f32,
|
||||
ticking: (f32, bool),
|
||||
weather: (bool, f32, f32),
|
||||
/// ClientboundUpdateRecipesPacket, when the game provides it.
|
||||
pub recipes: Option<Vec<u8>>,
|
||||
/// Operators and their permission levels (dedicated servers).
|
||||
pub ops: std::collections::HashMap<u128, u8>,
|
||||
chat_type: i32,
|
||||
@@ -193,7 +191,6 @@ impl Hub {
|
||||
last_clock: i64::MIN,
|
||||
last_rate: 0.0,
|
||||
ticking: (20.0, false),
|
||||
recipes: None,
|
||||
ops: Default::default(),
|
||||
weather: (false, 0.0, 0.0),
|
||||
chat_type,
|
||||
@@ -494,9 +491,8 @@ impl Hub {
|
||||
g.send(&C::SetHeldSlot(play::SetHeldSlot {
|
||||
slot: g.selected as i32,
|
||||
}));
|
||||
if let Some(recipes) = &self.recipes {
|
||||
g.sender.send(recipes.clone());
|
||||
}
|
||||
// PlayerList.placeNewPlayer: ClientboundUpdateRecipesPacket.
|
||||
g.send(&raw(ids::UPDATE_RECIPES, self.sync.recipes.clone()));
|
||||
// PlayerList.sendPlayerPermissionLevel, then the recipe book.
|
||||
self.send_permission_level(i);
|
||||
let g = &self.guests[i];
|
||||
@@ -1285,6 +1281,15 @@ impl Hub {
|
||||
id: g.entity_id,
|
||||
values: vec![(9, serializer::FLOAT, Value::Float(g.health))],
|
||||
}));
|
||||
// ServerPlayer.tick's CriteriaTriggers.TICK, then flushDirty.
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_millis() as i64);
|
||||
let first = self.sync.advancements.first_tick(&self.sync, now);
|
||||
if let Some(add) = first.recipe_book_add {
|
||||
g.send(&raw(ids::RECIPE_BOOK_ADD, add));
|
||||
}
|
||||
g.send(&raw(ids::UPDATE_ADVANCEMENTS, first.update_advancements));
|
||||
}
|
||||
let health = {
|
||||
let g = &self.guests[i];
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
//! (`data`). The play state is driven by the game thread (`hub`), which only
|
||||
//! ever exchanges decoded packets with these threads through channels, so a
|
||||
//! world that is not open to the network pays nothing.
|
||||
mod advancements;
|
||||
pub mod chunks;
|
||||
mod command_order;
|
||||
pub mod command_suggestions;
|
||||
pub mod commands;
|
||||
pub mod conn;
|
||||
@@ -16,6 +18,7 @@ pub mod guest;
|
||||
pub mod hub;
|
||||
pub mod menu;
|
||||
pub mod playerdata;
|
||||
mod recipes;
|
||||
pub mod tracking;
|
||||
|
||||
pub use conn::PlayerSender;
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! ClientboundUpdateRecipesPacket: what RecipeManager.finalizeRecipeLoading
|
||||
//! synchronizes, the recipe property sets (the items each furnace, smithing
|
||||
//! table slot and brewing stand slot accepts) and the stonecutter's recipes,
|
||||
//! read from the data pack's recipe files.
|
||||
use super::data::SyncData;
|
||||
use horizon_protocol::buf::Writer;
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
/// RecipeManager.RECIPE_PROPERTY_SETS: each set and the ingredients it takes
|
||||
/// from a recipe of the given type.
|
||||
const PROPERTY_SETS: &[(&str, &str, &[&str])] = &[
|
||||
("smithing_addition", "smithing", &["addition"]),
|
||||
("smithing_base", "smithing", &["base"]),
|
||||
("smithing_template", "smithing", &["template"]),
|
||||
("furnace_input", "minecraft:smelting", &["ingredient"]),
|
||||
("blast_furnace_input", "minecraft:blasting", &["ingredient"]),
|
||||
("smoker_input", "minecraft:smoking", &["ingredient"]),
|
||||
(
|
||||
"campfire_input",
|
||||
"minecraft:campfire_cooking",
|
||||
&["ingredient"],
|
||||
),
|
||||
("brewing_input", "minecraft:brewing", &["input"]),
|
||||
("brewing_reagent", "minecraft:brewing", &["reagent"]),
|
||||
];
|
||||
|
||||
/// An ingredient as its HolderSet: a tag, or the items listed.
|
||||
enum Ingredient {
|
||||
Tag(String),
|
||||
Items(Vec<String>),
|
||||
}
|
||||
|
||||
fn ingredient(v: &Value) -> Option<Ingredient> {
|
||||
match v {
|
||||
Value::String(s) => Some(match s.strip_prefix('#') {
|
||||
Some(tag) => Ingredient::Tag(tag.to_owned()),
|
||||
None => Ingredient::Items(vec![s.clone()]),
|
||||
}),
|
||||
Value::Array(a) => Some(Ingredient::Items(
|
||||
a.iter()
|
||||
.filter_map(|s| s.as_str().map(str::to_owned))
|
||||
.collect(),
|
||||
)),
|
||||
// A brewing slot: the item predicate's `item` ingredient.
|
||||
Value::Object(o) => ingredient(o.get("item")?),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every recipe file, by recipe id (the registry's order).
|
||||
pub(super) fn recipes(dir: &Path, prefix: &str, out: &mut BTreeMap<String, Value>) {
|
||||
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if path.is_dir() {
|
||||
recipes(&path, &format!("{prefix}{name}/"), out);
|
||||
} else if let Some(stem) = name.strip_suffix(".json")
|
||||
&& let Ok(v) = serde_json::from_slice(&std::fs::read(&path).unwrap_or_default())
|
||||
{
|
||||
out.insert(format!("minecraft:{prefix}{stem}"), v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The packet's payload for the vanilla data pack in `resources`.
|
||||
pub fn update_recipes(resources: &Path, sync: &SyncData) -> Vec<u8> {
|
||||
let mut all = BTreeMap::new();
|
||||
recipes(&resources.join("data/minecraft/recipe"), "", &mut all);
|
||||
let tags: BTreeMap<&str, &[i32]> = sync
|
||||
.tags
|
||||
.registries
|
||||
.iter()
|
||||
.filter(|r| r.registry == "minecraft:item")
|
||||
.flat_map(|r| r.tags.iter())
|
||||
.map(|t| (t.name.trim_start_matches("minecraft:"), t.ids.as_slice()))
|
||||
.collect();
|
||||
let item = |name: &str| sync.id("minecraft:item", name).unwrap_or(0);
|
||||
let items = |i: &Ingredient| -> Vec<i32> {
|
||||
match i {
|
||||
Ingredient::Tag(t) => tags
|
||||
.get(t.trim_start_matches("minecraft:"))
|
||||
.map(|ids| ids.to_vec())
|
||||
.unwrap_or_default(),
|
||||
Ingredient::Items(list) => list.iter().map(|n| item(n)).collect(),
|
||||
}
|
||||
};
|
||||
let mut w = Writer::new();
|
||||
w.varint(PROPERTY_SETS.len() as i32);
|
||||
for (key, kind, fields) in PROPERTY_SETS {
|
||||
let mut set = BTreeSet::new();
|
||||
for recipe in all.values() {
|
||||
let t = recipe["type"].as_str().unwrap_or("");
|
||||
let matches = if *kind == "smithing" {
|
||||
t.starts_with("minecraft:smithing_")
|
||||
} else {
|
||||
t == *kind
|
||||
};
|
||||
if matches {
|
||||
for field in *fields {
|
||||
if let Some(i) = ingredient(&recipe[*field]) {
|
||||
set.extend(items(&i));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
w.string(&format!("minecraft:{key}"));
|
||||
w.varint(set.len() as i32);
|
||||
for id in set {
|
||||
w.varint(id);
|
||||
}
|
||||
}
|
||||
// SelectableRecipe.SingleInputSet: each stonecutting recipe's input and
|
||||
// its result as an ItemStackSlotDisplay.
|
||||
let stonecutting: Vec<&Value> = all
|
||||
.values()
|
||||
.filter(|r| r["type"] == "minecraft:stonecutting")
|
||||
.collect();
|
||||
let item_stack = sync
|
||||
.id("minecraft:slot_display", "minecraft:item_stack")
|
||||
.unwrap_or(0);
|
||||
w.varint(stonecutting.len() as i32);
|
||||
for r in stonecutting {
|
||||
match ingredient(&r["ingredient"]) {
|
||||
Some(Ingredient::Tag(t)) => {
|
||||
w.varint(0);
|
||||
w.string(&t);
|
||||
}
|
||||
Some(i) => {
|
||||
let ids = items(&i);
|
||||
w.varint(ids.len() as i32 + 1);
|
||||
for id in ids {
|
||||
w.varint(id);
|
||||
}
|
||||
}
|
||||
None => w.varint(1),
|
||||
}
|
||||
w.varint(item_stack);
|
||||
w.varint(item(r["result"]["id"].as_str().unwrap_or("minecraft:air")));
|
||||
w.varint(r["result"]["count"].as_i64().unwrap_or(1) as i32);
|
||||
w.varint(0); // no components added
|
||||
w.varint(0); // nor removed
|
||||
}
|
||||
w.data
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! 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] = [
|
||||
@@ -86,11 +87,20 @@ pub struct Span {
|
||||
pub text: String,
|
||||
pub style: Style,
|
||||
}
|
||||
/// A run of styled spans.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
/// 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)
|
||||
@@ -111,6 +121,7 @@ impl Text {
|
||||
return Self::default();
|
||||
}
|
||||
Self {
|
||||
source: Some(json!({ "text": text }).into()),
|
||||
spans: vec![Span {
|
||||
text,
|
||||
style: Style::default(),
|
||||
@@ -118,18 +129,21 @@ impl Text {
|
||||
}
|
||||
}
|
||||
pub fn styled(s: impl Into<String>, style: Style) -> Self {
|
||||
let mut t = Self::literal(s);
|
||||
for span in &mut t.spans {
|
||||
span.style = style.clone();
|
||||
}
|
||||
t
|
||||
Self::literal(s).with_style(&style)
|
||||
}
|
||||
pub fn colored(s: impl Into<String>, color: u32) -> Self {
|
||||
Self::styled(s, Style::color(color))
|
||||
}
|
||||
/// Component.translatable(key, args) in the current language.
|
||||
pub fn translate(key: &str, args: &[Text]) -> Self {
|
||||
format_translation(&lang::get(key), args)
|
||||
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 {
|
||||
@@ -137,19 +151,81 @@ impl Text {
|
||||
Self::translate(key, &args)
|
||||
}
|
||||
pub fn append(mut self, other: impl Into<Text>) -> Self {
|
||||
self.spans.extend(other.into().spans);
|
||||
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>) {
|
||||
self.spans.extend(other.into().spans);
|
||||
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.
|
||||
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,
|
||||
}
|
||||
}
|
||||
pub fn with_color(self, color: u32) -> Self {
|
||||
self.with_style(&Style::color(color))
|
||||
}
|
||||
@@ -315,6 +391,53 @@ impl Text {
|
||||
}
|
||||
}
|
||||
|
||||
/// The style fields of a component's JSON.
|
||||
const STYLE_KEYS: [&str; 8] = [
|
||||
"color",
|
||||
"bold",
|
||||
"italic",
|
||||
"underlined",
|
||||
"strikethrough",
|
||||
"obfuscated",
|
||||
"click_event",
|
||||
"hover_event",
|
||||
];
|
||||
/// 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(command) = &style.suggest {
|
||||
out.push((
|
||||
"click_event".to_owned(),
|
||||
json!({ "action": "suggest_command", "command": command }),
|
||||
));
|
||||
}
|
||||
if let Some(hover) = &style.hover {
|
||||
out.push((
|
||||
"hover_event".to_owned(),
|
||||
json!({ "action": "show_text", "value": hover.component() }),
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// TranslatableContents.decomposeTemplate: `%s` takes the next argument,
|
||||
/// `%n$s` a numbered one and `%%` is a percent sign. Malformed templates are
|
||||
/// shown verbatim.
|
||||
|
||||
@@ -62,7 +62,7 @@ import net.minecraft.world.phys.Vec3;
|
||||
* cursor), the parsed nodes and the completion suggestions at the end of the
|
||||
* input. Also exports the registry contents the Rust side needs.
|
||||
*
|
||||
* usage: registries|run OUT_DIR [CORPUS PERMISSION_LEVEL]
|
||||
* usage: registries|tree|run OUT_DIR [CORPUS PERMISSION_LEVEL | SELECTION]
|
||||
*/
|
||||
public final class VanillaCommandParseOracle {
|
||||
static sun.misc.Unsafe unsafe;
|
||||
@@ -141,7 +141,9 @@ public final class VanillaCommandParseOracle {
|
||||
}
|
||||
FeatureFlagSet features = FeatureFlags.VANILLA_SET;
|
||||
CommandBuildContext buildContext = CommandBuildContext.simple(lookup, features);
|
||||
Commands commands = new Commands(Commands.CommandSelection.INTEGRATED, buildContext);
|
||||
// `tree OUT_DIR ALL` exports the tree of every command (dedicated and integrated).
|
||||
var selection = args[0].equals("tree") && args.length > 2 ? Commands.CommandSelection.valueOf(args[2]) : Commands.CommandSelection.INTEGRATED;
|
||||
Commands commands = new Commands(selection, buildContext);
|
||||
CommandDispatcher<CommandSourceStack> dispatcher = commands.getDispatcher();
|
||||
|
||||
if (args[0].equals("tree")) {
|
||||
|
||||
@@ -402,6 +402,8 @@ public final class VanillaProtocolClient {
|
||||
play();
|
||||
}
|
||||
|
||||
private static final String[] REPLIES = {"random value 7..7", "random value x", "trigger nope"};
|
||||
|
||||
private void play() throws Exception {
|
||||
state = "play";
|
||||
GameProtocols.Context context = new GameProtocols.Context() {
|
||||
@@ -511,7 +513,14 @@ public final class VanillaProtocolClient {
|
||||
step = 2;
|
||||
stepAt = now;
|
||||
send(new ServerboundChatCommandPacket("list"));
|
||||
} else if (step == 2 && now - stepAt > 1500) {
|
||||
} else if (step >= 2 && step < 2 + REPLIES.length && now - stepAt > 1500) {
|
||||
// Commands a player without operator rights may run, whose
|
||||
// replies (a failure, a syntax error with its context, a
|
||||
// failure with an argument) are compared component by component.
|
||||
send(new ServerboundChatCommandPacket(REPLIES[step - 2]));
|
||||
step++;
|
||||
stepAt = now;
|
||||
} else if (step == 2 + REPLIES.length && now - stepAt > 1500) {
|
||||
record("play-counts", "chunks " + counts.getOrDefault("minecraft:level_chunk_with_light", 0));
|
||||
return;
|
||||
}
|
||||
@@ -622,23 +631,26 @@ public final class VanillaProtocolClient {
|
||||
return input;
|
||||
}
|
||||
});
|
||||
// Vanilla sends each node's children in registration order, which
|
||||
// its commands report (sorted) does not keep: compared as sets.
|
||||
var lines = new TreeMap<String, String>();
|
||||
// Children in vanilla's registration order, but the game rules', which
|
||||
// GameRuleCommand registers in an identity-hashed order: sorted.
|
||||
var names = new java.util.ArrayList<String>();
|
||||
for (var child : root.getChildren()) {
|
||||
var paths = new java.util.TreeSet<String>();
|
||||
names.add(child.getName());
|
||||
var paths = new java.util.ArrayList<String>();
|
||||
describe(child, "", paths, new java.util.IdentityHashMap<>());
|
||||
lines.put(child.getName(), paths.size() + " " + sha(String.join("\n", paths).getBytes()));
|
||||
record("play-command", child.getName() + " " + paths.size() + " " + sha(String.join("\n", paths).getBytes()));
|
||||
}
|
||||
lines.forEach((k, v) -> record("play-command", k + " " + v));
|
||||
record("play-command-order", String.join(" ", names));
|
||||
}
|
||||
|
||||
private static void describe(com.mojang.brigadier.tree.CommandNode<Object> node, String path, java.util.Set<String> out,
|
||||
private static void describe(com.mojang.brigadier.tree.CommandNode<Object> node, String path, java.util.List<String> out,
|
||||
java.util.IdentityHashMap<Object, Boolean> seen) {
|
||||
String here = path + " " + node.getName() + (node.getCommand() != null ? "*" : "");
|
||||
out.add(here + (node.getRedirect() != null ? " -> " + node.getRedirect().getName() : ""));
|
||||
if (seen.put(node, true) != null) return;
|
||||
for (var child : node.getChildren()) describe(child, here, out, seen);
|
||||
var children = new java.util.ArrayList<>(node.getChildren());
|
||||
if (here.equals(" gamerule")) children.sort(java.util.Comparator.comparing(com.mojang.brigadier.tree.CommandNode::getName));
|
||||
for (var child : children) describe(child, here, out, seen);
|
||||
}
|
||||
|
||||
/** The first play packets: entity ids, seeds and times aside. */
|
||||
@@ -652,8 +664,42 @@ public final class VanillaProtocolClient {
|
||||
return text(r.packet).replaceAll("playerId=-?\\d+", "playerId=_").replaceAll("levels=\\[(ResourceKey\\[[^\\]]*\\](, )?)*\\]", "levels=" + levels);
|
||||
}
|
||||
if (t.equals("minecraft:set_time") || t.equals("minecraft:keep_alive") || t.equals("minecraft:ping")) return "";
|
||||
// The tree is compared below, as sets: the children's order is vanilla's registration order.
|
||||
// The tree is compared below: its node numbering follows the game rules' identity-hashed order.
|
||||
if (t.equals("minecraft:commands")) return "";
|
||||
// Vanilla's hash maps and sets order these per run: compared sorted.
|
||||
if (t.equals("minecraft:update_recipes")) {
|
||||
var p = (net.minecraft.network.protocol.game.ClientboundUpdateRecipesPacket) r.packet;
|
||||
var sets = new TreeMap<String, String>();
|
||||
p.itemSets().forEach((k, v) -> {
|
||||
var items = new java.util.TreeSet<String>();
|
||||
((java.util.Set<?>) field(v, "items")).forEach(h -> items.add(((net.minecraft.core.Holder<?>) h).getRegisteredName()));
|
||||
sets.put(k.identifier().toString(), items.toString());
|
||||
});
|
||||
p.stonecutterRecipes().entries().forEach(e -> record("play-stonecutter", field(e.input(), "values") + " -> " + e.recipe().optionDisplay()));
|
||||
sets.forEach((k, v) -> record("play-property-set", k + " " + v));
|
||||
return "sets=" + sets.size() + " stonecutter=" + p.stonecutterRecipes().entries().size();
|
||||
}
|
||||
if (t.equals("minecraft:update_advancements")) {
|
||||
var p = (net.minecraft.network.protocol.game.ClientboundUpdateAdvancementsPacket) r.packet;
|
||||
var added = new TreeMap<String, String>();
|
||||
for (var a : p.added()) {
|
||||
var adv = a.advancement().value();
|
||||
added.put(a.advancement().id().toString(), adv.parent() + " " + adv.display().map(d -> json(d.title()) + " " + json(d.description())
|
||||
+ " " + d.icon() + " " + d.type() + " " + d.background() + " " + d.showToast() + " " + d.hidden()).orElse("-")
|
||||
+ " " + a.x() + "," + a.y() + " " + adv.requirements().requirements() + " " + adv.sendsTelemetryEvent());
|
||||
}
|
||||
var progress = new TreeMap<String, String>();
|
||||
p.progress().forEach((k, v) -> {
|
||||
var criteria = new TreeMap<String, Boolean>();
|
||||
((Map<?, ?>) field(v, "criteria")).forEach((c, cp) -> criteria.put((String) c,
|
||||
((net.minecraft.advancements.CriterionProgress) cp).isDone()));
|
||||
progress.put(k.toString(), criteria.toString());
|
||||
});
|
||||
added.forEach((k, v) -> record("play-advancement", k + " " + v));
|
||||
return "reset=" + p.shouldReset() + " show=" + p.showAdvancements() + " added=" + added.size()
|
||||
+ " removed=" + new java.util.TreeSet<>(p.removed()) + " progress=" + progress;
|
||||
}
|
||||
if (t.equals("minecraft:recipe_book_add")) return text(r.packet) + " sha=" + sha(r.payload);
|
||||
if (t.equals("minecraft:set_entity_data")) {
|
||||
return text(((net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket) r.packet).packedItems());
|
||||
}
|
||||
@@ -663,4 +709,14 @@ public final class VanillaProtocolClient {
|
||||
}
|
||||
return r.payload.length > 200 ? "sha=" + sha(r.payload) : text(r.packet);
|
||||
}
|
||||
|
||||
private static Object field(Object owner, String name) {
|
||||
try {
|
||||
var f = owner.getClass().getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f.get(owner);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate crates/horizon-client/src/lan/command_order.rs: the order of the
|
||||
children of every node of vanilla's command tree (Commands constructed with
|
||||
CommandSelection.ALL), which the tree sent to players keeps. Brigadier keeps
|
||||
children in registration order; the data generator's commands report, which
|
||||
the sent tree is built from, sorts them.
|
||||
|
||||
python3 tools/generate_lan_command_order.py
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
OUT = lab.ROOT / 'crates/horizon-client/src/lan/command_order.rs'
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / 'lan-command-order'
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(parents=True, exist_ok=True)
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandParseOracle.java'
|
||||
path = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', path,
|
||||
'-d', str(classes), str(oracle)], check=True)
|
||||
subprocess.run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + path,
|
||||
'dev.horizonlab.parity.VanillaCommandParseOracle', 'tree', str(build), 'ALL'],
|
||||
check=True, cwd=build, stdout=subprocess.DEVNULL)
|
||||
tree = json.loads((build / 'tree.json').read_text())
|
||||
rows = []
|
||||
|
||||
def walk(node, path):
|
||||
names = list(node.get('children', {}))
|
||||
# GameRuleCommand registers the rules in an identity-hashed map's
|
||||
# order, which changes from run to run.
|
||||
if len(names) > 1 and path != ['gamerule']:
|
||||
rows.append((' '.join(path), ' '.join(names)))
|
||||
for name in names:
|
||||
walk(node['children'][name], path + [name])
|
||||
|
||||
walk(tree, [])
|
||||
lines = [
|
||||
'//! The order of the children of each node of vanilla\'s command tree',
|
||||
'//! (path of node names from the root, children in registration order),',
|
||||
'//! for nodes with several children. Generated by',
|
||||
'//! tools/generate_lan_command_order.py; do not edit by hand.',
|
||||
'',
|
||||
'pub const ORDER: &[(&str, &str)] = &[',
|
||||
]
|
||||
lines += [f' ("{p}", "{n}"),' for p, n in rows]
|
||||
lines += ['];', '']
|
||||
OUT.write_text('\n'.join(lines))
|
||||
print(f'wrote {len(rows)} nodes to {OUT}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -9,16 +9,19 @@ headless client made of vanilla's own codecs (any byte vanilla would not
|
||||
read is an error), pings each server, joins it in offline mode through
|
||||
login, configuration and play, accepts the spawn teleport, receives the
|
||||
chunks around the spawn (their bytes are compared: the world is loaded from
|
||||
the same files), chats, runs /list and leaves. The console then runs `list`
|
||||
and `say` and `stop`. Compared, all of them exactly:
|
||||
the same files), chats, runs /list and commands that fail (`/random value
|
||||
7..7`, `/random value x`, `/trigger nope`) and leaves. The console then
|
||||
runs `list` and `say` and `stop`. Compared, all of them exactly:
|
||||
|
||||
- the status response (MOTD, players, version, favicon) and the ping;
|
||||
- the legacy (pre-1.7, 0xFE) ping reply;
|
||||
- the login and configuration packets in order (compression, profile,
|
||||
brand, features, known packs, every registry, tags);
|
||||
- the play packets up to the first chunk batch, in order, with entity ids,
|
||||
keep-alive ids and times left out; the chunks sent and their bytes; the
|
||||
replies to the chat message and to /list;
|
||||
keep-alive ids and times left out (the recipe property sets and
|
||||
advancements, which vanilla keeps in hash maps, sorted); the command tree
|
||||
node by node; the chunks sent and their bytes; the replies to the chat
|
||||
message, /list and the failing commands, as text components;
|
||||
- the console lines about the player, the chat, `list`, `say` and `stop`;
|
||||
- the files the servers leave: server.properties (but the date line),
|
||||
eula.txt, ops.json, whitelist.json, banned-players.json, banned-ips.json.
|
||||
@@ -49,29 +52,6 @@ except ImportError:
|
||||
NAME = 'dedicated-server-parity'
|
||||
SEED = 12345
|
||||
PLAYER = 'Tester'
|
||||
# Packets Horizon's server does not send yet, listed rather than compared:
|
||||
# the recipe property sets and stonecutter recipes (ClientboundUpdateRecipes)
|
||||
# and a player's advancements (ClientboundUpdateAdvancements, and the recipe
|
||||
# unlocks their first tick grants). Each is reported on every run.
|
||||
KNOWN_GAPS = {
|
||||
'minecraft:update_recipes': 'ClientboundUpdateRecipesPacket (recipe property sets, stonecutter recipes)',
|
||||
'minecraft:update_advancements': 'ClientboundUpdateAdvancementsPacket (player advancements)',
|
||||
'minecraft:recipe_book_add+': 'recipes unlocked by advancements on the first tick',
|
||||
}
|
||||
|
||||
|
||||
def gap(line):
|
||||
"""The known gap a vanilla play-start line belongs to, if any."""
|
||||
parts = line.split(' ')
|
||||
if len(parts) < 2 or parts[0] != 'play-start':
|
||||
return None
|
||||
if parts[1] in KNOWN_GAPS:
|
||||
return parts[1]
|
||||
if parts[1] == 'minecraft:recipe_book_add' and 'entries=[]' not in line:
|
||||
return 'minecraft:recipe_book_add+'
|
||||
return None
|
||||
|
||||
|
||||
PROPERTIES = {
|
||||
'online-mode': 'false',
|
||||
'white-list': 'false',
|
||||
@@ -390,10 +370,6 @@ def main():
|
||||
(build / f'{label}.txt').write_text('\n'.join(results[label]) + '\n', encoding='utf-8')
|
||||
client_checks = horizon_client_joins(vanilla_server, binary, world, build, results['vanilla'])
|
||||
vanilla, horizon = results['vanilla'], results['horizon']
|
||||
gaps = sorted({gap(l) for l in vanilla if gap(l)})
|
||||
vanilla = [l for l in vanilla if not gap(l)]
|
||||
for g in gaps:
|
||||
print(f'known gap: {KNOWN_GAPS[g]}')
|
||||
errors = [l for l in vanilla + horizon if l.startswith('error')] + [l for l in client_checks if not l.endswith(': ok')]
|
||||
for line in client_checks:
|
||||
print(line)
|
||||
@@ -414,9 +390,10 @@ def main():
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
|
||||
lines=len(vanilla), known_gaps=[KNOWN_GAPS[g] for g in gaps], output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'),
|
||||
scope='Dedicated server seen by a vanilla-codec client: status, legacy ping, login, configuration, play '
|
||||
'start, chunks, chat, /list, console list/say/stop, files written. Offline mode.'))
|
||||
'start (recipes, advancements, command tree), chunks, chat, /list, failing commands\' replies, '
|
||||
'console list/say/stop, files written. Offline mode.'))
|
||||
print(f'dedicated server: {len(vanilla)} transcript lines identical')
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user