diff --git a/crates/horizon-client/src/lan/discovery.rs b/crates/horizon-client/src/lan/discovery.rs new file mode 100644 index 000000000..07eca3481 --- /dev/null +++ b/crates/horizon-client/src/lan/discovery.rs @@ -0,0 +1,169 @@ +//! LAN game discovery: LanServerPinger announces a hosted world on the +//! multicast group 224.0.2.60:4445 every 1.5 seconds as +//! `[MOTD]text[/MOTD][AD]port[/AD]`, and LanServerDetection collects those +//! announcements for the multiplayer screen. +use std::{ + io, + net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket}, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + }, + thread::JoinHandle, + time::{Duration, Instant}, +}; + +pub const GROUP: Ipv4Addr = Ipv4Addr::new(224, 0, 2, 60); +pub const PORT: u16 = 4445; +/// LanServerPinger sleeps 1500 ms between announcements. +const INTERVAL: Duration = Duration::from_millis(1500); +/// LanServerDetection.LanServerList drops entries not refreshed for 5 s. +const EXPIRY: Duration = Duration::from_secs(5); + +/// LanServerPinger.createPingString. +pub fn ping_string(motd: &str, port: u16) -> String { + format!("[MOTD]{motd}[/MOTD][AD]{port}[/AD]") +} +fn between<'a>(s: &'a str, open: &str, close: &str) -> Option<&'a str> { + let start = s.find(open)? + open.len(); + let end = s[start..].find(close)? + start; + Some(&s[start..end]) +} +/// LanServerPinger.parseMotd; vanilla shows "missing no" when absent. +pub fn parse_motd(s: &str) -> String { + between(s, "[MOTD]", "[/MOTD]") + .unwrap_or("missing no") + .to_owned() +} +/// LanServerPinger.parseAddress: the announced port, if present and valid. +pub fn parse_port(s: &str) -> Option { + between(s, "[AD]", "[/AD]")?.parse().ok().filter(|p| *p > 0) +} + +/// Announces one hosted world until dropped. +pub struct Pinger { + stop: Arc, + thread: Option>, +} +impl Pinger { + pub fn start(motd: String, port: u16) -> io::Result { + let socket = UdpSocket::bind(("0.0.0.0", 0))?; + let _ = socket.set_multicast_ttl_v4(4); + let stop = Arc::new(AtomicBool::new(false)); + let flag = stop.clone(); + let message = ping_string(&motd, port); + let thread = std::thread::Builder::new() + .name("horizon-lan-ping".into()) + .spawn(move || { + let target = SocketAddr::V4(SocketAddrV4::new(GROUP, PORT)); + while !flag.load(Ordering::Relaxed) { + let _ = socket.send_to(message.as_bytes(), target); + let mut slept = Duration::ZERO; + while slept < INTERVAL && !flag.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(50)); + slept += Duration::from_millis(50); + } + } + })?; + Ok(Self { + stop, + thread: Some(thread), + }) + } +} +impl Drop for Pinger { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + } +} + +/// A world announced on the local network. +#[derive(Clone, Debug, PartialEq)] +pub struct LanGame { + pub motd: String, + pub address: String, +} +type Games = Arc>>; + +/// Listens for announcements until the last clone is dropped. +#[derive(Clone, Debug)] +pub struct Scanner { + inner: Arc, +} +#[derive(Debug)] +struct ScanInner { + games: Games, + stop: Arc, +} +impl Drop for ScanInner { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + } +} +impl Scanner { + /// Bind the discovery port; without it the list simply stays empty. + pub fn start() -> Self { + let games: Games = Arc::default(); + let stop = Arc::new(AtomicBool::new(false)); + if let Ok(socket) = bind_listener() { + let (games, stop) = (games.clone(), stop.clone()); + let _ = std::thread::Builder::new() + .name("horizon-lan-scan".into()) + .spawn(move || listen(socket, games, stop)); + } + Self { + inner: Arc::new(ScanInner { games, stop }), + } + } + /// The live announcements, oldest first. + pub fn games(&self) -> Vec { + let mut games = self.inner.games.lock().unwrap(); + games.retain(|(_, seen)| seen.elapsed() < EXPIRY); + games.iter().map(|(g, _)| g.clone()).collect() + } +} +fn bind_listener() -> io::Result { + let socket = UdpSocket::bind(("0.0.0.0", PORT))?; + socket.join_multicast_v4(&GROUP, &Ipv4Addr::UNSPECIFIED)?; + socket.set_read_timeout(Some(Duration::from_millis(250)))?; + Ok(socket) +} +fn listen(socket: UdpSocket, games: Games, stop: Arc) { + let mut buf = [0u8; 1024]; + while !stop.load(Ordering::Relaxed) { + let Ok((n, from)) = socket.recv_from(&mut buf) else { + continue; + }; + let text = String::from_utf8_lossy(&buf[..n]); + let Some(port) = parse_port(&text) else { + continue; + }; + let game = LanGame { + motd: parse_motd(&text), + address: format!("{}:{port}", from.ip()), + }; + let mut games = games.lock().unwrap(); + match games.iter_mut().find(|(g, _)| g.address == game.address) { + Some(entry) => *entry = (game, Instant::now()), + None => games.push((game, Instant::now())), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ping_string_round_trips() { + let s = ping_string("Steve - World", 25565); + assert_eq!(s, "[MOTD]Steve - World[/MOTD][AD]25565[/AD]"); + assert_eq!(parse_motd(&s), "Steve - World"); + assert_eq!(parse_port(&s), Some(25565)); + assert_eq!(parse_port("[AD]0[/AD]"), None); + assert_eq!(parse_motd("junk"), "missing no"); + } +} diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index 6367295ae..b6af18530 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -8,6 +8,7 @@ pub mod chunks; pub mod conn; pub mod containers; pub mod data; +pub mod discovery; pub mod entity; pub mod guest; pub mod hub; @@ -111,6 +112,8 @@ pub struct Lan { events: Receiver, pub port: u16, listener: Option>, + /// The multicast announcement (LanServerPinger); absent when the socket failed. + _pinger: Option, } impl Lan { /// Listen on `port` (0 picks a free one). @@ -123,6 +126,7 @@ impl Lan { let listener = TcpListener::bind(("0.0.0.0", port))?; listener.set_nonblocking(true)?; let port = listener.local_addr()?.port(); + let _pinger = discovery::Pinger::start(motd.clone(), port).ok(); let (tx, events) = channel(); let shared = Arc::new(Shared { sync, @@ -142,6 +146,7 @@ impl Lan { events, port, listener: Some(listener), + _pinger, }) } /// Everything the connection threads reported since the last call. @@ -160,6 +165,7 @@ impl Lan { if let Some(t) = self.listener.take() { let _ = t.join(); } + self._pinger = None; } } impl Drop for Lan { diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 8e2ef5c64..ef067ce06 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -3,6 +3,7 @@ //! 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 crate::lan::discovery::Scanner; use horizon_protocol::servers::{self, ServerEntry}; use std::{ collections::HashMap, @@ -31,6 +32,8 @@ pub enum Screen { servers: Vec, selected: Option, pings: Pings, + /// Worlds announced on the local network, listed after the servers. + lan: Scanner, }, /// Add (index None) or edit a server entry. Edit { @@ -92,6 +95,18 @@ fn ping_all(servers: &[ServerEntry], pings: &Pings) { } } +/// The address of list row `index`: the saved servers, then the LAN games. +fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option { + match servers.get(index) { + Some(s) => Some(s.ip.clone()), + None => lan + .games() + .into_iter() + .nth(index - servers.len()) + .map(|g| g.address), + } +} + impl Screen { pub fn list(saves: &Path) -> Self { let servers = servers::load(&servers_file(saves)); @@ -101,6 +116,7 @@ impl Screen { servers, selected: None, pings, + lan: Scanner::start(), } } pub fn buttons(&self, w: f32, h: f32) -> Vec { @@ -256,6 +272,7 @@ impl Screen { servers, selected, pings, + lan, } => { 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)); @@ -319,6 +336,42 @@ impl Screen { ); } } + for (k, game) in lan.games().iter().enumerate() { + let i = servers.len() + k; + 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.text(atlas, "LAN World", x + 35.0, y + 1.0, u32::MAX, false); + batch.text( + atlas, + &game.motd, + x + 35.0, + y + 12.0, + rgba(128, 128, 128, 255), + false, + ); + batch.text( + atlas, + &game.address, + x + 35.0, + y + 22.0, + rgba(96, 96, 96, 255), + false, + ); + } if servers.is_empty() { centered( batch, @@ -392,12 +445,15 @@ impl Screen { match (&mut *self, id) { ( Self::List { - servers, selected, .. + servers, + selected, + lan, + .. }, Some(40), ) => { - if let Some(s) = selected.and_then(|i| servers.get(i)) { - return Outcome::Connect(s.ip.clone()); + if let Some(address) = selected.and_then(|i| entry_address(servers, lan, i)) { + return Outcome::Connect(address); } } (Self::List { .. }, Some(41)) => { @@ -446,21 +502,22 @@ impl Screen { (Self::List { .. }, Some(46)) => return Outcome::Back, ( Self::List { - servers, selected, .. + servers, + selected, + lan, + .. }, 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() - { + if y >= 36.0 && y < h - 64.0 && (x - w / 2.0).abs() < 154.0 { let index = index as usize; - if *selected == Some(index) { - return Outcome::Connect(servers[index].ip.clone()); + if let Some(address) = entry_address(servers, lan, index) { + if *selected == Some(index) { + return Outcome::Connect(address); + } + *selected = Some(index); } - *selected = Some(index); } } (