Send recipes, advancements and command replies to players as vanilla does

- ClientboundUpdateRecipesPacket at join: the recipe property sets and the
  stonecutter's recipes, from the data pack (lan/recipes.rs).
- On a player's first tick the minecraft:tick criteria are met: the recipes
  their advancements grant go out in ClientboundRecipeBookAddPacket, then
  ClientboundUpdateAdvancementsPacket with what the player may see
  (lan/advancements.rs).
- Command replies reach remote players as the components vanilla sends:
  Text keeps the Component it was built from (literal, translatable,
  siblings, style), sendFailure wraps the message as vanilla does, and the
  NBT wraps the elements of mixed lists.

The dedicated-server harness drops its known gaps: it compares these
packets (sorted where vanilla's hash maps order them per run) and the
replies to three failing commands, keeps only the first set_time among the
joining packets and turns random ticks off in the generated world.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-13 05:43:51 +02:00
parent e70c38e578
commit 0a2601c33a
11 changed files with 706 additions and 58 deletions
+1 -1
View File
@@ -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),
}
}
+3 -2
View File
@@ -358,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);
}
}
+32 -2
View File
@@ -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.
+11 -6
View File
@@ -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];
+2
View File
@@ -4,6 +4,7 @@
//! (`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;
@@ -17,6 +18,7 @@ pub mod guest;
pub mod hub;
pub mod menu;
pub mod playerdata;
mod recipes;
pub mod tracking;
pub use conn::PlayerSender;
+148
View File
@@ -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
}
+133 -10
View File
@@ -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.
@@ -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() {
@@ -476,7 +478,9 @@ public final class VanillaProtocolClient {
record("play", r.type + " " + json(p.reason()));
break;
}
if (ordered) {
// The clock goes out every second: after the first, where it
// falls among the joining packets is timing.
if (ordered && !(r.type.equals("minecraft:set_time") && counts.get(r.type) > 1)) {
record("play-start", r.type + " " + summary(r));
}
if (packet instanceof net.minecraft.network.protocol.game.ClientboundCommandsPacket p && counts.get(r.type) == 1) {
@@ -506,7 +510,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;
}
@@ -652,6 +663,40 @@ public final class VanillaProtocolClient {
if (t.equals("minecraft:set_time") || t.equals("minecraft:keep_alive") || t.equals("minecraft:ping")) return "";
// 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());
}
@@ -661,4 +706,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);
}
}
}
+11 -31
View File
@@ -9,7 +9,8 @@ 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`
the same files), chats, runs /list, then 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;
@@ -17,8 +18,10 @@ and `say` and `stop`. Compared, all of them exactly:
- 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',
@@ -327,6 +307,10 @@ def main():
server.wait_for(r'Done \(')
server.console('gamerule respawn_radius 0')
server.wait_for(r'respawn_radius', timeout=30)
# No random ticks: which of the chunks around the player have grown
# kelp or spread grass by the time they are sent is timing.
server.console('gamerule random_tick_speed 0')
server.wait_for(r'random_tick_speed', timeout=30)
# Vanilla keeps no spawn chunks: force-load the area the client is
# sent and its neighbours (the console stands at the world spawn) so
# both servers load full chunks instead of finishing proto-chunks.
@@ -355,10 +339,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)
@@ -379,7 +359,7 @@ 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.'))
print(f'dedicated server: {len(vanilla)} transcript lines identical')