diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs new file mode 100644 index 000000000..aa9fb70f8 --- /dev/null +++ b/crates/horizon-client/examples/lan_flat.rs @@ -0,0 +1,137 @@ +//! Serve a small flat world on the LAN server without the game, for joining +//! with a real client while developing the protocol: +//! `cargo run --release --example lan_flat -- RESOURCES PORT`. +use horizon_client::{ + assets::Assets, + blocks::BlockFacts, + chunk::{Chunk, MIN_Y}, + lan::{ + Lan, + chunks::ChunkEncoder, + data::SyncData, + hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, + }, + world::World, +}; +use horizon_protocol::packets::play::Serverbound as S; +use std::{path::PathBuf, sync::Arc, time::Duration}; + +fn main() -> Result<(), Box> { + let mut args = std::env::args().skip(1); + let root = PathBuf::from(args.next().ok_or("RESOURCES PORT")?); + let port: u16 = args.next().ok_or("port")?.parse()?; + let assets = Assets::load(&root)?; + let facts = BlockFacts::load(&root, assets.registry)?; + let state = |name: &str| { + assets + .registry + .default_state(name) + .map_or(0, |s| s.0 as u16) + }; + let sync = Arc::new(SyncData::load(&root)?); + let biomes: Vec = sync + .dynamic + .registries + .get("minecraft:worldgen/biome") + .map(|v| v.iter().map(|(n, _)| n.clone()).collect()) + .unwrap_or_default(); + let encoder = ChunkEncoder::new( + facts + .states + .iter() + .map(|s| (s.name.clone(), s.fluid_level > 0 || s.waterlogged)), + &sync.builtin, + &biomes, + &biomes, + ); + let (stone, dirt, grass) = ( + state("minecraft:stone"), + state("minecraft:dirt"), + state("minecraft:grass_block"), + ); + let mut world = World::new(facts.air, 0); + for cz in -8..=8 { + for cx in -8..=8 { + let mut chunk = Chunk::empty(cx, cz); + for z in 0..16 { + for x in 0..16 { + for y in MIN_Y..60 { + let v = if y == 59 { + grass + } else if y > 55 { + dirt + } else { + stone + }; + chunk.set(x, y, z, v); + } + } + } + chunk.lit = true; + world.chunks.insert((cx, cz), Arc::new(chunk)); + } + } + let lan = Lan::start(sync.clone(), port, "Flat - Example".into(), 8)?; + println!("listening on {}", lan.port); + let mut hub = Hub::new( + lan, + sync, + encoder, + HubConfig { + default_game_mode: 1, + guest_commands: true, + force_game_mode: false, + hardcore: false, + view_distance: 8, + simulation_distance: 8, + dimension: "minecraft:overworld".into(), + seed: 0, + max_players: 8, + }, + ); + let mut next_entity = 100u32; + let host = HostState { + uuid: 42, + name: "Host".into(), + entity_id: 1, + position: [0.5, 60.0, 0.5], + yaw: 0.0, + pitch: 0.0, + head_yaw: 0.0, + on_ground: true, + game_mode: 1, + sneaking: false, + sprinting: false, + equipment: Default::default(), + health: 20.0, + }; + loop { + world.game_time += 1; + world.day_time += 1; + let mut ctx = TickCtx { + world: &mut world, + host: &host, + entities: &[], + next_entity: &mut next_entity, + spawn: [8.5, 60.0, 8.5], + difficulty: 2, + difficulty_locked: false, + clock_rate: 1.0, + }; + for event in hub.tick(&mut ctx) { + match event { + HostEvent::Joined(conn) => hub.place_new_player(conn, &mut ctx), + HostEvent::Packet(_, packet) => { + if std::env::var_os("HORIZON_NET_DEBUG").is_some() + && !matches!(*packet, S::ClientTickEnd(_)) + { + eprintln!("[lan] {packet:?}"); + } + } + HostEvent::Chat(line) => println!("{line}"), + HostEvent::Left(_) => {} + } + } + std::thread::sleep(Duration::from_millis(50)); + } +} diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index bc6aaff78..d673d4031 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -84,6 +84,9 @@ pub struct Audio { next_tracked: u64, /// A `SoundSource` index the next sound plays on (`/playsound`). source_override: Option, + /// Positional sounds played since the last drain, kept while the world + /// is open to the network so guests hear them too. + pub capture: Option>, } fn decode(path: &Path) -> Option<(Vec, u32)> { use symphonia::core::{ @@ -192,6 +195,7 @@ impl Audio { music: None, next_tracked: 0, source_override: None, + capture: None, } } fn open(mixer: Arc>) -> 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; }; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index bc4c7a25b..a6d1c8d13 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -33,6 +33,9 @@ mod game_mode; mod golems; mod growth; mod jukebox; +mod lan; +mod lan_actions; +mod lan_screen; mod lightning; mod loom; mod machines; @@ -268,6 +271,8 @@ enum Screen { Stats, /// The Advancements screen. Advancements, + /// WorldOptionsScreen (game/lan_screen.rs). + WorldOptions, } #[derive(Clone)] enum Icon { @@ -664,6 +669,18 @@ struct Game<'a> { persist: persist::EntityMemory, /// Connected to a server: the world comes from the network (game/remote.rs). remote: Option, + /// This world is open to the network (game/lan.rs). + lan: Option, + world_options: Option, + /// The block a guest is acting on (game/lan_actions.rs). + forced_hit: Option, + /// Level events of this tick for the guests, and the guest acting now. + lan_events: Vec<(i32, [i32; 3], i32, Option)>, + lan_acting: Option, + /// Command feedback to forward to a guest. + chat_capture: Option>, + /// Allow Cheats: whether guests may be given commands. + cheats: bool, ui: chat::UiState, combat: combat::CombatTracker, mount: mounts::MountState, @@ -760,6 +777,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 { + // 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()) } @@ -1251,6 +1276,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 { @@ -2537,6 +2563,7 @@ impl Game<'_> { self.tick_mobs()?; self.tick_experience(); } + self.tick_lan(); self.tick_hand(); self.tick_sleep(); self.tick_portal()?; @@ -3108,6 +3135,7 @@ impl Game<'_> { Screen::Dead => self.draw_death_screen(&mut batch), Screen::Stats => self.draw_stats(&mut batch), Screen::Advancements => self.draw_advancements(&mut batch), + Screen::WorldOptions => self.draw_world_options(&mut batch), Screen::Inventory => { self.draw_inventory(&mut batch); } @@ -3876,6 +3904,7 @@ impl Game<'_> { // Mobs and their projectiles. self.mob_geometry(camera, alpha, &mut out); self.player_model_geometry(camera, alpha, &mut out); + self.guest_model_geometry(camera, alpha, &mut out); self.fangs_geometry(camera, alpha, &mut out); self.name_tag_geometry(camera, alpha, &mut out); // Arrows: two crossed quads along the flight direction. @@ -6955,6 +6984,7 @@ impl Game<'_> { Screen::Dead => {} Screen::Stats => self.screen = Screen::Paused, Screen::Advancements => self.close_advancements(), + Screen::WorldOptions => self.close_world_options(), Screen::Chat => self.close_chat(), }, KeyCode::KeyT if self.screen == Screen::Inventory => self.recipe_focus_search(), @@ -7339,6 +7369,9 @@ impl ApplicationHandler for Game<'_> { self.click_creative(button == MouseButton::Right); } Screen::Paused if pressed => self.pause_click()?, + Screen::WorldOptions if pressed && button == MouseButton::Left => { + self.world_options_click() + } Screen::Dead if pressed => self.death_click()?, Screen::Advancements if button == MouseButton::Left => { let size = self @@ -7415,6 +7448,9 @@ impl ApplicationHandler for Game<'_> { WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => { self.remote_chat_key(&event) } + WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::WorldOptions => { + self.world_options_key(&event) + } WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Options => { if event.state == ElementState::Pressed && let PhysicalKey::Code(key) = event.physical_key @@ -7864,6 +7900,13 @@ pub fn run() -> Result<()> { pending_bench: None, persist: Default::default(), 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(), mount: Default::default(), diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index b68fd9b4b..70b2712fc 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -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, @@ -462,6 +466,7 @@ impl Game<'_> { self.ui .chat .add(&self.res.atlas, line, None, self.ticks, focused); + self.lan_host_chat(message); } } pub(super) fn chat_scroll(&mut self, amount: f32) { diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index b74a65c04..e8b628414 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -485,6 +485,12 @@ impl Game<'_> { let Some(Arg::GameMode(m)) = ctx.get("gamemode") else { return Ok(0); }; + self.set_default_game_mode(match m { + horizon_client::command::args::GameMode::Survival => 0, + horizon_client::command::args::GameMode::Creative => 1, + horizon_client::command::args::GameMode::Adventure => 2, + horizon_client::command::args::GameMode::Spectator => 3, + }); self.feedback(Text::translate( "commands.defaultgamemode.success", &[Text::translate(&format!("gameMode.{}", m.name()), &[])], diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 4d505b463..5ac43ed1f 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -78,11 +78,15 @@ impl Game<'_> { if let Some(value) = self.block_command(&words)? { return Ok(Some(value)); } + if let Some(value) = self.lan_control(&words)? { + return Ok(Some(value)); + } match words[0] { "help" => Ok(Some(json!({ "commands": HELP .iter() .chain(super::station_control::HELP) .chain(super::blockctl::HELP) + .chain(super::lan::HELP) .chain(super::render_control::HELP) .chain(super::sculk::HELP) .collect::>() }))), @@ -451,6 +455,7 @@ impl Game<'_> { Screen::Chat => "chat", Screen::Stats => "stats", Screen::Advancements => "advancements", + Screen::WorldOptions => "world-options", } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs new file mode 100644 index 000000000..7cce27dac --- /dev/null +++ b/crates/horizon-client/src/game/lan.rs @@ -0,0 +1,620 @@ +//! Hosting the open world on the local network ("Open to LAN"): starts the +//! server threads and the play-state hub, feeds it the world's entities each +//! tick and turns what the guests do into gameplay. A world that is not open +//! costs one `Option` check per tick. +use super::{Game, chat::PLAYER_NAME}; +use horizon_client::{ + Result, + items::ItemStack, + lan::{ + self, Lan, MAX_PLAYERS, + chunks::ChunkEncoder, + data::SyncData, + entity::EntityState, + hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, + playerdata, + }, + mobs::Mob, + text::Text, +}; +use horizon_core::geometry::Vec3; +use horizon_protocol::{ + crypto::offline_uuid, + entity_data::{Value, serializer}, +}; +use std::{ + collections::HashMap, + sync::{Arc, OnceLock}, +}; + +/// The registries and tags are the same for every world: load them once. +static SYNC: OnceLock, String>> = OnceLock::new(); + +/// The settings of the open world (WorldOptionsScreen's multiplayer section). +#[derive(Clone, Debug)] +pub struct LanSettings { + pub port: u16, + pub guest_commands: bool, + pub force_game_mode: bool, +} + +pub(super) struct LanHost { + pub hub: Hub, + pub settings: LanSettings, + pub host_entity: i32, + pub host_uuid: u128, + /// The guests' models in the host's world. + pub models: HashMap, + host_mode: i32, + pub play: HashMap, + /// 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, +} + +/// A stable UUID for an entity that has none. +fn entity_uuid(id: u32) -> u128 { + 0x4856_5a4e_0000_0000_0000_0000_0000_0000u128 | u128::from(id) +} + +/// Species that are AgeableMob (or have a baby flag at the same index). +fn ageable(kind: &str) -> bool { + matches!( + kind, + "minecraft:cow" + | "minecraft:mooshroom" + | "minecraft:pig" + | "minecraft:sheep" + | "minecraft:chicken" + | "minecraft:horse" + | "minecraft:donkey" + | "minecraft:mule" + | "minecraft:llama" + | "minecraft:cat" + | "minecraft:wolf" + | "minecraft:fox" + | "minecraft:rabbit" + | "minecraft:panda" + | "minecraft:villager" + | "minecraft:zombie" + | "minecraft:husk" + | "minecraft:drowned" + | "minecraft:zombie_villager" + | "minecraft:piglin" + | "minecraft:hoglin" + | "minecraft:goat" + | "minecraft:ocelot" + | "minecraft:turtle" + | "minecraft:strider" + | "minecraft:camel" + | "minecraft:axolotl" + ) +} + +pub const HELP: &[&str] = &[ + "lan open [PORT] [commands] [force] open the world to the network (PORT 0 picks one)", + "lan close stop hosting", + "lan status the hosting state and the guests", +]; + +impl Game<'_> { + /// `horizon-ctl lan ...`. + pub(super) fn lan_control(&mut self, words: &[&str]) -> Result> { + use serde_json::json; + if words[0] != "lan" { + return Ok(None); + } + match words.get(1).copied() { + Some("open") => { + if self.title.is_some() { + return Err("open a world first".into()); + } + let port = words.get(2).map_or(Ok(0), |p| p.parse::())?; + self.lan_open(LanSettings { + port: if port == 0 { + lan::available_port() + } else { + port + }, + guest_commands: words.contains(&"commands"), + force_game_mode: words.contains(&"force"), + })?; + Ok(Some(json!({ "ok": true, "port": self.lan_port() }))) + } + Some("close") => { + self.lan_close(true); + Ok(Some(json!({ "ok": true }))) + } + Some("status") => Ok(Some(match &self.lan { + Some(h) => json!({ + "open": true, + "port": h.settings.port, + "guests": h.hub.guests.iter().map(|g| json!({ + "name": g.name, + "position": g.position, + "placed": g.placed, + "loaded": g.loaded, + "game_mode": g.game_mode, + "chunks": g.sent_chunks.len(), + "tracked": g.tracker.len(), + })).collect::>(), + }), + None => json!({ "open": false }), + })), + _ => Err("lan open|close|status".into()), + } + } + + pub(super) fn lan_open(&mut self, settings: LanSettings) -> Result<()> { + if self.lan.is_some() || self.remote.is_some() || self.title.is_some() { + return Err("already open".into()); + } + let root = self.options.resources.clone(); + let sync = SYNC + .get_or_init(|| SyncData::load(&root).map(Arc::new)) + .clone()?; + let biome_names: Vec = self + .res + .biomes + .list + .iter() + .map(|b| b.name.clone()) + .collect(); + let registry: Vec = sync + .dynamic + .registries + .get("minecraft:worldgen/biome") + .map(|v| v.iter().map(|(n, _)| n.clone()).collect()) + .unwrap_or_default(); + let encoder = ChunkEncoder::new( + self.res + .facts + .states + .iter() + .map(|s| (s.name.clone(), s.fluid_level > 0 || s.waterlogged)), + &sync.builtin, + &biome_names, + ®istry, + ); + let motd = format!("{PLAYER_NAME} - {}", self.level.name); + let lan = Lan::start(sync.clone(), settings.port, motd, MAX_PLAYERS)?; + let host_uuid = self.level.player_uuid.map_or_else( + || offline_uuid(PLAYER_NAME), + |u| { + u128::from(u[0] as u32) << 96 + | u128::from(u[1] as u32) << 64 + | u128::from(u[2] as u32) << 32 + | u128::from(u[3] as u32) + }, + ); + lan.reserve(host_uuid); + self.next_entity += 1; + let host_entity = self.next_entity as i32; + let hub = Hub::new( + lan, + sync, + encoder, + HubConfig { + default_game_mode: self.level.mode(), + guest_commands: settings.guest_commands, + force_game_mode: settings.force_game_mode, + hardcore: self.level.hardcore, + view_distance: self.settings.render_distance.clamp(2, 32), + simulation_distance: self.settings.render_distance.clamp(2, 32), + dimension: self.dim.id().to_owned(), + seed: self.level.seed, + max_players: MAX_PLAYERS, + }, + ); + let port = hub.lan.port; + self.world.block_log = Some(Vec::new()); + self.lan = Some(LanHost { + hub, + settings: LanSettings { port, ..settings }, + host_entity, + 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())], + )); + Ok(()) + } + + /// IntegratedServer.unpublishServer: the guests are sent away. + pub(super) fn lan_close(&mut self, announce: bool) { + let Some(mut host) = self.lan.take() else { + return; + }; + for g in &host.hub.guests { + playerdata::save(g, &self.world_root); + } + host.hub.disconnect_all(); + // 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( + "menu.multiplayerOptions.publish.stopped", + &[], + )); + } + } + + /// The world's default game mode (`defaultgamemode`). + pub(super) fn set_default_game_mode(&mut self, mode: i32) { + self.level.game_mode = mode; + self.level.creative = mode == 1; + if let Some(host) = self.lan.as_mut() { + host.hub.config.default_game_mode = mode; + } + } + + /// New command access and game mode forcing settings of the open world. + pub(super) fn lan_apply_settings(&mut self, guest_commands: bool, force: bool) { + if let Some(host) = self.lan.as_mut() { + host.settings.guest_commands = guest_commands; + host.settings.force_game_mode = force; + host.hub.config.guest_commands = guest_commands; + host.hub.config.force_game_mode = force; + host.hub.resend_commands(); + } + } + + pub(super) fn lan_port(&self) -> Option { + self.lan.as_ref().map(|h| h.settings.port) + } + + /// The host as the guests see them. + fn lan_host_state(&self, host: &LanHost) -> Option { + let p = self.player.as_ref()?; + let mut equipment: [Option; 6] = Default::default(); + equipment[0] = self.inventory.get(self.selected).cloned().flatten(); + equipment[1] = self.offhand.clone(); + // Feet, legs, chest, head are slots 2..=5; armor is stored head first. + equipment[2] = self.armor[3].clone(); + equipment[3] = self.armor[2].clone(); + equipment[4] = self.armor[1].clone(); + equipment[5] = self.armor[0].clone(); + Some(HostState { + uuid: host.host_uuid, + name: PLAYER_NAME.to_owned(), + entity_id: host.host_entity, + position: [p.position.x, p.position.y, p.position.z], + yaw: self.yaw, + pitch: self.pitch, + head_yaw: self.yaw, + on_ground: p.ground.on_ground, + game_mode: self.mode_id(), + sneaking: p.pose == horizon_client::pose::Pose::Crouching, + sprinting: p.sprinting, + equipment, + health: p.health.health(), + }) + } + + /// Mobs and items as the entities guests track. + fn lan_entities(&self, hub: &mut Hub) -> Vec { + let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len()); + for m in self.mobs.iter().filter(|m| !m.removed) { + let mut meta = Vec::new(); + if let Some(name) = &m.custom_name { + meta.push(( + 2, + serializer::OPTIONAL_COMPONENT, + Value::OptText(Some(horizon_protocol::text::literal(name))), + )); + if m.name_visible { + meta.push((3, serializer::BOOLEAN, Value::Bool(true))); + } + } + if m.fire_ticks > 0 { + meta.push((0, serializer::BYTE, Value::Byte(1))); + } + if m.health < m.kind.max_health { + meta.push((9, serializer::FLOAT, Value::Float(m.health.max(0.0)))); + } + let kind = m.kind.id.as_str(); + if ageable(kind) && m.is_baby() { + meta.push((16, serializer::BOOLEAN, Value::Bool(true))); + } + if kind == "minecraft:sheep" { + let value = (m.extra.color & 15) | if m.extra.sheared { 16 } else { 0 }; + meta.push((17, serializer::BYTE, Value::Byte(value as i8))); + } + let (yaw, pitch) = (m.yaw, m.head_pitch); + out.push(EntityState { + id: m.id as i32, + uuid: entity_uuid(m.id), + kind: kind.to_owned(), + position: [m.position.x, m.position.y, m.position.z], + yaw, + pitch, + head_yaw: m.head_yaw, + on_ground: m.on_ground, + velocity: [m.velocity.x, m.velocity.y, m.velocity.z], + data: 0, + meta, + equipment: Vec::new(), + send_velocity: false, + }); + } + for d in &self.dropped { + let stack = hub.stack(&Some(d.stack.clone())); + out.push(EntityState { + id: d.id as i32, + uuid: entity_uuid(d.id), + kind: "minecraft:item".to_owned(), + position: [d.position.x, d.position.y, d.position.z], + yaw: 0.0, + pitch: 0.0, + head_yaw: 0.0, + on_ground: d.on_ground, + velocity: [d.velocity.x, d.velocity.y, d.velocity.z], + data: 0, + meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))], + equipment: Vec::new(), + send_velocity: true, + }); + } + out + } + + /// Run the hub for this tick and apply what the guests did. + pub(super) fn tick_lan(&mut self) { + let Some(mut host) = self.lan.take() else { + return; + }; + if let Some(state) = self.lan_host_state(&host) { + let has_guests = !host.hub.guests.is_empty(); + let entities = if has_guests { + self.lan_entities(&mut host.hub) + } else { + Vec::new() + }; + let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); + let events = { + let mut ctx = TickCtx { + world: &mut self.world, + host: &state, + entities: &entities, + next_entity: &mut self.next_entity, + spawn, + difficulty: i32::from(self.ui.difficulty), + difficulty_locked: false, + clock_rate: if self.ui.rules.bool("advance_time") { + self.ui.clock.rate + } else { + 0.0 + }, + }; + host.hub.tick(&mut ctx) + }; + if host.host_mode != state.game_mode { + host.host_mode = state.game_mode; + host.hub.set_host_game_mode(state.uuid, state.game_mode); + } + for event in events { + match event { + HostEvent::Joined(conn) => { + self.lan_guest_joined(&mut host, conn, &state, &entities, spawn) + } + HostEvent::Left(guest) => { + playerdata::save(&guest, &self.world_root); + host.models.remove(&guest.conn); + } + HostEvent::Chat(line) => self.system_message(Text::literal(line)), + HostEvent::Packet(conn, packet) => { + self.lan_guest_packet(&mut host, conn, *packet); + } + } + } + } + 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); + } + + fn lan_guest_joined( + &mut self, + host: &mut LanHost, + conn: u32, + state: &HostState, + entities: &[EntityState], + spawn: [f64; 3], + ) { + let default_mode = host.hub.config.default_game_mode; + let force = host.hub.config.force_game_mode; + let root = self.world_root.clone(); + let Some(g) = host.hub.guest_mut(conn) else { + return; + }; + let known = playerdata::load(g, &root); + if !known || force { + g.game_mode = default_mode; + } + if !known { + g.position = spawn; + g.previous_position = spawn; + g.health = 20.0; + g.food = 20; + } + let mut ctx = TickCtx { + world: &mut self.world, + host: state, + entities, + next_entity: &mut self.next_entity, + spawn, + difficulty: i32::from(self.ui.difficulty), + difficulty_locked: false, + clock_rate: self.ui.clock.rate, + }; + host.hub.place_new_player(conn, &mut ctx); + } + + /// 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, [pos.x, pos.y, pos.z], *data, 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. + fn lan_update_streaming(&mut self, host: &LanHost) { + self.streaming.extra = host + .hub + .guests + .iter() + .filter(|g| g.placed) + .map(|g| (g.chunk(), g.view_distance + 1)) + .collect(); + } + + /// The guests' models, for the host to see them. + fn lan_update_models(&mut self, host: &mut LanHost) { + let Some(kind) = self.res.player_type.clone() else { + return; + }; + host.models + .retain(|conn, _| host.hub.guest(*conn).is_some_and(|g| g.placed)); + for g in host.hub.guests.iter().filter(|g| g.placed) { + let at = Vec3::new( + g.position[0], + g.position[1] - if g.sneaking { 0.125 } else { 0.0 }, + g.position[2], + ); + let m = host + .models + .entry(g.conn) + .or_insert_with(|| Mob::new(g.entity_id as u32, kind.clone(), at, g.yaw)); + let (dx, dy, dz) = ( + at.x - m.position.x, + at.y - m.position.y, + at.z - m.position.z, + ); + m.previous = m.position; + m.position = at; + if dx * dx + dy * dy + dz * dz > 100.0 { + m.previous = at; + } + m.previous_yaw = m.yaw; + m.previous_body_yaw = m.body_yaw; + m.previous_head_yaw = m.head_yaw; + m.previous_head_pitch = m.head_pitch; + m.yaw = g.yaw; + m.head_yaw = g.head_yaw; + m.head_pitch = g.pitch; + let mut target = m.body_yaw; + if dx * dx + dz * dz > 0.002_500_000_2 { + target = (dz.atan2(dx) as f32).to_degrees() - 90.0; + } + let wrap = |a: f32| (a + 180.0).rem_euclid(360.0) - 180.0; + m.body_yaw += wrap(target - m.body_yaw) * 0.3; + let diff = wrap(g.yaw - m.body_yaw); + if diff.abs() > 50.0 { + m.body_yaw += diff - diff.signum() * 50.0; + } + let dist = (dx * dx + dz * dz).sqrt() as f32; + m.previous_limb_speed = m.limb_speed; + m.limb_speed += ((dist * 4.0).min(1.0) - m.limb_speed) * 0.4; + m.limb_position += m.limb_speed; + m.age = m.age.wrapping_add(1); + m.extra.main_hand = g + .inventory + .get(g.selected) + .and_then(|s| s.as_ref()) + .map(|s| s.item.clone()); + m.extra.off_hand = g.offhand.as_ref().map(|s| s.item.clone()); + m.extra.crouching = g.sneaking; + } + } + + /// The guests' models for the entity pass. + pub(super) fn guest_model_geometry( + &self, + camera: glam::DVec3, + alpha: f64, + out: &mut Vec, + ) { + let Some(host) = &self.lan else { + return; + }; + let atlas = &self.res.atlas; + let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); + for m in host.models.values() { + let light = self.world.light( + m.position.x.floor() as i32, + (m.position.y + 1.62).floor() as i32, + m.position.z.floor() as i32, + ); + let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + horizon_client::mobs::render::render_with( + m, + alpha as f32, + camera, + &lookup, + packed, + &self.res.mob_data, + &self.player_armor_layers(), + out, + ); + } + } + + /// A chat line the host typed, for the guests. + pub(super) fn lan_host_chat(&mut self, message: &str) { + if let Some(host) = &self.lan { + host.hub.chat(PLAYER_NAME, message); + } + } +} diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs new file mode 100644 index 000000000..bb64597ef --- /dev/null +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -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, + destroy_delay: u32, + using: Option<(usize, u32)>, + use_delay: u32, + attack_ticks: u32, + swing: Option, + 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 { + 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( + &mut self, + host: &mut LanHost, + conn: u32, + f: impl FnOnce(&mut Self) -> R, + ) -> Option { + 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, + ) -> Option { + 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) { + 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 = 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 = 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 = 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; + } + } +} diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs new file mode 100644 index 000000000..4d8e46947 --- /dev/null +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -0,0 +1,371 @@ +//! WorldOptionsScreen: the in-world options with the multiplayer section +//! that opens the world to the local network (the 26.3 replacement of the +//! old "Open to LAN" screen): default and personal game mode, cheats, +//! difficulty, LAN on/off with its port, command access for guests and +//! forcing the game mode. +use super::{Game, Screen, lan::LanSettings}; +use horizon_client::{ + hud::{HudBatch, rgba}, + text::Text, + ui::{self, EditBox}, +}; +use winit::{event::KeyEvent, keyboard::PhysicalKey}; + +pub(super) struct WorldOptions { + default_mode: i32, + personal_mode: i32, + cheats: bool, + difficulty: u8, + lan: bool, + port: EditBox, + /// The free port suggested while the box is empty. + hint: u16, + guest_commands: bool, + force: bool, + initial: Snapshot, +} +#[derive(Clone, PartialEq)] +struct Snapshot { + default_mode: i32, + personal_mode: i32, + cheats: bool, + difficulty: u8, + lan: bool, + port: u16, + guest_commands: bool, + force: bool, +} + +const MODES: [&str; 4] = ["survival", "creative", "adventure", "spectator"]; +const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"]; + +#[derive(Clone, Copy, PartialEq)] +enum Button { + DefaultMode, + PersonalMode, + Cheats, + Difficulty, + Lan, + CommandAccess, + Force, + Apply, + Cancel, +} + +fn on_off(on: bool) -> Text { + Text::translate(if on { "options.on" } else { "options.off" }, &[]) +} +fn labelled(key: &str, value: Text) -> Text { + Text::translate("options.generic_value", &[Text::translate(key, &[]), value]) +} + +impl WorldOptions { + fn parsed_port(&self) -> Option { + if self.port.value.is_empty() { + return Some(self.hint); + } + self.port.value.parse::().ok().filter(|p| *p >= 1024) + } + fn snapshot(&self) -> Snapshot { + Snapshot { + default_mode: self.default_mode, + personal_mode: self.personal_mode, + cheats: self.cheats, + difficulty: self.difficulty, + lan: self.lan, + port: if self.lan { + self.parsed_port().unwrap_or(0) + } else { + 0 + }, + guest_commands: self.guest_commands && self.lan && self.cheats, + force: self.force, + } + } + fn changed(&self) -> bool { + let valid = !self.lan || self.parsed_port().is_some(); + valid && self.snapshot() != self.initial + } + fn buttons(w: f32) -> Vec<(Button, f32, f32, f32)> { + let x = (w / 2.0 - 154.0).floor(); + let right = x + 158.0; + vec![ + (Button::DefaultMode, x, 38.0, 308.0), + (Button::PersonalMode, x, 62.0, 308.0), + (Button::Cheats, x, 86.0, 150.0), + (Button::Difficulty, right, 86.0, 150.0), + (Button::Lan, x, 126.0, 150.0), + (Button::CommandAccess, x, 150.0, 150.0), + (Button::Force, right, 150.0, 150.0), + ] + } + fn footer(w: f32, h: f32) -> [(Button, f32, f32, f32); 2] { + let x = (w / 2.0 - 154.0).floor(); + [ + (Button::Apply, x, h - 28.0, 150.0), + (Button::Cancel, x + 158.0, h - 28.0, 150.0), + ] + } + fn label(&self, b: Button) -> Text { + let mode = |m: i32| { + Text::translate( + &format!("selectWorld.gameMode.{}", MODES[m as usize & 3]), + &[], + ) + }; + match b { + Button::DefaultMode => { + labelled("options.worldOptions.game_mode", mode(self.default_mode)) + } + Button::PersonalMode => labelled( + "options.worldOptions.personal_game_mode", + mode(self.personal_mode), + ), + Button::Cheats => labelled("selectWorld.allowCommands", on_off(self.cheats)), + Button::Difficulty => labelled( + "options.difficulty", + Text::translate( + &format!( + "options.difficulty.{}", + DIFFICULTIES[usize::from(self.difficulty) & 3] + ), + &[], + ), + ), + Button::Lan => labelled("menu.multiplayerOptions.lan", on_off(self.lan)), + Button::CommandAccess => labelled( + "options.worldOptions.guest.command_access", + on_off(self.guest_commands && self.lan && self.cheats), + ), + Button::Force => labelled( + "options.worldOptions.guest.force_game_mode", + on_off(self.force || !self.lan), + ), + Button::Apply => Text::translate("menu.multiplayerOptions.applyChanges", &[]), + Button::Cancel => Text::translate("gui.cancel", &[]), + } + } + fn active(&self, b: Button) -> bool { + match b { + Button::CommandAccess => self.lan && self.cheats, + Button::Force => self.lan && !(self.guest_commands && self.cheats), + Button::Apply => self.changed(), + _ => true, + } + } +} + +impl Game<'_> { + pub(super) fn open_world_options(&mut self) { + let hint = horizon_client::lan::available_port(); + let lan = self.lan.is_some(); + let mut port = EditBox::new(0.0, 0.0, 150.0, 20.0); + port.max_length = 5; + let (guest_commands, force) = self.lan.as_ref().map_or((false, true), |h| { + (h.settings.guest_commands, h.settings.force_game_mode) + }); + if let Some(p) = self.lan_port() { + port.set_value(&p.to_string()); + } + let mut options = WorldOptions { + default_mode: self.level.mode(), + personal_mode: self.mode_id(), + cheats: self.cheats, + difficulty: self.ui.difficulty, + lan, + port, + hint, + guest_commands, + force, + initial: Snapshot { + default_mode: 0, + personal_mode: 0, + cheats: false, + difficulty: 0, + lan: false, + port: 0, + guest_commands: false, + force: false, + }, + }; + options.initial = options.snapshot(); + self.world_options = Some(options); + self.screen = Screen::WorldOptions; + } + + pub(super) fn close_world_options(&mut self) { + self.world_options = None; + self.screen = Screen::Paused; + } + + pub(super) fn draw_world_options(&mut self, batch: &mut HudBatch) { + let Some(mut o) = self.world_options.take() else { + return; + }; + let atlas = &self.res.atlas; + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let centered = |batch: &mut HudBatch, key: &str, y: f32| { + let t = Text::translate(key, &[]); + let tw = atlas.font.width_text(&t); + batch.text_styled(atlas, &t, ((w - tw) / 2.0).floor(), y, u32::MAX, true); + }; + centered(batch, "options.worldOptions.title", 12.0); + centered(batch, "options.worldOptions.general.title", 26.0); + centered(batch, "options.worldOptions.multiplayer.title", 114.0); + for (b, x, y, bw) in WorldOptions::buttons(w) + .into_iter() + .chain(WorldOptions::footer(w, h)) + { + let active = o.active(b); + let hover = active && ui::hovered(self.cursor, x, y, bw, 20.0); + ui::button(batch, atlas, x, y, bw, 20.0, &o.label(b), active, hover); + } + // The port box sits beside the LAN button. + let x = (w / 2.0 - 154.0).floor() + 158.0; + o.port.x = x; + o.port.y = 126.0; + o.port.focused = o.lan && o.port.focused; + if o.lan { + o.port.draw(batch, atlas, None); + if o.port.value.is_empty() { + let hint = Text::literal(o.hint.to_string()); + batch.text_styled( + atlas, + &hint, + x + 4.0, + 132.0, + rgba(160, 160, 160, 255), + false, + ); + } + if o.parsed_port().is_none() { + let t = Text::translate( + "lanServer.port.invalid.new", + &[Text::literal("1024"), Text::literal("65535")], + ); + let first = t.clone(); + batch.text_styled(atlas, &first, x, 148.0, rgba(255, 85, 85, 255), true); + } + } else { + ui::button( + batch, + atlas, + x, + 126.0, + 150.0, + 20.0, + &Text::translate("lanServer.port", &[]), + false, + false, + ); + } + self.world_options = Some(o); + } + + pub(super) fn world_options_click(&mut self) { + let Some(mut o) = self.world_options.take() else { + return; + }; + let size = self + .renderer + .as_ref() + .map_or([1, 1], |r| [r.config.width, r.config.height]); + let b = HudBatch::new(size); + let (w, h) = (b.width, b.height); + let port_x = (w / 2.0 - 154.0).floor() + 158.0; + o.port.focused = o.lan && ui::hovered(self.cursor, port_x, 126.0, 150.0, 20.0); + let hit = WorldOptions::buttons(w) + .into_iter() + .chain(WorldOptions::footer(w, h)) + .find(|(button, x, y, bw)| { + o.active(*button) && ui::hovered(self.cursor, *x, *y, *bw, 20.0) + }) + .map(|b| b.0); + match hit { + Some(Button::DefaultMode) => o.default_mode = (o.default_mode + 1) % 4, + Some(Button::PersonalMode) => o.personal_mode = (o.personal_mode + 1) % 4, + Some(Button::Cheats) => o.cheats = !o.cheats, + Some(Button::Difficulty) => o.difficulty = (o.difficulty + 1) % 4, + Some(Button::Lan) => { + o.lan = !o.lan; + o.port.focused = false; + } + Some(Button::CommandAccess) => o.guest_commands = !o.guest_commands, + Some(Button::Force) => o.force = !o.force, + Some(Button::Cancel) => { + self.world_options = Some(o); + self.close_world_options(); + return; + } + Some(Button::Apply) => { + let wanted = o.snapshot(); + let before = o.initial.clone(); + self.world_options = Some(o); + self.apply_world_options(&before, &wanted); + self.close_world_options(); + self.screen = Screen::Playing; + self.capture(true); + return; + } + None => {} + } + self.world_options = Some(o); + } + + pub(super) fn world_options_key(&mut self, event: &KeyEvent) { + if event.state != winit::event::ElementState::Pressed { + return; + } + let PhysicalKey::Code(key) = event.physical_key else { + return; + }; + let ctrl = self.keys.contains(&winit::keyboard::KeyCode::ControlLeft); + let Some(o) = self.world_options.as_mut() else { + return; + }; + if !o.port.focused { + return; + } + if !o.port.key(key, ctrl, false) + && !ctrl + && let Some(text) = &event.text + { + let digits: String = text.chars().filter(char::is_ascii_digit).collect(); + if !digits.is_empty() { + o.port.insert_text(&digits); + } + } + } + + fn apply_world_options(&mut self, before: &Snapshot, wanted: &Snapshot) { + if wanted.difficulty != before.difficulty { + let name = DIFFICULTIES[usize::from(wanted.difficulty) & 3]; + self.run_command(&format!("difficulty {name}")); + } + if wanted.default_mode != before.default_mode { + self.set_default_game_mode(wanted.default_mode); + } + if wanted.personal_mode != before.personal_mode { + self.set_mode_id(wanted.personal_mode); + } + self.cheats = wanted.cheats; + let settings_changed = + wanted.guest_commands != before.guest_commands || wanted.force != before.force; + if wanted.lan != before.lan || (wanted.lan && wanted.port != before.port) { + self.lan_close(before.lan); + if wanted.lan { + let opened = self.lan_open(LanSettings { + port: wanted.port, + guest_commands: wanted.guest_commands, + force_game_mode: wanted.force, + }); + if opened.is_err() { + self.system_message(Text::translate("commands.publish.failed", &[])); + } + } + } else if settings_changed { + self.lan_apply_settings(wanted.guest_commands, wanted.force); + } + } +} diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 94585c7a6..b98c4ac7f 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -24,7 +24,7 @@ fn pause_buttons(w: f32, h: f32) -> Vec<(f32, f32, f32, &'static str, u8, bool)> 98.0, "options.worldOptions.button", 9, - false, + true, ), (x0 + 4.0, y0 + 146.0, 204.0, "menu.returnToMenu", 2, true), ] @@ -114,6 +114,7 @@ impl Game<'_> { Some(1) => self.open_options(false), Some(3) => self.open_stats(), Some(4) => self.open_advancements(true), + Some(9) => self.open_world_options(), Some(2) => self.close_world()?, _ => {} } diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs new file mode 100644 index 000000000..5660aaf94 --- /dev/null +++ b/crates/horizon-client/src/lan/chunks.rs @@ -0,0 +1,356 @@ +//! Encoding resident chunks for the wire: ClientboundLevelChunkWithLightPacket +//! (sections with their paletted containers, block entities and the sky and +//! block DataLayers) and the section block-change batches. +use crate::{ + chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS, Section}, + containers::BlockEntity, +}; +use horizon_protocol::{ + buf::set_bit, + chunk::{BIOMES, BLOCKS, BlockEntityInfo, ChunkData, LightData, Paletted, Strategy}, + packets::play::LevelChunkWithLight, + registry::{Builtin, ceil_log2}, +}; +use horizon_world::nbt::Tag; +use std::{collections::HashMap, sync::Arc}; + +const NON_AIR: u8 = 1; +const FLUID: u8 = 2; +const ENTITY: u8 = 4; + +/// The vanilla block entity type of a block (BlockEntityType.validBlocks). +pub fn block_entity_type(name: &str) -> Option<&'static str> { + let n = name.strip_prefix("minecraft:")?; + Some(match n { + "chest" => "minecraft:chest", + "trapped_chest" => "minecraft:trapped_chest", + "ender_chest" => "minecraft:ender_chest", + "barrel" => "minecraft:barrel", + "furnace" => "minecraft:furnace", + "blast_furnace" => "minecraft:blast_furnace", + "smoker" => "minecraft:smoker", + "hopper" => "minecraft:hopper", + "dispenser" => "minecraft:dispenser", + "dropper" => "minecraft:dropper", + "brewing_stand" => "minecraft:brewing_stand", + "beacon" => "minecraft:beacon", + "bell" => "minecraft:bell", + "campfire" | "soul_campfire" => "minecraft:campfire", + "enchanting_table" => "minecraft:enchanting_table", + "jukebox" => "minecraft:jukebox", + "lectern" => "minecraft:lectern", + "spawner" => "minecraft:mob_spawner", + "comparator" => "minecraft:comparator", + "daylight_detector" => "minecraft:daylight_detector", + "conduit" => "minecraft:conduit", + "decorated_pot" => "minecraft:decorated_pot", + "moving_piston" => "minecraft:piston", + "structure_block" => "minecraft:structure_block", + "jigsaw" => "minecraft:jigsaw", + "command_block" | "chain_command_block" | "repeating_command_block" => { + "minecraft:command_block" + } + "end_portal" => "minecraft:end_portal", + "end_gateway" => "minecraft:end_gateway", + "sculk_sensor" => "minecraft:sculk_sensor", + "calibrated_sculk_sensor" => "minecraft:calibrated_sculk_sensor", + "sculk_catalyst" => "minecraft:sculk_catalyst", + "sculk_shrieker" => "minecraft:sculk_shrieker", + "crafter" => "minecraft:crafter", + "chiseled_bookshelf" => "minecraft:chiseled_bookshelf", + "trial_spawner" => "minecraft:trial_spawner", + "vault" => "minecraft:vault", + "beehive" | "bee_nest" => "minecraft:beehive", + "suspicious_sand" | "suspicious_gravel" => "minecraft:brushable_block", + "creaking_heart" => "minecraft:creaking_heart", + "test_block" => "minecraft:test_block", + "test_instance_block" => "minecraft:test_instance_block", + n if n.ends_with("shulker_box") => "minecraft:shulker_box", + n if n.ends_with("_wall_hanging_sign") || n.ends_with("_hanging_sign") => { + "minecraft:hanging_sign" + } + n if n.ends_with("_sign") => "minecraft:sign", + n if n.ends_with("_banner") => "minecraft:banner", + n if n.ends_with("_head") || n.ends_with("_skull") => "minecraft:skull", + n if n.ends_with("_shelf") => "minecraft:shelf", + n if n.ends_with("copper_golem_statue") => "minecraft:copper_golem_statue", + _ => return None, + }) +} + +/// Per-state facts and registry ids for encoding chunks. +pub struct ChunkEncoder { + flags: Vec, + /// Block entity type id per state (-1 for none). + entity_types: Vec, + /// Network biome id per internal biome index. + pub biome_ids: Vec, + biome_bits: u8, + /// The block registry id of each state's block, for BlockEvent. + pub block_ids: Vec, +} +impl ChunkEncoder { + /// `biome_names`: the internal biome list in order; `biome_registry`: + /// the synchronized biome entries in network order. + pub fn new( + states: impl IntoIterator, bool)>, + builtin: &Builtin, + biome_names: &[String], + biome_registry: &[String], + ) -> Self { + let types = builtin.get("minecraft:block_entity_type"); + let blocks = builtin.get("minecraft:block"); + let mut flags = Vec::new(); + let mut entity_types = Vec::new(); + let mut block_ids = Vec::new(); + for (name, has_fluid) in states { + let air = matches!( + &*name, + "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" + ); + let mut f = 0u8; + if !air { + f |= NON_AIR; + if has_fluid { + f |= FLUID; + } + } + let t = block_entity_type(&name) + .and_then(|t| types.and_then(|ids| ids.id(t))) + .map_or(-1, |v| v as i16); + if t >= 0 { + f |= ENTITY; + } + flags.push(f); + entity_types.push(t); + block_ids.push(blocks.and_then(|b| b.id(&name)).unwrap_or(0)); + } + let biome_ids = biome_names + .iter() + .map(|n| { + biome_registry + .iter() + .position(|b| b == n) + .map_or(0, |i| i as i32) + }) + .collect(); + Self { + flags, + entity_types, + biome_ids, + biome_bits: ceil_log2(biome_registry.len()), + block_ids, + } + } + pub fn entity_type(&self, state: u16) -> Option { + self.entity_types + .get(usize::from(state)) + .filter(|t| **t >= 0) + .map(|t| i32::from(*t)) + } + pub fn is_air(&self, state: u16) -> bool { + self.flags + .get(usize::from(state)) + .is_none_or(|f| f & NON_AIR == 0) + } + + fn section( + &self, + section: &Section, + chunk: &Chunk, + index: usize, + ) -> (horizon_protocol::chunk::Section, bool) { + let mut values = Vec::with_capacity(BLOCKS); + let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, false); + let mut count = |state: u16, n: i16| { + let f = self.flags.get(usize::from(state)).copied().unwrap_or(0); + if f & NON_AIR != 0 { + non_empty += n; + if f & FLUID != 0 { + fluids += n; + } + } + f & ENTITY != 0 + }; + match §ion.blocks { + Blocks::Uniform(v) => { + entities |= count(*v, BLOCKS as i16); + values.resize(BLOCKS, i32::from(*v)); + } + Blocks::Full(a) => { + for &v in a.iter() { + entities |= count(v, 1); + values.push(i32::from(v)); + } + } + } + let biome_values: Vec = (0..BIOMES) + .map(|j| { + let internal = chunk.biomes.get(index * BIOMES + j).copied().unwrap_or(0); + self.biome_ids + .get(usize::from(internal)) + .copied() + .unwrap_or(0) + }) + .collect(); + ( + horizon_protocol::chunk::Section { + non_empty, + fluids, + states: Paletted::from_values(&values, Strategy::Blocks, 16), + biomes: Paletted::from_values(&biome_values, Strategy::Biomes, self.biome_bits), + }, + entities, + ) + } + + /// The chunk column with its light and block entities. + pub fn encode( + &self, + chunk: &Chunk, + block_entities: &HashMap<(i32, i32, i32), BlockEntity>, + ) -> LevelChunkWithLight { + let mut sections = Vec::with_capacity(SECTIONS); + let mut entity_infos = Vec::new(); + for (i, s) in chunk.sections.iter().enumerate() { + let (encoded, has_entities) = self.section(s, chunk, i); + if has_entities { + for y in 0..16 { + for z in 0..16 { + for x in 0..16 { + let state = s.get(crate::chunk::index(x, y, z)); + if let Some(kind) = self.entity_type(state) { + let wy = MIN_Y + (i as i32) * 16 + y; + let pos = (chunk.x * 16 + x, wy, chunk.z * 16 + z); + entity_infos.push(BlockEntityInfo { + packed_xz: ((x << 4) | z) as i8, + y: wy as i16, + kind, + tag: block_entities + .get(&pos) + .and_then(entity_tag) + .unwrap_or_else( + || Tag::compound(Vec::<(&str, Tag)>::new()), + ), + }); + } + } + } + } + } + sections.push(encoded); + } + LevelChunkWithLight { + x: chunk.x, + z: chunk.z, + chunk: ChunkData { + heightmaps: Vec::new(), + buffer: ChunkData::from_sections(§ions), + block_entities: entity_infos, + }, + light: light_data(chunk), + } + } +} + +/// The update tag of a block entity (getUpdateTag) for what the client shows. +pub fn entity_tag(entity: &BlockEntity) -> Option { + match entity { + BlockEntity::Sign(sign) => Some(Tag::compound(sign.encode())), + BlockEntity::Jukebox(_) | BlockEntity::Lectern(_) => None, + _ => None, + } +} + +/// Light sections run from one below the world to one above it. +fn light_data(chunk: &Chunk) -> LightData { + let mut data = LightData { + sky_mask: Vec::new(), + block_mask: Vec::new(), + empty_sky_mask: Vec::new(), + empty_block_mask: Vec::new(), + sky: Vec::new(), + block: Vec::new(), + }; + // The section below the world has no sky light; the one above is full. + set_bit(&mut data.empty_sky_mask, 0); + set_bit(&mut data.empty_block_mask, 0); + for (i, s) in chunk.sections.iter().enumerate() { + let bit = i + 1; + let (mut sky, mut block) = (vec![0u8; 2048], vec![0u8; 2048]); + let (mut sky_any, mut block_any) = (false, false); + match &s.light { + Light::Uniform(v) => { + let (sk, bl) = (v >> 4, v & 15); + sky_any = sk != 0; + block_any = bl != 0; + let (sb, bb) = (sk | sk << 4, bl | bl << 4); + sky.fill(sb); + block.fill(bb); + } + Light::Full(a) => { + for (j, &v) in a.iter().enumerate() { + let (sk, bl) = (v >> 4, v & 15); + sky_any |= sk != 0; + block_any |= bl != 0; + if j & 1 == 0 { + sky[j >> 1] |= sk; + block[j >> 1] |= bl; + } else { + sky[j >> 1] |= sk << 4; + block[j >> 1] |= bl << 4; + } + } + } + } + if sky_any { + set_bit(&mut data.sky_mask, bit); + data.sky.push(sky); + } else { + set_bit(&mut data.empty_sky_mask, bit); + } + if block_any { + set_bit(&mut data.block_mask, bit); + data.block.push(block); + } else { + set_bit(&mut data.empty_block_mask, bit); + } + } + set_bit(&mut data.sky_mask, SECTIONS + 1); + data.sky.push(vec![0xFF; 2048]); + set_bit(&mut data.empty_block_mask, SECTIONS + 1); + data +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn block_entity_blocks_are_recognised() { + assert_eq!( + block_entity_type("minecraft:oak_sign"), + Some("minecraft:sign") + ); + assert_eq!( + block_entity_type("minecraft:oak_wall_hanging_sign"), + Some("minecraft:hanging_sign") + ); + assert_eq!( + block_entity_type("minecraft:red_shulker_box"), + Some("minecraft:shulker_box") + ); + assert_eq!(block_entity_type("minecraft:stone"), None); + } + + #[test] + fn light_masks_cover_the_world_plus_borders() { + let chunk = Chunk::empty(0, 0); + let data = light_data(&chunk); + // Default sections are full sky light and no block light. + assert_eq!(data.sky.len(), SECTIONS + 1); + assert_eq!(data.block.len(), 0); + assert_eq!(data.sky[0][0], 0xFF); + assert!(horizon_protocol::buf::bit(&data.empty_block_mask, 5)); + } +} diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs new file mode 100644 index 000000000..6cd41d6d6 --- /dev/null +++ b/crates/horizon-client/src/lan/conn.rs @@ -0,0 +1,395 @@ +//! One accepted connection: handshake, status ping, offline-mode login and the +//! configuration phase (ServerStatusPacketListenerImpl, +//! ServerLoginPacketListenerImpl, ServerConfigurationPacketListenerImpl). A +//! player that completes configuration continues in the play state: the +//! reader forwards decoded packets to the game thread while a writer thread +//! frames, compresses and encrypts what the game queues, and answers the +//! keep-alive schedule on its own so a long frame never times a client out. +use super::{ + Joined, NetEvent, Out, Shared, + data::{CORE_PACK, SyncData}, +}; +use horizon_protocol::{ + PROTOCOL_VERSION, + connection::{ConnReader, ConnWriter, Connection}, + crypto::offline_uuid, + packets::{ + Empty, + configuration::{self as cfg, ClientInformation, KnownPack}, + handshake, login, play, status, + }, + text::translatable, +}; +use std::{ + net::TcpStream, + sync::{ + Arc, + atomic::{AtomicI32, AtomicI64, AtomicUsize, Ordering}, + mpsc::{Receiver, RecvTimeoutError, Sender, channel}, + }, + time::{Duration, Instant}, +}; + +/// ServerCommonPacketListenerImpl.KEEPALIVE_TIME and the disconnect timeout. +const KEEP_ALIVE_EVERY: Duration = Duration::from_secs(15); +const KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(30); +/// Packets queued for one client beyond this many bytes disconnect it. +const MAX_PENDING: usize = 96 << 20; +/// Connection.setupCompression threshold of the integrated server. +const COMPRESSION_THRESHOLD: i32 = 256; + +/// Vanilla's server-side disconnect during login is a JSON component. +fn login_disconnect(c: &mut Connection, key: &str) { + let json = format!("{{\"translate\":\"{key}\"}}"); + let _ = + c.send(&login::Clientbound::Disconnect(login::Disconnect { reason_json: json }).encode()); +} + +/// StringUtil.isValidPlayerName. +pub fn valid_name(name: &str) -> bool { + (1..=16).contains(&name.len()) && name.chars().all(|c| c as u32 > 32 && (c as u32) < 127) +} + +/// The sending half given to the game thread. +#[derive(Clone)] +pub struct PlayerSender { + pub tx: Sender, + pub pending: Arc, +} +impl PlayerSender { + pub fn send(&self, body: Vec) { + self.pending.fetch_add(body.len(), Ordering::Relaxed); + let _ = self.tx.send(Out::Packet(body)); + } +} + +pub fn serve(stream: TcpStream, shared: Arc) -> Result<(), String> { + let e = |e: horizon_protocol::Error| e.to_string(); + let mut c = Connection::from_stream(stream).map_err(e)?; + c.reader + .set_read_timeout(Some(Duration::from_secs(30))) + .map_err(e)?; + let (id, payload) = c.recv().map_err(e)?; + let intention = match handshake::Serverbound::decode(id, &payload).map_err(e)? { + handshake::Serverbound::Intention(i) => i, + _ => return Err("expected a handshake".into()), + }; + match intention.intent { + handshake::STATUS => serve_status(&mut c, &shared), + handshake::LOGIN | handshake::TRANSFER => { + if intention.protocol != PROTOCOL_VERSION { + let key = if intention.protocol < PROTOCOL_VERSION { + "multiplayer.disconnect.outdated_client" + } else { + "multiplayer.disconnect.incompatible" + }; + let json = format!( + "{{\"translate\":\"{key}\",\"with\":[\"{}\"]}}", + horizon_protocol::GAME_VERSION + ); + let _ = c.send( + &login::Clientbound::Disconnect(login::Disconnect { reason_json: json }) + .encode(), + ); + return Ok(()); + } + serve_login(c, &shared) + } + other => Err(format!("unknown intent {other}")), + } +} + +fn serve_status(c: &mut Connection, shared: &Shared) -> Result<(), String> { + let e = |e: horizon_protocol::Error| e.to_string(); + loop { + let (id, payload) = c.recv().map_err(e)?; + match status::Serverbound::decode(id, &payload).map_err(e)? { + status::Serverbound::StatusRequest(_) => { + let json = shared.status_json(); + c.send( + &status::Clientbound::StatusResponse(status::StatusResponse { json }).encode(), + ) + .map_err(e)?; + } + status::Serverbound::PingRequest(p) => { + c.send(&status::Clientbound::PongResponse(p).encode()) + .map_err(e)?; + return Ok(()); + } + status::Serverbound::Unknown(..) => return Ok(()), + } + } +} + +fn serve_login(mut c: Connection, shared: &Arc) -> Result<(), String> { + let e = |e: horizon_protocol::Error| e.to_string(); + let (id, payload) = c.recv().map_err(e)?; + let hello = match login::Serverbound::decode(id, &payload).map_err(e)? { + login::Serverbound::Hello(h) => h, + _ => return Err("expected a login hello".into()), + }; + if !valid_name(&hello.name) { + login_disconnect(&mut c, "multiplayer.disconnect.invalid_name"); + return Ok(()); + } + // Offline mode: the profile is derived from the name (PlayerList.canPlayerLogin + // then rejects duplicates and a full server). + let uuid = offline_uuid(&hello.name); + if let Some(reason) = shared.try_admit(uuid, &hello.name) { + login_disconnect(&mut c, reason); + return Ok(()); + } + let result = login_and_configure(&mut c, shared, uuid, &hello.name); + match result { + Ok(Some(parts)) => { + play(c, shared, parts); + Ok(()) + } + Ok(None) => { + shared.release(uuid); + Ok(()) + } + Err(err) => { + shared.release(uuid); + Err(err) + } + } +} + +struct Parts { + uuid: u128, + name: String, + info: ClientInformation, + brand: String, +} + +fn login_and_configure( + c: &mut Connection, + shared: &Arc, + uuid: u128, + name: &str, +) -> Result, String> { + let e = |e: horizon_protocol::Error| e.to_string(); + c.send( + &login::Clientbound::Compression(login::Compression { + threshold: COMPRESSION_THRESHOLD, + }) + .encode(), + ) + .map_err(e)?; + c.set_compression(COMPRESSION_THRESHOLD); + c.send( + &login::Clientbound::LoginFinished(login::LoginFinished { + profile: login::GameProfile { + uuid, + name: name.to_owned(), + properties: Vec::new(), + }, + session: uuid, + }) + .encode(), + ) + .map_err(e)?; + // The client may send its settings before acknowledging the login. + loop { + let (id, payload) = c.recv().map_err(e)?; + match login::Serverbound::decode(id, &payload).map_err(e)? { + login::Serverbound::LoginAcknowledged(_) => break, + login::Serverbound::CustomQueryAnswer(_) | login::Serverbound::CookieResponse(_) => {} + _ => return Err("unexpected packet during login".into()), + } + } + // Configuration. + let sync: &SyncData = &shared.sync; + let send = |c: &mut Connection, p: cfg::Clientbound| c.send(&p.encode()).map_err(e); + send( + c, + cfg::Clientbound::CustomPayload(cfg::CustomPayload { + channel: "minecraft:brand".into(), + data: { + let mut w = horizon_protocol::buf::Writer::new(); + w.string("horizon"); + w.data + }, + }), + )?; + send( + c, + cfg::Clientbound::UpdateEnabledFeatures(cfg::UpdateEnabledFeatures { + features: sync.features.clone(), + }), + )?; + let core = KnownPack { + namespace: CORE_PACK.0.into(), + id: CORE_PACK.1.into(), + version: CORE_PACK.2.into(), + }; + send( + c, + cfg::Clientbound::SelectKnownPacks(cfg::SelectKnownPacks { + packs: vec![core.clone()], + }), + )?; + let mut info = ClientInformation::new(10); + let mut brand = String::from("vanilla"); + let known_pack = loop { + let (id, payload) = c.recv().map_err(e)?; + match cfg::Serverbound::decode(id, &payload).map_err(e)? { + cfg::Serverbound::ClientInformation(i) => info = i, + cfg::Serverbound::CustomPayload(p) if p.channel == "minecraft:brand" => { + brand = horizon_protocol::buf::Reader::new(&p.data) + .string(32767) + .unwrap_or(brand); + } + cfg::Serverbound::SelectKnownPacks(p) => break p.packs == vec![core.clone()], + _ => {} + } + }; + for packet in sync.registry_packets(known_pack) { + send(c, cfg::Clientbound::RegistryData(packet))?; + } + send(c, cfg::Clientbound::UpdateTags(sync.tags.clone()))?; + send(c, cfg::Clientbound::FinishConfiguration(Empty))?; + loop { + let (id, payload) = c.recv().map_err(e)?; + match cfg::Serverbound::decode(id, &payload).map_err(e)? { + cfg::Serverbound::FinishConfiguration(_) => break, + cfg::Serverbound::ClientInformation(i) => info = i, + _ => {} + } + } + Ok(Some(Parts { + uuid, + name: name.to_owned(), + info, + brand, + })) +} + +fn play(c: Connection, shared: &Arc, parts: Parts) { + let conn_id = shared.next_id(); + let events = shared.events.clone(); + let _ = c.reader.set_read_timeout(Some(KEEP_ALIVE_TIMEOUT)); + let (mut reader, writer) = c.split(); + let (tx, rx) = channel(); + let pending = Arc::new(AtomicUsize::new(0)); + let latency = Arc::new(AtomicI32::new(0)); + let alive = Arc::new(AtomicI64::new(-1)); + let sender = PlayerSender { + tx: tx.clone(), + pending: pending.clone(), + }; + let writer_thread = { + let (alive, latency, pending) = (alive.clone(), latency.clone(), pending.clone()); + std::thread::Builder::new() + .name(format!("horizon-lan-out-{conn_id}")) + .spawn(move || write_loop(writer, rx, alive, latency, pending)) + .ok() + }; + let joined = Joined { + conn: conn_id, + uuid: parts.uuid, + name: parts.name, + info: parts.info, + brand: parts.brand, + sender, + latency, + }; + let reason = if events.send(NetEvent::Joined(Box::new(joined))).is_ok() { + read_loop(&mut reader, conn_id, &events, &alive) + } else { + "server closed".to_owned() + }; + let _ = tx.send(Out::Close); + let _ = events.send(NetEvent::Left(conn_id, reason)); + if let Some(t) = writer_thread { + let _ = t.join(); + } + shared.release(parts.uuid); +} + +fn read_loop( + reader: &mut ConnReader, + conn: u32, + events: &Sender, + alive: &AtomicI64, +) -> String { + loop { + let (id, payload) = match reader.recv() { + Ok(p) => p, + Err(e) => return e.to_string(), + }; + match play::Serverbound::decode(id, &payload) { + Ok(play::Serverbound::KeepAlive(k)) => alive.store(k.id, Ordering::Relaxed), + Ok(p) => { + if events.send(NetEvent::Packet(conn, Box::new(p))).is_err() { + return "server closed".to_owned(); + } + } + // A malformed packet disconnects like vanilla's decoder exception. + Err(e) => return format!("Invalid packet {id}: {e}"), + } + } +} + +fn write_loop( + mut writer: ConnWriter, + rx: Receiver, + alive: Arc, + latency: Arc, + pending: Arc, +) { + let start = Instant::now(); + let mut sent_at: Option<(i64, Instant)> = None; + let mut next = Instant::now() + KEEP_ALIVE_EVERY; + loop { + match rx.recv_timeout(Duration::from_millis(200)) { + Ok(Out::Packet(body)) => { + pending.fetch_sub(body.len(), Ordering::Relaxed); + if writer.send(&body).is_err() { + break; + } + if pending.load(Ordering::Relaxed) > MAX_PENDING { + break; + } + } + Ok(Out::Disconnect(reason)) => { + let _ = writer + .send(&play::Clientbound::Disconnect(cfg::Disconnect { reason }).encode()); + std::thread::sleep(Duration::from_millis(50)); + break; + } + Ok(Out::Close) | Err(RecvTimeoutError::Disconnected) => break, + Err(RecvTimeoutError::Timeout) => {} + } + let now = Instant::now(); + if let Some((id, at)) = sent_at { + if alive.load(Ordering::Relaxed) == id { + let ms = i32::try_from(at.elapsed().as_millis()).unwrap_or(i32::MAX); + let old = latency.load(Ordering::Relaxed); + latency.store((old * 3 + ms) / 4, Ordering::Relaxed); + sent_at = None; + } else if at.elapsed() > KEEP_ALIVE_TIMEOUT { + let _ = writer.send( + &play::Clientbound::Disconnect(cfg::Disconnect { + reason: translatable("disconnect.timeout", &[]), + }) + .encode(), + ); + break; + } + } + if sent_at.is_none() && now >= next { + let id = i64::try_from(start.elapsed().as_millis()).unwrap_or(0); + if writer + .send(&play::Clientbound::KeepAlive(cfg::KeepAlive { id }).encode()) + .is_err() + { + break; + } + sent_at = Some((id, now)); + next = now + KEEP_ALIVE_EVERY; + } + } + writer.shutdown(); +} diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs new file mode 100644 index 000000000..5fcbf09cd --- /dev/null +++ b/crates/horizon-client/src/lan/containers.rs @@ -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) { + 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, + ) { + 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) { + 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) { + 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>, + ) { + 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>) { + 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, mine: &Option) -> 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 { + 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 { + 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> = 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 = 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 } +} diff --git a/crates/horizon-client/src/lan/data.rs b/crates/horizon-client/src/lan/data.rs new file mode 100644 index 000000000..8101d107c --- /dev/null +++ b/crates/horizon-client/src/lan/data.rs @@ -0,0 +1,282 @@ +//! What the configuration phase sends: the synchronized registries (names in +//! network order, with their data for clients that do not know the vanilla +//! pack) and the tags of every registry, loaded from the prepared resources +//! (`data/minecraft/...`) and the registries report. +use horizon_protocol::{ + packets::configuration::{RegistryData, RegistryEntry, RegistryTags, TagEntry, UpdateTags}, + registry::{Builtin, Dynamic}, +}; +use horizon_world::nbt::{JavaString, Tag}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + path::{Path, PathBuf}, +}; + +/// RegistryDataLoader.SYNCHRONIZED_REGISTRIES, in vanilla's order. +pub const SYNCHRONIZED: &[&str] = &[ + "minecraft:worldgen/biome", + "minecraft:chat_type", + "minecraft:trim_pattern", + "minecraft:trim_material", + "minecraft:wolf_variant", + "minecraft:wolf_sound_variant", + "minecraft:pig_variant", + "minecraft:pig_sound_variant", + "minecraft:frog_variant", + "minecraft:cat_variant", + "minecraft:cat_sound_variant", + "minecraft:cow_sound_variant", + "minecraft:cow_variant", + "minecraft:chicken_sound_variant", + "minecraft:chicken_variant", + "minecraft:zombie_nautilus_variant", + "minecraft:painting_variant", + "minecraft:sulfur_cube_archetype", + "minecraft:dimension_type", + "minecraft:damage_type", + "minecraft:banner_pattern", + "minecraft:enchantment", + "minecraft:jukebox_song", + "minecraft:instrument", + "minecraft:test_environment", + "minecraft:test_instance", + "minecraft:dialog", + "minecraft:world_clock", + "minecraft:timeline", + "minecraft:decorated_pot_pattern", + "minecraft:block_transformer", + "minecraft:worldgen/block_state_provider", +]; +/// KnownPack.vanilla("core") for this version. +pub const CORE_PACK: (&str, &str, &str) = ("minecraft", "core", horizon_protocol::GAME_VERSION); + +/// A data-driven registry: entry names in network order and their JSON. +struct Entries { + names: Vec, + json: Vec, +} + +pub struct SyncData { + pub builtin: Builtin, + /// Entry names per synchronized registry (for id lookups). + pub dynamic: Dynamic, + registries: Vec<(String, Entries)>, + pub tags: UpdateTags, + pub features: Vec, +} + +/// Every `*.json` under `dir`, as (path without extension relative to dir, value), sorted. +fn walk(dir: &Path, prefix: &str, out: &mut BTreeMap) { + let Ok(read) = std::fs::read_dir(dir) else { + return; + }; + for entry in read.flatten() { + let path = entry.path(); + let name = entry.file_name().to_string_lossy().into_owned(); + if path.is_dir() { + walk(&path, &format!("{prefix}{name}/"), out); + } else if let Some(stem) = name.strip_suffix(".json") + && let Ok(text) = std::fs::read_to_string(&path) + && let Ok(value) = serde_json::from_str::(&text) + { + out.insert(format!("{prefix}{stem}"), value); + } + } +} + +/// A JSON value as the NBT that vanilla's NbtOps would produce from the codec +/// (integers are ints, other numbers doubles, booleans bytes). +pub fn json_to_nbt(v: &Value) -> Tag { + match v { + Value::Null => Tag::compound(Vec::<(&str, Tag)>::new()), + Value::Bool(b) => Tag::Byte(i8::from(*b)), + Value::Number(n) => match n.as_i64() { + Some(i) => match i32::try_from(i) { + Ok(i) => Tag::Int(i), + Err(_) => Tag::Long(i), + }, + None => Tag::Double(n.as_f64().unwrap_or(0.0).to_bits()), + }, + Value::String(s) => Tag::String(JavaString::from(s.as_str())), + Value::Array(a) => Tag::List(a.iter().map(json_to_nbt).collect()), + Value::Object(o) => Tag::compound(o.iter().map(|(k, v)| (k.as_str(), json_to_nbt(v)))), + } +} + +impl SyncData { + pub fn load(resources: &Path) -> Result { + let builtin = Builtin::find(resources) + .and_then(|p| Builtin::load(&p).ok()) + .ok_or("registries.json not found next to the resources")?; + let root: PathBuf = resources.join("data/minecraft"); + let mut registries = Vec::new(); + let mut dynamic = Dynamic::default(); + for key in SYNCHRONIZED { + let path = key.trim_start_matches("minecraft:"); + let mut found = BTreeMap::new(); + walk(&root.join(path), "", &mut found); + let (names, json): (Vec<_>, Vec<_>) = found + .into_iter() + .map(|(n, v)| (format!("minecraft:{n}"), v)) + .unzip(); + dynamic.registries.insert( + (*key).to_owned(), + names.iter().map(|n| (n.clone(), None)).collect(), + ); + registries.push(((*key).to_owned(), Entries { names, json })); + } + let tags = Self::load_tags(&root, &builtin, &dynamic); + Ok(Self { + builtin, + dynamic, + registries, + tags, + features: vec!["minecraft:vanilla".to_owned()], + }) + } + + /// The id of a name in a built-in or synchronized registry. + pub fn id(&self, registry: &str, name: &str) -> Option { + if let Some(ids) = self.builtin.get(registry) { + return ids.id(name); + } + self.dynamic + .registries + .get(registry)? + .iter() + .position(|(n, _)| n == name) + .map(|i| i as i32) + } + + /// ClientboundRegistryDataPacket per registry. With `known_pack` the + /// client rebuilds the entries from its own data, so none is sent. + pub fn registry_packets(&self, known_pack: bool) -> Vec { + self.registries + .iter() + .map(|(key, e)| RegistryData { + registry: key.clone(), + entries: e + .names + .iter() + .zip(&e.json) + .map(|(name, json)| RegistryEntry { + id: name.clone(), + data: if known_pack { + None + } else { + Some(json_to_nbt(json)) + }, + }) + .collect(), + }) + .collect() + } + + fn registry_names<'a>( + builtin: &'a Builtin, + dynamic: &'a Dynamic, + key: &str, + ) -> Option> { + if let Some(ids) = builtin.get(key) { + return Some( + ids.names + .iter() + .enumerate() + .map(|(i, n)| (n.as_str(), i as i32)) + .collect(), + ); + } + dynamic.registries.get(key).map(|v| { + v.iter() + .enumerate() + .map(|(i, (n, _))| (n.as_str(), i as i32)) + .collect() + }) + } + + /// TagNetworkSerialization.serializeTagsToNetwork from the tag files. + fn load_tags(root: &Path, builtin: &Builtin, dynamic: &Dynamic) -> UpdateTags { + let tag_root = root.join("tags"); + let mut registries = Vec::new(); + let mut keys: Vec = builtin + .registries + .keys() + .chain(dynamic.registries.keys()) + .cloned() + .collect(); + keys.sort(); + for key in keys { + let dir = tag_root.join(key.trim_start_matches("minecraft:")); + if !dir.is_dir() { + continue; + } + let mut files = BTreeMap::new(); + walk(&dir, "", &mut files); + if files.is_empty() { + continue; + } + let Some(names) = Self::registry_names(builtin, dynamic, &key) else { + continue; + }; + let mut tags = Vec::new(); + for name in files.keys() { + let mut ids = Vec::new(); + let mut seen = HashSet::new(); + Self::expand(&files, name, &names, &mut ids, &mut seen); + tags.push(TagEntry { + name: format!("minecraft:{name}"), + ids, + }); + } + registries.push(RegistryTags { + registry: key, + tags, + }); + } + UpdateTags { registries } + } + + fn expand( + files: &BTreeMap, + tag: &str, + names: &HashMap<&str, i32>, + out: &mut Vec, + seen: &mut HashSet, + ) { + if !seen.insert(tag.to_owned()) { + return; + } + let Some(values) = files.get(tag).and_then(|v| v["values"].as_array()) else { + return; + }; + for value in values { + let id = value + .as_str() + .or_else(|| value["id"].as_str()) + .unwrap_or_default(); + if let Some(reference) = id.strip_prefix('#') { + let reference = reference.trim_start_matches("minecraft:"); + Self::expand(files, reference, names, out, seen); + } else if let Some(&n) = names.get(id) + && !out.contains(&n) + { + out.push(n); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn json_becomes_nbt() { + let v: Value = serde_json::from_str(r#"{"a":1,"b":[true,2.5],"c":"x"}"#).unwrap(); + let t = json_to_nbt(&v); + assert!(matches!(t.get("a"), Some(Tag::Int(1)))); + assert!(matches!(t.get("c"), Some(Tag::String(_)))); + assert!(matches!(t.get("b"), Some(Tag::List(l)) if l.len() == 2)); + } +} diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs new file mode 100644 index 000000000..6ba8c1924 --- /dev/null +++ b/crates/horizon-client/src/lan/entity.rs @@ -0,0 +1,314 @@ +//! Entity tracking (ServerEntity / TrackedEntity): the game describes every +//! entity it simulates as an `EntityState` each tick; a `Tracker` remembers +//! what one client has been told and produces the spawn, movement, metadata, +//! equipment and removal packets that bring it up to date. +use horizon_protocol::{ + buf::pack_degrees, + entity_data::Value, + item::Stack, + packets::play::{ + self, AddEntity, MoveEntity, MoveEntityPos, MoveEntityPosRot, MoveEntityRot, RotateHead, + SetEntityData, SetEntityMotion, SetEquipment, TeleportEntity, VecDelta, + }, +}; + +/// What the game says about one entity this tick. +#[derive(Clone, Debug)] +pub struct EntityState { + pub id: i32, + pub uuid: u128, + /// Registry id of the entity type (`minecraft:zombie`). + pub kind: String, + pub position: [f64; 3], + pub yaw: f32, + pub pitch: f32, + pub head_yaw: f32, + pub on_ground: bool, + pub velocity: [f64; 3], + /// ClientboundAddEntityPacket.data (item frame direction, block state ...). + pub data: i32, + /// SynchedEntityData entries that differ from the defaults. + pub meta: Vec<(u8, i32, Value)>, + /// EquipmentSlot ordinals (0 main hand, 1 off hand, 2 feet, 3 legs, + /// 4 chest, 5 head) and their stacks. + pub equipment: Vec<(u8, Option)>, + /// Whether movement packets should include a velocity (items, projectiles). + pub send_velocity: bool, +} + +/// What a client was last told about one entity. +struct Sent { + /// The position in 1/4096 blocks (VecDeltaCodec base). + base: [i64; 3], + position: [f64; 3], + rotation: (i8, i8), + head: i8, + velocity: [f64; 3], + meta: Vec<(u8, i32, Value)>, + equipment: Vec<(u8, Option)>, + on_ground: bool, + ticks: u32, +} + +#[derive(Default)] +pub struct Tracker { + sent: std::collections::HashMap, +} + +fn quantize(p: [f64; 3]) -> [i64; 3] { + [ + (p[0] * 4096.0).round() as i64, + (p[1] * 4096.0).round() as i64, + (p[2] * 4096.0).round() as i64, + ] +} +fn dequantize(q: [i64; 3]) -> [f64; 3] { + [ + q[0] as f64 / 4096.0, + q[1] as f64 / 4096.0, + q[2] as f64 / 4096.0, + ] +} + +impl Tracker { + pub fn is_tracking(&self, id: i32) -> bool { + self.sent.contains_key(&id) + } + pub fn ids(&self) -> Vec { + self.sent.keys().copied().collect() + } + pub fn forget(&mut self, id: i32) { + self.sent.remove(&id); + } + pub fn clear(&mut self) { + self.sent.clear(); + } + pub fn len(&self) -> usize { + self.sent.len() + } + pub fn is_empty(&self) -> bool { + self.sent.is_empty() + } + + /// The packets that introduce an entity (ServerEntity.sendPairingData). + pub fn spawn(&mut self, e: &EntityState, entity_type: i32) -> Vec { + let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw)); + let head = pack_degrees(e.head_yaw); + let mut out = vec![play::Clientbound::AddEntity(AddEntity { + id: e.id, + uuid: e.uuid, + kind: entity_type, + position: e.position, + velocity: e.velocity, + pitch: rotation.0, + yaw: rotation.1, + head_yaw: head, + data: e.data, + })]; + if !e.meta.is_empty() { + out.push(play::Clientbound::SetEntityData(SetEntityData { + id: e.id, + values: e.meta.clone(), + })); + } + if !e.equipment.is_empty() { + out.push(play::Clientbound::SetEquipment(SetEquipment { + id: e.id, + slots: e.equipment.clone(), + })); + } + self.sent.insert( + e.id, + Sent { + base: quantize(e.position), + position: e.position, + rotation, + head, + velocity: e.velocity, + meta: e.meta.clone(), + equipment: e.equipment.clone(), + on_ground: e.on_ground, + ticks: 0, + }, + ); + out + } + + /// Changes since the last update (ServerEntity.sendChanges). + pub fn update(&mut self, e: &EntityState) -> Vec { + let Some(s) = self.sent.get_mut(&e.id) else { + return Vec::new(); + }; + let mut out = Vec::new(); + s.ticks += 1; + let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw)); + let rotated = rotation != s.rotation; + let now = quantize(e.position); + let delta = [now[0] - s.base[0], now[1] - s.base[1], now[2] - s.base[2]]; + let moved = delta != [0; 3]; + let fits = delta.iter().all(|d| i16::try_from(*d).is_ok()); + if moved && !fits { + out.push(play::Clientbound::TeleportEntity(TeleportEntity { + id: e.id, + position: e.position, + delta: e.velocity, + yaw: e.yaw, + pitch: e.pitch, + relatives: 0, + on_ground: e.on_ground, + })); + s.base = now; + } else if moved || rotated || e.on_ground != s.on_ground { + let d = VecDelta::Linear([delta[0] as i16, delta[1] as i16, delta[2] as i16]); + let rot = Some((rotation.1, rotation.0)); + let packet = if moved && rotated { + play::Clientbound::MoveEntityPosRot(MoveEntityPosRot(MoveEntity { + id: e.id, + delta: Some(d), + rotation: rot, + on_ground: e.on_ground, + })) + } else if moved { + play::Clientbound::MoveEntityPos(MoveEntityPos(MoveEntity { + id: e.id, + delta: Some(d), + rotation: None, + on_ground: e.on_ground, + })) + } else { + play::Clientbound::MoveEntityRot(MoveEntityRot(MoveEntity { + id: e.id, + delta: None, + rotation: rot, + on_ground: e.on_ground, + })) + }; + out.push(packet); + if moved { + s.base = now; + } + } + if moved || rotated || e.on_ground != s.on_ground { + s.rotation = rotation; + s.on_ground = e.on_ground; + } + s.position = dequantize(s.base); + let head = pack_degrees(e.head_yaw); + if head != s.head { + out.push(play::Clientbound::RotateHead(RotateHead { + id: e.id, + head_yaw: head, + })); + s.head = head; + } + if e.send_velocity { + let dv: f64 = (0..3) + .map(|i| (e.velocity[i] - s.velocity[i]).powi(2)) + .sum(); + if dv > 1.0e-7 || (e.velocity == [0.0; 3] && s.velocity != [0.0; 3]) { + out.push(play::Clientbound::SetEntityMotion(SetEntityMotion { + id: e.id, + velocity: e.velocity, + })); + s.velocity = e.velocity; + } + } + if e.meta != s.meta { + let changed: Vec<_> = e + .meta + .iter() + .filter(|m| !s.meta.contains(m)) + .cloned() + .collect(); + if !changed.is_empty() { + out.push(play::Clientbound::SetEntityData(SetEntityData { + id: e.id, + values: changed, + })); + } + s.meta = e.meta.clone(); + } + if e.equipment != s.equipment { + // Cleared slots are sent as empty stacks. + let mut slots: Vec<(u8, Option)> = e + .equipment + .iter() + .filter(|m| !s.equipment.contains(m)) + .cloned() + .collect(); + for (slot, _) in &s.equipment { + if !e.equipment.iter().any(|(k, _)| k == slot) { + slots.push((*slot, None)); + } + } + if !slots.is_empty() { + out.push(play::Clientbound::SetEquipment(SetEquipment { + id: e.id, + slots, + })); + } + s.equipment = e.equipment.clone(); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn state(x: f64) -> EntityState { + EntityState { + id: 7, + uuid: 1, + kind: "minecraft:zombie".into(), + position: [x, 64.0, 0.0], + yaw: 0.0, + pitch: 0.0, + head_yaw: 0.0, + on_ground: true, + velocity: [0.0; 3], + data: 0, + meta: Vec::new(), + equipment: Vec::new(), + send_velocity: false, + } + } + + #[test] + fn small_moves_are_relative_and_large_ones_teleport() { + let mut t = Tracker::default(); + let spawn = t.spawn(&state(0.0), 100); + assert!(matches!(spawn[0], play::Clientbound::AddEntity(_))); + assert!(t.update(&state(0.0)).is_empty()); + let step = t.update(&state(0.5)); + assert!(matches!(step[0], play::Clientbound::MoveEntityPos(_))); + let jump = t.update(&state(40.0)); + assert!(matches!(jump[0], play::Clientbound::TeleportEntity(_))); + } + + #[test] + fn metadata_and_equipment_send_only_the_changes() { + let mut t = Tracker::default(); + let mut e = state(0.0); + t.spawn(&e, 100); + e.meta.push((0, 0, Value::Byte(1))); + e.equipment.push((0, Some(Stack::new(5, 1)))); + let out = t.update(&e); + assert!( + out.iter() + .any(|p| matches!(p, play::Clientbound::SetEntityData(_))) + ); + assert!( + out.iter() + .any(|p| matches!(p, play::Clientbound::SetEquipment(_))) + ); + assert!(t.update(&e).is_empty()); + e.equipment.clear(); + let out = t.update(&e); + let Some(play::Clientbound::SetEquipment(eq)) = out.first() else { + panic!("expected equipment"); + }; + assert_eq!(eq.slots, vec![(0, None)]); + } +} diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs new file mode 100644 index 000000000..88e2806d1 --- /dev/null +++ b/crates/horizon-client/src/lan/guest.rs @@ -0,0 +1,252 @@ +//! A remote player: connection, position, chunk and entity views, and the +//! player state (inventory, health, game mode) that the host's gameplay code +//! operates on when it acts for them. +use super::{Joined, PlayerSender, entity::Tracker}; +use crate::{items::ItemStack, motion::PlayerMotion}; +use horizon_protocol::{ + item::Stack, + packets::{configuration::ClientInformation, play}, +}; +use std::{ + collections::{HashSet, VecDeque}, + sync::{Arc, atomic::AtomicI32}, +}; + +/// GameType ids. +pub const SURVIVAL: i32 = 0; +pub const CREATIVE: i32 = 1; +pub const ADVENTURE: i32 = 2; +pub const SPECTATOR: i32 = 3; + +pub struct Guest { + pub conn: u32, + pub uuid: u128, + pub name: String, + pub entity_id: i32, + pub sender: PlayerSender, + pub latency: Arc, + pub info: ClientInformation, + pub brand: String, + /// The chunk radius this client is sent. + pub view_distance: i32, + pub position: [f64; 3], + pub previous_position: [f64; 3], + pub yaw: f32, + pub pitch: f32, + pub head_yaw: f32, + pub on_ground: bool, + pub game_mode: i32, + pub sneaking: bool, + pub sprinting: bool, + pub fall_flying: bool, + pub flying: bool, + pub sleeping: bool, + /// Pending ClientboundPlayerPositionPacket id; movement is ignored until + /// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient). + pub awaiting_teleport: Option<(i32, [f64; 3])>, + pub teleport_counter: i32, + /// The client finished loading terrain (ServerboundPlayerLoadedPacket). + pub loaded: bool, + // Chunks. + pub center: Option<(i32, i32)>, + pub sent_chunks: HashSet<(i32, i32)>, + pub chunk_queue: Vec<(i32, i32)>, + pub unacknowledged: u32, + pub chunks_per_tick: f32, + pub chunk_credit: f32, + // Entities. + pub tracker: Tracker, + // Player state the gameplay code reads and writes. + pub motion: Option>, + /// The 36 inventory slots (hotbar first), armor (head..feet) and off hand. + pub inventory: Vec>, + pub armor: [Option; 4], + pub offhand: Option, + pub selected: usize, + pub carried: Option, + pub health: f32, + pub food: i32, + pub saturation: f32, + pub xp_level: i32, + pub xp_progress: f32, + pub xp_total: i32, + /// What the client believes the inventory menu holds (for change detection). + pub menu_sent: Vec>, + pub menu_state: i32, + pub sent_health: Option<(f32, i32, f32)>, + pub sent_xp: Option<(f32, i32, i32)>, + pub sent_selected: usize, + pub inbox: VecDeque, + pub joined_tick: u64, + pub ticks: u64, + pub dead: bool, + /// The join packets were sent (PlayerList.placeNewPlayer ran). + pub placed: bool, + /// The open block container, if any. + pub menu: Option, + pub next_window: i32, + /// An unfinished drag in the inventory menu. + pub drag: Option<(u8, Vec)>, + /// The compound this player was loaded from, for fields Horizon does not model. + pub saved: Option, +} + +impl Guest { + pub fn new(j: Joined, entity_id: i32, position: [f64; 3], view_distance: i32) -> Self { + Self { + conn: j.conn, + uuid: j.uuid, + name: j.name, + entity_id, + sender: j.sender, + latency: j.latency, + view_distance: (i32::from(j.info.view_distance)).clamp(2, view_distance), + info: j.info, + brand: j.brand, + position, + previous_position: position, + yaw: 0.0, + pitch: 0.0, + head_yaw: 0.0, + on_ground: false, + game_mode: SURVIVAL, + sneaking: false, + sprinting: false, + fall_flying: false, + flying: false, + sleeping: false, + awaiting_teleport: None, + teleport_counter: 0, + loaded: false, + center: None, + sent_chunks: HashSet::new(), + chunk_queue: Vec::new(), + unacknowledged: 0, + chunks_per_tick: 9.0, + chunk_credit: 0.0, + tracker: Tracker::default(), + motion: None, + inventory: vec![None; 36], + armor: [None, None, None, None], + offhand: None, + selected: 0, + carried: None, + health: 20.0, + food: 20, + saturation: 5.0, + xp_level: 0, + xp_progress: 0.0, + xp_total: 0, + menu_sent: vec![None; 46], + menu_state: 0, + sent_health: None, + sent_xp: None, + sent_selected: 0, + inbox: VecDeque::new(), + joined_tick: 0, + ticks: 0, + dead: false, + placed: false, + menu: None, + next_window: 0, + drag: None, + saved: None, + } + } + pub fn send(&self, packet: &play::Clientbound) { + self.sender.send(packet.encode()); + } + pub fn send_all(&self, packets: &[play::Clientbound]) { + for p in packets { + self.send(p); + } + } + pub fn chunk(&self) -> (i32, i32) { + ( + (self.position[0].floor() as i32) >> 4, + (self.position[2].floor() as i32) >> 4, + ) + } + pub fn creative(&self) -> bool { + self.game_mode == CREATIVE + } + pub fn spectator(&self) -> bool { + self.game_mode == SPECTATOR + } + /// PlayerAbilities flags (invulnerable, flying, may fly, instabuild). + pub fn ability_flags(&self) -> i8 { + let mut f = 0; + if self.creative() || self.spectator() { + f |= 1; + } + if self.flying || self.spectator() { + f |= 2; + } + if self.creative() || self.spectator() { + f |= 4; + } + if self.creative() { + f |= 8; + } + f + } + pub fn eye_height(&self) -> f64 { + if self.sneaking { 1.27 } else { 1.62 } + } + /// The inventory menu's 46 slots (ServerPlayer.inventoryMenu): 0 crafting + /// result, 1..=4 crafting grid, 5..=8 armor, 9..=35 main, 36..=44 hotbar, + /// 45 off hand. + pub fn menu_slot(&self, slot: usize) -> Option { + match slot { + 0..=4 => None, + 5..=8 => self.armor[slot - 5].clone(), + 9..=35 => self.inventory.get(slot).cloned().flatten(), + 36..=44 => self.inventory.get(slot - 36).cloned().flatten(), + 45 => self.offhand.clone(), + _ => None, + } + } + pub fn set_menu_slot(&mut self, slot: usize, item: Option) { + match slot { + 5..=8 => self.armor[slot - 5] = item, + 9..=35 => self.inventory[slot] = item, + 36..=44 => self.inventory[slot - 36] = item, + 45 => self.offhand = item, + _ => {} + } + } +} + +/// The off hand slot is conventionally 40 in saves and 45 in the menu. +pub fn stack_to_network( + item_id: impl Fn(&str) -> i32, + enchantment_id: impl Fn(&str) -> Option, + s: &Option, +) -> Option { + let s = s.as_ref()?; + let mut stack = Stack::new(item_id(&s.item), s.count as i32); + if s.damage > 0 { + stack.added.push(( + horizon_protocol::item::component::DAMAGE, + horizon_protocol::item::Component::Int(s.damage as i32), + )); + } + let enchantments: Vec<(i32, i32)> = s + .enchantments() + .iter() + .filter_map(|(e, level)| Some((enchantment_id(e)?, *level as i32))) + .collect(); + if !enchantments.is_empty() { + stack.added.push(( + horizon_protocol::item::component::ENCHANTMENTS, + horizon_protocol::item::Component::Enchantments(enchantments), + )); + } + if let Some(name) = s.custom_name() { + stack.added.push(( + horizon_protocol::item::component::CUSTOM_NAME, + horizon_protocol::item::Component::Text(horizon_protocol::text::literal(name)), + )); + } + Some(stack) +} diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs new file mode 100644 index 000000000..7201c6a05 --- /dev/null +++ b/crates/horizon-client/src/lan/hub.rs @@ -0,0 +1,1286 @@ +//! The play state of a hosted world (PlayerList, ServerGamePacketListenerImpl, +//! ChunkMap, PlayerChunkSender): admits the players the connection threads +//! hand over, sends them the level (chunks, time, weather, entities, player +//! list), keeps their views up to date as blocks and entities change, and +//! turns what they send into events for the gameplay code. It runs on the +//! game thread inside the tick, only when the world is open to the network. +use super::{ + Lan, NetEvent, + chunks::ChunkEncoder, + data::SyncData, + entity::EntityState, + guest::{Guest, stack_to_network}, +}; +use crate::{items::ItemStack, world::World}; +use horizon_protocol::{ + entity_data::{Value, serializer}, + packets::play::{self, Clientbound as C, Serverbound as S}, + text::{literal, translatable}, +}; +use horizon_world::nbt::{JavaString, Tag}; +use std::sync::{Arc, atomic::Ordering}; + +/// GameEvent types (ClientboundGameEventPacket). +pub mod game_event { + pub const START_RAINING: u8 = 1; + pub const STOP_RAINING: u8 = 2; + pub const CHANGE_GAME_MODE: u8 = 3; + pub const RAIN_LEVEL: u8 = 7; + pub const THUNDER_LEVEL: u8 = 8; + pub const LEVEL_CHUNKS_LOAD_START: u8 = 13; +} + +#[derive(Clone, Debug)] +pub struct HubConfig { + pub default_game_mode: i32, + pub guest_commands: bool, + pub force_game_mode: bool, + pub hardcore: bool, + pub view_distance: i32, + pub simulation_distance: i32, + pub dimension: String, + pub seed: i64, + pub max_players: usize, +} + +/// The host player as the other players see them. +#[derive(Clone, Debug)] +pub struct HostState { + pub uuid: u128, + pub name: String, + pub entity_id: i32, + pub position: [f64; 3], + pub yaw: f32, + pub pitch: f32, + pub head_yaw: f32, + pub on_ground: bool, + pub game_mode: i32, + pub sneaking: bool, + pub sprinting: bool, + pub equipment: [Option; 6], + pub health: f32, +} + +/// Everything the hub needs from the game for one tick. +pub struct TickCtx<'a> { + pub world: &'a mut World, + pub host: &'a HostState, + pub entities: &'a [EntityState], + pub next_entity: &'a mut u32, + /// Where new players appear. + pub spawn: [f64; 3], + pub difficulty: i32, + pub difficulty_locked: bool, + /// The overworld clock's speed (0 when the day does not advance). + pub clock_rate: f32, +} + +/// What the gameplay code has to do for a guest. +pub enum HostEvent { + /// A guest entered the world; load their saved state. + Joined(u32), + /// A guest left (state to save, entities to drop). + Left(Box), + Packet(u32, Box), + /// A chat line to show on the host (already broadcast to the guests). + Chat(String), +} + +pub struct Hub { + pub lan: Lan, + pub config: HubConfig, + pub encoder: ChunkEncoder, + pub guests: Vec, + pub(super) sync: Arc, + pub ticks: u64, + last_clock: i64, + weather: (bool, f32, f32), + chat_type: i32, + dimension_type: i32, + clock_ids: Vec, + item_ids: std::collections::HashMap, i32>, + entity_types: std::collections::HashMap, +} + +fn string(s: &str) -> Tag { + Tag::String(JavaString::from(s)) +} +pub fn yellow_translation(key: &str, args: &[&str]) -> Tag { + let mut t = translatable(key, args); + if let Tag::Compound(map) = &mut t { + map.insert(JavaString::from("color"), string("yellow")); + } + t +} + +impl Hub { + pub fn new(lan: Lan, sync: Arc, encoder: ChunkEncoder, config: HubConfig) -> Self { + let chat_type = sync + .id("minecraft:chat_type", "minecraft:chat") + .unwrap_or(0); + let dimension_type = sync + .id("minecraft:dimension_type", "minecraft:overworld") + .unwrap_or(0); + let clock_ids = (0..sync.dynamic.len("minecraft:world_clock") as i32).collect(); + Self { + lan, + config, + encoder, + guests: Vec::new(), + sync, + ticks: 0, + last_clock: i64::MIN, + weather: (false, 0.0, 0.0), + chat_type, + dimension_type, + clock_ids, + item_ids: Default::default(), + entity_types: Default::default(), + } + } + + pub fn guest(&self, conn: u32) -> Option<&Guest> { + self.guests.iter().find(|g| g.conn == conn) + } + pub fn guest_mut(&mut self, conn: u32) -> Option<&mut Guest> { + self.guests.iter_mut().find(|g| g.conn == conn) + } + + pub fn item_id(&mut self, item: &Arc) -> i32 { + if let Some(id) = self.item_ids.get(item) { + return *id; + } + let id = self + .sync + .builtin + .get("minecraft:item") + .and_then(|i| i.id(item)) + .unwrap_or(0); + self.item_ids.insert(item.clone(), id); + id + } + pub fn stack(&mut self, s: &Option) -> Option { + let id = s.as_ref().map(|s| self.item_id(&s.item))?; + let sync = self.sync.clone(); + stack_to_network(|_| id, |name| sync.id("minecraft:enchantment", name), s) + } + fn entity_type(&mut self, kind: &str) -> Option { + if let Some(id) = self.entity_types.get(kind) { + return Some(*id); + } + let id = self.sync.builtin.get("minecraft:entity_type")?.id(kind)?; + self.entity_types.insert(kind.to_owned(), id); + Some(id) + } + + pub fn broadcast(&self, packet: &C) { + let body = packet.encode(); + for g in self.guests.iter().filter(|g| g.placed) { + g.sender.send(body.clone()); + } + } + pub fn broadcast_except(&self, conn: u32, packet: &C) { + let body = packet.encode(); + for g in self.guests.iter().filter(|g| g.placed && g.conn != conn) { + g.sender.send(body.clone()); + } + } + /// PlayerList.broadcastSystemMessage. + pub fn system_message(&self, content: Tag) { + self.broadcast(&C::SystemChat(play::SystemChat { + content, + overlay: false, + })); + } + /// A chat message from `sender` (PlayerChatMessage as a disguised chat). + pub fn chat(&self, sender: &str, text: &str) { + self.broadcast(&self.chat_packet(sender, text)); + } + fn chat_packet(&self, sender: &str, text: &str) -> C { + C::DisguisedChat(play::DisguisedChat { + message: literal(text), + chat_type: play::ChatTypeBound { + chat_type: self.chat_type, + name: literal(sender), + target: None, + }, + }) + } + + /// Disconnect a guest with a reason (ServerGamePacketListenerImpl.disconnect). + pub fn kick(&mut self, conn: u32, reason: Tag) { + if let Some(g) = self.guest(conn) { + let _ = g.sender.tx.send(super::Out::Disconnect(reason)); + } + } + + fn player_info(&self, uuid: u128, name: &str, mode: i32, latency: i32) -> play::PlayerInfo { + play::PlayerInfo { + uuid, + name: Some(name.to_owned()), + properties: Vec::new(), + chat_session: None, + game_mode: Some(mode), + listed: Some(true), + latency: Some(latency), + display_name: None, + list_order: Some(0), + show_hat: Some(true), + } + } + /// ClientboundPlayerInfoUpdatePacket.createPlayerInitializing actions. + const INFO_ACTIONS: u8 = 1 | 4 | 8 | 16 | 64 | 128; + + // ---- joining ------------------------------------------------------- + + fn spawn_info(&self, game_mode: i32) -> play::SpawnInfo { + play::SpawnInfo { + dimension_type: self.dimension_type, + dimension: self.config.dimension.clone(), + seed: horizon_core::biome::obfuscate_seed(self.config.seed), + game_type: game_mode, + previous_game_type: None, + debug: false, + flat: false, + last_death: None, + portal_cooldown: 0, + sea_level: 63, + } + } + + fn admit(&mut self, j: super::Joined, ctx: &mut TickCtx) -> u32 { + let entity_id = *ctx.next_entity as i32; + *ctx.next_entity += 1; + let conn = j.conn; + let mut guest = Guest::new(j, entity_id, ctx.spawn, self.config.view_distance); + guest.game_mode = self.config.default_game_mode; + guest.joined_tick = self.ticks; + guest.position = ctx.spawn; + guest.previous_position = ctx.spawn; + self.guests.push(guest); + conn + } + + /// PlayerList.placeNewPlayer for a guest whose saved state is loaded. + pub fn place_new_player(&mut self, conn: u32, ctx: &mut TickCtx) { + let Some(i) = self.guests.iter().position(|g| g.conn == conn) else { + return; + }; + let (name, uuid, entity_id, mode, view) = { + let g = &self.guests[i]; + ( + g.name.clone(), + g.uuid, + g.entity_id, + g.game_mode, + g.view_distance, + ) + }; + let _ = view; + let levels = vec![ + "minecraft:overworld".to_owned(), + "minecraft:the_nether".to_owned(), + "minecraft:the_end".to_owned(), + ]; + self.guests[i].placed = true; + let g = &self.guests[i]; + g.send(&C::Login(play::Login { + player_id: entity_id, + hardcore: self.config.hardcore, + levels, + max_players: self.config.max_players as i32, + chunk_radius: self.config.view_distance, + simulation_distance: self.config.simulation_distance, + reduced_debug_info: false, + show_death_screen: true, + limited_crafting: false, + spawn: self.spawn_info(mode), + online_mode: false, + enforces_secure_chat: false, + })); + g.send(&C::ChangeDifficulty(play::ChangeDifficulty { + difficulty: ctx.difficulty, + locked: ctx.difficulty_locked, + })); + g.send(&C::PlayerAbilities(play::PlayerAbilities { + flags: g.ability_flags(), + flying_speed: 0.05, + walking_speed: 0.1, + })); + g.send(&C::SetHeldSlot(play::SetHeldSlot { + slot: g.selected as i32, + })); + self.send_commands(i); + self.system_message(yellow_translation("multiplayer.player.joined", &[&name])); + self.teleport(i, None); + // The player list: everyone already here, then the newcomer to all. + let mut entries = + vec![self.player_info(ctx.host.uuid, &ctx.host.name, ctx.host.game_mode, 0)]; + for o in self.guests.iter().filter(|o| o.conn != conn) { + entries.push(self.player_info( + o.uuid, + &o.name, + o.game_mode, + o.latency.load(Ordering::Relaxed), + )); + } + entries.push(self.player_info(uuid, &name, mode, 0)); + let own = play::PlayerInfoUpdate { + actions: Self::INFO_ACTIONS, + entries, + }; + self.guests[i].send(&C::PlayerInfoUpdate(own)); + let newcomer = play::PlayerInfoUpdate { + actions: Self::INFO_ACTIONS, + entries: vec![self.player_info(uuid, &name, mode, 0)], + }; + self.broadcast_except(conn, &C::PlayerInfoUpdate(newcomer)); + self.send_level_info(i, ctx); + self.send_inventory(i); + } + + /// Send everyone the command tree again (the permissions changed). + pub fn resend_commands(&self) { + for i in 0..self.guests.len() { + if self.guests[i].placed { + self.send_commands(i); + } + } + } + + /// Commands.sendCommands: the command tree for this player. + fn send_commands(&self, i: usize) { + let g = &self.guests[i]; + // A root with every command taking free-form arguments. + let mut nodes = vec![play::CommandNode { + kind: 0, + executable: false, + restricted: false, + children: Vec::new(), + redirect: None, + name: String::new(), + parser: None, + suggestions: None, + }]; + if self.config.guest_commands { + let argument = |name: &str| play::CommandNode { + kind: 2, + executable: true, + restricted: false, + children: Vec::new(), + redirect: None, + name: name.to_owned(), + // brigadier:string with the greedy phrase type. + parser: self + .sync + .builtin + .get("minecraft:command_argument_type") + .and_then(|ids| ids.id("brigadier:string")) + .map(|id| (id, vec![2])), + suggestions: None, + }; + for name in COMMANDS { + nodes.push(play::CommandNode { + kind: 1, + executable: true, + restricted: false, + children: vec![nodes.len() as i32 + 1], + redirect: None, + name: (*name).to_owned(), + parser: None, + suggestions: None, + }); + nodes.push(argument("args")); + let literal_index = nodes.len() as i32 - 2; + nodes[0].children.push(literal_index); + } + } + g.send(&C::Commands(play::Commands { nodes, root: 0 })); + } + + /// ServerGamePacketListenerImpl.teleport: move the client and wait for its confirmation. + pub fn teleport(&mut self, i: usize, position: Option<[f64; 3]>) { + let g = &mut self.guests[i]; + if let Some(p) = position { + g.position = p; + g.previous_position = p; + } + g.teleport_counter = (g.teleport_counter + 1) & 0x7FFF_FFFF; + let id = g.teleport_counter; + g.awaiting_teleport = Some((id, g.position)); + g.send(&C::PlayerPosition(play::PlayerPosition { + teleport: id, + position: g.position, + delta: [0.0; 3], + yaw: g.yaw, + pitch: g.pitch, + relatives: 0, + })); + } + + /// PlayerList.sendLevelInfo. + fn send_level_info(&mut self, i: usize, ctx: &TickCtx) { + let spawn = ctx.spawn; + let g = &self.guests[i]; + g.send(&C::InitializeBorder(play::InitializeBorder { + center_x: 0.0, + center_z: 0.0, + old_size: 59_999_968.0, + new_size: 59_999_968.0, + lerp_time: 0, + absolute_max_size: 29_999_984, + warning_blocks: 5, + warning_time: 15, + })); + g.send(&self.time_packet(ctx.world, ctx.clock_rate)); + g.send(&C::SetDefaultSpawnPosition(play::SetDefaultSpawnPosition { + pos: play::GlobalPos { + dimension: self.config.dimension.clone(), + pos: [ + spawn[0].floor() as i32, + spawn[1].floor() as i32, + spawn[2].floor() as i32, + ], + }, + yaw: 0.0, + pitch: 0.0, + })); + let w = &ctx.world.weather; + if w.raining { + g.send(&C::GameEvent(play::GameEvent { + event: game_event::START_RAINING, + param: 0.0, + })); + g.send(&C::GameEvent(play::GameEvent { + event: game_event::RAIN_LEVEL, + param: w.rain_level.1, + })); + g.send(&C::GameEvent(play::GameEvent { + event: game_event::THUNDER_LEVEL, + param: w.thunder_level.1, + })); + } + g.send(&C::GameEvent(play::GameEvent { + event: game_event::LEVEL_CHUNKS_LOAD_START, + param: 0.0, + })); + } + + fn time_packet(&self, world: &World, rate: f32) -> C { + let overworld = self + .sync + .id("minecraft:world_clock", "minecraft:overworld") + .unwrap_or(0); + C::SetTime(play::SetTime { + game_time: world.game_time, + clocks: self + .clock_ids + .iter() + .map(|&id| play::ClockState { + clock: id, + total_ticks: if id == overworld { world.day_time } else { 0 }, + partial_tick: 0.0, + rate: if id == overworld { rate } else { 0.0 }, + }) + .collect(), + }) + } + + /// ServerPlayer.initInventoryMenu / sendAllDataToRemote for the inventory menu. + pub fn send_inventory(&mut self, i: usize) { + let items: Vec> = (0..46).map(|s| self.guests[i].menu_slot(s)).collect(); + 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]; + g.menu_state = (g.menu_state + 1) & 0x7FFF; + g.send(&C::ContainerSetContent(play::ContainerSetContent { + container: 0, + state: g.menu_state, + items: net, + carried, + })); + g.menu_sent = items; + g.sent_selected = g.selected; + } + + // ---- per tick ------------------------------------------------------ + + pub fn tick(&mut self, ctx: &mut TickCtx) -> Vec { + self.ticks += 1; + let mut events = Vec::new(); + for event in self.lan.poll() { + match event { + NetEvent::Joined(j) => { + let conn = self.admit(*j, ctx); + events.push(HostEvent::Joined(conn)); + } + NetEvent::Left(conn, reason) => { + if let Some(i) = self.guests.iter().position(|g| g.conn == conn) { + let g = self.remove_guest(i, &reason); + events.push(HostEvent::Left(Box::new(g))); + } + } + NetEvent::Packet(conn, packet) => { + if let Some(g) = self.guest_mut(conn) { + g.inbox.push_back(*packet); + } + } + } + } + for i in 0..self.guests.len() { + if self.guests[i].placed { + self.process_inbox(i, ctx, &mut events); + } + } + if !self.guests.iter().any(|g| g.placed) { + if self.guests.is_empty() { + let _ = ctx.world.block_log.take(); + } + return events; + } + if ctx.world.block_log.is_none() { + ctx.world.block_log = Some(Vec::new()); + } + self.sync_world(ctx); + for i in 0..self.guests.len() { + if self.guests[i].placed { + self.update_chunks(i, ctx); + } + } + 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 { + self.sync_player_state(i); + } + } + let latencies: Vec<_> = self + .guests + .iter() + .map(|g| (g.uuid, g.latency.load(Ordering::Relaxed))) + .collect(); + if self.ticks.is_multiple_of(100) && !latencies.is_empty() { + let entries = latencies + .iter() + .map(|(uuid, latency)| play::PlayerInfo { + uuid: *uuid, + latency: Some(*latency), + ..Default::default() + }) + .collect(); + self.broadcast(&C::PlayerInfoUpdate(play::PlayerInfoUpdate { + actions: 16, + entries, + })); + } + events + } + + fn remove_guest(&mut self, i: usize, reason: &str) -> Guest { + let g = self.guests.remove(i); + if std::env::var_os("HORIZON_NET_DEBUG").is_some() { + eprintln!("[lan] {} left: {reason}", g.name); + } + if !g.placed { + return g; + } + self.broadcast(&C::PlayerInfoRemove(play::PlayerInfoRemove { + uuids: vec![g.uuid], + })); + self.broadcast(&C::RemoveEntities(play::RemoveEntities { + ids: vec![g.entity_id], + })); + self.system_message(yellow_translation("multiplayer.player.left", &[&g.name])); + g + } + + /// Time and weather (ServerLevel.tickTime / advanceWeatherCycle broadcasts). + fn sync_world(&mut self, ctx: &TickCtx) { + let world = &*ctx.world; + if self.ticks.is_multiple_of(20) || self.last_clock == i64::MIN { + self.broadcast(&self.time_packet(world, ctx.clock_rate)); + self.last_clock = world.day_time; + } + let w = &world.weather; + let (raining, rain, thunder) = self.weather; + if w.raining != raining { + self.broadcast(&C::GameEvent(play::GameEvent { + event: if w.raining { + game_event::START_RAINING + } else { + game_event::STOP_RAINING + }, + param: 0.0, + })); + } + if (w.rain_level.1 - rain).abs() > f32::EPSILON { + self.broadcast(&C::GameEvent(play::GameEvent { + event: game_event::RAIN_LEVEL, + param: w.rain_level.1, + })); + } + if (w.thunder_level.1 - thunder).abs() > f32::EPSILON { + self.broadcast(&C::GameEvent(play::GameEvent { + event: game_event::THUNDER_LEVEL, + param: w.thunder_level.1, + })); + } + self.weather = (w.raining, w.rain_level.1, w.thunder_level.1); + } + + // ---- chunks -------------------------------------------------------- + + fn update_chunks(&mut self, i: usize, ctx: &TickCtx) { + let (cx, cz) = self.guests[i].chunk(); + let r = self.guests[i].view_distance; + let g = &mut self.guests[i]; + if g.center != Some((cx, cz)) { + g.center = Some((cx, cz)); + g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { + x: cx, + z: cz, + })); + // Chunks that left the view. + let forget: Vec<_> = g + .sent_chunks + .iter() + .copied() + .filter(|&(x, z)| (x - cx).abs().max((z - cz).abs()) > r) + .collect(); + for (x, z) in forget { + g.sent_chunks.remove(&(x, z)); + g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] })); + } + g.chunk_queue + .retain(|&(x, z)| (x - cx).abs().max((z - cz).abs()) <= r); + for dz in -r..=r { + for dx in -r..=r { + let key = (cx + dx, cz + dz); + if !g.sent_chunks.contains(&key) && !g.chunk_queue.contains(&key) { + g.chunk_queue.push(key); + } + } + } + g.chunk_queue + .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); + } + // Send ready chunks, closest first, in batches. + if g.chunk_queue.is_empty() || g.unacknowledged >= 10 { + return; + } + g.chunk_credit = (g.chunk_credit + g.chunks_per_tick).min(g.chunks_per_tick.max(1.0) * 2.0); + let budget = g.chunk_credit.floor() as usize; + if budget == 0 { + return; + } + let mut packets = Vec::new(); + let mut taken = Vec::new(); + for (idx, key) in g.chunk_queue.iter().enumerate() { + if packets.len() >= budget { + break; + } + let Some(chunk) = ctx.world.chunks.get(key) else { + continue; + }; + if !chunk.lit { + continue; + } + packets.push(C::LevelChunkWithLight( + self.encoder.encode(chunk, &ctx.world.block_entities), + )); + taken.push(idx); + } + if packets.is_empty() { + return; + } + g.chunk_credit -= packets.len() as f32; + g.send(&C::ChunkBatchStart(horizon_protocol::packets::Empty)); + for p in &packets { + g.send(p); + } + g.send(&C::ChunkBatchFinished(play::ChunkBatchFinished { + size: packets.len() as i32, + })); + g.unacknowledged += 1; + for idx in taken.into_iter().rev() { + let key = g.chunk_queue.remove(idx); + g.sent_chunks.insert(key); + } + } + + /// Resend a chunk to everyone who has it (a block entity changed, relight). + pub fn resend_chunk(&mut self, world: &World, x: i32, z: i32) { + let Some(chunk) = world.chunks.get(&(x, z)) else { + return; + }; + let packet = C::LevelChunkWithLight(self.encoder.encode(chunk, &world.block_entities)); + let body = packet.encode(); + for g in self + .guests + .iter() + .filter(|g| g.sent_chunks.contains(&(x, z))) + { + g.sender.send(body.clone()); + } + } + + fn broadcast_block_changes(&mut self, world: &mut World) { + let Some(log) = world.block_log.as_mut() else { + return; + }; + if log.is_empty() { + return; + } + let mut changes = std::mem::take(log); + changes.sort_unstable(); + changes.dedup(); + // Group by section. + let mut sections: std::collections::BTreeMap<(i32, i32, i32), Vec<(i32, i32, i32)>> = + Default::default(); + for p in changes { + sections + .entry((p.0 >> 4, p.1 >> 4, p.2 >> 4)) + .or_default() + .push(p); + } + for ((sx, sy, sz), positions) in sections { + let viewers: Vec = (0..self.guests.len()) + .filter(|&i| { + self.guests[i].placed && self.guests[i].sent_chunks.contains(&(sx, sz)) + }) + .collect(); + if viewers.is_empty() { + continue; + } + let packet = if positions.len() == 1 { + let (x, y, z) = positions[0]; + C::BlockUpdate(play::BlockUpdate { + pos: [x, y, z], + state: i32::from(world.block(x, y, z).0 as u16), + }) + } else { + C::SectionBlocksUpdate(play::SectionBlocksUpdate { + section: [sx, sy, sz], + changes: positions + .iter() + .map(|&(x, y, z)| { + let state = i64::from(world.block(x, y, z).0); + state << 12 + | i64::from(x & 15) << 8 + | i64::from(z & 15) << 4 + | i64::from(y & 15) + }) + .collect(), + }) + }; + let body = packet.encode(); + for &i in &viewers { + self.guests[i].sender.send(body.clone()); + } + // Block entities with data the client shows. + for &(x, y, z) in &positions { + let Some(entity) = world.block_entities.get(&(x, y, z)) else { + continue; + }; + let Some(tag) = super::chunks::entity_tag(entity) else { + continue; + }; + let state = world.block(x, y, z).0 as u16; + let Some(kind) = self.encoder.entity_type(state) else { + continue; + }; + let body = C::BlockEntityData(play::BlockEntityData { + pos: [x, y, z], + kind, + tag, + }) + .encode(); + for &i in &viewers { + self.guests[i].sender.send(body.clone()); + } + } + } + } + + // ---- entities ------------------------------------------------------ + + fn player_state( + &self, + id: i32, + uuid: u128, + position: [f64; 3], + rot: (f32, f32, f32), + on_ground: bool, + flags: (bool, bool, bool, bool), + skin: u8, + health: f32, + equipment: Vec<(u8, Option)>, + ) -> EntityState { + let (sneaking, sprinting, gliding, sleeping) = flags; + let mut shared = 0i8; + if sneaking { + shared |= 0x02; + } + if sprinting { + shared |= 0x08; + } + if gliding { + shared |= -128; + } + let pose = if sleeping { + 2 + } else if gliding { + 1 + } else if sneaking { + 5 + } else { + 0 + }; + let mut meta = Vec::new(); + if shared != 0 { + meta.push((0, serializer::BYTE, Value::Byte(shared))); + } + if pose != 0 { + meta.push((6, serializer::POSE, Value::Id(pose))); + } + if (health - 1.0).abs() > f32::EPSILON && health != 20.0 { + meta.push((9, serializer::FLOAT, Value::Float(health))); + } + if skin != 0 { + meta.push((16, serializer::BYTE, Value::Byte(skin as i8))); + } + EntityState { + id, + uuid, + kind: "minecraft:player".into(), + position, + yaw: rot.0, + pitch: rot.1, + head_yaw: rot.2, + on_ground, + velocity: [0.0; 3], + data: 0, + meta, + equipment, + send_velocity: false, + } + } + + fn equipment_of( + &mut self, + main: &Option, + off: &Option, + armor: [&Option; 4], + ) -> Vec<(u8, Option)> { + // Armor is stored head..feet; the wire slots are feet(2) legs(3) chest(4) head(5). + let mut out = Vec::new(); + let slots = [ + (0u8, main), + (1, off), + (5, armor[0]), + (4, armor[1]), + (3, armor[2]), + (2, armor[3]), + ]; + for (slot, item) in slots { + if item.is_some() { + out.push((slot, self.stack(item))); + } + } + out + } + + /// All entities as one client sees them: the world's, the host, the other guests. + fn track_entities(&mut self, ctx: &mut TickCtx) { + let mut all: Vec = + Vec::with_capacity(ctx.entities.len() + self.guests.len() + 1); + let h = ctx.host; + let equipment = { + let e = &h.equipment; + self.equipment_of(&e[0], &e[1], [&e[5], &e[4], &e[3], &e[2]]) + }; + all.push(self.player_state( + h.entity_id, + h.uuid, + h.position, + (h.yaw, h.pitch, h.head_yaw), + h.on_ground, + (h.sneaking, h.sprinting, false, false), + 0x7F, + h.health, + equipment, + )); + let placed: Vec = (0..self.guests.len()) + .filter(|&i| self.guests[i].placed) + .collect(); + let guest_states: Vec<_> = placed + .into_iter() + .map(|i| { + let (main, off, armor) = { + let g = &self.guests[i]; + ( + g.inventory.get(g.selected).cloned().flatten(), + g.offhand.clone(), + g.armor.clone(), + ) + }; + let equipment = + self.equipment_of(&main, &off, [&armor[0], &armor[1], &armor[2], &armor[3]]); + let g = &self.guests[i]; + self.player_state( + g.entity_id, + g.uuid, + g.position, + (g.yaw, g.pitch, g.head_yaw), + g.on_ground, + (g.sneaking, g.sprinting, g.fall_flying, g.sleeping), + g.info.model_customisation, + g.health, + equipment, + ) + }) + .collect(); + all.extend(guest_states); + all.extend(ctx.entities.iter().cloned()); + let by_id: std::collections::HashMap = + all.iter().enumerate().map(|(i, e)| (e.id, i)).collect(); + for gi in 0..self.guests.len() { + if !self.guests[gi].placed { + continue; + } + let range = f64::from(self.guests[gi].view_distance * 16).min(128.0); + let me = self.guests[gi].entity_id; + let origin = self.guests[gi].position; + // Forget what disappeared or left range. + let mut removed = Vec::new(); + for id in self.guests[gi].tracker.ids() { + match by_id.get(&id) { + None => removed.push(id), + Some(&ei) => { + let e = &all[ei]; + if !in_range(origin, e.position, range + 8.0) { + removed.push(id); + } + } + } + } + if !removed.is_empty() { + for id in &removed { + self.guests[gi].tracker.forget(*id); + } + self.guests[gi].send(&C::RemoveEntities(play::RemoveEntities { ids: removed })); + } + for e in &all { + if e.id == me { + continue; + } + if self.guests[gi].tracker.is_tracking(e.id) { + let packets = self.guests[gi].tracker.update(e); + self.guests[gi].send_all(&packets); + } else if in_range(origin, e.position, range) { + let Some(kind) = self.entity_type(&e.kind) else { + continue; + }; + let packets = self.guests[gi].tracker.spawn(e, kind); + // Players need their list entry first; guests got it at join. + self.guests[gi].send_all(&packets); + } + } + } + } + + // ---- per-player state ------------------------------------------------ + + /// ServerPlayer.doTick: health, food, experience and the inventory menu. + fn sync_player_state(&mut self, i: usize) { + let health = { + let g = &self.guests[i]; + (g.health, g.food, g.saturation) + }; + if self.guests[i].sent_health != Some(health) { + let g = &mut self.guests[i]; + g.send(&C::SetHealth(play::SetHealth { + health: health.0, + food: health.1, + saturation: health.2, + })); + g.sent_health = Some(health); + } + let xp = { + let g = &self.guests[i]; + (g.xp_progress, g.xp_level, g.xp_total) + }; + if self.guests[i].sent_xp != Some(xp) { + let g = &mut self.guests[i]; + g.send(&C::SetExperience(play::SetExperience { + progress: xp.0, + level: xp.1, + total: xp.2, + })); + g.sent_xp = Some(xp); + } + // AbstractContainerMenu.broadcastChanges for the inventory menu. + let mut changes = Vec::new(); + for slot in 0..46 { + let now = self.guests[i].menu_slot(slot); + if now != self.guests[i].menu_sent[slot] { + changes.push((slot, now)); + } + } + for (slot, now) in changes { + let net = self.stack(&now); + let g = &mut self.guests[i]; + g.menu_state = (g.menu_state + 1) & 0x7FFF; + g.send(&C::ContainerSetSlot(play::ContainerSetSlot { + container: 0, + state: g.menu_state, + slot: slot as i16, + item: net, + })); + g.menu_sent[slot] = now; + } + } + + // ---- incoming ------------------------------------------------------ + + fn process_inbox(&mut self, i: usize, ctx: &mut TickCtx, events: &mut Vec) { + let mut budget = 400; + while budget > 0 { + let Some(packet) = self.guests[i].inbox.pop_front() else { + break; + }; + budget -= 1; + let conn = self.guests[i].conn; + match packet { + S::AcceptTeleportation(p) => { + let g = &mut self.guests[i]; + if g.awaiting_teleport.is_some_and(|(id, _)| id == p.id) { + g.awaiting_teleport = None; + } + } + S::MovePlayerPos(p) => { + self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags); + } + S::MovePlayerPosRot(p) => { + self.move_player(i, Some([p.x, p.y, p.z]), Some((p.yaw, p.pitch)), p.flags); + } + S::MovePlayerRot(p) => { + self.move_player(i, None, Some((p.yaw, p.pitch)), p.flags); + } + S::MovePlayerStatus(p) => { + self.guests[i].on_ground = p.flags & 1 != 0; + } + S::PlayerLoaded(_) => self.guests[i].loaded = true, + S::ChunkBatchReceived(p) => { + let g = &mut self.guests[i]; + g.unacknowledged = g.unacknowledged.saturating_sub(1); + g.chunks_per_tick = if p.chunks_per_tick.is_nan() { + 0.01 + } else { + p.chunks_per_tick.clamp(0.01, 64.0) + }; + } + S::ClientInformation(info) => { + let g = &mut self.guests[i]; + g.view_distance = + i32::from(info.view_distance).clamp(2, self.config.view_distance); + g.info = info; + g.center = None; + } + S::PlayerInput(p) => { + self.guests[i].sneaking = p.flags & 32 != 0; + self.guests[i].sprinting = p.flags & 64 != 0 && p.flags & 1 != 0; + } + S::PlayerCommand(p) => match p.action { + 1 => self.guests[i].sprinting = true, + 2 => self.guests[i].sprinting = false, + 6 => self.guests[i].fall_flying = true, + 0 => self.guests[i].sleeping = false, + _ => {} + }, + S::ClientTickEnd(_) => {} + S::Chat(c) => { + let text: String = c.message.chars().filter(|c| !c.is_control()).collect(); + if !text.is_empty() { + let name = self.guests[i].name.clone(); + self.chat(&name, &text); + events.push(HostEvent::Chat(format!("<{name}> {text}"))); + } + } + S::Unknown(id, ref payload) => { + // Packets Horizon does not model: ignore the ones that only + // matter to vanilla's chat signing. + let _ = (id, payload); + } + other => events.push(HostEvent::Packet(conn, Box::new(other))), + } + } + let _ = ctx; + } + + /// ServerGamePacketListenerImpl.handleMovePlayer. + fn move_player(&mut self, i: usize, pos: Option<[f64; 3]>, rot: Option<(f32, f32)>, flags: u8) { + let g = &mut self.guests[i]; + if g.awaiting_teleport.is_some() || !g.loaded && g.ticks == 0 && pos.is_none() { + return; + } + if let Some(p) = pos { + if p.iter().any(|v| !v.is_finite() || v.abs() > 3.0e7) { + return; + } + // A jump of more than a hundred blocks is a rejected move. + let d2: f64 = (0..3).map(|k| (p[k] - g.position[k]).powi(2)).sum(); + if d2 > 100.0 * 100.0 { + let at = g.position; + self.teleport(i, Some(at)); + return; + } + g.previous_position = g.position; + g.position = p; + } + if let Some((yaw, pitch)) = rot + && yaw.is_finite() + && pitch.is_finite() + { + g.yaw = yaw % 360.0; + g.pitch = pitch.clamp(-90.0, 90.0); + g.head_yaw = g.yaw; + } + g.on_ground = flags & 1 != 0; + g.ticks = g.ticks.max(1); + } + + /// Acknowledge a block interaction (ClientboundBlockChangedAckPacket). + pub fn ack(&self, conn: u32, sequence: i32) { + if sequence >= 0 + && let Some(g) = self.guest(conn) + { + g.send(&C::BlockChangedAck(play::BlockChangedAck { sequence })); + } + } + + /// Set a guest's game mode and tell everyone (ServerPlayer.setGameMode). + pub fn set_game_mode(&mut self, conn: u32, mode: i32) { + let Some(g) = self.guest_mut(conn) else { + return; + }; + g.game_mode = mode; + let uuid = g.uuid; + g.send(&C::GameEvent(play::GameEvent { + event: game_event::CHANGE_GAME_MODE, + param: mode as f32, + })); + g.send(&C::PlayerAbilities(play::PlayerAbilities { + flags: g.ability_flags(), + flying_speed: 0.05, + walking_speed: 0.1, + })); + self.broadcast(&C::PlayerInfoUpdate(play::PlayerInfoUpdate { + actions: 4, + entries: vec![play::PlayerInfo { + uuid, + game_mode: Some(mode), + ..Default::default() + }], + })); + } + + /// The host's game mode changed (PlayerInfo UPDATE_GAME_MODE for everyone). + pub fn set_host_game_mode(&self, uuid: u128, mode: i32) { + self.broadcast(&C::PlayerInfoUpdate(play::PlayerInfoUpdate { + actions: 4, + entries: vec![play::PlayerInfo { + uuid, + game_mode: Some(mode), + ..Default::default() + }], + })); + } + + pub fn disconnect_all(&mut self) { + let reason = translatable("multiplayer.disconnect.server_shutdown", &[]); + for g in &self.guests { + let _ = g.sender.tx.send(super::Out::Disconnect(reason.clone())); + } + } +} + +fn in_range(a: [f64; 3], b: [f64; 3], range: f64) -> bool { + let (dx, dz) = (a[0] - b[0], a[2] - b[2]); + dx * dx + dz * dz <= range * range && (a[1] - b[1]).abs() <= 400.0 +} + +/// The commands guests may type when the host allows them. +const COMMANDS: &[&str] = &[ + "advancement", + "attribute", + "clear", + "clone", + "damage", + "data", + "difficulty", + "effect", + "enchant", + "experience", + "fill", + "gamemode", + "gamerule", + "give", + "kill", + "me", + "msg", + "particle", + "playsound", + "say", + "scoreboard", + "seed", + "setblock", + "spawnpoint", + "summon", + "tag", + "teleport", + "tell", + "time", + "title", + "tp", + "weather", + "xp", +]; + +impl Hub { + pub fn item_name(&self, id: i32) -> Option> { + self.sync + .builtin + .get("minecraft:item")? + .name(id) + .map(std::sync::Arc::from) + } + pub fn enchantment_name(&self, id: i32) -> Option { + 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); + } +} diff --git a/crates/horizon-client/src/lan/menu.rs b/crates/horizon-client/src/lan/menu.rs new file mode 100644 index 000000000..38e0e8ff3 --- /dev/null +++ b/crates/horizon-client/src/lan/menu.rs @@ -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; +} + +/// 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>, + /// An unfinished drag: (mode, slots). + pub drag: Option<(u8, Vec)>, +} + +/// 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]>, +} + +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 { + 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) { + 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, std::ops::Range) { + 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, + reverse: bool, + rules: &dyn Rules, +) -> Option { + let order: Vec = 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)>, + slot: i32, + button: i32, + mode: i32, + rules: &dyn Rules, +) -> (Vec, Vec) { + let mut drops = Vec::new(); + let before: Vec> = (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)>, + 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); + } + } +} diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs new file mode 100644 index 000000000..6367295ae --- /dev/null +++ b/crates/horizon-client/src/lan/mod.rs @@ -0,0 +1,201 @@ +//! Hosting a world on the local network. The network side lives here: the +//! listener, the per-connection handshake/login/configuration threads and the +//! writer threads (`conn`), plus the data the configuration phase sends +//! (`data`). The play state is driven by the game thread (`hub`), which only +//! ever exchanges decoded packets with these threads through channels, so a +//! 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; +use horizon_protocol::packets::play; +use horizon_protocol::{GAME_VERSION, PROTOCOL_VERSION, packets::configuration::ClientInformation}; +use std::{ + collections::HashSet, + io, + net::{SocketAddr, TcpListener, TcpStream}, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering}, + mpsc::{Receiver, Sender, channel}, + }, + thread::JoinHandle, + time::Duration, +}; + +/// IntegratedServer.MAX_PLAYERS. +pub const MAX_PLAYERS: usize = 8; + +/// Messages from the connection threads to the game thread. +pub enum NetEvent { + /// A client finished configuration and enters the play state. + Joined(Box), + Packet(u32, Box), + /// The connection ended (reason for the log). + Left(u32, String), +} +pub struct Joined { + pub conn: u32, + pub uuid: u128, + pub name: String, + pub info: ClientInformation, + pub brand: String, + pub sender: PlayerSender, + /// Smoothed keep-alive round trip in milliseconds. + pub latency: Arc, +} +/// Queued for a connection's writer thread. +pub enum Out { + /// A packet body: VarInt id and payload. + Packet(Vec), + /// Send a play disconnect with this component, then close. + Disconnect(horizon_world::nbt::Tag), + Close, +} + +/// State shared with the connection threads. +pub struct Shared { + pub sync: Arc, + pub events: Sender, + motd: Mutex, + online: Mutex>, + max_players: usize, + next: AtomicU32, + stop: AtomicBool, +} +impl Shared { + pub fn next_id(&self) -> u32 { + self.next.fetch_add(1, Ordering::Relaxed) + } + /// PlayerList.canPlayerLogin: duplicates and a full server are refused. + pub fn try_admit(&self, uuid: u128, _name: &str) -> Option<&'static str> { + let mut online = self.online.lock().unwrap(); + if online.contains(&uuid) { + return Some("multiplayer.disconnect.duplicate_login"); + } + if online.len() >= self.max_players { + return Some("multiplayer.disconnect.server_full"); + } + online.insert(uuid); + None + } + pub fn release(&self, uuid: u128) { + self.online.lock().unwrap().remove(&uuid); + } + pub fn online(&self) -> usize { + self.online.lock().unwrap().len() + } + /// The status response (ServerStatus): version, players and the MOTD. + pub fn status_json(&self) -> String { + let motd = self.motd.lock().unwrap().clone(); + serde_json::json!({ + "version": { "name": GAME_VERSION, "protocol": PROTOCOL_VERSION }, + "players": { "max": self.max_players, "online": self.online() }, + "description": { "text": motd }, + "enforcesSecureChat": false, + }) + .to_string() + } +} + +/// A running LAN server. +pub struct Lan { + pub shared: Arc, + events: Receiver, + pub port: u16, + listener: Option>, +} +impl Lan { + /// Listen on `port` (0 picks a free one). + pub fn start( + sync: Arc, + port: u16, + motd: String, + max_players: usize, + ) -> io::Result { + let listener = TcpListener::bind(("0.0.0.0", port))?; + listener.set_nonblocking(true)?; + let port = listener.local_addr()?.port(); + let (tx, events) = channel(); + let shared = Arc::new(Shared { + sync, + events: tx, + motd: Mutex::new(motd), + online: Mutex::new(HashSet::new()), + max_players, + next: AtomicU32::new(1), + stop: AtomicBool::new(false), + }); + let accept_shared = shared.clone(); + let listener = std::thread::Builder::new() + .name("horizon-lan-accept".into()) + .spawn(move || accept_loop(listener, accept_shared))?; + Ok(Self { + shared, + events, + port, + listener: Some(listener), + }) + } + /// Everything the connection threads reported since the last call. + pub fn poll(&self) -> Vec { + self.events.try_iter().collect() + } + /// Reserve a uuid for the host so a guest cannot take the name. + pub fn reserve(&self, uuid: u128) { + self.shared.online.lock().unwrap().insert(uuid); + } + pub fn set_motd(&self, motd: &str) { + *self.shared.motd.lock().unwrap() = motd.to_owned(); + } + pub fn stop(&mut self) { + self.shared.stop.store(true, Ordering::Relaxed); + if let Some(t) = self.listener.take() { + let _ = t.join(); + } + } +} +impl Drop for Lan { + fn drop(&mut self) { + self.stop(); + } +} + +fn accept_loop(listener: TcpListener, shared: Arc) { + while !shared.stop.load(Ordering::Relaxed) { + match listener.accept() { + Ok((stream, addr)) => { + let shared = shared.clone(); + let _ = std::thread::Builder::new() + .name("horizon-lan-conn".into()) + .spawn(move || handle(stream, addr, shared)); + } + Err(e) if e.kind() == io::ErrorKind::WouldBlock => { + std::thread::sleep(Duration::from_millis(25)); + } + Err(_) => std::thread::sleep(Duration::from_millis(100)), + } + } +} +fn handle(stream: TcpStream, addr: SocketAddr, shared: Arc) { + let _ = stream.set_nonblocking(false); + if let Err(e) = conn::serve(stream, shared) + && std::env::var_os("HORIZON_NET_DEBUG").is_some() + { + eprintln!("[lan] {addr}: {e}"); + } +} + +/// HttpUtil.getAvailablePort: a free local port. +pub fn available_port() -> u16 { + TcpListener::bind(("0.0.0.0", 0)) + .and_then(|l| l.local_addr()) + .map_or(25565, |a| a.port()) +} diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs new file mode 100644 index 000000000..6dc5f15ba --- /dev/null +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -0,0 +1,130 @@ +//! Guests' saved state: `players/data/.dat` in the vanilla player +//! compound, through the same code that saves the host. +use super::guest::Guest; +use crate::{ + items::ItemStack, + save::{Level, read_dat, write_dat}, +}; +use horizon_protocol::crypto::uuid_string; +use std::{ + path::{Path, PathBuf}, + sync::Arc, +}; + +pub fn path(world: &Path, uuid: u128) -> PathBuf { + world + .join("players") + .join("data") + .join(format!("{}.dat", uuid_string(uuid))) +} + +fn uuid_ints(uuid: u128) -> [i32; 4] { + [ + (uuid >> 96) as i32, + (uuid >> 64) as i32, + (uuid >> 32) as i32, + uuid as i32, + ] +} + +/// Whether a saved file exists for this player. +pub fn exists(world: &Path, uuid: u128) -> bool { + path(world, uuid).is_file() +} + +/// Load a guest's saved state, if they have been here before. +pub fn load(guest: &mut Guest, world: &Path) -> bool { + let Some(tag) = read_dat(&path(world, guest.uuid)) else { + return false; + }; + let mut level = Level { + health: 20.0, + food: 20, + saturation: 5.0, + ..Level::default() + }; + level.read_player(&tag); + if let Some(p) = level.position { + guest.position = p; + guest.previous_position = p; + } + guest.yaw = level.rotation[0]; + guest.pitch = level.rotation[1]; + guest.head_yaw = guest.yaw; + guest.on_ground = level.on_ground; + guest.health = level.health; + guest.food = level.food; + guest.saturation = level.saturation; + guest.xp_level = level.xp_level; + guest.xp_progress = level.xp_progress; + guest.xp_total = level.xp_total; + guest.game_mode = level.mode(); + guest.selected = (level.selected_slot.max(0) as usize).min(8); + guest.saved = Some(tag); + for (slot, item, count, damage) in &level.inventory { + let mut stack = ItemStack { + item: Arc::from(item.as_str()), + count: *count, + damage: *damage, + extra: level.inventory_components.get(slot).cloned(), + }; + if stack.count == 0 { + stack.count = 1; + } + match *slot { + 0..=35 => guest.inventory[usize::from(*slot)] = Some(stack), + 100 => guest.armor[3] = Some(stack), + 101 => guest.armor[2] = Some(stack), + 102 => guest.armor[1] = Some(stack), + 103 => guest.armor[0] = Some(stack), + 150 => guest.offhand = Some(stack), + _ => {} + } + } + true +} + +/// Save a guest (PlayerDataStorage.save). +pub fn save(guest: &Guest, world: &Path) { + let mut level = Level { + player_uuid: Some(uuid_ints(guest.uuid)), + position: Some(guest.position), + rotation: [guest.yaw, guest.pitch], + health: guest.health, + food: guest.food, + saturation: guest.saturation, + xp_level: guest.xp_level, + xp_progress: guest.xp_progress, + xp_total: guest.xp_total, + game_mode: guest.game_mode, + creative: guest.game_mode == 1, + selected_slot: guest.selected as i32, + on_ground: guest.on_ground, + dimension: "minecraft:overworld".into(), + player_extra: guest.saved.clone(), + ..Level::default() + }; + let mut put = |slot: u8, stack: &Option| { + if let Some(s) = stack { + level + .inventory + .push((slot, s.item.to_string(), s.count, s.damage)); + if let Some(extra) = &s.extra { + level.inventory_components.insert(slot, extra.clone()); + } + } + }; + for (i, s) in guest.inventory.iter().enumerate() { + put(i as u8, s); + } + put(103, &guest.armor[0]); + put(102, &guest.armor[1]); + put(101, &guest.armor[2]); + put(100, &guest.armor[3]); + put(150, &guest.offhand); + let file = path(world, guest.uuid); + if let Some(dir) = file.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = write_dat(&file, level.player_tag()); +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 09c1ecbb0..a0be82404 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -43,6 +43,7 @@ pub mod input; pub mod item_data; pub mod items; pub mod keybinds; +pub mod lan; pub mod landing; pub mod lang; pub mod light; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index e949eb8ef..e94e74d9a 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -1299,7 +1299,7 @@ pub fn random_uuid() -> [i32; 4] { let b = (b & !(0xC000_0000_0000_0000)) | 0x8000_0000_0000_0000; [(a >> 32) as i32, a as i32, (b >> 32) as i32, b as i32] } -fn uuid_tag(u: [i32; 4]) -> Tag { +pub(crate) fn uuid_tag(u: [i32; 4]) -> Tag { Tag::IntArray(u.to_vec()) } pub(crate) fn uuid_from_tag(tag: Option<&Tag>) -> Option<[i32; 4]> { @@ -1580,7 +1580,7 @@ impl Level { level.player_extra = player; Some(level) } - fn read_player(&mut self, p: &Tag) { + pub fn read_player(&mut self, p: &Tag) { let n = |k: &str| number(p.get(k)); let f = |k: &str| float(p.get(k)); self.position = read_doubles::<3>(p.get("Pos")); diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 923feb62b..f6b3f64b6 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -123,6 +123,9 @@ pub struct Streaming { /// Chunks come from a server (`insert_remote`/`forget`): nothing is /// generated and columns are only unloaded when the server says so. pub remote: bool, + /// More areas to keep loaded (centre chunk, radius), e.g. around guests + /// of a world open to the network. They are generated and kept but not meshed. + pub extra: Vec<((i32, i32), i32)>, } pub struct WorkerContext { pub assets: Arc, @@ -231,6 +234,7 @@ impl Streaming { generated_total: 0, meshed_total: 0, remote: false, + extra: Vec::new(), } } /// A column received from a server: store it and relight it and its neighbours. @@ -265,8 +269,14 @@ impl Streaming { self.shared.ready.notify_one(); } fn distance(&self, x: i32, z: i32) -> i64 { - let (dx, dz) = (i64::from(x - self.center.0), i64::from(z - self.center.1)); - dx * dx + dz * dz + let d = |c: (i32, i32)| { + let (dx, dz) = (i64::from(x - c.0), i64::from(z - c.1)); + dx * dx + dz * dz + }; + self.extra + .iter() + .map(|(c, _)| d(*c)) + .fold(d(self.center), i64::min) } fn region(world: &World, x: i32, z: i32) -> Option> { let mut region: Region = Default::default(); @@ -408,12 +418,16 @@ impl Streaming { self.meshed.remove(key); } // Drop far proto chunks that are not checked out. - let (cx, cz, r4) = (self.center.0, self.center.1, i64::from(self.radius + 4)); + let areas: Vec<((i32, i32), i64)> = + std::iter::once((self.center, i64::from(self.radius + 4))) + .chain(self.extra.iter().map(|&(c, r)| (c, i64::from(r + 4)))) + .collect(); let forced = &self.forced; self.protos.retain(|&(x, z), p| { - let d = i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2); p.is_none() - || d <= r4 * r4 + || areas.iter().any(|&((cx, cz), r4)| { + i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2) <= r4 * r4 + }) || forced .iter() .any(|f| (x - f.0).abs() <= 3 && (z - f.1).abs() <= 3) @@ -496,20 +510,25 @@ impl Streaming { // Generation (load or proto), closest first, bounded in flight. let margin = if self.decorates { 3 } else { 1 }; if !self.remote && self.generating.len() < workers * 3 { - let r = self.radius + margin; let mut wanted = Vec::new(); - for dz in -r..=r { - for dx in -r..=r { - let (x, z) = (self.center.0 + dx, self.center.1 + dz); - if !self.in_range(x, z, margin) - || world.chunks.contains_key(&(x, z)) - || self.generating.contains(&(x, z)) - || self.protos.contains_key(&(x, z)) - || self.finishing.contains(&(x, z)) - { - continue; + let areas: Vec<((i32, i32), i32)> = std::iter::once((self.center, self.radius)) + .chain(self.extra.iter().copied()) + .collect(); + for (center, radius) in areas { + let r = radius + margin; + for dz in -r..=r { + for dx in -r..=r { + let (x, z) = (center.0 + dx, center.1 + dz); + if !self.in_range(x, z, margin) + || world.chunks.contains_key(&(x, z)) + || self.generating.contains(&(x, z)) + || self.protos.contains_key(&(x, z)) + || self.finishing.contains(&(x, z)) + { + continue; + } + wanted.push((self.distance(x, z), x, z)); } - wanted.push((self.distance(x, z), x, z)); } } // Forced chunks and their generation neighbourhood. @@ -560,7 +579,7 @@ impl Streaming { let dirty: Vec<_> = world.dirty_sections.iter().copied().collect(); let mut columns: HashMap<(i32, i32), Option>> = HashMap::new(); for (x, sy, z) in dirty { - if !world.chunks.contains_key(&(x, z)) || !self.in_range(x, z, 0) { + if !world.chunks.contains_key(&(x, z)) || !self.in_main_range(x, z, 0) { world.dirty_sections.remove(&(x, sy, z)); continue; } @@ -666,8 +685,17 @@ impl Streaming { } } fn in_range(&self, x: i32, z: i32, margin: i32) -> bool { + self.in_main_range(x, z, margin) + || self.extra.iter().any(|&(c, radius)| { + let r = i64::from(radius + margin); + let (dx, dz) = (i64::from(x - c.0), i64::from(z - c.1)); + dx * dx + dz * dz <= r * r + }) + } + fn in_main_range(&self, x: i32, z: i32, margin: i32) -> bool { let r = i64::from(self.radius + margin); - if self.distance(x, z) <= r * r { + let (dx, dz) = (i64::from(x - self.center.0), i64::from(z - self.center.1)); + if dx * dx + dz * dz <= r * r { return true; } let reach = (margin - 1).max(0); diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index c3c1ae6eb..64e30d1a9 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -37,6 +37,9 @@ pub struct World { pub game_time: i64, pub day_time: i64, pub weather: Weather, + /// Every block position written since the log was last drained, kept + /// only while the world is open to the network (see `lan`). + pub block_log: Option>, } /// ServerLevel weather state (advanceWeatherCycle). #[derive(Clone, Copy, Debug, Default)] @@ -117,6 +120,7 @@ impl World { game_time: 0, day_time: 1000, weather: Weather::default(), + block_log: None, } } /// A controlled blockstate scene for the native scene probes: material @@ -190,6 +194,9 @@ impl World { .push(((x, y, z), previous, state.0 as u16)); } self.revision = self.revision.wrapping_add(1); + if let Some(log) = &mut self.block_log { + log.push((x, y, z)); + } self.modified.insert((x >> 4, z >> 4)); let sy = (y - MIN_Y) >> 4; for dz in -1..=1 { diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs new file mode 100644 index 000000000..c8ee6e6c2 --- /dev/null +++ b/crates/horizon-client/tests/lan_bot.rs @@ -0,0 +1,495 @@ +//! A protocol bot joins a hosted world the way a vanilla client does: +//! handshake, status, offline login, configuration (registries and tags), +//! then the play state (login, chunks with light, player list, entities, +//! block changes). Needs the prepared resources; skipped without them. +use horizon_client::{ + chunk::{Chunk, MIN_Y}, + lan::{ + Lan, + chunks::ChunkEncoder, + data::SyncData, + entity::EntityState, + hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, + }, + world::World, +}; +use horizon_protocol::{ + PROTOCOL_VERSION, + connection::Connection, + crypto::offline_uuid, + packets::{ + Empty, + configuration::{self as cfg, ClientInformation}, + handshake, login, + play::{self, Clientbound as C, Serverbound as S}, + status, + }, +}; +use horizon_world::registry::BlockStateId; +use std::{ + path::Path, + sync::Arc, + thread, + time::{Duration, Instant}, +}; + +fn resources() -> Option { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + root.join("items.json").exists().then_some(root) +} + +const STONE: u16 = 1; + +fn flat_world() -> World { + let mut world = World::new(BlockStateId(0), 0); + for cz in -4..=4 { + for cx in -4..=4 { + let mut chunk = Chunk::empty(cx, cz); + for z in 0..16 { + for x in 0..16 { + chunk.set(x, MIN_Y + 4, z, STONE); + } + } + chunk.lit = true; + world.chunks.insert((cx, cz), Arc::new(chunk)); + } + } + world +} + +struct Bot { + c: Connection, + name: String, +} +impl Bot { + fn recv_play(&mut self) -> Result { + let (id, payload) = self.c.recv().map_err(|e| e.to_string())?; + match C::decode(id, &payload) { + Ok(p) => Ok(p), + // The command tree has argument nodes the client side does not decode. + Err(e) if id == horizon_protocol::ids::play::clientbound::COMMANDS => { + let _ = e; + Ok(C::Unknown(id, payload)) + } + Err(e) => Err(format!("packet {id}: {e}")), + } + } + fn send(&mut self, p: S) { + self.c.send(&p.encode()).unwrap(); + } +} + +fn connect(port: u16, name: &str, known_pack: bool) -> Result { + let e = |e: horizon_protocol::Error| e.to_string(); + let mut c = Connection::connect("127.0.0.1", port, Duration::from_secs(5)).map_err(e)?; + c.reader + .set_read_timeout(Some(Duration::from_secs(20))) + .map_err(e)?; + c.send( + &handshake::Serverbound::Intention(handshake::Intention { + protocol: PROTOCOL_VERSION, + host: "127.0.0.1".into(), + port, + intent: handshake::LOGIN, + }) + .encode(), + ) + .map_err(e)?; + c.send( + &login::Serverbound::Hello(login::ServerHello { + name: name.into(), + uuid: offline_uuid(name), + }) + .encode(), + ) + .map_err(e)?; + loop { + let (id, payload) = c.recv().map_err(e)?; + match login::Clientbound::decode(id, &payload).map_err(e)? { + login::Clientbound::Compression(p) => c.set_compression(p.threshold), + login::Clientbound::LoginFinished(p) => { + assert_eq!(p.profile.name, name); + assert_eq!(p.profile.uuid, offline_uuid(name)); + c.send(&login::Serverbound::LoginAcknowledged(Empty).encode()) + .map_err(e)?; + break; + } + login::Clientbound::Disconnect(d) => return Err(d.reason_json), + other => return Err(format!("unexpected login packet {other:?}")), + } + } + c.send(&cfg::Serverbound::ClientInformation(ClientInformation::new(4)).encode()) + .map_err(e)?; + let (mut registries, mut tags, mut features) = (0, 0, 0); + loop { + let (id, payload) = c.recv().map_err(e)?; + match cfg::Clientbound::decode(id, &payload).map_err(e)? { + cfg::Clientbound::SelectKnownPacks(p) => { + assert_eq!(p.packs.len(), 1); + assert_eq!(p.packs[0].id, "core"); + let reply = if known_pack { p.packs } else { Vec::new() }; + c.send( + &cfg::Serverbound::SelectKnownPacks(cfg::SelectKnownPacks { packs: reply }) + .encode(), + ) + .map_err(e)?; + } + cfg::Clientbound::RegistryData(r) => { + registries += 1; + let has_data = r.entries.iter().any(|e| e.data.is_some()); + assert_eq!(has_data, !known_pack, "{}", r.registry); + } + cfg::Clientbound::UpdateTags(t) => tags += t.registries.len(), + cfg::Clientbound::UpdateEnabledFeatures(_) => features += 1, + cfg::Clientbound::FinishConfiguration(_) => { + c.send(&cfg::Serverbound::FinishConfiguration(Empty).encode()) + .map_err(e)?; + break; + } + _ => {} + } + } + assert!(registries >= 28, "registries: {registries}"); + assert!(tags >= 5, "tag registries: {tags}"); + assert_eq!(features, 1); + Ok(Bot { + c, + name: name.into(), + }) +} + +/// Drive the hub like the game loop does until `done` is true. +struct Server { + hub: Hub, + world: World, + next_entity: u32, + placed: Vec<(u32, [i32; 3], u16, i32)>, +} +impl Server { + fn tick(&mut self, entities: &[EntityState]) { + let host = HostState { + uuid: 42, + name: "Host".into(), + entity_id: 1, + position: [0.5, -59.0, 0.5], + yaw: 0.0, + pitch: 0.0, + head_yaw: 0.0, + on_ground: true, + game_mode: 1, + sneaking: false, + sprinting: false, + equipment: Default::default(), + health: 20.0, + }; + let mut ctx = TickCtx { + world: &mut self.world, + host: &host, + entities, + next_entity: &mut self.next_entity, + spawn: [8.5, f64::from(MIN_Y + 5), 8.5], + difficulty: 2, + difficulty_locked: false, + clock_rate: 1.0, + }; + let events = self.hub.tick(&mut ctx); + for event in events { + match event { + HostEvent::Joined(conn) => self.hub.place_new_player(conn, &mut ctx), + HostEvent::Packet(conn, packet) => { + if let S::UseItemOn(p) = *packet { + let at = [p.pos[0], p.pos[1] + 1, p.pos[2]]; + ctx.world + .set(at[0], at[1], at[2], BlockStateId(u32::from(STONE))) + .unwrap(); + self.placed.push((conn, at, STONE, p.sequence)); + self.hub.ack(conn, p.sequence); + } + } + _ => {} + } + } + } +} + +fn server(resources: &Path) -> Server { + let sync = Arc::new(SyncData::load(resources).expect("sync data")); + let lan = Lan::start(sync.clone(), 0, "Test - World".into(), 8).unwrap(); + let biomes: Vec = sync + .dynamic + .registries + .get("minecraft:worldgen/biome") + .map(|v| v.iter().map(|(n, _)| n.clone()).collect()) + .unwrap_or_default(); + let states = vec![ + (Arc::::from("minecraft:air"), false), + (Arc::::from("minecraft:stone"), false), + (Arc::::from("minecraft:chest"), false), + ]; + let encoder = ChunkEncoder::new(states, &sync.builtin, &biomes, &biomes); + let hub = Hub::new( + lan, + sync, + encoder, + HubConfig { + default_game_mode: 1, + guest_commands: true, + force_game_mode: false, + hardcore: false, + view_distance: 3, + simulation_distance: 3, + dimension: "minecraft:overworld".into(), + seed: 1234, + max_players: 8, + }, + ); + Server { + hub, + world: flat_world(), + next_entity: 100, + placed: Vec::new(), + } +} + +/// Tick the server while a bot thread runs. +fn run( + s: &mut Server, + bot: impl FnOnce() -> Result + Send + 'static, +) -> T { + let handle = thread::spawn(bot); + let start = Instant::now(); + while !handle.is_finished() { + s.tick(&[]); + thread::sleep(Duration::from_millis(10)); + assert!(start.elapsed() < Duration::from_secs(40), "timed out"); + } + handle.join().unwrap().unwrap() +} + +#[test] +fn status_and_join() { + let Some(resources) = resources() else { + return; + }; + let mut s = server(&resources); + let port = s.hub.lan.port; + // Server list ping. + let json = run(&mut s, move || { + let mut c = Connection::connect("127.0.0.1", port, Duration::from_secs(5)) + .map_err(|e| e.to_string())?; + c.send( + &handshake::Serverbound::Intention(handshake::Intention { + protocol: PROTOCOL_VERSION, + host: "127.0.0.1".into(), + port, + intent: handshake::STATUS, + }) + .encode(), + ) + .unwrap(); + c.send(&status::Serverbound::StatusRequest(Empty).encode()) + .unwrap(); + let (id, payload) = c.recv().map_err(|e| e.to_string())?; + let status::Clientbound::StatusResponse(r) = + status::Clientbound::decode(id, &payload).map_err(|e| e.to_string())? + else { + return Err("no status".into()); + }; + Ok(r.json) + }); + let v: serde_json::Value = serde_json::from_str(&json).unwrap(); + assert_eq!(v["version"]["protocol"], 777); + assert_eq!(v["description"]["text"], "Test - World"); + + // Join, receive the world, place a block, see another player arrive. + let report = run(&mut s, move || { + let mut bot = connect(port, "Steve", true)?; + let mut chunks = 0; + let (mut login_seen, mut teleported, mut time, mut info) = (false, false, false, false); + let mut commands = false; + let deadline = Instant::now() + Duration::from_secs(15); + let mut sent_loaded = false; + let mut block_update = None; + while Instant::now() < deadline { + match bot.recv_play()? { + C::Login(l) => { + assert_eq!(l.chunk_radius, 3); + assert_eq!(l.spawn.dimension, "minecraft:overworld"); + assert_eq!(l.spawn.game_type, 1); + login_seen = true; + } + C::PlayerPosition(p) => { + assert_eq!(p.position[0], 8.5); + bot.send(S::AcceptTeleportation(play::AcceptTeleportation { + id: p.teleport, + x: p.position[0], + y: p.position[1], + z: p.position[2], + yaw: 0.0, + pitch: 0.0, + })); + teleported = true; + } + C::SetTime(t) => { + assert!(!t.clocks.is_empty()); + time = true; + } + C::PlayerInfoUpdate(u) => { + info |= u.entries.iter().any(|e| e.name.as_deref() == Some("Host")); + } + C::Unknown(id, _) if id == horizon_protocol::ids::play::clientbound::COMMANDS => { + commands = true + } + C::LevelChunkWithLight(l) => { + chunks += 1; + let sections = l.chunk.sections(24, 16, 7).map_err(|e| e.to_string())?; + // The floor is in the lowest section. + assert_eq!(sections[0].states.get(4 * 256), i32::from(STONE)); + assert_eq!(sections[0].non_empty, 256); + assert_eq!(sections[1].non_empty, 0); + assert!(!l.light.sky.is_empty()); + } + C::ChunkBatchFinished(b) => { + assert!(b.size > 0); + bot.send(S::ChunkBatchReceived(play::ChunkBatchReceived { + chunks_per_tick: 20.0, + })); + if !sent_loaded && chunks >= 9 { + bot.send(S::PlayerLoaded(Empty)); + sent_loaded = true; + bot.send(S::MovePlayerPosRot(play::MovePlayerPosRot { + x: 9.5, + y: f64::from(MIN_Y + 5), + z: 9.5, + yaw: 90.0, + pitch: 10.0, + flags: 1, + })); + bot.send(S::UseItemOn(play::UseItemOn { + hand: 0, + pos: [9, MIN_Y + 4, 9], + face: 1, + cursor: [0.5, 1.0, 0.5], + inside: false, + world_border: false, + sequence: 77, + })); + } + } + C::BlockUpdate(u) => { + block_update = Some((u.pos, u.state)); + } + C::BlockChangedAck(a) if a.sequence == 77 && block_update.is_some() => break, + _ => {} + } + } + assert!( + login_seen && teleported && time && info && commands, + "missing login data" + ); + assert!(chunks >= 9, "only {chunks} chunks"); + assert_eq!( + block_update, + Some(([9, MIN_Y + 5, 9], i32::from(STONE))), + "placed block was not broadcast" + ); + Ok(bot.name) + }); + assert_eq!(report, "Steve"); + assert_eq!(s.placed.len(), 1); +} + +#[test] +fn guests_see_each_other_and_the_world_entities() { + let Some(resources) = resources() else { + return; + }; + let mut s = server(&resources); + let port = s.hub.lan.port; + let zombie = EntityState { + id: 500, + uuid: 9, + kind: "minecraft:zombie".into(), + position: [12.0, f64::from(MIN_Y + 5), 12.0], + yaw: 0.0, + pitch: 0.0, + head_yaw: 0.0, + on_ground: true, + velocity: [0.0; 3], + data: 0, + meta: Vec::new(), + equipment: Vec::new(), + send_velocity: false, + }; + let first = thread::spawn(move || { + let mut bot = connect(port, "Alex", false)?; + let mut zombies = 0; + let mut players = 0; + let mut moves = 0; + let deadline = Instant::now() + Duration::from_secs(20); + while Instant::now() < deadline && !(zombies > 0 && players > 0 && moves > 0) { + match bot.recv_play()? { + C::PlayerPosition(p) => { + bot.send(S::AcceptTeleportation(play::AcceptTeleportation { + id: p.teleport, + x: p.position[0], + y: p.position[1], + z: p.position[2], + yaw: 0.0, + pitch: 0.0, + })) + } + C::AddEntity(a) if a.id == 500 => zombies += 1, + C::AddEntity(a) if a.uuid == offline_uuid("Bob") => players += 1, + C::MoveEntityPos(_) | C::MoveEntityPosRot(_) => moves += 1, + _ => {} + } + } + if zombies > 0 && players > 0 && moves > 0 { + Ok(()) + } else { + Err(format!("zombies {zombies} players {players} moves {moves}")) + } + }); + let second = thread::spawn(move || { + thread::sleep(Duration::from_millis(600)); + let mut bot = connect(port, "Bob", true)?; + let deadline = Instant::now() + Duration::from_secs(20); + let mut x = 8.5; + while Instant::now() < deadline { + // Keep reading and walking so the other player sees movement. + bot.c + .reader + .set_read_timeout(Some(Duration::from_millis(200))) + .unwrap(); + if let Ok((id, payload)) = bot.c.recv() + && let Ok(C::PlayerPosition(p)) = C::decode(id, &payload) + { + bot.send(S::AcceptTeleportation(play::AcceptTeleportation { + id: p.teleport, + x: p.position[0], + y: p.position[1], + z: p.position[2], + yaw: 0.0, + pitch: 0.0, + })); + } + x += 0.2; + bot.send(S::MovePlayerPos(play::MovePlayerPos { + x, + y: f64::from(MIN_Y + 5), + z: 8.5, + flags: 1, + })); + } + Ok::<(), String>(()) + }); + let start = Instant::now(); + while !first.is_finished() { + s.tick(std::slice::from_ref(&zombie)); + thread::sleep(Duration::from_millis(10)); + assert!(start.elapsed() < Duration::from_secs(40), "timed out"); + } + first.join().unwrap().unwrap(); + drop(second); +} diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index f90370cf3..6025b1e63 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -567,6 +567,139 @@ packet!(TeleportEntity { on_ground: bool => Bool, }); +packet!(BlockEvent { pos: [i32; 3] => Pos, b0: u8 => UByte, b1: u8 => UByte, block: i32 => VarInt }); +packet!( + /// ClientboundInitializeBorderPacket. + InitializeBorder { + center_x: f64 => Double, + center_z: f64 => Double, + old_size: f64 => Double, + new_size: f64 => Double, + lerp_time: i64 => VarLong, + absolute_max_size: i32 => VarInt, + warning_blocks: i32 => VarInt, + warning_time: i32 => VarInt, + } +); +packet!(TabList { header: Tag => Nbt, footer: Tag => Nbt }); +packet!(ServerData { motd: Tag => Nbt, icon: Option> => Opt }); +packet!( + /// ClientboundUpdateMobEffectPacket; flags: 1 ambient, 2 visible, 4 icon, 8 blend. + UpdateMobEffect { id: i32 => VarInt, effect: i32 => VarInt, amplifier: i32 => VarInt, duration: i32 => VarInt, flags: i8 => Byte } +); +packet!(RemoveMobEffect { id: i32 => VarInt, effect: i32 => VarInt }); +packet!( + /// ClientboundSwingAnimationPacket: hand (0 main, 1 off) and the swing + /// type (0 none, 1 whack, 2 stab) with its duration in ticks. + SwingAnimation { id: i32 => VarInt, hand: i32 => VarInt, kind: i32 => VarInt, duration: i32 => VarInt } +); +packet!(SoundEntity { + sound: (i32, Option<(String, Option)>) => SoundHolder, + source: i32 => VarInt, + id: i32 => VarInt, + volume: f32 => Float, + pitch: f32 => Float, + seed: i64 => Long, +}); +/// One entry of ClientboundCommandsPacket: a literal or an argument node. +#[derive(Clone, Debug, PartialEq)] +pub struct CommandNode { + /// 0 root, 1 literal, 2 argument. + pub kind: u8, + pub executable: bool, + pub restricted: bool, + pub children: Vec, + pub redirect: Option, + pub name: String, + /// Argument parser registry id and its raw property bytes. + pub parser: Option<(i32, Vec)>, + /// Custom suggestion provider (`minecraft:ask_server`). + pub suggestions: Option, +} +/// The command tree: nodes and the index of the root. +#[derive(Clone, Debug, PartialEq)] +pub struct Commands { + pub nodes: Vec, + pub root: i32, +} +impl Codec for Commands { + fn read(r: &mut Reader) -> Result { + let n = r.count(r.remaining())?; + let mut nodes = Vec::with_capacity(n.min(4096)); + for _ in 0..n { + let flags = r.u8()?; + let count = r.count(r.remaining())?; + let children = (0..count).map(|_| r.varint()).collect::>()?; + let redirect = if flags & 8 != 0 { + Some(r.varint()?) + } else { + None + }; + let kind = flags & 3; + let (mut name, mut parser, mut suggestions) = (String::new(), None, None); + if kind >= 1 { + name = r.string(32767)?; + } + if kind == 2 { + // Properties are parser specific; only the property-less parsers + // can be skipped without a table, so keep the rest of the packet. + return Err(crate::Error::new("argument nodes are not decoded")); + } + let _ = (&mut parser, &mut suggestions); + nodes.push(CommandNode { + kind, + executable: flags & 4 != 0, + restricted: flags & 32 != 0, + children, + redirect, + name, + parser, + suggestions, + }); + } + Ok(Self { + nodes, + root: r.varint()?, + }) + } + fn write(v: &Self, w: &mut Writer) { + w.varint(v.nodes.len() as i32); + for n in &v.nodes { + let mut flags = n.kind & 3; + if n.executable { + flags |= 4; + } + if n.redirect.is_some() { + flags |= 8; + } + if n.suggestions.is_some() { + flags |= 16; + } + if n.restricted { + flags |= 32; + } + w.u8(flags); + w.varint(n.children.len() as i32); + n.children.iter().for_each(|c| w.varint(*c)); + if let Some(r) = n.redirect { + w.varint(r); + } + if n.kind >= 1 { + w.string(&n.name); + } + if n.kind == 2 { + let (id, props) = n.parser.clone().unwrap_or((5, Vec::new())); + w.varint(id); + w.bytes(&props); + if let Some(s) = &n.suggestions { + w.string(s); + } + } + } + w.varint(v.root); + } +} + packet_enum!(Clientbound, crate::ids::play::clientbound { BundleDelimiter(Empty) = BUNDLE_DELIMITER, AddEntity(AddEntity) = ADD_ENTITY, @@ -574,11 +707,13 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { BlockChangedAck(BlockChangedAck) = BLOCK_CHANGED_ACK, BlockDestruction(BlockDestruction) = BLOCK_DESTRUCTION, BlockEntityData(BlockEntityData) = BLOCK_ENTITY_DATA, + BlockEvent(BlockEvent) = BLOCK_EVENT, BlockUpdate(BlockUpdate) = BLOCK_UPDATE, ChangeDifficulty(ChangeDifficulty) = CHANGE_DIFFICULTY, ChunkBatchFinished(ChunkBatchFinished) = CHUNK_BATCH_FINISHED, ChunkBatchStart(Empty) = CHUNK_BATCH_START, ClearTitles(Bool1) = CLEAR_TITLES, + Commands(Commands) = COMMANDS, ContainerClose(ContainerClose) = CONTAINER_CLOSE, ContainerSetContent(ContainerSetContent) = CONTAINER_SET_CONTENT, ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA, @@ -592,6 +727,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { GameEvent(GameEvent) = GAME_EVENT, HurtAnimation(HurtAnimation) = HURT_ANIMATION, KeepAlive(KeepAlive) = KEEP_ALIVE, + InitializeBorder(InitializeBorder) = INITIALIZE_BORDER, LevelChunkWithLight(LevelChunkWithLight) = LEVEL_CHUNK_WITH_LIGHT, LevelEvent(LevelEvent) = LEVEL_EVENT, LightUpdate(LightUpdate) = LIGHT_UPDATE, @@ -609,10 +745,12 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { PlayerPosition(PlayerPosition) = PLAYER_POSITION, PlayerRotation(PlayerRotation) = PLAYER_ROTATION, RemoveEntities(RemoveEntities) = REMOVE_ENTITIES, + RemoveMobEffect(RemoveMobEffect) = REMOVE_MOB_EFFECT, ResourcePackPush(ResourcePackPush) = RESOURCE_PACK_PUSH, Respawn(Respawn) = RESPAWN, RotateHead(RotateHead) = ROTATE_HEAD, SectionBlocksUpdate(SectionBlocksUpdate) = SECTION_BLOCKS_UPDATE, + ServerData(ServerData) = SERVER_DATA, SetActionBarText(Text) = SET_ACTION_BAR_TEXT, SetChunkCacheCenter(SetChunkCacheCenter) = SET_CHUNK_CACHE_CENTER, SetChunkCacheRadius(Distance) = SET_CHUNK_CACHE_RADIUS, @@ -631,10 +769,14 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { SetTitleText(Text) = SET_TITLE_TEXT, SetTitlesAnimation(TitlesAnimation) = SET_TITLES_ANIMATION, Sound(Sound) = SOUND, + SoundEntity(SoundEntity) = SOUND_ENTITY, StartConfiguration(Empty) = START_CONFIGURATION, + SwingAnimation(SwingAnimation) = SWING_ANIMATION, SystemChat(SystemChat) = SYSTEM_CHAT, + TabList(TabList) = TAB_LIST, TakeItemEntity(TakeItemEntity) = TAKE_ITEM_ENTITY, TeleportEntity(TeleportEntity) = TELEPORT_ENTITY, + UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT, UpdateTags(UpdateTags) = UPDATE_TAGS, }); packet!(