From 7c83fbb6df401eb4db6a60289cf26e70b55d7c48 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:12:03 +0200 Subject: [PATCH] Travel a guest's server-side velocity, and send hurts after it A guest's (and, on the server thread, the window's) knockback started from the velocity the last hit left on its server copy, which nothing ever slowed down, and each hit went out at once. So every hit after the first pushed harder (0.72, then 0.76 blocks a tick where vanilla sends 0.4 each time), netherite resisted from the wrong base, and a zombie's hit reached the client before the friction of the tick it landed in. Vanilla's server simulates a player too (MoveSimulationType AUTHORITATIVE_SIDE_AND_SERVER): ServerPlayer travels every tick with no input, and ServerEntity.sendChanges sends a velocity a hurt marked (Entity.markHurt) as it is after that travel. A player's melee hit is the exception (Player.causeExtraKnockback): it sends at once, then puts the server copy back to its velocity from before the hit. - MotionWorld::server_travel: Player.travel with no input, keeping only the velocity (the client's moves place the player). The server's copy checks no fall damage on its own moves (isLocalInstanceAuthoritative). - guest_server_tick runs it last, then sends the velocity if a hurt marked it since the last tick. - guest_hit_by leaves a marked velocity to that; guest_struck_by (melee from a player) sends at once and restores. - lan_e2e `knockback`: three hits each way push the victim as far each time. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan_actions.rs | 32 +++- crates/horizon-client/src/game/lan_mobs.rs | 43 ++++- crates/horizon-client/src/game/lan_pvp.rs | 2 +- crates/horizon-client/src/motion.rs | 167 ++++++++++++++---- tools/lan_e2e.py | 47 +++++ tools/test_server_knockback_parity.py | 15 +- 6 files changed, 244 insertions(+), 62 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 7fd969a9b..d42ffc511 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1911,7 +1911,7 @@ impl Game<'_> { let (rules, motion) = (game.world.health_rules, game.motion); let health = &motion.health; let Some(player) = game.player.as_mut() else { - return Vec::new(); + return (Vec::new(), None); }; let mut w = MotionWorld { entities: &[], @@ -1987,22 +1987,44 @@ impl Game<'_> { game.border_damage(); game.tick_mob_effects(); let Some(player) = game.player.as_mut() else { - return Vec::new(); + return (Vec::new(), None); }; let _ = player.peaceful_regeneration(rules); let _ = player.food_tick(health, rules); events.append(&mut player.events); - events + let _ = MotionWorld { + entities: &[], + player, + scene: &mut game.world, + assets: &game.pack.assets, + collision_binding: game.collision, + resources: game.motion, + } + .server_travel(); + // A hurt since the last tick marked the velocity (Entity.markHurt): + // ServerEntity.sendChanges sends it as it is after this travel. + let marked = std::mem::take(&mut player.health.sync_velocity); + let sounds = events .into_iter() .filter_map(|e| match e { MotionEvent::HurtSound(sound) => Some(sound), _ => None, }) - .collect::>() + .collect::>(); + (sounds, marked.then_some(player.velocity)) }); - for sound in sounds.into_iter().flatten() { + let Some((sounds, marked)) = sounds else { + return; + }; + for sound in sounds { self.player_hurt_sound(sound, at); } + if let (Some(v), Some(g)) = (marked, host.hub.guest(conn)) { + g.send(&C::SetEntityMotion(play::SetEntityMotion { + id: g.entity_id, + velocity: [v.x, v.y, v.z], + })); + } } /// ServerGamePacketListenerImpl.handlePlayerCommand START_FALL_FLYING: diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index b3f42f0c7..be277b6e0 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -213,7 +213,9 @@ impl Game<'_> { impl Game<'_> { /// Hurt a guest: `f` runs as them, and the knockback it gave reaches - /// their client (`hurtMarked`: ClientboundSetEntityMotionPacket). + /// their client. A hurt marks the velocity (Entity.markHurt), which goes + /// out once the guest's server copy has travelled (`guest_server_tick`); + /// a push with no hurt goes out at once. pub(super) fn guest_hit_by( &mut self, host: &mut LanHost, @@ -223,16 +225,47 @@ impl Game<'_> { let (result, pushed) = self.as_guest(host, conn, |g| { let before = g.player.as_ref().map(|p| p.velocity); let result = f(g); - let after = g.player.as_ref().map(|p| p.velocity); - (result, after.filter(|v| Some(*v) != before)) + let pushed = g + .player + .as_ref() + .filter(|p| !p.health.sync_velocity && Some(p.velocity) != before) + .map(|p| p.velocity); + (result, pushed) })?; - if let (Some(v), Some(g)) = (pushed, host.hub.guest(conn)) { + self.send_guest_motion(host, conn, pushed); + Some(result) + } + + /// A player's melee hit on a guest (Player.causeExtraKnockback on a + /// ServerPlayer): a hurt that marked the velocity sends it at once, and + /// the server's copy goes back to the velocity it had before the hit. + pub(super) fn guest_struck_by( + &mut self, + host: &mut LanHost, + conn: u32, + f: impl FnOnce(&mut Self) -> R, + ) -> Option { + let (result, sent) = self.as_guest(host, conn, |g| { + let before = g.player.as_ref().map(|p| p.velocity); + let result = f(g); + let sent = g.player.as_mut().zip(before).and_then(|(p, before)| { + std::mem::take(&mut p.health.sync_velocity) + .then(|| std::mem::replace(&mut p.velocity, before)) + }); + (result, sent) + })?; + self.send_guest_motion(host, conn, sent); + Some(result) + } + + /// ClientboundSetEntityMotionPacket to a guest about themselves. + pub(super) fn send_guest_motion(&self, host: &LanHost, conn: u32, velocity: Option) { + if let (Some(v), Some(g)) = (velocity, host.hub.guest(conn)) { g.send(&C::SetEntityMotion(play::SetEntityMotion { id: g.entity_id, velocity: [v.x, v.y, v.z], })); } - Some(result) } } diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index d2c643088..74c88895b 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -240,7 +240,7 @@ impl Game<'_> { && harm && match victim { Victim::Host => land(self), - Victim::Guest(conn) => self.guest_hit_by(host, conn, land).unwrap_or(false), + Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or(false), }; let sound = match (hurt, s.crit, s.scale > 0.9) { (false, ..) => "minecraft:entity.player.attack.nodamage", diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 9edbb4f2a..0a626b1e7 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -296,6 +296,10 @@ pub struct PlayerMotion { pub freeze_immune: bool, /// `Entity.oldPosition`: where this tick started. pub old_position: Vec3, + /// The server's copy of a player another client moves (a LAN guest), while + /// it travels on the server: `isLocalInstanceAuthoritative` is false, so + /// its moves check no fall damage. + pub server_copy: bool, /// `Entity.applyEffectsFromBlocks` runs after travel (always in the game; /// differential fixtures turn it off where their reference does). pub block_effects: bool, @@ -460,6 +464,7 @@ impl PlayerMotion { leather_boots: false, freeze_immune: false, old_position: position, + server_copy: false, block_effects: true, powder_snow_entered: Vec::new(), hurt_log: Vec::new(), @@ -467,6 +472,16 @@ impl PlayerMotion { border: None, }) } + /// LivingEntity.aiStep: speeds too small to matter stop. + fn drop_tiny_velocity(&mut self) { + let v = &mut self.velocity; + if v.x * v.x + v.z * v.z < 9.0e-6 { + (v.x, v.z) = (0.0, 0.0); + } + if v.y.abs() < 0.003 { + v.y = 0.0; + } + } /// `Entity.getTicksRequiredToFreeze`. pub const TICKS_REQUIRED_TO_FREEZE: i32 = 140; /// `Entity.getPercentFrozen`. @@ -920,15 +935,7 @@ impl MotionWorld<'_, '_, '_> { if self.player.no_jump_delay > 0 { self.player.no_jump_delay -= 1; } - let mut velocity = self.player.velocity; - if velocity.x * velocity.x + velocity.z * velocity.z < 9.0e-6 { - velocity.x = 0.0; - velocity.z = 0.0; - } - if velocity.y.abs() < 0.003 { - velocity.y = 0.0; - } - self.player.velocity = velocity; + self.player.drop_tiny_velocity(); let mut input = match input { TickInput::Living(v) => Vec3::new( f64::from(v[0] * 0.98), @@ -947,9 +954,38 @@ impl MotionWorld<'_, '_, '_> { } self.jump_phase()?; let before_travel = self.player.bounds(); - // Player.travel: swim steering, then LivingEntity.travel (fluids - // first, then gliding, then air), keeping 0.6 of the vertical speed - // while flying. + self.player_travel(input)?; + if self.player.block_effects { + self.apply_effects_from_blocks()?; + } + // LivingEntity.aiStep "freezing" (server). + if !self.player.in_powder_snow || !self.player.can_freeze() { + self.player.ticks_frozen = (self.player.ticks_frozen - 2).max(0); + } + self.player.remove_frost()?; + let on = self.support(movement_support::LEGACY_SUPPORT_OFFSET)?; + let on_air = self.assets.registry.state(self.block(on)).is_none_or(|s| { + matches!( + s.name.as_str(), + "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" + ) + }); + self.player.try_add_frost(on_air)?; + if self.player.health.tick_count % 40 == 0 + && self.player.is_fully_frozen() + && self.player.can_freeze() + { + self.freeze_damage()?; + } + if self.player.auto_spin_attack_ticks > 0 { + self.player.auto_spin_attack_ticks -= 1; + self.check_auto_spin_attack(before_travel); + } + Ok(()) + } + /// Player.travel: swim steering, then LivingEntity.travel (fluids first, + /// then gliding, then air), keeping 0.6 of the vertical speed while flying. + fn player_travel(&mut self, input: Vec3) -> Result<()> { if self.player.swimming { let look_y = horizon_world::view_direction::view_vector(self.player.pitch, self.player.yaw).y; @@ -979,34 +1015,29 @@ impl MotionWorld<'_, '_, '_> { if let Some(y) = flying_y { self.player.velocity.y = y * 0.6; } - if self.player.block_effects { - self.apply_effects_from_blocks()?; - } - // LivingEntity.aiStep "freezing" (server). - if !self.player.in_powder_snow || !self.player.can_freeze() { - self.player.ticks_frozen = (self.player.ticks_frozen - 2).max(0); - } - self.player.remove_frost()?; - let on = self.support(movement_support::LEGACY_SUPPORT_OFFSET)?; - let on_air = self.assets.registry.state(self.block(on)).is_none_or(|s| { - matches!( - s.name.as_str(), - "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" - ) - }); - self.player.try_add_frost(on_air)?; - if self.player.health.tick_count % 40 == 0 - && self.player.is_fully_frozen() - && self.player.can_freeze() - { - self.freeze_damage()?; - } - if self.player.auto_spin_attack_ticks > 0 { - self.player.auto_spin_attack_ticks -= 1; - self.check_auto_spin_attack(before_travel); - } Ok(()) } + /// ServerPlayer's own travel: the server simulates a player too + /// (`MoveSimulationType.AUTHORITATIVE_SIDE_AND_SERVER`), with no input + /// (it never sets xxa/zza). Only the delta movement it leaves stays: it + /// is what a hurt sends the player (`ServerEntity.sendChanges`), and + /// what the next knockback starts from; the client's next move places + /// the player. + pub fn server_travel(&mut self) -> Result<()> { + let p = &mut *self.player; + let (position, ground, collision) = (p.position, p.ground, p.collision); + let (history, fall_distance, steps) = (p.history.clone(), p.fall_distance, p.steps); + let events = p.events.len(); + p.drop_tiny_velocity(); + p.server_copy = true; + let travelled = self.player_travel(Vec3::ZERO); + let p = &mut *self.player; + p.server_copy = false; + (p.position, p.ground, p.collision) = (position, ground, collision); + (p.history, p.fall_distance, p.steps) = (history, fall_distance, steps); + p.events.truncate(events); + travelled + } /// `LivingEntity.checkAutoSpinAttack`: the first living entity in the /// box swept this tick takes the hit and ends the spin, bouncing the /// player back at a fifth of its speed; a wall ends it too. @@ -1678,7 +1709,7 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { &mut self.player.history } fn locally_authoritative(&mut self) -> Result { - Ok(true) + Ok(!self.player.server_copy) } fn set_on_ground_with_movement( &mut self, @@ -2327,6 +2358,64 @@ mod tests { assert_eq!(player.position.y, 4.0); } + #[test] + fn server_travel_moves_only_the_velocity() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 1).unwrap(); + let at = Vec3::new(20.5, 4.0, 20.5); + let mut player = PlayerMotion::new(&resources, at).unwrap(); + let mut travel = |player: &mut PlayerMotion| { + MotionWorld { + entities: &[], + player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + } + .server_travel() + .unwrap() + }; + // A knockback on the ground (vanilla's server sends 0.21840 0.27516 + // after a zombie's hit): ground friction, then gravity and drag. + player.ground.on_ground = true; + player.velocity = Vec3::new(-0.4, 0.3608, 0.0); + travel(&mut player); + assert!( + (player.velocity.x + 0.2184).abs() < 1e-6, + "{:?}", + player.velocity + ); + assert!( + (player.velocity.y - 0.275184).abs() < 1e-6, + "{:?}", + player.velocity + ); + assert_eq!(player.position, at); + assert!(player.ground.on_ground); + // Falling onto the ground hurts no one on the server's copy, and leaves + // the fall to the client's moves. + let health = player.health.health(); + player.position = Vec3::new(20.5, 4.5, 20.5); + player.ground.on_ground = false; + player.fall_distance = 10.0; + player.velocity = Vec3::new(0.0, -1.0, 0.0); + travel(&mut player); + assert_eq!(player.velocity.y, -0.0784000015258789); + assert_eq!(player.health.health(), health); + assert_eq!(player.fall_distance, 10.0); + assert!(player.events.is_empty()); + } + #[test] fn spectator_scroll_speed_controls_horizontal_and_vertical_flight() { let root = Path::new(env!("CARGO_MANIFEST_DIR")) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index f44a84ea8..bb527c467 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -222,6 +222,9 @@ address. The script then checks, from both sides, what a guest's game used to ge spider's bite poisons them (#1480, #1484). - cursor: the host and the guest each close their inventory with a stack on the cursor: it goes back into their inventory, none is thrown and the cursor is empty (#1283). +- knockback: the host hits the guest three times, then the guest the host, two seconds apart: each + hit slides the victim as far as vanilla's does, 1.989 blocks (a guest's server-side + velocity settles between hits; it used to add up, so each push went further). 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). @@ -5293,5 +5296,49 @@ CHECKS += ['digging'] CHECK_FNS.update(digging=check_digging) +# How far a plain wooden sword hit slides a standing player in vanilla: LivingEntity.knockback(0.4) from +# the server copy's (0, -0.0784, 0), then the victim's own client. +VANILLA_PUSH = 1.989 + + +def check_knockback(host, guest, out): + if dead(guest): + guest.raw('respawn') + guest.wait(40) + host('command', command='gamerule pvp true') + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='item replace entity @s weapon.mainhand with minecraft:wooden_sword') + g('command', command='effect give @s minecraft:resistance 1000 4 true') + face_each_other(host, guest) + pushes = {} + try: + for name, attacker, victim in (('host hits guest', host, guest), ('guest hits host', guest, host)): + # The victim is never teleported (a teleport resets its velocity): the attacker steps up to it from + # the west, then the east, then the west again. + for side in (-3, 3, -3): + vx, vy, vz = pos_of(victim) + attacker('command', command=f'tp @s {vx + side:.2f} {vy:.2f} {vz:.2f}') + attacker.wait(40) # a full charge, and the last push long settled + attacker.raw('look-at', f'{vx:.2f}', f'{vy + 1.6:.2f}', f'{vz:.2f}') + attacker.wait(5) + before = pos_of(victim) + attacker.raw('attack') + victim.wait(30) + after = pos_of(victim) + pushes.setdefault(name, []).append(round(math.dist(before[0::2], after[0::2]), 3)) + attacker.shot(out, 'knockback-' + name.replace(' ', '-')) + finally: + for g in (host, guest): + g('command', command='effect clear @s minecraft:resistance') + for name, distances in pushes.items(): + assert all(abs(d - VANILLA_PUSH) < 0.03 for d in distances), f'{name}: not {VANILLA_PUSH} each time: {pushes}' + return pushes + + +CHECKS += ['knockback'] +CHECK_FNS.update(knockback=check_knockback) + + if __name__ == '__main__': main() diff --git a/tools/test_server_knockback_parity.py b/tools/test_server_knockback_parity.py index cd061321d..547e803a2 100644 --- a/tools/test_server_knockback_parity.py +++ b/tools/test_server_knockback_parity.py @@ -56,8 +56,6 @@ PROPERTIES = { 'pause-when-empty-seconds': '-1', } # Cases Horizon still gets wrong, and why. -VELOCITY = ("a guest's server-side velocity never travels and a hit is sent before it would: each knockback starts " - "from the last one's (ServerPlayer's travel, ServerEntity.sendChanges, Player.causeExtraKnockback)") SPRINT = "the server never sends a guest its own sprint flag, so a sprint hit doesn't stop the attacker's sprint" YAW = "the extra knockback's direction comes from f32 sin/cos, not Mth's sine table (z is -2e-8 a block, not 0)" KNOWN = { @@ -65,16 +63,9 @@ KNOWN = { 'cow-knockback-2': YAW, 'zombie-sprint': f'{SPRINT}; {YAW}', 'zombie-knockback-2': YAW, - 'pvp-plain': VELOCITY, - 'pvp-sprint': f'{VELOCITY}; {SPRINT}', - 'pvp-knockback-2': VELOCITY, - 'pvp-crit': VELOCITY, - 'pvp-netherite': VELOCITY, - 'pvp-twice': VELOCITY, - 'pvp-sprint-twice': f'{VELOCITY}; {SPRINT}', - 'pvp-mace': f'{VELOCITY}; a smash on a player runs none of MaceItem.hurtEnemy (the attacker\'s fall goes on)', - 'pvp-cooldown': f'{VELOCITY}; a hit inside the hurt cooldown still knocks back (LivingEntity.hurtServer)', - 'zombie-hits-bob': VELOCITY, + 'pvp-sprint': SPRINT, + 'pvp-sprint-twice': SPRINT, + 'pvp-mace': "a smash on a player runs none of MaceItem.hurtEnemy (the attacker's fall goes on)", } A = (0.5, -60.0, 0.5) # Alice, facing east (yaw -90)