diff --git a/Cargo.lock b/Cargo.lock index e797c77a1..a9c516955 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -685,6 +685,7 @@ dependencies = [ "glam", "horizon-assets", "horizon-core", + "horizon-protocol", "horizon-world", "png", "pollster", diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 4da5f8513..edd4db819 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -11,6 +11,7 @@ description = "Horizon native development client" horizon-assets = { path = "../horizon-assets" } horizon-core = { path = "../horizon-core" } horizon-world = { path = "../horizon-world" } +horizon-protocol = { path = "../horizon-protocol" } wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl"] } winit = "0.30.13" pollster = "0.4" diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6f6b063aa..43b7c8542 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1,6 +1,7 @@ //! The playable game loop: streaming world, player simulation at 20 ticks/s, //! block interaction, inventory and HUD. mod control; +mod remote; use horizon_client::{ Result, assets::Assets, @@ -77,6 +78,9 @@ struct Options { no_pause: bool, /// Control socket path (`--control`), for `horizon-ctl`. control: Option, + /// Multiplayer: `--server HOST[:PORT]` joins at start; `--name` is the offline player name. + server: Option, + player_name: String, } impl Options { fn read() -> Result> { @@ -106,13 +110,15 @@ impl Options { dimension: None, no_pause: false, control: None, + server: None, + player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()), }; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (tools/prepare_native_client.py)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." + "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (tools/prepare_native_client.py)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." ); return Ok(None); } @@ -145,6 +151,8 @@ impl Options { "--smoke-report" => o.report = Some(value.into()), "--screenshot-after" => o.screenshot_after = Some(value.parse()?), "--world" => o.world = Some(value), + "--server" => o.server = Some(value), + "--name" => o.player_name = value, "--control-socket" => o.control = Some(value.into()), "--time" => o.time = Some(value.parse()?), "--weather" => o.weather = Some(value), @@ -387,6 +395,8 @@ struct Game<'a> { /// Control replies waiting for a rendered frame or a benchmark deadline. pending_screenshot: Option>, pending_bench: Option<(Instant, std::sync::mpsc::Sender)>, + /// Connected to a server: the world comes from the network (game/remote.rs). + remote: Option, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Dim { @@ -1211,7 +1221,7 @@ impl Game<'_> { None } fn spawn_player(&mut self) -> Result<()> { - if self.player.is_some() { + if self.player.is_some() || self.remote.is_some() { return Ok(()); } if let Some((_, target)) = &self.travelling { @@ -1284,6 +1294,9 @@ impl Game<'_> { Ok(()) } fn tick(&mut self) -> Result<()> { + if self.remote.is_some() { + return self.tick_remote(); + } self.ticks += 1; self.world.game_time += 1; self.world.weather.tick(&mut self.world.random); @@ -1566,6 +1579,9 @@ impl Game<'_> { } let atlas_ptr: *const HudAtlas = &self.res.atlas; let _ = atlas_ptr; + if self.remote_overlay(&mut batch) { + return batch; + } if self.player.is_none() { let text = if self.spawn_search > 0 { "Finding a place to spawn..." } else { "Loading terrain..." }; let atlas = &self.res.atlas; @@ -1715,6 +1731,7 @@ impl Game<'_> { } Screen::Playing | Screen::Options => {} } + self.remote_hud(&mut batch); batch } fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) { @@ -1872,6 +1889,9 @@ impl Game<'_> { } } fn close_container(&mut self) { + if self.remote.is_some() { + return self.remote_close_container(); + } let mut returned: Vec = self.carried.take().into_iter().collect(); returned.extend(self.craft_grid.iter_mut().filter_map(Option::take)); for stack in returned { @@ -1892,6 +1912,9 @@ impl Game<'_> { } } fn click_inventory(&mut self, right: bool) { + if self.remote.is_some() { + return self.remote_click(right); + } let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { return }; let batch = HudBatch::new(size); let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return }; @@ -3186,6 +3209,9 @@ impl Game<'_> { Ok(()) } fn close_world(&mut self) -> Result<()> { + if self.remote.is_some() { + return self.leave_server(None); + } self.save_game()?; self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); @@ -4073,6 +4099,9 @@ impl Game<'_> { } } fn save_game(&mut self) -> Result<()> { + if self.remote.is_some() { + return Ok(()); + } let keys: Vec<_> = self.world.modified.drain().collect(); let chunks: Vec<_> = keys .iter() @@ -4211,6 +4240,9 @@ impl Game<'_> { } /// A key press while a world is open (keyboard or control socket). fn key_pressed(&mut self, key: KeyCode) -> Result<()> { + if self.remote.is_some() && self.remote_key(key)? { + return Ok(()); + } match key { KeyCode::Escape => match self.screen { Screen::Options => { @@ -4277,6 +4309,9 @@ impl Game<'_> { } /// A mouse button while playing (window or control socket). fn play_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { + if self.remote.is_some() { + return self.remote_mouse(button, pressed); + } match button { MouseButton::Left => { if pressed && self.attack() { @@ -4308,6 +4343,9 @@ impl Game<'_> { Ok(()) } fn update_world(&mut self) { + if let Err(e) = self.poll_remote() { + eprintln!("Horizon: {e}"); + } if let Some(p) = &self.player { self.streaming.center = ((p.position.x.floor() as i32) >> 4, (p.position.z.floor() as i32) >> 4); } @@ -4453,6 +4491,7 @@ impl ApplicationHandler for Game<'_> { } Action::Play { folder } => self.open_world(&folder, None, None, false)?, Action::Create { folder, name, seed, creative } => self.open_world(&folder, Some(&name), seed, creative)?, + Action::Connect { address } => self.connect_server(&address, &self.options.player_name.clone())?, Action::None => {} } } @@ -4491,6 +4530,7 @@ impl ApplicationHandler for Game<'_> { } } } + Screen::Dead if pressed && self.remote.is_some() => self.remote_respawn(), Screen::Dead if pressed => { self.player = None; self.screen = Screen::Playing; @@ -4516,6 +4556,7 @@ impl ApplicationHandler for Game<'_> { } self.creative_screen.scroll = 0.0; } + WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => self.remote_chat_key(&event), WindowEvent::KeyboardInput { event, .. } if self.title.is_some() => { if event.state == ElementState::Pressed && let Some(title) = self.title.as_mut() @@ -4803,6 +4844,7 @@ pub fn run() -> Result<()> { frame_stats: Default::default(), pending_screenshot: None, pending_bench: None, + remote: None, }; if let Some(path) = &game.options.control { let server = horizon_client::control::Server::start(path) @@ -4811,6 +4853,10 @@ pub fn run() -> Result<()> { game.control = Some(server); } match game.options.world.clone() { + _ if game.options.server.is_some() => { + let (address, name) = (game.options.server.clone().unwrap_or_default(), game.options.player_name.clone()); + game.connect_server(&address, &name)?; + } Some(folder) => { let (seed, creative) = (game.options.seed, game.options.creative); game.open_world(&folder, None, Some(seed), creative)?; diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index f6b2bdcc6..94d0eac1c 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -27,6 +27,10 @@ const HELP: &[&str] = &[ "bench SECONDS reset stats, wait, then reply with the summary", "open WORLD [SEED] [creative] open or create a world from the title screen", "save save the world", + "connect HOST[:PORT] [NAME] join a multiplayer server (offline mode) from the title screen", + "chat MESSAGE send chat or a /command to the server", + "disconnect leave the server for the server list", + "respawn respawn after death on a server", "quit save and exit", ]; @@ -240,6 +244,36 @@ impl Game<'_> { self.open_world(folder, Some(folder), seed, creative)?; ok() } + "connect" => { + if self.title.is_none() { + return Err("leave the current world first".into()); + } + let name = words.get(2).map_or_else(|| self.options.player_name.clone(), |n| (*n).to_owned()); + self.connect_server(arg(1)?, &name)?; + ok() + } + "chat" => { + if self.remote.is_none() { + return Err("not connected to a server".into()); + } + let message = line.trim_start().strip_prefix("chat").unwrap_or("").trim(); + self.send_chat(message); + ok() + } + "respawn" => { + if self.remote.is_none() || self.screen != Screen::Dead { + return Err("respawn needs the death screen on a server".into()); + } + self.remote_respawn(); + ok() + } + "disconnect" => { + if self.remote.is_none() { + return Err("not connected to a server".into()); + } + self.leave_server(None)?; + ok() + } "save" => { self.require_world()?; self.save_game()?; @@ -330,6 +364,7 @@ impl Game<'_> { "meshed_sections": self.streaming.meshed_total, "renderer": renderer, "uptime_seconds": self.started.elapsed().as_secs_f64(), + "server": self.remote_status(), }) } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs new file mode 100644 index 000000000..ac9ecd11d --- /dev/null +++ b/crates/horizon-client/src/game/remote.rs @@ -0,0 +1,1685 @@ +//! Multiplayer: the game driven by a server connection instead of the local +//! simulation. Mirrors vanilla's ClientPacketListener (chunks, entities, +//! inventory, health, time, weather, chat, respawn and dimension changes), +//! LocalPlayer.sendPosition (movement packets) and MultiPlayerGameMode +//! (block breaking with sequence numbers, use-item, attacks, container +//! clicks). The player still moves with the local physics, as the vanilla +//! client predicts its own movement; the server stays authoritative for +//! everything else. +use super::{Dim, Game, Mining, Screen}; +use horizon_client::{ + Result, + chunk::{Blocks, Chunk, Light, MIN_Y, SECTIONS, Section}, + containers::{BlockEntity, Furnace, FurnaceKind}, + entities::{Experience, ItemEntity}, + hud::{HudBatch, rgba}, + items::ItemStack, + mobs::{Anim, Brain, Mob, MobType}, + motion::{MotionWorld, PlayerMotion}, + net::{Event, Session}, + save::SaveDir, + sprint::Keys, + streaming::{ChunkGenerator, Proto, Streaming}, + world::World, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_protocol::{ + entity_data::{ITEM_ENTITY_ITEM, Value}, + item::{Hashed, Stack}, + packets::{ + Empty, + play::{self, Clientbound as C, Serverbound as S}, + }, + registry::{Builtin, DimensionType, Dynamic, ceil_log2}, + text::{Language, format_java, plain}, +}; +use horizon_world::{nbt::Tag, registry::BlockStateId}; +use std::{ + collections::HashMap, + sync::Arc, + time::{Duration, Instant}, +}; +use winit::{event::MouseButton, keyboard::KeyCode}; + +/// Streaming needs a generator; a server world never generates. +struct NoTerrain; +impl ChunkGenerator for NoTerrain { + type Worker = (); + fn worker(&self) {} + fn proto(&self, _: &mut (), _: i32, _: i32) -> Proto { + Box::new(()) + } + fn finish(&self, _: Proto) -> Chunk { + Chunk::empty(0, 0) + } +} + +/// A server entity the client tracks (position as last sent). +struct Tracked { + kind: String, + position: [f64; 3], +} +/// Smooth an entity toward a new position over three ticks (InterpolationHandler). +#[derive(Clone, Copy)] +struct Lerp { + target: [f64; 3], + steps: u32, +} + +pub(super) struct Remote { + pub session: Session, + builtin: Arc, + lang: Arc, + registries: Arc, + joined: bool, + status: String, + entity_id: i32, + dimension: DimensionType, + biome_map: Vec, + biome_bits: u8, + view_distance: i32, + sequence: i32, + last_pos: [f64; 3], + last_rot: (f32, f32), + last_on_ground: bool, + last_collision: bool, + reminder: u32, + last_input: u8, + was_sprinting: bool, + carried: Option, + loaded_sent: bool, + /// Open container: (window id, menu name). + menu: Option<(i32, String)>, + state_id: i32, + use_target: Option<[i32; 3]>, + entities: HashMap, + lerps: HashMap, + /// Item entities waiting for their item data. + pending_items: HashMap, + health: (f32, i32, f32), + game_mode: i32, + pub chat: Vec<(String, Instant)>, + pub chat_input: Option, + action_bar: Option<(String, Instant)>, + players: HashMap, + destroying: Option<([i32; 3], u8, f32)>, + destroy_delay: u32, + placing: Option<([i32; 3], u64)>, + death_message: Option, + player_type: Option>, + /// Inventory as last synchronised, for creative-mode slot updates. + synced: Vec>, + decode_errors: u32, + clock: Option, + clock_rate: f32, +} + +fn face_direction(face: [i32; 3]) -> u8 { + match face { + [0, -1, 0] => 0, + [0, 1, 0] => 1, + [0, 0, -1] => 2, + [0, 0, 1] => 3, + [-1, 0, 0] => 4, + [1, 0, 0] => 5, + _ => 1, + } +} + +impl Game<'_> { + /// Leave the title for a server (ConnectScreen): an empty world fed by the connection. + pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> { + let root = self.options.resources.clone(); + let builtin = Builtin::find(&root) + .and_then(|p| Builtin::load(&p).ok()) + .ok_or("registries.json not found next to the resources; run the data generator reports (tools/prepare_native_client.py)")?; + let lang = Arc::new(horizon_client::net::load_language(&root)); + let view = self.settings.render_distance.clamp(2, 32) as i8; + let session = Session::connect(address, name, view, lang.clone()); + let player_type = horizon_client::mobs::load_model(&root, "minecraft:player#main").map(|model| { + Arc::new(MobType { + id: "minecraft:player".into(), + width: 0.6, + height: 1.8, + eye_height: 1.62, + category: "misc".into(), + max_health: 20.0, + speed: 0.1, + attack_damage: 1.0, + follow_range: 0.0, + step_height: 0.6, + model: Arc::new(model), + texture: "entity/player/wide/steve".into(), + brain: Brain::Passive, + anim: Anim::Humanoid { zombie_arms: false }, + sounds: ["entity.player.hurt", "entity.player.hurt", "entity.player.death"], + }) + }); + let mut streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), self.res.threads); + streaming.remote = true; + streaming.radius = self.settings.render_distance; + self.streaming = streaming; + self.world = World::new(self.res.facts.air, 0); + self.save = Arc::new(SaveDir::new(std::env::temp_dir().join("horizon-remote-unused"))); + self.inventory = vec![None; 36]; + self.armor = [None, None, None, None]; + self.craft_grid = vec![None; 9]; + self.craft_size = 2; + self.player = None; + self.spawn = None; + self.mobs.clear(); + self.arrows.clear(); + self.dropped.clear(); + self.particles.clear(); + self.orbs.clear(); + self.falling.clear(); + self.travelling = None; + self.mining = None; + self.container = None; + self.carried = None; + self.using = None; + self.creative = false; + self.experience = Experience { level: 0, progress: 0.0, total: 0 }; + self.screen = Screen::Playing; + self.title = None; + self.dim = Dim::Overworld; + if let Some(r) = self.renderer.as_mut() { + r.clear_sections(); + } + self.apply_settings(); + self.remote = Some(Remote { + session, + builtin: Arc::new(builtin), + lang, + registries: Arc::new(Dynamic::default()), + joined: false, + status: "Connecting to the server...".into(), + entity_id: 0, + dimension: DimensionType::vanilla("minecraft:overworld"), + biome_map: Vec::new(), + biome_bits: 7, + view_distance: self.settings.render_distance, + sequence: 0, + last_pos: [0.0; 3], + last_rot: (0.0, 0.0), + last_on_ground: false, + last_collision: false, + reminder: 0, + last_input: 0, + was_sprinting: false, + carried: None, + loaded_sent: false, + menu: None, + state_id: 0, + use_target: None, + entities: HashMap::new(), + lerps: HashMap::new(), + pending_items: HashMap::new(), + health: (20.0, 20, 5.0), + game_mode: 0, + chat: Vec::new(), + chat_input: None, + action_bar: None, + players: HashMap::new(), + destroying: None, + destroy_delay: 0, + placing: None, + death_message: None, + player_type, + synced: vec![None; 36], + decode_errors: 0, + clock: None, + clock_rate: 1.0, + }); + Ok(()) + } + + /// Disconnect and return to the multiplayer screen (DisconnectedScreen). + pub(super) fn leave_server(&mut self, reason: Option) -> Result<()> { + if let Some(mut r) = self.remote.take() { + r.session.disconnect(); + } + self.streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), 1); + self.streaming.paused = true; + self.world = World::new(self.res.facts.air, 0); + self.player = None; + self.mobs.clear(); + self.dropped.clear(); + self.particles.clear(); + self.screen = Screen::Playing; + self.container = None; + if let Some(r) = self.renderer.as_mut() { + r.clear_sections(); + } + let saves = std::env::current_dir()?.join("saves"); + let mut title = horizon_client::title::Title::new(saves.clone()); + title.mode = horizon_client::title::Mode::Multiplayer(match reason { + Some(reason) => horizon_client::multiplayer::Screen::Disconnected { reason }, + None => horizon_client::multiplayer::Screen::list(&saves), + }); + self.title = Some(title); + self.capture(false); + Ok(()) + } + + fn send(&self, packet: S) { + if let Some(r) = &self.remote { + r.session.send(packet); + } + } + fn next_sequence(&mut self) -> i32 { + let r = self.remote.as_mut().expect("remote"); + r.sequence += 1; + r.sequence + } + fn item_name(&self, id: i32) -> Arc { + let r = self.remote.as_ref().expect("remote"); + Arc::from(r.builtin.get("minecraft:item").and_then(|i| i.name(id)).unwrap_or("minecraft:air")) + } + fn item_id(&self, name: &str) -> i32 { + let r = self.remote.as_ref().expect("remote"); + r.builtin.get("minecraft:item").and_then(|i| i.id(name)).unwrap_or(0) + } + fn to_stack(&self, s: &Option) -> Option { + let s = s.as_ref()?; + Some(ItemStack { item: self.item_name(s.item), count: s.count.max(0) as u32, damage: s.damage().max(0) as u32 }) + } + fn to_network(&self, s: &Option) -> Option { + let s = s.as_ref()?; + let mut stack = Stack::new(self.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))); + } + Some(stack) + } + fn chat_line(&mut self, text: String) { + eprintln!("[chat] {text}"); + if let Some(r) = self.remote.as_mut() { + r.chat.push((text, Instant::now())); + if r.chat.len() > 100 { + r.chat.remove(0); + } + } + } + + /// Process everything the network thread received (once per frame, like + /// the client's packet processor). + pub(super) fn poll_remote(&mut self) -> Result<()> { + let Some(r) = &self.remote else { return Ok(()) }; + let events = r.session.poll(); + for event in events { + match event { + Event::Status(s) => { + if let Some(r) = self.remote.as_mut() { + r.status = s; + } + } + Event::Joined { registries, name, .. } => { + self.set_registries(registries); + if let Some(r) = self.remote.as_mut() { + r.joined = true; + r.status = format!("Joined as {name}; loading terrain..."); + } + } + Event::Reconfigured(registries) => self.set_registries(registries), + Event::DecodeError(e) => { + if let Some(r) = self.remote.as_mut() { + r.decode_errors += 1; + if r.decode_errors <= 20 { + eprintln!("Horizon: skipped undecodable packet {e}"); + } + } + } + Event::Disconnected(reason) => { + eprintln!("Horizon: disconnected: {reason}"); + return self.leave_server(Some(reason)); + } + Event::Packet(packet) => self.handle_packet(*packet)?, + } + if self.remote.is_none() { + break; + } + } + Ok(()) + } + fn set_registries(&mut self, registries: Arc) { + let biomes: Vec = registries + .registries + .get("minecraft:worldgen/biome") + .map(|list| list.iter().map(|(name, _)| self.res.biomes.id(name)).collect()) + .unwrap_or_default(); + if let Some(r) = self.remote.as_mut() { + r.biome_bits = ceil_log2(biomes.len()); + r.biome_map = biomes; + r.registries = registries; + } + } + /// Switch to a (possibly new) dimension: a fresh client level. + fn enter_remote_dimension(&mut self, spawn: &play::SpawnInfo, keep_world: bool) { + let Some(r) = self.remote.as_mut() else { return }; + let dimension = r.registries.dimension(spawn.dimension_type); + let same = r.dimension.name == dimension.name && keep_world; + r.dimension = dimension; + r.game_mode = spawn.game_type; + r.loaded_sent = false; + self.creative = spawn.game_type == 1; + self.dim = if spawn.dimension == "minecraft:the_nether" { Dim::Nether } else { Dim::Overworld }; + if !same { + let mut streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), self.res.threads); + streaming.remote = true; + streaming.radius = self.streaming.radius; + self.streaming = streaming; + let (time, day, weather) = (self.world.game_time, self.world.day_time, self.world.weather); + self.world = World::new(self.res.facts.air, spawn.seed); + self.world.game_time = time; + self.world.day_time = day; + self.world.weather = weather; + self.mobs.clear(); + self.dropped.clear(); + self.particles.clear(); + if let Some(r) = self.remote.as_mut() { + r.entities.clear(); + r.lerps.clear(); + r.pending_items.clear(); + } + if let Some(renderer) = self.renderer.as_mut() { + renderer.clear_sections(); + } + } + let has_sky = self.remote.as_ref().is_none_or(|r| r.dimension.has_skylight); + self.streaming.sky_light = has_sky; + self.streaming.nether_shading = self.dim == Dim::Nether; + self.player = None; + self.apply_settings(); + } + + /// LevelChunkSection data into the client's fixed -64..320 column. + fn remote_chunk(&self, p: &play::LevelChunkWithLight) -> std::result::Result { + let r = self.remote.as_ref().ok_or("no connection")?; + let sections = p.chunk.sections(r.dimension.sections(), 16, r.biome_bits).map_err(|e| e.to_string())?; + let mut chunk = Chunk::empty(p.x, p.z); + let mut biomes = vec![0u16; chunk.biomes.len()]; + let offset = (r.dimension.min_y - MIN_Y).div_euclid(16); + for (i, s) in sections.iter().enumerate() { + let target = offset + i as i32; + if !(0..SECTIONS as i32).contains(&target) { + continue; + } + let blocks = if s.states.bits == 0 { + Blocks::Uniform(s.states.get(0) as u16) + } else { + let mut a = Box::new([0u16; 4096]); + for (j, v) in a.iter_mut().enumerate() { + *v = s.states.get(j) as u16; + } + Blocks::Full(a) + }; + let mut section = Section { blocks, light: Light::Uniform(0xF0) }; + section.compact(); + chunk.sections[target as usize] = Arc::new(section); + for j in 0..64 { + let biome = r.biome_map.get(s.biomes.get(j) as usize).copied().unwrap_or(0); + if let Some(cell) = biomes.get_mut(target as usize * 64 + j) { + *cell = biome; + } + } + } + // Columns outside the dimension's range take its nearest biome. + let (lo, hi) = (offset.max(0) as usize * 64, ((offset + sections.len() as i32).min(SECTIONS as i32)) as usize * 64); + if lo < hi { + for j in 0..biomes.len() { + if j < lo { + biomes[j] = biomes[lo + j % 16]; + } else if j >= hi { + biomes[j] = biomes[hi - 16 + j % 16]; + } + } + } + chunk.biomes = Arc::new(biomes); + Ok(chunk) + } + /// Keep the renderable block entities (chests, furnaces) in step with blocks. + fn sync_block_entity(&mut self, pos: (i32, i32, i32), state: BlockStateId) { + let name = self.res.facts.get(state).name.clone(); + match BlockEntity::for_block(&name) { + Some(entity) => { + let same = self.world.block_entities.get(&pos).is_some_and(|e| e.id() == entity.id()); + if !same { + self.world.block_entities.insert(pos, entity); + } + } + None => { + self.world.block_entities.remove(&pos); + } + } + } + fn set_block(&mut self, pos: [i32; 3], state: i32) { + let state = BlockStateId(state.max(0) as u32); + if self.world.loaded(pos[0], pos[2]) && self.world.set(pos[0], pos[1], pos[2], state).is_ok() { + self.sync_block_entity((pos[0], pos[1], pos[2]), state); + } + // A block we just placed: play its place sound (the server skips the placer). + if let Some((target, _)) = self.remote.as_ref().and_then(|r| r.placing) + && target == pos + && !self.res.facts.is_air(state) + { + let s = self.res.facts.get(state).sounds.clone(); + let at = [f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5]; + self.audio.play(&s.place, Some(at), (s.volume + 1.0) / 2.0, s.pitch * 0.8); + if let Some(r) = self.remote.as_mut() { + r.placing = None; + } + } + } + fn spawn_entity(&mut self, id: i32, kind: &str, position: [f64; 3], yaw: f32, head: f32) { + let at = Vec3::new(position[0], position[1], position[2]); + let mob_type = if kind == "minecraft:player" { + self.remote.as_ref().and_then(|r| r.player_type.clone()) + } else { + self.res.mob_types.get(kind).cloned() + }; + if let Some(t) = mob_type { + let mut mob = Mob::new(id as u32, t, at, head); + mob.body_yaw = yaw; + mob.previous_body_yaw = yaw; + mob.persistent = true; + self.mobs.retain(|m| m.id != id as u32); + self.mobs.push(mob); + } + if let Some(r) = self.remote.as_mut() { + if kind == "minecraft:item" { + r.pending_items.insert(id, position); + } + r.entities.insert(id, Tracked { kind: kind.to_owned(), position }); + } + } + fn move_entity(&mut self, id: i32, position: [f64; 3], rotation: Option<(f32, f32)>, on_ground: bool) { + if let Some(r) = self.remote.as_mut() { + if let Some(t) = r.entities.get_mut(&id) { + t.position = position; + } + r.lerps.insert(id, Lerp { target: position, steps: 3 }); + if let Some(p) = r.pending_items.get_mut(&id) { + *p = position; + } + } + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { + m.on_ground = on_ground; + if let Some((yaw, pitch)) = rotation { + m.body_yaw = yaw; + m.head_pitch = pitch; + } + } + } + fn remove_entity(&mut self, id: i32) { + self.mobs.retain(|m| m.id != id as u32); + self.dropped.retain(|d| d.id != id as u32); + if let Some(r) = self.remote.as_mut() { + r.entities.remove(&id); + r.lerps.remove(&id); + r.pending_items.remove(&id); + } + } + /// Map a menu slot to Horizon's inventory screen slot ids. + fn menu_slot(menu: &str, slot: i32) -> Option { + let s = usize::try_from(slot).ok()?; + let rows = |n: usize| -> Option { + match s { + _ if s < n * 9 => Some(300 + s), + _ if s < n * 9 + 27 => Some(9 + s - n * 9), + _ if s < n * 9 + 36 => Some(s - n * 9 - 27), + _ => None, + } + }; + match menu { + "inventory" => match s { + 0 => Some(200), + 1..=4 => Some(100 + s - 1), + 5..=8 => Some(500 + s - 5), + 9..=35 => Some(s), + 36..=44 => Some(s - 36), + _ => None, + }, + "minecraft:crafting" => match s { + 0 => Some(200), + 1..=9 => Some(100 + s - 1), + 10..=36 => Some(9 + s - 10), + 37..=45 => Some(s - 37), + _ => None, + }, + "minecraft:furnace" | "minecraft:blast_furnace" | "minecraft:smoker" => match s { + 0..=2 => Some(300 + s), + 3..=29 => Some(9 + s - 3), + 30..=38 => Some(s - 30), + _ => None, + }, + "minecraft:generic_9x1" => rows(1), + "minecraft:generic_9x2" => rows(2), + "minecraft:generic_9x3" | "minecraft:shulker_box" => rows(3), + "minecraft:generic_9x4" => rows(4), + "minecraft:generic_9x5" => rows(5), + "minecraft:generic_9x6" => rows(6), + _ => None, + } + } + fn open_menu_name(&self, container: i32) -> String { + match self.remote.as_ref().and_then(|r| r.menu.as_ref()) { + Some((id, name)) if *id == container && container != 0 => name.clone(), + _ => "inventory".into(), + } + } + fn set_menu_slot(&mut self, container: i32, slot: i32, item: Option) { + let menu = self.open_menu_name(container); + if container != 0 && menu == "inventory" { + return; + } + let Some(internal) = Self::menu_slot(&menu, slot) else { return }; + if internal == 200 { + return; // the result slot is recomputed from the grid + } + *self.slot_mut(internal) = item; + } + + fn handle_packet(&mut self, packet: C) -> Result<()> { + match packet { + C::Login(p) => { + if let Some(r) = self.remote.as_mut() { + r.entity_id = p.player_id; + r.view_distance = p.chunk_radius; + } + self.streaming.radius = self.settings.render_distance.min(p.chunk_radius + 1).max(2); + self.enter_remote_dimension(&p.spawn, false); + self.send(S::ClientInformation(horizon_protocol::packets::configuration::ClientInformation::new(self.settings.render_distance.clamp(2, 32) as i8))); + } + C::Respawn(p) => { + self.enter_remote_dimension(&p.spawn, true); + self.screen = Screen::Playing; + if let Some(r) = self.remote.as_mut() { + r.death_message = None; + r.health = (20.0, 20, 5.0); + } + self.capture(true); + } + C::PlayerPosition(p) => self.remote_teleport(&p)?, + C::PlayerRotation(p) => { + self.yaw = if p.relative_yaw { self.yaw + p.yaw } else { p.yaw }; + self.pitch = (if p.relative_pitch { self.pitch + p.pitch } else { p.pitch }).clamp(-90.0, 90.0); + } + C::LevelChunkWithLight(p) => match self.remote_chunk(&p) { + Ok(chunk) => { + let (x, z) = (p.x, p.z); + self.streaming.insert_remote(&mut self.world, chunk); + self.world.block_entities.retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); + for info in &p.chunk.block_entities { + let pos = (x * 16 + i32::from(info.packed_xz as u8 >> 4), i32::from(info.y), z * 16 + i32::from(info.packed_xz as u8 & 15)); + let state = self.world.block(pos.0, pos.1, pos.2); + self.sync_block_entity(pos, state); + } + } + Err(e) => eprintln!("Horizon: chunk {} {}: {e}", p.x, p.z), + }, + C::ForgetLevelChunk(p) => { + let [x, z] = p.pos; + self.streaming.forget(&mut self.world, x, z); + self.world.block_entities.retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); + if let Some(renderer) = self.renderer.as_mut() { + for sy in 0..SECTIONS as i32 { + renderer.remove((x, sy, z)); + } + } + } + C::ChunkBatchFinished(_) => { + // ChunkBatchSizeCalculator's ceiling; meshing runs on workers. + self.send(S::ChunkBatchReceived(play::ChunkBatchReceived { chunks_per_tick: 64.0 })); + } + C::BlockUpdate(p) => self.set_block(p.pos, p.state), + C::SectionBlocksUpdate(p) => { + let [sx, sy, sz] = p.section; + for change in p.changes { + let local = (change & 0xFFF) as i32; + let pos = [sx * 16 + (local >> 8 & 15), sy * 16 + (local & 15), sz * 16 + (local >> 4 & 15)]; + self.set_block(pos, (change >> 12) as i32); + } + } + C::BlockChangedAck(_) => {} + C::LevelEvent(p) if p.kind == 2001 => { + // LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block. + let state = BlockStateId(p.data.max(0) as u32); + let s = self.res.facts.get(state).sounds.clone(); + let at = [f64::from(p.pos[0]) + 0.5, f64::from(p.pos[1]) + 0.5, f64::from(p.pos[2]) + 0.5]; + self.audio.play(&s.break_sound, Some(at), (s.volume + 1.0) / 2.0, s.pitch * 0.8); + self.destroy_particles(p.pos, state); + } + C::Sound(p) => { + let name = match &p.sound.1 { + Some((location, _)) => Some(location.clone()), + None => self.remote.as_ref().and_then(|r| r.builtin.get("minecraft:sound_event")?.name(p.sound.0).map(str::to_owned)), + }; + if let Some(name) = name { + let at = [f64::from(p.x) / 8.0, f64::from(p.y) / 8.0, f64::from(p.z) / 8.0]; + self.audio.play(&name, Some(at), p.volume, p.pitch); + } + } + C::AddEntity(p) => { + let kind = self.remote.as_ref().and_then(|r| r.builtin.get("minecraft:entity_type")?.name(p.kind).map(str::to_owned)).unwrap_or_default(); + let yaw = horizon_protocol::buf::unpack_degrees(p.yaw); + let head = horizon_protocol::buf::unpack_degrees(p.head_yaw); + self.spawn_entity(p.id, &kind, p.position, yaw, head); + } + C::RemoveEntities(p) => { + for id in p.ids { + self.remove_entity(id); + } + } + C::MoveEntityPos(play::MoveEntityPos(m)) | C::MoveEntityPosRot(play::MoveEntityPosRot(m)) | C::MoveEntityRot(play::MoveEntityRot(m)) => { + let base = self.remote.as_ref().and_then(|r| r.entities.get(&m.id)).map(|t| t.position); + let Some(base) = base else { return Ok(()) }; + let position = m.delta.as_ref().map_or(base, |d| d.end(base)); + let rotation = m.rotation.map(|(y, x)| (horizon_protocol::buf::unpack_degrees(y), horizon_protocol::buf::unpack_degrees(x))); + self.move_entity(m.id, position, rotation, m.on_ground); + } + C::EntityPositionSync(p) => self.move_entity(p.id, p.path.end(), Some((p.yaw, p.pitch)), p.on_ground), + C::TeleportEntity(p) => { + let base = self.remote.as_ref().and_then(|r| r.entities.get(&p.id)).map_or([0.0; 3], |t| t.position); + let rel = |bit: i32, i: usize| if p.relatives & bit != 0 { base[i] + p.position[i] } else { p.position[i] }; + let position = [rel(play::relative::X, 0), rel(play::relative::Y, 1), rel(play::relative::Z, 2)]; + self.move_entity(p.id, position, Some((p.yaw, p.pitch)), p.on_ground); + } + C::RotateHead(p) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + m.yaw = horizon_protocol::buf::unpack_degrees(p.head_yaw); + } + } + C::SetEntityData(p) => { + for (index, _, value) in &p.values { + if *index == ITEM_ENTITY_ITEM + && let Value::Item(stack) = value + { + self.remote_item_data(p.id, stack); + } + } + } + C::TakeItemEntity(p) => { + if self.remote.as_ref().is_some_and(|r| r.entity_id == p.player) + && let Some(eye) = self.eye_position() + { + let pitch = ((self.world.random.next_float() - self.world.random.next_float()) * 0.7 + 1.0) * 2.0; + self.audio.play("minecraft:entity.item.pickup", Some(eye), 0.2, pitch); + } + self.remove_entity(p.item); + } + C::HurtAnimation(p) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + m.hurt_time = 10; + } + } + C::EntityEvent(p) => { + // EntityEvent.DEATH: start the death animation. + if p.event == 3 + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) + { + m.health = 0.0; + } + } + C::Animate(p) if p.action == 0 => {} + C::SetHealth(p) => { + if let Some(r) = self.remote.as_mut() { + r.health = (p.health, p.food, p.saturation); + } + self.apply_remote_health(); + if p.health <= 0.0 && self.screen != Screen::Dead && self.player.is_some() { + self.screen = Screen::Dead; + self.capture(false); + } + } + C::PlayerCombatKill(p) => { + let lang = self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default(); + let message = plain(&p.message, &lang); + if let Some(r) = self.remote.as_mut() { + r.death_message = Some(message); + } + } + C::SetExperience(p) => self.experience = Experience { level: p.level, progress: p.progress, total: p.total }, + C::SetTime(p) => { + self.world.game_time = p.game_time; + let clock = { + let r = self.remote.as_ref(); + let names = r.and_then(|r| r.registries.registries.get("minecraft:world_clock")); + let wanted = r.map(|r| r.dimension.name.clone()).unwrap_or_default(); + p.clocks + .iter() + .find(|c| names.and_then(|n| n.get(c.clock as usize)).is_some_and(|(n, _)| *n == wanted)) + .or_else(|| p.clocks.first()) + .cloned() + }; + if let Some(c) = clock { + self.world.day_time = c.total_ticks; + if let Some(r) = self.remote.as_mut() { + r.clock = Some(c.clock); + r.clock_rate = c.rate; + } + } + } + C::GameEvent(p) => match p.event { + 1 => { + self.world.weather.raining = true; + self.world.weather.rain_level = (0.0, 0.0); + } + 2 => { + self.world.weather.raining = false; + self.world.weather.rain_level = (1.0, 1.0); + } + 3 => { + let mode = p.param as i32; + self.creative = mode == 1; + if let Some(r) = self.remote.as_mut() { + r.game_mode = mode; + } + } + 7 => { + self.world.weather.rain_level = (p.param, p.param); + self.world.weather.raining = p.param > 0.0; + } + 8 => { + self.world.weather.thunder_level = (p.param, p.param); + self.world.weather.thundering = p.param > 0.0; + } + _ => {} + }, + C::PlayerAbilities(p) => self.creative = p.flags & 8 != 0, + C::SetHeldSlot(p) => { + self.selected = p.slot.clamp(0, 8) as usize; + if let Some(r) = self.remote.as_mut() { + r.carried = Some(self.selected); + } + } + C::ContainerSetContent(p) => { + if let Some(r) = self.remote.as_mut() { + r.state_id = p.state; + } + for (slot, item) in p.items.iter().enumerate() { + let stack = self.to_stack(item); + self.set_menu_slot(p.container, slot as i32, stack); + } + self.carried = self.to_stack(&p.carried); + self.remote_synced(); + } + C::ContainerSetSlot(p) => { + if let Some(r) = self.remote.as_mut() { + r.state_id = p.state; + } + let stack = self.to_stack(&p.item); + self.set_menu_slot(p.container, i32::from(p.slot), stack); + self.remote_synced(); + } + C::SetCursorItem(p) => self.carried = self.to_stack(&p.item), + C::SetPlayerInventory(p) => { + let stack = self.to_stack(&p.item); + match p.slot { + 0..=35 => self.inventory[p.slot as usize] = stack, + 36..=39 => self.armor[3 - (p.slot - 36) as usize] = stack, + _ => {} + } + self.remote_synced(); + } + C::ContainerSetData(p) => { + if let Some(key) = self.container + && let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&key) + { + let v = i32::from(p.value); + match p.id { + 0 => f.lit_remaining = v, + 1 => f.lit_total = v, + 2 => f.cooking_timer = v, + 3 => f.cooking_total = v, + _ => {} + } + } + } + C::OpenScreen(p) => self.remote_open_screen(p), + C::ContainerClose(_) => { + if self.screen == Screen::Inventory { + self.remote_close_local(); + self.screen = Screen::Playing; + self.capture(true); + } + } + C::SystemChat(p) => { + let text = plain(&p.content, &self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default()); + if p.overlay { + if let Some(r) = self.remote.as_mut() { + r.action_bar = Some((text, Instant::now())); + } + } else { + self.chat_line(text); + } + } + C::PlayerChat(p) => { + let lang = self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default(); + let content = p.unsigned_content.as_ref().map_or_else(|| p.content.clone(), |t| plain(t, &lang)); + let line = self.format_chat(&p.chat_type, &content); + self.chat_line(line); + } + C::DisguisedChat(p) => { + let lang = self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default(); + let content = plain(&p.message, &lang); + let line = self.format_chat(&p.chat_type, &content); + self.chat_line(line); + } + C::PlayerInfoUpdate(p) => { + if let Some(r) = self.remote.as_mut() { + for e in p.entries { + if let Some(name) = e.name { + r.players.insert(e.uuid, name); + } + } + } + } + C::PlayerInfoRemove(p) => { + if let Some(r) = self.remote.as_mut() { + for u in p.uuids { + r.players.remove(&u); + } + } + } + C::SetChunkCacheRadius(p) => { + self.streaming.radius = self.settings.render_distance.min(p.distance + 1).max(2); + if let Some(r) = self.remote.as_mut() { + r.view_distance = p.distance; + } + } + C::SetActionBarText(p) | C::SetTitleText(p) => { + let lang = self.remote.as_ref().map(|r| r.lang.clone()).unwrap_or_default(); + let text = plain(&p.text, &lang); + if let Some(r) = self.remote.as_mut() { + r.action_bar = Some((text, Instant::now())); + } + } + _ => {} + } + Ok(()) + } + /// ChatType decoration: `chat.translation_key` with sender/content parameters. + fn format_chat(&self, bound: &play::ChatTypeBound, content: &str) -> String { + let Some(r) = self.remote.as_ref() else { return content.to_owned() }; + let sender = plain(&bound.name, &r.lang); + let decoration = r.registries.data("minecraft:chat_type", bound.chat_type).and_then(|t| t.get("chat")); + let key = match decoration.and_then(|d| d.get("translation_key")) { + Some(Tag::String(s)) => s.to_string_lossy(), + _ => "chat.type.text".into(), + }; + let params: Vec = match decoration.and_then(|d| d.get("parameters")) { + Some(Tag::List(list)) => list + .iter() + .map(|p| match p { + Tag::String(s) => match s.to_string_lossy().as_str() { + "sender" => sender.clone(), + "target" => bound.target.as_ref().map(|t| plain(t, &r.lang)).unwrap_or_default(), + _ => content.to_owned(), + }, + _ => String::new(), + }) + .collect(), + _ => vec![sender, content.to_owned()], + }; + let pattern = r.lang.get(&key).cloned().unwrap_or_else(|| "<%s> %s".into()); + format_java(&pattern, ¶ms) + } + fn remote_item_data(&mut self, id: i32, stack: &Option) { + let Some(stack) = self.to_stack(stack) else { return }; + let position = self.remote.as_mut().and_then(|r| r.pending_items.remove(&id)); + if let Some(item) = self.dropped.iter_mut().find(|d| d.id == id as u32) { + item.stack = stack; + return; + } + let Some(p) = position else { return }; + let at = Vec3::new(p[0], p[1], p[2]); + let bob_offset = self.world.random.next_float() * std::f32::consts::PI * 2.0; + self.dropped.push(ItemEntity { + id: id as u32, + stack, + position: at, + previous: at, + velocity: Vec3::ZERO, + on_ground: false, + age: 0, + pickup_delay: 0, + bob_offset, + }); + } + fn apply_remote_health(&mut self) { + let Some((health, food, saturation)) = self.remote.as_ref().map(|r| r.health) else { return }; + if let Some(p) = self.player.as_mut() { + if (p.health.health() - health).abs() > f32::EPSILON { + let _ = p.set_health(health.max(0.0), false); + } + p.health.food.food = food; + p.health.food.saturation = saturation; + } + } + /// ClientPacketListener.handleMovePlayer. + fn remote_teleport(&mut self, p: &play::PlayerPosition) -> Result<()> { + use play::relative as rel; + let current = self.player.as_ref().map(|pl| pl.position).unwrap_or(Vec3::ZERO); + let velocity = self.player.as_ref().map(|pl| pl.velocity).unwrap_or(Vec3::ZERO); + let pick = |bit: i32, base: f64, v: f64| if p.relatives & bit != 0 { base + v } else { v }; + let position = Vec3::new(pick(rel::X, current.x, p.position[0]), pick(rel::Y, current.y, p.position[1]), pick(rel::Z, current.z, p.position[2])); + let yaw = if p.relatives & rel::Y_ROT != 0 { self.yaw + p.yaw } else { p.yaw }; + let pitch = (if p.relatives & rel::X_ROT != 0 { self.pitch + p.pitch } else { p.pitch }).clamp(-90.0, 90.0); + let delta = Vec3::new( + pick(rel::DELTA_X, velocity.x, p.delta[0]), + pick(rel::DELTA_Y, velocity.y, p.delta[1]), + pick(rel::DELTA_Z, velocity.z, p.delta[2]), + ); + match self.player.as_mut() { + Some(player) => { + player.position = position; + player.velocity = delta; + } + None => { + let mut player = PlayerMotion::new(self.motion, position)?; + player.velocity = delta; + self.player = Some(player); + self.eye = 1.62; + self.previous_eye = 1.62; + self.clock.reset(); + self.apply_remote_health(); + } + } + self.previous_position = position; + self.yaw = yaw; + self.pitch = pitch; + if let Some(r) = self.remote.as_mut() { + r.last_pos = [position.x, position.y, position.z]; + r.last_rot = (yaw, pitch); + r.destroying = None; + } + self.mining = None; + self.send(S::AcceptTeleportation(play::AcceptTeleportation { id: p.teleport, x: position.x, y: position.y, z: position.z, yaw, pitch })); + Ok(()) + } + + /// One client tick while connected (Minecraft.tick with a ClientLevel). + pub(super) fn tick_remote(&mut self) -> Result<()> { + self.ticks += 1; + self.world.game_time += 1; + let rate = self.remote.as_ref().map_or(1.0, |r| r.clock_rate); + if rate > 0.0 { + self.world.day_time += rate.round() as i64; + } + // Weather levels drift toward their targets between server updates. + let w = &mut self.world.weather; + w.rain_level.0 = w.rain_level.1; + w.thunder_level.0 = w.thunder_level.1; + if self.use_delay > 0 { + self.use_delay -= 1; + } + self.tick_remote_entities(); + self.tick_hand(); + let facts = &self.res.facts; + let world = &self.world; + self.particles.retain_mut(|p| p.tick(world, |id| facts.states[id as usize].full_collision)); + let Some(player) = self.player.as_mut() else { return Ok(()) }; + let (cx, cz) = ((player.position.x.floor() as i32) >> 4, (player.position.z.floor() as i32) >> 4); + if !self.streaming.is_lit(cx, cz) { + return Ok(()); + } + if self.remote.as_ref().is_some_and(|r| !r.loaded_sent) { + // ClientPacketListener: the level around the player is ready. + self.send(S::PlayerLoaded(Empty)); + if let Some(r) = self.remote.as_mut() { + r.loaded_sent = true; + } + } + let Some(player) = self.player.as_mut() else { return Ok(()) }; + let chatting = self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()); + let playing = self.screen == Screen::Playing && !chatting; + let held = |k| playing && self.keys.contains(&k); + let keys = Keys { + forward: held(KeyCode::KeyW), + backward: held(KeyCode::KeyS), + left: held(KeyCode::KeyA), + right: held(KeyCode::KeyD), + jump: held(KeyCode::Space), + shift: held(KeyCode::ShiftLeft), + sprint: held(KeyCode::ControlLeft), + }; + let input = u8::from(keys.forward) + | u8::from(keys.backward) << 1 + | u8::from(keys.left) << 2 + | u8::from(keys.right) << 3 + | u8::from(keys.jump) << 4 + | u8::from(keys.shift) << 5 + | u8::from(keys.sprint) << 6; + self.previous_position = player.position; + player.yaw = self.yaw; + let dead = self.screen == Screen::Dead; + if !dead { + MotionWorld { player, scene: &mut self.world, assets: &self.res.assets, collision_binding: self.collision, resources: self.motion } + .controlled_simulation_tick(keys)?; + } + let events = std::mem::take(&mut player.events); + self.previous_eye = self.eye; + self.eye += (player.dimensions.eye_height - self.eye) * 0.5; + let crouching = player.pose == horizon_client::pose::Pose::Crouching; + let feet = [player.position.x, player.position.y, player.position.z]; + for event in events { + if let horizon_client::motion::MotionEvent::Emission { state, .. } = event + && !crouching + { + let sounds = self.res.facts.get(state).sounds.clone(); + self.audio.play(&sounds.step, Some(feet), sounds.volume * 0.15, sounds.pitch); + } + } + // The server owns health and hunger: undo local food/fall changes. + self.apply_remote_health(); + if let Some(p) = &self.player { + let (dx, dz) = (p.position.x - self.previous_position.x, p.position.z - self.previous_position.z); + let speed = ((dx * dx + dz * dz).sqrt() as f32).min(0.1); + self.walk.0 = self.walk.1; + self.walk.1 += (dx * dx + dz * dz).sqrt() as f32 * 0.6; + self.bob.0 = self.bob.1; + let target = if p.ground.on_ground { speed } else { 0.0 }; + self.bob.1 += (target - self.bob.1) * 0.4; + } + if !dead { + self.remote_mining(); + if self.right && self.use_delay == 0 && playing { + self.remote_use(); + self.use_delay = 4; + } + } + self.remote_send_state(input); + self.send(S::ClientTickEnd(Empty)); + Ok(()) + } + fn tick_remote_entities(&mut self) { + let Some(r) = self.remote.as_mut() else { return }; + let mut lerps = std::mem::take(&mut r.lerps); + for m in &mut self.mobs { + m.previous = m.position; + m.previous_yaw = m.yaw; + m.previous_body_yaw = m.body_yaw; + m.previous_limb_speed = m.limb_speed; + m.age += 1; + if m.hurt_time > 0 { + m.hurt_time -= 1; + } + if !m.alive() { + m.death_time += 1; + } + if let Some(l) = lerps.get_mut(&(m.id as i32)) + && l.steps > 0 + { + let n = f64::from(l.steps); + m.position = Vec3::new( + m.position.x + (l.target[0] - m.position.x) / n, + m.position.y + (l.target[1] - m.position.y) / n, + m.position.z + (l.target[2] - m.position.z) / n, + ); + l.steps -= 1; + } + // WalkAnimationState.update from the horizontal distance moved. + let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z); + let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0); + m.limb_speed += (target - m.limb_speed) * 0.4; + m.limb_position += m.limb_speed; + } + for d in &mut self.dropped { + d.previous = d.position; + d.age += 1; + if let Some(l) = lerps.get_mut(&(d.id as i32)) + && l.steps > 0 + { + let n = f64::from(l.steps); + d.position = Vec3::new( + d.position.x + (l.target[0] - d.position.x) / n, + d.position.y + (l.target[1] - d.position.y) / n, + d.position.z + (l.target[2] - d.position.z) / n, + ); + l.steps -= 1; + } + } + lerps.retain(|_, l| l.steps > 0); + if let Some(r) = self.remote.as_mut() { + for (id, l) in lerps { + r.lerps.entry(id).or_insert(l); + } + } + } + /// LocalPlayer.sendPosition plus input, sprint and held-slot updates. + fn remote_send_state(&mut self, input: u8) { + let Some(p) = self.player.as_ref() else { return }; + let (pos, on_ground, collision, sprinting) = ([p.position.x, p.position.y, p.position.z], p.ground.on_ground, p.collision.horizontal, p.sprinting); + let (yaw, pitch, selected) = (self.yaw, self.pitch, self.selected); + let Some(r) = self.remote.as_mut() else { return }; + let mut out = Vec::new(); + if r.carried != Some(selected) { + r.carried = Some(selected); + out.push(S::SetCarriedItem(play::SetCarriedItem { slot: selected as i16 })); + } + if input != r.last_input { + r.last_input = input; + out.push(S::PlayerInput(play::PlayerInput { flags: input })); + } + if sprinting != r.was_sprinting { + r.was_sprinting = sprinting; + out.push(S::PlayerCommand(play::PlayerCommand { id: r.entity_id, action: if sprinting { 1 } else { 2 }, data: 0 })); + } + r.reminder += 1; + let d = [pos[0] - r.last_pos[0], pos[1] - r.last_pos[1], pos[2] - r.last_pos[2]]; + let moved = d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 2.0e-4 * 2.0e-4 || r.reminder >= 20; + let rotated = yaw != r.last_rot.0 || pitch != r.last_rot.1; + let flags = u8::from(on_ground) | u8::from(collision) << 1; + let [x, y, z] = pos; + if moved && rotated { + out.push(S::MovePlayerPosRot(play::MovePlayerPosRot { x, y, z, yaw, pitch, flags })); + } else if moved { + out.push(S::MovePlayerPos(play::MovePlayerPos { x, y, z, flags })); + } else if rotated { + out.push(S::MovePlayerRot(play::MovePlayerRot { yaw, pitch, flags })); + } else if r.last_on_ground != on_ground || r.last_collision != collision { + out.push(S::MovePlayerStatus(play::MovePlayerStatus { flags })); + } + if moved { + r.last_pos = pos; + r.reminder = 0; + } + if rotated { + r.last_rot = (yaw, pitch); + } + r.last_on_ground = on_ground; + r.last_collision = collision; + // Creative inventory edits are sent slot by slot (SetCreativeModeSlot). + let mut creative_slots = Vec::new(); + if self.creative { + for i in 0..36 { + if self.inventory[i] != r.synced[i] { + r.synced[i] = self.inventory[i].clone(); + creative_slots.push(i); + } + } + } + for packet in out { + self.send(packet); + } + for i in creative_slots { + let slot = if i < 9 { 36 + i } else { i } as i16; + let item = self.to_network(&self.inventory[i]); + self.send(S::SetCreativeModeSlot(play::SetCreativeModeSlot { slot, item })); + } + } + /// Inventory as the server last described it. + fn remote_synced(&mut self) { + let inventory = self.inventory.clone(); + if let Some(r) = self.remote.as_mut() { + r.synced = inventory; + } + } + + /// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock. + fn remote_mining(&mut self) { + let Some(r) = self.remote.as_mut() else { return }; + if r.destroy_delay > 0 { + r.destroy_delay -= 1; + } + let chatting = r.chat_input.is_some(); + if !self.left || self.screen != Screen::Playing || chatting { + if let Some((pos, _, _)) = r.destroying.take() { + self.send(S::PlayerAction(play::PlayerAction { action: 2, pos, direction: 0, sequence: 0 })); + } + self.mining = None; + return; + } + let Some(hit) = self.pick() else { + self.mining = None; + return; + }; + let face = face_direction(hit.face); + let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + if self.res.facts.is_air(state) { + return; + } + if self.remote.as_ref().is_some_and(|r| r.destroy_delay > 0) { + return; + } + self.swing_arm(); + self.send(S::Punch(Empty)); + if self.creative { + let seq = self.next_sequence(); + self.predict_break(hit.pos, state); + self.send(S::PlayerAction(play::PlayerAction { action: 0, pos: hit.pos, direction: face, sequence: seq })); + if let Some(r) = self.remote.as_mut() { + r.destroy_delay = 5; + } + return; + } + let facts = self.res.facts.get(state).clone(); + let held = self.held().cloned(); + let mut speed = self.res.items.mining_speed(held.as_ref(), &facts.name); + if self.player.as_ref().is_some_and(|p| !p.ground.on_ground) { + speed /= 5.0; + } + let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held.as_ref(), &facts.name); + let progress = if facts.hardness < 0.0 { + 0.0 + } else if facts.hardness == 0.0 { + 1.0 + } else { + speed / facts.hardness / if harvest { 30.0 } else { 100.0 } + }; + let same = self.remote.as_ref().and_then(|r| r.destroying).is_some_and(|(p, _, _)| p == hit.pos); + if !same { + if let Some((old, _, _)) = self.remote.as_mut().and_then(|r| r.destroying.take()) { + self.send(S::PlayerAction(play::PlayerAction { action: 2, pos: old, direction: face, sequence: 0 })); + } + let seq = self.next_sequence(); + self.send(S::PlayerAction(play::PlayerAction { action: 0, pos: hit.pos, direction: face, sequence: seq })); + if progress >= 1.0 { + self.predict_break(hit.pos, state); + if let Some(r) = self.remote.as_mut() { + r.destroy_delay = 5; + } + return; + } + if let Some(r) = self.remote.as_mut() { + r.destroying = Some((hit.pos, face, 0.0)); + } + self.mining = Some(Mining { pos: hit.pos, progress: 0.0, ticks: 0 }); + return; + } + let Some((pos, last_face, done)) = self.remote.as_ref().and_then(|r| r.destroying) else { return }; + let done = done + progress; + let ticks = self.mining.as_ref().map_or(0, |m| m.ticks) + 1; + if ticks % 4 == 1 { + let c = [f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5]; + self.audio.play(&facts.sounds.hit, Some(c), (facts.sounds.volume + 1.0) / 8.0, facts.sounds.pitch * 0.5); + } + self.crack_particle(pos, hit.face, state); + if done >= 1.0 { + let seq = self.next_sequence(); + self.predict_break(pos, state); + self.send(S::PlayerAction(play::PlayerAction { action: 3, pos, direction: face, sequence: seq })); + if let Some(r) = self.remote.as_mut() { + r.destroying = None; + r.destroy_delay = 5; + } + self.mining = None; + } else { + if last_face != face { + self.send(S::PlayerAction(play::PlayerAction { action: 1, pos, direction: face, sequence: 0 })); + } + if let Some(r) = self.remote.as_mut() { + r.destroying = Some((pos, face, done)); + } + self.mining = Some(Mining { pos, progress: done, ticks }); + } + } + /// MultiPlayerGameMode.destroyBlock: the predicted break. + fn predict_break(&mut self, pos: [i32; 3], state: BlockStateId) { + let s = self.res.facts.get(state).sounds.clone(); + let at = [f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, f64::from(pos[2]) + 0.5]; + self.audio.play(&s.break_sound, Some(at), (s.volume + 1.0) / 2.0, s.pitch * 0.8); + self.destroy_particles(pos, state); + let fluid = self.res.facts.get(state).waterlogged; + let air = if fluid { self.world.air } else { self.world.air }; + if self.world.set(pos[0], pos[1], pos[2], air).is_ok() { + self.world.block_entities.remove(&(pos[0], pos[1], pos[2])); + } + self.mining = None; + } + /// Minecraft.startUseItem: use on the targeted block, then the item itself. + fn remote_use(&mut self) { + let held_block = self.held().and_then(|h| self.res.items.get(&h.item)).is_some_and(|i| i.block.is_some()); + let sneaking = self.keys.contains(&KeyCode::ShiftLeft); + // Entities first (interact), like the hit result order. + if let Some((i, _)) = self.mob_hit() { + let id = self.mobs[i].id as i32; + self.send(S::Interact(play::Interact { id, hand: 0, location: [0.0, 1.0, 0.0], secondary: sneaking })); + self.swing_arm(); + return; + } + if let Some(hit) = self.pick() { + let seq = self.next_sequence(); + let cursor = [ + (hit.point[0] - f64::from(hit.pos[0])) as f32, + (hit.point[1] - f64::from(hit.pos[1])) as f32, + (hit.point[2] - f64::from(hit.pos[2])) as f32, + ]; + self.send(S::UseItemOn(play::UseItemOn { + hand: 0, + pos: hit.pos, + face: i32::from(face_direction(hit.face)), + cursor, + inside: hit.face == [0; 3], + world_border: false, + sequence: seq, + })); + let target = [hit.pos[0] + hit.face[0], hit.pos[1] + hit.face[1], hit.pos[2] + hit.face[2]]; + let ticks = self.ticks; + if let Some(r) = self.remote.as_mut() { + r.use_target = Some(hit.pos); + r.placing = Some((target, ticks)); + } + if held_block { + self.swing_arm(); + return; + } + } + if self.held().is_some() { + let seq = self.next_sequence(); + self.send(S::UseItem(play::UseItem { hand: 0, sequence: seq, yaw: self.yaw, pitch: self.pitch })); + } + } + /// Left click: attack the targeted entity (MultiPlayerGameMode.attack). + pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { + if self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()) { + return Ok(()); + } + match button { + MouseButton::Left => { + if pressed && let Some((i, _)) = self.mob_hit() { + let id = self.mobs[i].id as i32; + self.send(S::Attack(play::Attack { id })); + self.send(S::Punch(Empty)); + self.swing_arm(); + return Ok(()); + } + if pressed && self.pick().is_none() { + self.send(S::Punch(Empty)); + self.swing_arm(); + } + self.left = pressed; + } + MouseButton::Right => { + self.right = pressed; + if pressed { + self.remote_use(); + self.use_delay = 4; + } else { + self.send(S::PlayerAction(play::PlayerAction { action: 6, pos: [0; 3], direction: 0, sequence: 0 })); + } + } + MouseButton::Middle if pressed => { + if let Some(hit) = self.pick() { + self.send(S::PickItemFromBlock(play::PickItemFromBlock { pos: hit.pos, include_data: false })); + } + } + _ => {} + } + Ok(()) + } + /// Keys with a multiplayer meaning; returns true when consumed. + pub(super) fn remote_key(&mut self, key: KeyCode) -> Result { + if self.screen != Screen::Playing { + if key == KeyCode::KeyE && self.screen == Screen::Inventory || key == KeyCode::Escape && self.screen == Screen::Inventory { + self.remote_close_container(); + self.screen = Screen::Playing; + self.capture(true); + return Ok(true); + } + return Ok(false); + } + match key { + KeyCode::KeyT | KeyCode::Slash | KeyCode::Enter => { + let text = if key == KeyCode::Slash { "/" } else { "" }; + if let Some(r) = self.remote.as_mut() { + r.chat_input = Some(text.to_owned()); + } + self.keys.clear(); + self.left = false; + self.right = false; + self.capture(false); + Ok(true) + } + KeyCode::KeyQ => { + let all = self.keys.contains(&KeyCode::ControlLeft); + self.send(S::PlayerAction(play::PlayerAction { action: if all { 4 } else { 5 }, pos: [0; 3], direction: 0, sequence: 0 })); + // Inventory.removeFromSelected (prediction). + let slot = &mut self.inventory[self.selected]; + if let Some(s) = slot { + if all || s.count <= 1 { + *slot = None; + } else { + s.count -= 1; + } + } + self.swing_arm(); + Ok(true) + } + KeyCode::KeyE => { + // The inventory opens without telling the server. + self.screen = if self.creative { Screen::Creative } else { Screen::Inventory }; + self.craft_size = 2; + self.capture(false); + Ok(true) + } + _ => Ok(false), + } + } + pub(super) fn remote_chat_open(&self) -> bool { + self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()) + } + /// ChatScreen: typing, Enter to send, Escape to cancel. + pub(super) fn remote_chat_key(&mut self, event: &winit::event::KeyEvent) { + use winit::keyboard::PhysicalKey; + if event.state != winit::event::ElementState::Pressed { + return; + } + let Some(r) = self.remote.as_mut() else { return }; + let Some(input) = r.chat_input.as_mut() else { return }; + match event.physical_key { + PhysicalKey::Code(KeyCode::Escape) => { + r.chat_input = None; + self.capture(true); + } + PhysicalKey::Code(KeyCode::Backspace) => { + input.pop(); + } + PhysicalKey::Code(KeyCode::Enter | KeyCode::NumpadEnter) => { + let message = r.chat_input.take().unwrap_or_default(); + self.send_chat(&message); + self.capture(true); + } + _ => { + if let Some(text) = &event.text { + for c in text.chars().filter(|c| !c.is_control()) { + if input.chars().count() < 256 { + input.push(c); + } + } + } + } + } + } + /// ClientPacketListener.sendChat / sendCommand (unsigned). + pub(super) fn send_chat(&mut self, message: &str) { + let message = message.trim(); + if message.is_empty() { + return; + } + if let Some(command) = message.strip_prefix('/') { + self.send(S::ChatCommand(play::ChatCommand { command: command.to_owned() })); + } else { + let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64); + self.send(S::Chat(play::Chat { + message: message.chars().take(256).collect(), + timestamp, + salt: 0, + signature: None, + last_seen: play::LastSeenUpdate { offset: 0, acknowledged: [0; 3], checksum: 0 }, + })); + } + } + /// A container click: the server answers with the authoritative slots. + pub(super) fn remote_click(&mut self, right: bool) { + let Some(size) = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]) else { return }; + let batch = HudBatch::new(size); + let Some(internal) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return }; + let (container, menu) = match self.remote.as_ref().and_then(|r| r.menu.clone()) { + Some((id, name)) => (id, name), + None => (0, "inventory".to_owned()), + }; + let slot = (0..64).find(|&s| Self::menu_slot(&menu, s) == Some(internal)); + let Some(slot) = slot else { return }; + let shift = self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); + let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s)); + let state = self.remote.as_ref().map_or(0, |r| r.state_id); + self.send(S::ContainerClick(play::ContainerClick { + container, + state, + slot: slot as i16, + button: i8::from(right), + input: if shift { 1 } else { 0 }, + changed: Vec::new(), + carried, + })); + } + pub(super) fn remote_close_container(&mut self) { + let id = self.remote.as_ref().and_then(|r| r.menu.as_ref().map(|m| m.0)).unwrap_or(0); + self.send(S::ContainerClose(play::ContainerClose { container: id })); + self.remote_close_local(); + } + fn remote_close_local(&mut self) { + if let Some(r) = self.remote.as_mut() { + r.menu = None; + } + self.craft_size = 2; + if let Some(key) = self.container.take() { + // Server containers stay renderable but lose their copied slots. + if let Some(entity) = self.world.block_entities.get_mut(&key) { + for s in entity.slots_mut() { + *s = None; + } + } + } + } + /// ClientboundOpenScreenPacket for the menus Horizon draws. + fn remote_open_screen(&mut self, p: play::OpenScreen) { + let menu = self.remote.as_ref().and_then(|r| r.builtin.get("minecraft:menu")?.name(p.menu).map(str::to_owned)).unwrap_or_default(); + let target = self.remote.as_ref().and_then(|r| r.use_target).map(|t| (t[0], t[1], t[2])); + let entity = match menu.as_str() { + "minecraft:crafting" => None, + "minecraft:furnace" | "minecraft:blast_furnace" | "minecraft:smoker" => { + let kind = match menu.as_str() { + "minecraft:blast_furnace" => FurnaceKind::BlastFurnace, + "minecraft:smoker" => FurnaceKind::Smoker, + _ => FurnaceKind::Furnace, + }; + Some(BlockEntity::Furnace(Furnace { + kind, + items: [None, None, None], + lit_remaining: 0, + lit_total: 0, + cooking_timer: 0, + cooking_total: 0, + speed: 1.0, + })) + } + m if m.starts_with("minecraft:generic_9x") || m == "minecraft:shulker_box" => { + let rows = m.strip_prefix("minecraft:generic_9x").and_then(|r| r.parse::().ok()).unwrap_or(3); + Some(BlockEntity::Chest(vec![None; rows * 9])) + } + _ => { + // Unsupported menu: tell the server we closed it. + self.send(S::ContainerClose(play::ContainerClose { container: p.container })); + self.chat_line(format!("(Horizon cannot show {menu} screens yet)")); + return; + } + }; + if let Some(r) = self.remote.as_mut() { + r.menu = Some((p.container, menu.clone())); + } + self.craft_size = if menu == "minecraft:crafting" { 3 } else { 2 }; + self.container = None; + if let Some(entity) = entity { + let key = target.unwrap_or((i32::MIN, 0, 0)); + self.world.block_entities.insert(key, entity); + self.container = Some(key); + } + self.screen = Screen::Inventory; + self.capture(false); + } + pub(super) fn remote_respawn(&mut self) { + self.send(S::ClientCommand(play::ClientCommand { action: 0 })); + } + + /// Connecting / loading screens; true when it covered the frame. + pub(super) fn remote_overlay(&self, batch: &mut HudBatch) -> bool { + let Some(r) = &self.remote else { return false }; + if self.player.is_some() { + return false; + } + let atlas = &self.res.atlas; + let (w, h) = (batch.width, batch.height); + batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255)); + for (i, line) in [r.status.as_str(), r.session.address.as_str()].iter().enumerate() { + let tw = HudBatch::text_width(atlas, line); + batch.text(atlas, line, (w - tw) / 2.0, h / 2.0 - 12.0 + i as f32 * 12.0, if i == 0 { u32::MAX } else { rgba(160, 160, 160, 255) }, true); + } + let _ = r.joined; + true + } + /// Chat (ChatComponent), the chat input line and the action bar. + pub(super) fn remote_hud(&self, batch: &mut HudBatch) { + let Some(r) = &self.remote else { return }; + let atlas = &self.res.atlas; + let (w, h) = (batch.width, batch.height); + let open = r.chat_input.is_some(); + let now = Instant::now(); + let mut y = h - 48.0; + for (text, at) in r.chat.iter().rev().take(if open { 20 } else { 10 }) { + let age = now.duration_since(*at); + // Lines fade out after ten seconds unless the chat is open. + let alpha = if open { 1.0 } else { (1.0 - (age.as_secs_f32() - 9.0).max(0.0)).clamp(0.0, 1.0) }; + if alpha <= 0.0 { + break; + } + let a = (alpha * 255.0) as u8; + batch.fill(atlas, 2.0, y - 1.0, 320.0, 9.0, rgba(0, 0, 0, (alpha * 128.0) as u8)); + batch.text(atlas, text, 4.0, y, rgba(255, 255, 255, a), true); + y -= 9.0; + } + if let Some(input) = &r.chat_input { + batch.fill(atlas, 2.0, h - 14.0, w - 4.0, 12.0, rgba(0, 0, 0, 128)); + let blink = (self.started.elapsed().as_millis() / 300) % 2 == 0; + let shown = if blink { format!("{input}_") } else { input.clone() }; + batch.text(atlas, &shown, 4.0, h - 12.0, rgba(224, 224, 224, 255), true); + } + if let Some((text, at)) = &r.action_bar + && now.duration_since(*at) < Duration::from_secs(3) + { + let tw = HudBatch::text_width(atlas, text); + batch.text(atlas, text, (w - tw) / 2.0, h - 68.0, u32::MAX, true); + } + if self.screen == Screen::Dead + && let Some(message) = &r.death_message + { + let tw = HudBatch::text_width(atlas, message); + batch.text(atlas, message, (w - tw) / 2.0, 85.0, u32::MAX, true); + } + } + /// Status for `horizon-ctl status`. + pub(super) fn remote_status(&self) -> Option { + let r = self.remote.as_ref()?; + Some(serde_json::json!({ + "address": r.session.address, + "name": r.session.name, + "joined": r.joined, + "status": r.status, + "entity_id": r.entity_id, + "dimension": r.dimension.name, + "game_mode": r.game_mode, + "chunks": self.world.chunks.len(), + "entities": r.entities.values().fold(std::collections::BTreeMap::<&str, u32>::new(), |mut m, t| { + *m.entry(t.kind.as_str()).or_default() += 1; + m + }), + "players": r.players.values().collect::>(), + "health": r.health.0, + "food": r.health.1, + "decode_errors": r.decode_errors, + "chat": r.chat.iter().rev().take(10).rev().map(|(t, _)| t.clone()).collect::>(), + })) + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 00265cade..06d32d9f5 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -27,6 +27,8 @@ pub mod mesher; pub mod mobs; pub mod models; pub mod motion; +pub mod multiplayer; +pub mod net; pub mod particles; pub mod pose; pub mod save; diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs new file mode 100644 index 000000000..5072f616f --- /dev/null +++ b/crates/horizon-client/src/multiplayer.rs @@ -0,0 +1,276 @@ +//! Multiplayer screens on the title: the server list (JoinMultiplayerScreen, +//! stored in servers.dat), Add/Edit Server, Direct Connection, and the +//! Disconnected screen. Entries are pinged in the background like +//! ServerStatusPinger to show the MOTD, player count and latency. +use crate::hud::{HudAtlas, HudBatch, rgba}; +use horizon_protocol::servers::{self, ServerEntry}; +use std::{ + collections::HashMap, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, + time::Duration, +}; + +/// The result of pinging one address. +#[derive(Clone, Debug)] +pub enum Ping { + Pinging, + Ok { motd: String, players: String, ms: u128, version: String }, + Failed(String), +} +type Pings = Arc>>; + +#[derive(Clone, Debug)] +pub enum Screen { + List { servers: Vec, selected: Option, pings: Pings }, + /// Add (index None) or edit a server entry. + Edit { index: Option, name: String, address: String, focus: u8 }, + Direct { address: String }, + Disconnected { reason: String }, +} +/// What a click asks the title screen to do. +pub enum Outcome { + None, + Back, + Connect(String), +} +/// A button: x, y, width, label, enabled, id. +pub type ButtonSpec = (f32, f32, f32, String, bool, u8); + +pub fn servers_file(saves: &Path) -> PathBuf { + saves.parent().map_or_else(|| PathBuf::from("servers.dat"), |p| p.join("servers.dat")) +} +fn ping_all(servers: &[ServerEntry], pings: &Pings) { + for s in servers { + let address = s.ip.clone(); + pings.lock().unwrap().insert(address.clone(), Ping::Pinging); + let pings = pings.clone(); + let _ = std::thread::Builder::new().name("horizon-ping".into()).spawn(move || { + let result = match crate::net::ping(&address, Duration::from_secs(5)) { + Ok((json, ms)) => { + let lang = Default::default(); + let motd = crate::net::json_text(&json["description"], &lang); + let players = format!("{}/{}", json["players"]["online"].as_i64().unwrap_or(0), json["players"]["max"].as_i64().unwrap_or(0)); + let version = json["version"]["name"].as_str().unwrap_or("?").to_owned(); + Ping::Ok { motd, players, ms, version } + } + Err(e) => Ping::Failed(e), + }; + pings.lock().unwrap().insert(address, result); + }); + } +} + +impl Screen { + pub fn list(saves: &Path) -> Self { + let servers = servers::load(&servers_file(saves)); + let pings: Pings = Arc::default(); + ping_all(&servers, &pings); + Self::List { servers, selected: None, pings } + } + pub fn buttons(&self, w: f32, h: f32) -> Vec { + let b = |x: f32, y: f32, bw: f32, label: &str, enabled: bool, id: u8| (x, y, bw, label.to_owned(), enabled, id); + match self { + // JoinMultiplayerScreen's two button rows. + Self::List { selected, .. } => vec![ + b(w / 2.0 - 154.0, h - 52.0, 100.0, "Join Server", selected.is_some(), 40), + b(w / 2.0 - 50.0, h - 52.0, 100.0, "Direct Connection", true, 41), + b(w / 2.0 + 54.0, h - 52.0, 100.0, "Add Server", true, 42), + b(w / 2.0 - 154.0, h - 28.0, 74.0, "Edit", selected.is_some(), 43), + b(w / 2.0 - 76.0, h - 28.0, 74.0, "Delete", selected.is_some(), 44), + b(w / 2.0 + 2.0, h - 28.0, 74.0, "Refresh", true, 45), + b(w / 2.0 + 80.0, h - 28.0, 74.0, "Back", true, 46), + ], + Self::Edit { address, .. } => vec![ + b(w / 2.0 - 100.0, h / 4.0 + 96.0 + 18.0, 200.0, "Done", servers::parse_address(address).is_some(), 50), + b(w / 2.0 - 100.0, h / 4.0 + 120.0 + 18.0, 200.0, "Cancel", true, 51), + ], + Self::Direct { address } => vec![ + b(w / 2.0 - 100.0, h / 4.0 + 96.0 + 12.0, 200.0, "Join Server", servers::parse_address(address).is_some(), 52), + b(w / 2.0 - 100.0, h / 4.0 + 120.0 + 12.0, 200.0, "Cancel", true, 53), + ], + Self::Disconnected { .. } => vec![b(w / 2.0 - 100.0, h / 2.0 + 30.0, 200.0, "Back to Server List", true, 54)], + } + } + fn field(atlas: &HudAtlas, batch: &mut HudBatch, label: &str, value: &str, y: f32, focused: bool, blink: bool) { + let w = batch.width; + batch.text(atlas, label, w / 2.0 - 100.0, y, rgba(160, 160, 160, 255), true); + batch.fill(atlas, w / 2.0 - 100.0, y + 11.0, 200.0, 20.0, if focused { u32::MAX } else { rgba(160, 160, 160, 255) }); + batch.fill(atlas, w / 2.0 - 99.0, y + 12.0, 198.0, 18.0, rgba(0, 0, 0, 255)); + let shown = if focused && blink { format!("{value}_") } else { value.to_owned() }; + batch.text(atlas, &shown, w / 2.0 - 96.0, y + 17.0, rgba(224, 224, 224, 255), true); + } + pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool) { + let (w, h) = (batch.width, batch.height); + batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120)); + let centered = |batch: &mut HudBatch, text: &str, y: f32, color: u32| { + let tw = HudBatch::text_width(atlas, text); + batch.text(atlas, text, (w - tw) / 2.0, y, color, true); + }; + match self { + Self::List { servers, selected, pings } => { + centered(batch, "Play Multiplayer", 8.0, u32::MAX); + batch.fill(atlas, 0.0, 32.0, w, h - 32.0 - 64.0, rgba(0, 0, 0, 100)); + let pings = pings.lock().unwrap(); + for (i, server) in servers.iter().enumerate() { + let y = 36.0 + i as f32 * 36.0; + if y + 36.0 > h - 64.0 { + break; + } + let x = w / 2.0 - 152.0; + if *selected == Some(i) { + batch.fill(atlas, x - 2.0, y - 2.0, 306.0, 36.0, rgba(128, 128, 128, 255)); + batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255)); + } + batch.sprite_scaled(atlas, "misc/unknown_server", x, y, 32.0, 32.0, u32::MAX); + batch.text(atlas, &server.name, x + 35.0, y + 1.0, u32::MAX, false); + let (line, right, color) = match pings.get(&server.ip) { + Some(Ping::Ok { motd, players, ms, .. }) => (motd.lines().next().unwrap_or("").to_owned(), format!("{players} {ms} ms"), rgba(128, 128, 128, 255)), + Some(Ping::Failed(_)) => ("Can't connect to server".to_owned(), String::new(), rgba(170, 0, 0, 255)), + _ => ("Pinging...".to_owned(), String::new(), rgba(128, 128, 128, 255)), + }; + batch.text(atlas, &line, x + 35.0, y + 12.0, color, false); + batch.text(atlas, &server.ip, x + 35.0, y + 22.0, rgba(96, 96, 96, 255), false); + if !right.is_empty() { + let tw = HudBatch::text_width(atlas, &right); + batch.text(atlas, &right, x + 300.0 - tw, y + 1.0, rgba(128, 128, 128, 255), false); + } + } + if servers.is_empty() { + centered(batch, "No servers yet: add one or use Direct Connection", h / 2.0 - 20.0, rgba(160, 160, 160, 255)); + } + } + Self::Edit { index, name, address, focus } => { + centered(batch, if index.is_some() { "Edit Server Info" } else { "Add Server" }, 17.0, u32::MAX); + Self::field(atlas, batch, "Server Name", name, 53.0, *focus == 0, blink); + Self::field(atlas, batch, "Server Address", address, 94.0, *focus == 1, blink); + } + Self::Direct { address } => { + centered(batch, "Direct Connection", 20.0, u32::MAX); + Self::field(atlas, batch, "Server Address", address, 100.0 - 11.0, true, blink); + } + Self::Disconnected { reason } => { + centered(batch, "Connection Lost", h / 2.0 - 40.0, rgba(170, 170, 170, 255)); + for (i, line) in wrap(reason, 300.0, atlas).iter().enumerate() { + centered(batch, line, h / 2.0 - 16.0 + i as f32 * 9.0, u32::MAX); + } + } + } + } + pub fn click(&mut self, id: Option, x: f32, y: f32, size: (f32, f32), saves: &Path) -> Outcome { + let (w, h) = size; + match (&mut *self, id) { + (Self::List { servers, selected, .. }, Some(40)) => { + if let Some(s) = selected.and_then(|i| servers.get(i)) { + return Outcome::Connect(s.ip.clone()); + } + } + (Self::List { .. }, Some(41)) => *self = Self::Direct { address: String::new() }, + (Self::List { .. }, Some(42)) => *self = Self::Edit { index: None, name: "Minecraft Server".into(), address: String::new(), focus: 1 }, + (Self::List { servers, selected, .. }, Some(43)) => { + if let Some((i, s)) = selected.and_then(|i| servers.get(i).map(|s| (i, s.clone()))) { + *self = Self::Edit { index: Some(i), name: s.name, address: s.ip, focus: 0 }; + } + } + (Self::List { servers, selected, .. }, Some(44)) => { + if let Some(i) = selected.take() + && i < servers.len() + { + servers.remove(i); + let _ = servers::save(&servers_file(saves), servers); + } + } + (Self::List { .. }, Some(45)) => *self = Self::list(saves), + (Self::List { .. }, Some(46)) => return Outcome::Back, + (Self::List { servers, selected, .. }, None) => { + let index = ((y - 36.0) / 36.0).floor(); + if y >= 36.0 && y < h - 64.0 && (x - w / 2.0).abs() < 154.0 && (index as usize) < servers.len() { + let index = index as usize; + if *selected == Some(index) { + return Outcome::Connect(servers[index].ip.clone()); + } + *selected = Some(index); + } + } + (Self::Edit { index, name, address, .. }, Some(50)) => { + let mut list = servers::load(&servers_file(saves)); + let entry = ServerEntry::new(name.trim(), address.trim()); + match index.and_then(|i| list.get_mut(i)) { + Some(e) => { + e.name = entry.name; + e.ip = entry.ip; + } + None => list.push(entry), + } + let _ = servers::save(&servers_file(saves), &list); + *self = Self::list(saves); + } + (Self::Edit { .. } | Self::Direct { .. } | Self::Disconnected { .. }, Some(51 | 53 | 54)) => *self = Self::list(saves), + (Self::Direct { address }, Some(52)) => return Outcome::Connect(address.trim().to_owned()), + (Self::Edit { focus, .. }, None) => { + for (i, fy) in [(0u8, 53.0 + 11.0), (1, 94.0 + 11.0)] { + if y >= fy && y < fy + 20.0 && (x - w / 2.0).abs() < 100.0 { + *focus = i; + } + } + } + _ => {} + } + Outcome::None + } + fn focused_field(&mut self) -> Option<&mut String> { + match self { + Self::Edit { name, address, focus, .. } => Some(if *focus == 0 { name } else { address }), + Self::Direct { address } => Some(address), + _ => None, + } + } + pub fn type_text(&mut self, text: &str) { + if let Some(field) = self.focused_field() { + for c in text.chars().filter(|c| !c.is_control()) { + if field.chars().count() < 128 { + field.push(c); + } + } + } + } + pub fn backspace(&mut self) { + if let Some(field) = self.focused_field() { + field.pop(); + } + } + pub fn tab(&mut self) { + if let Self::Edit { focus, .. } = self { + *focus = (*focus + 1) % 2; + } + } + /// Escape: back to the list, or out of it (true). + pub fn escape(&mut self, saves: &Path) -> bool { + match self { + Self::List { .. } => true, + _ => { + *self = Self::list(saves); + false + } + } + } +} + +/// Greedy word wrap to a pixel width. +pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec { + let mut lines = Vec::new(); + for paragraph in text.lines() { + let mut line = String::new(); + for word in paragraph.split(' ') { + let candidate = if line.is_empty() { word.to_owned() } else { format!("{line} {word}") }; + if HudBatch::text_width(atlas, &candidate) > width && !line.is_empty() { + lines.push(std::mem::take(&mut line)); + line = word.to_owned(); + } else { + line = candidate; + } + } + lines.push(line); + } + lines +} diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs new file mode 100644 index 000000000..551fdac41 --- /dev/null +++ b/crates/horizon-client/src/net.rs @@ -0,0 +1,295 @@ +//! Multiplayer session: a network thread that connects to a server, logs in +//! (offline mode only), runs the configuration phase and then forwards decoded +//! play packets to the game thread. Keep-alives and pings are answered on the +//! network thread like vanilla's connection handlers so a busy frame never +//! times the client out. Online-mode (authenticated) servers are refused: +//! Horizon never handles Microsoft credentials. +use horizon_protocol::{ + PROTOCOL_VERSION, + connection::{ConnReader, ConnWriter, Connection, Counters}, + crypto::offline_uuid, + packets::{Empty, configuration as cfg, handshake, login, play}, + registry::Dynamic, + servers::parse_address, + text::{Language, plain}, +}; +use std::{ + sync::{ + Arc, Mutex, + mpsc::{Receiver, Sender, channel}, + }, + thread::JoinHandle, + time::Duration, +}; + +/// What the network thread reports to the game. +pub enum Event { + /// Progress text for the connecting screen. + Status(String), + /// Configuration finished: the play state begins with these registries. + Joined { registries: Arc, uuid: u128, name: String }, + Packet(Box), + /// A packet that failed to decode (skipped, like vanilla's skippable packets). + DecodeError(String), + /// The server sent us back to configuration and finished it again. + Reconfigured(Arc), + Disconnected(String), +} + +pub struct Session { + events: Receiver, + writer: Arc>>, + thread: Option>, + pub address: String, + pub name: String, + pub counters: Arc>>>, + /// HORIZON_NET_DEBUG=1 logs every packet sent from the game thread. + debug: bool, +} +impl Session { + /// Start connecting in the background. + pub fn connect(address: &str, name: &str, view_distance: i8, lang: Arc) -> Self { + let (send, events) = channel(); + let writer = Arc::new(Mutex::new(None)); + let counters = Arc::new(Mutex::new(None)); + let (thread_writer, thread_counters) = (writer.clone(), counters.clone()); + let (address_owned, name_owned) = (address.to_owned(), name.to_owned()); + let thread = std::thread::Builder::new() + .name("horizon-net".into()) + .spawn(move || { + let reason = match run(&address_owned, &name_owned, view_distance, &lang, &send, &thread_writer, &thread_counters) { + Ok(reason) => reason, + Err(e) => e, + }; + if let Some(w) = thread_writer.lock().unwrap().take() { + w.shutdown(); + } + let _ = send.send(Event::Disconnected(reason)); + }) + .ok(); + let debug = std::env::var_os("HORIZON_NET_DEBUG").is_some(); + Self { events, writer, thread, address: address.to_owned(), name: name.to_owned(), counters, debug } + } + /// Everything received since the last poll. + pub fn poll(&self) -> Vec { + self.events.try_iter().collect() + } + /// Send a play packet; silently dropped once the connection is gone. + pub fn send(&self, packet: play::Serverbound) { + if self.debug && !matches!(packet, play::Serverbound::ClientTickEnd(_) | play::Serverbound::MovePlayerPos(_) | play::Serverbound::MovePlayerPosRot(_)) { + eprintln!("[net] -> {packet:?}"); + } + if let Some(w) = self.writer.lock().unwrap().as_mut() + && w.send(&packet.encode()).is_err() + { + w.shutdown(); + } + } + pub fn disconnect(&mut self) { + if let Some(w) = self.writer.lock().unwrap().take() { + w.shutdown(); + } + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + } +} +impl Drop for Session { + fn drop(&mut self) { + self.disconnect(); + } +} + +fn status(send: &Sender, text: &str) { + let _ = send.send(Event::Status(text.to_owned())); +} + +/// The whole connection; returns the disconnect reason. +fn run( + address: &str, + name: &str, + view_distance: i8, + lang: &Language, + send: &Sender, + shared_writer: &Mutex>, + shared_counters: &Mutex>>, +) -> Result { + let (host, port) = parse_address(address).ok_or_else(|| format!("Invalid server address: {address}"))?; + status(send, "Connecting to the server..."); + let mut c = Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?; + *shared_counters.lock().unwrap() = Some(c.reader.counters.clone()); + let e = |e: horizon_protocol::Error| e.to_string(); + c.send( + &handshake::Serverbound::Intention(handshake::Intention { protocol: PROTOCOL_VERSION, host: host.clone(), port, intent: handshake::LOGIN }) + .encode(), + ) + .map_err(e)?; + status(send, "Logging in..."); + let uuid = offline_uuid(name); + c.send(&login::Serverbound::Hello(login::ServerHello { name: name.to_owned(), uuid }).encode()).map_err(e)?; + let profile = 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) => { + c.send(&login::Serverbound::LoginAcknowledged(Empty).encode()).map_err(e)?; + break p.profile; + } + login::Clientbound::Disconnect(p) => { + let reason = serde_json::from_str::(&p.reason_json).map(|v| json_text(&v, lang)).unwrap_or(p.reason_json); + return Err(reason); + } + login::Clientbound::Hello(_) => { + return Err("This server is in online mode. Horizon only joins offline-mode servers (online-mode=false).".into()); + } + login::Clientbound::CustomQuery(q) => { + c.send(&login::Serverbound::CustomQueryAnswer(login::CustomQueryAnswer { transaction: q.transaction, payload: None }).encode()) + .map_err(e)?; + } + login::Clientbound::CookieRequest(q) => { + c.send(&login::Serverbound::CookieResponse(login::CookieResponse { key: q.key, payload: None }).encode()).map_err(e)?; + } + login::Clientbound::Unknown(..) => {} + } + }; + status(send, "Joining world..."); + c.send(&cfg::Serverbound::ClientInformation(cfg::ClientInformation::new(view_distance)).encode()).map_err(e)?; + c.send(&cfg::Serverbound::CustomPayload(cfg::CustomPayload { channel: "minecraft:brand".into(), data: brand() }).encode()).map_err(e)?; + let (mut reader, writer) = c.split(); + *shared_writer.lock().unwrap() = Some(writer); + let registries = configure(&mut reader, shared_writer, lang)?; + let _ = send.send(Event::Joined { registries: Arc::new(registries), uuid: profile.uuid, name: profile.name }); + loop { + let (id, payload) = reader.recv().map_err(e)?; + let packet = match play::Clientbound::decode(id, &payload) { + Ok(p) => p, + Err(err) => { + let name = horizon_protocol::ids::name(horizon_protocol::State::Play, horizon_protocol::Direction::Clientbound, id).unwrap_or("?"); + let _ = send.send(Event::DecodeError(format!("{name}: {err}"))); + continue; + } + }; + let reply = |p: play::Serverbound| { + if let Some(w) = shared_writer.lock().unwrap().as_mut() { + let _ = w.send(&p.encode()); + } + }; + match packet { + play::Clientbound::KeepAlive(k) => reply(play::Serverbound::KeepAlive(k)), + play::Clientbound::Ping(p) => reply(play::Serverbound::Pong(p)), + play::Clientbound::BundleDelimiter(_) => {} + play::Clientbound::ResourcePackPush(p) => { + // Declined: Horizon has no server resource packs. + reply(play::Serverbound::ResourcePack(cfg::ResourcePackResponse { id: p.id, action: 1 })); + } + play::Clientbound::StartConfiguration(_) => { + reply(play::Serverbound::ConfigurationAcknowledged(Empty)); + let registries = configure(&mut reader, shared_writer, lang)?; + let _ = send.send(Event::Reconfigured(Arc::new(registries))); + } + play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)), + other => { + if send.send(Event::Packet(Box::new(other))).is_err() { + return Ok("Disconnected".into()); + } + } + } + } +} + +/// The configuration phase: registries, tags and known packs until the +/// server finishes it (ClientConfigurationPacketListenerImpl). +fn configure(reader: &mut ConnReader, writer: &Mutex>, lang: &Language) -> Result { + let mut registries = Dynamic::default(); + let reply = |p: cfg::Serverbound| -> Result<(), String> { + match writer.lock().unwrap().as_mut() { + Some(w) => w.send(&p.encode()).map_err(|e| e.to_string()), + None => Err("Disconnected".into()), + } + }; + loop { + let (id, payload) = reader.recv().map_err(|e| e.to_string())?; + match cfg::Clientbound::decode(id, &payload).map_err(|e| e.to_string())? { + cfg::Clientbound::KeepAlive(k) => reply(cfg::Serverbound::KeepAlive(k))?, + cfg::Clientbound::Ping(p) => reply(cfg::Serverbound::Pong(p))?, + // Know no packs: the server then sends every registry entry in full. + cfg::Clientbound::SelectKnownPacks(_) => reply(cfg::Serverbound::SelectKnownPacks(cfg::SelectKnownPacks { packs: vec![] }))?, + cfg::Clientbound::RegistryData(r) => registries.add(r), + cfg::Clientbound::CodeOfConduct(_) => reply(cfg::Serverbound::AcceptCodeOfConduct(Empty))?, + cfg::Clientbound::ResourcePackPush(p) => reply(cfg::Serverbound::ResourcePack(cfg::ResourcePackResponse { id: p.id, action: 1 }))?, + cfg::Clientbound::CookieRequest(q) => reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse { key: q.key, payload: None }))?, + cfg::Clientbound::Disconnect(d) => return Err(plain(&d.reason, lang)), + cfg::Clientbound::FinishConfiguration(_) => { + reply(cfg::Serverbound::FinishConfiguration(Empty))?; + return Ok(registries); + } + _ => {} + } + } +} + +/// The minecraft:brand payload: a string naming the client. +fn brand() -> Vec { + let mut w = horizon_protocol::buf::Writer::new(); + w.string("horizon"); + w.data +} + +/// Flatten a JSON chat component (login disconnects are JSON). +pub fn json_text(v: &serde_json::Value, lang: &Language) -> String { + match v { + serde_json::Value::String(s) => s.clone(), + serde_json::Value::Array(a) => a.iter().map(|e| json_text(e, lang)).collect(), + serde_json::Value::Object(o) => { + let mut out = if let Some(t) = o.get("text").and_then(|t| t.as_str()) { + t.to_owned() + } else if let Some(key) = o.get("translate").and_then(|t| t.as_str()) { + let args: Vec = o.get("with").and_then(|w| w.as_array()).map(|a| a.iter().map(|e| json_text(e, lang)).collect()).unwrap_or_default(); + let pattern = lang.get(key).cloned().or_else(|| o.get("fallback").and_then(|f| f.as_str()).map(str::to_owned)).unwrap_or_else(|| key.to_owned()); + horizon_protocol::text::format_java(&pattern, &args) + } else { + String::new() + }; + if let Some(extra) = o.get("extra").and_then(|e| e.as_array()) { + for e in extra { + out.push_str(&json_text(e, lang)); + } + } + out + } + other => other.to_string(), + } +} + +/// en_us.json from the prepared resources. +pub fn load_language(resources: &std::path::Path) -> Language { + std::fs::read(resources.join("assets/minecraft/lang/en_us.json")) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() +} + +/// Ask a server for its status (ServerStatusPinger): MOTD, players and the +/// round trip time in milliseconds. +pub fn ping(address: &str, timeout: Duration) -> Result<(serde_json::Value, u128), String> { + use horizon_protocol::packets::status; + let (host, port) = parse_address(address).ok_or("Invalid address")?; + let mut c = Connection::connect(&host, port, timeout).map_err(|e| e.to_string())?; + c.reader.set_read_timeout(Some(timeout)).map_err(|e| e.to_string())?; + let e = |e: horizon_protocol::Error| e.to_string(); + c.send( + &handshake::Serverbound::Intention(handshake::Intention { protocol: PROTOCOL_VERSION, host: host.clone(), port, intent: handshake::STATUS }) + .encode(), + ) + .map_err(e)?; + c.send(&status::Serverbound::StatusRequest(Empty).encode()).map_err(e)?; + let (id, payload) = c.recv().map_err(e)?; + let json = match status::Clientbound::decode(id, &payload).map_err(e)? { + status::Clientbound::StatusResponse(s) => serde_json::from_str(&s.json).map_err(|e| e.to_string())?, + _ => return Err("unexpected status reply".into()), + }; + let start = std::time::Instant::now(); + c.send(&status::Serverbound::PingRequest(status::Ping { time: 1 }).encode()).map_err(e)?; + let _ = c.recv().map_err(e)?; + Ok((json, start.elapsed().as_millis())) +} diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 60e404f76..f7a49b5dd 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -111,6 +111,9 @@ pub struct Streaming { pub nether_shading: bool, pub generated_total: u64, pub meshed_total: u64, + /// Chunks come from a server (`insert_remote`/`forget`): nothing is + /// generated and columns are only unloaded when the server says so. + pub remote: bool, } pub struct WorkerContext { pub assets: Arc, @@ -205,8 +208,31 @@ impl Streaming { nether_shading: false, generated_total: 0, meshed_total: 0, + remote: false, } } + /// A column received from a server: store it and relight it and its neighbours. + pub fn insert_remote(&mut self, world: &mut World, chunk: Chunk) { + let key = (chunk.x, chunk.z); + self.lit.remove(&key); + self.lighting.remove(&key); + world.chunks.insert(key, Arc::new(chunk)); + self.generated_total += 1; + for dz in -1..=1 { + for dx in -1..=1 { + world.dirty_light.insert((key.0 + dx, key.1 + dz)); + } + } + } + /// A column the server unloaded (ClientboundForgetLevelChunkPacket). + pub fn forget(&mut self, world: &mut World, x: i32, z: i32) -> Option> { + self.lit.remove(&(x, z)); + self.meshed.remove(&(x, z)); + self.lighting.remove(&(x, z)); + self.meshing.retain(|k, _| (k.0, k.2) != (x, z)); + world.dirty_sections.retain(|k| (k.0, k.2) != (x, z)); + world.chunks.remove(&(x, z)) + } fn submit(&mut self, priority: i64, job: Job) { self.order += 1; self.shared.queue.lock().unwrap().push(Queued { @@ -316,7 +342,7 @@ impl Streaming { .chunks .keys() .copied() - .filter(|&(x, z)| !self.in_range(x, z, 3)) + .filter(|&(x, z)| !self.remote && !self.in_range(x, z, 3)) .collect(); for key in &far { self.decorated.remove(key); @@ -390,7 +416,7 @@ impl Streaming { } // Generation (load or proto), closest first, bounded in flight. let margin = if self.decorates { 3 } else { 1 }; - if self.generating.len() < workers * 3 { + if !self.remote && self.generating.len() < workers * 3 { let r = self.radius + margin; let mut wanted = Vec::new(); for dz in -r..=r { diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index ba53902ea..430419cca 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -18,6 +18,7 @@ pub enum Mode { Main, Select { worlds: Vec, selected: Option }, Create { name: String, seed: String, creative: bool, focus: u8 }, + Multiplayer(crate::multiplayer::Screen), } #[derive(Clone, Debug, PartialEq)] pub enum Action { @@ -26,6 +27,7 @@ pub enum Action { Options, Play { folder: String }, Create { folder: String, name: String, seed: Option, creative: bool }, + Connect { address: String }, } pub struct Title { pub mode: Mode, @@ -79,7 +81,7 @@ impl Title { let y = h / 4.0 + 48.0; vec![ b(w / 2.0 - 100.0, y, 200.0, "Singleplayer", true, 1), - b(w / 2.0 - 100.0, y + 24.0, 200.0, "Multiplayer", false, 0), + b(w / 2.0 - 100.0, y + 24.0, 200.0, "Multiplayer", true, 4), b(w / 2.0 - 100.0, y + 48.0, 200.0, "Minecraft Realms", false, 0), b(w / 2.0 - 100.0, y + 84.0, 98.0, "Options...", true, 3), b(w / 2.0 + 2.0, y + 84.0, 98.0, "Quit Game", true, 2), @@ -95,6 +97,7 @@ impl Title { b(w / 2.0 - 155.0, h - 28.0, 150.0, "Create New World", true, 21), b(w / 2.0 + 5.0, h - 28.0, 150.0, "Cancel", true, 22), ], + Mode::Multiplayer(screen) => screen.buttons(w, h).into_iter().map(|(x, y, bw, label, enabled, id)| b(x, y, bw, &label, enabled, id)).collect(), } } pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, cursor: (f32, f32)) { @@ -155,6 +158,7 @@ impl Title { batch.text(atlas, &shown, w / 2.0 - 96.0, y + 17.0, rgba(224, 224, 224, 255), true); } } + Mode::Multiplayer(screen) => screen.draw(atlas, batch, (self.started.elapsed().as_millis() / 300) % 2 == 0), } for b in self.buttons(w, h) { let hover = b.enabled && cursor.0 >= b.x && cursor.0 < b.x + b.w && cursor.1 >= b.y && cursor.1 < b.y + 20.0; @@ -193,6 +197,18 @@ impl Title { Action::None } (Mode::Main, Some(2)) => Action::Quit, + (Mode::Main, Some(4)) => { + self.mode = Mode::Multiplayer(crate::multiplayer::Screen::list(&self.saves)); + Action::None + } + (Mode::Multiplayer(screen), hit) => match screen.click(hit, x, y, (w, h), &self.saves) { + crate::multiplayer::Outcome::Back => { + self.mode = Mode::Main; + Action::None + } + crate::multiplayer::Outcome::Connect(address) => Action::Connect { address }, + crate::multiplayer::Outcome::None => Action::None, + }, (Mode::Main, Some(3)) => Action::Options, (Mode::Select { worlds, selected }, Some(10)) => match selected.and_then(|i| worlds.get(i)) { Some(world) => Action::Play { folder: world.folder.clone() }, @@ -254,6 +270,9 @@ impl Title { } } pub fn type_text(&mut self, text: &str) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.type_text(text); + } if let Mode::Create { name, seed, focus, .. } = &mut self.mode { let field = if *focus == 0 { name } else { seed }; for c in text.chars().filter(|c| !c.is_control()) { @@ -264,17 +283,28 @@ impl Title { } } pub fn backspace(&mut self) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.backspace(); + } if let Mode::Create { name, seed, focus, .. } = &mut self.mode { let field = if *focus == 0 { name } else { seed }; field.pop(); } } pub fn tab(&mut self) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.tab(); + } if let Mode::Create { focus, .. } = &mut self.mode { *focus = (*focus + 1) % 2; } } pub fn escape(&mut self) { + if let Mode::Multiplayer(screen) = &mut self.mode + && !screen.escape(&self.saves) + { + return; + } self.mode = match &self.mode { Mode::Create { .. } => Mode::Select { worlds: list_worlds(&self.saves), selected: None }, _ => Mode::Main,