Merge pull request #603 from ludovic111/perf/sp-open-to-lan

Integrated server: Open to LAN
This commit is contained in:
Ludovic Marie
2026-10-17 03:56:44 +02:00
committed by GitHub
14 changed files with 571 additions and 118 deletions
@@ -88,6 +88,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
seed: 0,
max_players: 8,
dedicated: false,
integrated: false,
},
);
let mut next_entity = 100u32;
+4 -1
View File
@@ -1087,6 +1087,8 @@ struct Game<'a> {
lan: Option<lan::LanHost>,
/// Single player's server thread, which `remote` is connected to.
integrated: Option<integrated::Integrated>,
/// This game is that server thread's (game/integrated.rs).
serving: Option<integrated::Serving>,
/// The open world is shared behind an invite code (game/friends.rs).
friends: Option<friends::Sharing>,
world_options: Option<lan_screen::WorldOptions>,
@@ -3635,7 +3637,7 @@ impl Game<'_> {
/// `Minecraft.pause`: a single-player game with a pausing screen open.
fn pauses_game(&self) -> bool {
self.has_singleplayer_server()
&& self.lan.is_none()
&& !self.is_published()
&& self.title.is_none()
&& (matches!(
self.screen,
@@ -10072,6 +10074,7 @@ impl<'a> Game<'a> {
remote: None,
lan: None,
integrated: None,
serving: None,
world_options: None,
options_to_world_options: false,
command_block_screen: None,
@@ -758,18 +758,25 @@ impl Game<'_> {
.and_then(|l| l.local_addr())
.map_or(25564, |a| i32::from(a.port())),
};
if let Some(lan) = &self.lan {
return Err(err(
"commands.publish.alreadyPublished.lan",
&[&lan.settings.port],
));
let published = if self.serving() {
self.published_port()
} else {
self.lan.as_ref().map(|l| l.settings.port)
};
if let Some(port) = published {
return Err(err("commands.publish.alreadyPublished.lan", &[&port]));
}
let settings = super::super::lan::LanSettings {
port: port as u16,
guest_commands: allow,
force_game_mode: false,
};
if self.lan_start(settings).is_err() {
let started = if self.serving() {
self.publish(settings).is_ok()
} else {
self.lan_start(settings).is_ok()
};
if !started {
return Err(err("commands.publish.failed", &[]));
}
let port_text = port.to_string();
@@ -785,6 +792,13 @@ impl Game<'_> {
Ok(port)
}
pub(super) fn cmd_unpublish(&mut self) -> R<i32> {
if self.serving() {
if !self.unpublish() {
return Err(err("commands.unpublish.notPublished", &[]));
}
self.feedback(Text::translate("commands.unpublish.success", &[]));
return Ok(1);
}
if self.lan.is_none() {
return Err(err("commands.unpublish.notPublished", &[]));
}
+1 -1
View File
@@ -38,7 +38,7 @@ impl DebugHost for Host<'_, '_> {
// the menu as it always has (key_pressed).
let g = &mut *self.game;
if without_menu && g.screen == Screen::Playing {
g.pause_menu = !(g.has_singleplayer_server() && g.lan.is_none());
g.pause_menu = !(g.has_singleplayer_server() && !g.is_published());
g.screen = Screen::Paused;
g.capture(false);
g.mining = None;
@@ -463,6 +463,7 @@ impl Game<'_> {
seed: self.level.seed,
max_players: props.max_players.max(0) as usize,
dedicated: true,
integrated: false,
};
let settings = LanSettings {
port,
+268 -17
View File
@@ -2,6 +2,10 @@
//! its own "Server thread", as vanilla's does, and the window joins it as a
//! player through memory, so a world tick never holds up a frame.
//!
//! The window asks its server for what only the server knows (Open to LAN,
//! the world's options) with [`Integrated::call`], as vanilla's client calls
//! into its `IntegratedServer`.
//!
//! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the
//! player joins as a network player, and the server side of a network player
//! does not do everything single player does yet. Worlds whose player is
@@ -15,7 +19,7 @@ use horizon_client::{
Result,
audio::Audio,
hud::HudAtlas,
lan::{MAX_PLAYERS, NetConfig, hub::HubConfig},
lan::{Lan, MAX_PLAYERS, NetConfig, hub::HubConfig},
save::Level,
settings::Settings,
title::WorldOptions,
@@ -23,11 +27,12 @@ use horizon_client::{
use horizon_protocol::connection::Pipe;
use horizon_protocol::{crypto::offline_uuid, text::translatable};
use std::{
net::TcpListener,
path::Path,
sync::{
Arc,
atomic::{AtomicBool, AtomicU32, Ordering},
mpsc::{Sender, channel},
atomic::{AtomicBool, AtomicU16, AtomicU32, Ordering},
mpsc::{Receiver, Sender, channel, sync_channel},
},
thread::JoinHandle,
time::{Duration, Instant},
@@ -39,13 +44,20 @@ struct Flags {
/// `Minecraft.pause`: a single-player pause screen is open.
paused: AtomicBool,
stop: AtomicBool,
/// `IntegratedServer.getPort`: the port it is open to the LAN on, 0
/// while it is not.
published: AtomicU16,
smoothed_tick_ms: AtomicU32,
}
/// Work the window hands its server thread (`MinecraftServer.execute`).
type Task = Box<dyn FnOnce(&mut Game<'_>) + Send>;
/// The window's handle on its server thread.
pub(super) struct Integrated {
flags: Arc<Flags>,
thread: Option<JoinHandle<()>>,
tasks: Sender<Task>,
/// The world's name (`level.dat`'s `LevelName`), for the pause menu.
pub world_name: String,
}
@@ -57,6 +69,24 @@ impl Integrated {
pub fn set_paused(&self, paused: bool) {
self.flags.paused.store(paused, Ordering::Relaxed);
}
/// `IntegratedServer.getPort` while `isPublished`.
pub fn published(&self) -> Option<u16> {
Some(self.flags.published.load(Ordering::Relaxed)).filter(|&p| p != 0)
}
/// `executeBlocking`: run `f` on the server thread between two ticks and
/// wait for its answer; `None` once the server has stopped.
pub fn call<T: Send + 'static>(
&self,
f: impl FnOnce(&mut Game<'_>) -> T + Send + 'static,
) -> Option<T> {
let (tx, rx) = sync_channel(1);
self.tasks
.send(Box::new(move |g| {
let _ = tx.send(f(g));
}))
.ok()?;
rx.recv_timeout(Duration::from_secs(10)).ok()
}
/// `IntegratedServer.halt(true)`: returns once the world is saved and let go.
pub fn stop(mut self) {
self.halt();
@@ -74,6 +104,21 @@ impl Drop for Integrated {
}
}
/// The server thread's side of the window's handle (`Game::serving`).
pub(super) struct Serving {
flags: Arc<Flags>,
tasks: Receiver<Task>,
/// The window's profile.
owner: u128,
/// Open to LAN or closed from inside a player's command, while the hub
/// is out of its place: applied after the tick.
pending: Option<Publish>,
}
enum Publish {
Open(TcpListener, LanSettings),
Close,
}
/// What the server thread hands the window once the world is open: its end
/// of the connection and the world's name, or why it failed.
type Ready = std::result::Result<(Pipe, String), String>;
@@ -85,8 +130,11 @@ struct Launch {
seed: Option<i64>,
creative: bool,
create: Option<WorldOptions>,
/// The window's profile: the only one let in, and the world's player.
/// The window's profile: the only one let in until the world is open to
/// the LAN, and the world's player.
owner: u128,
/// Its name, for the LAN's MOTD.
player: String,
}
/// Whether this world opens on a server thread: asked for, and its player
@@ -103,6 +151,14 @@ impl Game<'_> {
pub(super) fn has_singleplayer_server(&self) -> bool {
self.remote.is_none() || self.integrated.is_some()
}
/// `IntegratedServer.isPublished`: the world is open to the network.
pub(super) fn is_published(&self) -> bool {
self.lan.is_some()
|| self
.integrated
.as_ref()
.is_some_and(|s| s.published().is_some())
}
/// `Minecraft.doWorldLoad`: start the server thread on the world, wait
/// until it can be joined, then join it through memory.
pub(super) fn open_integrated(
@@ -125,6 +181,7 @@ impl Game<'_> {
create: create.cloned(),
// An offline-mode server names its players by their offline profile.
owner: offline_uuid(&player),
player: player.clone(),
};
let mut options = self.options.clone();
// A server without a console: no local player, no window, no control socket.
@@ -142,6 +199,7 @@ impl Game<'_> {
let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone());
let flags = Arc::new(Flags::default());
let (ready_tx, ready) = channel();
let (tasks, server_tasks) = channel();
let server_flags = flags.clone();
let thread = std::thread::Builder::new()
.name("Server thread".into())
@@ -152,7 +210,8 @@ impl Game<'_> {
options,
settings,
launch,
&server_flags,
server_flags,
server_tasks,
&ready_tx,
);
if let Err(e) = result {
@@ -163,6 +222,7 @@ impl Game<'_> {
let mut handle = Integrated {
flags,
thread: Some(thread),
tasks,
world_name: String::new(),
};
let pipe = match ready.recv() {
@@ -183,7 +243,8 @@ impl Game<'_> {
fn run_integrated(
&mut self,
launch: Launch,
flags: &Flags,
flags: Arc<Flags>,
tasks: Receiver<Task>,
ready: &Sender<Ready>,
) -> Result<()> {
self.open_world(
@@ -197,7 +258,8 @@ impl Game<'_> {
let view_distance = self.settings.render_distance.clamp(2, 32);
let config = HubConfig {
default_game_mode: self.level.mode(),
guest_commands: true,
// Only the owner until it is opened to the LAN.
guest_commands: false,
force_game_mode: false,
hardcore: self.level.hardcore,
view_distance,
@@ -207,23 +269,28 @@ impl Game<'_> {
max_players: MAX_PLAYERS,
// No player of its own: the hub runs without a host.
dedicated: true,
integrated: true,
};
let owner = launch.owner;
let published = flags.clone();
let net = NetConfig {
// No network until it is opened to the LAN.
// No network until it is opened to the LAN; the memory connection
// is not compressed (`Connection.isMemoryConnection`).
listen: false,
// A memory connection is not compressed (`Connection.isMemoryConnection`).
compression_threshold: -1,
enable_status: false,
announce: false,
gate: Some(Arc::new(move |_, uuid, _| {
(uuid != owner).then(|| translatable("multiplayer.disconnect.not_whitelisted", &[]))
(uuid != owner && published.published.load(Ordering::Relaxed) == 0)
.then(|| translatable("multiplayer.disconnect.not_whitelisted", &[]))
})),
..NetConfig::lan(0, self.level.name.clone(), MAX_PLAYERS)
// IntegratedServer.initServer: the MOTD names the owner and the world.
..NetConfig::lan(
0,
format!("{} - {}", launch.player, self.level.name),
MAX_PLAYERS,
)
};
let settings = LanSettings {
port: 0,
guest_commands: true,
guest_commands: false,
force_game_mode: false,
};
self.lan_host(settings, net, config, None)?;
@@ -242,10 +309,17 @@ impl Game<'_> {
});
host.hub.lan.connect_local()?
};
self.serving = Some(Serving {
flags: flags.clone(),
tasks,
owner,
pending: None,
});
let _ = ready.send(Ok((pipe, self.level.name.clone())));
self.settle_spawn()?;
let mut next = Instant::now();
while !flags.stop.load(Ordering::Relaxed) {
self.run_tasks();
self.update_dedicated_streaming();
self.update_world();
if flags.paused.load(Ordering::Relaxed) {
@@ -260,6 +334,7 @@ impl Game<'_> {
Ordering::Relaxed,
);
}
self.apply_publish();
let rate = self.clock.rate().max(1.0);
next += Duration::from_secs_f64(1.0 / f64::from(rate));
let now = Instant::now();
@@ -275,6 +350,10 @@ impl Game<'_> {
/// `MinecraftServer.stopServer`: the players are saved and sent away,
/// then the world is saved.
fn stop_integrated(&mut self) -> Result<()> {
// IntegratedServer.stopServer: teardownPublishedState.
if let Some(s) = self.serving.take() {
s.flags.published.store(0, Ordering::Relaxed);
}
if let Some(mut host) = self.lan.take() {
for g in &host.hub.guests {
self.save_guest(&host, g);
@@ -297,19 +376,191 @@ impl Game<'_> {
}
}
/// What the world options screen shows of an integrated server.
#[derive(Clone, Copy, Debug)]
pub(super) struct ServerOptions {
pub default_mode: i32,
/// The owner's own game mode.
pub personal_mode: i32,
pub cheats: bool,
pub difficulty: u8,
pub hardcore: bool,
pub difficulty_locked: bool,
pub port: Option<u16>,
pub guest_commands: bool,
pub force: bool,
}
/// The server thread's side.
impl Game<'_> {
/// Whether this game is an integrated server's.
pub(super) fn serving(&self) -> bool {
self.serving.is_some()
}
/// The window's requests, between two ticks.
fn run_tasks(&mut self) {
let tasks: Vec<Task> = match &self.serving {
Some(s) => s.tasks.try_iter().collect(),
None => return,
};
for task in tasks {
task(self);
self.apply_publish();
}
}
/// `IntegratedServer.getPort` while published.
pub(super) fn published_port(&self) -> Option<u16> {
let s = self.serving.as_ref()?;
Some(s.flags.published.load(Ordering::Relaxed)).filter(|&p| p != 0)
}
/// `IntegratedServer.publishServer`: listen on `settings.port` (0 picks
/// one) and announce the world. The socket is bound at once so a busy
/// port fails here; the hub starts listening once it is at hand.
pub(super) fn publish(&mut self, settings: LanSettings) -> std::result::Result<u16, String> {
let Some(s) = self.serving.as_mut() else {
return Err("not an integrated server".into());
};
if s.flags.published.load(Ordering::Relaxed) != 0 {
return Err("already published".into());
}
let listener = Lan::bind(None, settings.port).map_err(|e| e.to_string())?;
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
log::info!("Published LAN server on port {port}");
s.flags.published.store(port, Ordering::Relaxed);
s.pending = Some(Publish::Open(listener, LanSettings { port, ..settings }));
self.apply_publish();
Ok(port)
}
/// `IntegratedServer.unpublishServer`: stop listening and send every
/// player but the owner away. False when it was not published.
pub(super) fn unpublish(&mut self) -> bool {
let Some(s) = self.serving.as_mut() else {
return false;
};
if s.flags.published.swap(0, Ordering::Relaxed) == 0 {
return false;
}
s.pending = Some(Publish::Close);
self.apply_publish();
true
}
/// Publish or unpublish for real, once the hub is in its place (a
/// player's `/publish` runs while it is out).
fn apply_publish(&mut self) {
if self.lan.is_none() {
return;
}
let Some(s) = self.serving.as_mut() else {
return;
};
let (Some(pending), owner) = (s.pending.take(), s.owner) else {
return;
};
let allow_commands = self.allow_commands();
let Some(host) = self.lan.as_mut() else {
return;
};
match pending {
Publish::Open(listener, settings) => {
if let Err(e) = host.hub.lan.listen_on(listener, true) {
log::error!("Horizon: Open to LAN: {e}");
}
host.settings = settings;
host.hub.config.force_game_mode = settings.force_game_mode;
// IntegratedServer.setGuestCommandAccess, then updatePermissions.
host.hub.config.guest_commands = settings.guest_commands && allow_commands;
host.hub.resend_commands();
}
Publish::Close => {
host.hub.lan.stop_listening();
log::info!(
"Unpublishing integrated server (was on port {})",
host.settings.port
);
let others: Vec<u32> = host
.hub
.guests
.iter()
.filter(|g| g.uuid != owner)
.map(|g| g.conn)
.collect();
for conn in others {
host.hub.kick(
conn,
translatable("multiplayer.disconnect.server_shutdown", &[]),
);
}
}
}
}
/// The world options screen's state, read on the server.
pub(super) fn server_options(&self) -> ServerOptions {
let owner = self.serving.as_ref().map(|s| s.owner);
let host = self.lan.as_ref();
let personal_mode = host
.and_then(|h| h.hub.guests.iter().find(|g| Some(g.uuid) == owner))
.map_or(self.level.mode(), |g| g.game_mode);
let published = self.published_port();
ServerOptions {
default_mode: self.level.mode(),
personal_mode,
cheats: self.allow_commands(),
difficulty: self.ui.difficulty,
hardcore: self.level.hardcore,
difficulty_locked: self.level.difficulty_locked,
port: published,
guest_commands: published.is_some() && host.is_some_and(|h| h.settings.guest_commands),
force: published.is_none() || host.is_some_and(|h| h.settings.force_game_mode),
}
}
/// `IntegratedServer.setPersonalGameType`: the owner's game mode.
pub(super) fn set_owner_mode(&mut self, mode: i32) {
let Some(owner) = self.serving.as_ref().map(|s| s.owner) else {
return;
};
if let Some(host) = self.lan.as_mut()
&& let Some(conn) = host
.hub
.guests
.iter()
.find(|g| g.uuid == owner)
.map(|g| g.conn)
{
host.hub.set_game_mode(conn, mode);
}
}
/// `IntegratedServer.setWorldAllowCommands`: the owner is an operator
/// while the world allows commands; everyone's level is sent again.
pub(super) fn owner_allow_commands(&mut self, allow: bool) {
let Some(owner) = self.serving.as_ref().map(|s| s.owner) else {
return;
};
let published = self.published_port().is_some();
if let Some(host) = self.lan.as_mut() {
host.hub.ops.insert(owner, if allow { 4 } else { 0 });
if published {
host.hub.config.guest_commands = allow && host.settings.guest_commands;
}
host.hub.resend_commands();
}
}
}
/// The server thread: a game of its own over the shared resources.
#[allow(clippy::too_many_arguments)]
fn serve(
res: &Arc<Resources>,
pack: PackResources,
options: Options,
settings: Settings,
launch: Launch,
flags: &Flags,
flags: Arc<Flags>,
tasks: Receiver<Task>,
ready: &Sender<Ready>,
) -> Result<()> {
// It draws nothing: only the font, which books and chat measure with.
let atlas = HudAtlas::fonts(&options.resources)?;
let audio = Audio::silent(&options.resources);
let mut server = Game::new(res, pack, atlas, options, settings, audio)?;
server.run_integrated(launch, flags, ready)
server.run_integrated(launch, flags, tasks, ready)
}
+88 -34
View File
@@ -31,7 +31,7 @@ use std::{
static SYNC: OnceLock<std::result::Result<Arc<SyncData>, String>> = OnceLock::new();
/// The settings of the open world (WorldOptionsScreen's multiplayer section).
#[derive(Clone, Debug)]
#[derive(Clone, Copy, Debug)]
pub struct LanSettings {
pub port: u16,
pub guest_commands: bool,
@@ -316,6 +316,15 @@ impl Game<'_> {
if words[0] != "lan" {
return Ok(None);
}
if let Some(server) = &self.integrated
&& words.get(1) == Some(&"status")
{
// The hub is the server thread's.
let status = server
.call(|g| g.lan_status())
.ok_or("the integrated server stopped")?;
return Ok(Some(status));
}
match words.get(1).copied() {
Some("open") => {
if self.title.is_some() {
@@ -337,43 +346,58 @@ impl Game<'_> {
self.lan_close(true);
Ok(Some(json!({ "ok": true })))
}
Some("status") => Ok(Some(match &self.lan {
Some(h) => json!({
"open": true,
"host": h.host_name,
"port": h.settings.port,
"guests": h.hub.guests.iter().map(|g| json!({
"name": g.name,
"position": g.position,
"placed": g.placed,
"loaded": g.loaded,
"game_mode": g.game_mode,
"sneaking": g.sneaking,
"health": g.health,
// FoodData: food level, saturation and exhaustion.
"food": [
f64::from(g.food),
f64::from(g.saturation),
g.motion.as_ref().map_or(0.0, |m| f64::from(m.health.food.exhaustion)),
],
"chunks": g.sent_chunks.len(),
"tracked": g.tracker.len(),
// The armour the host draws on this guest, head to feet.
"model_armor": h.models.get(&g.conn).map(|m| {
[&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet]
.map(|s| s.as_deref())
}),
})).collect::<Vec<_>>(),
}),
None => json!({ "open": false }),
})),
Some("status") => Ok(Some(self.lan_status())),
_ => Err("lan open|close|status".into()),
}
}
/// `horizon-ctl lan status`.
fn lan_status(&self) -> serde_json::Value {
use serde_json::json;
match &self.lan {
Some(h) if !self.serving() || self.published_port().is_some() => json!({
"open": true,
"host": h.host_name,
"port": h.settings.port,
"guests": h.hub.guests.iter().map(|g| json!({
"name": g.name,
"position": g.position,
"placed": g.placed,
"loaded": g.loaded,
"game_mode": g.game_mode,
"sneaking": g.sneaking,
"health": g.health,
// FoodData: food level, saturation and exhaustion.
"food": [
f64::from(g.food),
f64::from(g.saturation),
g.motion.as_ref().map_or(0.0, |m| f64::from(m.health.food.exhaustion)),
],
"chunks": g.sent_chunks.len(),
"tracked": g.tracker.len(),
// The armour the host draws on this guest, head to feet.
"model_armor": h.models.get(&g.conn).map(|m| {
[&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet]
.map(|s| s.as_deref())
}),
})).collect::<Vec<_>>(),
}),
_ => json!({ "open": false }),
}
}
pub(super) fn lan_open(&mut self, settings: LanSettings) -> Result<()> {
self.lan_start(settings)?;
let port = self.lan.as_ref().map_or(0, |l| l.settings.port);
let port = if let Some(server) = &self.integrated {
// ShareToLanScreen: IntegratedServer.publishServer.
server
.call(move |g| g.publish(settings))
.ok_or("the integrated server stopped")??
} else if self.serving() {
return self.publish(settings).map(drop).map_err(Into::into);
} else {
self.lan_start(settings)?;
self.lan.as_ref().map_or(0, |l| l.settings.port)
};
self.system_message(Text::translate(
"menu.multiplayerOptions.publish.started.lan",
&[Text::literal(port.to_string())],
@@ -408,6 +432,7 @@ impl Game<'_> {
seed: self.level.seed,
max_players: MAX_PLAYERS,
dedicated: false,
integrated: false,
};
let net = NetConfig::lan(settings.port, motd, MAX_PLAYERS);
self.lan_host(settings, net, config, Some(host_uuid))
@@ -484,6 +509,22 @@ impl Game<'_> {
/// IntegratedServer.unpublishServer: the guests are sent away.
pub(super) fn lan_close(&mut self, announce: bool) {
if self.integrated.is_some() || self.serving() {
let closed = match &self.integrated {
Some(server) => server.call(|g| g.unpublish()).unwrap_or(false),
None => self.unpublish(),
};
if closed {
self.friends_lan_closed();
}
if closed && announce && self.integrated.is_some() {
self.system_message(Text::translate(
"menu.multiplayerOptions.publish.stopped",
&[],
));
}
return;
}
self.friends_lan_closed();
let Some(mut host) = self.lan.take() else {
return;
@@ -541,16 +582,29 @@ impl Game<'_> {
/// New command access and game mode forcing settings of the open world.
pub(super) fn lan_apply_settings(&mut self, guest_commands: bool, force: bool) {
if let Some(server) = &self.integrated {
server.call(move |g| g.lan_apply_settings(guest_commands, force));
return;
}
// An integrated server gives guests commands only where the world
// allows them (IntegratedServer.getCustomPermissionLevel).
let effective = guest_commands && (!self.serving() || self.allow_commands());
if let Some(host) = self.lan.as_mut() {
host.settings.guest_commands = guest_commands;
host.settings.force_game_mode = force;
host.hub.config.guest_commands = guest_commands;
host.hub.config.guest_commands = effective;
host.hub.config.force_game_mode = force;
host.hub.resend_commands();
}
}
pub(super) fn lan_port(&self) -> Option<u16> {
if let Some(server) = &self.integrated {
return server.published();
}
if self.serving() {
return self.published_port();
}
self.lan.as_ref().map(|h| h.settings.port)
}
@@ -676,6 +676,31 @@ impl Game<'_> {
);
return;
}
// An integrated server runs every player's commands at their own
// permission level (`CommandSourceStack.permissions`).
if host.hub.config.integrated {
let Some(level) = host.hub.guest(conn).map(|g| g.permission) else {
return;
};
let command = command.trim_start_matches('/').to_owned();
let lines = self.as_guest(host, conn, |g| {
let console = std::mem::replace(&mut g.ui.registries.permission, level);
g.chat_capture = Some(Vec::new());
g.run_command(&command);
g.ui.registries.permission = console;
g.chat_capture.take().unwrap_or_default()
});
for line in lines.unwrap_or_default() {
host.hub.send_to(
conn,
&C::SystemChat(play::SystemChat {
content: horizon_client::lan::data::component_nbt(&line.component()),
overlay: false,
}),
);
}
return;
}
// A LAN world follows its Allow Commands; a dedicated server leaves
// it to the ops list (the guest's permission level).
let allowed = self.options.dedicated.is_some() || self.allow_commands();
+68 -18
View File
@@ -7,6 +7,7 @@
use super::{
Game, Screen,
game_rules_screen::{Exit, RulesScreen},
integrated::ServerOptions,
lan::LanSettings,
};
use horizon_client::{
@@ -50,7 +51,7 @@ enum View {
Restrictions,
GameRules,
}
#[derive(Clone, PartialEq)]
#[derive(Clone, Copy, PartialEq)]
struct Snapshot {
default_mode: i32,
personal_mode: i32,
@@ -406,28 +407,32 @@ impl Restrictions {
impl Game<'_> {
pub(super) fn open_world_options(&mut self) {
let hint = horizon_client::lan::available_port();
let lan = self.lan.is_some();
let mut port = EditBox::new(0.0, 0.0, 150.0, 20.0);
port.max_length = 5;
let (guest_commands, force) = self.lan.as_ref().map_or((false, true), |h| {
(h.settings.guest_commands, h.settings.force_game_mode)
});
if let Some(p) = self.lan_port() {
// The world is the server thread's when there is one.
let state = match &self.integrated {
Some(server) => match server.call(|g| g.server_options()) {
Some(state) => state,
None => return,
},
None => self.local_server_options(),
};
if let Some(p) = state.port {
port.set_value(&p.to_string());
}
let mut options = WorldOptions {
default_mode: self.level.mode(),
personal_mode: self.mode_id(),
cheats: self.allow_commands(),
difficulty: self.ui.difficulty,
lan,
default_mode: state.default_mode,
personal_mode: state.personal_mode,
cheats: state.cheats,
difficulty: state.difficulty,
lan: state.port.is_some(),
port,
hint,
guest_commands,
force,
hardcore: self.level.hardcore,
difficulty_locked: self.level.difficulty_locked,
locked: self.level.difficulty_locked || self.level.hardcore,
guest_commands: state.guest_commands,
force: state.force,
hardcore: state.hardcore,
difficulty_locked: state.difficulty_locked,
locked: state.difficulty_locked || state.hardcore,
scroll: 0.0,
view: View::Options,
rules: None,
@@ -808,7 +813,7 @@ impl Game<'_> {
fn apply_and_close_world_options(&mut self, o: WorldOptions) {
let wanted = o.snapshot();
let before = o.initial.clone();
let before = o.initial;
self.world_options = Some(o);
self.apply_world_options(&before, &wanted);
self.close_world_options();
@@ -891,7 +896,47 @@ impl Game<'_> {
}
}
/// The world options of a world run in the frame.
fn local_server_options(&self) -> ServerOptions {
let (guest_commands, force) = self.lan.as_ref().map_or((false, true), |h| {
(h.settings.guest_commands, h.settings.force_game_mode)
});
ServerOptions {
default_mode: self.level.mode(),
personal_mode: self.mode_id(),
cheats: self.allow_commands(),
difficulty: self.ui.difficulty,
hardcore: self.level.hardcore,
difficulty_locked: self.level.difficulty_locked,
port: self.lan_port(),
guest_commands,
force,
}
}
fn apply_world_options(&mut self, before: &Snapshot, wanted: &Snapshot) {
if let Some(server) = &self.integrated {
// The server applies them; the window tells what came of
// Open to LAN (ShareToLanScreen's messages).
let (b, w) = (*before, *wanted);
server.call(move |g| g.apply_world_options(&b, &w));
if w.lan != b.lan || (w.lan && w.port != b.port) {
match (w.lan, self.lan_port()) {
(true, Some(port)) => self.system_message(Text::translate(
"menu.multiplayerOptions.publish.started.lan",
&[Text::literal(port.to_string())],
)),
(true, None) => {
self.system_message(Text::translate("commands.publish.failed", &[]));
}
(false, _) => self.system_message(Text::translate(
"menu.multiplayerOptions.publish.stopped",
&[],
)),
}
}
return;
}
if wanted.difficulty != before.difficulty {
let name = DIFFICULTIES[usize::from(wanted.difficulty) & 3];
self.as_console(|g| g.run_command(&format!("difficulty {name}")));
@@ -904,10 +949,15 @@ impl Game<'_> {
self.set_default_game_mode(wanted.default_mode);
}
if wanted.personal_mode != before.personal_mode {
self.set_mode_id(wanted.personal_mode);
if self.serving() {
self.set_owner_mode(wanted.personal_mode);
} else {
self.set_mode_id(wanted.personal_mode);
}
}
if wanted.cheats != before.cheats {
self.set_allow_commands(wanted.cheats);
self.owner_allow_commands(wanted.cheats);
}
let settings_changed =
wanted.guest_commands != before.guest_commands || wanted.force != before.force;
+2 -1
View File
@@ -361,8 +361,9 @@ fn login_and_configure(
name: &str,
) -> Result<Option<Parts>, String> {
let e = |e: horizon_protocol::Error| e.to_string();
// ServerLoginPacketListenerImpl: memory connections are not compressed.
let threshold = shared.config.compression_threshold;
if threshold >= 0 {
if threshold >= 0 && !c.is_memory() {
c.send(&login::Clientbound::Compression(login::Compression { threshold }).encode())
.map_err(e)?;
c.set_compression(threshold);
+13 -2
View File
@@ -48,6 +48,10 @@ pub struct HubConfig {
pub max_players: usize,
/// A dedicated server: operators from `ops`, the dedicated-only commands.
pub dedicated: bool,
/// An integrated server (`dedicated` too, since it has no host player):
/// the owner's level from `ops`, the others' from Allow Commands and
/// the guests' command access, and the integrated-only commands.
pub integrated: bool,
}
/// The host player as the other players see them.
@@ -445,7 +449,11 @@ impl Hub {
/// (IntegratedServer.setGuestCommandAccess); a dedicated server its
/// operators' level (`ops`).
fn default_permission(&self, uuid: u128) -> u8 {
if self.config.dedicated {
if self.config.integrated {
// IntegratedServer.getProfilePermissions / getCustomPermissionLevel.
let guests = if self.config.guest_commands { 2 } else { 0 };
self.ops.get(&uuid).copied().unwrap_or(guests)
} else if self.config.dedicated {
self.ops.get(&uuid).copied().unwrap_or(0)
} else if self.config.guest_commands {
2
@@ -682,7 +690,10 @@ impl Hub {
fn send_commands(&self, i: usize) {
let g = &self.guests[i];
let packet = match &self.sync.commands {
Some(tree) => tree.packet(g.permission, self.config.dedicated, &self.sync.builtin),
Some(tree) => {
let dedicated = self.config.dedicated && !self.config.integrated;
tree.packet(g.permission, dedicated, &self.sync.builtin)
}
None => play::Commands {
nodes: vec![play::CommandNode {
kind: 0,
+75 -38
View File
@@ -310,6 +310,8 @@ pub struct Lan {
events: Receiver<NetEvent>,
pub port: u16,
listener: Option<JoinHandle<()>>,
/// Stops the accept loop alone: local connections stay.
listener_stop: Arc<AtomicBool>,
/// The multicast announcement (LanServerPinger); absent when the socket failed.
_pinger: Option<discovery::Pinger>,
}
@@ -325,26 +327,8 @@ impl Lan {
}
/// ServerConnectionListener.startTcpServerListener with a configuration.
pub fn start_with(sync: Arc<data::SyncData>, config: NetConfig) -> io::Result<Self> {
let listener = if config.listen {
let bind = config
.bind
.unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED));
let listener = TcpListener::bind((bind, config.port))?;
listener.set_nonblocking(true)?;
Some(listener)
} else {
None
};
let port = match &listener {
Some(l) => l.local_addr()?.port(),
None => 0,
};
let _pinger = if config.announce && listener.is_some() {
discovery::Pinger::start(config.motd.clone(), port).ok()
} else {
None
};
let (tx, events) = channel();
let (listen, port, announce) = (config.listen, config.port, config.announce);
let shared = Arc::new(Shared {
sync,
events: tx,
@@ -357,21 +341,77 @@ impl Lan {
random: Mutex::new(crate::server::java_properties::now_millis() as u64 | 1),
config,
});
let accept_shared = shared.clone();
let listener = listener
.map(|listener| {
std::thread::Builder::new()
.name("horizon-lan-accept".into())
.spawn(move || accept_loop(listener, accept_shared))
})
.transpose()?;
Ok(Self {
let mut lan = Self {
shared,
events,
port,
listener,
_pinger,
})
port: 0,
listener: None,
listener_stop: Arc::new(AtomicBool::new(false)),
_pinger: None,
};
if listen {
lan.listen(port, announce)?;
}
Ok(lan)
}
/// Start accepting connections on `port` (0 picks a free one), and
/// announce the world on the local network when `announce`
/// (`IntegratedServer.publishServer`'s LanServerPinger). Returns the port.
pub fn listen(&mut self, port: u16, announce: bool) -> io::Result<u16> {
if self.listener.is_some() {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"already listening",
));
}
let listener = Self::bind(self.shared.config.bind, port)?;
self.listen_on(listener, announce)
}
/// The socket [`Lan::listen`] accepts on, bound ahead so that a failure
/// can be reported before the hub is at hand.
pub fn bind(address: Option<std::net::IpAddr>, port: u16) -> io::Result<TcpListener> {
let bind = address.unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED));
let listener = TcpListener::bind((bind, port))?;
listener.set_nonblocking(true)?;
Ok(listener)
}
/// [`Lan::listen`] on a socket already bound.
pub fn listen_on(&mut self, listener: TcpListener, announce: bool) -> io::Result<u16> {
if self.listener.is_some() {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"already listening",
));
}
let port = listener.local_addr()?.port();
let stop = Arc::new(AtomicBool::new(false));
let (accept_shared, accept_stop) = (self.shared.clone(), stop.clone());
let thread = std::thread::Builder::new()
.name("horizon-lan-accept".into())
.spawn(move || accept_loop(listener, accept_shared, &accept_stop))?;
self._pinger = if announce {
discovery::Pinger::start(self.shared.motd(), port).ok()
} else {
None
};
self.listener = Some(thread);
self.listener_stop = stop;
self.port = port;
Ok(port)
}
/// Stop accepting connections and announcing; connections already in
/// (the local one included) stay.
pub fn stop_listening(&mut self) {
self.listener_stop.store(true, Ordering::Relaxed);
if let Some(t) = self.listener.take() {
let _ = t.join();
}
self._pinger = None;
self.port = 0;
}
/// Whether connections from the network are accepted.
pub fn listening(&self) -> bool {
self.listener.is_some()
}
/// `Connection.connectToLocalServer`: a connection through memory, its
/// server end served on its own thread like an accepted socket.
@@ -402,10 +442,7 @@ impl Lan {
}
pub fn stop(&mut self) {
self.shared.stop.store(true, Ordering::Relaxed);
if let Some(t) = self.listener.take() {
let _ = t.join();
}
self._pinger = None;
self.stop_listening();
}
}
impl Drop for Lan {
@@ -414,8 +451,8 @@ impl Drop for Lan {
}
}
fn accept_loop(listener: TcpListener, shared: Arc<Shared>) {
while !shared.stop.load(Ordering::Relaxed) {
fn accept_loop(listener: TcpListener, shared: Arc<Shared>, stop: &AtomicBool) {
while !shared.stop.load(Ordering::Relaxed) && !stop.load(Ordering::Relaxed) {
match listener.accept() {
Ok((stream, addr)) => {
let shared = shared.clone();
+1
View File
@@ -241,6 +241,7 @@ fn server(resources: &Path) -> Server {
view_distance: 3,
simulation_distance: 3,
dedicated: false,
integrated: false,
dimension: "minecraft:overworld".into(),
seed: 1234,
max_players: 8,
@@ -227,6 +227,10 @@ impl Connection {
},
})
}
/// `Connection.isMemoryConnection`: through a [`Pipe`] rather than a socket.
pub fn is_memory(&self) -> bool {
matches!(self.reader.stream, Stream::Memory(_))
}
/// ClientboundLoginCompressionPacket: negative thresholds disable compression.
pub fn set_compression(&mut self, threshold: i32) {
let t = usize::try_from(threshold).ok();