Merge pull request #1422 from ludovic111/fix/st-leads

🤖 Agent: merged after verify and CI parity passed; each fix has a lan_e2e check (host and guest) passing on the server thread and in-frame (bugs-st-1).
This commit is contained in:
Ludovic Marie
2026-10-23 13:20:40 +02:00
committed by GitHub
9 changed files with 131 additions and 8 deletions
+1
View File
@@ -2702,6 +2702,7 @@ impl Game<'_> {
attributes: Vec::new(),
precise: false,
needs_sync: false,
leash: None,
})
}
}
+23 -4
View File
@@ -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<i32>, 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<i32>,
mob_players: &HashMap<u32, u32>,
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
@@ -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,
}
}
+13
View File
@@ -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) => {
+42 -2
View File
@@ -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<i32>,
}
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<i32>,
was_riding: bool,
/// The lead's holder the clients were told of.
leash: Option<i32>,
/// 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)>,
+1
View File
@@ -1564,6 +1564,7 @@ impl Hub {
attributes,
precise: false,
needs_sync: false,
leash: None,
}
}
+1
View File
@@ -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)?;
@@ -671,6 +671,11 @@ packet!(SetCursorItem { item: Option<Stack> => 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<i32> => List<VarInt> }
@@ -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,
+42 -2
View File
@@ -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):