From 92209ddeee57823e860fb08430c8f7e857d6b2a8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 23:01:02 +0200 Subject: [PATCH] Trading on the dedicated server, compared with vanilla's test_dedicated_server_parity summons a librarian beside the spawn and the vanilla protocol client right-clicks it: the OpenScreen packet (title as Entity.getDisplayName, UUIDs left out) and the MerchantOffers packet must match vanilla's server. Villagers keep Xp, LastRestock and RestocksToday before their offers are made (vanilla's null offers). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity_nbt.rs | 13 +++-- crates/horizon-client/src/game/lan_trading.rs | 56 ++++++++++++++++++- crates/horizon-client/src/game/trading.rs | 14 +++-- crates/horizon-client/src/merchant.rs | 3 + .../parity/VanillaProtocolClient.java | 39 +++++++++++++ tools/test_dedicated_server_parity.py | 4 ++ 6 files changed, 119 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 03b3030ca..64cbe15ba 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -1256,7 +1256,9 @@ fn villager_data(m: &Mob) -> Tag { } /// `AbstractVillager` "Offers" (`MerchantOffers.CODEC`). fn put_offers(map: &mut Compound, m: &Mob) { - let Some(t) = &m.extra.trade else { return }; + let Some(t) = m.extra.trade.as_ref().filter(|t| !t.unset) else { + return; + }; map.insert("Offers".into(), offers_to_nbt(&t.offers)); } /// `ItemCost.CODEC`: id, count (always written) and the exact components. @@ -1395,11 +1397,14 @@ fn read_villager(m: &mut Mob, tag: &Tag) { if m.species() == crate::mobs::Species::Villager { crate::mobs::villager::read_nbt(m, tag); } - let Some(offers_tag) = tag.get("Offers") else { + let offers_tag = tag.get("Offers"); + let xp = number(tag.get("Xp")).unwrap_or(0) as i32; + if offers_tag.is_none() && xp == 0 && tag.get("LastRestock").is_none() { return; - }; - let offers = offers_from_nbt(offers_tag); + } + let offers = offers_tag.map(offers_from_nbt).unwrap_or_default(); m.extra.trade = Some(Box::new(Trader { + unset: offers_tag.is_none(), xp: number(tag.get("Xp")).unwrap_or(0) as i32, offers, last_restock: number(tag.get("LastRestock")).unwrap_or(0), diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index abad0b693..8b033f8b2 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -54,7 +54,7 @@ impl Game<'_> { state.session.hero = None; state.session.update_special_prices(); } - let title = horizon_protocol::text::literal(&self.merchant_title(&state)); + let title = self.merchant_display_name(&state); let Some(window) = host.hub.open_merchant_window(conn, title) else { self.merchant_closed(&mut state); return; @@ -71,8 +71,62 @@ impl Game<'_> { self.lan_send_merchant_content(host, conn, &mut gm); host.play.entry(conn).or_default().merchant = Some(gm); } + /// `Entity.getDisplayName` of the merchant, the screen's title: its name + /// (custom, else the profession's) with the show_entity hover event and + /// its UUID as insertion. + fn merchant_display_name(&mut self, state: &MerchantState) -> horizon_world::nbt::Tag { + use horizon_world::nbt::Tag; + let s = &state.session; + let (kind, key) = if s.villager { + let p = s.profession.trim_start_matches("minecraft:"); + ( + "minecraft:villager", + format!("entity.minecraft.villager.{p}"), + ) + } else { + ( + "minecraft:wandering_trader", + "entity.minecraft.wandering_trader".to_owned(), + ) + }; + let name = match &state.name { + Some(n) => horizon_protocol::text::literal(n), + None => Tag::compound([("translate", Tag::String(key.as_str().into()))]), + }; + let uuid = state.mob.map_or([0; 4], |id| self.mob_uuid(id)); + let w = uuid.map(|v| v as u32); + let text = format!( + "{:08x}-{:04x}-{:04x}-{:04x}-{:04x}{:08x}", + w[0], + w[1] >> 16, + w[1] & 0xffff, + w[2] >> 16, + w[2] & 0xffff, + w[3] + ); + let mut out = match name.clone() { + Tag::Compound(c) => c, + other => { + let mut c = horizon_world::nbt::Compound::new(); + c.insert("text".into(), other); + c + } + }; + out.insert( + "hover_event".into(), + Tag::compound([ + ("action", Tag::String("show_entity".into())), + ("id", Tag::String(kind.into())), + ("uuid", Tag::IntArray(uuid.to_vec())), + ("name", name), + ]), + ); + out.insert("insertion".into(), Tag::String(text.as_str().into())); + Tag::Compound(out) + } /// The screen title: the custom name, else the profession (the client /// adds the level itself). + #[allow(dead_code)] fn merchant_title(&self, state: &MerchantState) -> String { if let Some(name) = &state.name { return name.clone(); diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 336f439e3..4f9a6e6ec 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -179,7 +179,12 @@ impl Game<'_> { /// `AbstractVillager.getOffers`: generated on first use. pub(super) fn ensure_offers(&mut self, index: usize) { let species = self.mobs[index].species(); - if self.mobs[index].extra.trade.is_none() { + let unset = self.mobs[index] + .extra + .trade + .as_ref() + .is_none_or(|t| t.unset); + if unset { let m = &self.mobs[index]; let variant = format!( "minecraft:{}", @@ -206,10 +211,9 @@ impl Game<'_> { Vec::new() } }; - self.mobs[index].extra.trade = Some(Box::new(merchant::Trader { - offers, - ..Default::default() - })); + let trade = self.mobs[index].extra.trade.get_or_insert_default(); + trade.offers = offers; + trade.unset = false; } } /// `Villager.mobInteract` / `WanderingTrader.mobInteract`: shake the diff --git a/crates/horizon-client/src/merchant.rs b/crates/horizon-client/src/merchant.rs index 936eab0aa..32f7512dc 100644 --- a/crates/horizon-client/src/merchant.rs +++ b/crates/horizon-client/src/merchant.rs @@ -57,6 +57,9 @@ pub struct Trader { pub last_restock: i64, pub restocks_today: i32, pub check_day: i64, + /// The offers are not made yet (vanilla's `offers` is null): they are + /// generated when first asked for, keeping the experience. + pub unset: bool, } impl Trader { fn update_demand(&mut self) { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index d03cab7d3..109f33b66 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -430,6 +430,9 @@ public final class VanillaProtocolClient { long deadline = System.currentTimeMillis() + 90_000; int step = 0; long stepAt = 0; + // The villager the server's console summoned beside the spawn. + int villager = -1; + net.minecraft.world.phys.Vec3 villagerAt = null; while (System.currentTimeMillis() < deadline) { Received r; try { @@ -474,6 +477,28 @@ public final class VanillaProtocolClient { + p.chatType().targetName().map(VanillaProtocolClient::json)); } else if (packet instanceof ClientboundDisguisedChatPacket p && step > 0) { record("play-chat", "disguised " + json(p.message()) + " " + p.chatType().chatType().getRegisteredName()); + } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket p + && p.getType() == net.minecraft.world.entity.EntityTypes.VILLAGER) { + villager = p.getId(); + villagerAt = new net.minecraft.world.phys.Vec3(p.getX(), p.getY(), p.getZ()); + } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundOpenScreenPacket p && step > 0) { + record("play-trade", "open " + p.getContainerId() + " " + + net.minecraft.core.registries.BuiltInRegistries.MENU.getKey(p.getType()) + " " + // The villager's UUID is each server's own. + + json(p.getTitle()).replaceAll("\"uuid\":\\[[^\\]]*\\]", "\"uuid\":\"\"") + .replaceAll("\"insertion\":\"[^\"]*\"", "\"insertion\":\"\"")); + } else if (packet instanceof net.minecraft.network.protocol.game.ClientboundMerchantOffersPacket p && step > 0) { + StringBuilder sb = new StringBuilder("offers " + p.getContainerId() + " " + p.getVillagerLevel() + " " + + p.getVillagerXp() + " " + p.showProgress() + " " + p.canRestock()); + for (var o : p.getOffers()) { + sb.append(" | ").append(o.getItemCostA()).append(' ').append(o.getItemCostB()).append(' ') + .append(net.minecraft.world.item.ItemStack.CODEC.encodeStart( + ParityData.access.createSerializationContext(com.mojang.serialization.JsonOps.INSTANCE), o.getResult()).getOrThrow()) + .append(' ').append(o.isOutOfStock()).append(' ').append(o.getUses()).append(' ').append(o.getMaxUses()) + .append(' ').append(o.getXp()).append(' ').append(o.getSpecialPriceDiff()).append(' ') + .append(Float.floatToRawIntBits(o.getPriceMultiplier())).append(' ').append(o.getDemand()); + } + record("play-trade", sb.toString()); } else if (packet instanceof ClientboundDisconnectPacket p) { record("play", r.type + " " + json(p.reason())); break; @@ -521,6 +546,20 @@ public final class VanillaProtocolClient { step++; stepAt = now; } else if (step == 2 + REPLIES.length && now - stepAt > 1500) { + // Right-click the villager: the trading screen and its offers. + record("play-trade", "villager " + (villager >= 0)); + if (villager >= 0) { + send(new net.minecraft.network.protocol.game.ServerboundInteractPacket(villager, + net.minecraft.world.InteractionHand.MAIN_HAND, new net.minecraft.world.phys.Vec3(0.0, 1.0, 0.0), false)); + } + step++; + stepAt = now; + } else if (step == 3 + REPLIES.length && now - stepAt > 1500) { + send(new net.minecraft.network.protocol.game.ServerboundSelectTradePacket(0)); + step++; + stepAt = now; + } else if (step == 4 + REPLIES.length && now - stepAt > 1500) { + send(new net.minecraft.network.protocol.game.ServerboundContainerClosePacket(1)); record("play-counts", "chunks " + counts.getOrDefault("minecraft:level_chunk_with_light", 0)); return; } diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 3dbbbc7c6..7861b1157 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -240,6 +240,10 @@ def run_side(label, command, directory, client): server = Server(command, directory, label) try: server.wait_for(r'Done \(') + # A librarian beside the spawn for the client to trade with (no AI: + # it stays put; experience keeps its profession). + server.console('summon minecraft:villager ~1 ~ ~ {NoAI:1b,Xp:1,VillagerData:' + '{profession:"minecraft:librarian",level:2,type:"minecraft:plains"}}') port = int(PROPERTIES_PORTS[label]) legacy = legacy_ping(port) client(port, directory.parent / f'{label}-client.txt')