From 6c6b58dd55fb068101467887fa3891dbc970ddc8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:23:00 +0200 Subject: [PATCH] Server: the level follows its lone player through Nether and End portals The server holds one level at a time, as the in-frame game does. While one player is online (single player on the server thread, or a world with one player in it), a Nether or End portal swaps the server's level the in-frame way (switch_level, split out of enter_dimension) and the player is moved as ServerPlayer.teleport moves it into another level: a Respawn packet keeping all data, the difficulty, permission level, teleport, abilities, level info, inventory, effects and the portal travel sound, then a teleport to the exit once the destination has loaded (the Nether portal found or built, the End platform, the Overworld's spawn column). Respawning away from the Overworld takes the level back there first. What the hub sends follows the level: - Chunks carry the level's sections only (y 0 to 255 in the Nether and the End), without sky light where the dimension has none, and heightmaps from the level's floor. Until now every level went out with the Overworld's 24 sections, which a client in the Nether or the End reads 64 blocks off. - The dimension type follows the level the hub names; the default spawn position is the Overworld's. - A level switch keeps the block change log (an open hub kept none after a portal) and the sculk watch list. Worlds whose player is in the Nether or the End now open on the server thread too. The network client maps the End to the End (it drew it as the Overworld) and shows the death screen on its own PlayerCombatKill, as ClientPacketListener.handlePlayerCombatKill does, whatever health came last. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 32 ++- crates/horizon-client/src/game/end.rs | 125 +++++---- crates/horizon-client/src/game/integrated.rs | 16 +- crates/horizon-client/src/game/lan.rs | 1 + crates/horizon-client/src/game/lan_actions.rs | 3 +- .../horizon-client/src/game/nether_portal.rs | 33 ++- crates/horizon-client/src/game/remote.rs | 13 +- .../horizon-client/src/game/server_travel.rs | 248 ++++++++++++++++++ crates/horizon-client/src/lan/chunks.rs | 96 +++++-- crates/horizon-client/src/lan/hub.rs | 85 +++++- crates/horizon-client/src/save.rs | 15 +- 11 files changed, 553 insertions(+), 114 deletions(-) create mode 100644 crates/horizon-client/src/game/server_travel.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 73fcbbf52..1c7145b9e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -112,6 +112,7 @@ mod scoreboard; mod screens; mod sculk; mod sculk_fixture; +mod server_travel; mod shader_packs; mod shield; mod sign_edit; @@ -972,6 +973,8 @@ struct Game<'a> { world_root: PathBuf, /// A player carried through a portal, re-placed once the destination loads. travelling: Option<(PlayerMotion, Vec3)>, + /// A server's lone player on its way to another level. + server_trip: Option, /// Nether portals: the player's, items' and mobs' (game/nether_portal.rs). portals: nether_portal::Portals, /// The pending travel goes through an End portal (EndPortalBlock destinations). @@ -6434,6 +6437,17 @@ impl Game<'_> { let Some(player) = self.player.take() else { return Ok(()); }; + let from = self.dim; + let destination = self.switch_level(target, player.position)?; + self.trigger_dimension(from, target); + self.travelling = Some((player, destination)); + self.end_travel = (target == Dim::End || from == Dim::End) && self.end_portal_travel; + Ok(()) + } + /// The level swap under a dimension change: save the departing level, + /// open `target`'s, and return where a player leaving from `from` goes + /// (scaled coordinates, or the End portal's fixed destination). + pub(super) fn switch_level(&mut self, target: Dim, from: Vec3) -> Result { // Save the departing dimension's changed chunks. self.streaming.save(&mut self.world, true); let keys: Vec<_> = self.world.modified.drain().collect(); @@ -6449,11 +6463,10 @@ impl Game<'_> { _ => 1.0, }; let destination = self.end_destination(target).unwrap_or(Vec3::new( - player.position.x * scale, - player.position.y, - player.position.z * scale, + from.x * scale, + from.y, + from.z * scale, )); - let from_end = self.dim == Dim::End; let (streaming, save) = self.make_streaming(&self.world_root.clone(), target, self.level.seed)?; let mut world = World::new(self.res.facts.air, self.level.seed); @@ -6461,12 +6474,14 @@ impl Game<'_> { world.game_time = self.world.game_time; world.day_time = self.world.day_time; world.weather = self.world.weather; + // An open hub keeps hearing the new level's block changes. + world.block_log = self.world.block_log.as_ref().map(|_| Vec::new()); + // The sculk tables' watched blocks are built once per game. + world.watched = std::mem::take(&mut self.world.watched); self.streaming = streaming; self.world = world; self.save = save; - let from = self.dim; self.dim = target; - self.trigger_dimension(from, target); self.level.dimension = target.id().to_owned(); self.block_ticks = Ticks::new(self.level.seed as i32); self.tick_chunks.clear(); @@ -6479,13 +6494,11 @@ impl Game<'_> { self.pickups.clear(); self.orbs.clear(); self.mining = None; - self.travelling = Some((player, destination)); - self.end_travel = (target == Dim::End || from_end) && self.end_portal_travel; if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } self.apply_settings(); - Ok(()) + Ok(destination) } /// PortalShape: an obsidian frame around 2..=21 by 3..=21 empty blocks. fn portal_shape(&self, start: [i32; 3], x_axis: bool) -> Option<([i32; 3], i32, i32)> { @@ -10045,6 +10058,7 @@ impl<'a> Game<'a> { dim: Dim::Overworld, world_root: PathBuf::new(), travelling: None, + server_trip: None, portals: Default::default(), end_travel: false, respawn_config: None, diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index d02904872..a80c51796 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -222,7 +222,7 @@ impl Game<'_> { } } - fn block_name(&self, p: [i32; 3]) -> std::sync::Arc { + pub(super) fn block_name(&self, p: [i32; 3]) -> std::sync::Arc { self.res .facts .get(self.world.block(p[0], p[1], p[2])) @@ -366,31 +366,11 @@ impl Game<'_> { if self.travelling.is_some() || p.health.dead_or_dying() { return Ok(()); } - let w = f64::from(p.dimensions.width) / 2.0; - let lo = [p.position.x - w, p.position.y, p.position.z - w]; - let hi = [ - p.position.x + w, - p.position.y + f64::from(p.dimensions.height), - p.position.z + w, - ]; - let mut portal = false; - let mut gateway = None; - for x in lo[0].floor() as i32..=hi[0].floor() as i32 { - for y in lo[1].floor() as i32..=hi[1].floor() as i32 { - for z in lo[2].floor() as i32..=hi[2].floor() as i32 { - let name = self.block_name([x, y, z]); - // EndPortalBlock entity-inside shape: y 6/16..12/16. - if &*name == "minecraft:end_portal" - && lo[1] < f64::from(y) + 0.75 - && hi[1] > f64::from(y) + 0.375 - { - portal = true; - } else if &*name == "minecraft:end_gateway" && self.dim == Dim::End { - gateway = Some([x, y, z]); - } - } - } - } + let (portal, gateway) = self.inside_end_portals( + p.position, + f64::from(p.dimensions.width), + f64::from(p.dimensions.height), + ); if portal { if self.portals.player.cooldown == 0 { let target = if self.dim == Dim::End { @@ -417,6 +397,38 @@ impl Game<'_> { Ok(()) } + /// Whether a `width` by `height` box at `position` is inside an End + /// portal (its entity-inside shape), and the End gateway it touches. + pub(super) fn inside_end_portals( + &self, + position: Vec3, + width: f64, + height: f64, + ) -> (bool, Option<[i32; 3]>) { + let w = width / 2.0; + let lo = [position.x - w, position.y, position.z - w]; + let hi = [position.x + w, position.y + height, position.z + w]; + let mut portal = false; + let mut gateway = None; + for x in lo[0].floor() as i32..=hi[0].floor() as i32 { + for y in lo[1].floor() as i32..=hi[1].floor() as i32 { + for z in lo[2].floor() as i32..=hi[2].floor() as i32 { + let name = self.block_name([x, y, z]); + // EndPortalBlock entity-inside shape: y 6/16..12/16. + if &*name == "minecraft:end_portal" + && lo[1] < f64::from(y) + 0.75 + && hi[1] > f64::from(y) + 0.375 + { + portal = true; + } else if &*name == "minecraft:end_gateway" && self.dim == Dim::End { + gateway = Some([x, y, z]); + } + } + } + } + (portal, gateway) + } + /// EndPortalBlock.getPortalDestination for the pending enter_dimension. pub(super) fn end_destination(&self, target: Dim) -> Option { if !self.end_portal_travel { @@ -451,10 +463,36 @@ impl Game<'_> { self.previous_eye = 1.62; self.clock.reset(); } - let mut position = target; - if let Some(job) = self.end.job.take() { - position = self.resolve_gateway(job, target)?; - } else if self.dim == Dim::End { + let position = if let Some(job) = self.end.job.take() { + self.resolve_gateway(job, target)? + } else { + let (position, yaw) = self.end_arrival(target)?; + if let Some(yaw) = yaw { + self.yaw = yaw; + player.yaw = yaw; + player.head_yaw = yaw; + } + position + }; + player.position = position; + player.velocity = Vec3::ZERO; + player.fall_distance = 0.0; + self.previous_position = player.position; + self.player = Some(player); + self.pad.player_replaced(); + self.sway = Default::default(); + self.apply_equipment(); + let pitch = self.world.random.next_float() * 0.4 + 0.8; + self.audio + .play("minecraft:block.portal.travel", None, 0.25, pitch); + Ok(()) + } + + /// Where an End portal's traveller lands once `target` has loaded, and + /// the yaw it faces there: the platform below the End's spawn point, + /// facing west, or the top of the Overworld's spawn column. + pub(super) fn end_arrival(&mut self, target: Vec3) -> Result<(Vec3, Option)> { + if self.dim == Dim::End { // EndPlatformFeature.createEndPlatform below the spawn point. let origin = [END_SPAWN[0], END_SPAWN[1] - 1, END_SPAWN[2]]; for dz in -2..=2 { @@ -473,28 +511,13 @@ impl Game<'_> { } } // Direction.WEST.toYRot(). - self.yaw = 90.0; - player.yaw = 90.0; - player.head_yaw = 90.0; - } else { - // ServerPlayer.findRespawnPositionAndUseSpawnBlock: onto the spawn column. - let y = self - .land_column(target.x.floor() as i32, target.z.floor() as i32) - .map_or(target.y, f64::from); - position = Vec3::new(target.x, y, target.z); + return Ok((target, Some(90.0))); } - player.position = position; - player.velocity = Vec3::ZERO; - player.fall_distance = 0.0; - self.previous_position = player.position; - self.player = Some(player); - self.pad.player_replaced(); - self.sway = Default::default(); - self.apply_equipment(); - let pitch = self.world.random.next_float() * 0.4 + 0.8; - self.audio - .play("minecraft:block.portal.travel", None, 0.25, pitch); - Ok(()) + // ServerPlayer.findRespawnPositionAndUseSpawnBlock: onto the spawn column. + let y = self + .land_column(target.x.floor() as i32, target.z.floor() as i32) + .map_or(target.y, f64::from); + Ok((Vec3::new(target.x, y, target.z), None)) } /// Dying away from the Overworld respawns at the world spawn there. diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 1ecdbff28..7b5f3cced 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -8,11 +8,9 @@ //! //! 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. +//! does not do everything single player does yet. use super::{ - Dim, Game, Options, PackResources, Resources, + Game, Options, PackResources, Resources, lan::{LanSettings, Owner}, }; use horizon_client::{ @@ -20,7 +18,6 @@ use horizon_client::{ audio::Audio, hud::HudAtlas, lan::{Lan, MAX_PLAYERS, NetConfig, hub::HubConfig}, - save::Level, settings::Settings, title::WorldOptions, }; @@ -137,12 +134,9 @@ struct Launch { player: String, } -/// 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) +/// Whether this world opens on a server thread: asked for. +pub(super) fn wanted(options: &Options, _world: &Path) -> bool { + options.server_thread && options.dedicated.is_none() } impl Game<'_> { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 3fc959027..0cc61255d 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -851,6 +851,7 @@ impl Game<'_> { } self.lan_flush_effects(&mut host); self.tick_guests(&mut host); + self.tick_server_travel(&mut host); self.lan_swings(&mut host); self.lan_update_streaming(&host); self.lan_update_models(&mut host); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 716bd6ae0..4572fc43c 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -846,6 +846,7 @@ impl Game<'_> { if !host.hub.guests[i].dead { return; } + self.respawn_level(host); let g = &mut host.hub.guests[i]; g.dead = false; g.health = 20.0; @@ -891,7 +892,7 @@ impl Game<'_> { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { continue; }; - if host.hub.guests[gi].dead { + if host.hub.guests[gi].dead || self.on_server_trip(conn) { continue; } let play = host.play.entry(conn).or_default(); diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index 01a657b0b..df684e713 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -92,13 +92,13 @@ impl Game<'_> { } } /// `ServerLevel.isAllowedToEnterPortal`. - fn may_enter(&self, target: Dim) -> bool { + pub(super) fn may_enter(&self, target: Dim) -> bool { target != Dim::Nether || self.ui.rules.bool("allow_entering_nether_using_portals") } /// The plan of an entity of `width` by `height` at `at` going through the /// portal at `entry` (`getDimensionTransitionFromExit` and the scaled, /// clamped exit of `getPortalDestination`). - fn portal_plan( + pub(super) fn portal_plan( &self, entry: BlockPos, at: Vec3, @@ -195,7 +195,7 @@ impl Game<'_> { } /// The exit portal of `plan` in the loaded dimension: the closest one /// within reach, else one built by `PortalForcer.createPortal`. - fn nether_exit_portal(&mut self, plan: &Plan) -> Option { + pub(super) fn nether_exit_portal(&mut self, plan: &Plan) -> Option { let to_nether = plan.dim == Dim::Nether; let radius = if to_nether { 16 } else { 128 }; let border = self.border_bounds(); @@ -231,7 +231,7 @@ impl Game<'_> { } /// `NetherPortalBlock.createDimensionTransition`: the arrival position /// and the yaw turned by. - fn arrival(&self, plan: &Plan, exit: FoundRectangle) -> (Vec3, f32) { + pub(super) fn arrival(&self, plan: &Plan, exit: FoundRectangle) -> (Vec3, f32) { let b = &self.res.behaviours; let corner = exit.min_corner; let exit_x_axis = b @@ -312,8 +312,16 @@ impl Game<'_> { self.portals.travel = Some(plan); self.end_portal_travel = false; self.enter_dimension(plan.dim)?; - // The destination is all on disk now: load around the portal its - // points of interest lead to, or the approximate exit. + let centre = self.arrival_centre(&plan); + if let Some((_, target)) = self.travelling.as_mut() { + *target = centre; + } + Ok(()) + } + /// Where to wait for the destination of `plan` to load, once its level + /// is open: the portal its points of interest lead to, or the + /// approximate exit. + pub(super) fn arrival_centre(&self, plan: &Plan) -> Vec3 { let to_nether = plan.dim == Dim::Nether; let portals = self.portal_blocks(plan.approximate, if to_nether { 16 } else { 128 }); let (min_section, max_section) = if to_nether { (0, 15) } else { (-4, 19) }; @@ -327,14 +335,11 @@ impl Game<'_> { max_section, ); let centre = found.unwrap_or(plan.approximate); - if let Some((_, target)) = self.travelling.as_mut() { - *target = Vec3::new( - f64::from(centre.x) + 0.5, - f64::from(centre.y), - f64::from(centre.z) + 0.5, - ); - } - Ok(()) + Vec3::new( + f64::from(centre.x) + 0.5, + f64::from(centre.y), + f64::from(centre.z) + 0.5, + ) } /// The player's arrival once the destination has loaded around the /// approximate exit: the waiting entities first, then the exit portal diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 6fc342a96..0e26267fe 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -549,11 +549,7 @@ impl Game<'_> { r.loaded_sent = false; r.predictions.clear(); self.set_mode_id(spawn.game_type); - self.dim = if spawn.dimension == "minecraft:the_nether" { - Dim::Nether - } else { - Dim::Overworld - }; + self.dim = Dim::from_id(&spawn.dimension); if !same { let mut streaming = Streaming::new( Arc::new(NoTerrain), @@ -1246,9 +1242,16 @@ impl Game<'_> { .map(|r| r.lang.clone()) .unwrap_or_default(); let message = plain(&p.message, &lang); + let me = self.remote.as_ref().is_some_and(|r| r.entity_id == p.id); if let Some(r) = self.remote.as_mut() { r.death_message = Some(message); } + // ClientPacketListener.handlePlayerCombatKill: the death + // screen, whatever health was last sent. + if me && self.screen != Screen::Dead && self.player.is_some() { + self.screen = Screen::Dead; + self.capture(false); + } } C::SetExperience(p) => { self.experience = Experience { diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs new file mode 100644 index 000000000..d5b1e4d95 --- /dev/null +++ b/crates/horizon-client/src/game/server_travel.rs @@ -0,0 +1,248 @@ +//! A server's player between dimensions. +//! +//! The server holds one level at a time, as the in-frame game does. While a +//! single player is online (single player on the server thread, or a world +//! with one player in it) that level follows the player through Nether and +//! End portals, and back to the Overworld when the player respawns. The swap +//! is the in-frame path's (`switch_level`, the portal plans, the arrival +//! search); the player hears it as `ServerPlayer.teleport` into another +//! level: a Respawn packet keeping all data, then a teleport to the exit once +//! the destination has loaded. With several players online the portals do +//! not take anyone yet: that needs the server to hold every level. + +use super::nether_portal::PLAYER_DELAY; +use super::{Dim, Game, lan::LanHost}; +use horizon_client::lan::hub::TickCtx; +use horizon_core::{geometry::Vec3, position::BlockPos}; + +/// A trip under way: the level has changed and its chunks are loading +/// around `target`. +pub(super) struct Trip { + conn: u32, + target: Vec3, + /// Through an End portal (or out of the End by respawning). + end: bool, +} + +/// The lone player's box: Player's standing dimensions. +const WIDTH: f64 = 0.6; +const HEIGHT: f64 = 1.8; + +impl Game<'_> { + /// Whether `conn` is between two levels: the server leaves its body + /// alone until it arrives. + pub(super) fn on_server_trip(&self, conn: u32) -> bool { + self.server_trip.as_ref().is_some_and(|t| t.conn == conn) + } + + /// Per server tick, after the guests' own: `Entity.handlePortal` for the + /// lone player (Nether portals count up their transition time, End + /// portals take it at once), or the arrival of the trip under way. + pub(super) fn tick_server_travel(&mut self, host: &mut LanHost) { + if self.options.dedicated.is_none() { + return; + } + if self.server_trip.is_some() { + self.arrive_server_trip(host); + return; + } + let [g] = host.hub.guests.as_slice() else { + return; + }; + if !g.placed || !g.loaded || g.dead || g.spectator() { + return; + } + let (conn, at, invulnerable, sleeping) = ( + g.conn, + Vec3::new(g.position[0], g.position[1], g.position[2]), + g.creative(), + g.sleeping, + ); + // Entity.checkInsideBlocks: the Nether portal blocks the box is in. + if let Some(pos) = self.nether_portal_inside(at) { + self.portals.player.set_inside(pos, PLAYER_DELAY); + } + let (end_portal, _) = self.inside_end_portals(at, WIDTH, HEIGHT); + if end_portal { + if self.portals.player.cooldown == 0 { + let target = if self.dim == Dim::End { + Dim::Overworld + } else { + Dim::End + }; + self.start_server_trip(host, conn, target, true); + } + // Entity.setAsInsidePortal while cooling down restarts the cooldown. + self.portals.player.cooldown = 10; + return; + } + let rule = if invulnerable { + "players_nether_portal_creative_delay" + } else { + "players_nether_portal_default_delay" + }; + let transition = self.ui.rules.int(rule).max(0); + let Some(entry) = self + .portals + .player + .handle(!sleeping, transition, PLAYER_DELAY) + else { + return; + }; + let plan = self.portal_plan(entry, at, WIDTH as f32, HEIGHT as f32, true); + if !self.may_enter(plan.dim) { + return; + } + self.portals.travel = Some(plan); + self.start_server_trip(host, conn, plan.dim, false); + } + + /// A Nether portal block the lone player's box is in. + fn nether_portal_inside(&self, at: Vec3) -> Option { + let w = WIDTH / 2.0 - 1.0e-5; + let lo = [at.x - w, at.y + 1.0e-5, at.z - w]; + let hi = [at.x + w, at.y + HEIGHT - 1.0e-5, at.z + w]; + for x in lo[0].floor() as i32..=hi[0].floor() as i32 { + for y in lo[1].floor() as i32..=hi[1].floor() as i32 { + for z in lo[2].floor() as i32..=hi[2].floor() as i32 { + if &*self.block_name([x, y, z]) == "minecraft:nether_portal" { + return Some(BlockPos::new(x, y, z)); + } + } + } + } + None + } + + /// The level swap, and the player told it is in the new level at the + /// approximate exit while it loads. + fn start_server_trip(&mut self, host: &mut LanHost, conn: u32, target: Dim, end: bool) { + let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return; + }; + let g = &host.hub.guests[i]; + let from = Vec3::new(g.position[0], g.position[1], g.position[2]); + let yaw = g.yaw; + let source = self.dim; + self.end_portal_travel = end; + let switched = self.switch_level(target, from); + self.end_portal_travel = false; + let destination = match switched { + Ok(d) => d, + Err(e) => { + log::error!("could not open {}: {e}", target.id()); + return; + } + }; + let destination = match self.portals.travel { + Some(plan) if !end => self.arrival_centre(&plan), + _ => destination, + }; + host.hub.set_dimension(target.id()); + let at = [destination.x, destination.y, destination.z]; + let ctx = self.server_ctx(); + host.hub.change_level(i, at, yaw, &ctx); + self.as_guest(host, conn, |g| g.trigger_dimension(source, target)); + self.server_trip = Some(Trip { + conn, + target: destination, + end, + }); + } + + /// Once the destination has loaded around the trip's target: the exit + /// (the Nether portal found or built, the End platform, the Overworld's + /// spawn column) and the teleport there. + fn arrive_server_trip(&mut self, host: &mut LanHost) { + let Some(trip) = self.server_trip.as_ref() else { + return; + }; + let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else { + // They left on the way. + self.server_trip = None; + self.portals.travel = None; + return; + }; + let (cx, cz) = ( + (trip.target.x.floor() as i32) >> 4, + (trip.target.z.floor() as i32) >> 4, + ); + if !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { + return; + } + let Some(trip) = self.server_trip.take() else { + return; + }; + self.resolve_arrivals(); + let (position, yaw) = if trip.end { + match self.end_arrival(trip.target) { + Ok((at, yaw)) => (at, yaw.unwrap_or(host.hub.guests[i].yaw)), + Err(e) => { + log::error!("End arrival: {e}"); + (trip.target, host.hub.guests[i].yaw) + } + } + } else { + let plan = self.portals.travel.take(); + let exit = plan.as_ref().and_then(|plan| self.nether_exit_portal(plan)); + match (plan, exit) { + (Some(plan), Some(exit)) => { + let (at, rotation) = self.arrival(&plan, exit); + (at, host.hub.guests[i].yaw + rotation) + } + _ => (trip.target, host.hub.guests[i].yaw), + } + }; + // Player.getDimensionChangingDelay. + self.portals.player.cooldown = 10; + let g = &mut host.hub.guests[i]; + g.yaw = yaw; + // A new body at the exit: no fall distance or motion carried over. + g.motion = None; + host.hub + .teleport(i, Some([position.x, position.y, position.z])); + } + + /// `PlayerList.respawn` away from the Overworld: the lone player's level + /// goes back to the Overworld first, where the world spawn is. + pub(super) fn respawn_level(&mut self, host: &mut LanHost) { + if self.options.dedicated.is_none() || self.dim == Dim::Overworld { + return; + } + if host.hub.guests.len() != 1 { + return; + } + self.server_trip = None; + self.portals.travel = None; + self.end_portal_travel = true; + let from = self.spawn.unwrap_or(Vec3::ZERO); + let switched = self.switch_level(Dim::Overworld, from); + self.end_portal_travel = false; + if let Err(e) = switched { + log::error!("could not open the Overworld: {e}"); + return; + } + host.hub.set_dimension(Dim::Overworld.id()); + } + + /// The hub's view of the server for packets sent outside its own tick. + pub(super) fn server_ctx(&mut self) -> TickCtx<'_> { + let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); + TickCtx { + world: &mut self.world, + host: None, + entities: &[], + next_entity: &mut self.next_entity, + spawn, + difficulty: i32::from(self.ui.difficulty), + difficulty_locked: self.level.difficulty_locked, + clock_rate: if self.ui.rules.bool("advance_time") { + self.ui.clock.rate + } else { + 0.0 + }, + tick_rate: self.clock.rate(), + tick_frozen: self.clock.frozen(), + } + } +} diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 6ca321edd..99b87a20e 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -90,6 +90,11 @@ pub struct ChunkEncoder { pub block_ids: Vec, /// The save's tables, for the heightmaps. pub tables: Option>, + /// The level's sections among a column's: all of them in the Overworld, + /// y 0 to 255 in the Nether and the End (`DimensionType` min_y and height). + sections: std::ops::Range, + /// Whether the level has sky light (`DimensionType.hasSkyLight`). + sky: bool, } impl ChunkEncoder { /// `biome_names`: the internal biome list in order; `biome_registry`: @@ -143,8 +148,20 @@ impl ChunkEncoder { biome_bits: ceil_log2(biome_registry.len()), block_ids, tables: None, + sections: 0..SECTIONS, + sky: true, } } + /// Encode for a level of `min_y` and `height` (multiples of 16 within + /// the column), with or without sky light. + pub fn set_dimension(&mut self, min_y: i32, height: i32, sky: bool) { + let lo = usize::try_from((min_y - MIN_Y) >> 4) + .unwrap_or(0) + .min(SECTIONS); + let n = usize::try_from(height >> 4).unwrap_or(SECTIONS); + self.sections = lo..(lo + n).min(SECTIONS); + self.sky = sky; + } pub fn entity_type(&self, state: u16) -> Option { self.entity_types .get(usize::from(state)) @@ -200,7 +217,7 @@ impl ChunkEncoder { /// The non-air sections of a column as bits (LevelChunkSection.hasOnlyAir). fn occupied(&self, chunk: &Chunk) -> u64 { let mut bits = 0u64; - for (i, s) in chunk.sections.iter().enumerate() { + for (i, s) in chunk.sections[self.sections.clone()].iter().enumerate() { let mut unpacked = [0u16; BLOCKS]; s.unpack(&mut unpacked); let any = unpacked @@ -225,7 +242,7 @@ impl ChunkEncoder { } } let mut packet = self.encode(chunk, &world.block_entities); - packet.light = light_data(chunk, around); + packet.light = self.light(chunk, around); packet } @@ -234,9 +251,15 @@ impl ChunkEncoder { chunk: &Chunk, block_entities: &HashMap<(i32, i32, i32), BlockEntity>, ) -> LevelChunkWithLight { - let mut sections = Vec::with_capacity(SECTIONS); + let mut sections = Vec::with_capacity(self.sections.len()); let mut entity_infos = Vec::new(); - for (i, s) in chunk.sections.iter().enumerate() { + for (i, s) in chunk + .sections + .iter() + .enumerate() + .skip(self.sections.start) + .take(self.sections.len()) + { let (encoded, has_entities) = self.section(s); if has_entities { for y in 0..16 { @@ -293,14 +316,30 @@ impl ChunkEncoder { heightmaps: self .tables .as_ref() - .map(|t| crate::save::client_heightmaps(chunk, t)) + .map(|t| { + let min_y = MIN_Y + 16 * self.sections.start as i32; + let height = 16 * self.sections.len() as i32; + crate::save::client_heightmaps_in(chunk, t, min_y, height) + }) .unwrap_or_default(), buffer: ChunkData::from_sections(§ions), block_entities: entity_infos, }, - light: light_data(chunk, u64::MAX), + light: self.light(chunk, u64::MAX), } } + + /// The light layers of the level's sections. + fn light(&self, chunk: &Chunk, around: u64) -> LightData { + let mut data = light_data(&chunk.sections[self.sections.clone()], around); + if !self.sky { + // No sky light storage at all. + data.sky_mask.clear(); + data.empty_sky_mask.clear(); + data.sky.clear(); + } + data + } } /// The order LevelChunk.getBlockEntities() iterates in: a fastutil @@ -373,7 +412,8 @@ pub fn entity_tag(entity: &BlockEntity) -> Option { /// non-air section of this column or a neighbouring one (`around`, bit i for /// section i; LayerLightSectionStorage.updateSectionStatus). An existing /// layer is sent, or marked empty when all dark; the others are left out. -fn light_data(chunk: &Chunk, around: u64) -> LightData { +fn light_data(sections: &[Arc
], around: u64) -> LightData { + let n = sections.len(); let mut data = LightData { sky_mask: Vec::new(), block_mask: Vec::new(), @@ -383,19 +423,18 @@ fn light_data(chunk: &Chunk, around: u64) -> LightData { block: Vec::new(), }; // Light section b holds chunk section b - 1. - let exists = |b: usize| { - (b.saturating_sub(2)..=b.min(SECTIONS - 1)).any(|s| s + 2 >= b && around >> s & 1 != 0) - }; + let exists = + |b: usize| (b.saturating_sub(2)..=b.min(n - 1)).any(|s| s + 2 >= b && around >> s & 1 != 0); let full_sky = Light::Uniform(0xF0); - for b in 0..SECTIONS + 2 { + for b in 0..n + 2 { if !exists(b) { continue; } let light = match b { // Below the world nothing is lit; above it the sky is full. 0 => &Light::Uniform(0), - _ if b == SECTIONS + 1 => &full_sky, - _ => &chunk.sections[b - 1].light, + _ if b == n + 1 => &full_sky, + _ => §ions[b - 1].light, }; let (mut sky, mut block) = (vec![0u8; 2048], vec![0u8; 2048]); let (mut sky_any, mut block_any) = (false, false); @@ -464,12 +503,39 @@ mod tests { fn light_masks_cover_the_world_plus_borders() { let chunk = Chunk::empty(0, 0); // A column with nothing around it has no light layers at all. - assert!(light_data(&chunk, 0).sky.is_empty()); - let data = light_data(&chunk, u64::MAX); + assert!(light_data(&chunk.sections, 0).sky.is_empty()); + let data = light_data(&chunk.sections, u64::MAX); // Default sections are full sky light and no block light. assert_eq!(data.sky.len(), SECTIONS + 1); assert_eq!(data.block.len(), 0); assert_eq!(data.sky[0][0], 0xFF); assert!(horizon_protocol::buf::bit(&data.empty_block_mask, 5)); } + + #[test] + fn a_nether_column_sends_its_sixteen_sections_without_sky_light() { + let chunk = Chunk::empty(0, 0); + let mut encoder = ChunkEncoder::new( + [("minecraft:air".into(), false)], + &Builtin::default(), + &[], + &[], + ); + let overworld = encoder.encode(&chunk, &HashMap::new()); + encoder.set_dimension(0, 256, false); + let nether = encoder.encode(&chunk, &HashMap::new()); + // An all-air section is the same bytes wherever it is. + let per_section = overworld.chunk.buffer.len() / SECTIONS; + assert_eq!(nether.chunk.buffer.len(), per_section * 16); + assert!(nether.light.sky.is_empty() && nether.light.sky_mask.is_empty()); + // Block light layers: one below and one above the sixteen sections. + assert!(horizon_protocol::buf::bit( + &nether.light.empty_block_mask, + 17 + )); + assert!(!horizon_protocol::buf::bit( + &nether.light.empty_block_mask, + 18 + )); + } } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 806c91fc3..d98df083e 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -186,9 +186,12 @@ impl Hub { .id("minecraft:chat_type", "minecraft:chat") .unwrap_or(0); let dimension_type = sync - .id("minecraft:dimension_type", "minecraft:overworld") + .id("minecraft:dimension_type", &config.dimension) .unwrap_or(0); let clock_ids = (0..sync.dynamic.len("minecraft:world_clock") as i32).collect(); + let mut encoder = encoder; + let d = horizon_protocol::registry::DimensionType::vanilla(&config.dimension); + encoder.set_dimension(d.min_y, d.height, d.has_skylight); Self { lan, config, @@ -737,11 +740,12 @@ impl Hub { })); } - /// ClientboundSetDefaultSpawnPositionPacket for the level's respawn data. + /// ClientboundSetDefaultSpawnPositionPacket for the level's respawn data + /// (the world spawn, in the Overworld wherever the player is). fn default_spawn(&self, spawn: [f64; 3]) -> C { C::SetDefaultSpawnPosition(play::SetDefaultSpawnPosition { pos: play::GlobalPos { - dimension: self.config.dimension.clone(), + dimension: "minecraft:overworld".into(), pos: [ spawn[0].floor() as i32, spawn[1].floor() as i32, @@ -1831,6 +1835,81 @@ impl Hub { // ServerPlayer.initInventoryMenu. self.send_inventory(i); } + + /// The level the players are in: the server holds one at a time, and the + /// hub's packets name it. + pub fn set_dimension(&mut self, dimension: &str) { + self.config.dimension = dimension.to_owned(); + self.dimension_type = self + .sync + .id("minecraft:dimension_type", dimension) + .unwrap_or(0); + let d = horizon_protocol::registry::DimensionType::vanilla(dimension); + self.encoder + .set_dimension(d.min_y, d.height, d.has_skylight); + } + + /// ServerPlayer.teleport(TeleportTransition) into the level the hub now + /// names (`set_dimension`): ClientboundRespawnPacket keeping all data, + /// then vanilla's packet order. Nothing tracked in the old level is + /// removed one by one: the client drops its whole level. + pub fn change_level(&mut self, i: usize, at: [f64; 3], yaw: f32, ctx: &TickCtx) { + let mode = self.guests[i].game_mode; + let info = self.spawn_info(mode); + self.close_container_for(i); + let g = &mut self.guests[i]; + g.tracker.clear(); + g.sent_chunks.clear(); + g.chunk_queue.clear(); + g.center = None; + g.yaw = yaw; + g.position = at; + g.previous_position = at; + g.send(&C::Respawn(play::Respawn { + spawn: info, + // ClientboundRespawnPacket.KEEP_ALL_DATA. + keep: 3, + })); + g.send(&C::ChangeDifficulty(play::ChangeDifficulty { + difficulty: ctx.difficulty, + locked: ctx.difficulty_locked, + })); + self.send_permission_level(i); + self.teleport(i, None); + let g = &mut self.guests[i]; + g.send(&C::PlayerAbilities(play::PlayerAbilities { + flags: g.ability_flags(), + flying_speed: 0.05, + walking_speed: 0.1, + })); + self.send_level_info(i, ctx); + // PlayerList.sendAllPlayerInfo: the inventory and the held slot. + self.send_inventory(i); + let g = &mut self.guests[i]; + g.send(&C::SetHeldSlot(play::SetHeldSlot { + slot: g.selected as i32, + })); + self.send_active_effects(i); + let g = &mut self.guests[i]; + // ServerPlayer.sendPostEffects. + g.send(&raw(ids::POST_EFFECTS, vec![0])); + // TeleportTransition.PLAY_PORTAL_SOUND. + g.send(&C::LevelEvent(play::LevelEvent { + kind: 1032, + pos: [0, 0, 0], + data: 0, + global: false, + })); + // lastSentExp, lastSentHealth and lastSentFood. + g.sent_health = None; + g.sent_xp = None; + let (cx, cz) = g.chunk(); + g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { + x: cx, + z: cz, + })); + g.center_sent = Some((cx, cz)); + } } /// A packet Horizon sends as raw bytes (no fields worth a type). diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index a8553e276..398a340a2 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -730,6 +730,15 @@ fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag { /// sendToClient: WORLD_SURFACE, MOTION_BLOCKING, MOTION_BLOCKING_NO_LEAVES), /// as (network id, packed longs) in Heightmap.Types order. pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec)> { + client_heightmaps_in(chunk, tables, MIN_Y, SECTIONS as i32 * 16) +} +/// The client heightmaps of a level from `min_y`, `height` blocks high. +pub fn client_heightmaps_in( + chunk: &Chunk, + tables: &SaveTables, + min_y: i32, + height: i32, +) -> Vec<(i32, Vec)> { let kinds = [ (1, HeightmapType::WorldSurface), (4, HeightmapType::MotionBlocking), @@ -737,11 +746,7 @@ pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec = kinds .iter() - .filter_map(|(id, k)| { - Heightmap::new(*k, MIN_Y, SECTIONS as i32 * 16) - .ok() - .map(|m| (*id, m)) - }) + .filter_map(|(id, k)| Heightmap::new(*k, min_y, height).ok().map(|m| (*id, m))) .collect(); let view = HeightmapView { chunk, tables }; let mut refs: Vec<&mut Heightmap> = maps.iter_mut().map(|(_, m)| m).collect();