Run single player on an integrated server thread (opt-in)

With --server-thread or HORIZON_SERVER_THREAD=1, opening a single-player
world starts a game of its own on a "Server thread" over the shared
resources, as vanilla's IntegratedServer does, and the window joins it as a
player over a local connection. The world tick then never runs inside a
frame.

- The server listens on 127.0.0.1 only, lets in the window's profile alone,
  without compression, and makes it an operator when the world allows
  commands.
- The window's player is the world's own player: it loads from and saves to
  players/data/<singleplayer_uuid>.dat, so the world opens the same way in
  either mode.
- A pause screen pauses the server (IntegratedServer.tickServer), and
  leaving the world or quitting waits for the server to save.
- The integrated server does not mesh sections it never draws.
- Worlds whose player is outside the Overworld open the usual way for now.
- The bench summary reports the 0.1% low.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-16 17:18:03 +02:00
parent c2f4ecc188
commit 56dc4352d2
8 changed files with 434 additions and 36 deletions
+12 -8
View File
@@ -467,13 +467,16 @@ impl FrameStats {
}
let total: f64 = sorted.iter().map(|&m| f64::from(m)).sum();
let percentile = |p: f64| sorted[((n as f64 * p).ceil() as usize).clamp(1, n) - 1];
// Average frame time of the slowest 1% of frames, as frames per second.
let slowest = n.div_ceil(100);
let slow: f64 = sorted[n - slowest..]
.iter()
.map(|&m| f64::from(m))
.sum::<f64>()
/ slowest as f64;
// Average frame time of the slowest 1% (0.1%) of frames, as frames per second.
let low = |per: usize| {
let slowest = n.div_ceil(per);
let slow: f64 = sorted[n - slowest..]
.iter()
.map(|&m| f64::from(m))
.sum::<f64>()
/ slowest as f64;
1000.0 / slow
};
// Where the slowest 1% of frames by CPU time go.
let slow_phases = {
let mut cpu = self.cpu.clone();
@@ -487,7 +490,8 @@ impl FrameStats {
"frames": n,
"seconds": total / 1000.0,
"avg_fps": n as f64 * 1000.0 / total,
"low_1pct_fps": 1000.0 / slow,
"low_1pct_fps": low(100),
"low_01pct_fps": low(1000),
"p50_ms": percentile(0.5),
"p95_ms": percentile(0.95),
"p99_ms": percentile(0.99),
+28 -2
View File
@@ -56,6 +56,7 @@ mod golems;
mod growth;
mod hand;
mod initial_spawn;
mod integrated;
mod item_draw;
mod item_particles;
mod jukebox;
@@ -243,6 +244,11 @@ struct Options {
benchmark: Option<String>,
/// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt.
dev_mods: Vec<PathBuf>,
/// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on
/// an integrated server thread (game/integrated.rs).
server_thread: bool,
/// Set on the integrated server's own options: it draws nothing, so it skips meshing.
integrated: bool,
}
impl Options {
/// The name to join servers with: the one given, else the offline name kept
@@ -294,6 +300,8 @@ impl Options {
dedicated: None,
benchmark: None,
dev_mods: Vec::new(),
server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1"),
integrated: false,
};
let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok();
let mut args = std::env::args().skip(1);
@@ -314,6 +322,7 @@ impl Options {
"--no-pause" => o.no_pause = true,
"--offscreen" => o.offscreen = true,
"--control" => o.control = Some(horizon_client::control::default_path()),
"--server-thread" => o.server_thread = true,
_ => {
let value = args
.next()
@@ -1074,6 +1083,8 @@ struct Game<'a> {
remote: Option<remote::Remote>,
/// This world is open to the network (game/lan.rs).
lan: Option<lan::LanHost>,
/// Single player's server thread, which `remote` is connected to.
integrated: Option<integrated::Integrated>,
/// The open world is shared behind an invite code (game/friends.rs).
friends: Option<friends::Sharing>,
world_options: Option<lan_screen::WorldOptions>,
@@ -3632,7 +3643,7 @@ impl Game<'_> {
}
/// `Minecraft.pause`: a single-player game with a pausing screen open.
fn pauses_game(&self) -> bool {
self.remote.is_none()
(self.remote.is_none() || self.integrated.is_some())
&& self.lan.is_none()
&& self.title.is_none()
&& (matches!(
@@ -6129,8 +6140,11 @@ impl Game<'_> {
creative: bool,
create: Option<&horizon_client::title::WorldOptions>,
) -> Result<()> {
self.perf.world_opening();
let save_root = std::env::current_dir()?.join("saves").join(folder);
if integrated::wanted(&self.options, &save_root) {
return self.open_integrated(folder, name, seed, creative, create);
}
self.perf.world_opening();
horizon_client::save::upgrade_older_world(&save_root)?;
horizon_client::save::migrate_legacy(&save_root)?;
self.session_lock = None;
@@ -6392,6 +6406,8 @@ impl Game<'_> {
streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed));
streaming.sky_light = dim != Dim::Nether;
streaming.nether_shading = dim == Dim::Nether;
// The integrated server draws nothing (the dedicated server keeps its behaviour).
streaming.mesh = !self.options.integrated;
Ok((streaming, save))
}
/// Change dimension through a portal (Entity.changeDimension with
@@ -6587,6 +6603,11 @@ impl Game<'_> {
return Ok(());
}
self.saved_for_exit = true;
if let Some(server) = self.integrated.take() {
// The server thread saves the world.
server.stop();
return Ok(());
}
self.close_container();
if self.remote.is_none() {
self.stats.custom("leave_game", 1);
@@ -8340,6 +8361,7 @@ impl Game<'_> {
self.save_schedule();
self.save_warden_tracker();
self.sync_level();
self.store_owner();
self.level.write(&self.world_root)?;
self.save_world_state();
self.message = Some(("Saved the game".into(), Instant::now()));
@@ -9652,6 +9674,9 @@ impl ApplicationHandler for Game<'_> {
}
self.limit_frame();
self.pause = self.pauses_game();
if let Some(server) = &self.integrated {
server.set_paused(self.pause);
}
self.clock.end_frame(self.pause);
let finished = self
.renderer
@@ -10047,6 +10072,7 @@ impl<'a> Game<'a> {
persist: Default::default(),
remote: None,
lan: None,
integrated: None,
world_options: None,
options_to_world_options: false,
command_block_screen: None,
+2 -2
View File
@@ -525,7 +525,7 @@ impl Game<'_> {
/// Load the spawn area and find the world spawn as single player does,
/// without keeping a player there.
fn settle_spawn(&mut self) -> Result<()> {
pub(super) fn settle_spawn(&mut self) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(600);
while self.player.is_none() {
self.update_world();
@@ -541,7 +541,7 @@ impl Game<'_> {
/// The chunks to keep loaded: the players' (lan_update_streaming), or
/// the spawn chunk while nobody is online.
fn update_dedicated_streaming(&mut self) {
pub(super) fn update_dedicated_streaming(&mut self) {
let center = self
.lan
.as_ref()
@@ -0,0 +1,288 @@
//! The integrated server (`IntegratedServer`): single player's world runs on
//! its own "Server thread", as vanilla's does, and the window joins it as a
//! player over a local connection, so a world tick never holds up a frame.
//!
//! 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
//! outside the Overworld open the usual way, since network players stay in
//! the Overworld so far.
use super::{
Dim, Game, Options, PackResources, Resources,
lan::{LanSettings, Owner},
};
use horizon_client::{
Result,
audio::Audio,
hud::HudAtlas,
lan::{MAX_PLAYERS, NetConfig, hub::HubConfig},
save::Level,
settings::Settings,
title::WorldOptions,
};
use horizon_protocol::{crypto::offline_uuid, text::translatable};
use std::{
net::{IpAddr, Ipv4Addr},
path::Path,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc::{Sender, channel},
},
thread::JoinHandle,
time::{Duration, Instant},
};
/// What the window tells its server thread.
#[derive(Default)]
struct Flags {
/// `Minecraft.pause`: a single-player pause screen is open.
paused: AtomicBool,
stop: AtomicBool,
}
/// The window's handle on its server thread.
pub(super) struct Integrated {
flags: Arc<Flags>,
thread: Option<JoinHandle<()>>,
}
impl Integrated {
/// `IntegratedServer.tickServer` skips the world while the game is paused.
pub fn set_paused(&self, paused: bool) {
self.flags.paused.store(paused, Ordering::Relaxed);
}
/// `IntegratedServer.halt(true)`: returns once the world is saved and let go.
pub fn stop(mut self) {
self.halt();
}
fn halt(&mut self) {
self.flags.stop.store(true, Ordering::Relaxed);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
impl Drop for Integrated {
fn drop(&mut self) {
self.halt();
}
}
/// The world to open and the player who owns it.
struct Launch {
folder: String,
name: Option<String>,
seed: Option<i64>,
creative: bool,
create: Option<WorldOptions>,
/// The window's profile: the only one let in, and the world's player.
owner: u128,
}
/// Whether this world opens on a server thread: asked for, and its player
/// (if any yet) in the Overworld.
pub(super) fn wanted(options: &Options, world: &Path) -> bool {
options.server_thread
&& options.dedicated.is_none()
&& Level::read(world).is_none_or(|l| Dim::from_id(&l.dimension) == Dim::Overworld)
}
impl Game<'_> {
/// `Minecraft.doWorldLoad`: start the server thread on the world, wait
/// until it listens, then join it.
pub(super) fn open_integrated(
&mut self,
folder: &str,
name: Option<&str>,
seed: Option<i64>,
creative: bool,
create: Option<&WorldOptions>,
) -> Result<()> {
let auth = horizon_client::auth::current();
let player = auth
.as_ref()
.map_or_else(|| self.options.player_name(), |a| a.name.clone());
let launch = Launch {
folder: folder.to_owned(),
name: name.map(str::to_owned),
seed,
creative,
create: create.cloned(),
// An offline-mode server names its players by their offline profile.
owner: offline_uuid(&player),
};
let mut options = self.options.clone();
// A server without a console: no local player, no window, no control socket.
options.dedicated = Some(Vec::new());
options.server_thread = false;
options.integrated = true;
options.control = None;
options.benchmark = None;
options.frames = None;
options.world_frames = None;
options.report = None;
options.server = None;
options.world = None;
options.dev_mods.clear();
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 server_flags = flags.clone();
let thread = std::thread::Builder::new()
.name("Server thread".into())
.spawn(move || {
let result = serve(
&res,
pack,
options,
settings,
launch,
&server_flags,
&ready_tx,
);
if let Err(e) = result {
log::error!("Horizon: integrated server: {e}");
let _ = ready_tx.send(Err(e.to_string()));
}
})?;
let handle = Integrated {
flags,
thread: Some(thread),
};
let port = match ready.recv() {
Ok(Ok(port)) => port,
Ok(Err(e)) => return Err(e.into()),
Err(_) => return Err("the integrated server stopped".into()),
};
self.connect_server(&format!("127.0.0.1:{port}"), &player)?;
self.integrated = Some(handle);
Ok(())
}
/// The server thread's loop (`MinecraftServer.runServer`): 20 ticks a
/// second, the world held while the window is paused.
fn run_integrated(
&mut self,
launch: Launch,
flags: &Flags,
ready: &Sender<std::result::Result<u16, String>>,
) -> Result<()> {
self.open_world(
&launch.folder,
launch.name.as_deref(),
launch.seed,
launch.creative,
launch.create.as_ref(),
)?;
let saved = Box::new(self.level.clone());
let view_distance = self.settings.render_distance.clamp(2, 32);
let config = HubConfig {
default_game_mode: self.level.mode(),
guest_commands: true,
force_game_mode: false,
hardcore: self.level.hardcore,
view_distance,
simulation_distance: self.settings.simulation_distance.clamp(2, 32),
dimension: self.dim.id().to_owned(),
seed: self.level.seed,
max_players: MAX_PLAYERS,
// No player of its own: the hub runs without a host.
dedicated: true,
};
let owner = launch.owner;
let net = NetConfig {
bind: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)),
// A local 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", &[]))
})),
..NetConfig::lan(0, self.level.name.clone(), MAX_PLAYERS)
};
let settings = LanSettings {
port: 0,
guest_commands: true,
force_game_mode: false,
};
self.lan_host(settings, net, config, None)?;
let commands = self.allow_commands();
let port = {
let host = self
.lan
.as_mut()
.ok_or("the integrated server did not start")?;
// The owner is an operator when the world allows commands
// (`IntegratedPlayerList`, `MinecraftServer.getProfilePermissions`).
host.hub.ops.insert(owner, if commands { 4 } else { 0 });
host.owner = Some(Owner {
uuid: owner,
saved: Some(saved),
});
host.settings.port
};
let _ = ready.send(Ok(port));
self.settle_spawn()?;
let mut next = Instant::now();
while !flags.stop.load(Ordering::Relaxed) {
self.update_dedicated_streaming();
self.update_world();
if flags.paused.load(Ordering::Relaxed) {
// Only the connections run.
self.tick_lan();
} else {
self.tick()?;
}
let rate = self.clock.rate().max(1.0);
next += Duration::from_secs_f64(1.0 / f64::from(rate));
let now = Instant::now();
if next > now {
std::thread::sleep(next - now);
} else if now - next > Duration::from_secs(2) {
next = now;
}
}
self.stop_integrated()
}
/// `MinecraftServer.stopServer`: the players are saved and sent away,
/// then the world is saved.
fn stop_integrated(&mut self) -> Result<()> {
if let Some(mut host) = self.lan.take() {
for g in &host.hub.guests {
self.save_guest(&host, g);
}
let conns: Vec<u32> = host.hub.guests.iter().map(|g| g.conn).collect();
for conn in conns {
host.hub.kick(
conn,
translatable("multiplayer.disconnect.server_shutdown", &[]),
);
}
self.lan = Some(host);
}
std::thread::sleep(Duration::from_millis(100));
self.save_game()?;
self.lan_close(false);
self.save.flush();
self.session_lock = None;
Ok(())
}
}
/// The server thread: a game of its own over the shared resources.
fn serve(
res: &Arc<Resources>,
pack: PackResources,
options: Options,
settings: Settings,
launch: Launch,
flags: &Flags,
ready: &Sender<std::result::Result<u16, String>>,
) -> Result<()> {
let atlas = HudAtlas::build(&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)
}
+49 -3
View File
@@ -55,6 +55,17 @@ pub(super) struct LanHost {
mob_state: HashMap<u32, (i32, bool)>,
/// The guest each mob sees as its player, when not the host (game/lan_mobs.rs).
pub mob_players: HashMap<u32, u32>,
/// An integrated server's owner (game/integrated.rs).
pub owner: Option<Owner>,
}
/// The player who owns an integrated server's world: a guest whose state is
/// the world's own player (`players/data/<singleplayer_uuid>.dat`), as in
/// single player.
pub(super) struct Owner {
pub uuid: u128,
/// The world's player as loaded, until the owner joins.
pub saved: Option<Box<horizon_client::save::Level>>,
}
/// A stable UUID for an entity that has none.
@@ -465,6 +476,7 @@ impl Game<'_> {
broken: Vec::new(),
mob_state: HashMap::new(),
mob_players: HashMap::new(),
owner: None,
});
self.audio.capture = Some(Vec::new());
Ok(())
@@ -477,7 +489,7 @@ impl Game<'_> {
return;
};
for g in &host.hub.guests {
playerdata::save(g, &self.world_root);
self.save_guest(&host, g);
}
host.hub.disconnect_all();
// Give the writer threads a moment to flush the disconnect packets.
@@ -494,6 +506,30 @@ impl Game<'_> {
}
}
/// Save a guest when they leave or the world closes: an integrated
/// server's owner with the world (`save_game`), anyone else in their file.
pub(super) fn save_guest(&mut self, host: &LanHost, guest: &horizon_client::lan::guest::Guest) {
if host.owner.as_ref().is_some_and(|o| o.uuid == guest.uuid) {
if guest.placed {
playerdata::store(guest, &mut self.level);
}
} else {
playerdata::save(guest, &self.world_root);
}
}
/// The integrated server's owner into the world's player, for `Level::write`.
pub(super) fn store_owner(&mut self) {
let Some(host) = &self.lan else {
return;
};
let Some(uuid) = host.owner.as_ref().map(|o| o.uuid) else {
return;
};
if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == uuid && g.placed) {
playerdata::store(g, &mut self.level);
}
}
/// The world's default game mode (`defaultgamemode`).
pub(super) fn set_default_game_mode(&mut self, mode: i32) {
self.level.game_mode = mode;
@@ -664,7 +700,7 @@ impl Game<'_> {
self.container_openers_changed(pos, false);
}
self.lan_crafting_left(&mut host, &mut guest);
playerdata::save(&guest, &self.world_root);
self.save_guest(&host, &guest);
host.models.remove(&guest.conn);
if self.options.dedicated.is_some() && guest.placed {
super::dedicated::log(
@@ -707,10 +743,20 @@ impl Game<'_> {
let default_mode = host.hub.config.default_game_mode;
let force = host.hub.config.force_game_mode;
let root = self.world_root.clone();
let owner = host.owner.as_mut();
let Some(g) = host.hub.guest_mut(conn) else {
return;
};
let known = playerdata::load(g, &root);
let saved = owner
.filter(|o| o.uuid == g.uuid)
.and_then(|o| o.saved.take());
let known = match saved {
Some(level) => {
playerdata::apply(g, &level);
level.position.is_some()
}
None => playerdata::load(g, &root),
};
if !known || force {
g.game_mode = default_mode;
}
+13
View File
@@ -274,6 +274,14 @@ impl Game<'_> {
if let Some(mut r) = self.remote.take() {
r.session.disconnect();
}
// Single player's server thread saves the world before the title shows.
let single_player = match self.integrated.take() {
Some(server) => {
server.stop();
true
}
None => false,
};
horizon_client::crash::clear_detail("Server");
self.debug_charts.reset();
self.tab_list.reset();
@@ -296,6 +304,11 @@ impl Game<'_> {
}
let saves = std::env::current_dir()?.join("saves");
let mut title = horizon_client::title::Title::new(saves.clone(), &self.options.resources);
if single_player && reason.is_none() {
self.title = Some(title);
self.capture(false);
return Ok(());
}
title.mode = horizon_client::title::Mode::Multiplayer(match reason {
Some(reason) => horizon_client::multiplayer::Screen::Disconnected {
reason,
+34 -21
View File
@@ -45,6 +45,13 @@ pub fn load(guest: &mut Guest, world: &Path) -> bool {
..Level::default()
};
level.read_player(&tag);
level.player_extra = Some(tag);
apply(guest, &level);
true
}
/// Give a guest the player state read into `level`.
pub fn apply(guest: &mut Guest, level: &Level) {
if let Some(p) = level.position {
guest.position = p;
guest.previous_position = p;
@@ -61,7 +68,7 @@ pub fn load(guest: &mut Guest, world: &Path) -> bool {
guest.xp_total = level.xp_total;
guest.game_mode = level.mode();
guest.selected = (level.selected_slot.max(0) as usize).min(8);
guest.saved = Some(tag);
guest.saved = level.player_extra.clone();
if level.ender_items.len() == 27 {
guest.ender_items = level.ender_items.clone();
}
@@ -85,30 +92,41 @@ pub fn load(guest: &mut Guest, world: &Path) -> bool {
_ => {}
}
}
true
}
/// Save a guest (PlayerDataStorage.save).
pub fn save(guest: &Guest, world: &Path) {
let mut level = Level {
player_uuid: Some(uuid_ints(guest.uuid)),
position: Some(guest.position),
rotation: [guest.yaw, guest.pitch],
health: guest.health,
food: guest.food,
saturation: guest.saturation,
xp_level: guest.xp_level,
xp_progress: guest.xp_progress,
xp_total: guest.xp_total,
game_mode: guest.game_mode,
creative: guest.game_mode == 1,
selected_slot: guest.selected as i32,
on_ground: guest.on_ground,
dimension: "minecraft:overworld".into(),
player_extra: guest.saved.clone(),
ender_items: guest.ender_items.clone(),
..Level::default()
};
store(guest, &mut level);
let file = path(world, guest.uuid);
if let Some(dir) = file.parent() {
let _ = std::fs::create_dir_all(dir);
}
let _ = write_dat(&file, level.player_tag());
}
/// Put a guest's state in `level`'s player fields.
pub fn store(guest: &Guest, level: &mut Level) {
level.position = Some(guest.position);
level.rotation = [guest.yaw, guest.pitch];
level.health = guest.health;
level.food = guest.food;
level.saturation = guest.saturation;
level.xp_level = guest.xp_level;
level.xp_progress = guest.xp_progress;
level.xp_total = guest.xp_total;
level.game_mode = guest.game_mode;
level.creative = guest.game_mode == 1;
level.selected_slot = guest.selected as i32;
level.on_ground = guest.on_ground;
level.player_extra = guest.saved.clone();
level.ender_items = guest.ender_items.clone();
level.inventory.clear();
level.inventory_components.clear();
let mut put = |slot: u8, stack: &Option<ItemStack>| {
if let Some(s) = stack {
level
@@ -127,9 +145,4 @@ pub fn save(guest: &Guest, world: &Path) {
put(101, &guest.armor[2]);
put(100, &guest.armor[3]);
put(150, &guest.offhand);
let file = path(world, guest.uuid);
if let Some(dir) = file.parent() {
let _ = std::fs::create_dir_all(dir);
}
let _ = write_dat(&file, level.player_tag());
}
+8
View File
@@ -200,6 +200,8 @@ pub struct Streaming {
/// More areas to keep loaded (centre chunk, radius), e.g. around guests
/// of a world open to the network. They are generated and kept but not meshed.
pub extra: Vec<((i32, i32), i32)>,
/// Mesh the sections for drawing (false on a server thread).
pub mesh: bool,
}
/// Snapshot only after a scan found no missing candidates. Public range fields
/// and `World::chunks` can change without going through Streaming, so compare
@@ -466,6 +468,7 @@ impl Streaming {
meshed_total: 0,
remote: false,
extra: Vec::new(),
mesh: true,
}
}
/// Resource packs reloaded (`LevelRenderer.allChanged`): mesh with the new
@@ -959,6 +962,11 @@ impl Streaming {
Job::Light(x, z, region, self.sequence, self.sky_light),
);
}
// A server draws nothing: its sections are never meshed.
if !self.mesh {
world.dirty_sections.clear();
return (uploads, removed);
}
// Meshing once the column and its neighbours are lit, and the column
// is within the render distance. Sections set aside past it come back
// when the player moves: a column that loads with its light gets no