Merge pull request #627 from ludovic111/fix/offhand-on-server

Swap and sync the off hand on a server
This commit is contained in:
Ludovic Marie
2026-10-17 06:04:38 +02:00
committed by GitHub
3 changed files with 45 additions and 2 deletions
+7 -1
View File
@@ -8878,7 +8878,13 @@ impl Game<'_> {
}
_ => {}
},
// key.swapOffhand: ServerboundPlayerActionPacket SWAP_ITEM_WITH_OFFHAND.
// key.swapOffhand: on a server, ServerboundPlayerActionPacket SWAP_ITEM_WITH_OFFHAND
// (the server swaps the hands and sends both slots back; spectators can't).
KeyCode::KeyF if self.screen == Screen::Playing && self.remote.is_some() => {
if !self.spectator() {
self.remote_swap_hands();
}
}
KeyCode::KeyF if self.screen == Screen::Playing => {
std::mem::swap(&mut self.offhand, &mut self.inventory[self.selected]);
self.using = None;
@@ -402,10 +402,15 @@ impl Game<'_> {
}
});
}
7 => {
// SWAP_ITEM_WITH_OFFHAND: the hands swap and the item in use stops
// (ServerGamePacketListenerImpl.handlePlayerAction), not for spectators.
7 if !spectator => {
let g = &mut host.hub.guests[gi];
let slot = g.selected;
std::mem::swap(&mut g.inventory[slot], &mut g.offhand);
if let Some(play) = host.play.get_mut(&conn) {
play.using = None;
}
}
_ => {}
},
+32
View File
@@ -778,6 +778,8 @@ impl Game<'_> {
5..=8 => Some(500 + s - 5),
9..=35 => Some(s),
36..=44 => Some(s - 36),
// InventoryMenu.SHIELD_SLOT: the off hand.
45 => Some(504),
_ => None,
},
"minecraft:crafting" => match s {
@@ -1295,6 +1297,8 @@ impl Game<'_> {
match p.slot {
0..=35 => self.inventory[p.slot as usize] = stack,
36..=39 => self.armor[3 - (p.slot - 36) as usize] = stack,
// Inventory.SLOT_OFFHAND.
40 => self.offhand = stack,
_ => {}
}
self.remote_synced();
@@ -2572,6 +2576,17 @@ impl Game<'_> {
}));
}
}
/// Minecraft.handleKeybinds, key.swapOffhand: the server swaps the hands
/// (ServerboundPlayerActionPacket SWAP_ITEM_WITH_OFFHAND at BlockPos.ZERO, facing down) and
/// sends both slots back; nothing is predicted.
pub(super) fn remote_swap_hands(&mut self) {
self.send(S::PlayerAction(play::PlayerAction {
action: 7,
pos: [0; 3],
direction: 0,
sequence: 0,
}));
}
/// A container click: the server answers with the authoritative slots.
pub(super) fn remote_click(&mut self, right: bool) {
let Some(size) = self
@@ -2992,3 +3007,20 @@ impl Game<'_> {
}))
}
}
#[cfg(test)]
mod tests {
use super::Game;
#[test]
fn every_inventory_menu_slot_is_a_game_slot_and_45_is_the_off_hand() {
// InventoryMenu: result, 2x2 grid, armour, 27 + 9 inventory slots, then the off hand.
assert_eq!(Game::menu_slot("inventory", 45), Some(504));
let mut seen = std::collections::HashSet::new();
for slot in 0..46 {
let internal = Game::menu_slot("inventory", slot);
assert!(internal.is_some_and(|i| seen.insert(i)), "slot {slot}");
}
assert_eq!(Game::menu_slot("inventory", 46), None);
}
}