Network client: show the server's advancements and statistics

ClientboundUpdateAdvancementsPacket and ClientboundAwardStatsPacket are
new in the protocol crate, and the window applies them as vanilla's client
does:

- ClientAdvancements.update: a reset replaces the tree, added advancements
  join it with their place on the tab (DisplayInfo x, y), removed ones go,
  each changed one takes the progress sent, and one that is done in a
  non-reset update with show set gets its toast. The advancements screen
  lays a server's tree out where the server placed it and shows everything
  it sent.
- handleAwardStats: the counters the server sends, by registry name.
  Opening the statistics screen asks for them (StatsScreen.init's
  REQUEST_STATS).

Joining and leaving a server start from empty advancements and statistics.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-17 07:02:33 +02:00
parent cfcf69f0b9
commit 56a4989560
6 changed files with 432 additions and 6 deletions
@@ -72,6 +72,9 @@ impl Toast {
#[derive(Default)]
pub(super) struct AdvState {
pub(super) tree: Arc<Tree>,
/// `ClientAdvancements`: a server's tree carries each advancement's
/// place on its tab (`DisplayInfo` x, y), in tree order.
pub(super) positions: Option<Vec<(f32, f32)>>,
pub(super) progress: Progress,
pub(super) loaded: bool,
pub(super) toasts: VecDeque<Toast>,
@@ -843,6 +846,110 @@ impl Game<'_> {
}
}
}
impl Game<'_> {
/// `ClientAdvancements.update` (ClientboundUpdateAdvancementsPacket):
/// the server's advancements replace or join the tree, each changed one
/// takes the progress sent, and one just done shows its toast. `icons`
/// are the added advancements' icon items by name.
pub(super) fn remote_advancements(
&mut self,
p: horizon_protocol::packets::play::UpdateAdvancements,
icons: Vec<String>,
) {
use horizon_client::scoreboard::tag_to_json;
let mut list: Vec<adv::Advancement> = Vec::new();
let mut positions: Vec<(f32, f32)> = Vec::new();
if !p.reset {
let old = self.adv.positions.take().unwrap_or_default();
for (i, a) in self.adv.tree.list.iter().enumerate() {
if !p.removed.contains(&a.id) {
list.push(a.clone());
positions.push(old.get(i).copied().unwrap_or((0.0, 0.0)));
}
}
} else {
self.adv.progress = Progress::default();
}
for id in &p.removed {
self.adv.progress.criteria.remove(id);
}
for (a, icon) in p.added.into_iter().zip(icons) {
list.retain(|o| o.id != a.id);
let display = a.display.map(|d| adv::Display {
icon,
title: tag_to_json(&d.title),
description: tag_to_json(&d.description),
frame: match d.frame {
1 => Frame::Challenge,
2 => Frame::Goal,
_ => Frame::Task,
},
background: d.background,
show_toast: d.show_toast,
announce: false,
hidden: d.hidden,
});
let mut criteria: Vec<adv::Criterion> = Vec::new();
for name in a.requirements.iter().flatten() {
if !criteria.iter().any(|c| &c.name == name) {
criteria.push(adv::Criterion {
name: name.clone(),
trigger: String::new(),
conditions: Value::Null,
});
}
}
list.push(adv::Advancement {
id: a.id,
parent: a.parent,
display,
criteria,
requirements: a.requirements,
rewards: Default::default(),
});
positions.push((a.x, a.y));
}
let mut tree = Tree {
list,
..Tree::default()
};
for (i, a) in tree.list.iter().enumerate() {
tree.by_id.insert(a.id.clone(), i);
}
self.ui.registries.advancements = tree.list.iter().map(|a| a.id.clone()).collect();
self.adv.tree = Arc::new(tree);
self.adv.positions = Some(positions);
let tree = self.adv.tree.clone();
for (id, criteria) in p.progress {
let Some(&i) = tree.by_id.get(&id) else {
continue;
};
// The client only shows whether a criterion is obtained, not when.
let obtained: BTreeMap<String, String> = criteria
.into_iter()
.filter(|(_, at)| at.is_some())
.map(|(name, _)| (name, String::new()))
.collect();
self.adv.progress.criteria.insert(id, obtained);
let a = &tree.list[i];
if !p.reset
&& p.show
&& self.adv.progress.done(a)
&& let Some(d) = a.display.as_ref().filter(|d| d.show_toast)
{
self.adv.toasts.push_back(Toast {
icon: d.icon.clone(),
frame: d.frame,
title: text_of(&d.title),
slide: Slide::default(),
recipes: Vec::new(),
changed: false,
last_changed: 0,
});
}
}
}
}
/// A text component from advancement JSON (`translate` or `text`).
pub(super) fn text_of(v: &Value) -> Text {
if let Some(key) = v["translate"].as_str() {
@@ -163,11 +163,18 @@ impl Game<'_> {
}
let tree = self.adv.tree.clone();
let kids = tree.children();
let pos = tree
.layout()
.into_iter()
.map(|p| p.map(|(x, y)| (x * 28, (y * 27.0).floor() as i32)))
.collect();
// A server's advancements come placed (`DisplayInfo` x, y).
let pos = match &self.adv.positions {
Some(server) => server
.iter()
.map(|&(x, y)| Some(((x * 28.0).floor() as i32, (y * 27.0).floor() as i32)))
.collect(),
None => tree
.layout()
.into_iter()
.map(|p| p.map(|(x, y)| (x * 28, (y * 27.0).floor() as i32)))
.collect(),
};
self.adv_ui.cache = Some(Cache { tree, kids, pos });
}
fn adv_done(&self, i: usize) -> bool {
@@ -184,7 +191,12 @@ impl Game<'_> {
};
};
let tree = &c.tree;
let visible = tree.visible(&c.kids, |i| self.adv.progress.done(&tree.list[i]));
// A server sends only what the player may see.
let visible = if self.adv.positions.is_some() {
vec![true; tree.list.len()]
} else {
tree.visible(&c.kids, |i| self.adv.progress.done(&tree.list[i]))
};
// AdvancementTab.create: a displayed root with a background.
let mut tabs: Vec<usize> = (0..tree.list.len())
.filter(|&i| {
+45
View File
@@ -313,6 +313,9 @@ impl Game<'_> {
});
// The level's TickRateManager follows the server's ticking packets.
self.clock = horizon_client::clock::FixedStep::client();
// The player's advancements and statistics are the server's.
self.adv = Default::default();
self.stats = Default::default();
Ok(())
}
@@ -336,6 +339,8 @@ impl Game<'_> {
};
horizon_client::crash::clear_detail("Server");
self.clock = Default::default();
self.adv = Default::default();
self.stats = Default::default();
self.debug_charts.reset();
self.tab_list.reset();
self.score.board = Default::default();
@@ -1718,6 +1723,46 @@ impl Game<'_> {
self.clock.set_frozen(p.frozen);
}
C::TickingStep(p) => self.clock.set_frozen_ticks_to_run(p.steps),
C::UpdateAdvancements(p) => {
let icons = p
.added
.iter()
.map(|a| {
a.display
.as_ref()
.map_or_else(String::new, |d| self.item_name(d.icon.item).to_string())
})
.collect();
self.remote_advancements(p, icons);
}
// handleAwardStats: StatsCounter.setValue for each.
C::AwardStats(p) => {
let Some(r) = self.remote.as_ref() else {
return Ok(());
};
let mut known = Vec::new();
for (ty, value, count) in p.stats {
let Some(ty) = r
.builtin
.get("minecraft:stat_type")
.and_then(|t| t.name(ty))
else {
continue;
};
let values = match ty {
"minecraft:mined" => "minecraft:block",
"minecraft:killed" | "minecraft:killed_by" => "minecraft:entity_type",
"minecraft:custom" => "minecraft:custom_stat",
_ => "minecraft:item",
};
if let Some(key) = r.builtin.get(values).and_then(|v| v.name(value)) {
known.push((ty.to_owned(), key.to_owned(), count));
}
}
for (ty, key, count) in known {
self.stats.values.entry(ty).or_default().insert(key, count);
}
}
C::SetActionBarText(p) | C::SetTitleText(p) => {
let lang = self
.remote
@@ -173,6 +173,12 @@ const FOOTER: f32 = 33.0;
impl Game<'_> {
pub(super) fn open_stats(&mut self) {
self.load_stats();
// StatsScreen.init: a server's client asks for its statistics.
if self.remote.is_some() {
self.send(horizon_protocol::packets::play::Serverbound::ClientCommand(
horizon_protocol::packets::play::ClientCommand { action: 1 },
));
}
self.stats_ui = StatsUi::default();
self.screen = Screen::Stats;
}
+36
View File
@@ -218,6 +218,42 @@ impl Codec<Option<Stack>> for Slot {
}
}
/// ItemStackTemplate.STREAM_CODEC: the item, the count, then the patch.
pub struct Template;
impl Codec<Stack> for Template {
fn read(r: &mut Reader) -> Result<Stack> {
let item = r.varint()?;
let count = r.varint()?;
let positive = r.count(65536)?;
let negative = r.count(65536)?;
let mut added = Vec::with_capacity(positive.min(64));
for _ in 0..positive {
let kind = r.varint()?;
added.push((kind, Component::read(kind, r)?));
}
let removed = (0..negative).map(|_| r.varint()).collect::<Result<_>>()?;
Ok(Stack {
item,
count,
added,
removed,
})
}
fn write(s: &Stack, w: &mut Writer) {
w.varint(s.item);
w.varint(s.count);
w.varint(s.added.len() as i32);
w.varint(s.removed.len() as i32);
for (kind, c) in &s.added {
w.varint(*kind);
c.write(*kind, w);
}
for kind in &s.removed {
w.varint(*kind);
}
}
}
/// HashedStack: what the client believes a slot holds. Component values are
/// sent as hashes; Horizon sends patches without hashes, so a server whose
/// stack carries components resynchronises that slot (as it does for any
+220
View File
@@ -982,10 +982,200 @@ impl Codec<Commands> for Commands {
}
}
/// `DisplayInfo` of an advancement as sent.
#[derive(Clone, Debug, PartialEq)]
pub struct AdvancementDisplay {
pub title: Tag,
pub description: Tag,
pub icon: crate::item::Stack,
/// `AdvancementType` ordinal: task, challenge, goal.
pub frame: i32,
pub show_toast: bool,
pub hidden: bool,
pub background: Option<String>,
}
/// `ClientboundUpdateAdvancementsPacket.PositionedAdvancement`.
#[derive(Clone, Debug, PartialEq)]
pub struct Advancement {
pub id: String,
pub parent: Option<String>,
pub display: Option<AdvancementDisplay>,
pub requirements: Vec<Vec<String>>,
pub telemetry: bool,
pub x: f32,
pub y: f32,
}
/// `ClientboundUpdateAdvancementsPacket`: whether it replaces what the
/// client has, the advancements added and removed, the progress of each
/// changed one (criterion, when obtained in epoch milliseconds), and whether
/// to show toasts.
#[derive(Clone, Debug, PartialEq)]
pub struct UpdateAdvancements {
pub reset: bool,
pub added: Vec<Advancement>,
pub removed: Vec<String>,
pub progress: Vec<(String, Vec<(String, Option<i64>)>)>,
pub show: bool,
}
impl Codec<UpdateAdvancements> for UpdateAdvancements {
fn read(r: &mut Reader) -> Result<Self> {
let reset = r.bool()?;
let n = r.count(r.remaining())?;
let mut added = Vec::with_capacity(n.min(1024));
for _ in 0..n {
let id = r.string(32767)?;
let parent = if r.bool()? {
Some(r.string(32767)?)
} else {
None
};
let display = if r.bool()? {
let title = r.nbt()?;
let description = r.nbt()?;
let icon = crate::item::Template::read(r)?;
let frame = r.varint()?;
let flags = r.i32()?;
let background = if flags & 1 != 0 {
Some(r.string(32767)?)
} else {
None
};
Some(AdvancementDisplay {
title,
description,
icon,
frame,
show_toast: flags & 2 != 0,
hidden: flags & 4 != 0,
background,
})
} else {
None
};
let groups = r.count(r.remaining())?;
let mut requirements = Vec::with_capacity(groups.min(256));
for _ in 0..groups {
let k = r.count(r.remaining())?;
requirements.push((0..k).map(|_| r.string(32767)).collect::<Result<_>>()?);
}
let telemetry = r.bool()?;
let (x, y) = (r.f32()?, r.f32()?);
added.push(Advancement {
id,
parent,
display,
requirements,
telemetry,
x,
y,
});
}
let n = r.count(r.remaining())?;
let removed = (0..n).map(|_| r.string(32767)).collect::<Result<_>>()?;
let n = r.count(r.remaining())?;
let mut progress = Vec::with_capacity(n.min(1024));
for _ in 0..n {
let id = r.string(32767)?;
let k = r.count(r.remaining())?;
let mut criteria = Vec::with_capacity(k.min(256));
for _ in 0..k {
let name = r.string(32767)?;
let at = if r.bool()? { Some(r.i64()?) } else { None };
criteria.push((name, at));
}
progress.push((id, criteria));
}
let show = r.bool()?;
Ok(Self {
reset,
added,
removed,
progress,
show,
})
}
fn write(v: &Self, w: &mut Writer) {
w.bool(v.reset);
w.varint(v.added.len() as i32);
for a in &v.added {
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(&d.title);
w.nbt(&d.description);
crate::item::Template::write(&d.icon, w);
w.varint(d.frame);
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 g in &a.requirements {
w.varint(g.len() as i32);
for c in g {
w.string(c);
}
}
w.bool(a.telemetry);
w.f32(a.x);
w.f32(a.y);
}
w.varint(v.removed.len() as i32);
for id in &v.removed {
w.string(id);
}
w.varint(v.progress.len() as i32);
for (id, criteria) in &v.progress {
w.string(id);
w.varint(criteria.len() as i32);
for (name, at) in criteria {
w.string(name);
w.bool(at.is_some());
if let Some(at) = at {
w.i64(*at);
}
}
}
w.bool(v.show);
}
}
packet!(
/// ClientboundAwardStatsPacket: (stat type, value, count) by network id.
AwardStats { stats: Vec<(i32, i32, i32)> => StatList }
);
/// `Object2IntMap<Stat<?>>`: each stat's type and value ids, then its count.
pub struct StatList;
impl Codec<Vec<(i32, i32, i32)>> for StatList {
fn read(r: &mut Reader) -> Result<Vec<(i32, i32, i32)>> {
let n = r.count(r.remaining())?;
(0..n)
.map(|_| Ok((r.varint()?, r.varint()?, r.varint()?)))
.collect()
}
fn write(v: &Vec<(i32, i32, i32)>, w: &mut Writer) {
w.varint(v.len() as i32);
for &(a, b, c) in v {
w.varint(a);
w.varint(b);
w.varint(c);
}
}
}
packet_enum!(Clientbound, crate::ids::play::clientbound {
BundleDelimiter(Empty) = BUNDLE_DELIMITER,
AddEntity(AddEntity) = ADD_ENTITY,
Animate(Animate) = ANIMATE,
AwardStats(AwardStats) = AWARD_STATS,
BlockChangedAck(BlockChangedAck) = BLOCK_CHANGED_ACK,
BlockDestruction(BlockDestruction) = BLOCK_DESTRUCTION,
BlockEntityData(BlockEntityData) = BLOCK_ENTITY_DATA,
@@ -1072,6 +1262,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
TeleportEntity(TeleportEntity) = TELEPORT_ENTITY,
TickingState(TickingState) = TICKING_STATE,
TickingStep(TickingStep) = TICKING_STEP,
UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS,
UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT,
UpdateTags(UpdateTags) = UPDATE_TAGS,
});
@@ -1538,6 +1729,35 @@ mod tests {
frozen: true,
}),
Clientbound::TickingStep(TickingStep { steps: 7 }),
Clientbound::AwardStats(AwardStats {
stats: vec![(8, 3, 120), (0, 1, 2)],
}),
Clientbound::UpdateAdvancements(UpdateAdvancements {
reset: true,
added: vec![Advancement {
id: "minecraft:story/root".into(),
parent: None,
display: Some(AdvancementDisplay {
title: literal("Minecraft"),
description: literal("The heart and story of the game"),
icon: crate::item::Stack::new(42, 1),
frame: 0,
show_toast: false,
hidden: false,
background: Some("minecraft:block/stone".into()),
}),
requirements: vec![vec!["crafting_table".into()]],
telemetry: false,
x: 0.0,
y: 1.5,
}],
removed: vec!["minecraft:story/gone".into()],
progress: vec![(
"minecraft:story/root".into(),
vec![("crafting_table".into(), Some(1_792_216_800_000))],
)],
show: true,
}),
];
for p in packets {
round_trip(p, Clientbound::encode, Clientbound::decode);