From 28d218b3a2c17ff1b5b373b52b24b8d3000bfd2e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:48:13 +0200 Subject: [PATCH 1/6] Guests: a bed puts the guest to sleep, not the host The bed's sleeping state, timer and respawn point were the host's fields, so a guest clicking a bed put the host to sleep and moved the host's spawn. as_guest now swaps them with the guest's own; the guest gets its sleeping pose and bed (entity data 14), wakes on STOP_SLEEPING with the WAKE_UP animation, and the night skips only once enough players sleep (players_sleeping_percentage). Guests respawn at their own bed, else the world spawn. Server clients lie in the bed from the synced position. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 52 +++++---- crates/horizon-client/src/game/agent.rs | 2 + crates/horizon-client/src/game/lan.rs | 1 + crates/horizon-client/src/game/lan_actions.rs | 106 +++++++++++++++++- crates/horizon-client/src/game/remote.rs | 34 +++++- crates/horizon-client/src/lan/guest.rs | 12 ++ crates/horizon-client/src/lan/hub.rs | 37 +++++- crates/horizon-client/src/lan/playerdata.rs | 2 + tools/lan_e2e.py | 54 ++++++++- 9 files changed, 273 insertions(+), 27 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 238f68e55..5ce509705 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8057,40 +8057,48 @@ impl Game<'_> { self.stats.reset("custom", "minecraft:time_since_rest"); } fn wake_up(&mut self) { + if self.remote.is_some() { + // InBedChatScreen.sendWakeUp: the server wakes the player. + self.remote_stop_sleeping(); + return; + } self.sleeping = None; self.sleep_timer = 100; } fn tick_sleep(&mut self) { self.sleep_timer = tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); - let Some(head) = self.sleeping else { - return; - }; - if self.keys.contains(&KeyCode::ShiftLeft) - || self - .player - .as_ref() - .is_none_or(|p| p.health.dead_or_dying()) - { - self.wake_up(); - return; + if let Some(head) = self.sleeping { + if self.keys.contains(&KeyCode::ShiftLeft) + || self + .player + .as_ref() + .is_none_or(|p| p.health.dead_or_dying()) + { + self.wake_up(); + return; + } + if let Some(p) = self.player.as_mut() { + p.position = Vec3::new( + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ); + p.velocity = Vec3::ZERO; + } } - if let Some(p) = self.player.as_mut() { - p.position = Vec3::new( - f64::from(head[0]) + 0.5, - f64::from(head[1]) + 0.5625, - f64::from(head[2]) + 0.5, - ); - p.velocity = Vec3::ZERO; - } - // ServerLevel: once everyone has slept 100 ticks, skip to morning and clear weather. - if self.sleep_timer >= 100 { + // ServerLevel.tick: once enough of the players have slept 100 ticks, + // skip to morning, clear the weather and wake everyone. + if self.enough_slept() { let t = self.world.day_time; self.world.day_time = t + 24000 - t.rem_euclid(24000); self.world.weather.raining = false; self.world.weather.thundering = false; self.world.weather.rain_time = 0; self.world.weather.thunder_time = 0; - self.wake_up(); + if self.sleeping.is_some() { + self.wake_up(); + } + self.wake_guests(); } } fn creative_origin(batch: &HudBatch) -> (f32, f32) { diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 48b24bbb3..11e4cef07 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -466,6 +466,8 @@ impl Game<'_> { }), "dimension": self.dim.id(), "gamemode": format!("{:?}", self.mode).to_lowercase(), + // The bed (its head) the player sleeps in. + "sleeping": self.sleeping, "time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) }, "weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering }, "paused": self.pause, diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index d574b8928..1c149ba00 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -370,6 +370,7 @@ impl Game<'_> { "loaded": g.loaded, "game_mode": g.game_mode, "sneaking": g.sneaking, + "sleeping": g.bed, "health": g.health, // FoodData: food level, saturation and exhaustion. "food": [ diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 7cd4b0474..380fa09ec 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -163,6 +163,16 @@ impl Game<'_> { self.right = play.using.is_some() || self.using.is_some(); let riding = self.riding.take(); let host_station = self.station.take(); + // The guest's bed, sleep counter and respawn point; the host's + // respawn point, anchor and action bar stay theirs. + let sleeping = std::mem::replace(&mut self.sleeping, g.bed); + let sleep_timer = std::mem::replace(&mut self.sleep_timer, g.sleep_timer); + let spawn = std::mem::replace( + &mut self.spawn, + g.spawn.map(|s| Vec3::new(s[0], s[1], s[2])), + ); + let respawn = (self.respawn_config.take(), self.level.spawn); + let message = self.message.take(); // The guest's own ender inventory; one the host has open goes back // into the host's while the guest acts. let host_ender = self.ender_open; @@ -194,6 +204,12 @@ impl Game<'_> { let opened_table = std::mem::replace(&mut self.craft_size, craft_size) == 3; self.craft_grid = craft_grid; let opened_station = std::mem::replace(&mut self.station, host_station); + let bed = std::mem::replace(&mut self.sleeping, sleeping); + let guest_sleep_timer = std::mem::replace(&mut self.sleep_timer, sleep_timer); + let guest_spawn = std::mem::replace(&mut self.spawn, spawn).map(|s| [s.x, s.y, s.z]); + (self.respawn_config, self.level.spawn) = respawn; + // ServerPlayer.displayClientMessage(_, true): the guest's action bar. + let guest_message = std::mem::replace(&mut self.message, message); self.riding = riding; self.left = left; self.right = right; @@ -211,6 +227,15 @@ impl Game<'_> { self.keys.remove(&KeyCode::ShiftLeft); } let g = &mut host.hub.guests[i]; + let fell_asleep = bed.is_some() && g.bed.is_none(); + (g.bed, g.sleep_timer, g.spawn) = (bed, guest_sleep_timer, guest_spawn); + g.sleeping = g.bed.is_some(); + if let Some((text, _)) = guest_message { + g.send(&C::SystemChat(play::SystemChat { + content: literal(&text), + overlay: true, + })); + } std::mem::swap(&mut self.ender_items, &mut g.ender_items); std::mem::swap(&mut self.adv.progress, &mut g.advancements); std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed); @@ -260,6 +285,19 @@ impl Game<'_> { } } let g = &mut host.hub.guests[i]; + if let Some(head) = g.bed.filter(|_| fell_asleep) { + // LivingEntity.startSleeping: in the bed, still. + let at = [ + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ]; + g.position = at; + if let Some(m) = g.motion.as_mut() { + m.position = Vec3::new(at[0], at[1], at[2]); + m.velocity = Vec3::ZERO; + } + } if new_mode != g.game_mode { let conn = g.conn; host.hub.set_game_mode(conn, new_mode); @@ -903,10 +941,19 @@ impl Game<'_> { } fn guest_respawn(&mut self, host: &mut LanHost, conn: u32) { - let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { return; }; + // The guest's own bed, else the world spawn: never the host's bed. + let world = self + .level + .world_spawn + .map(|[x, y, z]| [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]); + let spawn = host.hub.guests[i] + .spawn + .or(world) + .or(self.spawn.map(|s| [s.x, s.y, s.z])) + .unwrap_or([0.5, 80.0, 0.5]); if !host.hub.guests[i].dead { return; } @@ -964,6 +1011,7 @@ impl Game<'_> { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { continue; }; + self.guest_sleep_tick(host, gi); if host.hub.guests[gi].dead || self.on_server_trip(conn) { continue; } @@ -1029,6 +1077,62 @@ impl Game<'_> { } } + /// `Player.tick`'s sleep counter, and `LivingEntity.tick`'s wake-up of a + /// sleeper who died or whose bed is gone. + fn guest_sleep_tick(&mut self, host: &mut LanHost, gi: usize) { + let g = &mut host.hub.guests[gi]; + g.sleep_timer = super::tick_sleep_timer(g.sleep_timer, g.bed.is_some()); + if let Some(head) = g.bed { + let block = self.world.block(head[0], head[1], head[2]); + let bed = self.res.facts.get(block).name.ends_with("_bed"); + if g.dead || g.health <= 0.0 || !bed { + host.hub.wake(gi); + } + } + } + + /// `SleepStatus.areEnoughSleeping` and `areEnoughDeepSleeping` over the + /// host's player and the guests: of the players not in spectator mode, + /// players_sleeping_percentage of them (at least one) are in bed, and as + /// many have slept 100 ticks. + pub(super) fn enough_slept(&self) -> bool { + let (mut active, mut sleeping, mut deep) = (0i64, 0i64, 0i64); + let mut count = |in_bed: bool, timer: u32| { + active += 1; + if in_bed { + sleeping += 1; + if timer >= 100 { + deep += 1; + } + } + }; + if self.player.is_some() && !self.spectator() { + count(self.sleeping.is_some(), self.sleep_timer); + } + if let Some(host) = self.lan.as_ref() { + for g in host + .hub + .guests + .iter() + .filter(|g| g.placed && !g.spectator()) + { + count(g.bed.is_some(), g.sleep_timer); + } + } + let percent = i64::from(self.ui.rules.int("players_sleeping_percentage").max(0)); + let needed = ((active * percent + 99) / 100).max(1); + sleeping >= needed && deep >= needed + } + + /// `ServerLevel.wakeUpAllPlayers` for the guests. + pub(super) fn wake_guests(&mut self) { + if let Some(host) = self.lan.as_mut() { + for i in 0..host.hub.guests.len() { + host.hub.wake(i); + } + } + } + /// `PlayerList.broadcastSystemMessage` of the advancements guests made /// (their own actions, commands and ticks). fn announce_guest_advancements(&mut self, host: &mut LanHost) { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 05e1f81c3..0a2c987d1 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -760,6 +760,7 @@ impl Game<'_> { 0 => { if me { self.sleeping = None; + self.sleep_timer = 100; } return; } @@ -1271,6 +1272,18 @@ impl Game<'_> { } } } + // LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): this + // player lies down in the bed, or gets up. + if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + for (index, _, value) in &p.values { + if let (14, Value::OptPos(bed)) = (index, value) { + if bed.is_some() && self.sleeping.is_none() { + self.sleep_timer = 0; + } + self.sleeping = *bed; + } + } + } for (index, _, value) in &p.values { if *index == ITEM_ENTITY_ITEM && let Value::Item(stack) = value @@ -2124,6 +2137,8 @@ impl Game<'_> { self.tick_hand(); self.tick_particles(); self.tick_client_effects(); + // Player.tick's sleep counter (the darkening and the wake-up fade). + self.sleep_timer = super::tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); let ghast_collisions = self.happy_ghast_player_collisions(); let Some(player) = self.player.as_mut() else { return Ok(()); @@ -2176,7 +2191,15 @@ impl Game<'_> { ); player.yaw = self.yaw; let dead = self.screen == Screen::Dead; - if !dead { + // LivingEntity.isImmobile: a sleeper lies still in the bed. + if let Some(head) = self.sleeping { + player.position = Vec3::new( + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ); + player.velocity = Vec3::ZERO; + } else if !dead { MotionWorld { entities: &ghast_collisions, player, @@ -3134,6 +3157,15 @@ impl Game<'_> { .ok()?; Some((rows, r.menu_title.clone().unwrap_or_default())) } + /// ServerboundPlayerCommandPacket STOP_SLEEPING. + pub(super) fn remote_stop_sleeping(&mut self) { + let id = self.remote.as_ref().map_or(0, |r| r.entity_id); + self.send(S::PlayerCommand(play::PlayerCommand { + id, + action: 0, + data: 0, + })); + } pub(super) fn remote_respawn(&mut self) { self.send(S::ClientCommand(play::ClientCommand { action: 0 })); } diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index b0ecf772f..a397e8bc3 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -69,6 +69,14 @@ pub struct Guest { pub fall_flying: bool, pub flying: bool, pub sleeping: bool, + /// The bed (its head) the player sleeps in (`LivingEntity.getSleepingPos`), + /// `Player.sleepCounter`, and the bed last told to the player itself. + pub bed: Option<[i32; 3]>, + pub sleep_timer: u32, + pub sent_bed: Option<[i32; 3]>, + /// Where the player respawns (a bed's spot; `ServerPlayer.respawnConfig`), + /// None for the world spawn. + pub spawn: Option<[f64; 3]>, /// Pending ClientboundPlayerPositionPacket id; movement is ignored until /// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient). pub awaiting_teleport: Option<(i32, [f64; 3])>, @@ -201,6 +209,10 @@ impl Guest { fall_flying: false, flying: false, sleeping: false, + bed: None, + sleep_timer: 0, + sent_bed: None, + spawn: None, awaiting_teleport: None, teleport_counter: 0, teleport_tick: 0, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 598bbc088..cac03821b 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1439,10 +1439,44 @@ impl Hub { } } + /// ServerPlayer.stopSleepInBed: the wake-up animation goes to the player + /// and those around, the pose is standing again and the sleep counter + /// starts the wake-up fade (100). + pub fn wake(&mut self, i: usize) { + let g = &mut self.guests[i]; + if g.bed.take().is_none() && !g.sleeping { + return; + } + g.sleeping = false; + g.sleep_timer = 100; + let (id, at) = (g.entity_id, g.position); + // ClientboundAnimatePacket.WAKE_UP. + self.broadcast_near( + at, + 128.0, + &C::Animate(play::Animate { id, action: 0 }), + None, + ); + } + // ---- per-player state ------------------------------------------------ /// ServerPlayer.doTick: health, food, experience and the inventory menu. fn sync_player_state(&mut self, i: usize) { + // LivingEntity.startSleeping / stopSleeping: the pose and the bed go + // to the player too (its client lies down in the bed from them). + let g = &mut self.guests[i]; + if g.bed != g.sent_bed { + g.sent_bed = g.bed; + let pose = if g.bed.is_some() { 2 } else { 0 }; + g.send(&C::SetEntityData(play::SetEntityData { + id: g.entity_id, + values: vec![ + (6, serializer::POSE, Value::Id(pose)), + (14, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(g.bed)), + ], + })); + } // ServerEntity.sendDirtyEntityData on the player's first tick: the // health its creation set is still dirty, and goes to the player too. if self.guests[i].sent_health.is_none() { @@ -1691,7 +1725,8 @@ impl Hub { 1 => self.guests[i].sprinting = true, 2 => self.guests[i].sprinting = false, 6 => self.guests[i].fall_flying = true, - 0 => self.guests[i].sleeping = false, + // STOP_SLEEPING. + 0 => self.wake(i), _ => {} }, S::Chat(c) => { diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 555463685..770120879 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -69,6 +69,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects); guest.game_mode = level.mode(); guest.selected = (level.selected_slot.max(0) as usize).min(8); + guest.spawn = level.spawn.map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); guest.saved = level.player_extra.clone(); guest.recipe_book = level.recipe_book.clone(); if level.ender_items.len() == 27 { @@ -125,6 +126,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.game_mode = guest.game_mode; level.creative = guest.game_mode == 1; level.selected_slot = guest.selected as i32; + level.spawn = guest.spawn.map(|s| [s[0] - 0.5, s[1], s[2] - 0.5]); level.on_ground = guest.on_ground; level.player_extra = guest.saved.clone(); level.recipe_book = guest.recipe_book.clone(); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 667fdda2d..c4d5969e4 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -20,6 +20,8 @@ address. The script then checks, from both sides, what a guest's game used to ge - containers: the guest's ender chest holds the guest's items, not the host's, and a double chest opens as 9x6 with the right half first; - feedback: the guest's command feedback names the guest and shows the numbers. +- sleep: at night the guest lies down in its own bed (not the host); alone it stays night, it + gets up with Escape, and once the host sleeps too the night ends and both wake. Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -48,7 +50,7 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402 ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials', 'sleep'] class Game: @@ -622,11 +624,59 @@ def check_trials(host, guest, out): return {'spawner': trial, 'vault': active, 'rewarded': uuid(rewarded), 'host': uuid(host_uuid)} +def bed_at(game, foot): + """A bed whose foot is at `foot`, its head one block east.""" + x, y, z = foot + game('command', command=f'setblock {x} {y} {z} minecraft:red_bed[facing=east,part=foot]') + game('command', command=f'setblock {x + 1} {y} {z} minecraft:red_bed[facing=east,part=head]') + return [x + 1, y, z] + + +def check_sleep(host, guest, out): + for g in (host, guest): + g('command', command='gamemode survival') + host('command', command='time set midnight') + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + guest_bed = bed_at(guest, (gx, gy, gz + 2)) + host_bed = bed_at(host, (hx, hy, hz + 2)) + guest.wait(10) + guest.raw('interact', *guest_bed) + guest.wait(10) + asleep = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'), + 'server': host.raw('lan', 'status')['guests'][0].get('sleeping')} + guest.shot(out, 'sleep-guest') + # Alone in bed: still night 120 ticks later (everyone must sleep). + guest.wait(120) + night = host('state')['time']['time_of_day'] + # Escape gets the guest up (InBedChatScreen), then back to bed. + guest.raw('key', 'esc', 'tap') + guest.wait(10) + up = guest('state').get('sleeping') + guest.raw('interact', *guest_bed) + host.raw('interact', *host_bed) + host.wait(130) + after = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'), + 'time': host('state')['time']['time_of_day']} + guest.shot(out, 'sleep-morning') + for at in (guest_bed, host_bed): + guest('command', command=f'fill {at[0] - 1} {at[1]} {at[2]} {at[0]} {at[1]} {at[2]} minecraft:air') + host('command', command='time set day') + detail = {'asleep': asleep, 'night': night, 'up': up, 'after': after} + assert asleep['guest'] == guest_bed and asleep['server'] == guest_bed, f'the guest is not in its bed: {detail}' + assert asleep['host'] is None, f'the guest\'s bed put the host to sleep: {detail}' + assert 13000 < night < 23000, f'one of two players asleep ended the night: {detail}' + assert up is None, f'Escape did not get the guest up: {detail}' + assert after['guest'] is None and after['host'] is None and after['time'] < 1000, f'no morning: {detail}' + return detail + + CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials, - 'walls': check_walls} + 'walls': check_walls, + 'sleep': check_sleep} def run(ctl, out, resources, checks): From ce62f9c57f70ea4a50fd6a0d45604f017d9cde38 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:34:55 +0200 Subject: [PATCH 2/6] Server clients: eating plays on the player's own screen A server client sent UseItem and never started the use itself, so food showed no eating animation or crumbs, and holding right click sent a new UseItem every 4 ticks. Like MultiPlayerGameMode.useItem, the client now starts eating (Consumable.startConsuming), counts the use down for the animation and its particles, and starts no other use until it ends; the server still eats the item. Looking at another player no longer stops the item from being used (Player.interactOn passes). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/agent.rs | 2 + crates/horizon-client/src/game/remote.rs | 56 ++++++++++++++++++++++-- tools/lan_e2e.py | 40 ++++++++++++++++- 3 files changed, 92 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 48b24bbb3..1659ab225 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -466,6 +466,8 @@ impl Game<'_> { }), "dimension": self.dim.id(), "gamemode": format!("{:?}", self.mode).to_lowercase(), + // The item in use: its slot and for how many ticks. + "using": self.using.map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })), "time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) }, "weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering }, "paused": self.pause, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 05e1f81c3..a473eeb57 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2220,10 +2220,12 @@ impl Game<'_> { self.tick_player_model(); if !dead { self.remote_mining(); - if self.right && self.use_delay == 0 && playing { + // Minecraft.handleKeybinds: no new use while an item is in use. + if self.right && self.use_delay == 0 && playing && self.using.is_none() { self.remote_use(); self.use_delay = 4; } + self.remote_tick_using(); } self.remote_send_state(input); self.send(S::ClientTickEnd(Empty)); @@ -2602,8 +2604,16 @@ impl Game<'_> { location: [0.0, 1.0, 0.0], secondary: sneaking, })); - self.swing_arm(); - return; + // Player.interactOn: another player passes, and the held item is + // used instead (Minecraft.startUseItem). + let player = self + .remote + .as_ref() + .is_some_and(|r| r.level_players.contains_key(&id)); + if !player { + self.swing_arm(); + return; + } } if let Some(hit) = self.pick() { let seq = self.next_sequence(); @@ -2636,7 +2646,7 @@ impl Game<'_> { return; } } - if self.held().is_some() { + if let Some(held) = self.held().cloned() { let seq = self.next_sequence(); self.send(S::UseItem(play::UseItem { hand: 0, @@ -2644,6 +2654,44 @@ impl Game<'_> { yaw: self.yaw, pitch: self.pitch, })); + // MultiPlayerGameMode.useItem runs the use here too: food starts + // being eaten (Consumable.startConsuming). + if let Some(info) = self.res.items.get(&held.item).cloned() { + self.start_eating(&info); + } + } + } + /// `LivingEntity.updatingUsingItem` for food on a server client: the + /// eating animation and its crumbs. The server eats it and sends the + /// stack, the hunger and the sounds. + fn remote_tick_using(&mut self) { + let Some((slot, ticks)) = self.using else { + return; + }; + let stack = self.stack_in(slot).cloned(); + let food = stack + .as_ref() + .and_then(|s| self.res.items.get(&s.item)) + .is_some_and(|i| i.consumable && i.food.is_some()); + let (Some(stack), true) = (stack, food) else { + self.using = None; + return; + }; + if !self.right || slot != self.selected || self.screen != Screen::Playing { + self.using = None; + return; + } + // Consumable.shouldEmitParticlesAndSounds, as in tick_used_item. + let duration = 32; + let remaining = duration - ticks.min(duration); + if duration - remaining > (duration as f32 * 0.21875) as u32 && remaining % 4 == 0 { + self.eat_particles(&stack, 5); + } + if ticks + 1 >= duration { + self.using = None; + self.eat_particles(&stack, 16); + } else { + self.using = Some((slot, ticks + 1)); } } /// Left click: attack the targeted entity (MultiPlayerGameMode.attack). diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 667fdda2d..fa8e0ffb9 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -20,6 +20,8 @@ address. The script then checks, from both sides, what a guest's game used to ge - containers: the guest's ender chest holds the guest's items, not the host's, and a double chest opens as 9x6 with the right half first; - feedback: the guest's command feedback names the guest and shows the numbers. +- eat: holding right click with bread, the guest's own screen plays the eating (the item in use + counts up) and the server eats one loaf and feeds the guest. Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -39,6 +41,7 @@ import shutil import subprocess import sys import tempfile +import threading import time import zlib from pathlib import Path @@ -48,7 +51,7 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402 ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials', 'eat'] class Game: @@ -622,11 +625,44 @@ def check_trials(host, guest, out): return {'spawner': trial, 'vault': active, 'rewarded': uuid(rewarded), 'host': uuid(host_uuid)} +def check_eat(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + # Hungry: the eating needs food below 20 (Player.canEat). + guest('command', command='effect give @s minecraft:hunger 3 255') + guest.wait(70) + guest('command', command='effect clear @s') + guest('command', command='give @s minecraft:bread 3') + guest.wait(5) + guest.raw('select', 'minecraft:bread') + hungry = guest('state')['player']['food'] + # use-item --hold returns once released: watch the guest's screen meanwhile. + hold = threading.Thread(target=guest.raw, args=('use-item', '--hold', 2.2)) + hold.start() + using = [] + for _ in range(4): + time.sleep(0.2) + using.append(guest('state').get('using')) + guest.shot(out, 'eat') + hold.join() + guest.wait(10) + fed = guest('state')['player']['food'] + left = guest('inventory')['counts'].get('minecraft:bread', 0) + detail = {'hungry': hungry, 'fed': fed, 'bread': left, 'using': using, 'after': guest('state').get('using')} + assert hungry < 20, f'the guest is not hungry: {detail}' + ticks = [u['ticks'] for u in using if u] + assert len(ticks) >= 3 and ticks == sorted(ticks) and ticks[-1] > ticks[0], f'no eating on the guest\'s screen: {detail}' + assert left == 2 and fed > hungry, f'the server did not eat one loaf: {detail}' + assert detail['after'] is None, f'still eating after the release: {detail}' + return detail + + CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials, - 'walls': check_walls} + 'walls': check_walls, + 'eat': check_eat} def run(ctl, out, resources, checks): From 123e8286ac55894a0e9f61c78b3844fd46241e2a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:13:14 +0200 Subject: [PATCH 3/6] Guests: container clicks reach the server (chests, furnaces, crafting drags) On a LAN world or a server, a guest's clicks that went through the menu engine (placing a carried stack, quick craft drags, double clicks, number keys, Q) ran only on the guest's own copy and were never sent: the item showed in the chest or furnace, the server still had it in the inventory, and the next menu brought it back. menu_ops now sends every click of the server's open menu as vanilla's MultiPlayerGameMode.handleContainerInput does: the engine predicts it on the client's copy, then a ContainerClick goes out with the slots it changed and the carried stack after it (a drag is its three kinds of clicks). The plain inventory and crafting table are predicted too, the Shift double click sends each QUICK_MOVE, and a prediction no longer drops, crafts or makes maps on the client (the server does). tools/lan_e2e.py clicks: real mouse presses put a stack into a chest and a furnace, drag planks over the crafting grid and craft; the server has each. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 31 +++-- crates/horizon-client/src/game/remote.rs | 142 ++++++++++++++++++++++- crates/horizon-client/src/game/tweaks.rs | 10 +- crates/horizon-client/src/menu.rs | 13 +++ tools/lan_e2e.py | 92 ++++++++++++++- 5 files changed, 263 insertions(+), 25 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 238f68e55..83b4a665a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4524,6 +4524,10 @@ impl Game<'_> { /// Several clicks on one menu instance (a quick craft drag is three). fn menu_ops(&mut self, ops: &[(Option, i32, horizon_client::menu::Input)]) -> bool { use horizon_client::menu::Input; + if self.remote.is_some() && self.screen == Screen::Inventory { + // On a server the clicks are the server's: predicted and sent. + return self.remote_menu_ops(ops); + } if let [(Some(slot), button, input)] = ops { self.crafter_slot_clicked(*slot, *button, *input); } @@ -4698,7 +4702,7 @@ impl Game<'_> { plain: false, }; (kind, map) - } else if self.station.is_none() && !self.mount_active() && self.remote.is_none() { + } else if self.station.is_none() && !self.mount_active() { let table = self.craft_size == 3; let map = Map { container: 0, @@ -4811,7 +4815,12 @@ impl Game<'_> { Some(false) => return true, Some(true) => {} } - self.register_exploration_maps(made); + // On a server the clicks only predict: the server drops, crafts and + // makes maps itself. + let predicting = self.remote.is_some(); + if !predicting { + self.register_exploration_maps(made); + } if let Some(s) = menu.merchant.take() { self.merchant_sync_out(s); } @@ -4829,10 +4838,12 @@ impl Game<'_> { if !offhand_mapped { self.offhand = menu.player_item(40).cloned(); } - for stack in dropped { - self.player_drop(stack); + if !predicting { + for stack in dropped { + self.player_drop(stack); + } + self.award_crafted(&crafted); } - self.award_crafted(&crafted); if kind == Kind::Loom { if let Some(s) = self.station.as_mut() { s.loom.selected = usize::try_from(menu.data[0]).ok(); @@ -4964,9 +4975,13 @@ impl Game<'_> { return; } if let Some(moved) = self.last_quick_moved.clone() { - self.menu_session(|menu, env, to_menu| { - Some(menu.quick_move_all(env, to_menu(slot)?, &moved).is_ok()) - }); + if self.remote.is_some() { + self.remote_quick_move_all(slot, &moved); + } else { + self.menu_session(|menu, env, to_menu| { + Some(menu.quick_move_all(env, to_menu(slot)?, &moved).is_ok()) + }); + } } self.last_inv_click = None; self.inv_clicks.skip_release(); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 05e1f81c3..37c561476 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -14,6 +14,7 @@ use horizon_client::{ entities::{Experience, ItemEntity}, hud::{HudBatch, rgba}, items::ItemStack, + menu::Input, mobs::{Mob, MobType}, motion::{MotionWorld, PlayerMotion}, net::{Event, Session}, @@ -2880,17 +2881,108 @@ impl Game<'_> { let Some(internal) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return; }; - let input = if self.has_shift_down() { 1 } else { 0 }; - self.remote_slot_click(internal, i8::from(right), input); + let input = if self.has_shift_down() { + Input::QuickMove + } else { + Input::Pickup + }; + self.remote_menu_ops(&[(Some(internal), i32::from(right), input)]); + } + /// The server's open menu: its window id and menu type (0, "inventory" + /// when none is open). + fn remote_menu(&self) -> (i32, String) { + match self.remote.as_ref().and_then(|r| r.menu.clone()) { + Some((id, name)) => (id, name), + None => (0, "inventory".to_owned()), + } + } + /// `MultiPlayerGameMode.handleContainerInput` for each click of `ops` on + /// the server's open menu (a quick craft drag is several): the verified + /// menu engine predicts them on this client's copy, then each goes out as + /// a `ContainerClick` with the slots it changed and the carried stack + /// after it; the server corrects anything it sees differently. A menu the + /// engine doesn't model sends the clicks unpredicted. False when a click's + /// slot isn't one of the menu's. + pub(super) fn remote_menu_ops(&mut self, ops: &[(Option, i32, Input)]) -> bool { + let (container, menu) = self.remote_menu(); + let mut clicks = Vec::with_capacity(ops.len()); + for &(slot, button, input) in ops { + let slot = match slot { + None => -999, + Some(internal) => { + match (0..64).find(|&s| Self::menu_slot(&menu, s) == Some(internal)) { + Some(s) => s as i16, + None => return false, + } + } + }; + clicks.push((slot, button, input)); + } + // Unpredicted: nothing changed, the carried stack as it is. + let mut sent: Vec = clicks + .iter() + .map(|&(slot, button, input)| (slot, button, input, Vec::new(), self.carried.clone())) + .collect(); + // The engine's slot indices are the menu's own, as on the network. + self.menu_session(|m, env, _| { + let mut predicted = Vec::with_capacity(clicks.len()); + for &(slot, button, input) in &clicks { + let before = menu_items(m); + if m.click(env, i32::from(slot), button, input).is_err() { + // The server throws on it too: nothing is predicted. + return Some(false); + } + let changed = changed_slots(&before, m); + predicted.push((slot, button, input, changed, m.carried.clone())); + } + sent = predicted; + Some(true) + }); + self.send_clicks(container, sent); + true + } + /// A Shift double click on a server (`AbstractContainerScreen.mouseReleased`): + /// a predicted QUICK_MOVE for every slot the engine moves, each sent. + pub(super) fn remote_quick_move_all(&mut self, slot: usize, moved: &ItemStack) { + let (container, _) = self.remote_menu(); + let mut sent: Vec = Vec::new(); + self.menu_session(|m, env, to_menu| { + let clicked = to_menu(slot)?; + let mut before = menu_items(m); + let mut each = |m: &horizon_client::menu::Menu, t: usize| { + let changed = changed_slots(&before, m); + sent.push((t as i16, 0, Input::QuickMove, changed, m.carried.clone())); + before = menu_items(m); + }; + Some( + m.quick_move_all_each(env, clicked, moved, &mut each) + .is_ok(), + ) + }); + self.send_clicks(container, sent); + } + fn send_clicks(&mut self, container: i32, clicks: Vec) { + let state = self.remote.as_ref().map_or(0, |r| r.state_id); + let hashed = |g: &Self, s: &Option| g.to_network(s).map(|s| Hashed::of(&s)); + for (slot, button, input, changed, carried) in clicks { + let changed = changed.iter().map(|(i, s)| (*i, hashed(self, s))).collect(); + let carried = hashed(self, &carried); + self.send(S::ContainerClick(play::ContainerClick { + container, + state, + slot, + button: button as i8, + input: input_ordinal(input), + changed, + carried, + })); + } } /// A `ContainerClick` on game slot `internal` of the server's open menu /// (`input` is the ContainerInput ordinal). False when the menu has no /// such slot. pub(super) fn remote_slot_click(&mut self, internal: usize, button: i8, input: i32) -> bool { - let (container, menu) = match self.remote.as_ref().and_then(|r| r.menu.clone()) { - Some((id, name)) => (id, name), - None => (0, "inventory".to_owned()), - }; + let (container, menu) = self.remote_menu(); let slot = (0..64).find(|&s| Self::menu_slot(&menu, s) == Some(internal)); let Some(slot) = slot else { return false }; let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s)); @@ -3288,6 +3380,44 @@ impl Game<'_> { } } +/// A click sent to a server: its slot, button and input, the slots it +/// changed and the carried stack after it. +type Predicted = ( + i16, + i32, + Input, + Vec<(i16, Option)>, + Option, +); + +fn menu_items(m: &horizon_client::menu::Menu) -> Vec> { + (0..m.slot_count()).map(|i| m.slot(i).cloned()).collect() +} + +/// The slots whose stack is no longer `before`'s (`ItemStack.matches`). +fn changed_slots( + before: &[Option], + m: &horizon_client::menu::Menu, +) -> Vec<(i16, Option)> { + (0..m.slot_count()) + .filter(|&i| m.slot(i) != before.get(i).and_then(Option::as_ref)) + .map(|i| (i as i16, m.slot(i).cloned())) + .collect() +} + +/// ServerboundContainerClickPacket's `ContainerInput` ordinal. +pub(super) fn input_ordinal(input: Input) -> i32 { + match input { + Input::Pickup => 0, + Input::QuickMove => 1, + Input::Swap => 2, + Input::Clone => 3, + Input::Throw => 4, + Input::QuickCraft => 5, + Input::PickupAll => 6, + } +} + #[cfg(test)] mod tests { use super::Game; diff --git a/crates/horizon-client/src/game/tweaks.rs b/crates/horizon-client/src/game/tweaks.rs index 018b6640b..f15aa9ea7 100644 --- a/crates/horizon-client/src/game/tweaks.rs +++ b/crates/horizon-client/src/game/tweaks.rs @@ -70,15 +70,7 @@ impl Game<'_> { /// One ordinary click on a game slot. False when nothing took it. pub(super) fn tweak_click(&mut self, slot: usize, button: i32, input: Input) -> bool { if self.remote.is_some() { - let ordinal = match input { - Input::Pickup => 0, - Input::QuickMove => 1, - Input::Swap => 2, - Input::Clone => 3, - Input::Throw => 4, - Input::QuickCraft => 5, - Input::PickupAll => 6, - }; + let ordinal = super::remote::input_ordinal(input); return self.remote_slot_click(slot, button as i8, ordinal); } if !self.menu_click(Some(slot), button, input) { diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 5e57edcfc..64286b1fe 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -1668,6 +1668,18 @@ impl Menu { env: &Env, clicked: usize, moved: &ItemStack, + ) -> Result<(), &'static str> { + self.quick_move_all_each(env, clicked, moved, &mut |_, _| {}) + } + + /// `quick_move_all`, calling `each` with the menu and the slot after each + /// QUICK_MOVE (a server's client sends every one of them). + pub fn quick_move_all_each( + &mut self, + env: &Env, + clicked: usize, + moved: &ItemStack, + each: &mut dyn FnMut(&Self, usize), ) -> Result<(), &'static str> { if clicked >= self.slots.len() || !self.can_take_for_pick_all(clicked) { return Ok(()); @@ -1680,6 +1692,7 @@ impl Menu { && self.quick_replace(t, moved, env) { self.click(env, t as i32, 0, Input::QuickMove)?; + each(self, t); } } Ok(()) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 667fdda2d..0ced0915d 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -20,6 +20,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - containers: the guest's ender chest holds the guest's items, not the host's, and a double chest opens as 9x6 with the right half first; - feedback: the guest's command feedback names the guest and shows the numbers. +- clicks: with real mouse presses (not click-slot, which skips the screen's press and drag + handling), the guest puts a stack into a chest and a furnace, drags planks across + its crafting grid and gathers a stack with a double click; the server has each. Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -48,7 +51,7 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402 ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials', 'clicks'] class Game: @@ -456,6 +459,91 @@ def check_containers(host, guest, out): return {'ender': ender, 'double': double, 'taken': taken} +def slot_point(game, slot): + """The GUI point in the middle of slot `slot` of the open screen (`ui`'s slot-N).""" + for w in game.raw('ui')['widgets']: + if w.get('id') == f'slot-{slot}': + x, y, width, height = w['bounds'] + return x + width / 2, y + height / 2 + raise Failed(f'no slot {slot} on the screen') + + +def mouse(game, *slots, right=False): + """Press over the first slot, move over the others and release: one click, or a drag.""" + points = [f'{v:.1f}' for s in slots for v in slot_point(game, s)] + game.raw('drag-at', *(['right'] if right else []), *points) + game.wait(4) + + +def hotbar_slot(game, item): + return next(s['slot'] for s in game('inventory')['hotbar'] if s and s.get('item') == item) + + +def check_clicks(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='give @s minecraft:cobblestone 10') + guest('command', command='give @s minecraft:coal 3') + guest('command', command='give @s minecraft:raw_iron 2') + guest('command', command='give @s minecraft:oak_planks 2') + guest.wait(10) + x, y, z = (int(v // 1) for v in pos_of(guest)) + chest, furnace = (x, y, z + 2), (x, y, z - 2) + guest('command', command=f'setblock {chest[0]} {chest[1]} {chest[2]} minecraft:chest') + guest('command', command=f'setblock {furnace[0]} {furnace[1]} {furnace[2]} minecraft:furnace') + guest.wait(10) + # Pick the cobblestone up and put it down in the chest's first slot. + guest.raw('interact', *chest) + guest.raw('wait-for', 'screen', 'container', '--timeout', 10) + guest.wait(10) + mouse(guest, hotbar_slot(guest, 'minecraft:cobblestone')) + mouse(guest, 300) + guest.wait(10) + guest.shot(out, 'clicks-chest') + guest.raw('key', 'esc', 'tap') + guest.wait(10) + in_chest, _ = open_container(guest, chest, out, 'clicks-chest-after') + # Coal into the fuel slot, raw iron into the input. + guest.raw('interact', *furnace) + guest.raw('wait-for', 'screen', 'container', '--timeout', 10) + guest.wait(10) + mouse(guest, hotbar_slot(guest, 'minecraft:coal')) + mouse(guest, 301) + mouse(guest, hotbar_slot(guest, 'minecraft:raw_iron')) + mouse(guest, 300) + guest.wait(10) + guest.shot(out, 'clicks-furnace') + guest.raw('key', 'esc', 'tap') + guest.wait(10) + # Opening the furnace again resends the whole menu: the server's own view. + in_furnace, _ = open_container(guest, furnace, out, 'clicks-furnace-after') + # Two planks dragged over the 2x2 grid's left column: one each, four sticks. + guest.raw('key', 'e', 'tap') + guest.raw('wait-for', 'screen', 'inventory') + guest.wait(5) + mouse(guest, hotbar_slot(guest, 'minecraft:oak_planks')) + mouse(guest, 100, 102) + guest.wait(10) + grid = {s['slot']: (s.get('item'), s.get('count')) for s in guest('screen').get('slots', []) + if s.get('slot') in (100, 102, 200) and s.get('item')} + guest.shot(out, 'clicks-drag') + guest.raw('click-slot', 200, 'shift') + guest.wait(10) + guest.raw('key', 'esc', 'tap') + guest.wait(10) + # The chest's menu brings the whole inventory as the server has it. + open_container(guest, chest, out, 'clicks-inventory') + counts = guest('inventory')['counts'] + for at in (chest, furnace): + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air') + assert in_chest == {0: 'minecraft:cobblestone'}, f'the chest holds {in_chest} after the guest put cobblestone in' + assert in_furnace == {0: 'minecraft:raw_iron', 1: 'minecraft:coal'}, f'the furnace holds {in_furnace}' + assert grid.get(100) == ('minecraft:oak_planks', 1) and grid.get(102) == ('minecraft:oak_planks', 1), \ + f'the drag left the grid as {grid}' + assert counts.get('minecraft:stick') == 4 and 'minecraft:cobblestone' not in counts, f'inventory after: {counts}' + return {'chest': in_chest, 'furnace': in_furnace, 'grid': grid, 'inventory': counts} + + def check_feedback(host, guest, out): x, y, z = (round(v, 1) for v in pos_of(guest)) guest('command', command='item replace entity @s weapon.mainhand with minecraft:stick') @@ -626,7 +714,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials, - 'walls': check_walls} + 'walls': check_walls, 'clicks': check_clicks} def run(ctl, out, resources, checks): From 69dd4feb316616eef6255a4f41dc3b680a6a43e6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:14:18 +0200 Subject: [PATCH 4/6] Server clients: mobs' and players' heads turn smoothly, not flicker On a LAN world or a server, other entities' heads flickered between two directions. The client wrote ClientboundRotateHeadPacket's head yaw into the entity's yRot and the move packets' yRot into the body yaw, never moved the head's previous yaw and pitch on, and never ran the body rotation, so each frame interpolated the head from stale values. As vanilla: move packets interpolate the position, yRot and xRot over three ticks (LinearInterpolationHandler), RotateHead the head yaw over three (lerpHeadTo), each tick keeps the previous head rotation for the frames, and the body follows (a mob's BodyRotationControl, a player's walk direction within 50 degrees of the look). AddEntity sets yRot and xRot and puts the body and head at the packet's head yaw (recreateFromPacket). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/remote.rs | 106 ++++++++++++++++++++--- 1 file changed, 92 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 05e1f81c3..079f00d59 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -61,8 +61,11 @@ struct Tracked { } /// Smooth an entity toward a new position over three ticks (InterpolationHandler). #[derive(Clone, Copy)] +/// `LinearInterpolationHandler`'s target: a position and rotation (yRot, +/// xRot) reached in `steps` ticks. struct Lerp { target: [f64; 3], + rotation: Option<(f32, f32)>, steps: u32, } @@ -102,6 +105,8 @@ pub(super) struct Remote { use_target: Option<[i32; 3]>, entities: HashMap, lerps: HashMap, + /// `LivingEntity.lerpHeadTo`: the head yaw and the ticks left to reach it. + head_lerps: HashMap, /// Item entities waiting for their item data. pending_items: HashMap, health: (f32, i32, f32), @@ -288,6 +293,7 @@ impl Game<'_> { use_target: None, entities: HashMap::new(), lerps: HashMap::new(), + head_lerps: HashMap::new(), pending_items: HashMap::new(), health: (20.0, 20, 5.0), game_mode: 0, @@ -587,6 +593,7 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.entities.clear(); r.lerps.clear(); + r.head_lerps.clear(); r.pending_items.clear(); // A new ClientLevel: a new chunk storage, centred on 0, 0. r.chunk_center = (0, 0); @@ -868,7 +875,10 @@ impl Game<'_> { } } } - fn spawn_entity(&mut self, id: i32, kind: &str, position: [f64; 3], yaw: f32, head: f32) { + /// `recreateFromPacket`: yRot and xRot from the packet, the body and head + /// both at its head yaw (LivingEntity). + fn spawn_entity(&mut self, id: i32, kind: &str, position: [f64; 3], rotation: [f32; 3]) { + let [yaw, pitch, head] = rotation; let at = Vec3::new(position[0], position[1], position[2]); let mob_type = if kind == "minecraft:player" { self.remote.as_ref().and_then(|r| r.player_type.clone()) @@ -877,8 +887,8 @@ impl Game<'_> { }; if let Some(t) = mob_type { let mut mob = Mob::new(id as u32, t, at, head); - mob.body_yaw = yaw; - mob.previous_body_yaw = yaw; + (mob.yaw, mob.previous_yaw) = (yaw, yaw); + (mob.head_pitch, mob.previous_head_pitch) = (pitch, pitch); mob.persistent = true; self.mobs.retain(|m| m.id != id as u32); self.mobs.push(mob); @@ -903,14 +913,21 @@ impl Game<'_> { rotation: Option<(f32, f32)>, on_ground: bool, ) { + let mob = self.mobs.iter_mut().find(|m| m.id == id as u32); if let Some(r) = self.remote.as_mut() { if let Some(t) = r.entities.get_mut(&id) { t.position = position; } + // AbstractInterpolationHandler.interpolateTo: without a rotation, + // the one it was heading for (or has). + let rotation = rotation + .or_else(|| r.lerps.get(&id).and_then(|l| l.rotation)) + .or_else(|| mob.as_ref().map(|m| (m.yaw, m.head_pitch))); r.lerps.insert( id, Lerp { target: position, + rotation, steps: 3, }, ); @@ -918,12 +935,8 @@ impl Game<'_> { *p = position; } } - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { + if let Some(m) = mob { m.on_ground = on_ground; - if let Some((yaw, pitch)) = rotation { - m.body_yaw = yaw; - m.head_pitch = pitch; - } } } fn remove_entity(&mut self, id: i32) { @@ -932,6 +945,7 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.entities.remove(&id); r.lerps.remove(&id); + r.head_lerps.remove(&id); r.pending_items.remove(&id); } } @@ -1181,8 +1195,8 @@ impl Game<'_> { .map(str::to_owned) }) .unwrap_or_default(); - let yaw = horizon_protocol::buf::unpack_degrees(p.yaw); - let head = horizon_protocol::buf::unpack_degrees(p.head_yaw); + let rotation = + [p.yaw, p.pitch, p.head_yaw].map(horizon_protocol::buf::unpack_degrees); if let Some(r) = self.remote.as_mut() { if kind == "minecraft:player" { r.level_players.insert(p.id, p.uuid); @@ -1190,7 +1204,7 @@ impl Game<'_> { r.level_players.remove(&p.id); } } - self.spawn_entity(p.id, &kind, p.position, yaw, head); + self.spawn_entity(p.id, &kind, p.position, rotation); } C::RemoveEntities(p) => { for id in p.ids { @@ -1241,9 +1255,11 @@ impl Game<'_> { ]; self.move_entity(p.id, position, Some((p.yaw, p.pitch)), p.on_ground); } + // ClientPacketListener.handleRotateMob: lerpHeadTo(yHeadRot, 3). C::RotateHead(p) => { - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { - m.yaw = horizon_protocol::buf::unpack_degrees(p.head_yaw); + if let Some(r) = self.remote.as_mut() { + let yaw = horizon_protocol::buf::unpack_degrees(p.head_yaw); + r.head_lerps.insert(p.id, (yaw, 3)); } } C::SetEntityData(p) => { @@ -2236,14 +2252,18 @@ impl Game<'_> { return; }; let mut lerps = std::mem::take(&mut r.lerps); + let head_lerps = &mut r.head_lerps; let players = &r.level_players; for m in &mut self.mobs { - if !running && !players.contains_key(&(m.id as i32)) { + let player = players.contains_key(&(m.id as i32)); + if !running && !player { continue; } m.previous = m.position; m.previous_yaw = m.yaw; m.previous_body_yaw = m.body_yaw; + m.previous_head_yaw = m.head_yaw; + m.previous_head_pitch = m.head_pitch; m.previous_limb_speed = m.limb_speed; m.age += 1; if m.species() == horizon_client::mobs::Species::Rabbit { @@ -2258,6 +2278,7 @@ impl Game<'_> { if !m.alive() { m.death_time += 1; } + // Entity.commonTick: LinearInterpolationHandler.interpolate. if let Some(l) = lerps.get_mut(&(m.id as i32)) && l.steps > 0 { @@ -2267,8 +2288,27 @@ impl Game<'_> { m.position.y + (l.target[1] - m.position.y) / n, m.position.z + (l.target[2] - m.position.z) / n, ); + if let Some((yaw, pitch)) = l.rotation { + let alpha = 1.0 / l.steps as f32; + m.yaw += wrap_degrees(yaw - m.yaw) * alpha; + m.head_pitch += (pitch - m.head_pitch) * alpha; + } l.steps -= 1; } + // LivingEntity.aiStep: the head's own interpolation. + if let Some((yaw, steps)) = head_lerps.get_mut(&(m.id as i32)) + && *steps > 0 + { + m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32; + *steps -= 1; + } + // LivingEntity.tick's tickHeadTurn: a mob's BodyRotationControl, + // a player's body following its walk and look. + if player { + remote_player_head_turn(m); + } else if m.alive() { + m.body_rotation_tick(); + } // WalkAnimationState.update from the horizontal distance moved. let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z); let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0); @@ -2294,6 +2334,7 @@ impl Game<'_> { } } lerps.retain(|_, l| l.steps > 0); + head_lerps.retain(|_, (_, steps)| *steps > 0); if let Some(r) = self.remote.as_mut() { for (id, l) in lerps { r.lerps.entry(id).or_insert(l); @@ -3288,6 +3329,43 @@ impl Game<'_> { } } +/// `Mth.wrapDegrees`. +fn wrap_degrees(a: f32) -> f32 { + let a = a % 360.0; + if a >= 180.0 { + a - 360.0 + } else if a < -180.0 { + a + 360.0 + } else { + a + } +} + +/// `LivingEntity.tick`'s body target and `tickHeadTurn` for another player: +/// the body turns toward where it walks (backwards when walking back), or to +/// the look while the arm swings, and stays within 50 degrees of the look. +fn remote_player_head_turn(m: &mut Mob) { + let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z); + let mut target = m.body_yaw; + if (dx * dx + dz * dz) as f32 > 0.002_500_000_2 { + let walk = (dz.atan2(dx) as f32).to_degrees() - 90.0; + let facing = (wrap_degrees(m.yaw) - walk).abs(); + target = if 95.0 < facing && facing < 265.0 { + walk - 180.0 + } else { + walk + }; + } + if m.anim.attack_anim > 0.0 { + target = m.yaw; + } + m.body_yaw += wrap_degrees(target - m.body_yaw) * 0.3; + let head = wrap_degrees(m.yaw - m.body_yaw); + if head.abs() > 50.0 { + m.body_yaw += head - head.signum() * 50.0; + } +} + #[cfg(test)] mod tests { use super::Game; From 22dc3e595404dfc0c0143da4ab72edbb82ebe31b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:08:13 +0200 Subject: [PATCH 5/6] Guests: touching mobs push them on their own client, as in vanilla A mob's push of a guest went to the guest as SetEntityMotion carrying the server copy's velocity, which nothing damps: every tick of contact added to it and replaced what the guest's client was doing. Vanilla pushes players on their own client only (EntitySelector.pushableBy): the server no longer sends those pushes, and a server client now pushes its player away from every living entity it touches (Entity.push, team rules, no spectators, bats or passengers of the same vehicle). Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 1 + crates/horizon-client/src/game/creatures.rs | 1 + crates/horizon-client/src/game/lan_mobs.rs | 2 + crates/horizon-client/src/game/remote.rs | 69 ++++++++++++++++++- .../horizon-client/src/game/respawn_anchor.rs | 2 +- crates/horizon-client/src/mobs.rs | 3 + crates/horizon-client/src/mobs/ai.rs | 12 ++-- tools/lan_e2e.py | 27 +++++++- 8 files changed, 109 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 087fd3edf..0b3adec31 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -999,6 +999,7 @@ fn main() -> horizon_client::Result<()> { hero: false, uuid: PLAYER_UUID, allies: Default::default(), + remote: false, } }); let mut scratch = LegacyRandom::new(0); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 076c2fbef..acac3b596 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -196,6 +196,7 @@ impl Game<'_> { hero: self.potions.effects.get("hero_of_the_village").is_some(), uuid: self.level.player_uuid.unwrap_or_default(), allies: std::sync::Arc::new(self.player_allies()), + remote: false, }) } /// Biome facts at a position for finalizeSpawn and variant rules. diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 7cef7cda6..e12446b0c 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -107,6 +107,7 @@ impl Game<'_> { v.velocity = Vec3::new(moved[0], moved[1], moved[2]); v.uuid = horizon_client::lan::playerdata::uuid_ints(uuid); v.allies = Default::default(); + v.remote = true; views.push((conn, v)); } } @@ -271,6 +272,7 @@ mod tests { hero: false, uuid: [0; 4], allies: Default::default(), + remote: false, } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 05e1f81c3..1200da1ca 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -14,12 +14,13 @@ use horizon_client::{ entities::{Experience, ItemEntity}, hud::{HudBatch, rgba}, items::ItemStack, - mobs::{Mob, MobType}, + mobs::{Mob, MobType, Who}, motion::{MotionWorld, PlayerMotion}, net::{Event, Session}, save::SaveDir, sprint::Keys, streaming::{ChunkGenerator, Proto, Streaming}, + tab_list::SPECTATOR, world::World, }; use horizon_core::{geometry::Vec3, paletted::PalettedContainer, random::RandomSource}; @@ -2125,6 +2126,7 @@ impl Game<'_> { self.tick_particles(); self.tick_client_effects(); let ghast_collisions = self.happy_ghast_player_collisions(); + let pushed = self.remote_pushes(); let Some(player) = self.player.as_mut() else { return Ok(()); }; @@ -2177,6 +2179,7 @@ impl Game<'_> { player.yaw = self.yaw; let dead = self.screen == Screen::Dead; if !dead { + player.velocity = player.velocity.add_vector(pushed); MotionWorld { entities: &ghast_collisions, player, @@ -2229,6 +2232,70 @@ impl Game<'_> { self.send(S::ClientTickEnd(Empty)); Ok(()) } + /// The local player's share of every touching entity's + /// `LivingEntity.pushEntities`: on a client `EntitySelector.pushableBy` + /// lets entities push only the local player, so the server never sends + /// these pushes. `doPush(player)` is `player.push(entity)`. + fn remote_pushes(&self) -> Vec3 { + let (Some(p), Some(r)) = (self.player.as_ref(), self.remote.as_ref()) else { + return Vec3::ZERO; + }; + // LivingEntity.isPushable: alive, no spectator, off ladders. + let feet = [ + p.position.x.floor() as i32, + p.position.y.floor() as i32, + p.position.z.floor() as i32, + ]; + if self.screen == Screen::Dead + || p.spectator + || self.block_in_tag("minecraft:climbable", &self.block_name(feet)) + { + return Vec3::ZERO; + } + let bounds = p.bounds(); + let teams = self.mob_teams(); + let mut push = Vec3::ZERO; + for m in &self.mobs { + let spectator = r + .level_players + .get(&(m.id as i32)) + .and_then(|uuid| r.tab_players.get(uuid)) + .is_some_and(|t| t.game_mode == SPECTATOR); + // Bats never push; a spectator has no physics; passengers of the + // same vehicle never push each other. + if !m.alive() + || spectator + || m.species() == horizon_client::mobs::Species::Bat + || self + .riding + .is_some_and(|v| v == m.id || m.extra.mount == Some(v)) + || !m.bounds().intersects(bounds) + || !horizon_client::scoreboard::pushable_by( + teams.of(Who::Mob(m.id)), + teams.of(Who::Player), + true, + ) + { + continue; + } + // Entity.push(Entity), `this` the player. + let (mut xa, mut za) = (m.position.x - p.position.x, m.position.z - p.position.z); + let mut dd = xa.abs().max(za.abs()); + if dd < f64::from(0.01_f32) { + continue; + } + dd = dd.sqrt(); + xa /= dd; + za /= dd; + let pow = (1.0 / dd).min(1.0); + xa *= pow; + za *= pow; + xa *= f64::from(0.05_f32); + za *= f64::from(0.05_f32); + push = Vec3::new(push.x - xa, push.y, push.z - za); + } + push + } /// ClientLevel.tickEntities; a frozen level only ticks the players /// (`TickRateManager.isEntityFrozen`). fn tick_remote_entities(&mut self, running: bool) { diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index 5a31dfd5c..aa94d5b17 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -324,7 +324,7 @@ impl Game<'_> { ) .unwrap_or_else(|_| VoxelShape::empty()) } - fn block_in_tag(&self, tag: &str, block: &str) -> bool { + pub(super) fn block_in_tag(&self, tag: &str, block: &str) -> bool { self.res .items .block_tags diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 2ab4c0557..53143d2df 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1398,6 +1398,9 @@ pub struct PlayerView { /// The mobs on the player's team (`isAlliedTo`): combat targeting /// leaves the player alone. pub allies: std::sync::Arc>, + /// A LAN guest: its own client moves it, and touching mobs push it there + /// (`EntitySelector.pushableBy` on the client). + pub remote: bool, } pub struct MobWorld<'a> { pub world: &'a World, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 9ab29d0a5..f74a3c7d1 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -822,10 +822,14 @@ fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec) { za *= pow; xa *= f64::from(0.05_f32); za *= f64::from(0.05_f32); - events.push(MobEvent::Push { - target: who, - velocity: [-xa, 0.0, -za], - }); + // A guest's server-side push never reaches its client (ServerPlayer + // motion is synced only when hurt): its client pushes it itself. + if who != Who::Player || w.player.as_ref().is_none_or(|p| !p.remote) { + events.push(MobEvent::Push { + target: who, + velocity: [-xa, 0.0, -za], + }); + } if self_pushable { m.velocity = Vec3::new(m.velocity.x + xa, m.velocity.y, m.velocity.z + za); } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 667fdda2d..85b2bb12a 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -20,6 +20,8 @@ address. The script then checks, from both sides, what a guest's game used to ge - containers: the guest's ender chest holds the guest's items, not the host's, and a double chest opens as 9x6 with the right half first; - feedback: the guest's command feedback names the guest and shows the numbers. +- push: a cow standing in the guest pushes it just clear of the cow (the guest's own client + pushes it, as in vanilla), not ever faster across the ground. Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -48,7 +50,7 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402 ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials', 'push'] class Game: @@ -622,11 +624,32 @@ def check_trials(host, guest, out): return {'spawner': trial, 'vault': active, 'rewarded': uuid(rewarded), 'host': uuid(host_uuid)} +def check_push(host, guest, out): + guest('command', command='gamemode survival') + x, y, z = (int(v // 1) + 0.5 for v in pos_of(guest)) + guest('command', command=f'tp @s {x} {y - 0.5} {z}') + guest.wait(20) + x, y, z = pos_of(guest) + # A cow that doesn't walk, 0.3 east of the guest: the two boxes overlap until their centres are + # 0.75 apart, so the push stops a fraction of a block away. + guest('command', command=f'summon minecraft:cow {x + 0.3:.2f} {y:.2f} {z:.2f} {{NoAI:1b}}') + guest.wait(60) + nx, _, nz = pos_of(guest) + guest.shot(out, 'push') + guest('command', command='kill @e[type=minecraft:cow]') + moved = ((nx - x) ** 2 + (nz - z) ** 2) ** 0.5 + detail = {'from': [round(x, 3), round(z, 3)], 'to': [round(nx, 3), round(nz, 3)], 'moved': round(moved, 3)} + assert nx < x, f'the cow did not push the guest west: {detail}' + assert moved < 1.5, f'the cow pushed the guest too far: {detail}' + return detail + + CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials, - 'walls': check_walls} + 'walls': check_walls, + 'push': check_push} def run(ctl, out, resources, checks): From d1d36f4121bd8eb1a4d3d95b7072420cf3ef6d65 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:26:37 +0200 Subject: [PATCH 6/6] Guests: experience orbs fly to them and give them their points On a LAN world or a server, guests never got experience: orbs followed and were taken only by the host's own player (none on a dedicated server), and guests weren't sent orbs at all. - Each orb follows the nearest living, non-spectator player within 8 blocks, the host or a guest (ExperienceOrb.followNearbyPlayer). - A guest takes an orb as Player.aiStep does: one of those in its box grown by 1, 0.5, 1, at random, at most every 2 ticks (takeXpDelay), repairing with Mending first; the rest goes to the guest's experience (sent with SetExperience as before), the level-up sound every fifth level. TakeItemEntity goes to the players around, the pickup sound plays at the orb. - Orbs have entity ids and are tracked to guests (AddEntity, DATA_VALUE). The client shows a server's orbs, moves them with the server's packets and flies them to their collector. tools/lan_e2e.py xp: three 7-point orbs near the guest: it sees three and ends at level 2 (21 points); the host gets none. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entities.rs | 2 + crates/horizon-client/src/entity_nbt.rs | 2 + crates/horizon-client/src/game.rs | 78 ++++++++++++++----- crates/horizon-client/src/game/commands.rs | 2 + crates/horizon-client/src/game/lan.rs | 19 ++++- crates/horizon-client/src/game/lan_actions.rs | 78 ++++++++++++++++++- crates/horizon-client/src/game/persist.rs | 8 +- crates/horizon-client/src/game/pickups.rs | 1 + crates/horizon-client/src/game/remote.rs | 70 +++++++++++++---- tools/lan_e2e.py | 34 +++++++- 10 files changed, 254 insertions(+), 40 deletions(-) diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 5e6a3336a..c0ee36bcd 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -178,6 +178,8 @@ impl ItemEntity { /// ExperienceOrb: gravity 0.03, homing towards the player within 8 blocks. #[derive(Clone, Debug)] pub struct ExperienceOrb { + /// The entity id servers track it by. + pub id: u32, pub position: Vec3, pub previous: Vec3, pub velocity: Vec3, diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index adeb1da25..90e1efc03 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -937,6 +937,7 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec { }; let count = number(tag.get("Count")).unwrap_or(1).clamp(1, 64) as usize; let orb = ExperienceOrb { + id: 0, position, previous: position, velocity: motion(tag), @@ -1575,6 +1576,7 @@ mod tests { #[test] fn orbs_expand_their_count() { let o = ExperienceOrb { + id: 0, position: Vec3::new(1.0, 2.0, 3.0), previous: Vec3::ZERO, velocity: Vec3::ZERO, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 238f68e55..4604ce855 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7352,7 +7352,9 @@ impl Game<'_> { let mut r = dispenser::entity_random(); let _yaw = r.next_float(); let p = Vec3::new(at[0], at[1], at[2]); + self.next_entity += 1; self.orbs.push(ExperienceOrb { + id: self.next_entity, position: p, previous: p, velocity: Vec3::new( @@ -7416,13 +7418,29 @@ impl Game<'_> { .player .as_ref() .filter(|p| !p.health.dead_or_dying() && !spectator); - let target = player.map(|p| { - [ - p.position.x, - p.position.y + f64::from(p.dimensions.eye_height) / 2.0, - p.position.z, - ] - }); + // ExperienceOrb.followNearbyPlayer: each orb goes for the nearest + // living player within 8 blocks, the host's own or a guest. + let mut followed: Vec<([f64; 3], [f64; 3])> = player + .map(|p| { + let feet = [p.position.x, p.position.y, p.position.z]; + let eye = f64::from(p.dimensions.eye_height); + (feet, [feet[0], feet[1] + eye / 2.0, feet[2]]) + }) + .into_iter() + .collect(); + if let Some(host) = self.lan.as_ref() { + followed.extend( + host.hub + .guests + .iter() + .filter(|g| g.placed && g.loaded && !g.dead && g.health > 0.0) + .filter(|g| !g.spectator()) + .map(|g| { + let p = g.position; + (p, [p[0], p[1] + g.eye_height() / 2.0, p[2]]) + }), + ); + } let bounds = player.map(|p| { let w = f64::from(p.dimensions.width) / 2.0; ( @@ -7435,7 +7453,19 @@ impl Game<'_> { ) }); let mut orbs = std::mem::take(&mut self.orbs); - orbs.retain_mut(|o| o.tick(&self.world, &self.res.facts, self.collision, target)); + orbs.retain_mut(|o| { + let distance = |feet: &[f64; 3]| -> f64 { + (feet[0] - o.position.x).powi(2) + + (feet[1] - o.position.y).powi(2) + + (feet[2] - o.position.z).powi(2) + }; + let target = followed + .iter() + .filter(|(feet, _)| distance(feet) < 64.0) + .min_by(|a, b| distance(&a.0).total_cmp(&distance(&b.0))) + .map(|(_, target)| *target); + o.tick(&self.world, &self.res.facts, self.collision, target) + }); let mut gained = 0; let mut taken = Vec::new(); if let Some((min, max)) = bounds { @@ -7469,19 +7499,25 @@ impl Game<'_> { (self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9; self.audio .play("minecraft:entity.experience_orb.pickup", at, 0.1, pitch); - if self.experience.give(gained as i32) - && self.experience.level % 5 == 0 - && self.ticks > self.last_level_up + 100 - { - self.last_level_up = self.ticks; - let volume = if self.experience.level > 30 { - 1.0 - } else { - self.experience.level as f32 / 30.0 - }; - self.audio - .play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0); - } + self.give_orb_points(gained); + } + } + /// `Player.giveExperiencePoints`, and `giveExperienceLevels`' level-up + /// sound every fifth level (at most every 100 ticks). + pub(super) fn give_orb_points(&mut self, gained: u32) { + let at = self.eye_position(); + if self.experience.give(gained as i32) + && self.experience.level % 5 == 0 + && self.ticks > self.last_level_up + 100 + { + self.last_level_up = self.ticks; + let volume = if self.experience.level > 30 { + 1.0 + } else { + self.experience.level as f32 / 30.0 + }; + self.audio + .play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0); } } /// BowItem.releaseUsing: power from charge time, arrows at power * 3. diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 6c4817f63..4f53f1add 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1418,7 +1418,9 @@ impl Game<'_> { return Err(err("commands.summon.failed", &[])); } "experience_orb" => { + self.next_entity += 1; self.orbs.push(horizon_client::entities::ExperienceOrb { + id: self.next_entity, position: Vec3::new(pos[0], pos[1], pos[2]), previous: Vec3::new(pos[0], pos[1], pos[2]), velocity: Vec3::new(0.0, 0.0, 0.0), diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index d574b8928..1c7b53f2a 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -714,7 +714,7 @@ impl Game<'_> { /// Mobs and items as the entities guests track. fn lan_entities(&self, hub: &mut Hub) -> Vec { - let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len()); + let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len() + self.orbs.len()); for m in self.mobs.iter().filter(|m| !m.removed) { let kind = m.kind.id.as_str(); let meta = mob_meta(m, hub); @@ -752,6 +752,23 @@ impl Game<'_> { equipment: Vec::new(), }); } + for o in &self.orbs { + out.push(EntityState { + id: o.id as i32, + uuid: entity_uuid(o.id), + kind: "minecraft:experience_orb".to_owned(), + position: [o.position.x, o.position.y, o.position.z], + yaw: 0.0, + pitch: 0.0, + head_yaw: 0.0, + on_ground: o.on_ground, + velocity: [o.velocity.x, o.velocity.y, o.velocity.z], + data: 0, + // ExperienceOrb.DATA_VALUE. + meta: vec![(8, serializer::INT, Value::Int(o.value as i32))], + equipment: Vec::new(), + }); + } out } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 7cd4b0474..240d5fbaa 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -18,7 +18,7 @@ use horizon_client::{ }, motion::{MotionEvent, MotionWorld, PlayerMotion}, }; -use horizon_core::geometry::Vec3; +use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_protocol::{ packets::play::{self, Clientbound as C, Serverbound as S}, text::literal, @@ -54,6 +54,8 @@ pub(super) struct GuestPlay { /// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw. pub(super) stats: super::stats::Stats, last_inventory: u64, + /// `Player.takeXpDelay`: ticks until the next orb can be taken. + xp_delay: u32, } struct ItemRules<'a>(&'a horizon_client::items::Items); @@ -1006,6 +1008,7 @@ impl Game<'_> { host.hub.flush_progress(conn); self.guest_dig_feedback(host, conn); self.guest_pickups(host, gi); + self.guest_orbs(host, gi); let g = &mut host.hub.guests[gi]; if g.health <= 0.0 && !g.dead { g.dead = true; @@ -1307,6 +1310,79 @@ impl Game<'_> { } } + /// `Player.tick`'s takeXpDelay and `Player.aiStep`'s touch of the + /// experience orbs in the guest's box grown by 1, 0.5, 1: one of them at + /// random, at most every 2 ticks (`ExperienceOrb.playerTouch`), repairs + /// with Mending and gives the rest as points. Everyone near hears it. + fn guest_orbs(&mut self, host: &mut LanHost, gi: usize) { + let g = &host.hub.guests[gi]; + // Player's standing and crouching boxes: 1.8 and 1.5 high. + let height = if g.sneaking { 1.5 } else { 1.8 }; + let (conn, id, at) = (g.conn, g.entity_id, g.position); + let unable = g.spectator() || g.dead || g.health <= 0.0; + let play = host.play.entry(conn).or_default(); + if play.xp_delay > 0 { + play.xp_delay -= 1; + } + if unable || play.xp_delay > 0 { + return; + } + let (min, max) = ( + [at[0] - 1.3, at[1] - 0.5, at[2] - 1.3], + [at[0] + 1.3, at[1] + height + 0.5, at[2] + 1.3], + ); + let touching: Vec = self + .orbs + .iter() + .enumerate() + .filter(|(_, o)| { + o.position.x + 0.25 > min[0] + && o.position.x - 0.25 < max[0] + && o.position.y + 0.5 > min[1] + && o.position.y < max[1] + && o.position.z + 0.25 > min[2] + && o.position.z - 0.25 < max[2] + }) + .map(|(i, _)| i) + .collect(); + if touching.is_empty() { + return; + } + // Util.getRandom(orbs, random). + let pick = self + .world + .random + .next_int_bound(touching.len() as i32) + .unwrap_or(0) as usize; + let orb = self.orbs.remove(touching[pick]); + play.xp_delay = 2; + host.hub.take_item(orb.id as i32, id, 1, at); + // ClientPacketListener.handleTakeItemEntity's sound, at the orb. + let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9; + let p = orb.position; + self.audio.play( + "minecraft:entity.experience_orb.pickup", + Some([p.x, p.y, p.z]), + 0.1, + pitch, + ); + let value = orb.value; + if let Some(target) = super::pickups::guest_target(host, id as u32) { + use super::pickups::{Collector, Taken}; + self.add_pickup_toward( + Taken::Orb(Box::new(orb)), + Collector::Guest(id as u32), + target, + ); + } + self.as_guest(host, conn, |game| { + let rest = game.mending(value); + if rest > 0 { + game.give_orb_points(rest); + } + }); + } + /// The host's own `ItemPickupParticle` toward the guest's model. fn guest_pickup( &mut self, diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 96d879f13..27fe36694 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -176,7 +176,13 @@ impl Game<'_> { self.dropped.push(e); } } - "minecraft:experience_orb" => self.orbs.extend(entity_nbt::orbs_from_nbt(&tag)), + "minecraft:experience_orb" => { + for mut orb in entity_nbt::orbs_from_nbt(&tag) { + self.next_entity += 1; + orb.id = self.next_entity; + self.orbs.push(orb); + } + } "minecraft:arrow" => { if let Some((mut p, in_block)) = entity_nbt::arrow_from_nbt( &tag, diff --git a/crates/horizon-client/src/game/pickups.rs b/crates/horizon-client/src/game/pickups.rs index 2729dc98f..1e19bcfc3 100644 --- a/crates/horizon-client/src/game/pickups.rs +++ b/crates/horizon-client/src/game/pickups.rs @@ -148,6 +148,7 @@ mod tests { fn orb_at(x: f64, y: f64, z: f64) -> Taken { let at = horizon_core::geometry::Vec3::new(x, y, z); Taken::Orb(Box::new(ExperienceOrb { + id: 0, position: at, previous: at, velocity: horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0), diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 05e1f81c3..def1060f7 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -11,7 +11,7 @@ use horizon_client::{ Result, chunk::{BIOME_STRATEGY, BLOCK_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section}, containers::{BlockEntity, Furnace, FurnaceKind}, - entities::{Experience, ItemEntity}, + entities::{Experience, ExperienceOrb, ItemEntity}, hud::{HudBatch, rgba}, items::ItemStack, mobs::{Mob, MobType}, @@ -875,6 +875,19 @@ impl Game<'_> { } else { self.res.mob_types.get(kind).cloned() }; + if kind == "minecraft:experience_orb" { + // Its value (ExperienceOrb.DATA_VALUE) follows in SetEntityData. + self.orbs.retain(|o| o.id != id as u32); + self.orbs.push(ExperienceOrb { + id: id as u32, + position: at, + previous: at, + velocity: Vec3::ZERO, + value: 1, + age: 0, + on_ground: false, + }); + } if let Some(t) = mob_type { let mut mob = Mob::new(id as u32, t, at, head); mob.body_yaw = yaw; @@ -928,6 +941,7 @@ impl Game<'_> { } fn remove_entity(&mut self, id: i32) { self.mobs.retain(|m| m.id != id as u32); + self.orbs.retain(|o| o.id != id as u32); self.dropped.retain(|d| d.id != id as u32); if let Some(r) = self.remote.as_mut() { r.entities.remove(&id); @@ -1277,6 +1291,13 @@ impl Game<'_> { { self.remote_item_data(p.id, stack); } + // ExperienceOrb.DATA_VALUE (the icon's size). + if *index == 8 + && let Value::Int(v) = value + && let Some(o) = self.orbs.iter_mut().find(|o| o.id == p.id as u32) + { + o.value = (*v).max(0) as u32; + } } } // ClientPacketListener.handleSetEquipment: what a mob or another @@ -1303,10 +1324,13 @@ impl Game<'_> { } } C::TakeItemEntity(p) => { - if self - .remote - .as_ref() - .is_some_and(|r| r.entity_id == p.player) + // An orb's sound comes from the server, at the orb. + let orb = self.orbs.iter().any(|o| o.id == p.item as u32); + if !orb + && self + .remote + .as_ref() + .is_some_and(|r| r.entity_id == p.player) && let Some(eye) = self.eye_position() { let pitch = ((self.world.random.next_float() - self.world.random.next_float()) @@ -1317,17 +1341,20 @@ impl Game<'_> { .play("minecraft:entity.item.pickup", Some(eye), 0.2, pitch); } // ItemPickupParticle toward the collector (this player, another one or a mob). + let collector = if self + .remote + .as_ref() + .is_some_and(|r| r.entity_id == p.player) + { + super::pickups::Collector::Player + } else { + super::pickups::Collector::Mob(p.player as u32) + }; if let Some(item) = self.dropped.iter().find(|d| d.id == p.item as u32).cloned() { - let collector = if self - .remote - .as_ref() - .is_some_and(|r| r.entity_id == p.player) - { - super::pickups::Collector::Player - } else { - super::pickups::Collector::Mob(p.player as u32) - }; self.add_pickup(super::pickups::Taken::Item(Box::new(item)), collector); + } else if let Some(orb) = self.orbs.iter().find(|o| o.id == p.item as u32).cloned() + { + self.add_pickup(super::pickups::Taken::Orb(Box::new(orb)), collector); } self.remove_entity(p.item); } @@ -2278,6 +2305,21 @@ impl Game<'_> { horizon_client::mobs::rabbit::post_tick(m); } } + for o in self.orbs.iter_mut().filter(|_| running) { + o.previous = o.position; + o.age += 1; + if let Some(l) = lerps.get_mut(&(o.id as i32)) + && l.steps > 0 + { + let n = f64::from(l.steps); + o.position = Vec3::new( + o.position.x + (l.target[0] - o.position.x) / n, + o.position.y + (l.target[1] - o.position.y) / n, + o.position.z + (l.target[2] - o.position.z) / n, + ); + l.steps -= 1; + } + } for d in self.dropped.iter_mut().filter(|_| running) { d.previous = d.position; d.age += 1; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 667fdda2d..7997d001e 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -20,6 +20,8 @@ address. The script then checks, from both sides, what a guest's game used to ge - containers: the guest's ender chest holds the guest's items, not the host's, and a double chest opens as 9x6 with the right half first; - feedback: the guest's command feedback names the guest and shows the numbers. +- xp: experience orbs 4 blocks away fly to the guest, show on the guest's screen and give the + guest their points (not the host). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -48,7 +50,7 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402 ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials', 'xp'] class Game: @@ -622,11 +624,39 @@ def check_trials(host, guest, out): return {'spawner': trial, 'vault': active, 'rewarded': uuid(rewarded), 'host': uuid(host_uuid)} +def check_xp(host, guest, out): + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='xp set @s 0 levels') + g('command', command='xp set @s 0 points') + guest.wait(10) + x, y, z = pos_of(guest) + # Three orbs of 7 points 4 blocks east of the guest (out of reach, within the 8 blocks orbs + # follow from): they fly to the guest. + for _ in range(3): + guest('command', command=f'summon minecraft:experience_orb {x + 4:.2f} {y + 0.5:.2f} {z:.2f} {{Value:7s}}') + guest.wait(2) + seen = remote(guest).get('entities', {}).get('minecraft:experience_orb', 0) + guest.shot(out, 'xp-orbs') + guest.wait(60) + xp = guest('state')['player']['xp'] + host_xp = host('state')['player']['xp'] + left = remote(guest).get('entities', {}).get('minecraft:experience_orb', 0) + detail = {'seen': seen, 'guest': xp, 'host': host_xp, 'left': left} + # ExperienceOrb.scanForMerges: orbs of one value side by side can merge into one. + assert 1 <= seen <= 3, f'the guest saw {seen} orbs: {detail}' + assert xp['total'] == 21 and xp['level'] == 2, f'the guest\'s experience after three 7-point orbs: {detail}' + assert host_xp['total'] == 0, f'the host took the orbs: {detail}' + assert left == 0, f'orbs left on the guest\'s screen: {detail}' + return {'seen': seen, 'guest': xp, 'host': host_xp} + + CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials, - 'walls': check_walls} + 'walls': check_walls, + 'xp': check_xp} def run(ctl, out, resources, checks):