From 0d8249e124ad6e3d945730d7e5ddf18b5507bec8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 07:50:04 +0200 Subject: [PATCH] Leads: a server's clients draw the rope (ClientboundSetEntityLinkPacket) A server never told its clients who holds a mob's lead, so on single player's server thread, a LAN guest's or a dedicated server's client the lead was used up and the mob tied, but no rope showed. The tracker now sends ClientboundSetEntityLinkPacket as vanilla does: in ServerEntity.sendPairingData for a leashed entity, and when the lead is tied or comes off (Leashable.setLeashedTo / dropLeash, the holder 0). The holder is the player the mob sees (a guest, else the host) or a mob; a fence knot isn't an entity on Horizon's server yet. The client sets the mob's holder from it: itself, another player or a mob. lan_e2e's new `leads` check ties and unties a cow on both sides. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/dragon.rs | 1 + crates/horizon-client/src/game/lan.rs | 27 ++++++++++-- .../horizon-client/src/game/lan_entities.rs | 1 + crates/horizon-client/src/game/remote.rs | 13 ++++++ crates/horizon-client/src/lan/entity.rs | 44 ++++++++++++++++++- crates/horizon-client/src/lan/hub.rs | 1 + crates/horizon-client/tests/lan_bot.rs | 1 + crates/horizon-protocol/src/packets/play.rs | 7 +++ tools/lan_e2e.py | 44 ++++++++++++++++++- 9 files changed, 131 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index d5cc5d9bf..c6f5d419b 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2702,6 +2702,7 @@ impl Game<'_> { attributes: Vec::new(), precise: false, needs_sync: false, + leash: None, }) } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index b5d0db5f1..8467b6d3a 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -14,7 +14,7 @@ use horizon_client::{ hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, playerdata, }, - mobs::Mob, + mobs::{Mob, leash::Holder}, text::Text, }; use horizon_core::geometry::Vec3; @@ -774,9 +774,27 @@ impl Game<'_> { } /// The entities guests track: mobs, items and the rest (game/lan_entities.rs). - fn lan_entities(&self, host_entity: Option, hub: &mut Hub, out: &mut States) { + /// `mob_players` is the guest each mob sees as its player (game/lan_mobs.rs). + fn lan_entities( + &self, + host_entity: Option, + mob_players: &HashMap, + hub: &mut Hub, + out: &mut States, + ) { out.clear(); for m in self.mobs.iter().filter(|m| !m.removed) { + // The lead's holder: the player the mob sees (a guest, else the + // host) or another mob. A fence knot isn't an entity here. + let leash = m.extra.leash.and_then(|h| match h { + Holder::Player => mob_players + .get(&m.id) + .and_then(|conn| hub.guest(*conn)) + .map(|g| g.entity_id) + .or(host_entity), + Holder::Mob(id) => Some(id as i32), + Holder::Knot(_) => None, + }); let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str()); e.position = [m.position.x, m.position.y, m.position.z]; (e.yaw, e.pitch, e.head_yaw) = (m.yaw, m.head_pitch, m.head_yaw); @@ -786,6 +804,7 @@ impl Game<'_> { mob_meta(m, hub, &mut e.meta, &mut e.defaults); mob_equipment(m, hub, &mut e.equipment); self.mob_attributes(m, &mut e.attributes); + e.leash = leash; } for d in &self.dropped { let stack = hub.stack(&Some(d.stack.clone())); @@ -847,7 +866,7 @@ impl Game<'_> { .filter_map(|g| Some((g.vehicle?, g.entity_id))) .collect(); self.lan_riding(host_entity, &guests, &mut host.hub.riding); - self.lan_entities(host_entity, &mut host.hub, &mut states); + self.lan_entities(host_entity, &host.mob_players, &mut host.hub, &mut states); } else { states.clear(); } @@ -1035,7 +1054,7 @@ impl Game<'_> { return; } // A dedicated server has no host player. - self.lan_entities(None, &mut host.hub, &mut theirs); + self.lan_entities(None, &host.mob_players, &mut host.hub, &mut theirs); theirs.as_slice() } else { entities diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 6342e921c..f3098408c 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -41,6 +41,7 @@ fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) -> attributes: Vec::new(), precise: false, needs_sync: false, + leash: None, } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 19306efd7..dfde08d7f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1874,6 +1874,19 @@ impl Game<'_> { ); } C::SetPassengers(p) => self.remote_set_passengers(p.vehicle, &p.passengers), + // ClientPacketListener.handleEntityLinkPacket: who holds a mob's + // lead (this player, another player or a mob), for the rope. + C::SetEntityLink(p) => { + let me = self.remote.as_ref().map(|r| r.entity_id); + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.source as u32) { + use horizon_client::mobs::leash::Holder; + m.extra.leash = match p.dest { + 0 => None, + d if Some(d) == me => Some(Holder::Player), + d => Some(Holder::Mob(d as u32)), + }; + } + } C::MoveVehicle(p) => self.remote_move_vehicle(p.position, p.yaw), // ClientPacketListener.handleRotateMob: lerpHeadTo(yHeadRot, 3). C::RotateHead(p) => { diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 9bdb037f7..676fd0adc 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -12,8 +12,8 @@ use horizon_protocol::{ item::Stack, packets::play::{ self, AddEntity, AttributeSnapshot, EntityPositionSync, MoveEntity, MoveEntityPos, - MoveEntityPosRot, MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion, - SetEquipment, SetPassengers, UpdateAttributes, VecDelta, + MoveEntityPosRot, MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityLink, + SetEntityMotion, SetEquipment, SetPassengers, UpdateAttributes, VecDelta, }, }; @@ -65,6 +65,8 @@ pub struct EntityState { pub precise: bool, /// `Entity.needsSync`: send its changes this tick, due or not. pub needs_sync: bool, + /// `Leashable.getLeashHolder`: the entity holding its lead. + pub leash: Option, } impl EntityState { @@ -87,6 +89,7 @@ impl EntityState { self.attributes.clear(); self.precise = false; self.needs_sync = false; + self.leash = None; } } @@ -219,6 +222,8 @@ struct ServerEntity { /// and the first update after it dismounts is a full position sync. passengers: Vec, was_riding: bool, + /// The lead's holder the clients were told of. + leash: Option, /// The level tick it was last seen in, its place in that tick's list, and /// whether it was added in it (its first update is the next tick's). seen: u32, @@ -262,6 +267,7 @@ impl ServerEntity { teleport_delay: 0, passengers: riding.passengers(e.id).to_vec(), was_riding: false, + leash: e.leash, seen: 0, index: 0, added: true, @@ -314,6 +320,13 @@ impl ServerEntity { if let Some(&vehicle) = riding.vehicle.get(&e.id) { out.push(riding.set_passengers(vehicle)); } + // A leashed entity: who holds its lead. + if let Some(dest) = e.leash { + out.push(play::Clientbound::SetEntityLink(SetEntityLink { + source: e.id, + dest, + })); + } } /// Changes since the last update (ServerEntity.sendChanges): movement and @@ -327,6 +340,14 @@ impl ServerEntity { self.passengers.clear(); self.passengers.extend_from_slice(passengers); } + // Leashable.setLeashedTo / dropLeash: sendToTrackingPlayers at once. + if e.leash != self.leash { + out.push(play::Clientbound::SetEntityLink(SetEntityLink { + source: e.id, + dest: e.leash.unwrap_or(0), + })); + self.leash = e.leash; + } // SynchedEntityData.isDirty: once for every client. let dirty = e.meta != self.meta; let due = self.interval != 0 && self.tick.is_multiple_of(self.interval); @@ -868,6 +889,7 @@ mod tests { attributes: Vec::new(), precise: false, needs_sync: false, + leash: None, } } @@ -1132,6 +1154,24 @@ mod tests { assert_eq!(eq.slots, vec![(0, None)]); } + #[test] + fn a_lead_tied_and_untied_reaches_the_clients() { + let link = |out: &[play::Clientbound]| { + out.iter().find_map(|p| match p { + play::Clientbound::SetEntityLink(l) => Some((l.source, l.dest)), + _ => None, + }) + }; + let mut e = state(0.0); + let mut s = added(&e); + changes(&mut s, &e); + e.leash = Some(7); + assert_eq!(link(&changes(&mut s, &e)), Some((e.id, 7))); + assert_eq!(link(&changes(&mut s, &e)), None); + e.leash = None; + assert_eq!(link(&changes(&mut s, &e)), Some((e.id, 0))); + } + /// Two clients at the origin; the chunks they hold. struct Clients { chunks: crate::fast_hash::FxHashSet<(i32, i32)>, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 1330b0ae4..c8f2e980d 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1564,6 +1564,7 @@ impl Hub { attributes, precise: false, needs_sync: false, + leash: None, } } diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 4b8bbc897..fdafcbb68 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -435,6 +435,7 @@ fn guests_see_each_other_and_the_world_entities() { attributes: Vec::new(), precise: false, needs_sync: false, + leash: None, }; let first = thread::spawn(move || { let mut bot = connect(port, "Alex", false)?; diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 24eec6a05..23ba00699 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -671,6 +671,11 @@ packet!(SetCursorItem { item: Option => Slot }); packet!(SetDefaultSpawnPosition { pos: GlobalPos => GlobalPos, yaw: f32 => Float, pitch: f32 => Float }); packet!(SetEntityData { id: i32 => VarInt, values: Vec<(u8, i32, Value)> => EntityData }); packet!(SetEntityMotion { id: i32 => VarInt, velocity: [f64; 3] => LpVec3 }); +packet!( + /// ClientboundSetEntityLinkPacket: the entity holding a leashed entity's + /// lead, 0 when none (Leashable.setDelayedLeashHolderId). + SetEntityLink { source: i32 => Int, dest: i32 => Int } +); packet!( /// ClientboundSetPassengersPacket: a vehicle and every entity riding it. SetPassengers { vehicle: i32 => VarInt, passengers: Vec => List } @@ -1532,6 +1537,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { SetDisplayObjective(SetDisplayObjective) = SET_DISPLAY_OBJECTIVE, SetEntityData(SetEntityData) = SET_ENTITY_DATA, SetEntityMotion(SetEntityMotion) = SET_ENTITY_MOTION, + SetEntityLink(SetEntityLink) = SET_ENTITY_LINK, SetEquipment(SetEquipment) = SET_EQUIPMENT, SetExperience(SetExperience) = SET_EXPERIENCE, SetHealth(SetHealth) = SET_HEALTH, @@ -2263,6 +2269,7 @@ mod tests { vehicle: 2, passengers: vec![3, 300], }), + Clientbound::SetEntityLink(SetEntityLink { source: 2, dest: 0 }), Clientbound::ProjectilePower(ProjectilePower { id: 4, power: 0.1 }), Clientbound::SetEquipment(SetEquipment { id: 2, diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index de8c78dc3..b3dae9ef4 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -29,6 +29,8 @@ address. The script then checks, from both sides, what a guest's game used to ge cow on fire burns and goes out; then the wither's health drops when it is hurt, the sheep is dyed blue with its wool back and the calf grows up (#1367, #1368, #1370, #1371, #1385, #1390); +- leads: the host and the guest each tie a cow to a lead and untie it: the rope shows on both + sides, held by the player who tied it, and goes on both (#1360); - respawn: a player killed is drawn dead by the other side, and alive again once it respawns (the respawned player is a new entity to the others); the host dies, and on the server thread the guest too; @@ -206,7 +208,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -1225,6 +1227,43 @@ def check_looks(host, guest, out): return seen['later']['guest'] +def check_leads(host, guest, out): + spots = apart(host, guest) + result = {} + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + at = (x + 0.5, y, z + 2.5) + + def cow(game): + found = [m for m in game.raw('mobs', 32).get('near', []) if m['kind'] == 'minecraft:cow' + and abs(m['pos'][0] - at[0]) < 1 and abs(m['pos'][2] - at[2]) < 1] + assert found, f'{game.name} sees no cow at {at}' + return found[0] + player('command', command='gamemode survival') + player('command', command=f'summon minecraft:cow {at[0]} {y} {at[2]} {{NoAI:1b}}') + player('command', command='item replace entity @s weapon.mainhand with minecraft:lead') + player.wait(30) + try: + player.raw('look-at', f'{at[0]:.2f}', f'{y + 0.7:.2f}', f'{at[2]:.2f}') + player.raw('mouse', 'right', 'click') + player.wait(20) + tied = {'own': cow(player)['leash'], 'other': cow(other)['leash']} + player.shot(out, 'leads-' + label) + other.shot(out, f'leads-{label}-seen') + # An empty hand unties it (the lead was used up). + player.raw('mouse', 'right', 'click') + player.wait(20) + untied = {'own': cow(player)['leash'], 'other': cow(other)['leash']} + finally: + player('command', command=f'kill @e[type=!minecraft:player,x={at[0]},y={y},z={at[2]},distance=..6]') + player('command', command='clear @s') + result[label] = {'tied': tied, 'untied': untied} + # The other side draws it held by the player who tied it (another player to it). + assert tied['own'] == 'Player' and tied['other'], f"the {label}'s cow on its lead: {tied}" + assert untied == {'own': None, 'other': None}, f"the {label}'s cow untied: {untied}" + return result + + def container_items(game): """The open container's stacks by slot (Horizon's container slots are 300 and up) and its size.""" slots = [s for s in game('screen').get('slots', []) if s.get('slot', 0) >= 300] @@ -3905,7 +3944,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'contacts': check_contacts, 'absorption': check_absorption, 'breath': check_breath, 'lava': check_lava, 'levels': check_levels, 'drops': check_drops, 'underwater': check_underwater, - 'looks': check_looks} + 'looks': check_looks, + 'leads': check_leads} def run(ctl, out, resources, checks):