A guest's door, trapdoor, fence gate, lever and button use is predicted

Vanilla's MultiPlayerGameMode.useItemOn runs the use on the client's own
level inside startPrediction, records each block it changes under the
packet's sequence in BlockStatePredictionHandler, and keeps them until
ClientboundBlockChangedAckPacket settles them (a use the server refused
goes back). A Horizon guest only sent the use: its door opened one round
trip later.

The guest already ran the use on a dry copy of its level to know whether
the click ends there; the blocks that use changes are now kept on its
level as predictions under the use's sequence, as the break prediction
does, when they are all hand-operated blocks: a wooden or copper door,
trapdoor or fence gate, a lever or a button (an iron door has no hand use
and changes nothing). The sound still comes from the server.

lan_e2e `predict`: with the host process frozen, the oak door the guest
clicks is already open on the guest's side (both halves), stays open on
both sides once the server answers, and an iron door stays shut.

Fixes #869

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-21 21:46:32 +02:00
parent c1b5fe95d2
commit a4247e9323
2 changed files with 102 additions and 10 deletions
+61 -7
View File
@@ -3244,7 +3244,11 @@ impl Game<'_> {
.and_then(|h| self.res.items().get(&h.item))
.is_some_and(|i| i.block.is_some());
if let Some(hit) = self.pick() {
let reacts = hand == Hand::Main && self.remote_block_reacts(&hit, held.as_ref());
let (reacts, changes) = if hand == Hand::Main {
self.remote_block_reacts(&hit, held.as_ref())
} else {
(false, Vec::new())
};
let seq = self.next_sequence();
let cursor = [
(hit.point[0] - f64::from(hit.pos[0])) as f32,
@@ -3270,6 +3274,9 @@ impl Game<'_> {
r.use_target = Some(hit.pos);
r.placing = Some((target, ticks));
}
if reacts {
self.predict_use(&changes, seq);
}
if held_block {
self.with_hand(hand, Game::swing_arm);
return true;
@@ -3279,15 +3286,60 @@ impl Game<'_> {
false
}
/// MultiPlayerGameMode.useItemOn inside startPrediction: the blocks the
/// use changed on this client's level at once, each kept as predicted
/// under the use's sequence until the server acknowledges it (a use the
/// server refused goes back). Only the blocks a hand opens or flips: a
/// wooden or copper door, trapdoor or fence gate, a lever or a button;
/// whatever else the use changes waits for the server.
fn predict_use(
&mut self,
changes: &[(horizon_core::position::BlockPos, BlockStateId)],
seq: i32,
) {
let facts = self.res.facts();
let predicted = |state: BlockStateId| {
let name = facts.get(state).name.trim_start_matches("minecraft:");
((name.ends_with("_door") || name.ends_with("_trapdoor")) && !name.starts_with("iron_"))
|| name.ends_with("_fence_gate")
|| name.ends_with("_button")
|| name == "lever"
};
if changes.is_empty()
|| !changes
.iter()
.all(|(p, s)| predicted(*s) && predicted(self.world.block(p.x, p.y, p.z)))
{
return;
}
for &(p, state) in changes {
let pos = [p.x, p.y, p.z];
let before = self.world.block(p.x, p.y, p.z);
// BlockStatePredictionHandler.retainKnownServerState.
if let Some(r) = self.remote.as_mut() {
r.predictions
.entry(pos)
.and_modify(|e| e.0 = seq)
.or_insert((seq, before.0 as i32));
}
self.set_block(pos, state.0 as i32);
}
}
/// Whether the block hit takes a main-hand right click with `held`
/// (`BlockState.useItemOn`, then `useWithoutItem`): a door, a button, a
/// container. Vanilla's client runs it on its own level first; this runs
/// it on a copy that keeps no change.
fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> bool {
/// container, and the blocks it changed. Vanilla's client runs it on its
/// own level first; this runs it on a copy, and `predict_use` keeps the
/// changes it predicts.
fn remote_block_reacts(
&self,
hit: &super::Hit,
held: Option<&ItemStack>,
) -> (bool, Vec<(horizon_core::position::BlockPos, BlockStateId)>) {
// Player.isSecondaryUseActive with something in either hand.
let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some();
if self.keys.contains(&KeyCode::ShiftLeft) && hands_full {
return false;
return (false, Vec::new());
}
use horizon_core::geometry::Direction;
let face = match hit.face {
@@ -3303,7 +3355,8 @@ impl Game<'_> {
changed: HashMap::new(),
random: horizon_core::random::LegacyRandom::new(0),
};
self.res
let reacts = self
.res
.behaviours()
.use_item_on(
&mut level,
@@ -3314,7 +3367,8 @@ impl Game<'_> {
self.use_context(),
held.map(|s| &*s.item),
)
.consumes_action()
.consumes_action();
(reacts, level.changed.into_iter().collect())
}
/// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether
+41 -3
View File
@@ -52,6 +52,8 @@ address. The script then checks, from both sides, what a guest's game used to ge
its crafting grid and gathers a stack with a double click; the server has each.
- 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.
- predict: with the host frozen, the oak door the guest opens opens on the guest's screen at once (its
prediction), and stays open once the server answers; an iron door stays shut (#869).
- 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.
- eat: holding right click with bread, the guest's own screen plays the eating (the item in use
@@ -111,7 +113,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', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth']
class Game:
@@ -1255,6 +1257,42 @@ def check_sleep(host, guest, out):
assert lying['host'] and lying['guest'], f'a sleeping player is drawn standing: {detail}'
assert not lying['after'], f'a player up again is still drawn lying: {detail}'
return detail
def check_predict(host, guest, out):
# MultiPlayerGameMode.useItemOn under startPrediction (#869): the guest's door opens on its own screen
# at once, with the host (the server) frozen, and the server's answer later agrees; an iron door
# (no hand use) stays shut on both sides.
guest('command', command='gamemode survival')
guest('command', command='clear @s')
x, y, z = (int(v // 1) for v in pos_of(guest))
wood, iron = (x - 1, y, z + 2), (x + 1, y, z + 2)
for (bx, by, bz), kind in ((wood, 'oak_door'), (iron, 'iron_door')):
for half, dy in (('lower', 0), ('upper', 1)):
host('command', command=f'setblock {bx} {by + dy} {bz} minecraft:{kind}[facing=north,hinge=right,half={half}]')
guest.wait(20)
state = lambda game, at: game.raw('block', *at)['state']
seen = {}
os.kill(host.pid, signal.SIGSTOP)
try:
guest.raw('interact', *wood)
seen['guest_frozen'] = (state(guest, wood), state(guest, (wood[0], wood[1] + 1, wood[2])))
guest.raw('interact', *iron)
seen['guest_iron_frozen'] = state(guest, iron)
finally:
os.kill(host.pid, signal.SIGCONT)
guest.wait(20)
seen['guest_after'] = state(guest, wood)
seen['host_after'] = state(host, wood)
seen['iron_after'] = (state(guest, iron), state(host, iron))
guest.shot(out, 'predict')
for (bx, by, bz) in (wood, iron):
host('command', command=f'fill {bx} {by} {bz} {bx} {by + 1} {bz} minecraft:air')
assert all('open=true' in s for s in seen['guest_frozen']), f'the door waited for the server: {seen}'
assert 'open=true' in seen['guest_after'] and 'open=true' in seen['host_after'], f'the door did not stay open: {seen}'
assert 'open=false' in seen['guest_iron_frozen'], f'the guest opened an iron door by hand: {seen}'
assert all('open=false' in s for s in seen['iron_after']), f'an iron door opened: {seen}'
return seen
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))
@@ -1712,7 +1750,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, 'predict': check_predict}
def run(ctl, out, resources, checks):
@@ -1721,7 +1759,7 @@ def run(ctl, out, resources, checks):
host.d.env['HORIZON_SERVER_THREAD'] = '1'
results = {}
try:
host('launch', wait=False, offscreen=sys.platform == 'darwin')
host.pid = host('launch', wait=False, offscreen=sys.platform == 'darwin')['pid']
# Guests' commands need the world's Allow Commands as well as the LAN's (#372): a creative
# world has them; everyone plays in survival.
host.raw('open', 'Lan', 5, 'creative')