From 7784350bad422fff2741959e5e1698255d3d8251 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:27:15 +0200 Subject: [PATCH 1/5] Play with friends: Invite friends in the pause menu The Horizon pause menu gains "Invite friends" beside Open to LAN. It opens the world to LAN if it isn't (Open to LAN's defaults) and shares that port behind an invite code through the relay; the menu shows the code with Copy and Stop sharing, who is here and why the code changed. Closing the LAN server ends the code; stopping sharing closes LAN again if sharing opened it. `horizon-ctl friends host|stop|status` drives it in harnesses. Without HORIZON_RELAY_URL (the default until a relay is deployed) the button is disabled and says the feature isn't available yet. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/horizon-client/Cargo.toml | 1 + crates/horizon-client/src/front.rs | 114 +++++++++++- crates/horizon-client/src/game.rs | 5 + crates/horizon-client/src/game/control.rs | 4 + crates/horizon-client/src/game/friends.rs | 215 ++++++++++++++++++++++ crates/horizon-client/src/game/lan.rs | 1 + crates/horizon-client/src/game/screens.rs | 12 +- 8 files changed, 350 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-client/src/game/friends.rs diff --git a/Cargo.lock b/Cargo.lock index 18f4db44a..d278339d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1007,6 +1007,7 @@ dependencies = [ "glam", "horizon-assets", "horizon-core", + "horizon-friends", "horizon-protocol", "horizon-telemetry", "horizon-theme", diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 838e56ace..0b9df5a04 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -12,6 +12,7 @@ horizon-assets = { path = "../horizon-assets" } horizon-core = { path = "../horizon-core" } horizon-world = { path = "../horizon-world" } horizon-protocol = { path = "../horizon-protocol" } +horizon-friends = { path = "../horizon-friends" } 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/front.rs b/crates/horizon-client/src/front.rs index 64a27d5ac..4eddbdcdd 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -1018,12 +1018,36 @@ pub fn wrap(ui: &Ui, text: &str, width: f32) -> Vec { /// blurred world, with the game's actions as a page. Ids match /// `game/screens.rs`'s PauseScreen actions: 0 back to game, 1 options, /// 2 save and quit, 3 statistics, 4 advancements, 9 world options. +/// Play with friends as the pause menu shows it (game/friends.rs fills it). +#[derive(Clone, Debug, Default)] +pub struct FriendsView { + /// A singleplayer world (not a server): the button is offered. + pub shown: bool, + /// A relay is configured in this build. + pub available: bool, + pub sharing: bool, + pub code: Option, + /// While there is no code: getting one, or why not. + pub status: String, + /// The players in the world besides the host. + pub guests: Vec, + pub notice: Option, + /// The code was just copied. + pub copied: bool, +} + pub mod pause { use super::*; fn act(a: u8) -> u64 { id("pause", u64::from(a)) } - pub fn draw(ui: &mut Ui, world: &str, quit_label: &str, opened: Instant) { + pub fn draw( + ui: &mut Ui, + world: &str, + quit_label: &str, + opened: Instant, + friends: &FriendsView, + ) { let (w, h) = (ui.w, ui.h); let p = t::ease_out_quint(opened.elapsed().as_secs_f32() / t::move_()); ui.opacity = p; @@ -1065,8 +1089,31 @@ pub mod pause { Kind::Secondary, true, ); + if friends.shown { + let iw = ui.button_width("Invite friends", true); + ui.button( + act(10), + [x + bw + lw + 16.0, y, iw, CONTROL_LARGE], + "Invite friends", + Kind::Secondary, + friends.available && !friends.sharing, + ); + } y += CONTROL_LARGE + 32.0; ui.row_index = 0; + if friends.shown && !friends.available { + ui.text( + Face::Regular, + SMALL, + x, + y - 18.0, + color::FAINT, + "Inviting friends isn't available yet in this build.", + ); + } + if friends.sharing { + y = invite(ui, x, y, cw, friends); + } ui.divider(x, y, cw); let rh = ui.row( x, @@ -1088,6 +1135,65 @@ pub mod pause { ui.opacity = 1.0; ui.offset = (0.0, 0.0); } + /// The invite section while sharing: the code with Copy and Stop + /// sharing, who is here, and what changed. Returns the y below it. + fn invite(ui: &mut Ui, x: f32, mut y: f32, cw: f32, f: &FriendsView) -> f32 { + ui.divider(x, y, cw); + let top = y + 12.0; + ui.text( + Face::Regular, + BODY, + x, + top + 6.0, + color::MUTED, + "Invite code", + ); + let vx = x + t::ROW_LABEL + 16.0; + match &f.code { + Some(code) => { + ui.text_line(Face::Display, 22.0, CONTROL, vx, top, color::TEXT, code); + } + None => { + let status = ui.fit(Face::Regular, BODY, &f.status, cw - t::ROW_LABEL - 220.0); + ui.text_line(Face::Regular, BODY, CONTROL, vx, top, color::MUTED, &status); + } + } + let stop = "Stop sharing"; + let sw = ui.button_width(stop, false); + ui.button( + act(12), + [x + cw - sw, top, sw, CONTROL], + stop, + Kind::Danger, + true, + ); + let copy = if f.copied { "Copied" } else { "Copy" }; + let copy_w = ui.button_width("Copied", false); + ui.button( + act(11), + [x + cw - sw - 8.0 - copy_w, top, copy_w, CONTROL], + copy, + Kind::Secondary, + f.code.is_some(), + ); + y = top + CONTROL + 10.0; + let here = if f.guests.is_empty() { + "No friends here yet.".to_owned() + } else { + format!("Here now: {}", f.guests.join(", ")) + }; + let lines = [ + Some("Friends paste the code in Multiplayer, Join a friend, or on the launcher's Play page.".to_owned()), + Some(here), + f.notice.clone(), + ]; + for line in lines.into_iter().flatten() { + let line = ui.fit(Face::Regular, SMALL, &line, cw); + ui.text(Face::Regular, SMALL, x, y, color::FAINT, &line); + y += (SMALL * 1.45).round(); + } + y + 12.0 + } /// The PauseScreen action under a click, if any. pub fn click( atlas: &HudAtlas, @@ -1096,6 +1202,7 @@ pub mod pause { y: f32, world: &str, quit_label: &str, + friends: &FriendsView, ) -> Option { let mut ui = Ui::dry(atlas, batch, (x, y)); draw( @@ -1103,6 +1210,7 @@ pub mod pause { world, quit_label, Instant::now() - std::time::Duration::from_secs(5), + friends, ); let hit = ui.hit((x, y))?; let nav = id("pause.nav", 0); @@ -1111,7 +1219,9 @@ pub mod pause { h if h == nav + 1 => Some(4), h if h == nav + 2 => Some(3), h if h == nav + 3 => Some(1), - h => [0u8, 1, 2, 3, 4, 9].into_iter().find(|&a| act(a) == h), + h => [0u8, 1, 2, 3, 4, 9, 10, 11, 12] + .into_iter() + .find(|&a| act(a) == h), } } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5e2156f10..3f93b5f4b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -40,6 +40,7 @@ mod fireworks; mod fishing; mod fov; mod frames; +mod friends; mod functions; mod game_mode; mod ghasts; @@ -927,6 +928,8 @@ struct Game<'a> { remote: Option, /// This world is open to the network (game/lan.rs). lan: Option, + /// The open world is shared behind an invite code (game/friends.rs). + friends: Option, world_options: Option, /// KeyboardHandler's debug key state (game/debug_keys.rs), the physical /// keys held, and the debug renderers F3+B and F3+G switch on. @@ -3161,6 +3164,7 @@ impl Game<'_> { }); } horizon_client::spans::time("tick_lan", || self.tick_lan()); + self.tick_friends(); horizon_client::spans::time("tick_hand", || self.tick_hand()); horizon_client::spans::time("tick_sleep", || self.tick_sleep()); horizon_client::spans::time("tick_portal", || self.tick_nether_portal())?; @@ -9446,6 +9450,7 @@ pub fn run() -> Result<()> { remote: None, lan: None, world_options: None, + friends: None, debug_keys: Default::default(), show_hitboxes: false, show_chunk_borders: false, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 61c0cce0a..328e13b27 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -120,6 +120,9 @@ impl Game<'_> { if let Some(value) = self.lan_control(&words)? { return Ok(Some(value)); } + if let Some(value) = self.friends_control(&words)? { + return Ok(Some(value)); + } match self.agent_command(&words, line, reply, event_loop)? { super::agent::Handled::Reply(value) => return Ok(Some(value)), super::agent::Handled::Deferred => return Ok(None), @@ -131,6 +134,7 @@ impl Game<'_> { .chain(super::station_control::HELP) .chain(super::blockctl::HELP) .chain(super::lan::HELP) + .chain(super::friends::HELP) .chain(super::render_control::HELP) .chain(super::sculk::HELP) .chain(super::agent::HELP) diff --git a/crates/horizon-client/src/game/friends.rs b/crates/horizon-client/src/game/friends.rs new file mode 100644 index 000000000..0ccdcfdff --- /dev/null +++ b/crates/horizon-client/src/game/friends.rs @@ -0,0 +1,215 @@ +//! Play with friends, host side: "Invite friends" opens the world to LAN if +//! it isn't (with Open to LAN's defaults) and shares that port behind an +//! invite code through the relay (horizon-friends). The integrated server is +//! the LAN one, unchanged: tunnelled guests are LAN guests that connect from +//! the loopback address. +use super::{Game, lan::LanSettings}; +use horizon_client::{Result, front::FriendsView, text::Text}; +use horizon_friends::{Code, Host, HostConfig, HostEvent, HostState, PathMode}; +use horizon_protocol::{GAME_VERSION, PROTOCOL_VERSION}; +use std::time::{Duration, Instant}; + +pub(super) struct Sharing { + host: Host, + /// Sharing opened the world to LAN, so stopping closes it again. + opened_lan: bool, + code: Option, + /// Wrong codes tried against the current code. + wrong: u32, + notice: Option, + copied: Option, +} + +pub const HELP: &[&str] = &[ + "friends host share the open world behind an invite code (needs HORIZON_RELAY_URL)", + "friends stop stop sharing", + "friends status the code, the relay state and the guests", +]; + +impl Game<'_> { + /// Start sharing the open world. + pub(super) fn friends_start(&mut self) -> Result<()> { + if self.friends.is_some() { + return Ok(()); + } + if self.remote.is_some() || self.title.is_some() { + return Err("open a singleplayer world first".into()); + } + let relay = horizon_friends::relay_url() + .ok_or("inviting friends is not available yet in this build")?; + let opened_lan = self.lan.is_none(); + if opened_lan { + // ShareToLanScreen's defaults, as the world options screen offers them. + self.lan_open(LanSettings { + port: horizon_client::lan::available_port(), + guest_commands: false, + force_game_mode: true, + })?; + } + let port = self.lan_port().ok_or("the world isn't open to LAN")?; + let host = match Host::start(HostConfig { + relay, + lan: std::net::SocketAddr::from(([127, 0, 0, 1], port)), + protocol: PROTOCOL_VERSION, + game: GAME_VERSION.to_owned(), + path: PathMode::from_env(), + }) { + Ok(h) => h, + Err(e) => { + if opened_lan { + self.lan_close(true); + } + return Err(e.into()); + } + }; + self.friends = Some(Sharing { + host, + opened_lan, + code: None, + wrong: 0, + notice: None, + copied: None, + }); + Ok(()) + } + + /// Stop sharing: the code ends; the world closes to LAN again if sharing + /// opened it. + pub(super) fn friends_stop(&mut self) { + let Some(mut sharing) = self.friends.take() else { + return; + }; + sharing.host.stop(); + if sharing.opened_lan { + self.lan_close(true); + } else { + self.system_message(Text::literal("Stopped sharing the invite code.")); + } + } + + /// The LAN server is closing: the code goes with it. + pub(super) fn friends_lan_closed(&mut self) { + if let Some(mut sharing) = self.friends.take() { + sharing.host.stop(); + } + } + + /// New codes and the relay's state, once a tick and while the pause menu + /// is drawn. + pub(super) fn tick_friends(&mut self) { + let Some(sharing) = self.friends.as_mut() else { + return; + }; + let mut announce = None; + for event in sharing.host.poll() { + match event { + HostEvent::Code(code) => { + if sharing.code.is_some() { + sharing.notice = + Some(if sharing.wrong >= horizon_friends::host::MAX_WRONG { + "Someone kept trying a wrong code, so the code changed.".to_owned() + } else { + "The invite service restarted, so the code changed.".to_owned() + }); + } + sharing.wrong = 0; + announce = Some(code.to_string()); + sharing.code = Some(code); + } + HostEvent::WrongCode { count } => { + sharing.wrong = count; + sharing.notice = Some(format!("Someone tried a wrong code ({count} of 5).")); + } + HostEvent::Connected { .. } | HostEvent::Disconnected { .. } => {} + } + } + if let HostState::Retrying(_) = sharing.host.state() { + sharing.code = None; + } + if let Some(code) = announce { + self.system_message(Text::literal(format!( + "Friends can join with the code {code}" + ))); + } + } + + pub(super) fn friends_copy(&mut self) { + let Some(code) = self.friends.as_ref().and_then(|s| s.code.clone()) else { + return; + }; + use horizon_client::clipboard::Clipboard; + self.clipboard.set(&code.to_string()); + if let Some(s) = self.friends.as_mut() { + s.copied = Some(Instant::now()); + } + } + + /// What the pause menu shows. + pub(super) fn friends_view(&self) -> FriendsView { + let guests = self + .lan + .as_ref() + .map(|h| h.hub.guests.iter().map(|g| g.name.clone()).collect()) + .unwrap_or_default(); + let Some(s) = &self.friends else { + return FriendsView { + shown: self.remote.is_none(), + available: horizon_friends::relay_url().is_some(), + ..FriendsView::default() + }; + }; + let status = match s.host.state() { + HostState::Registering => "Getting a code…".to_owned(), + HostState::Retrying(e) => format!("Couldn't reach the invite service; retrying ({e})"), + HostState::Sharing(_) | HostState::Stopped => String::new(), + }; + FriendsView { + shown: true, + available: true, + sharing: true, + code: s.code.as_ref().map(Code::to_string), + status, + guests, + notice: s.notice.clone(), + copied: s + .copied + .is_some_and(|t| t.elapsed() < Duration::from_secs(2)), + } + } + + /// `horizon-ctl friends ...`. + pub(super) fn friends_control(&mut self, words: &[&str]) -> Result> { + use serde_json::json; + if words[0] != "friends" { + return Ok(None); + } + match words.get(1).copied() { + Some("host") => { + self.friends_start()?; + Ok(Some(json!({ "ok": true, "lan_port": self.lan_port() }))) + } + Some("stop") => { + self.friends_stop(); + Ok(Some(json!({ "ok": true }))) + } + Some("status") => { + self.tick_friends(); + let view = self.friends_view(); + let state = self + .friends + .as_ref() + .map(|s| format!("{:?}", s.host.state())); + Ok(Some(json!({ + "available": view.available, + "sharing": view.sharing, + "code": view.code, + "state": state, + "sessions": self.friends.as_ref().map_or(0, |s| s.host.sessions()), + "guests": view.guests, + "lan_port": self.lan_port(), + }))) + } + _ => Err("friends host|stop|status".into()), + } + } +} diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index ed29d0305..1bce62bb8 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -450,6 +450,7 @@ impl Game<'_> { /// IntegratedServer.unpublishServer: the guests are sent away. pub(super) fn lan_close(&mut self, announce: bool) { + self.friends_lan_closed(); let Some(mut host) = self.lan.take() else { return; }; diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 7858cdfe2..91fba4365 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -76,8 +76,10 @@ impl Game<'_> { if horizon_client::ui_theme::horizon() { let opened = *self.pause_since.get_or_insert_with(std::time::Instant::now); let (world, quit) = self.pause_labels(); + self.tick_friends(); + let friends = self.friends_view(); let mut ui = horizon_client::ui_theme::Ui::new(&self.res.atlas, batch, self.cursor); - horizon_client::front::pause::draw(&mut ui, &world, quit, opened); + horizon_client::front::pause::draw(&mut ui, &world, quit, opened, &friends); ui.finish(); return; } @@ -144,6 +146,7 @@ impl Game<'_> { self.cursor.1, &world, quit, + &self.friends_view(), ) } else { pause_buttons(w, h) @@ -163,6 +166,13 @@ impl Game<'_> { Some(3) => self.open_stats(), Some(4) => self.open_advancements(true), Some(9) => self.open_world_options(), + Some(10) => { + if let Err(e) = self.friends_start() { + self.system_message(Text::literal(format!("Couldn't share the world: {e}"))); + } + } + Some(11) => self.friends_copy(), + Some(12) => self.friends_stop(), Some(2) => self.close_world()?, _ => {} } From 21a70c8e97b606bf791a6e79b244b23e37d3883f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:45:53 +0200 Subject: [PATCH 2/5] LAN: a guest's entity id no longer takes the host's Hub::admit read the entity counter before incrementing it, while the game increments first (the current value is the last id in use). The first guest after Open to LAN got the host's own entity id, so its client took the host's AddEntity for itself and never showed the host. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/lan/hub.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 6811eb129..2486fd1a5 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -420,8 +420,10 @@ impl Hub { } fn admit(&mut self, j: super::Joined, ctx: &mut TickCtx) -> u32 { - let entity_id = *ctx.next_entity as i32; + // The game's ids are taken by incrementing first: the current value + // is the last id in use (the host's own, right after opening to LAN). *ctx.next_entity += 1; + let entity_id = *ctx.next_entity as i32; let conn = j.conn; let mut guest = Guest::new(j, entity_id, ctx.spawn, self.config.view_distance); guest.last_action_tick = self.ticks; From 241dee2649b601ebb43326345cd0ea85b845f55a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:45:53 +0200 Subject: [PATCH 3/5] Invite friends: count direct and relayed sessions in friends status Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/friends.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/friends.rs b/crates/horizon-client/src/game/friends.rs index 0ccdcfdff..57a2c09de 100644 --- a/crates/horizon-client/src/game/friends.rs +++ b/crates/horizon-client/src/game/friends.rs @@ -16,6 +16,8 @@ pub(super) struct Sharing { code: Option, /// Wrong codes tried against the current code. wrong: u32, + /// Sessions carried directly and through the relay so far. + paths: (u32, u32), notice: Option, copied: Option, } @@ -67,6 +69,7 @@ impl Game<'_> { opened_lan, code: None, wrong: 0, + paths: (0, 0), notice: None, copied: None, }); @@ -120,7 +123,9 @@ impl Game<'_> { sharing.wrong = count; sharing.notice = Some(format!("Someone tried a wrong code ({count} of 5).")); } - HostEvent::Connected { .. } | HostEvent::Disconnected { .. } => {} + HostEvent::Connected { direct: true, .. } => sharing.paths.0 += 1, + HostEvent::Connected { direct: false, .. } => sharing.paths.1 += 1, + HostEvent::Disconnected { .. } => {} } } if let HostState::Retrying(_) = sharing.host.state() { @@ -205,6 +210,8 @@ impl Game<'_> { "code": view.code, "state": state, "sessions": self.friends.as_ref().map_or(0, |s| s.host.sessions()), + "direct": self.friends.as_ref().map_or(0, |s| s.paths.0), + "relayed": self.friends.as_ref().map_or(0, |s| s.paths.1), "guests": view.guests, "lan_port": self.lan_port(), }))) From 872e77e19bdf6af8c58a3b1c269ba0e8344fc206 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:03:18 +0200 Subject: [PATCH 4/5] Invite friends: who is here and notices read in the muted colour, the hint stays faint Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/front.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index 4eddbdcdd..ffe0b1ace 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -1182,14 +1182,16 @@ pub mod pause { } else { format!("Here now: {}", f.guests.join(", ")) }; + let hint = + "Friends paste the code in Multiplayer, Join a friend, or on the launcher's Play page."; let lines = [ - Some("Friends paste the code in Multiplayer, Join a friend, or on the launcher's Play page.".to_owned()), - Some(here), - f.notice.clone(), + Some((here, color::MUTED)), + f.notice.clone().map(|n| (n, color::MUTED)), + Some((hint.to_owned(), color::FAINT)), ]; - for line in lines.into_iter().flatten() { + for (line, tint) in lines.into_iter().flatten() { let line = ui.fit(Face::Regular, SMALL, &line, cw); - ui.text(Face::Regular, SMALL, x, y, color::FAINT, &line); + ui.text(Face::Regular, SMALL, x, y, tint, &line); y += (SMALL * 1.45).round(); } y + 12.0 From 7a475a948cd934373cdfc4326155efac2b69dba8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:34:10 +0200 Subject: [PATCH 5/5] Invite friends works with no relay: the code, and what friends can expect Sharing no longer needs a relay. The panel shows the full invite code in groups (monospace, wrapped) with Copy and Stop sharing, then who can join: friends anywhere when the router opened the port or this computer has a public address; otherwise what to do (UPnP, the port to forward and the LAN address, a relay, a VPN; CGNAT called out) with a link to the troubleshooting docs. A relay set in horizon.txt (friendsRelay) or HORIZON_RELAY_URL adds its short code. horizon.txt keeps other lines when the menu style is saved. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/front.rs | 87 +++++++++---- crates/horizon-client/src/game/friends.rs | 141 ++++++++++++++-------- crates/horizon-client/src/ui_theme.rs | 25 +++- 3 files changed, 176 insertions(+), 77 deletions(-) diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index ffe0b1ace..cc6237ead 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -1023,12 +1023,15 @@ pub fn wrap(ui: &Ui, text: &str, width: f32) -> Vec { pub struct FriendsView { /// A singleplayer world (not a server): the button is offered. pub shown: bool, - /// A relay is configured in this build. - pub available: bool, pub sharing: bool, pub code: Option, - /// While there is no code: getting one, or why not. + /// Who can join and what to do when friends on the internet can't (or, + /// before the code, what the game is doing). pub status: String, + /// Friends on the internet can reach the host. + pub reachable: bool, + /// Where the troubleshooting is, when they can't. + pub help: Option, /// The players in the world besides the host. pub guests: Vec, pub notice: Option, @@ -1096,21 +1099,11 @@ pub mod pause { [x + bw + lw + 16.0, y, iw, CONTROL_LARGE], "Invite friends", Kind::Secondary, - friends.available && !friends.sharing, + !friends.sharing, ); } y += CONTROL_LARGE + 32.0; ui.row_index = 0; - if friends.shown && !friends.available { - ui.text( - Face::Regular, - SMALL, - x, - y - 18.0, - color::FAINT, - "Inviting friends isn't available yet in this build.", - ); - } if friends.sharing { y = invite(ui, x, y, cw, friends); } @@ -1137,6 +1130,20 @@ pub mod pause { } /// The invite section while sharing: the code with Copy and Stop /// sharing, who is here, and what changed. Returns the y below it. + /// The code's groups packed into lines of at most `width`. + fn code_lines(ui: &Ui, code: &str, width: f32) -> Vec { + let mut lines: Vec = Vec::new(); + for group in code.split('-') { + match lines.last_mut() { + Some(l) if ui.measure(Face::Mono, BODY, &format!("{l}-{group}")) <= width => { + l.push('-'); + l.push_str(group); + } + _ => lines.push(group.to_owned()), + } + } + lines + } fn invite(ui: &mut Ui, x: f32, mut y: f32, cw: f32, f: &FriendsView) -> f32 { ui.divider(x, y, cw); let top = y + 12.0; @@ -1149,15 +1156,6 @@ pub mod pause { "Invite code", ); let vx = x + t::ROW_LABEL + 16.0; - match &f.code { - Some(code) => { - ui.text_line(Face::Display, 22.0, CONTROL, vx, top, color::TEXT, code); - } - None => { - let status = ui.fit(Face::Regular, BODY, &f.status, cw - t::ROW_LABEL - 220.0); - ui.text_line(Face::Regular, BODY, CONTROL, vx, top, color::MUTED, &status); - } - } let stop = "Stop sharing"; let sw = ui.button_width(stop, false); ui.button( @@ -1169,14 +1167,51 @@ pub mod pause { ); let copy = if f.copied { "Copied" } else { "Copy" }; let copy_w = ui.button_width("Copied", false); + let buttons = sw + 8.0 + copy_w; ui.button( act(11), - [x + cw - sw - 8.0 - copy_w, top, copy_w, CONTROL], + [x + cw - buttons, top, copy_w, CONTROL], copy, Kind::Secondary, f.code.is_some(), ); - y = top + CONTROL + 10.0; + let line = (BODY * 1.45).round(); + let value_w = (cw - t::ROW_LABEL - 16.0 - buttons - 16.0).max(120.0); + y = top + 6.0; + match &f.code { + Some(code) => { + for l in code_lines(ui, code, value_w) { + ui.text(Face::Mono, BODY, vx, y, color::TEXT, &l); + y += line; + } + } + None => { + for l in wrap(ui, &f.status, value_w) { + ui.text(Face::Regular, BODY, vx, y, color::MUTED, &l); + y += line; + } + } + } + y = y.max(top + CONTROL) + 10.0; + let small = (SMALL * 1.45).round(); + if f.code.is_some() { + // Who can join: plain when friends anywhere can, in the text + // colour (it asks for something) when only the LAN and VPNs can. + let tint = if f.reachable { + color::MUTED + } else { + color::TEXT + }; + for l in wrap(ui, &f.status, cw) { + ui.text(Face::Regular, SMALL, x, y, tint, &l); + y += small; + } + if let Some(help) = &f.help { + let l = ui.fit(Face::Regular, SMALL, &format!("Help: {help}"), cw); + ui.text(Face::Regular, SMALL, x, y, color::FAINT, &l); + y += small; + } + } let here = if f.guests.is_empty() { "No friends here yet.".to_owned() } else { @@ -1192,7 +1227,7 @@ pub mod pause { for (line, tint) in lines.into_iter().flatten() { let line = ui.fit(Face::Regular, SMALL, &line, cw); ui.text(Face::Regular, SMALL, x, y, tint, &line); - y += (SMALL * 1.45).round(); + y += small; } y + 12.0 } diff --git a/crates/horizon-client/src/game/friends.rs b/crates/horizon-client/src/game/friends.rs index 57a2c09de..90e5b82a2 100644 --- a/crates/horizon-client/src/game/friends.rs +++ b/crates/horizon-client/src/game/friends.rs @@ -1,11 +1,13 @@ //! Play with friends, host side: "Invite friends" opens the world to LAN if //! it isn't (with Open to LAN's defaults) and shares that port behind an -//! invite code through the relay (horizon-friends). The integrated server is -//! the LAN one, unchanged: tunnelled guests are LAN guests that connect from -//! the loopback address. +//! invite code (horizon-friends). The code holds this computer's addresses +//! and the key, so friends join with no server of ours; a relay the player +//! configured adds a short code and a fallback. The integrated server is the +//! LAN one, unchanged: tunnelled guests are LAN guests that connect from the +//! loopback address. use super::{Game, lan::LanSettings}; use horizon_client::{Result, front::FriendsView, text::Text}; -use horizon_friends::{Code, Host, HostConfig, HostEvent, HostState, PathMode}; +use horizon_friends::{Host, HostConfig, HostEvent, PathMode, host::DEFAULT_PORT, reach, stun}; use horizon_protocol::{GAME_VERSION, PROTOCOL_VERSION}; use std::time::{Duration, Instant}; @@ -13,21 +15,46 @@ pub(super) struct Sharing { host: Host, /// Sharing opened the world to LAN, so stopping closes it again. opened_lan: bool, - code: Option, - /// Wrong codes tried against the current code. + code: Option, + /// Wrong codes tried so far. wrong: u32, - /// Sessions carried directly and through the relay so far. - paths: (u32, u32), notice: Option, copied: Option, + /// Sessions carried directly and through the relay so far. + paths: (u32, u32), } pub const HELP: &[&str] = &[ - "friends host share the open world behind an invite code (needs HORIZON_RELAY_URL)", + "friends host share the open world behind an invite code", "friends stop stop sharing", - "friends status the code, the relay state and the guests", + "friends status the code, how friends reach this host, the guests", ]; +/// The relay the player set (Join a friend's Relay field, `friendsRelay` +/// in horizon.txt), else `HORIZON_RELAY_URL`. None by default. +pub(super) fn relay_setting() -> Option { + let dir = std::env::current_dir().ok()?; + horizon_client::ui_theme::preference(&dir, "friendsRelay") + .filter(|r| !r.is_empty()) + .or_else(horizon_friends::relay_url) +} + +/// `HORIZON_STUN_SERVERS`, else `friendsStun` in horizon.txt, else the defaults. +fn stun_servers() -> Vec { + if std::env::var_os("HORIZON_STUN_SERVERS").is_some() { + return stun::servers_from_env(); + } + let dir = std::env::current_dir().unwrap_or_default(); + match horizon_client::ui_theme::preference(&dir, "friendsStun") { + Some(list) => stun::parse_servers(&list), + None => stun::servers_from_env(), + } +} + +fn env_flag(name: &str, default: bool) -> bool { + std::env::var(name).map_or(default, |v| v != "0") +} + impl Game<'_> { /// Start sharing the open world. pub(super) fn friends_start(&mut self) -> Result<()> { @@ -37,8 +64,6 @@ impl Game<'_> { if self.remote.is_some() || self.title.is_some() { return Err("open a singleplayer world first".into()); } - let relay = horizon_friends::relay_url() - .ok_or("inviting friends is not available yet in this build")?; let opened_lan = self.lan.is_none(); if opened_lan { // ShareToLanScreen's defaults, as the world options screen offers them. @@ -50,11 +75,22 @@ impl Game<'_> { } let port = self.lan_port().ok_or("the world isn't open to LAN")?; let host = match Host::start(HostConfig { - relay, lan: std::net::SocketAddr::from(([127, 0, 0, 1], port)), protocol: PROTOCOL_VERSION, game: GAME_VERSION.to_owned(), + relay: relay_setting(), path: PathMode::from_env(), + port: std::env::var("HORIZON_FRIENDS_PORT") + .ok() + .and_then(|p| p.parse().ok()) + .unwrap_or(DEFAULT_PORT), + reach: reach::Options { + // HORIZON_FRIENDS_UPNP=0 leaves the router alone. + map_port: env_flag("HORIZON_FRIENDS_UPNP", true), + stun: stun_servers(), + // Both ends on one machine (tests). + loopback: env_flag("HORIZON_FRIENDS_LOOPBACK", false), + }, }) { Ok(h) => h, Err(e) => { @@ -69,15 +105,15 @@ impl Game<'_> { opened_lan, code: None, wrong: 0, - paths: (0, 0), notice: None, copied: None, + paths: (0, 0), }); Ok(()) } - /// Stop sharing: the code ends; the world closes to LAN again if sharing - /// opened it. + /// Stop sharing: the code ends (direct port closed, router mapping + /// deleted); the world closes to LAN again if sharing opened it. pub(super) fn friends_stop(&mut self) { let Some(mut sharing) = self.friends.take() else { return; @@ -97,44 +133,37 @@ impl Game<'_> { } } - /// New codes and the relay's state, once a tick and while the pause menu - /// is drawn. + /// New codes and sessions, once a tick and while the pause menu is drawn. pub(super) fn tick_friends(&mut self) { let Some(sharing) = self.friends.as_mut() else { return; }; - let mut announce = None; + let mut announce = false; for event in sharing.host.poll() { match event { HostEvent::Code(code) => { - if sharing.code.is_some() { - sharing.notice = - Some(if sharing.wrong >= horizon_friends::host::MAX_WRONG { - "Someone kept trying a wrong code, so the code changed.".to_owned() - } else { - "The invite service restarted, so the code changed.".to_owned() - }); + if sharing.code.is_some() && sharing.wrong >= horizon_friends::host::MAX_WRONG { + sharing.notice = Some( + "Someone kept trying a wrong short code, so it changed.".to_owned(), + ); + sharing.wrong = 0; } - sharing.wrong = 0; - announce = Some(code.to_string()); + announce = sharing.code.is_none(); sharing.code = Some(code); } HostEvent::WrongCode { count } => { sharing.wrong = count; - sharing.notice = Some(format!("Someone tried a wrong code ({count} of 5).")); + sharing.notice = Some("Someone tried a wrong code.".to_owned()); } HostEvent::Connected { direct: true, .. } => sharing.paths.0 += 1, HostEvent::Connected { direct: false, .. } => sharing.paths.1 += 1, HostEvent::Disconnected { .. } => {} } } - if let HostState::Retrying(_) = sharing.host.state() { - sharing.code = None; - } - if let Some(code) = announce { - self.system_message(Text::literal(format!( - "Friends can join with the code {code}" - ))); + if announce { + self.system_message(Text::literal( + "Your invite code is ready in the pause menu: copy it and send it to your friends.", + )); } } @@ -143,7 +172,7 @@ impl Game<'_> { return; }; use horizon_client::clipboard::Clipboard; - self.clipboard.set(&code.to_string()); + self.clipboard.set(&code); if let Some(s) = self.friends.as_mut() { s.copied = Some(Instant::now()); } @@ -159,21 +188,33 @@ impl Game<'_> { let Some(s) = &self.friends else { return FriendsView { shown: self.remote.is_none(), - available: horizon_friends::relay_url().is_some(), ..FriendsView::default() }; }; - let status = match s.host.state() { - HostState::Registering => "Getting a code…".to_owned(), - HostState::Retrying(e) => format!("Couldn't reach the invite service; retrying ({e})"), - HostState::Sharing(_) | HostState::Stopped => String::new(), + let state = s.host.state(); + let mut status = if s.code.is_none() { + "Finding how friends can reach you…".to_owned() + } else { + state.summary.clone() }; + if let Some(short) = &state.short { + status.push_str(&format!(" Short code for the relay: {short}.")); + } + if let Some(problem) = &state.relay_problem { + status.push(' '); + status.push_str(problem); + } + let reachable = matches!( + state.verdict, + Some(reach::Verdict::Mapped(_) | reach::Verdict::Public) + ) || state.short.is_some(); FriendsView { shown: true, - available: true, sharing: true, - code: s.code.as_ref().map(Code::to_string), + code: s.code.clone(), status, + reachable, + help: (!reachable && s.code.is_some()).then(|| reach::HELP_URL.to_owned()), guests, notice: s.notice.clone(), copied: s @@ -200,15 +241,15 @@ impl Game<'_> { Some("status") => { self.tick_friends(); let view = self.friends_view(); - let state = self - .friends - .as_ref() - .map(|s| format!("{:?}", s.host.state())); + let state = self.friends.as_ref().map(|s| s.host.state()); Ok(Some(json!({ - "available": view.available, "sharing": view.sharing, "code": view.code, - "state": state, + "short": state.as_ref().and_then(|s| s.short.as_ref().map(ToString::to_string)), + "summary": view.status, + "reachable": view.reachable, + "verdict": state.as_ref().and_then(|s| s.verdict.as_ref().map(|v| format!("{v:?}"))), + "direct_port": state.as_ref().map(|s| s.port), "sessions": self.friends.as_ref().map_or(0, |s| s.host.sessions()), "direct": self.friends.as_ref().map_or(0, |s| s.paths.0), "relayed": self.friends.as_ref().map_or(0, |s| s.paths.1), diff --git a/crates/horizon-client/src/ui_theme.rs b/crates/horizon-client/src/ui_theme.rs index 8b8a74f65..c554f44f9 100644 --- a/crates/horizon-client/src/ui_theme.rs +++ b/crates/horizon-client/src/ui_theme.rs @@ -71,7 +71,30 @@ pub fn save_preferences(dir: &Path) { MenuStyle::Horizon => "horizon", MenuStyle::Classic => "classic", }; - let _ = std::fs::write(dir.join("horizon.txt"), format!("menuStyle:{value}\n")); + set_preference(dir, "menuStyle", Some(value)); +} +/// A Horizon-only preference from `horizon.txt` (`key:value` lines). +pub fn preference(dir: &Path, key: &str) -> Option { + let text = std::fs::read_to_string(dir.join("horizon.txt")).ok()?; + text.lines().find_map(|l| { + let (k, v) = l.split_once(':')?; + (k.trim() == key).then(|| v.trim().to_owned()) + }) +} +/// Set (or with None remove) one preference, keeping the others. +pub fn set_preference(dir: &Path, key: &str, value: Option<&str>) { + let text = std::fs::read_to_string(dir.join("horizon.txt")).unwrap_or_default(); + let mut lines: Vec = text + .lines() + .filter(|l| l.split_once(':').is_none_or(|(k, _)| k.trim() != key)) + .map(str::to_owned) + .collect(); + if let Some(v) = value { + lines.push(format!("{key}:{v}")); + } + let mut out = lines.join("\n"); + out.push('\n'); + let _ = std::fs::write(dir.join("horizon.txt"), out); } /// The dark palette (`horizon_theme::DARK`) in the HUD's colour encoding, plus the