Merge pull request #470 from ludovic111/fix/lan-pvp

LAN: PvP between the host and guests
This commit is contained in:
Ludovic Marie
2026-10-16 13:02:54 +02:00
committed by GitHub
7 changed files with 246 additions and 77 deletions
+55 -36
View File
@@ -63,6 +63,7 @@ mod lan;
mod lan_actions;
mod lan_crafting;
mod lan_mobs;
mod lan_pvp;
mod lan_screen;
mod lan_trading;
mod leads;
@@ -1108,6 +1109,27 @@ fn facing_offset(facing: &str) -> [i32; 3] {
_ => [0, -1, 0],
}
}
/// How far along `dir` (within `reach`) a ray from `eye` enters `b`.
fn ray_box(eye: [f64; 3], dir: [f64; 3], reach: f64, b: Aabb) -> Option<f64> {
let (min, max) = (b.min_position(), b.max_position());
let (lo, hi) = ([min.x, min.y, min.z], [max.x, max.y, max.z]);
let (mut t0, mut t1) = (0.0f64, reach);
for a in 0..3 {
if dir[a].abs() < 1e-9 {
if eye[a] < lo[a] || eye[a] > hi[a] {
return None;
}
continue;
}
let (mut ta, mut tb) = ((lo[a] - eye[a]) / dir[a], (hi[a] - eye[a]) / dir[a]);
if ta > tb {
std::mem::swap(&mut ta, &mut tb);
}
t0 = t0.max(ta);
t1 = t1.min(tb);
}
(t0 <= t1).then_some(t0)
}
fn view_vector(yaw: f32, pitch: f32) -> [f64; 3] {
let (y, p) = (f64::from(yaw).to_radians(), f64::from(pitch).to_radians());
[-y.sin() * p.cos(), -p.sin(), y.cos() * p.cos()]
@@ -5664,31 +5686,41 @@ impl Game<'_> {
if !m.alive() {
continue;
}
let b = m.bounds();
let (min, max) = (b.min_position(), b.max_position());
let (lo, hi) = ([min.x, min.y, min.z], [max.x, max.y, max.z]);
let (mut t0, mut t1) = (0.0f64, reach);
let mut hit = true;
for a in 0..3 {
if dir[a].abs() < 1e-9 {
if eye[a] < lo[a] || eye[a] > hi[a] {
hit = false;
}
continue;
}
let (mut ta, mut tb) = ((lo[a] - eye[a]) / dir[a], (hi[a] - eye[a]) / dir[a]);
if ta > tb {
std::mem::swap(&mut ta, &mut tb);
}
t0 = t0.max(ta);
t1 = t1.min(tb);
}
if hit && t0 <= t1 && best.is_none_or(|b| t0 < b.1) {
best = Some((i, t0));
if let Some(t) = ray_box(eye, dir, reach, m.bounds())
&& best.is_none_or(|b| t < b.1)
{
best = Some((i, t));
}
}
best
}
/// `Player.attack`'s damage against `target_kind` (with the attack
/// strength and whether it is a critical hit): the weapon and effects
/// scaled by the attack strength, a mace's smash, the critical hit, then
/// enchantments.
pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) {
let hand_damage = 1.0
+ self
.held()
.and_then(|h| self.res.items.get(&h.item))
.map_or(0.0, |i| i.attack_damage);
let damage = hand_damage + self.effect_attack_bonus();
let scale = self.attack_strength_scale();
let mut amount = damage * (0.2 + scale * scale * 0.8);
// Item.getAttackDamageBonus (a mace's smash), before the critical hit.
amount += self.smash_damage_bonus(target_kind);
let player = self.player.as_ref();
// Player.canCriticalAttack: falling, off the ground, not sprinting.
let falling =
player.is_some_and(|p| !p.ground.on_ground && p.fall_distance > 0.0 && !p.sprinting);
let crit = scale > 0.9 && falling;
if crit {
amount *= 1.5;
}
// Enchantment damage (sharpness, smite, bane) scaled by the attack strength.
amount += self.enchant_damage_bonus(target_kind) * scale;
(amount, scale, crit)
}
/// `Player.getAttackStrengthScale(0.5)`.
fn attack_strength_scale(&self) -> f32 {
let speed = self
@@ -5746,6 +5778,7 @@ impl Game<'_> {
|| self.attack_boat(hand_damage)
|| self.attack_cart(hand_damage)
|| self.attack_dragon()
|| self.attack_guest()
{
return true;
}
@@ -5762,23 +5795,9 @@ impl Game<'_> {
return false;
}
}
let damage = hand_damage + self.effect_attack_bonus();
let scale = self.attack_strength_scale();
let mut amount = damage * (0.2 + scale * scale * 0.8);
let target_kind = self.mobs[index].kind.id.clone();
let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"));
// Item.getAttackDamageBonus (a mace's smash), before the critical hit.
amount += self.smash_damage_bonus(&target_kind);
let player = self.player.as_ref();
// Player.canCriticalAttack: falling, off the ground, not sprinting.
let falling =
player.is_some_and(|p| !p.ground.on_ground && p.fall_distance > 0.0 && !p.sprinting);
let crit = scale > 0.9 && falling;
if crit {
amount *= 1.5;
}
// Enchantment damage (sharpness, smite, bane) scaled by the attack strength.
amount += self.enchant_damage_bonus(&target_kind) * scale;
let (amount, scale, crit) = self.melee_damage(&target_kind);
self.attack_ticks = 0;
if let Some(p) = self.player.as_mut()
&& !self.creative
+8 -3
View File
@@ -1377,7 +1377,12 @@ impl Game<'_> {
pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) {
self.mob_hits_player(amount, from, kind);
}
fn mob_hits_player(&mut self, amount: f32, from: [f64; 3], damage_type: &str) -> bool {
pub(super) fn mob_hits_player(
&mut self,
amount: f32,
from: [f64; 3],
damage_type: &str,
) -> bool {
if self.creative {
return false;
}
@@ -1390,8 +1395,8 @@ impl Game<'_> {
.is_some_and(|t| t.contains(damage_type));
let blocking = self.player_blocking(Some(from), damage_type, false);
let raised = blocking.is_some();
// Melee: the attacker stands at `from`.
let attacker = (!projectile)
// Melee: the attacker stands at `from` (another player's hit has no mob behind it).
let attacker = (!projectile && damage_type != "minecraft:player_attack")
.then(|| {
self.mobs
.iter()
+1
View File
@@ -143,6 +143,7 @@ impl Game<'_> {
|| before(self.cart_hit().map(|h| h.1))
|| before(self.dragon_hit().map(|h| h.1))
|| before(self.mob_hit().map(|h| h.1))
|| before(self.guest_hit().map(|h| h.1))
}
/// `LocalPlayer.isHandsBusy`: paddling a boat.
fn hands_busy(&self) -> bool {
@@ -582,6 +582,12 @@ impl Game<'_> {
if host.hub.guests[gi].spectator() {
return;
}
if let Some(victim) = Self::pvp_victim(host, conn, id) {
if let Some(Some(strike)) = self.as_guest(host, conn, |g| g.pvp_strike()) {
self.pvp_land(host, victim, &strike);
}
return;
}
let (old_yaw, old_pitch) = (host.hub.guests[gi].yaw, host.hub.guests[gi].pitch);
if self.look_at_entity(host, gi, id).is_none() {
return;
+36 -35
View File
@@ -114,8 +114,7 @@ impl Game<'_> {
views
}
/// Mob events aimed at a guest, run as that guest. Knockback reaches
/// their client (`hurtMarked`: ClientboundSetEntityMotionPacket).
/// Mob events aimed at a guest, run as that guest (`guest_hit_by`).
pub(super) fn lan_guest_mob_events(&mut self, events: Vec<(u32, MobEvent)>) {
if events.is_empty() {
return;
@@ -124,17 +123,9 @@ impl Game<'_> {
return;
};
for (conn, e) in events {
let pushed = self.as_guest(&mut host, conn, |g| {
let before = g.player.as_ref().map(|p| p.velocity);
self.guest_hit_by(&mut host, conn, |g| {
let _ = g.handle_mob_events(vec![e]);
g.player
.as_ref()
.map(|p| p.velocity)
.filter(|v| Some(*v) != before)
});
if let Some(Some(v)) = pushed {
send_motion(&host, conn, v);
}
}
self.lan = Some(host);
}
@@ -148,15 +139,7 @@ impl Game<'_> {
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead && !g.spectator())
.map(|g| {
let [x, y, z] = g.position;
let height = if g.sneaking { 1.5 } else { 1.8 };
let b = Aabb::new(
Vec3::new(x - 0.3, y, z - 0.3),
Vec3::new(x + 0.3, y + height, z + 0.3),
);
(Who::Mob(g.entity_id as u32), b)
})
.map(|g| (Who::Mob(g.entity_id as u32), guest_bounds(g)))
.collect()
}
@@ -173,36 +156,54 @@ impl Game<'_> {
.find(|g| g.entity_id as u32 == id)
.map(|g| g.conn);
if let Some(conn) = conn {
let pushed = self.as_guest(&mut host, conn, |g| {
let before = g.player.as_ref().map(|p| p.velocity);
self.guest_hit_by(&mut host, conn, |g| {
let hit = Hit::Entity {
who: Who::Player,
at,
};
let _ = g.projectile_hit(p, hit);
g.player
.as_ref()
.map(|p| p.velocity)
.filter(|v| Some(*v) != before)
});
if let Some(Some(v)) = pushed {
send_motion(&host, conn, v);
}
}
self.lan = Some(host);
conn.is_some()
}
}
fn send_motion(host: &LanHost, conn: u32, v: Vec3) {
if let Some(g) = host.hub.guest(conn) {
g.send(&C::SetEntityMotion(play::SetEntityMotion {
id: g.entity_id,
velocity: [v.x, v.y, v.z],
}));
impl Game<'_> {
/// Hurt a guest: `f` runs as them, and the knockback it gave reaches
/// their client (`hurtMarked`: ClientboundSetEntityMotionPacket).
pub(super) fn guest_hit_by<R>(
&mut self,
host: &mut LanHost,
conn: u32,
f: impl FnOnce(&mut Self) -> R,
) -> Option<R> {
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))
})?;
if let (Some(v), Some(g)) = (pushed, host.hub.guest(conn)) {
g.send(&C::SetEntityMotion(play::SetEntityMotion {
id: g.entity_id,
velocity: [v.x, v.y, v.z],
}));
}
Some(result)
}
}
/// A guest's bounding box (0.6 wide, 1.8 tall, 1.5 crouching).
pub(super) fn guest_bounds(g: &horizon_client::lan::guest::Guest) -> Aabb {
let [x, y, z] = g.position;
let height = if g.sneaking { 1.5 } else { 1.8 };
Aabb::new(
Vec3::new(x - 0.3, y, z - 0.3),
Vec3::new(x + 0.3, y + height, z + 0.3),
)
}
#[cfg(test)]
mod tests {
use super::*;
+110
View File
@@ -0,0 +1,110 @@
//! Players hitting players in an open world (`Player.attack` on a player):
//! the host hits a guest, a guest hits the host or another guest. The hit
//! is worked out as the attacker (weapon, attack strength, critical hit,
//! enchantments, a mace's smash) and lands on the victim like any player
//! attack (blocking, armour, knockback), when the `pvp` game rule allows it
//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`).
use super::{Game, lan::LanHost, lan_mobs::guest_bounds, ray_box, view_vector};
/// Who a player's attack lands on.
#[derive(Clone, Copy)]
pub(super) enum Victim {
Host,
Guest(u32),
}
/// The attacker's side of the hit.
pub(super) struct Strike {
amount: f32,
scale: f32,
crit: bool,
from: [f64; 3],
}
impl Game<'_> {
/// The guest on the host's crosshair and how far, within reach.
pub(super) fn guest_hit(&self) -> Option<(u32, f64)> {
let host = self.lan.as_ref()?;
let eye = self.eye_position()?;
let dir = view_vector(self.yaw, self.pitch);
let reach = if self.creative { 5.0 } else { 3.0 };
host.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded && !g.dead && !g.spectator())
.filter_map(|g| Some((g.conn, ray_box(eye, dir, reach, guest_bounds(g))?)))
.min_by(|a, b| a.1.total_cmp(&b.1))
}
/// The host's attack on the guest under the crosshair, when no mob or
/// block is nearer.
pub(super) fn attack_guest(&mut self) -> bool {
let Some((conn, d)) = self.guest_hit() else {
return false;
};
if self.mob_hit().is_some_and(|(_, m)| m < d) || !self.before_block(d) {
return false;
}
let Some(mut host) = self.lan.take() else {
return false;
};
if let Some(strike) = self.pvp_strike() {
self.pvp_land(&mut host, Victim::Guest(conn), &strike);
}
self.lan = Some(host);
true
}
/// The player `id` that guest `conn` attacks, if it is one.
pub(super) fn pvp_victim(host: &LanHost, conn: u32, id: i32) -> Option<Victim> {
if id == host.host_entity {
return Some(Victim::Host);
}
host.hub
.guests
.iter()
.find(|g| g.entity_id == id && g.conn != conn && g.placed && !g.dead)
.map(|g| Victim::Guest(g.conn))
}
/// The attacker's side of `Player.attack` (the host, or a guest swapped
/// in): the damage, the charge reset, the exhaustion and the swing.
pub(super) fn pvp_strike(&mut self) -> Option<Strike> {
let p = self.player.as_ref()?;
let from = [p.position.x, p.position.y, p.position.z];
let (amount, scale, crit) = self.melee_damage("minecraft:player");
self.attack_ticks = 0;
if let Some(p) = self.player.as_mut()
&& !self.creative
{
p.health.food.exhaustion = (p.health.food.exhaustion + 0.1).min(40.0);
}
self.swing_arm();
Some(Strike {
amount,
scale,
crit,
from,
})
}
/// The hit landing on the victim, then the attacker's attack sound.
pub(super) fn pvp_land(&mut self, host: &mut LanHost, victim: Victim, s: &Strike) {
let hurt = self.ui.rules.bool("pvp")
&& match victim {
Victim::Host => self.mob_hits_player(s.amount, s.from, "minecraft:player_attack"),
Victim::Guest(conn) => self
.guest_hit_by(host, conn, |g| {
g.mob_hits_player(s.amount, s.from, "minecraft:player_attack")
})
.unwrap_or(false),
};
let sound = match (hurt, s.crit, s.scale > 0.9) {
(false, ..) => "minecraft:entity.player.attack.nodamage",
(true, true, _) => "minecraft:entity.player.attack.crit",
(true, false, true) => "minecraft:entity.player.attack.strong",
(true, false, false) => "minecraft:entity.player.attack.weak",
};
self.audio.play(sound, Some(s.from), 1.0, 1.0);
}
}
+30 -3
View File
@@ -15,7 +15,8 @@ address. The script then checks, from both sides, what a guest's game used to ge
- damage: a guest in survival takes fall damage;
- mobs: with the host in creative, a zombie and a skeleton go for the guest and hurt them;
- hazards: a guest in survival gets hungry sprint-jumping and is hurt by lava, a block at the eyes,
drowning and the void (then respawns).
drowning and the void (then respawns);
- pvp: the guest and the host hit each other with a sword; with the pvp game rule off, nothing.
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).
@@ -42,7 +43,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', 'chest', 'crafting', 'damage', 'mobs', 'hazards']
CHECKS = ['tab', 'self', 'armour', 'nametags', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp']
class Game:
@@ -362,9 +363,35 @@ def check_hazards(host, guest, out):
return {'hunger': hunger, **hurt}
def check_pvp(host, guest, out):
for g in (host, guest):
g('command', command='gamemode survival')
g('command', command='item replace entity @s weapon.mainhand with minecraft:iron_sword')
face_each_other(host, guest)
hits = {}
try:
for name, rule, attacker in (('guest hits host', 'true', guest), ('host hits guest', 'true', host),
('pvp off', 'false', guest)):
host('command', command=f'gamerule pvp {rule}')
face_each_other(host, guest)
attacker.wait(30) # a full attack charge
victim = (lambda: host('state')['player']['health']) if attacker is guest else (lambda: remote(guest)['health'])
before = victim()
attacker.raw('attack')
attacker.wait(10)
hits[name] = (before, victim())
attacker.shot(out, 'pvp-' + name.replace(' ', '-'))
finally:
host('command', command='gamerule pvp true')
assert hits['guest hits host'][1] < hits['guest hits host'][0], f'the guest did not hurt the host: {hits}'
assert hits['host hits guest'][1] < hits['host hits guest'][0], f'the host did not hurt the guest: {hits}'
assert hits['pvp off'][1] == hits['pvp off'][0], f'pvp off still hurts: {hits}'
return hits
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}
'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp}
def run(ctl, out, resources, checks):