A player's arrow hurts the other players on a served world

A remote player's projectiles never hit other players: a player's shots
only looked for mobs and the host, a guest's flew as if the host had shot
it (so it could not hit the host until it left the host's box), and a hit
on a guest from another guest ran as the shooter, who has no hub to reach
the victim. No bow PvP on a server or between LAN players.

A player's arrows, snowballs and eggs now meet every player, a guest's
flying from that guest (Projectile.getOwner). A hit on another player runs
as the victim's hurt, refused when the pvp game rule is off or the teams
are allies without friendly fire (ServerPlayer.canHarmPlayer), which turns
the arrow back as a raised shield does (AbstractArrow.onHitEntity).
Pearls, potions and wind charges fly past players as before.

lan_e2e `arrows`: the guest shoots the host and the host the guest with a
bow, both hurt; with pvp off, no harm.

Part of #484

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-21 21:32:30 +02:00
parent c1b5fe95d2
commit 5763854b0d
4 changed files with 164 additions and 5 deletions
+3
View File
@@ -25,6 +25,9 @@ pub(super) struct CombatTracker {
pub(super) last_hurt_mob: Option<(u32, i64)>,
/// The mob whose projectile is hitting the player now.
pub(super) projectile_owner: Option<u32>,
/// The projectile hitting the player now is another player's that
/// `ServerPlayer.canHarmPlayer` refuses (the `pvp` rule, an ally).
pub(super) refuse_player_hit: bool,
/// The mob exploding now (`ServerExplosion.source`): its team's friendly
/// fire decides whom the blast may hurt.
pub(super) explosion_source: Option<u32>,
+24 -2
View File
@@ -1393,7 +1393,8 @@ impl Game<'_> {
from: [f64; 3],
damage_type: &str,
) -> bool {
if self.creative {
// ServerPlayer.canHarmPlayer refused another player's projectile.
if self.creative || self.combat.refuse_player_hit {
return false;
}
let projectile = self
@@ -1631,14 +1632,30 @@ impl Game<'_> {
w: &w,
targets: targets_guests,
};
let guest_entities = self.lan_guest_entities();
projectiles.retain_mut(|p| {
let mob_shot = !matches!(p.owner, Some(Who::Player));
let (keep, hit) = match (p.arrow.is_some(), mob_shot) {
// A player's arrows, snowballs and eggs meet every player; a
// guest's flies from that guest (Projectile.getOwner), not
// from the host, until it has left them.
let pvp = !mob_shot && super::lan_pvp::meets_players(&p.kind);
let shooter = p
.guest
.filter(|_| pvp)
.and_then(|c| guest_entities.iter().find(|(g, _)| *g == c))
.map(|&(_, id)| Who::Mob(id));
if shooter.is_some() {
p.owner = shooter;
}
let (keep, hit) = match (p.arrow.is_some(), mob_shot || pvp) {
(true, false) => horizon_client::arrows::tick(p, &scene, &arrow_targets),
(true, true) => horizon_client::arrows::tick(p, &scene, &arrow_targets_guests),
(false, false) => p.tick(&pw),
(false, true) => p.tick(&pw_guests),
};
if shooter.is_some() {
p.owner = Some(Who::Player);
}
if let Some(a) = p.arrow.as_mut() {
arrow_events.extend(a.events.drain(..).map(|e| (p.position, e)));
}
@@ -1690,6 +1707,11 @@ impl Game<'_> {
}
self.creatures.projectiles.append(&mut projectiles);
for (p, hit) in hits {
// A player's arrow on another player lands as the victim's hurt.
if let Some(victim) = self.projectile_pvp_victim(&p, hit) {
self.projectile_hits_player(&p, hit, victim)?;
continue;
}
// A guest's projectile lands as theirs: a pearl takes them, what
// it hurts answers to them. One hitting the host (`Who::Player`
// here) stays the host's hit.
+101 -1
View File
@@ -3,9 +3,26 @@
//! 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`).
//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`). A player's arrow on
//! another player lands the same way.
use super::{Game, lan::LanHost, lan_mobs::guest_bounds, ray_box, view_vector};
use horizon_client::{
Result,
mobs::Who,
projectiles::{Hit, Projectile, ProjectileKind},
};
/// The player projectiles that meet other players: arrows (their hurt), and
/// snowballs and eggs, which break on them (`Player.hurtServer` takes no 0
/// damage). Pearls, potions and wind charges fly past players as before.
pub(super) fn meets_players(kind: &ProjectileKind) -> bool {
matches!(
kind,
ProjectileKind::Arrow { .. } | ProjectileKind::Snowball | ProjectileKind::Egg
)
}
/// Who a player's attack lands on.
#[derive(Clone, Copy)]
pub(super) enum Victim {
@@ -105,6 +122,89 @@ impl Game<'_> {
})
}
/// The guests by connection, with their entity ids.
pub(super) fn lan_guest_entities(&self) -> Vec<(u32, u32)> {
self.lan.as_ref().map_or_else(Vec::new, |host| {
host.hub
.guests
.iter()
.map(|g| (g.conn, g.entity_id as u32))
.collect()
})
}
/// The player a player's projectile hit, when it hit one: the host for a
/// guest's shot, or a guest.
pub(super) fn projectile_pvp_victim(&self, p: &Projectile, hit: Hit) -> Option<Victim> {
if p.owner != Some(Who::Player) || !meets_players(&p.kind) {
return None;
}
let Hit::Entity { who, .. } = hit else {
return None;
};
match who {
Who::Player => p.guest.map(|_| Victim::Host),
Who::Mob(id) => self
.lan
.as_ref()?
.hub
.guests
.iter()
.find(|g| g.entity_id as u32 == id)
.map(|g| Victim::Guest(g.conn)),
}
}
/// A player's projectile on a player: the hit runs as the victim, whose
/// hurt refuses it when the `pvp` game rule or their teams forbid it
/// (`ServerPlayer.canHarmPlayer`; `AbstractArrow.onHitEntity` then turns
/// the arrow back).
pub(super) fn projectile_hits_player(
&mut self,
p: &Projectile,
hit: Hit,
victim: Victim,
) -> Result<()> {
let Hit::Entity { at, .. } = hit else {
return Ok(());
};
let Some(mut host) = self.lan.take() else {
return self.projectile_hit(p, hit);
};
let team_of = |game: &Self, name: &str| game.score.board.players_team(name).cloned();
let attacker = match p.guest {
Some(conn) => host.hub.guest(conn).and_then(|g| team_of(self, &g.name)),
None => self.player_team().cloned(),
};
let target = match victim {
Victim::Host => self.player_team().cloned(),
Victim::Guest(conn) => host.hub.guest(conn).and_then(|g| team_of(self, &g.name)),
};
let refused = !(self.ui.rules.bool("pvp")
&& horizon_client::scoreboard::teams_allow_damage(target.as_ref(), attacker.as_ref()));
let on_player = Hit::Entity {
who: Who::Player,
at,
};
let result = match victim {
Victim::Host => {
self.lan = Some(host);
self.combat.refuse_player_hit = refused;
let r = self.projectile_hit(p, on_player);
self.combat.refuse_player_hit = false;
return r;
}
Victim::Guest(conn) => self.guest_hit_by(&mut host, conn, |g| {
g.combat.refuse_player_hit = refused;
let r = g.projectile_hit(p, on_player);
g.combat.refuse_player_hit = false;
r
}),
};
self.lan = Some(host);
result.unwrap_or(Ok(()))
}
/// The hit landing on the victim with its extra knockback, then the
/// attacker's attack sound. Whether the victim was hurt.
pub(super) fn pvp_land(&mut self, host: &mut LanHost, victim: Victim, s: &Strike) -> bool {
+36 -2
View File
@@ -20,6 +20,7 @@ address. The script then checks, from both sides, what a guest's game used to ge
drowning and the void (then respawns);
- pvp: the guest and the host hit each other with a sword; with the pvp game rule off, or on one
team without friendly fire, nothing;
- arrows: the guest and the host shoot each other with a bow; with the pvp game rule off, nothing (#484);
- respawn: a player killed is drawn dead by the other side, and alive again once it respawns (the
respawned player is a new entity to the others); the host dies, and on the server thread
the guest too;
@@ -111,7 +112,7 @@ ROOT = Path(__file__).resolve().parents[1]
GUEST_NAME = 'Guest'
# The host plays single player on its server thread (--server-thread).
SERVER_THREAD = False
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth']
CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth']
class Game:
@@ -613,6 +614,39 @@ def check_pvp(host, guest, out):
return hits
def check_arrows(host, guest, out):
# A player's arrow on another player (#484): AbstractArrow.onHitEntity, refused by
# ServerPlayer.canHarmPlayer with the pvp game rule off (the arrow turns back).
for g in (host, guest):
g('command', command='gamemode survival')
g('command', command='clear @s')
g('command', command='item replace entity @s weapon.mainhand with minecraft:bow')
g('command', command='give @s minecraft:arrow 16')
hits = {}
try:
for name, rule, shooter in (('guest shoots host', 'true', guest), ('host shoots guest', 'true', host),
('pvp off', 'false', guest)):
host('command', command=f'gamerule pvp {rule}')
for g in (host, guest):
g('command', command='effect give @s minecraft:instant_health 1 5')
face_each_other(host, guest)
shooter.wait(20)
victim = (lambda: host('state')['player']['health']) if shooter is guest else (lambda: remote(guest)['health'])
before = victim()
shooter.raw('use-item', '--hold', 1.3) # a full draw (BowItem: 20 ticks)
shooter.wait(20)
hits[name] = (before, victim())
shooter.shot(out, 'arrows-' + name.replace(' ', '-'))
finally:
host('command', command='gamerule pvp true')
for g in (host, guest):
g('command', command='clear @s')
assert hits['guest shoots host'][1] < hits['guest shoots host'][0], f"the guest's arrow did not hurt the host: {hits}"
assert hits['host shoots guest'][1] < hits['host shoots guest'][0], f"the host's arrow did not hurt the guest: {hits}"
assert hits['pvp off'][1] == hits['pvp off'][0], f'pvp off, an arrow still hurts: {hits}'
return hits
def dead_players(game, want, ticks=60):
"""The other players `game`'s client draws dead, once that is `want` (empty or not) or after `ticks`."""
for _ in range(ticks // 5):
@@ -1712,7 +1746,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name
'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles,
'light': check_light, 'plates': check_plates,
'swings': check_swings, 'cracks': check_cracks,
'time': check_time, 'growth': check_growth}
'time': check_time, 'growth': check_growth, 'arrows': check_arrows}
def run(ctl, out, resources, checks):