Add LAN containers, menu and host actions

Remote players can now open and click containers, and the host gets a LAN menu and action hooks, building on the first LAN server.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 03:47:15 +02:00
parent 708f70cbbd
commit 3eabcc6bd5
10 changed files with 1723 additions and 7 deletions
+7
View File
@@ -84,6 +84,9 @@ pub struct Audio {
next_tracked: u64,
/// A `SoundSource` index the next sound plays on (`/playsound`).
source_override: Option<usize>,
/// Positional sounds played since the last drain, kept while the world
/// is open to the network so guests hear them too.
pub capture: Option<Vec<(String, [f64; 3], f32, f32)>>,
}
fn decode(path: &Path) -> Option<(Vec<f32>, u32)> {
use symphonia::core::{
@@ -192,6 +195,7 @@ impl Audio {
music: None,
next_tracked: 0,
source_override: None,
capture: None,
}
}
fn open(mixer: Arc<Mutex<Mixer>>) -> Result<(cpal::Stream, u32)> {
@@ -309,6 +313,9 @@ impl Audio {
}
/// Play a sound event at a world position (None = non-positional UI sound).
pub fn play(&mut self, event: &str, at: Option<[f64; 3]>, volume: f32, pitch: f32) {
if let (Some(capture), Some(at)) = (self.capture.as_mut(), at) {
capture.push((event.to_owned(), at, volume, pitch));
}
let Some(variant) = self.resolve(event, 0) else {
return;
};
+21
View File
@@ -34,6 +34,7 @@ mod golems;
mod growth;
mod jukebox;
mod lan;
mod lan_actions;
mod lan_screen;
mod lightning;
mod loom;
@@ -667,6 +668,13 @@ struct Game<'a> {
/// This world is open to the network (game/lan.rs).
lan: Option<lan::LanHost>,
world_options: Option<lan_screen::WorldOptions>,
/// The block a guest is acting on (game/lan_actions.rs).
forced_hit: Option<Hit>,
/// Level events of this tick for the guests, and the guest acting now.
lan_events: Vec<(i32, [i32; 3], i32, Option<u32>)>,
lan_acting: Option<u32>,
/// Command feedback to forward to a guest.
chat_capture: Option<Vec<String>>,
/// Allow Cheats: whether guests may be given commands.
cheats: bool,
ui: chat::UiState,
@@ -765,6 +773,14 @@ impl Game<'_> {
/// Voxel traversal against non-air, non-fluid blocks, clipped against
/// each block's outline shape (`BlockGetter.clip` with `ClipContext.Block.OUTLINE`).
fn pick(&self) -> Option<Hit> {
// A guest of a hosted world acts on the block their client targeted.
if let Some(hit) = &self.forced_hit {
return Some(Hit {
pos: hit.pos,
face: hit.face,
point: hit.point,
});
}
let origin = self.eye_position()?;
self.clip_ray(origin, view_vector(self.yaw, self.pitch), self.reach())
}
@@ -1256,6 +1272,7 @@ impl Game<'_> {
/// Side effects reported by the behaviour library, in vanilla order.
fn process_level_events(&mut self) -> Result<()> {
let events = std::mem::take(&mut self.level_events);
self.lan_record_events(&events);
for event in events {
match event {
LevelEvent::LevelEvent {
@@ -7881,6 +7898,10 @@ pub fn run() -> Result<()> {
remote: None,
lan: None,
world_options: None,
forced_hit: None,
lan_events: Vec::new(),
lan_acting: None,
chat_capture: None,
cheats: true,
ui: Default::default(),
combat: Default::default(),
+4
View File
@@ -367,6 +367,10 @@ impl Game<'_> {
}
/// A chat message from the game (ChatComponent.addServerSystemMessage).
pub(super) fn system_message(&mut self, text: Text) {
if let Some(capture) = self.chat_capture.as_mut() {
capture.push(text.plain());
return;
}
let focused = self.screen == Screen::Chat;
self.ui.chat.add(
&self.res.atlas,
+60 -6
View File
@@ -46,6 +46,11 @@ pub(super) struct LanHost {
/// The guests' models in the host's world.
pub models: HashMap<u32, Mob>,
host_mode: i32,
pub play: HashMap<u32, super::lan_actions::GuestPlay>,
/// Blocks broken this tick (their sound is a level event for the guests).
pub broken: Vec<[f64; 3]>,
/// Hurt and death state of the mobs guests see.
mob_state: HashMap<u32, (i32, bool)>,
}
/// A stable UUID for an entity that has none.
@@ -211,7 +216,11 @@ impl Game<'_> {
host_uuid,
models: HashMap::new(),
host_mode: self.mode_id(),
play: HashMap::new(),
broken: Vec::new(),
mob_state: HashMap::new(),
});
self.audio.capture = Some(Vec::new());
self.system_message(Text::translate(
"menu.multiplayerOptions.publish.started.lan",
&[Text::literal(port.to_string())],
@@ -231,6 +240,8 @@ impl Game<'_> {
// Give the writer threads a moment to flush the disconnect packets.
std::thread::sleep(std::time::Duration::from_millis(100));
self.world.block_log = None;
self.audio.capture = None;
self.lan_events.clear();
self.streaming.extra.clear();
if announce {
self.system_message(Text::translate(
@@ -409,6 +420,9 @@ impl Game<'_> {
}
}
}
self.lan_flush_effects(&mut host);
self.tick_guests(&mut host);
self.lan_swings(&mut host);
self.lan_update_streaming(&host);
self.lan_update_models(&mut host);
self.lan = Some(host);
@@ -451,12 +465,52 @@ impl Game<'_> {
host.hub.place_new_player(conn, &mut ctx);
}
fn lan_guest_packet(
&mut self,
_host: &mut LanHost,
_conn: u32,
_packet: horizon_protocol::packets::play::Serverbound,
) {
/// Level events the game queued, for the guests (`process_level_events`).
pub(super) fn lan_record_events(&mut self, events: &[horizon_world::level::LevelEvent]) {
if self.audio.capture.is_none() {
return;
}
for e in events {
if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e {
self.lan_events.push((
*id as i32,
[pos.x, pos.y, pos.z],
*data as i32,
self.lan_acting,
));
}
}
}
/// Send the tick's level events, sounds and mob animations.
fn lan_flush_effects(&mut self, host: &mut LanHost) {
for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) {
if kind == 2001 {
host.broken
.push([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]);
}
host.hub.level_event(kind, pos, data, acting);
}
self.lan_broadcast_effects(host);
if host.hub.guests.is_empty() {
host.mob_state.clear();
return;
}
// Hurt and death animations of mobs.
let mut seen = HashMap::new();
for m in &self.mobs {
let dead = !m.alive();
let old = host.mob_state.get(&m.id).copied();
let at = [m.position.x, m.position.y, m.position.z];
if m.hurt_time > old.map_or(0, |o| o.0) && !dead {
host.hub.entity_event(m.id as i32, 2, at);
}
if dead && !old.is_some_and(|o| o.1) {
host.hub.entity_event(m.id as i32, 3, at);
}
seen.insert(m.id, (m.hurt_time, dead));
}
host.mob_state = seen;
}
/// Keep the chunks around every guest loaded.
@@ -0,0 +1,723 @@
//! What guests do in a hosted world. The host's gameplay code is written for
//! the one local player, so a guest's action runs through it with the guest's
//! state swapped in for the duration of the call (position, inventory, game
//! mode, experience, mining and item use): digging, placing, using items and
//! blocks, attacking and the commands all behave exactly as they do for the
//! host, and every world change they cause reaches all players through the
//! block log, the level events and the entity tracker.
use super::{Game, Hit, Mining, Screen, lan::LanHost};
use horizon_client::{
containers::BlockEntity,
entities::Experience,
items::ItemStack,
lan::{guest::SPECTATOR, menu::Rules},
motion::PlayerMotion,
};
use horizon_core::geometry::Vec3;
use horizon_protocol::{
packets::play::{self, Clientbound as C, Serverbound as S},
text::literal,
};
use winit::keyboard::KeyCode;
/// Per-guest state of the gameplay code that lives outside `Guest`.
#[derive(Default)]
pub(super) struct GuestPlay {
mining: Option<Mining>,
destroy_delay: u32,
using: Option<(usize, u32)>,
use_delay: u32,
attack_ticks: u32,
swing: Option<u32>,
swing_anim: (f32, f32),
/// The block being dug and the face the client aimed at.
digging: Option<([i32; 3], [i32; 3])>,
last_progress: i32,
/// Hand movements the client announced and the host animated.
swung: bool,
}
struct ItemRules<'a>(&'a horizon_client::items::Items);
impl Rules for ItemRules<'_> {
fn max_stack(&self, item: &str) -> u32 {
self.0.get(item).map_or(64, |i| i.max_stack)
}
fn armor_index(&self, item: &str) -> Option<usize> {
match self.0.get(item)?.equip_slot.as_deref()? {
"head" => Some(0),
"chest" => Some(1),
"legs" => Some(2),
"feet" => Some(3),
_ => None,
}
}
}
fn direction(face: i32) -> [i32; 3] {
match face {
0 => [0, -1, 0],
1 => [0, 1, 0],
2 => [0, 0, -1],
3 => [0, 0, 1],
4 => [-1, 0, 0],
_ => [1, 0, 0],
}
}
impl Game<'_> {
/// Run `f` as the guest `conn`: the host's player state is swapped for theirs.
pub(super) fn as_guest<R>(
&mut self,
host: &mut LanHost,
conn: u32,
f: impl FnOnce(&mut Self) -> R,
) -> Option<R> {
let i = host.hub.guests.iter().position(|g| g.conn == conn)?;
if host.hub.guests[i].motion.is_none() {
let p = Vec3::new(
host.hub.guests[i].position[0],
host.hub.guests[i].position[1],
host.hub.guests[i].position[2],
);
host.hub.guests[i].motion = PlayerMotion::new(self.motion, p).ok().map(Box::new);
}
let mut play = host.play.remove(&conn).unwrap_or_default();
let g = &mut host.hub.guests[i];
// The guest's body.
let mut motion = g.motion.take()?;
motion.position = Vec3::new(g.position[0], g.position[1], g.position[2]);
motion.ground.on_ground = g.on_ground;
motion.yaw = g.yaw;
motion.pitch = g.pitch;
motion.sprinting = g.sprinting;
motion.may_fly = g.creative() || g.game_mode == SPECTATOR;
motion.invulnerable = motion.may_fly;
let _ = motion.set_health(g.health, false);
motion.health.food.food = g.food;
motion.health.food.saturation = g.saturation;
let mut player = Some(*motion);
std::mem::swap(&mut self.player, &mut player);
let eye = (g.eye_height() as f32, self.eye);
self.eye = eye.0;
let (yaw, pitch) = (self.yaw, self.pitch);
self.yaw = g.yaw;
self.pitch = g.pitch;
std::mem::swap(&mut self.inventory, &mut g.inventory);
std::mem::swap(&mut self.armor, &mut g.armor);
std::mem::swap(&mut self.offhand, &mut g.offhand);
std::mem::swap(&mut self.carried, &mut g.carried);
let selected = std::mem::replace(&mut self.selected, g.selected);
let (mode, creative) = (self.mode, self.creative);
self.set_mode_raw(g.game_mode);
let xp = std::mem::replace(
&mut self.experience,
Experience {
level: g.xp_level,
progress: g.xp_progress,
total: g.xp_total,
},
);
let sneak = self.keys.contains(&KeyCode::ShiftLeft);
if g.sneaking {
self.keys.insert(KeyCode::ShiftLeft);
} else {
self.keys.remove(&KeyCode::ShiftLeft);
}
let screen = std::mem::replace(&mut self.screen, Screen::Playing);
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);
let using = std::mem::replace(&mut self.using, play.using.take());
let use_delay = std::mem::replace(&mut self.use_delay, play.use_delay);
let attack_ticks = std::mem::replace(&mut self.attack_ticks, play.attack_ticks);
let swing = std::mem::replace(&mut self.swing, play.swing.take());
let swing_anim = std::mem::replace(&mut self.swing_anim, play.swing_anim);
let (left, right) = (self.left, self.right);
self.left = play.digging.is_some();
self.right = play.using.is_some() || self.using.is_some();
let riding = self.riding.take();
self.lan_acting = Some(conn);
let result = f(self);
self.lan_acting = None;
// What the action opened: handed to the guest instead of the host.
let opened = self.container.take();
self.riding = riding;
self.left = left;
self.right = right;
play.mining = std::mem::replace(&mut self.mining, mining);
play.destroy_delay = std::mem::replace(&mut self.destroy_delay, destroy_delay);
play.using = std::mem::replace(&mut self.using, using);
play.use_delay = std::mem::replace(&mut self.use_delay, use_delay);
play.attack_ticks = std::mem::replace(&mut self.attack_ticks, attack_ticks);
play.swing = std::mem::replace(&mut self.swing, swing);
play.swing_anim = std::mem::replace(&mut self.swing_anim, swing_anim);
self.container = container;
self.screen = screen;
if sneak {
self.keys.insert(KeyCode::ShiftLeft);
} else {
self.keys.remove(&KeyCode::ShiftLeft);
}
let g = &mut host.hub.guests[i];
let new_xp = std::mem::replace(&mut self.experience, xp);
g.xp_level = new_xp.level;
g.xp_progress = new_xp.progress;
g.xp_total = new_xp.total;
let new_mode = self.mode_id();
self.mode = mode;
self.creative = creative;
self.selected = std::mem::replace(&mut g.selected, selected);
// `g.selected` now holds the host's value: swap the inventories back.
std::mem::swap(&mut self.selected, &mut g.selected);
std::mem::swap(&mut self.inventory, &mut g.inventory);
std::mem::swap(&mut self.armor, &mut g.armor);
std::mem::swap(&mut self.offhand, &mut g.offhand);
std::mem::swap(&mut self.carried, &mut g.carried);
self.yaw = yaw;
self.pitch = pitch;
self.eye = eye.1;
std::mem::swap(&mut self.player, &mut player);
if let Some(mut m) = player {
g.health = m.health.health();
g.food = m.health.food.food;
g.saturation = m.health.food.saturation;
// A teleport (commands) moves the guest.
let at = [m.position.x, m.position.y, m.position.z];
m.sprinting = false;
let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum();
g.motion = Some(Box::new(m));
if moved > 0.0001 {
host.hub.teleport(i, Some(at));
}
}
let g = &mut host.hub.guests[i];
if new_mode != g.game_mode {
let conn = g.conn;
host.hub.set_game_mode(conn, new_mode);
}
host.play.insert(conn, play);
if let Some(pos) = opened {
self.lan_open_container(host, conn, pos);
}
Some(result)
}
/// The game mode fields without `set_mode`'s side effects on the host.
fn set_mode_raw(&mut self, id: i32) {
use horizon_client::command::args::GameMode;
self.mode = match id {
1 => GameMode::Creative,
2 => GameMode::Adventure,
3 => GameMode::Spectator,
_ => GameMode::Survival,
};
self.creative = self.mode == GameMode::Creative;
}
/// Hand a container the guest opened over (ServerPlayer.openMenu).
fn lan_open_container(&mut self, host: &mut LanHost, conn: u32, pos: (i32, i32, i32)) {
let Some(entity) = self.world.block_entities.get(&pos) else {
return;
};
let (menu, title) = match entity {
BlockEntity::Chest(items) => match items.len() {
27 => ("minecraft:generic_9x3", "container.chest"),
9 => ("minecraft:generic_3x3", "container.dispenser"),
5 => ("minecraft:hopper", "container.hopper"),
_ => return,
},
_ => return,
};
let name = &self
.res
.facts
.get(self.world.block(pos.0, pos.1, pos.2))
.name;
let title = match &**name {
"minecraft:barrel" => "container.barrel",
"minecraft:dropper" => "container.dropper",
n if n.ends_with("shulker_box") => "container.shulkerBox",
_ => title,
};
let items = entity.slots().to_vec();
host.hub.open_container(
conn,
menu,
horizon_protocol::text::translatable(title, &[]),
pos,
items,
);
}
/// A packet from a guest that the hub does not handle itself.
pub(super) fn lan_guest_packet(&mut self, host: &mut LanHost, conn: u32, packet: S) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
if host.hub.guests[gi].dead && !matches!(packet, S::ClientCommand(_)) {
return;
}
let spectator = host.hub.guests[gi].spectator();
match packet {
S::PlayerAction(a) => match a.action {
0 => {
host.hub.ack(conn, a.sequence);
if spectator {
return;
}
let face = direction(i32::from(a.direction));
let play = host.play.entry(conn).or_default();
play.digging = Some((a.pos, face));
play.last_progress = -1;
}
1 => {}
2 | 3 => {
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),
);
}
}
4 | 5 => {
if !spectator {
self.as_guest(host, conn, |g| g.drop_held(a.action == 4));
}
}
6 => {
self.as_guest(host, conn, |g| {
if let Some((slot, ticks)) = g.using.take()
&& g.stack_in(slot)
.is_some_and(|s| &*s.item == "minecraft:bow")
{
g.release_bow(ticks);
}
});
}
7 => {
let g = &mut host.hub.guests[gi];
let slot = g.selected;
std::mem::swap(&mut g.inventory[slot], &mut g.offhand);
}
_ => {}
},
S::SetCarriedItem(p) => {
if (0..9).contains(&p.slot) {
host.hub.guests[gi].selected = p.slot as usize;
if let Some(play) = host.play.get_mut(&conn) {
play.using = None;
}
}
}
S::UseItemOn(p) => {
host.hub.ack(conn, p.sequence);
if spectator {
return;
}
let face = direction(p.face);
let hit = Hit {
pos: p.pos,
face,
point: [
f64::from(p.pos[0]) + f64::from(p.cursor[0]),
f64::from(p.pos[1]) + f64::from(p.cursor[1]),
f64::from(p.pos[2]) + f64::from(p.cursor[2]),
],
};
self.as_guest(host, conn, |g| {
g.forced_hit = Some(hit);
let _ = g.use_item();
g.forced_hit = None;
});
// The client predicted a result: correct it with what really is.
for pos in [
p.pos,
[p.pos[0] + face[0], p.pos[1] + face[1], p.pos[2] + face[2]],
] {
let state = self.world.block(pos[0], pos[1], pos[2]).0 as i32;
host.hub
.send_to(conn, &C::BlockUpdate(play::BlockUpdate { pos, state }));
}
}
S::UseItem(p) => {
host.hub.ack(conn, p.sequence);
if spectator {
return;
}
self.as_guest(host, conn, |g| {
let _ = g.use_item();
});
}
S::Attack(p) => self.guest_attack(host, conn, p.id),
S::Interact(p) => {
if let Some((position, eye)) = self.look_at_entity(host, gi, p.id) {
let _ = (position, eye);
self.as_guest(host, conn, |g| {
let _ = g.use_item();
});
}
}
S::SetCreativeModeSlot(p) => {
let g = &mut host.hub.guests[gi];
if !g.creative() || !(0..46).contains(&p.slot) {
return;
}
let item = self.item_from_network(host, &p.item);
host.hub.guests[gi].set_menu_slot(p.slot as usize, item);
}
S::ContainerClick(p) => {
let rules = ItemRules(&self.res.items);
let drops = host.hub.container_click(conn, p, &mut self.world, &rules);
self.drop_guest_items(host, gi, drops);
}
S::ContainerClose(p) => {
host.hub.container_closed(conn, 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::ChatCommand(c) => self.guest_command(host, conn, &c.command),
S::Unknown(8, payload) => {
// A signed command: the text comes first.
if let Ok(text) = horizon_protocol::buf::Reader::new(&payload).string(32767) {
self.guest_command(host, conn, &text);
}
}
S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn),
S::PickItemFromBlock(p) => {
let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]);
let item = self.res.facts.get(state).item.clone();
let g = &mut host.hub.guests[gi];
if g.creative() && &*item != "minecraft:air" {
let slot = g.selected;
g.inventory[slot] = Some(ItemStack::new(&item, 1));
}
}
_ => {}
}
}
fn item_from_network(
&self,
host: &LanHost,
stack: &Option<horizon_protocol::item::Stack>,
) -> Option<ItemStack> {
use horizon_protocol::item::{Component, component};
let s = stack.as_ref()?;
let name = host
.hub
.item_name(s.item)
.unwrap_or_else(|| "minecraft:air".into());
let mut out = ItemStack::new(&name, s.count.max(1) as u32);
out.damage = s.damage().max(0) as u32;
if let Some(Component::Enchantments(list)) = s.component(component::ENCHANTMENTS) {
for (id, level) in list {
if let Some(e) = host.hub.enchantment_name(*id) {
out.enchant(&e, *level as u32);
}
}
}
Some(out)
}
fn drop_guest_items(&mut self, host: &LanHost, gi: usize, stacks: Vec<ItemStack>) {
let g = &host.hub.guests[gi];
let eye = [
g.position[0],
g.position[1] + g.eye_height() - 0.3,
g.position[2],
];
let (yaw, pitch) = (
f64::from(g.yaw).to_radians(),
f64::from(g.pitch).to_radians(),
);
for stack in stacks {
let v = [
-yaw.sin() * pitch.cos() * 0.3,
-pitch.sin() * 0.3 + 0.1,
yaw.cos() * pitch.cos() * 0.3,
];
self.spawn_item(stack, eye, v, 40);
}
}
/// Aim the swapped-in player at an entity; returns its centre and the eye.
fn look_at_entity(
&mut self,
host: &mut LanHost,
gi: usize,
id: i32,
) -> Option<([f64; 3], [f64; 3])> {
let m = self.mobs.iter().find(|m| m.id as i32 == id)?;
let centre = [
m.position.x,
m.position.y + m.kind.height * 0.5,
m.position.z,
];
let g = &mut host.hub.guests[gi];
let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]];
let d = [centre[0] - eye[0], centre[1] - eye[1], centre[2] - eye[2]];
let horizontal = (d[0] * d[0] + d[2] * d[2]).sqrt();
g.yaw = (-d[0].atan2(d[2])).to_degrees() as f32;
g.pitch = (-d[1].atan2(horizontal)).to_degrees() as f32;
Some((centre, eye))
}
fn guest_attack(&mut self, host: &mut LanHost, conn: u32, id: i32) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
if host.hub.guests[gi].spectator() {
return;
}
let (old_yaw, old_pitch) = (host.hub.guests[gi].yaw, host.hub.guests[gi].pitch);
if self.look_at_entity(host, gi, id).is_none() {
return;
}
self.as_guest(host, conn, |g| {
g.attack();
});
host.hub.guests[gi].yaw = old_yaw;
host.hub.guests[gi].pitch = old_pitch;
}
/// Commands.performCommand for a guest with command access.
fn guest_command(&mut self, host: &mut LanHost, conn: u32, command: &str) {
if !host.settings.guest_commands || !self.cheats {
host.hub.send_to(
conn,
&C::SystemChat(play::SystemChat {
content: horizon_protocol::text::translatable("command.unknown.command", &[]),
overlay: false,
}),
);
return;
}
let command = command.trim_start_matches('/').to_owned();
let lines = self.as_guest(host, conn, |g| {
g.chat_capture = Some(Vec::new());
g.run_command(&command);
g.chat_capture.take().unwrap_or_default()
});
for line in lines.unwrap_or_default() {
host.hub.send_to(
conn,
&C::SystemChat(play::SystemChat {
content: literal(&line),
overlay: false,
}),
);
}
}
fn guest_respawn(&mut self, host: &mut LanHost, conn: u32) {
let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]);
let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
if !host.hub.guests[i].dead {
return;
}
let g = &mut host.hub.guests[i];
g.dead = false;
g.health = 20.0;
g.food = 20;
g.saturation = 5.0;
g.sent_health = None;
g.motion = None;
host.hub.respawn(i, spawn);
}
/// Per tick, for every guest: dig, use items, pick up drops, die.
pub(super) fn tick_guests(&mut self, host: &mut LanHost) {
let conns: Vec<u32> = host
.hub
.guests
.iter()
.filter(|g| g.placed && g.loaded)
.map(|g| g.conn)
.collect();
for conn in conns {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
continue;
};
if host.hub.guests[gi].dead {
continue;
}
let play = host.play.entry(conn).or_default();
let digging = play.digging;
let using = play.using.is_some();
let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100;
if digging.is_some() || using || delayed {
self.as_guest(host, conn, |g| {
g.attack_ticks = g.attack_ticks.saturating_add(1);
if let Some((pos, face)) = digging {
g.forced_hit = Some(Hit {
pos,
face,
point: [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
],
});
}
let _ = g.tick_mining();
g.forced_hit = None;
g.right = g.using.is_some();
g.tick_using();
if g.use_delay > 0 {
g.use_delay -= 1;
}
});
}
self.guest_dig_feedback(host, conn);
self.guest_pickups(host, gi);
let g = &mut host.hub.guests[gi];
if g.health <= 0.0 && !g.dead {
g.dead = true;
let message = literal(&format!("{} died", g.name));
host.hub.send_to(
conn,
&C::PlayerCombatKill(play::PlayerCombatKill {
id: host.hub.guests[gi].entity_id,
message,
}),
);
}
}
}
/// 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 {
return;
};
let play = host.play.entry(conn).or_default();
let Some((pos, _)) = play.digging else {
return;
};
let progress = play
.mining
.as_ref()
.map_or(-1, |m| (m.progress.clamp(0.0, 1.0) * 10.0) as i32 - 1);
let swinging = play.swing.is_some();
if progress != play.last_progress && progress >= 0 {
play.last_progress = progress;
host.hub.broadcast_near(
[f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])],
64.0,
&C::BlockDestruction(play::BlockDestruction {
id: host.hub.guests[gi].entity_id,
pos,
progress: progress as u8,
}),
Some(conn),
);
}
let _ = swinging;
}
/// Dropped items touching a guest go into their inventory.
fn guest_pickups(&mut self, host: &mut LanHost, gi: usize) {
let (conn, mode, position, id) = {
let g = &host.hub.guests[gi];
(g.conn, g.game_mode, g.position, g.entity_id)
};
if mode == SPECTATOR || self.dropped.is_empty() {
return;
}
let near: Vec<usize> = self
.dropped
.iter()
.enumerate()
.filter(|(_, d)| {
d.pickup_delay == 0
&& (d.position.x - position[0]).abs() < 1.5
&& (d.position.z - position[2]).abs() < 1.5
&& d.position.y > position[1] - 0.6
&& d.position.y < position[1] + 2.4
})
.map(|(i, _)| i)
.collect();
let mut taken = Vec::new();
for i in near.into_iter().rev() {
let (stack, item_id) = (self.dropped[i].stack.clone(), self.dropped[i].id);
let before = stack.count;
let rest = self.as_guest(host, conn, |g| g.give(stack)).flatten();
match rest {
None => {
self.dropped.remove(i);
taken.push((item_id, before));
}
Some(rest) if rest.count < before => {
self.dropped[i].stack = rest;
taken.push((item_id, before - self.dropped[i].stack.count));
}
Some(_) => {}
}
}
for (item, count) in taken {
host.hub.take_item(item as i32, id, count as i32, position);
host.hub
.sound("minecraft:entity.item.pickup", position, 0.2, 1.4, 7, None);
}
}
/// Positional sounds and level events of the tick, for the guests.
pub(super) fn lan_broadcast_effects(&mut self, host: &mut LanHost) {
let sounds = self.audio.capture.take().unwrap_or_default();
self.audio.capture = Some(Vec::new());
let blocks: Vec<[f64; 3]> = std::mem::take(&mut host.broken);
for (name, at, volume, pitch) in sounds {
// Block breaks are heard through the level event.
if blocks
.iter()
.any(|b| (0..3).all(|k| (b[k] + 0.5 - at[k]).abs() < 1e-6))
{
continue;
}
let source = horizon_client::settings::sound_source(&name) as i32;
host.hub.sound(&name, at, volume, pitch, source, None);
}
}
/// Guests' arm swings for everyone else.
pub(super) fn lan_swings(&mut self, host: &mut LanHost) {
let conns: Vec<u32> = host.play.keys().copied().collect();
for conn in conns {
let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else {
continue;
};
let (id, at) = (g.entity_id, g.position);
let play = host.play.get_mut(&conn).expect("play");
let swinging = play.swing == Some(0);
if swinging && !play.swung {
host.hub.swing(id, 0, at, Some(conn));
}
play.swung = swinging;
}
}
}
+393
View File
@@ -0,0 +1,393 @@
//! Hub operations on what guests perceive and do beyond the basics: sounds,
//! level events, animations and block containers with their clicks.
use super::{
hub::Hub,
menu::{self, Menu, Rules, View},
};
use crate::{items::ItemStack, world::World};
use horizon_protocol::{
item::Hashed,
packets::play::{self, Clientbound as C},
};
use horizon_world::nbt::Tag;
use std::collections::HashMap;
impl Hub {
pub fn send_to(&self, conn: u32, packet: &C) {
if let Some(g) = self.guest(conn) {
g.send(packet);
}
}
/// Send to every placed guest within `range` blocks of `at`.
pub fn broadcast_near(&self, at: [f64; 3], range: f64, packet: &C, except: Option<u32>) {
let body = packet.encode();
for g in self
.guests
.iter()
.filter(|g| g.placed && Some(g.conn) != except)
{
let d: f64 = (0..3).map(|k| (g.position[k] - at[k]).powi(2)).sum();
if d <= range * range {
g.sender.send(body.clone());
}
}
}
/// ClientboundSoundPacket for a sound event name (an inline event when
/// the registry does not know it).
pub fn sound(
&self,
name: &str,
at: [f64; 3],
volume: f32,
pitch: f32,
source: i32,
except: Option<u32>,
) {
let sound = match self.sync.id("minecraft:sound_event", name) {
Some(id) => (id, None),
None => (-1, Some((name.to_owned(), None))),
};
let packet = C::Sound(play::Sound {
sound,
source,
x: (at[0] * 8.0) as i32,
y: (at[1] * 8.0) as i32,
z: (at[2] * 8.0) as i32,
volume,
pitch,
seed: self.ticks as i64,
});
self.broadcast_near(at, f64::from(volume.max(1.0)) * 16.0, &packet, except);
}
/// ClientboundLevelEventPacket (block break particles and sounds ...).
pub fn level_event(&self, kind: i32, pos: [i32; 3], data: i32, except: Option<u32>) {
let at = [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])];
self.broadcast_near(
at,
64.0,
&C::LevelEvent(play::LevelEvent {
kind,
pos,
data,
global: false,
}),
except,
);
}
pub fn entity_event(&self, id: i32, event: i8, at: [f64; 3]) {
self.broadcast_near(
at,
128.0,
&C::EntityEvent(play::EntityEvent { id, event }),
None,
);
}
pub fn swing(&self, id: i32, hand: i32, at: [f64; 3], except: Option<u32>) {
self.broadcast_near(
at,
128.0,
&C::SwingAnimation(play::SwingAnimation {
id,
hand,
kind: 1,
duration: 6,
}),
except,
);
}
pub fn take_item(&self, item: i32, collector: i32, count: i32, at: [f64; 3]) {
self.broadcast_near(
at,
64.0,
&C::TakeItemEntity(play::TakeItemEntity {
item,
player: collector,
amount: count,
}),
None,
);
}
/// Open a block container for a guest (ServerPlayer.openMenu).
pub fn open_container(
&mut self,
conn: u32,
menu_kind: &str,
title: Tag,
pos: (i32, i32, i32),
items: Vec<Option<ItemStack>>,
) {
let Some(kind) = self
.sync
.builtin
.get("minecraft:menu")
.and_then(|m| m.id(menu_kind))
else {
return;
};
let Some(i) = self.guests.iter().position(|g| g.conn == conn) else {
return;
};
self.close_container_at(i);
let g = &mut self.guests[i];
g.next_window = g.next_window % 100 + 1;
let window = g.next_window;
g.send(&C::OpenScreen(play::OpenScreen {
container: window,
menu: kind,
title,
}));
g.menu = Some(Menu {
window,
kind,
pos: Some(pos),
size: items.len(),
state: 0,
sent: Vec::new(),
drag: None,
});
self.send_menu_content(i, items);
}
fn send_menu_content(&mut self, i: usize, mut items: Vec<Option<ItemStack>>) {
for j in 0..36 {
items.push(self.guests[i].inventory[player_slot(j)].clone());
}
let net: Vec<_> = items.iter().map(|s| self.stack(s)).collect();
let carried = self.guests[i].carried.clone();
let carried = self.stack(&carried);
let g = &mut self.guests[i];
let Some(menu) = g.menu.as_mut() else {
return;
};
menu.state = (menu.state + 1) & 0x7FFF;
let packet = C::ContainerSetContent(play::ContainerSetContent {
container: menu.window,
state: menu.state,
items: net,
carried,
});
menu.sent = items;
g.send(&packet);
}
fn close_container_at(&mut self, i: usize) {
let g = &mut self.guests[i];
if let Some(menu) = g.menu.take() {
g.send(&C::ContainerClose(play::ContainerClose {
container: menu.window,
}));
}
}
pub(super) fn close_container_for(&mut self, i: usize) {
self.close_container_at(i);
}
pub fn close_container(&mut self, conn: u32) {
if let Some(i) = self.guests.iter().position(|g| g.conn == conn) {
self.close_container_at(i);
}
}
/// The client closed its window.
pub fn container_closed(&mut self, conn: u32, window: i32) {
if let Some(g) = self.guest_mut(conn)
&& g.menu.as_ref().is_some_and(|m| m.window == window)
{
g.menu = None;
}
}
fn hashed_matches(&mut self, claimed: &Option<Hashed>, mine: &Option<ItemStack>) -> bool {
match (claimed, mine) {
(None, None) => true,
(Some(h), Some(s)) => h.item == self.item_id(&s.item) && h.count == s.count as i32,
_ => false,
}
}
fn view_slot(&self, i: usize, world: &World, slot: usize) -> Option<ItemStack> {
let g = &self.guests[i];
match &g.menu {
Some(m) if slot < m.size => {
let e = world.block_entities.get(&m.pos?)?;
e.slots().get(slot).cloned().flatten()
}
Some(m) => g
.inventory
.get(player_slot(slot - m.size))
.cloned()
.flatten(),
None => g.menu_slot(slot),
}
}
/// ServerGamePacketListenerImpl.handleContainerClick. Returns the stacks
/// thrown out of the menu.
pub fn container_click(
&mut self,
conn: u32,
p: play::ContainerClick,
world: &mut World,
rules: &dyn Rules,
) -> Vec<ItemStack> {
let Some(i) = self.guests.iter().position(|g| g.conn == conn) else {
return Vec::new();
};
let in_menu = p.container != 0;
let window_ok = !in_menu
|| self.guests[i]
.menu
.as_ref()
.is_some_and(|m| m.window == p.container);
if !window_ok || self.guests[i].spectator() {
return Vec::new();
}
let pos = self.guests[i].menu.as_ref().and_then(|m| m.pos);
let mut drag = if in_menu {
self.guests[i].menu.as_mut().and_then(|m| m.drag.take())
} else {
self.guests[i].drag.take()
};
let (drops, changed) = {
let guest = &mut self.guests[i];
let mut entity = pos.and_then(|k| world.block_entities.get_mut(&k));
let slots = entity.as_mut().map(|e| e.slots_mut());
if in_menu && slots.is_none() {
return Vec::new();
}
let mut view = View {
guest,
container: slots,
};
menu::click(
&mut view,
&mut drag,
i32::from(p.slot),
i32::from(p.button),
p.input,
rules,
)
};
if in_menu {
if let Some(m) = self.guests[i].menu.as_mut() {
m.drag = drag;
}
} else {
self.guests[i].drag = drag;
}
// Tell the client about every slot it got wrong, or that it did not claim.
let claimed: HashMap<usize, Option<Hashed>> = p
.changed
.iter()
.map(|(s, h)| (*s as usize, h.clone()))
.collect();
let total = if in_menu {
self.guests[i].menu.as_ref().map_or(0, |m| m.size) + 36
} else {
46
};
let mut resend: Vec<usize> = Vec::new();
for slot in 0..total {
let mine = self.view_slot(i, world, slot);
let agreed = match claimed.get(&slot) {
Some(c) => self.hashed_matches(c, &mine),
None => !changed.contains(&slot),
};
if !agreed {
resend.push(slot);
}
}
for slot in resend {
let mine = self.view_slot(i, world, slot);
let net = self.stack(&mine);
let g = &mut self.guests[i];
let state = if in_menu {
g.menu.as_mut().map_or(0, |m| {
m.state = (m.state + 1) & 0x7FFF;
m.state
})
} else {
g.menu_state = (g.menu_state + 1) & 0x7FFF;
g.menu_state
};
g.send(&C::ContainerSetSlot(play::ContainerSetSlot {
container: p.container,
state,
slot: slot as i16,
item: net,
}));
}
let carried = self.guests[i].carried.clone();
if !self.hashed_matches(&p.carried, &carried) {
let net = self.stack(&carried);
self.guests[i].send(&C::SetCursorItem(play::SetCursorItem { item: net }));
}
// What the client now believes equals the server's state.
let items: Vec<_> = (0..total).map(|s| self.view_slot(i, world, s)).collect();
if in_menu {
if let Some(m) = self.guests[i].menu.as_mut() {
m.sent = items;
}
} else {
self.guests[i].menu_sent = items;
}
drops
}
/// Slot changes of open containers (AbstractContainerMenu.broadcastChanges).
pub fn sync_containers(&mut self, world: &World) {
for i in 0..self.guests.len() {
let Some(menu) = self.guests[i]
.menu
.as_ref()
.filter(|_| self.guests[i].placed)
else {
continue;
};
let (size, window, pos) = (menu.size, menu.window, menu.pos);
if !pos.is_some_and(|k| world.block_entities.contains_key(&k)) {
self.close_container_at(i);
continue;
}
for slot in 0..size + 36 {
let now = self.view_slot(i, world, slot);
let sent = self.guests[i]
.menu
.as_ref()
.and_then(|m| m.sent.get(slot).cloned());
if sent.as_ref() == Some(&now) {
continue;
}
let net = self.stack(&now);
let g = &mut self.guests[i];
if let Some(m) = g.menu.as_mut() {
m.state = (m.state + 1) & 0x7FFF;
let state = m.state;
if m.sent.len() <= slot {
m.sent.resize(slot + 1, None);
}
m.sent[slot] = now;
g.send(&C::ContainerSetSlot(play::ContainerSetSlot {
container: window,
state,
slot: slot as i16,
item: net,
}));
}
}
}
}
}
/// Inventory index of the n-th player slot of a container menu (27 main, then the hotbar).
fn player_slot(n: usize) -> usize {
if n < 27 { 9 + n } else { n - 27 }
}
+8
View File
@@ -82,6 +82,11 @@ pub struct Guest {
pub dead: bool,
/// The join packets were sent (PlayerList.placeNewPlayer ran).
pub placed: bool,
/// The open block container, if any.
pub menu: Option<super::menu::Menu>,
pub next_window: i32,
/// An unfinished drag in the inventory menu.
pub drag: Option<(u8, Vec<usize>)>,
/// The compound this player was loaded from, for fields Horizon does not model.
pub saved: Option<horizon_world::nbt::Tag>,
}
@@ -142,6 +147,9 @@ impl Guest {
ticks: 0,
dead: false,
placed: false,
menu: None,
next_window: 0,
drag: None,
saved: None,
}
}
+38 -1
View File
@@ -91,7 +91,7 @@ pub struct Hub {
pub config: HubConfig,
pub encoder: ChunkEncoder,
pub guests: Vec<Guest>,
sync: Arc<SyncData>,
pub(super) sync: Arc<SyncData>,
pub ticks: u64,
last_clock: i64,
weather: (bool, f32, f32),
@@ -549,6 +549,7 @@ impl Hub {
}
}
self.broadcast_block_changes(ctx.world);
self.sync_containers(ctx.world);
self.track_entities(ctx);
for i in 0..self.guests.len() {
if self.guests[i].placed {
@@ -1247,3 +1248,39 @@ const COMMANDS: &[&str] = &[
"weather",
"xp",
];
impl Hub {
pub fn item_name(&self, id: i32) -> Option<std::sync::Arc<str>> {
self.sync
.builtin
.get("minecraft:item")?
.name(id)
.map(std::sync::Arc::from)
}
pub fn enchantment_name(&self, id: i32) -> Option<String> {
self.sync
.dynamic
.name("minecraft:enchantment", id)
.map(str::to_owned)
}
/// ServerPlayer.respawn: back to `at` with a fresh start.
pub fn respawn(&mut self, i: usize, at: [f64; 3]) {
let mode = self.guests[i].game_mode;
let info = self.spawn_info(mode);
self.close_container_for(i);
let g = &mut self.guests[i];
g.position = at;
g.previous_position = at;
g.send(&C::Respawn(play::Respawn {
spawn: info,
keep: 0,
}));
g.center = None;
g.sent_chunks.clear();
g.chunk_queue.clear();
g.tracker.clear();
self.teleport(i, None);
self.send_inventory(i);
}
}
+467
View File
@@ -0,0 +1,467 @@
//! Container menus for guests (AbstractContainerMenu.doClick): the player's
//! inventory menu (window 0) and block containers (chests, barrels, hoppers,
//! dispensers, shulker boxes). The click modes are pickup, quick move, swap,
//! clone, throw, quick craft (drag) and pickup all; items thrown out of a
//! menu are returned for the game to drop.
use super::guest::Guest;
use crate::items::ItemStack;
/// What the menus need to know about items.
pub trait Rules {
fn max_stack(&self, item: &str) -> u32;
/// The armor slot (0 head .. 3 feet) an item can be worn in.
fn armor_index(&self, item: &str) -> Option<usize>;
}
/// An open block container.
pub struct Menu {
pub window: i32,
/// The `minecraft:menu` registry id.
pub kind: i32,
pub pos: Option<(i32, i32, i32)>,
/// Slots of the container itself (without the 36 inventory slots).
pub size: usize,
pub state: i32,
/// What the client was last told, for change detection.
pub sent: Vec<Option<ItemStack>>,
/// An unfinished drag: (mode, slots).
pub drag: Option<(u8, Vec<usize>)>,
}
/// Slots of a menu seen as one list.
pub struct View<'a> {
pub guest: &'a mut Guest,
/// The container's slots, or None for the inventory menu.
pub container: Option<&'a mut [Option<ItemStack>]>,
}
impl View<'_> {
pub fn len(&self) -> usize {
match &self.container {
Some(c) => c.len() + 36,
None => 46,
}
}
pub fn is_empty(&self) -> bool {
false
}
pub fn get(&self, i: usize) -> Option<ItemStack> {
match &self.container {
Some(c) if i < c.len() => c[i].clone(),
Some(c) => self
.guest
.inventory
.get(player_slot(i - c.len()))
.cloned()
.flatten(),
None => self.guest.menu_slot(i),
}
}
pub fn set(&mut self, i: usize, item: Option<ItemStack>) {
match &mut self.container {
Some(c) if i < c.len() => c[i] = item,
Some(c) => {
let n = c.len();
self.guest.inventory[player_slot(i - n)] = item;
}
None => self.guest.set_menu_slot(i, item),
}
}
/// Whether the slot takes part in clicks at all.
fn enabled(&self, i: usize) -> bool {
self.container.is_some() || i >= 5
}
fn may_place(&self, i: usize, stack: &ItemStack, rules: &dyn Rules) -> bool {
if self.container.is_none() && (5..=8).contains(&i) {
return rules.armor_index(&stack.item) == Some(i - 5);
}
self.enabled(i)
}
fn slot_max(&self, i: usize, stack: &ItemStack, rules: &dyn Rules) -> u32 {
if self.container.is_none() && (5..=8).contains(&i) {
return 1;
}
rules.max_stack(&stack.item).max(1)
}
/// The ranges quick move uses: (container start..end, main, hotbar).
fn player_ranges(&self) -> (std::ops::Range<usize>, std::ops::Range<usize>) {
match &self.container {
Some(c) => (c.len()..c.len() + 27, c.len() + 27..c.len() + 36),
None => (9..36, 36..45),
}
}
}
/// Inventory index of the n-th player slot of a container menu (27 main, then hotbar).
fn player_slot(n: usize) -> usize {
if n < 27 { 9 + n } else { n - 27 }
}
/// Inventory.add-like merge of `stack` into slots `range` (moveItemStackTo).
fn move_to(
view: &mut View,
mut stack: ItemStack,
range: std::ops::Range<usize>,
reverse: bool,
rules: &dyn Rules,
) -> Option<ItemStack> {
let order: Vec<usize> = if reverse {
range.rev().collect()
} else {
range.collect()
};
for &i in &order {
if stack.count == 0 {
break;
}
if !view.enabled(i) {
continue;
}
if let Some(mut existing) = view.get(i)
&& existing.same_item_same_components(&stack)
{
let max = view.slot_max(i, &existing, rules);
if existing.count < max {
let moved = (max - existing.count).min(stack.count);
existing.count += moved;
stack.count -= moved;
view.set(i, Some(existing));
}
}
}
for &i in &order {
if stack.count == 0 {
break;
}
if view.enabled(i) && view.get(i).is_none() && view.may_place(i, &stack, rules) {
let moved = stack.count.min(view.slot_max(i, &stack, rules));
view.set(
i,
Some(ItemStack {
count: moved,
..stack.clone()
}),
);
stack.count -= moved;
}
}
(stack.count > 0).then_some(stack)
}
fn quick_move(view: &mut View, i: usize, rules: &dyn Rules) {
let Some(stack) = view.get(i) else {
return;
};
if !view.enabled(i) {
return;
}
let (main, hotbar) = view.player_ranges();
let rest = if let Some(c) = &view.container {
let n = c.len();
if i < n {
// Container to inventory, filling from the hotbar's end.
move_to(view, stack, n..n + 36, true, rules)
} else {
move_to(view, stack, 0..n, false, rules)
}
} else if (5..=8).contains(&i) || i == 45 || i < 5 {
move_to(view, stack, 9..45, false, rules)
} else {
// Wear it, otherwise swap between the main inventory and the hotbar.
let armor = rules
.armor_index(&stack.item)
.filter(|a| view.get(5 + a).is_none());
if let Some(a) = armor {
view.set(
5 + a,
Some(ItemStack {
count: 1,
..stack.clone()
}),
);
let mut rest = stack.clone();
rest.count -= 1;
(rest.count > 0).then_some(rest)
} else if hotbar.contains(&i) {
move_to(view, stack, main, false, rules)
} else {
move_to(view, stack, hotbar, false, rules)
}
};
view.set(i, rest);
}
/// The click modes of ServerboundContainerClickPacket.
pub mod input {
pub const PICKUP: i32 = 0;
pub const QUICK_MOVE: i32 = 1;
pub const SWAP: i32 = 2;
pub const CLONE: i32 = 3;
pub const THROW: i32 = 4;
pub const QUICK_CRAFT: i32 = 5;
pub const PICKUP_ALL: i32 = 6;
}
/// Apply one click; returns the stacks thrown out and the slots changed.
pub fn click(
view: &mut View,
drag: &mut Option<(u8, Vec<usize>)>,
slot: i32,
button: i32,
mode: i32,
rules: &dyn Rules,
) -> (Vec<ItemStack>, Vec<usize>) {
let mut drops = Vec::new();
let before: Vec<Option<ItemStack>> = (0..view.len()).map(|i| view.get(i)).collect();
if mode == input::QUICK_CRAFT {
quick_craft(view, drag, slot, button, rules);
} else {
*drag = None;
match mode {
input::PICKUP | input::QUICK_MOVE if slot == -999 => {
if mode == input::PICKUP
&& let Some(mut carried) = view.guest.carried.take()
{
if button == 1 && carried.count > 1 {
let mut one = carried.clone();
one.count = 1;
carried.count -= 1;
view.guest.carried = Some(carried);
drops.push(one);
} else {
drops.push(carried);
}
}
}
input::PICKUP => pickup(view, slot, button, rules),
input::QUICK_MOVE => {
if let Ok(i) = usize::try_from(slot)
&& i < view.len()
{
quick_move(view, i, rules);
}
}
input::SWAP => swap(view, slot, button, rules),
input::CLONE => {
if view.guest.carried.is_none()
&& view.guest.creative()
&& let Ok(i) = usize::try_from(slot)
&& let Some(stack) = view.get(i)
{
let max = rules.max_stack(&stack.item).max(1);
view.guest.carried = Some(ItemStack {
count: max,
..stack
});
}
}
input::THROW => {
if view.guest.carried.is_none()
&& let Ok(i) = usize::try_from(slot)
&& view.enabled(i)
&& let Some(mut stack) = view.get(i)
{
if button == 1 || stack.count <= 1 {
drops.push(stack);
view.set(i, None);
} else {
let mut one = stack.clone();
one.count = 1;
stack.count -= 1;
view.set(i, Some(stack));
drops.push(one);
}
}
}
input::PICKUP_ALL => pickup_all(view, slot, rules),
_ => {}
}
}
let changed = (0..view.len())
.filter(|&i| view.get(i) != before[i])
.collect();
(drops, changed)
}
fn pickup(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) {
let Ok(i) = usize::try_from(slot) else {
return;
};
if i >= view.len() || !view.enabled(i) {
return;
}
let right = button == 1;
let (slot_item, carried) = (view.get(i), view.guest.carried.clone());
match (slot_item, carried) {
(None, None) => {}
(None, Some(mut c)) => {
if view.may_place(i, &c, rules) {
let amount = if right { 1 } else { c.count }.min(view.slot_max(i, &c, rules));
view.set(
i,
Some(ItemStack {
count: amount,
..c.clone()
}),
);
c.count -= amount;
view.guest.carried = (c.count > 0).then_some(c);
}
}
(Some(mut s), None) => {
let take = if right { s.count.div_ceil(2) } else { s.count };
let taken = ItemStack {
count: take,
..s.clone()
};
s.count -= take;
view.set(i, (s.count > 0).then_some(s));
view.guest.carried = Some(taken);
}
(Some(mut s), Some(mut c)) => {
if !view.may_place(i, &c, rules) {
return;
}
if s.same_item_same_components(&c) {
let max = view.slot_max(i, &s, rules);
let moved = if right { 1 } else { c.count }.min(max.saturating_sub(s.count));
s.count += moved;
c.count -= moved;
view.set(i, Some(s));
view.guest.carried = (c.count > 0).then_some(c);
} else if c.count <= view.slot_max(i, &c, rules) {
view.set(i, Some(c));
view.guest.carried = Some(s);
}
}
}
}
fn swap(view: &mut View, slot: i32, button: i32, rules: &dyn Rules) {
let Ok(i) = usize::try_from(slot) else {
return;
};
if i >= view.len() || !view.enabled(i) {
return;
}
// Hotbar slot `button` (0..9) or the off hand (40).
let other = match button {
0..=8 => match &view.container {
Some(c) => c.len() + 27 + button as usize,
None => 36 + button as usize,
},
40 if view.container.is_none() => 45,
_ => return,
};
if other == i {
return;
}
let (a, b) = (view.get(i), view.get(other));
if a.as_ref().is_some_and(|a| !view.may_place(other, a, rules))
|| b.as_ref().is_some_and(|b| !view.may_place(i, b, rules))
{
return;
}
view.set(i, b);
view.set(other, a);
}
fn pickup_all(view: &mut View, slot: i32, rules: &dyn Rules) {
let _ = slot;
let Some(mut carried) = view.guest.carried.clone() else {
return;
};
let max = rules.max_stack(&carried.item).max(1);
// Partial stacks first, then full ones.
for full in [false, true] {
for i in 0..view.len() {
if carried.count >= max {
break;
}
if !view.enabled(i) || (view.container.is_none() && i == 0) {
continue;
}
let Some(mut s) = view.get(i) else {
continue;
};
if !s.same_item_same_components(&carried) || (s.count == max) != full {
continue;
}
let moved = (max - carried.count).min(s.count);
carried.count += moved;
s.count -= moved;
view.set(i, (s.count > 0).then_some(s));
}
}
view.guest.carried = Some(carried);
}
/// Dragging a stack over slots (QUICK_CRAFT): start, add slots, end.
fn quick_craft(
view: &mut View,
drag: &mut Option<(u8, Vec<usize>)>,
slot: i32,
button: i32,
rules: &dyn Rules,
) {
let (stage, kind) = (button & 3, ((button >> 2) & 3) as u8);
match stage {
0 => *drag = view.guest.carried.is_some().then_some((kind, Vec::new())),
1 => {
if let (Some((_, slots)), Ok(i)) = (drag.as_mut(), usize::try_from(slot))
&& i < view.len()
&& !slots.contains(&i)
&& let Some(c) = &view.guest.carried
&& view.enabled(i)
&& view.may_place(i, c, rules)
&& view.get(i).is_none_or(|s| s.same_item_same_components(c))
{
slots.push(i);
}
}
_ => {
let Some((kind, slots)) = drag.take() else {
return;
};
let Some(mut carried) = view.guest.carried.clone() else {
return;
};
if slots.is_empty() {
return;
}
if slots.len() == 1 {
// A single slot behaves like a plain click.
let button = if kind == 1 { 1 } else { 0 };
pickup(view, slots[0] as i32, button, rules);
return;
}
let each = match kind {
0 => carried.count / slots.len() as u32,
1 => 1,
_ => rules.max_stack(&carried.item).max(1),
};
for i in slots {
if carried.count == 0 {
break;
}
let existing = view.get(i).map_or(0, |s| s.count);
let max = view.slot_max(i, &carried, rules);
let put = each.min(max.saturating_sub(existing)).min(carried.count);
if put == 0 {
continue;
}
view.set(
i,
Some(ItemStack {
count: existing + put,
..carried.clone()
}),
);
if kind != 2 || !view.guest.creative() {
carried.count -= put;
}
}
view.guest.carried = (carried.count > 0).then_some(carried);
}
}
}
+2
View File
@@ -6,10 +6,12 @@
//! world that is not open to the network pays nothing.
pub mod chunks;
pub mod conn;
pub mod containers;
pub mod data;
pub mod entity;
pub mod guest;
pub mod hub;
pub mod menu;
pub mod playerdata;
pub use conn::PlayerSender;