diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 6bf76f160..051b77dd4 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -36,6 +36,11 @@ pub(super) struct GuestPlay { swing: horizon_client::first_person::SwingState, /// The block being dug and the face the client aimed at. digging: Option<([i32; 3], [i32; 3])>, + /// The server tick the digging started (ServerPlayerGameMode.destroyProgressStart). + dig_start: u64, + /// A block the client stopped digging before the server's time was up: it breaks once + /// its progress since `dig_start` is complete (ServerPlayerGameMode.hasDelayedDestroy). + delayed: Option<([i32; 3], u64)>, last_progress: i32, /// Hand movements the client announced and the host animated. swung: bool, @@ -350,35 +355,41 @@ impl Game<'_> { let face = direction(i32::from(a.direction)); let play = host.play.entry(conn).or_default(); play.digging = Some((a.pos, face)); + play.dig_start = host.hub.ticks; play.last_progress = -1; + // The pause between two blocks is the client's (MultiPlayerGameMode's + // destroyDelay); the server digs from the START it receives. + play.destroy_delay = 0; } 1 => {} - 2 | 3 => { + 3 => { + host.hub.ack(conn, a.sequence); + self.guest_stop_digging(host, conn, a.pos); + } + 2 => { host.hub.ack(conn, a.sequence); let play = host.play.entry(conn).or_default(); play.digging = None; play.mining = None; - if a.action == 2 { - let state = self.world.block(a.pos[0], a.pos[1], a.pos[2]).0 as i32; - host.hub.send_to( - conn, - &C::BlockUpdate(play::BlockUpdate { pos: a.pos, state }), - ); - host.hub.broadcast_near( - [ - f64::from(a.pos[0]), - f64::from(a.pos[1]), - f64::from(a.pos[2]), - ], - 64.0, - &C::BlockDestruction(play::BlockDestruction { - id: host.hub.guests[gi].entity_id, - pos: a.pos, - progress: 255, - }), - Some(conn), - ); - } + let state = self.world.block(a.pos[0], a.pos[1], a.pos[2]).0 as i32; + host.hub.send_to( + conn, + &C::BlockUpdate(play::BlockUpdate { pos: a.pos, state }), + ); + host.hub.broadcast_near( + [ + f64::from(a.pos[0]), + f64::from(a.pos[1]), + f64::from(a.pos[2]), + ], + 64.0, + &C::BlockDestruction(play::BlockDestruction { + id: host.hub.guests[gi].entity_id, + pos: a.pos, + progress: 255, + }), + Some(conn), + ); } 4 | 5 => { if !spectator { @@ -806,6 +817,7 @@ impl Game<'_> { } }); } + self.guest_delayed_destroy(host, conn); self.guest_server_tick(host, conn); self.guest_dig_feedback(host, conn); self.guest_pickups(host, gi); @@ -919,6 +931,81 @@ impl Game<'_> { }) } + /// ServerPlayerGameMode.handleBlockBreakAction, STOP_DESTROY_BLOCK: the client finished + /// digging `pos` (and predicted the break). The server breaks it if its own count of the + /// digging since START is at least 70 % done; otherwise it keeps digging alone and breaks + /// it when done (`guest_delayed_destroy`), so the client's broken block is never left + /// standing on the server. + fn guest_stop_digging(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) { + let ticks = host.hub.ticks; + let play = host.play.entry(conn).or_default(); + let dug = play.digging.take().is_some_and(|(p, _)| p == pos); + play.mining = None; + let start = play.dig_start; + let state = self.world.block(pos[0], pos[1], pos[2]); + if !dug || self.res.facts.is_air(state) { + return; + } + let progress = self + .as_guest(host, conn, |g| g.destroy_progress(pos)) + .map_or(0.0, |p| p * (ticks - start + 1) as f32); + if progress >= 0.7 { + self.guest_destroy(host, conn, pos); + } else { + let play = host.play.entry(conn).or_default(); + if play.delayed.is_none() { + play.delayed = Some((pos, start)); + } + } + } + + /// ServerPlayerGameMode.tick's delayed destroy: the block breaks once its progress since + /// the digging started is complete, unless something else removed it first. + fn guest_delayed_destroy(&mut self, host: &mut LanHost, conn: u32) { + let Some((pos, start)) = host.play.get(&conn).and_then(|p| p.delayed) else { + return; + }; + let ticks = host.hub.ticks; + let state = self.world.block(pos[0], pos[1], pos[2]); + let progress = if self.res.facts.is_air(state) { + None + } else { + self.as_guest(host, conn, |g| g.destroy_progress(pos)) + .map(|p| p * (ticks - start + 1) as f32) + }; + match progress { + Some(p) if p < 1.0 => {} + done => { + if let Some(play) = host.play.get_mut(&conn) { + play.delayed = None; + } + if done.is_some() { + self.guest_destroy(host, conn, pos); + } + } + } + } + + /// ServerPlayerGameMode.destroyBlock for a guest, its crack cleared for the others + /// (`destroyBlockProgress(id, pos, -1)`). + fn guest_destroy(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) { + self.as_guest(host, conn, |g| { + let _ = g.break_block(pos); + }); + if let Some(g) = host.hub.guest(conn) { + host.hub.broadcast_near( + [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], + 64.0, + &C::BlockDestruction(play::BlockDestruction { + id: g.entity_id, + pos, + progress: 255, + }), + Some(conn), + ); + } + } + /// The crack animation other players see. fn guest_dig_feedback(&mut self, host: &mut LanHost, conn: u32) { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index aa88896e8..d70021eab 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -88,6 +88,11 @@ pub(super) struct Remote { was_sprinting: bool, carried: Option, loaded_sent: bool, + /// BlockStatePredictionHandler: blocks changed ahead of the server (a predicted break), + /// with the sequence of the last action that changed them and the state the server + /// last said they have. Until the server acknowledges that sequence its block updates + /// only replace the remembered state; then the block takes it. + predictions: HashMap<[i32; 3], (i32, i32)>, /// Open container: (window id, menu name). menu: Option<(i32, String)>, /// The open menu's title as the server named it. @@ -271,6 +276,7 @@ impl Game<'_> { was_sprinting: false, carried: None, loaded_sent: false, + predictions: HashMap::new(), menu: None, menu_title: None, state_id: 0, @@ -509,6 +515,7 @@ impl Game<'_> { r.dimension = dimension; r.game_mode = spawn.game_type; r.loaded_sent = false; + r.predictions.clear(); self.set_mode_id(spawn.game_type); self.dim = if spawn.dimension == "minecraft:the_nether" { Dim::Nether @@ -636,6 +643,42 @@ impl Game<'_> { } } } + /// ClientLevel.setServerVerifiedBlockState: a block the client predicted keeps its + /// predicted state until the server acknowledges the action; the server's state is + /// remembered for then. + fn server_block(&mut self, pos: [i32; 3], state: i32) { + if let Some((_, known)) = self + .remote + .as_mut() + .and_then(|r| r.predictions.get_mut(&pos)) + { + *known = state; + return; + } + self.set_block(pos, state); + } + /// BlockStatePredictionHandler.endPredictionsUpTo (ClientboundBlockChangedAckPacket): the + /// actions up to `sequence` are settled, so the blocks they predicted take the state the + /// server gave them (a break the server refused comes back). + fn end_predictions(&mut self, sequence: i32) { + let Some(r) = self.remote.as_mut() else { + return; + }; + let settled: Vec<_> = r + .predictions + .iter() + .filter(|(_, (s, _))| *s <= sequence) + .map(|(&pos, &(_, state))| (pos, state)) + .collect(); + for (pos, state) in settled { + if let Some(r) = self.remote.as_mut() { + r.predictions.remove(&pos); + } + if self.world.block(pos[0], pos[1], pos[2]).0 as i32 != state { + self.set_block(pos, state); + } + } + } fn set_block(&mut self, pos: [i32; 3], state: i32) { let state = BlockStateId(state.max(0) as u32); if self.world.loaded(pos[0], pos[2]) @@ -879,7 +922,7 @@ impl Game<'_> { chunks_per_tick: 64.0, })); } - C::BlockUpdate(p) => self.set_block(p.pos, p.state), + C::BlockUpdate(p) => self.server_block(p.pos, p.state), C::SectionBlocksUpdate(p) => { let [sx, sy, sz] = p.section; for change in p.changes { @@ -889,10 +932,10 @@ impl Game<'_> { sy * 16 + (local & 15), sz * 16 + (local >> 4 & 15), ]; - self.set_block(pos, (change >> 12) as i32); + self.server_block(pos, (change >> 12) as i32); } } - C::BlockChangedAck(_) => {} + C::BlockChangedAck(p) => self.end_predictions(p.sequence), // ClientLevel.blockEvent: BlockEntity.triggerEvent (chest lids, // shulker boxes, bells) when the block is still the one it names. C::BlockEvent(p) => { @@ -2108,7 +2151,7 @@ impl Game<'_> { self.send(S::Punch(Empty)); if self.creative { let seq = self.next_sequence(); - self.predict_break(hit.pos, state); + self.predict_break(hit.pos, state, seq); self.send(S::PlayerAction(play::PlayerAction { action: 0, pos: hit.pos, @@ -2157,7 +2200,7 @@ impl Game<'_> { sequence: seq, })); if progress >= 1.0 { - self.predict_break(hit.pos, state); + self.predict_break(hit.pos, state, seq); if let Some(r) = self.remote.as_mut() { r.destroy_delay = 5; } @@ -2194,7 +2237,7 @@ impl Game<'_> { self.crack_particle(pos, hit.face, state); if done >= 1.0 { let seq = self.next_sequence(); - self.predict_break(pos, state); + self.predict_break(pos, state, seq); self.send(S::PlayerAction(play::PlayerAction { action: 3, pos, @@ -2226,7 +2269,14 @@ impl Game<'_> { } } /// MultiPlayerGameMode.destroyBlock: the predicted break. - fn predict_break(&mut self, pos: [i32; 3], state: BlockStateId) { + fn predict_break(&mut self, pos: [i32; 3], state: BlockStateId, sequence: i32) { + // BlockStatePredictionHandler.retainKnownServerState. + if let Some(r) = self.remote.as_mut() { + r.predictions + .entry(pos) + .and_modify(|p| p.0 = sequence) + .or_insert((sequence, state.0 as i32)); + } let s = self.res.facts.get(state).sounds.clone(); let at = [ f64::from(pos[0]) + 0.5, diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 954ffc714..00f346b07 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -97,6 +97,8 @@ pub struct Guest { pub menu_state: i32, pub sent_health: Option<(f32, i32, f32)>, pub sent_xp: Option<(f32, i32, i32)>, + /// The last action sequence to acknowledge at the next tick (-1: none). + pub ack_up_to: std::cell::Cell, pub sent_selected: usize, pub inbox: VecDeque, pub joined_tick: u64, @@ -178,6 +180,7 @@ impl Guest { menu_state: 0, sent_health: None, sent_xp: None, + ack_up_to: std::cell::Cell::new(-1), sent_selected: 0, inbox: VecDeque::new(), joined_tick: 0, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index fcae7c097..602a540b7 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -784,6 +784,15 @@ impl Hub { } } self.broadcast_block_changes(ctx.world); + // ServerGamePacketListenerImpl.tick: the actions handled since the last tick are + // acknowledged after the block changes they made were sent, so a client's predicted + // blocks settle on the server's states. + for g in &self.guests { + let sequence = g.ack_up_to.replace(-1); + if sequence >= 0 { + g.send(&C::BlockChangedAck(play::BlockChangedAck { sequence })); + } + } self.sync_containers(ctx.world); self.track_entities(ctx); for i in 0..self.guests.len() { @@ -1478,11 +1487,13 @@ impl Hub { } /// Acknowledge a block interaction (ClientboundBlockChangedAckPacket). + /// ServerGamePacketListenerImpl.ackBlockChangesUpTo: sent with the next tick's block + /// changes (`tick`). pub fn ack(&self, conn: u32, sequence: i32) { if sequence >= 0 && let Some(g) = self.guest(conn) { - g.send(&C::BlockChangedAck(play::BlockChangedAck { sequence })); + g.ack_up_to.set(g.ack_up_to.get().max(sequence)); } }