Merge pull request #199 from ludovic111/feat/friends-host

Play with friends (2/3): Invite friends in the pause menu (no server needed)
This commit is contained in:
Ludovic Marie
2026-10-15 05:06:36 +02:00
committed by GitHub
10 changed files with 462 additions and 5 deletions
Generated
+1
View File
@@ -1007,6 +1007,7 @@ dependencies = [
"glam",
"horizon-assets",
"horizon-core",
"horizon-friends",
"horizon-protocol",
"horizon-telemetry",
"horizon-theme",
+1
View File
@@ -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"
+149 -2
View File
@@ -1018,12 +1018,39 @@ pub fn wrap(ui: &Ui, text: &str, width: f32) -> Vec<String> {
/// 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,
pub sharing: bool,
pub code: Option<String>,
/// 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<String>,
/// The players in the world besides the host.
pub guests: Vec<String>,
pub notice: Option<String>,
/// 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 +1092,21 @@ 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.sharing,
);
}
y += CONTROL_LARGE + 32.0;
ui.row_index = 0;
if friends.sharing {
y = invite(ui, x, y, cw, friends);
}
ui.divider(x, y, cw);
let rh = ui.row(
x,
@@ -1088,6 +1128,109 @@ 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.
/// The code's groups packed into lines of at most `width`.
fn code_lines(ui: &Ui, code: &str, width: f32) -> Vec<String> {
let mut lines: Vec<String> = 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;
ui.text(
Face::Regular,
BODY,
x,
top + 6.0,
color::MUTED,
"Invite code",
);
let vx = x + t::ROW_LABEL + 16.0;
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);
let buttons = sw + 8.0 + copy_w;
ui.button(
act(11),
[x + cw - buttons, top, copy_w, CONTROL],
copy,
Kind::Secondary,
f.code.is_some(),
);
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 {
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((here, color::MUTED)),
f.notice.clone().map(|n| (n, color::MUTED)),
Some((hint.to_owned(), color::FAINT)),
];
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;
}
y + 12.0
}
/// The PauseScreen action under a click, if any.
pub fn click(
atlas: &HudAtlas,
@@ -1096,6 +1239,7 @@ pub mod pause {
y: f32,
world: &str,
quit_label: &str,
friends: &FriendsView,
) -> Option<u8> {
let mut ui = Ui::dry(atlas, batch, (x, y));
draw(
@@ -1103,6 +1247,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 +1256,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),
}
}
}
+5
View File
@@ -40,6 +40,7 @@ mod fireworks;
mod fishing;
mod fov;
mod frames;
mod friends;
mod functions;
mod game_mode;
mod gamemode_switcher;
@@ -929,6 +930,8 @@ struct Game<'a> {
remote: Option<remote::Remote>,
/// This world is open to the network (game/lan.rs).
lan: Option<lan::LanHost>,
/// The open world is shared behind an invite code (game/friends.rs).
friends: Option<friends::Sharing>,
world_options: Option<lan_screen::WorldOptions>,
/// KeyboardHandler's debug key state (game/debug_keys.rs), the physical
/// keys held, and the debug renderers F3+B and F3+G switch on.
@@ -3211,6 +3214,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())?;
@@ -9506,6 +9510,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,
@@ -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)
+263
View File
@@ -0,0 +1,263 @@
//! 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 (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::{Host, HostConfig, HostEvent, PathMode, host::DEFAULT_PORT, reach, stun};
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<String>,
/// Wrong codes tried so far.
wrong: u32,
notice: Option<String>,
copied: Option<Instant>,
/// 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",
"friends stop stop sharing",
"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<String> {
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<String> {
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<()> {
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 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 {
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) => {
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,
paths: (0, 0),
});
Ok(())
}
/// 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;
};
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 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 = false;
for event in sharing.host.poll() {
match event {
HostEvent::Code(code) => {
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;
}
announce = sharing.code.is_none();
sharing.code = Some(code);
}
HostEvent::WrongCode { count } => {
sharing.wrong = count;
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 announce {
self.system_message(Text::literal(
"Your invite code is ready in the pause menu: copy it and send it to your friends.",
));
}
}
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);
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(),
..FriendsView::default()
};
};
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,
sharing: true,
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
.copied
.is_some_and(|t| t.elapsed() < Duration::from_secs(2)),
}
}
/// `horizon-ctl friends ...`.
pub(super) fn friends_control(&mut self, words: &[&str]) -> Result<Option<serde_json::Value>> {
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| s.host.state());
Ok(Some(json!({
"sharing": view.sharing,
"code": view.code,
"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),
"guests": view.guests,
"lan_port": self.lan_port(),
})))
}
_ => Err("friends host|stop|status".into()),
}
}
}
+1
View File
@@ -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;
};
+11 -1
View File
@@ -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()?,
_ => {}
}
+3 -1
View File
@@ -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;
+24 -1
View File
@@ -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<String> {
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<String> = 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