Merge pull request #429 from ludovic111/fix/lan-guest-crafting

LAN guest: crafting in the 2x2 grid and at a crafting table
This commit is contained in:
Ludovic Marie
2026-10-16 00:10:10 +02:00
committed by GitHub
6 changed files with 356 additions and 7 deletions
+1
View File
@@ -56,6 +56,7 @@ mod item_particles;
mod jukebox;
mod lan;
mod lan_actions;
mod lan_crafting;
mod lan_screen;
mod lan_trading;
mod leads;
+2 -1
View File
@@ -645,13 +645,14 @@ impl Game<'_> {
);
}
}
HostEvent::Left(guest) => {
HostEvent::Left(mut guest) => {
// The container they had open loses an opener.
if let Some(pos) = guest.menu.as_ref().and_then(|m| m.pos)
&& !guest.spectator()
{
self.container_openers_changed(pos, false);
}
self.lan_crafting_left(&mut host, &mut guest);
playerdata::save(&guest, &self.world_root);
host.models.remove(&guest.conn);
if self.options.dedicated.is_some() && guest.placed {
+20 -1
View File
@@ -37,6 +37,8 @@ pub(super) struct GuestPlay {
swung: bool,
/// The trading screen the guest has open.
pub(super) merchant: Option<super::lan_trading::GuestMerchant>,
/// The inventory menu and the crafting table the guest crafts in.
pub(super) crafting: super::lan_crafting::GuestCrafting,
}
struct ItemRules<'a>(&'a horizon_client::items::Items);
@@ -126,6 +128,10 @@ impl Game<'_> {
self.keys.remove(&KeyCode::ShiftLeft);
}
let screen = std::mem::replace(&mut self.screen, Screen::Playing);
// The host's crafting grid stays theirs; a crafting table the guest
// opens shows as the 3x3 size.
let craft_size = std::mem::replace(&mut self.craft_size, 2);
let craft_grid = std::mem::replace(&mut self.craft_grid, vec![None; 9]);
let container = self.container.take();
let mining = std::mem::replace(&mut self.mining, play.mining.take());
let destroy_delay = std::mem::replace(&mut self.destroy_delay, play.destroy_delay);
@@ -145,6 +151,8 @@ impl Game<'_> {
// What the action opened: handed to the guest instead of the host.
let opened = self.container.take();
let opened_table = std::mem::replace(&mut self.craft_size, craft_size) == 3;
self.craft_grid = craft_grid;
let opened_station = std::mem::replace(&mut self.station, host_station);
self.riding = riding;
self.left = left;
@@ -210,6 +218,9 @@ impl Game<'_> {
if let Some(station) = opened_station {
self.lan_station_opened(host, conn, station);
}
if opened_table {
self.lan_open_crafting(host, conn);
}
Some(result)
}
@@ -411,6 +422,8 @@ impl Game<'_> {
host.hub.guests[gi].set_menu_slot(p.slot as usize, item);
}
S::ContainerClick(p) if self.lan_merchant_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {}
S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {}
S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item),
S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => {
let g = &mut host.hub.guests[gi];
@@ -418,9 +431,15 @@ impl Game<'_> {
self.drop_guest_items(host, gi, vec![c]);
}
}
S::ContainerClose(p) if self.lan_crafting_closed(host, conn, Some(p.container)) => {
let g = &mut host.hub.guests[gi];
if let Some(c) = g.carried.take() {
self.drop_guest_items(host, gi, vec![c]);
}
}
S::ContainerClick(p) => {
let rules = ItemRules(&self.res.items);
let drops = host.hub.container_click(conn, p, &mut self.world, &rules);
let drops = host.hub.container_click(conn, &p, &mut self.world, &rules);
self.drop_guest_items(host, gi, drops);
}
S::ContainerClose(p) => {
@@ -0,0 +1,287 @@
//! Crafting for LAN guests: the inventory's 2x2 grid (window 0) and the
//! crafting table (`minecraft:crafting`) run the host's menu engine
//! (`horizon_client::menu`, `Kind::Inventory` / `Kind::Crafting`) over the
//! guest's inventory, with vanilla's packets: OpenScreen, container clicks
//! and their corrections, and the grid back into the inventory when the menu
//! closes (`AbstractContainerMenu.clearContainer`).
use super::{Game, lan::LanHost};
use horizon_client::{
items::ItemStack,
lan::guest::Guest,
menu::{Env, Input, Kind, Menu},
};
use horizon_protocol::packets::play::{self, Clientbound as C};
/// The guest's menus the game runs: kept between clicks, so a drag (quick
/// craft) spans them as in vanilla.
#[derive(Default)]
pub(super) struct GuestCrafting {
/// The inventory menu; its grid lives in the hub's guest.
inventory: Option<Box<Menu>>,
/// The open crafting table: its window, state id and menu.
table: Option<(i32, i32, Box<Menu>)>,
}
/// ServerboundContainerClickPacket's input.
pub(super) fn input(id: i32) -> Input {
match id {
0 => Input::Pickup,
1 => Input::QuickMove,
2 => Input::Swap,
3 => Input::Clone,
4 => Input::Throw,
5 => Input::QuickCraft,
_ => Input::PickupAll,
}
}
/// The armor's player-container slots, head to feet (`Inventory` 39..36).
const ARMOR: [usize; 4] = [39, 38, 37, 36];
const OFFHAND: usize = 40;
/// The guest's inventory, armor, off hand, selection and carried stack into `menu`.
fn load_player(menu: &mut Menu, g: &Guest) {
for i in 0..36 {
menu.set_player_item(i, g.inventory[i].clone());
}
for (k, slot) in ARMOR.into_iter().enumerate() {
menu.set_player_item(slot, g.armor[k].clone());
}
menu.set_player_item(OFFHAND, g.offhand.clone());
menu.selected = g.selected;
menu.creative = g.creative();
menu.carried = g.carried.clone();
}
/// `load_player` back.
fn store_player(menu: &mut Menu, g: &mut Guest) {
for i in 0..36 {
g.inventory[i] = menu.player_item(i).cloned();
}
for (k, slot) in ARMOR.into_iter().enumerate() {
g.armor[k] = menu.player_item(slot).cloned();
}
g.offhand = menu.player_item(OFFHAND).cloned();
g.carried = menu.carried.take();
}
/// Inventory.placeItemBackInInventory for each stack: what doesn't fit is
/// left for Player.drop (creative players keep it too).
fn place_back(menu: &mut Menu, env: &Env, stacks: Vec<ItemStack>) {
menu.creative = false;
for mut stack in stacks {
menu.give(env, &mut stack);
if stack.count > 0 {
menu.dropped.push(stack);
}
}
}
impl Game<'_> {
fn menu_env(&self) -> Env<'_> {
Env {
items: &self.res.items,
recipes: &self.res.recipes,
brewing: &self.res.stations.brewing,
banners: &self.res.stations.banners,
trade: None,
}
}
/// Runs `op` on the guest's menu with their inventory copied in and back.
fn guest_menu_op<R>(
&mut self,
host: &mut LanHost,
gi: usize,
menu: &mut Menu,
op: impl FnOnce(&mut Menu, &Env) -> R,
) -> R {
let env = self.menu_env();
load_player(menu, &host.hub.guests[gi]);
let result = op(menu, &env);
let dropped = std::mem::take(&mut menu.dropped);
menu.drops.clear();
menu.crafted.clear();
store_player(menu, &mut host.hub.guests[gi]);
self.drop_guest_items(host, gi, dropped);
result
}
/// A click on the guest's inventory menu (window 0): `InventoryMenu`,
/// crafting grid included. False for other windows.
pub(super) fn lan_inventory_click(
&mut self,
host: &mut LanHost,
conn: u32,
p: &play::ContainerClick,
) -> bool {
if p.container != 0 {
return false;
}
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return true;
};
if host.hub.guests[gi].spectator() {
return true;
}
let crafting = host.play.entry(conn).or_default();
let mut menu = crafting
.crafting
.inventory
.take()
.unwrap_or_else(|| Box::new(Menu::new(Kind::Inventory)));
let grid = host.hub.guests[gi].craft_grid.clone();
let changed = self.guest_menu_op(host, gi, &mut menu, |menu, env| {
for (k, s) in grid.into_iter().enumerate() {
menu.set_slot(env, 1 + k, s);
}
let before: Vec<_> = (0..menu.slot_count())
.map(|s| menu.slot(s).cloned())
.collect();
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
(0..menu.slot_count())
.filter(|&s| menu.slot(s) != before[s].as_ref())
.collect::<Vec<_>>()
});
let g = &mut host.hub.guests[gi];
for k in 0..4 {
g.craft_grid[k] = menu.slot(1 + k).cloned();
}
g.craft_result = menu.slot(0).cloned();
host.play.entry(conn).or_default().crafting.inventory = Some(menu);
host.hub.inventory_clicked(conn, p, &self.world, &changed);
true
}
/// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`).
pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) {
self.lan_crafting_closed(host, conn, None);
// The container it replaces loses its opener.
self.guest_container_closed(host, conn);
let title = horizon_protocol::text::translatable("container.crafting", &[]);
let Some(window) = host.hub.open_window(conn, "minecraft:crafting", title) else {
return;
};
let menu = Box::new(Menu::new(Kind::Crafting));
host.play.entry(conn).or_default().crafting.table = Some((window, 0, menu));
self.lan_send_table_content(host, conn);
}
/// A click on the guest's crafting table window; false for other windows.
pub(super) fn lan_crafting_click(
&mut self,
host: &mut LanHost,
conn: u32,
p: &play::ContainerClick,
) -> bool {
let Some(play) = host.play.get_mut(&conn) else {
return false;
};
let Some((window, state, mut menu)) = play
.crafting
.table
.take_if(|(window, _, _)| *window == p.container)
else {
return false;
};
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
&& !host.hub.guests[gi].spectator()
{
self.guest_menu_op(host, gi, &mut menu, |menu, env| {
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
});
}
host.play.entry(conn).or_default().crafting.table = Some((window, state, menu));
self.lan_send_table_content(host, conn);
true
}
/// The whole crafting table menu for the client (`sendAllDataToRemote`).
fn lan_send_table_content(&mut self, host: &mut LanHost, conn: u32) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let Some((window, state, menu)) = host
.play
.get_mut(&conn)
.and_then(|p| p.crafting.table.as_mut())
else {
return;
};
*state = (*state + 1) & 0x7FFF;
let (window, state) = (*window, *state);
let mut items: Vec<Option<ItemStack>> = (0..10).map(|s| menu.slot(s).cloned()).collect();
let g = &host.hub.guests[gi];
items.extend((9..36).chain(0..9).map(|i| g.inventory[i].clone()));
let carried = g.carried.clone();
let items = items.iter().map(|s| host.hub.stack(s)).collect();
let carried = host.hub.stack(&carried);
host.hub.send_to(
conn,
&C::ContainerSetContent(play::ContainerSetContent {
container: window,
state,
items,
carried,
}),
);
}
/// `AbstractContainerMenu.removed` of a crafting menu: the closed window
/// (`window`; None closes the table whichever it is, and 0 the inventory
/// menu) gives its grid back to the inventory, what doesn't fit is
/// dropped. False when no such window is open.
pub(super) fn lan_crafting_closed(
&mut self,
host: &mut LanHost,
conn: u32,
window: Option<i32>,
) -> bool {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return false;
};
let crafting = &mut host.play.entry(conn).or_default().crafting;
let grid: Vec<ItemStack> = if window == Some(0) {
crafting.inventory = None;
let g = &mut host.hub.guests[gi];
g.craft_result = None;
g.craft_grid.iter_mut().filter_map(Option::take).collect()
} else {
match crafting
.table
.take_if(|(w, _, _)| window.is_none_or(|window| *w == window))
{
Some((_, _, menu)) => (1..10).filter_map(|s| menu.slot(s).cloned()).collect(),
None => return false,
}
};
if grid.is_empty() {
return true;
}
let mut menu = Menu::new(Kind::Inventory);
self.guest_menu_op(host, gi, &mut menu, |menu, env| place_back(menu, env, grid));
true
}
/// A guest left: what their crafting grids held goes back into their
/// inventory before it is saved (dropped where they stood if full).
pub(super) fn lan_crafting_left(&mut self, host: &mut LanHost, g: &mut Guest) {
let table = host.play.remove(&g.conn).and_then(|p| p.crafting.table);
let mut grid: Vec<ItemStack> = g.craft_grid.iter_mut().filter_map(Option::take).collect();
g.craft_result = None;
if let Some((_, _, menu)) = table {
grid.extend((1..10).filter_map(|s| menu.slot(s).cloned()));
}
if grid.is_empty() {
return;
}
let mut menu = Menu::new(Kind::Inventory);
load_player(&mut menu, g);
place_back(&mut menu, &self.menu_env(), grid);
let dropped = std::mem::take(&mut menu.dropped);
store_player(&mut menu, g);
for stack in dropped {
self.spawn_item(stack, g.position, [0.0, 0.1, 0.0], 40);
}
}
}
+36 -4
View File
@@ -180,11 +180,17 @@ impl Hub {
/// Open a trading window for a guest (`Merchant.openTradingScreen`):
/// its id, or None when the menu type is unknown.
pub fn open_merchant_window(&mut self, conn: u32, title: Tag) -> Option<i32> {
self.open_window(conn, "minecraft:merchant", title)
}
/// ServerPlayer.openMenu for a menu the game runs (merchant, crafting
/// table): the open container closes, a new window id opens this menu.
pub fn open_window(&mut self, conn: u32, menu: &str, title: Tag) -> Option<i32> {
let kind = self
.sync
.builtin
.get("minecraft:menu")
.and_then(|m| m.id("minecraft:merchant"))?;
.and_then(|m| m.id(menu))?;
let i = self.guests.iter().position(|g| g.conn == conn)?;
self.close_container_at(i);
let g = &mut self.guests[i];
@@ -277,7 +283,7 @@ impl Hub {
pub fn container_click(
&mut self,
conn: u32,
p: play::ContainerClick,
p: &play::ContainerClick,
world: &mut World,
rules: &dyn Rules,
) -> Vec<ItemStack> {
@@ -326,7 +332,34 @@ impl Hub {
} else {
self.guests[i].drag = drag;
}
// Tell the client about every slot it got wrong, or that it did not claim.
self.answer_click(i, p, world, &changed);
drops
}
/// A click on the inventory menu (window 0) the game applied itself
/// (the crafting grid): the client is corrected like after any click.
pub fn inventory_clicked(
&mut self,
conn: u32,
p: &play::ContainerClick,
world: &World,
changed: &[usize],
) {
if let Some(i) = self.guests.iter().position(|g| g.conn == conn) {
self.answer_click(i, p, world, changed);
}
}
/// After a click: tell the client about every slot it got wrong, or that
/// it did not claim, and the carried stack.
fn answer_click(
&mut self,
i: usize,
p: &play::ContainerClick,
world: &World,
changed: &[usize],
) {
let in_menu = p.container != 0;
let claimed: HashMap<usize, Option<Hashed>> = p
.changed
.iter()
@@ -382,7 +415,6 @@ impl Hub {
} else {
self.guests[i].menu_sent = items;
}
drops
}
/// Slot changes of open containers (AbstractContainerMenu.broadcastChanges).
+10 -1
View File
@@ -80,6 +80,10 @@ pub struct Guest {
pub offhand: Option<ItemStack>,
pub selected: usize,
pub carried: Option<ItemStack>,
/// The inventory menu's crafting grid (2x2) and its result
/// (`InventoryMenu.craftSlots`, `resultSlots`), which the game computes.
pub craft_grid: [Option<ItemStack>; 4],
pub craft_result: Option<ItemStack>,
pub health: f32,
pub food: i32,
pub saturation: f32,
@@ -154,6 +158,8 @@ impl Guest {
offhand: None,
selected: 0,
carried: None,
craft_grid: Default::default(),
craft_result: None,
health: 20.0,
food: 20,
saturation: 5.0,
@@ -221,7 +227,8 @@ impl Guest {
/// 45 off hand.
pub fn menu_slot(&self, slot: usize) -> Option<ItemStack> {
match slot {
0..=4 => None,
0 => self.craft_result.clone(),
1..=4 => self.craft_grid[slot - 1].clone(),
5..=8 => self.armor[slot - 5].clone(),
9..=35 => self.inventory.get(slot).cloned().flatten(),
36..=44 => self.inventory.get(slot - 36).cloned().flatten(),
@@ -231,6 +238,8 @@ impl Guest {
}
pub fn set_menu_slot(&mut self, slot: usize, item: Option<ItemStack>) {
match slot {
0 => self.craft_result = item,
1..=4 => self.craft_grid[slot - 1] = item,
5..=8 => self.armor[slot - 5] = item,
9..=35 => self.inventory[slot] = item,
36..=44 => self.inventory[slot - 36] = item,