From 45cbb4f7d668cf578c8b8e7fca8f65d9112385fa Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 14:02:22 +0200 Subject: [PATCH 1/6] LAN: a guest's chest, crafting table or sign no longer takes the host's mouse (#687) A guest's action runs on the host's game with the guest's state swapped in (`as_guest`). The swap restored the open screen but not what opening one does to the window: `capture(false)` released the host's pointer, so the cursor showed and the camera stopped whenever a guest opened a chest, a crafting table or any other menu. `keys.clear()` dropped the keys the host was holding, and a sign, book, command block or mount menu the guest opened was drawn on the host's screen. - `capture` leaves the window alone while a guest acts. - `as_guest` keeps the host's held keys, sign editor, book, command block screen and mount menu, as it already kept the open screen. - `state` reports `pointer_grabbed` (mouse movement turns the camera). - tools/lan_e2e.py: `chest` and `crafting` check that the host keeps its screen and its mouse look; a new `sign` check places a sign as the guest. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 5 +++ crates/horizon-client/src/game/agent.rs | 3 ++ crates/horizon-client/src/game/lan_actions.rs | 23 ++++++---- tools/lan_e2e.py | 44 +++++++++++++++++-- 4 files changed, 63 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0f898f8bf..51fe3797c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3666,6 +3666,11 @@ impl Game<'_> { ) || self.book.is_some()) } fn capture(&mut self, capture: bool) { + // A guest's action (`as_guest`) opens and closes screens on the + // guest's own client: the window's pointer stays the host's (#687). + if self.lan_acting.is_some() { + return; + } // MouseHandler.grabMouse never captures an inactive window. if capture && !self.focused { return; diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 48b24bbb3..2798f5706 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -469,6 +469,9 @@ impl Game<'_> { "time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) }, "weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering }, "paused": self.pause, + // Mouse movement turns the camera (`apply_mouse_look`): the real + // pointer is grabbed, or an agent's `mouse-move` stands in for it. + "pointer_grabbed": self.captured || self.agent_pointer, "player": player, "selected": self.selected + 1, "held": self.held().map(|s| self.stack_value(s)), diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 1d3433cf0..0e90a6280 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -140,13 +140,20 @@ impl Game<'_> { total: g.xp_total, }, ); - let sneak = self.keys.contains(&KeyCode::ShiftLeft); + // The host's held keys stay theirs: the guest holds only sneak, and a + // screen the guest opens (`keys.clear()`) leaves the host walking. + let host_keys = std::mem::take(&mut self.keys); if g.sneaking { self.keys.insert(KeyCode::ShiftLeft); - } else { - self.keys.remove(&KeyCode::ShiftLeft); } + // The window's screens are the host's: a sign, book, command block or + // mount menu the guest's action opens is not drawn over the host's + // world (#687). The guest's client opens its own. let screen = std::mem::replace(&mut self.screen, Screen::Playing); + let host_sign = self.sign_edit.take(); + let host_book = self.book.take(); + let host_command_block = self.command_block_screen.take(); + let host_mount_menu = std::mem::take(&mut self.mount_menu); // The host's crafting grid stays theirs; a crafting table the guest // opens shows as the 3x3 size. let craft_size = std::mem::replace(&mut self.craft_size, 2); @@ -205,11 +212,11 @@ impl Game<'_> { play.swing = std::mem::replace(&mut self.swing, swing); self.container = container; self.screen = screen; - if sneak { - self.keys.insert(KeyCode::ShiftLeft); - } else { - self.keys.remove(&KeyCode::ShiftLeft); - } + self.sign_edit = host_sign; + self.book = host_book; + self.command_block_screen = host_command_block; + self.mount_menu = host_mount_menu; + self.keys = host_keys; let g = &mut host.hub.guests[i]; std::mem::swap(&mut self.ender_items, &mut g.ender_items); std::mem::swap(&mut self.adv.progress, &mut g.advancements); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 667fdda2d..d76cf922c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -10,8 +10,10 @@ address. The script then checks, from both sides, what a guest's game used to ge - armour: each side draws the other player in that player's own armour; - nametags: each side draws the other player's name above them; - chest: a chest the guest opens opens on the guest's screen, its lid opens on both sides and - closes on both when the guest closes it; -- crafting: the guest crafts planks in the inventory's 2x2 grid and opens a crafting table; + closes on both when the guest closes it; the host keeps playing with its mouse look (#687); +- crafting: the guest crafts planks in the inventory's 2x2 grid and opens a crafting table, which + leaves the host's screen and mouse look alone; +- sign: a sign the guest places doesn't open a sign editor on the host; - damage: a guest in survival takes fall damage; - mobs: with the host in creative, a zombie and a skeleton go for the guest and hurt them; - hazards: a guest in survival gets hungry sprint-jumping and is hurt by lava, a block at the eyes, @@ -48,7 +50,7 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402 ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials'] class Game: @@ -180,6 +182,19 @@ def check_nametags(host, guest, out): return {'host': h, 'guest': g} +def grab(game): + """Mouse look on, as a player's grabbed pointer: an agent's mouse-move stands in for it.""" + game.raw('mouse-move', 1, 0) + game.raw('mouse-move', -1, 0) + + +def host_unaffected(host, what): + """What a guest opens is the guest's: the host keeps its world on screen and its mouse look (#687).""" + state = host('state') + assert state.get('screen') == 'playing', f'{what} opened the {state.get("screen")} screen on the host' + assert state.get('pointer_grabbed'), f"{what} released the host's pointer" + + def lid(game, pos): return game.raw('block', *pos).get('lid', 0.0) @@ -189,9 +204,11 @@ def check_chest(host, guest, out): chest = (x, y, z + 2) guest('command', command=f'setblock {chest[0]} {chest[1]} {chest[2]} minecraft:chest') guest.wait(10) + grab(host) guest.raw('interact', *chest) screen = guest.raw('wait-for', 'screen', 'container', '--timeout', 10) guest.wait(20) + host_unaffected(host, "the guest's chest") opened = {'guest': lid(guest, chest), 'host': lid(host, chest)} host.raw('look-at', chest[0] + 0.5, chest[1] + 0.5, chest[2] + 0.5) host.wait(2) @@ -231,8 +248,10 @@ def check_crafting(host, guest, out): table = (x, y, z - 2) guest('command', command=f'setblock {table[0]} {table[1]} {table[2]} minecraft:crafting_table') guest.wait(10) + grab(host) guest.raw('interact', *table) guest.raw('wait-for', 'screen', 'inventory', '--timeout', 10) + host_unaffected(host, "the guest's crafting table") size = guest('screen').get('craft_size') assert size == 3, f'the crafting table opened a {size}x{size} grid' # Two planks one above the other in the 3x3 grid: four sticks. @@ -252,6 +271,23 @@ def check_crafting(host, guest, out): return {'planks': planks, 'table': counts} +def check_sign(host, guest, out): + x, y, z = (int(v // 1) for v in pos_of(guest)) + spot = (x + 2, y, z) + guest('command', command=f'setblock {spot[0]} {spot[1] - 1} {spot[2]} minecraft:stone') + guest('command', command=f'setblock {spot[0]} {spot[1]} {spot[2]} minecraft:air') + guest('command', command='give @s minecraft:oak_sign 1') + guest.wait(10) + grab(host) + guest.raw('place', *spot, '--item', 'minecraft:oak_sign') + guest.wait(20) + placed = host.raw('block', *spot).get('block') + host.shot(out, 'sign') + assert placed and 'sign' in placed, f'the guest placed {placed}' + host_unaffected(host, "the guest's sign") + return placed + + def check_damage(host, guest, out): guest('command', command='gamemode survival') guest.wait(10) @@ -623,7 +659,7 @@ def check_trials(host, guest, out): CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, - 'chest': check_chest, 'crafting': check_crafting, 'damage': check_damage, + 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials, 'walls': check_walls} From a67a323959a43dcfc2d853634b2d1f253b5fbf34 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 14:45:28 +0200 Subject: [PATCH 2/6] Server: one level per dimension, so players can be in different dimensions A server (the dedicated server and single player's server thread) now holds a level per dimension, like vanilla's `MinecraftServer.levels`. Each server tick runs every level with players in it, one at a time, by swapping its fields into place (game/levels.rs), so the world tick code runs unchanged. Before this, a portal did nothing while two or more players were online. - Levels: the parked levels keep the world, streaming, save, block ticks, entities, block entity state, raids, sculk and creaking scans. The Overworld stays loaded; another level is saved and closed after 300 ticks with nobody in it. Saving saves every level. - Hub: `tick` is split into `poll` (the network, once per tick), `tick_level` (the packets, chunks, block changes, containers and entities of the players in the level in place) and `end_tick` (latency). Each guest has a dimension; time, weather, sounds and events reach only the players in their level, and the clock and weather last sent are kept per level. - Travel: every player has their own portal state; a portal moves only that player into the destination's level (`ServerPlayer.teleport` packets as before). Respawning brings a player back to the Overworld's level. - Player data saves and loads each player's dimension, and a returning player is placed in their own level. - tools/lan_e2e.py --server-thread --check portals: the guest goes to the Nether while the host stays, then the host goes to the End while the guest is in the Nether, and both come back. The in-frame game keeps its one level that follows its player. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 43 ++- crates/horizon-client/src/game/creaking.rs | 8 + crates/horizon-client/src/game/dedicated.rs | 24 +- .../horizon-client/src/game/falling_damage.rs | 2 +- crates/horizon-client/src/game/integrated.rs | 6 +- crates/horizon-client/src/game/lan.rs | 60 ++- crates/horizon-client/src/game/lan_actions.rs | 23 +- crates/horizon-client/src/game/lan_mobs.rs | 9 +- crates/horizon-client/src/game/lan_pvp.rs | 4 +- crates/horizon-client/src/game/lan_trading.rs | 2 +- crates/horizon-client/src/game/levels.rs | 350 ++++++++++++++++++ crates/horizon-client/src/game/raids.rs | 11 + crates/horizon-client/src/game/sculk.rs | 9 + .../horizon-client/src/game/server_travel.rs | 259 +++++++------ crates/horizon-client/src/lan/containers.rs | 4 +- crates/horizon-client/src/lan/guest.rs | 4 + crates/horizon-client/src/lan/hub.rs | 113 +++++- crates/horizon-client/src/lan/playerdata.rs | 6 +- tools/lan_e2e.py | 76 +++- 19 files changed, 828 insertions(+), 185 deletions(-) create mode 100644 crates/horizon-client/src/game/levels.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 51fe3797c..633417bf5 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -70,6 +70,7 @@ mod lan_screen; mod lan_trading; mod leads; mod level_particles; +mod levels; mod lightning; mod llamas; mod loom; @@ -973,8 +974,14 @@ 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, + /// A server's players on their way to another level, each waiting for + /// the destination to load around them. + server_trips: Vec, + /// A server's levels other than the one in place (game/levels.rs). + levels: levels::Levels, + /// Which pass of a server tick runs (`tick_server`): the first one reads + /// the network, the last one ends the players' tick. + level_pass: levels::Pass, /// 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). @@ -1164,7 +1171,7 @@ struct Game<'a> { /// The local player as a model (third person, the inventory). player_model: Option, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] enum Dim { Overworld, Nether, @@ -8429,18 +8436,10 @@ impl Game<'_> { if self.remote.is_some() { return Ok(()); } - self.streaming.save(&mut self.world, wait); - let keys: Vec<_> = self.world.modified.drain().collect(); - let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); - self.save - .save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?; - if wait { - self.save.flush(); - } - self.save_entities(wait)?; + self.save_level(wait)?; + self.save_parked_levels(wait)?; self.save_maps(); self.save_random_sequences(); - self.save_raids(); self.save_fight(); self.save_wandering_trader(); self.save_portal_arrivals(); @@ -8457,6 +8456,20 @@ impl Game<'_> { self.message = Some(("Saved the game".into(), Instant::now())); Ok(()) } + /// Save the level in place: its changed chunks, its entities and its raids. + fn save_level(&mut self, wait: bool) -> Result<()> { + self.streaming.save(&mut self.world, wait); + let keys: Vec<_> = self.world.modified.drain().collect(); + let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); + self.save + .save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?; + if wait { + self.save.flush(); + } + self.save_entities(wait)?; + self.save_raids(); + Ok(()) + } fn render(&mut self) -> Result { self.poll_shader_pack(); let Some(size) = self @@ -10132,7 +10145,9 @@ impl<'a> Game<'a> { dim: Dim::Overworld, world_root: PathBuf::new(), travelling: None, - server_trip: None, + server_trips: Vec::new(), + levels: Default::default(), + level_pass: Default::default(), portals: Default::default(), end_travel: false, respawn_config: None, diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index 1caa419ff..f99526253 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -362,3 +362,11 @@ pub(super) struct CreakingState { /// Which block states are creaking hearts, by state id. hearts: Vec, } + +impl CreakingState { + /// Exchange the chunks scanned for creaking hearts with another level's + /// (game/levels.rs). + pub(super) fn swap_level(&mut self, other: &mut Self) { + std::mem::swap(&mut self.scanned, &mut other.scanned); + } +} diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 9c4b41db0..e6983177a 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -543,18 +543,12 @@ impl Game<'_> { ); self.save_game()?; } - self.update_dedicated_streaming(); - self.update_world(); - if paused { - // MinecraftServer.tickServer: only the connections run. - self.tick_lan(); - } else { - if !state.autosave { - // `save-off`: the periodic save inside the tick is skipped. - self.ticks = self.ticks.max(1); - } - self.tick()?; + if !paused && !state.autosave { + // `save-off`: the periodic save inside the tick is skipped. + self.ticks = self.ticks.max(1); } + // MinecraftServer.tickServer: while paused only the connections run. + self.tick_server(paused)?; if idle_timeout > 0 { self.kick_idle(idle_timeout); } @@ -595,7 +589,13 @@ impl Game<'_> { let center = self .lan .as_ref() - .and_then(|h| h.hub.guests.iter().find(|g| g.placed).map(|g| g.chunk())) + .and_then(|h| { + h.hub + .guests + .iter() + .find(|g| h.hub.here(g)) + .map(|g| g.chunk()) + }) .or_else(|| { self.spawn .map(|s| ((s.x.floor() as i32) >> 4, (s.z.floor() as i32) >> 4)) diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs index 16a003c04..f10a3b738 100644 --- a/crates/horizon-client/src/game/falling_damage.rs +++ b/crates/horizon-client/src/game/falling_damage.rs @@ -23,7 +23,7 @@ impl Game<'_> { .guests .iter() .filter(|g| { - g.placed + host.hub.here(g) && g.loaded && !g.dead && !g.creative() diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 7b5f3cced..412c41693 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -314,14 +314,12 @@ impl Game<'_> { 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) { // Only the connections run. - self.tick_lan(); + self.tick_server(true)?; } else { let started = Instant::now(); - self.tick()?; + self.tick_server(false)?; self.debug_charts.log_tick(started, started.elapsed()); flags.smoothed_tick_ms.store( self.debug_charts.smoothed_tick_ms.to_bits(), diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 078083006..d2c3a7e9c 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -52,7 +52,7 @@ pub(super) struct LanHost { /// Blocks broken this tick (their sound is a level event for the guests). pub broken: Vec<[f64; 3]>, /// Hurt and death state of the mobs guests see. - mob_state: HashMap, + mob_state: HashMap>, /// The guest each mob sees as its player, when not the host (game/lan_mobs.rs). pub mob_players: HashMap, /// An integrated server's owner (game/integrated.rs). @@ -783,7 +783,19 @@ impl Game<'_> { tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), }; - host.hub.tick(&mut ctx) + // A server with several levels runs a pass for each + // (`tick_server`): the network is read once, before the first. + let pass = self.level_pass; + let mut events = if pass.first { + host.hub.poll(&mut ctx) + } else { + Vec::new() + }; + events.extend(host.hub.tick_level(&mut ctx)); + if pass.last { + host.hub.end_tick(); + } + events }; if let Some(state) = &state && host.host_mode != state.game_mode @@ -823,7 +835,15 @@ impl Game<'_> { if let Some(pos) = guest.menu.as_ref().and_then(|m| m.pos) && !guest.spectator() { - self.container_openers_changed(pos, false); + // In the level they were in. + let back = self.dim; + let theirs = super::Dim::from_id(&guest.dimension); + if self.enter_level(Some(&mut host), theirs).is_ok() { + self.container_openers_changed(pos, false); + } + if let Err(e) = self.enter_level(Some(&mut host), back) { + log::error!("could not reopen {}: {e}", back.id()); + } } self.lan_crafting_left(&mut host, &mut guest); self.save_guest(&host, &guest); @@ -875,6 +895,7 @@ 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 in_place = host.hub.config.dimension.clone(); let owner = host.owner.as_mut(); let Some(g) = host.hub.guest_mut(conn) else { return; @@ -897,8 +918,28 @@ impl Game<'_> { g.previous_position = spawn; g.health = 20.0; g.food = 20; + g.dimension = super::Dim::Overworld.id().to_owned(); + } + // A server places each player in their own level + // (`PlayerList.placeNewPlayer`); the in-frame game has one. + let back = self.dim; + let level = super::Dim::from_id(&g.dimension); + let elsewhere = self.options.dedicated.is_some() && level != back; + if !elsewhere { + g.dimension = in_place; } self.load_guest_records(host, conn); + let theirs; + let entities = if elsewhere { + if let Err(e) = self.enter_level(Some(host), level) { + log::error!("could not open {}: {e}", level.id()); + return; + } + theirs = self.lan_entities(&mut host.hub); + &theirs[..] + } else { + entities + }; let mut ctx = TickCtx { world: &mut self.world, host: state, @@ -912,6 +953,9 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), }; host.hub.place_new_player(conn, &mut ctx); + if elsewhere && let Err(e) = self.enter_level(Some(host), back) { + log::error!("could not reopen {}: {e}", back.id()); + } } /// Level events the game queued, for the guests (`process_level_events`). @@ -966,7 +1010,11 @@ impl Game<'_> { let mut seen = HashMap::new(); for m in &self.mobs { let dead = !m.alive(); - let old = host.mob_state.get(&m.id).copied(); + let old = host + .mob_state + .get(&self.dim) + .and_then(|s| s.get(&m.id)) + .copied(); let at = [m.position.x, m.position.y, m.position.z]; if m.hurt_time > old.map_or(0, |o| o.0) && !dead { host.hub.entity_event(m.id as i32, 2, at); @@ -976,7 +1024,7 @@ impl Game<'_> { } seen.insert(m.id, (m.hurt_time, dead)); } - host.mob_state = seen; + host.mob_state.insert(self.dim, seen); } /// Keep the chunks around every guest loaded. @@ -985,7 +1033,7 @@ impl Game<'_> { .hub .guests .iter() - .filter(|g| g.placed) + .filter(|g| host.hub.here(g)) // The tracked square's corners and their lit neighbours lie // within (view distance + 2) * √2 of the player's chunk. .map(|g| (g.chunk(), (g.view_distance + 2) * 3 / 2 + 1)) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0e90a6280..6b0463290 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -54,6 +54,8 @@ pub(super) struct GuestPlay { /// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw. pub(super) stats: super::stats::Stats, last_inventory: u64, + /// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs). + pub(super) portal: horizon_client::nether_portal::PortalState, } struct ItemRules<'a>(&'a horizon_client::items::Items); @@ -917,7 +919,18 @@ impl Game<'_> { if !host.hub.guests[i].dead { return; } - self.respawn_level(host); + // PlayerList.respawn: a server's player comes back in the Overworld, + // where the world spawn is (respawn anchors and beds aside). + let back = self.dim; + let away = self.options.dedicated.is_some() + && host.hub.guests[i].dimension != super::Dim::Overworld.id(); + if away { + self.server_trips.retain(|t| !t.is(conn)); + if let Err(e) = self.enter_level(Some(host), super::Dim::Overworld) { + log::error!("could not open the Overworld: {e}"); + return; + } + } let g = &mut host.hub.guests[i]; g.dead = false; g.health = 20.0; @@ -953,6 +966,9 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), }; host.hub.respawn(i, spawn, &ctx); + if away && let Err(e) = self.enter_level(Some(host), back) { + log::error!("could not reopen {}: {e}", back.id()); + } } /// Per tick, for every guest: dig, use items, pick up drops, die. @@ -963,7 +979,7 @@ impl Game<'_> { .hub .guests .iter() - .filter(|g| g.placed && g.loaded) + .filter(|g| host.hub.here(g) && g.loaded) .map(|g| g.conn) .collect(); for conn in conns { @@ -1355,6 +1371,9 @@ impl Game<'_> { let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else { continue; }; + if !host.hub.here(g) { + continue; + } let (id, at) = (g.entity_id, g.position); let play = host.play.get_mut(&conn).expect("play"); let swinging = play.swing.swinging() && play.swing.ticks == 0; diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 7cef7cda6..e613a9a2f 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -138,7 +138,7 @@ impl Game<'_> { host.hub .guests .iter() - .filter(|g| g.placed && g.loaded && !g.dead && !g.spectator()) + .filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator()) .map(|g| (Who::Mob(g.entity_id as u32), guest_bounds(g))) .collect() } @@ -209,9 +209,12 @@ pub(super) struct Present { impl Game<'_> { /// Every guest in the world (`ServerLevel.getPlayers` past the host). pub(super) fn lan_present(&self) -> Vec { - let guests = self.lan.iter().flat_map(|h| &h.hub.guests); + let guests = self + .lan + .iter() + .flat_map(|h| h.hub.guests.iter().filter(|g| h.hub.here(g))); guests - .filter(|g| g.placed && g.loaded) + .filter(|g| g.loaded) .map(|g| { let [x, y, z] = g.position; Present { diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index bd10241ff..1bdf9146a 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -32,7 +32,7 @@ impl Game<'_> { host.hub .guests .iter() - .filter(|g| g.placed && g.loaded && !g.dead && !g.spectator()) + .filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator()) .filter_map(|g| Some((g.conn, ray_box(eye, dir, reach, guest_bounds(g))?))) .min_by(|a, b| a.1.total_cmp(&b.1)) } @@ -64,7 +64,7 @@ impl Game<'_> { host.hub .guests .iter() - .find(|g| g.entity_id == id && g.conn != conn && g.placed && !g.dead) + .find(|g| g.entity_id == id && g.conn != conn && host.hub.here(g) && !g.dead) .map(|g| Victim::Guest(g.conn)) } diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index d6bfc4141..ee6b55d16 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -372,7 +372,7 @@ impl Game<'_> { .hub .guests .iter() - .find(|g| g.conn == conn) + .find(|g| g.conn == conn && host.hub.here(g)) .map(|g| uuid_words(g.uuid)) else { continue; diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs new file mode 100644 index 000000000..82a142364 --- /dev/null +++ b/crates/horizon-client/src/game/levels.rs @@ -0,0 +1,350 @@ +//! A server's levels, one per dimension (`MinecraftServer.levels`). +//! +//! The game's tick code reads one level: the one in place, held in `Game`'s +//! own fields (the world, its streaming and save, block ticks, entities). +//! A server (the dedicated server and single player's server thread) keeps +//! the other dimensions' levels here and ticks each one that has players by +//! swapping it into place (`enter_level`), the way `as_guest` swaps a player +//! in, so the tick code runs unchanged, one level at a time. The in-frame +//! game holds one level, which follows its player (`enter_dimension`). +//! +//! Shared by every level, as vanilla's derived levels share the +//! Overworld's level data: the game time, the day time and the weather, the +//! game rules, the scoreboard, the maps and the entities waiting to arrive +//! through a portal. + +use super::{ + Dim, ExperienceOrb, FallingBlock, Game, ItemEntity, Mob, boats, commands, + creaking::CreakingState, dragon, fireworks, lan::LanHost, lightning, machines, minecarts, + ominous_item_spawner, persist, raids::Raiding, sculk::SculkState, tnt, trident, +}; +use horizon_client::{ + Result, block_entity_anim::BlockEntityAnims, random_tick_sections::RandomTickSections, + save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, world::World, +}; +use horizon_world::level::{LevelEvent, Ticks}; +use std::{collections::HashMap, sync::Arc}; + +/// Server ticks a level other than the Overworld stays loaded with no player +/// in it, before it is saved and closed (vanilla unloads a level's chunks +/// once no ticket holds them; the Overworld stays loaded). +const IDLE_TICKS: u32 = 300; + +/// A level that is not in place: every per-level field of `Game`. +pub(super) struct Parked { + world: World, + streaming: Streaming, + save: Arc, + block_ticks: Ticks, + tick_chunks: TickChunkMembership, + random_tick_sections: RandomTickSections, + level_events: Vec, + falling: Vec, + paintings: Vec, + item_frames: Vec, + armor_stands: Vec, + others: Vec, + boats: Vec, + carts: Vec, + jukebox_sounds: HashMap<(i32, i32, i32), u64>, + bolts: Vec, + crystals: Vec, + dragon: Option, + dragon_fireballs: Vec, + breath_clouds: Vec, + tridents: Vec, + rockets: Vec, + ominous_spawners: Vec, + tnts: Vec, + hoppers: HashMap<(i32, i32, i32), machines::HopperState>, + mobs: Vec, + projectiles: Vec, + dropped: Vec, + orbs: Vec, + persist: persist::EntityMemory, + lectern_pulses: Vec<((i32, i32, i32), i32)>, + lid_openers: HashMap<(i32, i32, i32), i32>, + lan_events: Vec<(i32, [i32; 3], i32, Option)>, + lan_block_events: Vec<([i32; 3], i32, i32, u16)>, + lan_entity_events: Vec<(i32, i8, [f64; 3])>, + /// Only the per-level parts of these are used (`swap_level`). + anims: BlockEntityAnims, + raiding: Raiding, + sculk: SculkState, + creaking: CreakingState, + /// Server ticks since a player was last in the level. + idle: u32, +} + +/// Which passes of the server tick the level in place runs: the first +/// reads the network (`Hub::poll`), the last ends the tick for every player +/// (`Hub::end_tick`). A tick with one level is both. +#[derive(Clone, Copy)] +pub(super) struct Pass { + pub first: bool, + pub last: bool, +} + +impl Default for Pass { + fn default() -> Self { + Self { + first: true, + last: true, + } + } +} + +/// The levels not in place, by dimension. +#[derive(Default)] +pub(super) struct Levels { + parked: HashMap, +} + +impl Game<'_> { + /// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`). + fn open_level(&self, dim: Dim) -> Result { + let (streaming, save) = + self.make_streaming(&self.world_root.clone(), dim, self.level.seed)?; + let mut world = World::new(self.res.facts.air, self.level.seed); + world.fast_lava = dim == Dim::Nether; + Ok(Parked { + world, + streaming, + save, + block_ticks: Ticks::new(self.level.seed as i32), + tick_chunks: Default::default(), + random_tick_sections: Default::default(), + level_events: Vec::new(), + falling: Vec::new(), + paintings: Vec::new(), + item_frames: Vec::new(), + armor_stands: Vec::new(), + others: Vec::new(), + boats: Vec::new(), + carts: Vec::new(), + jukebox_sounds: HashMap::new(), + bolts: Vec::new(), + crystals: Vec::new(), + dragon: None, + dragon_fireballs: Vec::new(), + breath_clouds: Vec::new(), + tridents: Vec::new(), + rockets: Vec::new(), + ominous_spawners: Vec::new(), + tnts: Vec::new(), + hoppers: HashMap::new(), + mobs: Vec::new(), + projectiles: Vec::new(), + dropped: Vec::new(), + orbs: Vec::new(), + persist: Default::default(), + lectern_pulses: Vec::new(), + lid_openers: HashMap::new(), + lan_events: Vec::new(), + lan_block_events: Vec::new(), + lan_entity_events: Vec::new(), + anims: Default::default(), + raiding: Default::default(), + sculk: Default::default(), + creaking: Default::default(), + idle: 0, + }) + } + + /// Exchange the level in place with `p`. + fn swap_level(&mut self, p: &mut Parked) { + use std::mem::swap; + swap(&mut self.world, &mut p.world); + swap(&mut self.streaming, &mut p.streaming); + swap(&mut self.save, &mut p.save); + swap(&mut self.block_ticks, &mut p.block_ticks); + swap(&mut self.tick_chunks, &mut p.tick_chunks); + swap(&mut self.random_tick_sections, &mut p.random_tick_sections); + swap(&mut self.level_events, &mut p.level_events); + swap(&mut self.falling, &mut p.falling); + swap(&mut self.paintings, &mut p.paintings); + swap(&mut self.item_frames, &mut p.item_frames); + swap(&mut self.armor_stands, &mut p.armor_stands); + swap(&mut self.others, &mut p.others); + swap(&mut self.boats, &mut p.boats); + swap(&mut self.carts, &mut p.carts); + swap(&mut self.jukebox_sounds, &mut p.jukebox_sounds); + swap(&mut self.bolts, &mut p.bolts); + swap(&mut self.crystals, &mut p.crystals); + swap(&mut self.dragon, &mut p.dragon); + swap(&mut self.dragon_fireballs, &mut p.dragon_fireballs); + swap(&mut self.breath_clouds, &mut p.breath_clouds); + swap(&mut self.tridents, &mut p.tridents); + swap(&mut self.rockets, &mut p.rockets); + swap(&mut self.ominous_spawners, &mut p.ominous_spawners); + swap(&mut self.tnts, &mut p.tnts); + swap(&mut self.hoppers, &mut p.hoppers); + swap(&mut self.mobs, &mut p.mobs); + swap(&mut self.creatures.projectiles, &mut p.projectiles); + swap(&mut self.dropped, &mut p.dropped); + swap(&mut self.orbs, &mut p.orbs); + swap(&mut self.persist, &mut p.persist); + swap(&mut self.lectern_pulses, &mut p.lectern_pulses); + swap(&mut self.lid_openers, &mut p.lid_openers); + swap(&mut self.lan_events, &mut p.lan_events); + swap(&mut self.lan_block_events, &mut p.lan_block_events); + swap(&mut self.lan_entity_events, &mut p.lan_entity_events); + let (a, b) = (&mut self.be_anims, &mut p.anims); + swap(&mut a.chests, &mut b.chests); + swap(&mut a.books, &mut b.books); + swap(&mut a.shulkers, &mut b.shulkers); + swap(&mut a.bells, &mut b.bells); + swap(&mut a.conduits, &mut b.conduits); + swap(&mut a.skulls, &mut b.skulls); + swap(&mut a.pots, &mut b.pots); + swap(&mut a.gateways, &mut b.gateways); + swap(&mut a.gateway_servers, &mut b.gateway_servers); + self.raiding.swap_level(&mut p.raiding); + self.sculk.swap_level(&mut p.sculk); + self.creaking.swap_level(&mut p.creaking); + // What only the client draws starts over. + self.particles.clear(); + self.pickups.clear(); + } + + /// Put `target`'s level in place, opening it first if it is not loaded. + /// The level that was in place is kept with the others; the shared + /// clock and weather go with the swap. `host` is the hub when the caller + /// holds it (`self.lan` is taken during the network tick). + pub(super) fn enter_level(&mut self, host: Option<&mut LanHost>, target: Dim) -> Result<()> { + // The in-frame game keeps its one level (`enter_dimension`). + if self.options.dedicated.is_none() { + return Ok(()); + } + if target != self.dim { + let (mut p, opened) = match self.levels.parked.remove(&target) { + Some(p) => (p, false), + None => (self.open_level(target)?, true), + }; + p.world.game_time = self.world.game_time; + p.world.day_time = self.world.day_time; + p.world.weather = self.world.weather; + // The sculk tables' watched blocks are built once per game. + p.world.watched = std::mem::take(&mut self.world.watched); + self.swap_level(&mut p); + p.idle = 0; + let left = std::mem::replace(&mut self.dim, target); + self.levels.parked.insert(left, p); + if opened { + // The new streaming's radius and meshing options. + self.apply_settings(); + } + } + let host = match host { + Some(h) => Some(h), + None => self.lan.as_mut(), + }; + if let Some(h) = host { + h.hub.set_dimension(target.id()); + } + Ok(()) + } + + /// One server tick (`MinecraftServer.tickServer`): each level with + /// players in turn (`tickChildren`), its chunks streamed and loaded and + /// its world ticked. The first pass reads the network and runs the + /// tick's shared parts (the clock, the weather, functions, the autosave); + /// the next ones only their level. While `paused`, only the connections + /// run. + pub(super) fn tick_server(&mut self, paused: bool) -> Result<()> { + let dims = self.levels_to_tick(); + let n = dims.len(); + let mut result = Ok(()); + for (k, dim) in dims.into_iter().enumerate() { + if let Err(e) = self.enter_level(None, dim) { + result = Err(e); + break; + } + self.level_pass = Pass { + first: k == 0, + last: k + 1 == n, + }; + self.update_dedicated_streaming(); + self.update_world(); + result = if paused { + self.tick_lan(); + Ok(()) + } else if k == 0 { + self.tick() + } else { + let running = self.clock.world_runs(); + if running { + self.tick_weather_effects(); + } + self.tick_world(running) + }; + if result.is_err() { + break; + } + } + self.level_pass = Pass::default(); + result?; + self.close_idle_levels() + } + + /// The levels this server tick runs, in `MinecraftServer.levels` order + /// (the Overworld, the Nether, the End): every level with a player in + /// it, or the Overworld while nobody is online. + pub(super) fn levels_to_tick(&self) -> Vec { + let guests = self + .lan + .as_ref() + .map_or(&[][..], |h| h.hub.guests.as_slice()); + let mut dims: Vec = [Dim::Overworld, Dim::Nether, Dim::End] + .into_iter() + .filter(|d| guests.iter().any(|g| g.dimension == d.id())) + .collect(); + if dims.is_empty() { + dims.push(Dim::Overworld); + } + dims + } + + /// Count the parked levels' empty ticks, and save and close the ones + /// (other than the Overworld) nobody has been in for a while. + pub(super) fn close_idle_levels(&mut self) -> Result<()> { + let occupied = self.levels_to_tick(); + let mut closing = Vec::new(); + for (dim, p) in &mut self.levels.parked { + if occupied.contains(dim) { + p.idle = 0; + continue; + } + p.idle += 1; + if *dim != Dim::Overworld && p.idle >= IDLE_TICKS { + closing.push(*dim); + } + } + if closing.is_empty() { + return Ok(()); + } + let back = self.dim; + for dim in closing { + self.enter_level(None, dim)?; + self.save_level(true)?; + self.enter_level(None, back)?; + self.levels.parked.remove(&dim); + } + Ok(()) + } + + /// Save every parked level (`MinecraftServer.saveAllChunks`); the level + /// in place is the caller's to save. + pub(super) fn save_parked_levels(&mut self, wait: bool) -> Result<()> { + if self.levels.parked.is_empty() { + return Ok(()); + } + let back = self.dim; + let dims: Vec = self.levels.parked.keys().copied().collect(); + for dim in dims { + self.enter_level(None, dim)?; + self.save_level(wait)?; + } + self.enter_level(None, back) + } +} diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 63f45c1c5..ff06d5ac8 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -39,6 +39,17 @@ pub(super) struct Raiding { homes: HashMap>)>, } +impl Raiding { + /// Exchange the level-held parts (`ServerLevel.getRaids`) with another + /// level's (game/levels.rs). + pub(super) fn swap_level(&mut self, other: &mut Self) { + std::mem::swap(&mut self.raids, &mut other.raids); + std::mem::swap(&mut self.loaded, &mut other.loaded); + std::mem::swap(&mut self.bar_hurts, &mut other.bar_hurts); + std::mem::swap(&mut self.homes, &mut other.homes); + } +} + /// `SectionPos` of a block position. pub(super) fn section(p: [i32; 3]) -> (i32, i32, i32) { (p[0] >> 4, p[1] >> 4, p[2] >> 4) diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 6901200f1..c06a23871 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -80,6 +80,15 @@ pub(super) struct SculkState { ticks: u32, pub tracker_loaded: bool, } + +impl SculkState { + /// Exchange the level-held parts (its sculk block entities and the + /// chunks scanned for them) with another level's (game/levels.rs). + pub(super) fn swap_level(&mut self, other: &mut Self) { + std::mem::swap(&mut self.index, &mut other.index); + std::mem::swap(&mut self.known, &mut other.known); + } +} /// An insertion-ordered set of block positions (`Level.blockEntityTickers` /// keeps the order block entities were added in). #[derive(Default)] diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index d5b1e4d95..b5ef01eed 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -1,59 +1,81 @@ -//! A server's player between dimensions. +//! A server's players 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. +//! A server holds a level per dimension (game/levels.rs). A player who steps +//! into a Nether or End portal moves to the destination's level, which opens +//! if nobody was there: the swap is the in-frame path's portal plans and +//! arrival search, and 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 around them. -use super::nether_portal::PLAYER_DELAY; +use super::nether_portal::{PLAYER_DELAY, Plan}; 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`. +/// A trip under way: the player is in the destination's level, whose +/// chunks are loading around `target`. pub(super) struct Trip { conn: u32, + dim: Dim, target: Vec3, - /// Through an End portal (or out of the End by respawning). + /// Through an End portal. end: bool, + /// The Nether portal plan, whose exit is found or built on arrival. + plan: Option, } -/// The lone player's box: Player's standing dimensions. +/// A player's box: Player's standing dimensions. const WIDTH: f64 = 0.6; const HEIGHT: f64 = 1.8; +impl Trip { + pub(super) fn is(&self, conn: u32) -> bool { + self.conn == conn + } +} + 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) + self.server_trips.iter().any(|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. + /// Per server tick in each level, after the guests' own: the arrivals of + /// the trips into this level, then `Entity.handlePortal` for each player + /// in it (Nether portals count up their transition time, End portals + /// take them at once). 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; + self.arrive_server_trips(host); + let conns: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator()) + .map(|g| g.conn) + .collect(); + for conn in conns { + if self.on_server_trip(conn) { + continue; + } + // `Entity.portalProcess` and `portalCooldown` are the player's own. + let mut portal = host.play.entry(conn).or_default().portal; + std::mem::swap(&mut self.portals.player, &mut portal); + self.handle_server_portal(host, conn); + std::mem::swap(&mut self.portals.player, &mut portal); + host.play.entry(conn).or_default().portal = portal; } - let [g] = host.hub.guests.as_slice() else { + } + + /// `Entity.handlePortal` for one player, whose portal state is in place. + fn handle_server_portal(&mut self, host: &mut LanHost, conn: u32) { + let Some(g) = host.hub.guest(conn) else { return; }; - if !g.placed || !g.loaded || g.dead || g.spectator() { - return; - } - let (conn, at, invulnerable, sleeping) = ( - g.conn, + let (at, invulnerable, sleeping) = ( Vec3::new(g.position[0], g.position[1], g.position[2]), g.creative(), g.sleeping, @@ -70,7 +92,7 @@ impl Game<'_> { } else { Dim::End }; - self.start_server_trip(host, conn, target, true); + self.start_server_trip(host, conn, target, None); } // Entity.setAsInsidePortal while cooling down restarts the cooldown. self.portals.player.cooldown = 10; @@ -93,11 +115,10 @@ impl Game<'_> { if !self.may_enter(plan.dim) { return; } - self.portals.travel = Some(plan); - self.start_server_trip(host, conn, plan.dim, false); + self.start_server_trip(host, conn, plan.dim, Some(plan)); } - /// A Nether portal block the lone player's box is in. + /// A Nether portal block a 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]; @@ -114,9 +135,16 @@ impl Game<'_> { 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) { + /// The player moves to `target`'s level (opened if nobody was there) + /// and is told it is there, at the approximate exit, while it loads. The + /// level whose tick is running is put back in place afterwards. + fn start_server_trip( + &mut self, + host: &mut LanHost, + conn: u32, + target: Dim, + plan: Option, + ) { let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { return; }; @@ -124,105 +152,100 @@ impl Game<'_> { let from = Vec3::new(g.position[0], g.position[1], g.position[2]); let yaw = g.yaw; let source = self.dim; + let end = plan.is_none(); + // Coordinates scale by 8 between the Overworld and the Nether; an + // End portal has fixed destinations. + let scale = match (source, target) { + (Dim::Overworld, Dim::Nether) | (Dim::End, Dim::Nether) => 1.0 / 8.0, + (Dim::Nether, Dim::Overworld) => 8.0, + _ => 1.0, + }; self.end_portal_travel = end; - let switched = self.switch_level(target, from); + let scaled = self.end_destination(target).unwrap_or(Vec3::new( + from.x * scale, + from.y, + from.z * scale, + )); self.end_portal_travel = false; - let destination = match switched { - Ok(d) => d, - Err(e) => { - log::error!("could not open {}: {e}", target.id()); - return; - } + if let Err(e) = self.enter_level(Some(host), target) { + log::error!("could not open {}: {e}", target.id()); + return; + } + let destination = match plan { + Some(plan) => self.arrival_centre(&plan), + None => scaled, }; - 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 { + self.server_trips.push(Trip { conn, + dim: target, target: destination, end, + plan, }); + if let Err(e) = self.enter_level(Some(host), source) { + log::error!("could not reopen {}: {e}", source.id()); + } } - /// 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) - } + /// The trips into the level in place whose destination has loaded + /// around their target: the exit (the Nether portal found or built, the + /// End platform, the Overworld's spawn column) and the teleport there. + fn arrive_server_trips(&mut self, host: &mut LanHost) { + let mut k = 0; + while k < self.server_trips.len() { + let trip = &self.server_trips[k]; + let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else { + // They left on the way. + self.server_trips.remove(k); + continue; + }; + let (cx, cz) = ( + (trip.target.x.floor() as i32) >> 4, + (trip.target.z.floor() as i32) >> 4, + ); + if trip.dim != self.dim + || !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) + { + k += 1; + continue; } - } 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) + let trip = self.server_trips.remove(k); + self.resolve_arrivals(); + let yaw = host.hub.guests[i].yaw; + let (position, yaw) = if trip.end { + match self.end_arrival(trip.target) { + Ok((at, turned)) => (at, turned.unwrap_or(yaw)), + Err(e) => { + log::error!("End arrival: {e}"); + (trip.target, yaw) + } } - _ => (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; + } else { + let exit = trip + .plan + .as_ref() + .and_then(|plan| self.nether_exit_portal(plan)); + match (trip.plan, exit) { + (Some(plan), Some(exit)) => { + let (at, rotation) = self.arrival(&plan, exit); + (at, yaw + rotation) + } + _ => (trip.target, yaw), + } + }; + // Player.getDimensionChangingDelay. + host.play.entry(trip.conn).or_default().portal.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])); } - 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. diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 0fa47510a..0a8e21586 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -25,7 +25,7 @@ impl Hub { for g in self .guests .iter() - .filter(|g| g.placed && Some(g.conn) != except) + .filter(|g| self.here(g) && Some(g.conn) != except) { let d: f64 = (0..3).map(|k| (g.position[k] - at[k]).powi(2)).sum(); if d <= range * range { @@ -464,7 +464,7 @@ impl Hub { let Some(menu) = self.guests[i] .menu .as_ref() - .filter(|_| self.guests[i].placed) + .filter(|_| self.here(&self.guests[i])) else { continue; }; diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index db426ca21..45e1eca38 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -131,6 +131,9 @@ pub struct Guest { pub dead: bool, /// The join packets were sent (PlayerList.placeNewPlayer ran). pub placed: bool, + /// The level the player is in (`ServerPlayer.level().dimension()`): the + /// hub's level passes only reach the players in theirs. + pub dimension: String, /// The open block container, if any. pub menu: Option, pub next_window: i32, @@ -226,6 +229,7 @@ impl Guest { moves_from_ground: false, dead: false, placed: false, + dimension: "minecraft:overworld".into(), menu: None, next_window: 0, drag: None, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 8fcc41329..b751fb034 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -112,6 +112,9 @@ pub struct Hub { last_rate: f32, ticking: (f32, bool), weather: (bool, f32, f32), + /// The clock and weather last sent in the levels not in place, by + /// dimension (`set_dimension` swaps them with the fields above). + level_sync: std::collections::HashMap, /// Operators and their permission levels (dedicated servers). pub ops: std::collections::HashMap, chat_type: i32, @@ -180,6 +183,24 @@ fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool { dx * dx + dz * dz < i64::from(r) * i64::from(r) } +/// What a level's players were last told of its clock and weather. +#[derive(Clone, Copy)] +struct LevelSync { + last_clock: i64, + last_rate: f32, + weather: (bool, f32, f32), +} + +impl Default for LevelSync { + fn default() -> Self { + Self { + last_clock: i64::MIN, + last_rate: 0.0, + weather: (false, 0.0, 0.0), + } + } +} + impl Hub { pub fn new(lan: Lan, sync: Arc, encoder: ChunkEncoder, config: HubConfig) -> Self { let chat_type = sync @@ -204,6 +225,7 @@ impl Hub { ticking: (20.0, false), ops: Default::default(), weather: (false, 0.0, 0.0), + level_sync: Default::default(), chat_type, dimension_type, clock_ids, @@ -257,6 +279,18 @@ impl Hub { g.sender.send(body.clone()); } } + /// Whether a guest is placed in the level in place (`config.dimension`). + pub fn here(&self, g: &Guest) -> bool { + g.placed && g.dimension == self.config.dimension + } + /// `PlayerList.broadcastAll(packet, dimension)`: the players in the + /// level in place. + pub fn broadcast_level(&self, packet: &C) { + let body = packet.encode(); + for g in self.guests.iter().filter(|g| self.here(g)) { + g.sender.send(body.clone()); + } + } pub fn broadcast_except(&self, conn: u32, packet: &C) { let body = packet.encode(); for g in self.guests.iter().filter(|g| g.placed && g.conn != conn) { @@ -448,6 +482,7 @@ impl Hub { guest.joined_tick = self.ticks; guest.position = ctx.spawn; guest.previous_position = ctx.spawn; + guest.dimension = self.config.dimension.clone(); self.guests.push(guest); conn } @@ -857,7 +892,19 @@ impl Hub { // ---- per tick ------------------------------------------------------ + /// A whole tick with one level: the network, the level, then the + /// players' latencies. pub fn tick(&mut self, ctx: &mut TickCtx) -> Vec { + let mut events = self.poll(ctx); + events.extend(self.tick_level(ctx)); + self.end_tick(); + events + } + + /// The network since the last tick, once per server tick before any + /// level ticks: joins (into the level in place), leaves, and each guest's + /// packets queued for its own level's pass. + pub fn poll(&mut self, ctx: &mut TickCtx) -> Vec { self.ticks += 1; let mut events = Vec::new(); for event in self.lan.poll() { @@ -893,13 +940,25 @@ impl Hub { } } } + events + } + + /// The level in place's part of the tick (`ServerLevel.tick`'s chunk + /// map and the connections of the players in it): their packets, then + /// the chunks, block changes, containers and entities they see. + pub fn tick_level(&mut self, ctx: &mut TickCtx) -> Vec { + let mut events = Vec::new(); for i in 0..self.guests.len() { - if self.guests[i].placed { + if self.here(&self.guests[i]) { self.process_inbox(i, ctx, &mut events); } } - if !self.guests.iter().any(|g| g.placed) { - if self.guests.is_empty() { + if !self.guests.iter().any(|g| self.here(g)) { + if !self + .guests + .iter() + .any(|g| g.dimension == self.config.dimension) + { let _ = ctx.world.block_log.take(); } return events; @@ -909,7 +968,7 @@ impl Hub { } self.sync_world(ctx); for i in 0..self.guests.len() { - if self.guests[i].placed { + if self.here(&self.guests[i]) { self.update_chunks(i, ctx); } } @@ -917,7 +976,7 @@ impl Hub { // ServerGamePacketListenerImpl.tick: the actions handled since the last tick are // acknowledged after the block changes they made were sent, so a client's predicted // blocks settle on the server's states. - for g in &self.guests { + for g in self.guests.iter().filter(|g| self.here(g)) { let sequence = g.ack_up_to.replace(-1); if sequence >= 0 { g.send(&C::BlockChangedAck(play::BlockChangedAck { sequence })); @@ -926,11 +985,16 @@ impl Hub { self.sync_containers(ctx.world); self.track_entities(ctx); for i in 0..self.guests.len() { - if self.guests[i].placed { + if self.here(&self.guests[i]) { self.sync_player_state(i); self.sync_effects(i); } } + events + } + + /// After every level: `PlayerList.tick`. + pub fn end_tick(&mut self) { let latencies: Vec<_> = self .guests .iter() @@ -952,7 +1016,6 @@ impl Hub { entries, })); } - events } fn remove_guest(&mut self, i: usize, reason: &str) -> Guest { @@ -983,7 +1046,7 @@ impl Hub { // MinecraftServer.tickServer: the game time every 20 ticks // (forceGameTimeSynchronization, no clocks). if self.ticks.is_multiple_of(20) { - self.broadcast(&C::SetTime(play::SetTime { + self.broadcast_level(&C::SetTime(play::SetTime { game_time: world.game_time, clocks: Vec::new(), })); @@ -999,7 +1062,7 @@ impl Hub { .sync .id("minecraft:world_clock", "minecraft:overworld") .unwrap_or(0); - self.broadcast(&C::SetTime(play::SetTime { + self.broadcast_level(&C::SetTime(play::SetTime { game_time: world.game_time, clocks: vec![play::ClockState { clock: overworld, @@ -1018,7 +1081,7 @@ impl Hub { let w = &world.weather; let (raining, rain, thunder) = self.weather; if w.raining != raining { - self.broadcast(&C::GameEvent(play::GameEvent { + self.broadcast_level(&C::GameEvent(play::GameEvent { event: if w.raining { game_event::START_RAINING } else { @@ -1028,13 +1091,13 @@ impl Hub { })); } if (w.rain_level.1 - rain).abs() > f32::EPSILON { - self.broadcast(&C::GameEvent(play::GameEvent { + self.broadcast_level(&C::GameEvent(play::GameEvent { event: game_event::RAIN_LEVEL, param: w.rain_level.1, })); } if (w.thunder_level.1 - thunder).abs() > f32::EPSILON { - self.broadcast(&C::GameEvent(play::GameEvent { + self.broadcast_level(&C::GameEvent(play::GameEvent { event: game_event::THUNDER_LEVEL, param: w.thunder_level.1, })); @@ -1164,7 +1227,7 @@ impl Hub { for ((sx, sy, sz), positions) in sections { let viewers: Vec = (0..self.guests.len()) .filter(|&i| { - self.guests[i].placed && self.guests[i].sent_chunks.contains(&(sx, sz)) + self.here(&self.guests[i]) && self.guests[i].sent_chunks.contains(&(sx, sz)) }) .collect(); if viewers.is_empty() { @@ -1329,7 +1392,7 @@ impl Hub { )); } let placed: Vec = (0..self.guests.len()) - .filter(|&i| self.guests[i].placed) + .filter(|&i| self.here(&self.guests[i])) .collect(); let guest_states: Vec<_> = placed .into_iter() @@ -1363,7 +1426,7 @@ impl Hub { let by_id: std::collections::HashMap = all.iter().enumerate().map(|(i, e)| (e.id, i)).collect(); for gi in 0..self.guests.len() { - if !self.guests[gi].placed { + if !self.here(&self.guests[gi]) { continue; } let view = self.guests[gi].view_distance; @@ -1772,12 +1835,15 @@ impl Hub { let mode = self.guests[i].game_mode; let mut info = self.spawn_info(mode); // Player.getLastDeathLocation, set where the player died. + // The level they died in: theirs until now. info.last_death = self.guests[i].last_death.map(|pos| play::GlobalPos { - dimension: self.config.dimension.clone(), + dimension: self.guests[i].dimension.clone(), pos, }); self.close_container_for(i); let g = &mut self.guests[i]; + // PlayerList.respawn: into the level in place (the respawn level). + g.dimension = self.config.dimension.clone(); // ServerLevel.removePlayerImmediately: every entity paired with the dead player is // removed (ServerEntity.removePairing, one packet each). Its chunks are dropped // without ForgetLevelChunk (PlayerChunkSender.dropChunk skips dead players): the @@ -1846,6 +1912,20 @@ impl Hub { /// 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) { + if self.config.dimension == dimension { + return; + } + // What this level's players were told stays with it. + let leaving = LevelSync { + last_clock: self.last_clock, + last_rate: self.last_rate, + weather: self.weather, + }; + let entering = self.level_sync.remove(dimension).unwrap_or_default(); + self.level_sync + .insert(std::mem::take(&mut self.config.dimension), leaving); + (self.last_clock, self.last_rate, self.weather) = + (entering.last_clock, entering.last_rate, entering.weather); self.config.dimension = dimension.to_owned(); self.dimension_type = self .sync @@ -1865,6 +1945,7 @@ impl Hub { let info = self.spawn_info(mode); self.close_container_for(i); let g = &mut self.guests[i]; + g.dimension = self.config.dimension.clone(); g.tracker.clear(); g.sent_chunks.clear(); g.chunk_queue.clear(); diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 555463685..44b269a8f 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -71,6 +71,10 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.selected = (level.selected_slot.max(0) as usize).min(8); guest.saved = level.player_extra.clone(); guest.recipe_book = level.recipe_book.clone(); + guest.dimension = match level.dimension.as_str() { + d @ ("minecraft:the_nether" | "minecraft:the_end") => d.to_owned(), + _ => "minecraft:overworld".to_owned(), + }; if level.ender_items.len() == 27 { guest.ender_items = level.ender_items.clone(); } @@ -100,7 +104,6 @@ pub fn apply(guest: &mut Guest, level: &Level) { pub fn save(guest: &Guest, world: &Path) { let mut level = Level { player_uuid: Some(uuid_ints(guest.uuid)), - dimension: "minecraft:overworld".into(), ..Level::default() }; store(guest, &mut level); @@ -114,6 +117,7 @@ pub fn save(guest: &Guest, world: &Path) { /// Put a guest's state in `level`'s player fields. pub fn store(guest: &Guest, level: &mut Level) { level.position = Some(guest.position); + level.dimension = guest.dimension.clone(); level.rotation = [guest.yaw, guest.pitch]; level.health = guest.health; level.food = guest.food; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index d76cf922c..48d45f714 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -21,7 +21,10 @@ address. The script then checks, from both sides, what a guest's game used to ge - pvp: the guest and the host hit each other with a sword; with the pvp game rule off, nothing; - containers: the guest's ender chest holds the guest's items, not the host's, and a double chest opens as 9x6 with the right half first; -- feedback: the guest's command feedback names the guest and shows the numbers. +- feedback: the guest's command feedback names the guest and shows the numbers; +- portals: (--server-thread) the server holds a level per dimension: the guest goes to the Nether + through a portal while the host stays, then the host goes to the End while the guest is in + the Nether, and both come back. Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -29,6 +32,7 @@ both sides go to --out (host-*.png, guest-*.png). python3 tools/lan_e2e.py # build with the fast profile, run every check python3 tools/lan_e2e.py --bin-dir target/fast # prebuilt binaries python3 tools/lan_e2e.py --check chest --check tab + python3 tools/lan_e2e.py --server-thread --check portals # the host's world on its server thread Needs the prepared resources in .local/horizon-client and, on Linux, vscreen (the desktop); on macOS both games render offscreen. Games started here have no audio (HORIZON_NO_AUDIO=1). @@ -50,7 +54,9 @@ from agent_control_e2e import Cli, Failed, game_env # noqa: E402 ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials'] +# The host plays single player on its server thread (--server-thread). +SERVER_THREAD = False +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials', 'portals'] class Game: @@ -288,6 +294,65 @@ def check_sign(host, guest, out): return placed +def wait_dimension(game, dimension, ticks): + """Wait up to `ticks` for the game to be in `dimension` with its world loaded around it.""" + for _ in range(ticks // 20): + state = game('state') + if state.get('dimension') == dimension and state.get('player'): + return state + game.wait(20) + return game('state') + + +def nether_portal(game, x, y, z): + """A lit portal along x, two blocks wide and three tall, its inside starting at x y z.""" + game('command', command=f'fill {x - 1} {y - 1} {z} {x + 2} {y + 3} {z} minecraft:obsidian') + game('command', command=f'fill {x} {y} {z} {x + 1} {y + 2} {z} minecraft:nether_portal[axis=x]') + + +def check_portals(host, guest, out): + if not SERVER_THREAD: + return 'skipped (needs --server-thread)' + x, y, z = (int(v // 1) for v in pos_of(guest)) + nether_portal(guest, x, y, z + 3) + guest.wait(5) + guest('command', command=f'tp @s {x + 0.5} {y} {z + 3.5}') + # players_nether_portal_default_delay: 80 ticks in survival. + there = wait_dimension(guest, 'minecraft:the_nether', 600) + guest.wait(40) + guest.shot(out, 'portals-nether') + host_dim = host('state').get('dimension') + assert there.get('dimension') == 'minecraft:the_nether', f'the guest is in {there.get("dimension")}' + assert host_dim == 'minecraft:overworld', f'the host went to {host_dim} with the guest' + arrived = [int(v // 1) for v in pos_of(guest)] + below = guest.raw('block', arrived[0], arrived[1] - 1, arrived[2]) + assert below.get('loaded') and below.get('block') != 'minecraft:air', f'under the guest in the Nether: {below}' + # The host takes an End portal while the guest is in the Nether: three levels at once. + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + host('command', command=f'setblock {hx} {hy} {hz} minecraft:end_portal') + end = wait_dimension(host, 'minecraft:the_end', 600) + host.wait(40) + host.shot(out, 'portals-end') + guest_dim = guest('state').get('dimension') + assert end.get('dimension') == 'minecraft:the_end', f'the host is in {end.get("dimension")}' + assert guest_dim == 'minecraft:the_nether', f'the guest left the Nether for {guest_dim}' + # Both come back: the host through an exit portal, the guest out of its portal and in again. + ex, ey, ez = (int(v // 1) for v in pos_of(host)) + host('command', command=f'setblock {ex + 2} {ey} {ez} minecraft:end_portal') + host('command', command=f'tp @s {ex + 2.5} {ey} {ez + 0.5}') + guest('command', command=f'tp @s {arrived[0] + 0.5} {arrived[1]} {arrived[2] - 2.5}') + guest.wait(30) + guest('command', command=f'tp @s {arrived[0] + 0.5} {arrived[1]} {arrived[2] + 0.5}') + home = wait_dimension(host, 'minecraft:overworld', 600) + back = wait_dimension(guest, 'minecraft:overworld', 600) + guest.wait(40) + host.shot(out, 'portals-back') + guest.shot(out, 'portals-back') + assert home.get('dimension') == 'minecraft:overworld', f'the host stayed in {home.get("dimension")}' + assert back.get('dimension') == 'minecraft:overworld', f'the guest stayed in {back.get("dimension")}' + return {'guest_nether': arrived, 'host_end': [ex, ey, ez], 'back': pos_of(guest)} + + def check_damage(host, guest, out): guest('command', command='gamemode survival') guest.wait(10) @@ -662,11 +727,13 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials, - 'walls': check_walls} + 'walls': check_walls, 'portals': check_portals} def run(ctl, out, resources, checks): host, guest = Game('host', ctl, resources), Game('guest', ctl, resources) + if SERVER_THREAD: + host.d.env['HORIZON_SERVER_THREAD'] = '1' results = {} try: host('launch', wait=False, offscreen=sys.platform == 'darwin') @@ -712,7 +779,10 @@ def main(): parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build with the fast profile)') parser.add_argument('--check', action='append', choices=CHECKS, help='run only these checks (repeatable)') parser.add_argument('--out', default=str(ROOT / '.local/lan-e2e'), help='screenshots and game logs go here') + parser.add_argument('--server-thread', action='store_true', help="the host's world runs on its server thread") args = parser.parse_args() + global SERVER_THREAD + SERVER_THREAD = args.server_thread if args.bin_dir: bins = Path(args.bin_dir).resolve() else: From b2784363a138e8e4124428e369d8aa22851cffe7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 14:49:29 +0200 Subject: [PATCH 3/6] Mobs see only the guests in their own level Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan_mobs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index e613a9a2f..53b79407c 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -92,7 +92,7 @@ impl Game<'_> { .hub .guests .iter() - .filter(|g| g.placed && g.loaded && !g.dead) + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) .map(|g| { let moved = [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]); (g.conn, g.uuid, moved) From 805d5532e541deb1888216c8ebfc15775d8b2ea5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 15:04:04 +0200 Subject: [PATCH 4/6] Give mob, beacon, sculk and splash effects to every player On a server (the integrated server thread and the dedicated server) the host has no player of its own, so effects that only touched the host's player reached nobody; on a LAN world they reached only the host. Beacons, the warden's and shriekers' darkness, the elder guardian's mining fatigue, splash and lingering potions' splash and the raid victory's Hero of the Village now run for each player in the level, guests through `as_guest`. The elder guardian's curse sends the guest the GUARDIAN_ELDER_EFFECT game event, which the remote client now shows (the apparition and the curse sound). lan_e2e.py gains an `effects` check: a speed beacon next to both players must give both of them speed. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/beacon.rs | 4 ++ crates/horizon-client/src/game/creatures.rs | 41 ++++++++++-- crates/horizon-client/src/game/lan_actions.rs | 26 ++++++++ crates/horizon-client/src/game/potions.rs | 66 +++++++++++-------- crates/horizon-client/src/game/raids.rs | 14 ++-- crates/horizon-client/src/game/remote.rs | 15 +++++ crates/horizon-client/src/game/sculk.rs | 3 + crates/horizon-client/src/lan/hub.rs | 1 + tools/lan_e2e.py | 27 +++++++- 9 files changed, 153 insertions(+), 44 deletions(-) diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 15a7de79d..c8c437965 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -220,7 +220,11 @@ impl Game<'_> { levels } /// `applyEffects`: the powers for players within `levels * 10 + 10` (any height above). + /// `BeaconBlockEntity.applyEffects`: every player in range. fn beacon_effects(&mut self, p: [i32; 3], b: &Beacon) { + self.for_each_player(|g| g.beacon_effects_on_player(p, b)); + } + fn beacon_effects_on_player(&mut self, p: [i32; 3], b: &Beacon) { let Some(primary) = b.primary.as_deref().and_then(effect_id) else { return; }; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 076c2fbef..6fc25eb67 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1358,25 +1358,52 @@ impl Game<'_> { /// mining fatigue III for five minutes unless a stronger or longer one /// is on, with the curse sound and the elder's apparition. fn elder_curse(&mut self, at: [f64; 3]) { + let mut cursed = Vec::new(); + self.for_each_player(|g| { + if g.elder_curse_player(at) { + cursed.push(g.lan_acting); + } + }); + // A guest's client shows the apparition and plays the curse itself + // (ClientboundGameEventPacket.GUARDIAN_ELDER_EFFECT). + if let Some(host) = self.lan.as_ref() { + for conn in cursed.into_iter().flatten() { + host.hub.send_to( + conn, + &horizon_protocol::packets::play::Clientbound::GameEvent( + horizon_protocol::packets::play::GameEvent { + event: horizon_client::lan::hub::game_event::GUARDIAN_ELDER_EFFECT, + param: 1.0, + }, + ), + ); + } + } + } + /// The curse on the player in place; whether it took. + fn elder_curse_player(&mut self, at: [f64; 3]) -> bool { if self.creative || self.spectator() { - return; + return false; } let Some(p) = self.player.as_ref() else { - return; + return false; }; let d = p.position.subtract(Vec3::new(at[0], at[1], at[2])); if d.x * d.x + d.y * d.y + d.z * d.z >= 2500.0 || p.health.dead_or_dying() { - return; + return false; } let active = self.potions.effects.get("minecraft:mining_fatigue"); if active.is_some_and(|e| e.amplifier >= 2 && e.duration >= 1200) { - return; + return false; } let at = [p.position.x, p.position.y, p.position.z]; self.give_player_effect("minecraft:mining_fatigue", 6000, 2); - self.audio - .play("minecraft:entity.elder_guardian.curse", Some(at), 1.0, 1.0); - self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS; + if self.lan_acting.is_none() { + self.audio + .play("minecraft:entity.elder_guardian.curse", Some(at), 1.0, 1.0); + self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS; + } + true } /// Damage of a given type to the player from a point. pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 6b0463290..bb81c913f 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -291,6 +291,32 @@ impl Game<'_> { Some(result) } + /// `ServerLevel.players()` in turn: the host's own player, then each + /// guest in the level in place with their state swapped in (`as_guest`). + /// What reaches the players around a point (a beacon's powers, a splash + /// potion, a warden's darkness, an elder guardian's curse) lands on each + /// of them, not only on the host. A server has no player of its own. + /// Inside a guest's action (the hub taken) only that player is in place. + pub(super) fn for_each_player(&mut self, mut f: impl FnMut(&mut Self)) { + if self.player.is_some() { + f(self); + } + let Some(mut host) = self.lan.take() else { + return; + }; + let conns: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| g.conn) + .collect(); + for conn in conns { + self.as_guest(&mut host, conn, &mut f); + } + self.lan = Some(host); + } + /// The game mode fields without `set_mode`'s side effects on the host. fn set_mode_raw(&mut self, id: i32) { use horizon_client::command::args::GameMode; diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index a60926256..ffa63b7c9 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -467,6 +467,41 @@ impl Game<'_> { self.splash(&stack, at); } } + /// A splash potion's effects on the player in place, by their distance. + fn splash_on_player( + &mut self, + effects: &'static [(&'static str, i32, i32)], + at: Vec3, + scale: f64, + ) { + if let Some(p) = self.player.as_ref() { + let center = Vec3::new( + p.position.x, + p.position.y + f64::from(p.dimensions.height) / 2.0, + p.position.z, + ); + let d2 = + (center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2); + if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) { + let intensity = 1.0 - d2.sqrt() / 4.0; + for (id, duration, amp) in effects { + let instant = brewing::effect(id).is_some_and(|e| e.instant); + if instant { + if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { + self.apply_effect_action(a); + } + } else { + let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; + if d > 20 + && let Some(e) = brewing::effect(id) + { + self.potions.effects.add(EffectInstance::new(e.id, d, *amp)); + } + } + } + } + } + } /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). fn splash(&mut self, stack: &ItemStack, at: Vec3) { if &*stack.item == "minecraft:experience_bottle" { @@ -527,34 +562,9 @@ impl Game<'_> { let Some(def) = stack.potion().and_then(brewing::potion) else { return; }; - // The player. - if let Some(p) = self.player.as_ref() { - let center = Vec3::new( - p.position.x, - p.position.y + f64::from(p.dimensions.height) / 2.0, - p.position.z, - ); - let d2 = - (center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2); - if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) { - let intensity = 1.0 - d2.sqrt() / 4.0; - for (id, duration, amp) in def.effects { - let instant = brewing::effect(id).is_some_and(|e| e.instant); - if instant { - if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { - self.apply_effect_action(a); - } - } else { - let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; - if d > 20 - && let Some(e) = brewing::effect(id) - { - self.potions.effects.add(EffectInstance::new(e.id, d, *amp)); - } - } - } - } - } + // Every player in range (`ThrownSplashPotion.applySplash` over + // `LivingEntity`s, the players among them). + self.for_each_player(|g| g.splash_on_player(def.effects, at, scale)); // Mobs take the instant effects (undead invert healing and harming). let undead = &self.res.stations.enchantments.entity_tags; let mut hits = Vec::new(); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index ff06d5ac8..25a440af3 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -624,17 +624,17 @@ impl Game<'_> { raider::state_mut(m).ticks_outside_raid = ticks; } } - Action::Victory { heroes, amplifier } => { - let me = self.level.player_uuid; - if me.is_some_and(|u| heroes.contains(&u)) && !self.spectator() { + // Raid.tick on a victory: each hero who is still alive. + Action::Victory { heroes, amplifier } => self.for_each_player(|g| { + if heroes.contains(&g.acting_uuid()) && !g.spectator() { let mut effect = EffectInstance::new("hero_of_the_village", raid::HERO_DURATION, amplifier); effect.visible = false; - self.potions.effects.add(effect); - self.stats.custom("raid_win", 1); - self.trigger_player("minecraft:hero_of_the_village"); + g.potions.effects.add(effect); + g.stats.custom("raid_win", 1); + g.trigger_player("minecraft:hero_of_the_village"); } - } + }), } } /// `Raid.playSound`: the horn, 13 blocks away from the player toward the diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 05e1f81c3..f5539ffd2 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1439,6 +1439,21 @@ impl Game<'_> { } } C::GameEvent(p) => match p.event { + // GUARDIAN_ELDER_EFFECT: the apparition, and the curse sound + // unless the elder guardian is silent. + 10 => { + self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS; + if p.param == 1.0 + && let Some(at) = self.player.as_ref().map(|m| m.position) + { + self.audio.play( + "minecraft:entity.elder_guardian.curse", + Some([at.x, at.y, at.z]), + 1.0, + 1.0, + ); + } + } 1 => { self.world.weather.raining = true; self.world.weather.rain_level = (0.0, 0.0); diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index c06a23871..e33b78d5f 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -1180,6 +1180,9 @@ impl Game<'_> { /// `Warden.applyDarknessAround` / `MobEffectUtil.addEffectToPlayersAround`. pub(super) fn apply_darkness(&mut self, at: [f64; 3], radius: f64) { + self.for_each_player(|g| g.darkness_on_player(at, radius)); + } + fn darkness_on_player(&mut self, at: [f64; 3], radius: f64) { if self.creative || self.spectator() { return; } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b751fb034..bc5761246 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -32,6 +32,7 @@ pub mod game_event { pub const CHANGE_GAME_MODE: u8 = 3; pub const RAIN_LEVEL: u8 = 7; pub const THUNDER_LEVEL: u8 = 8; + pub const GUARDIAN_ELDER_EFFECT: u8 = 10; pub const LEVEL_CHUNKS_LOAD_START: u8 = 13; } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 48d45f714..2de0a564c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -22,6 +22,7 @@ address. The script then checks, from both sides, what a guest's game used to ge - containers: the guest's ender chest holds the guest's items, not the host's, and a double chest opens as 9x6 with the right half first; - feedback: the guest's command feedback names the guest and shows the numbers; +- effects: a beacon's power reaches every player in range, the host and the guest; - portals: (--server-thread) the server holds a level per dimension: the guest goes to the Nether through a portal while the host stays, then the host goes to the End while the guest is in the Nether, and both come back. @@ -56,7 +57,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials', 'portals'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'trials', 'effects', 'portals'] class Game: @@ -294,6 +295,28 @@ def check_sign(host, guest, out): return placed +def effect_ids(game): + return [e.get('id', '').removeprefix('minecraft:') for e in game('state')['player'].get('effects', [])] + + +def check_effects(host, guest, out): + x, y, z = (int(v // 1) for v in pos_of(host)) + bx, by, bz = x - 3, y, z - 3 + host('command', command=f'fill {bx - 1} {by - 1} {bz - 1} {bx + 1} {by - 1} {bz + 1} minecraft:iron_block') + host('command', command=f'setblock {bx} {by} {bz} minecraft:beacon{{primary_effect:"minecraft:speed"}}') + # BeaconBlockEntity.tick applies its powers every 80 ticks, once the beam has reached the sky. + seen = {} + for _ in range(15): + host.wait(20) + seen = {'host': effect_ids(host), 'guest': effect_ids(guest)} + if all('speed' in v for v in seen.values()): + break + host.shot(out, 'effects') + guest.shot(out, 'effects') + assert 'speed' in seen['host'] and 'speed' in seen['guest'], f'beacon effects: {seen}' + return seen + + def wait_dimension(game, dimension, ticks): """Wait up to `ticks` for the game to be in `dimension` with its world loaded around it.""" for _ in range(ticks // 20): @@ -727,7 +750,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'containers': check_containers, 'feedback': check_feedback, 'trials': check_trials, - 'walls': check_walls, 'portals': check_portals} + 'walls': check_walls, 'effects': check_effects, 'portals': check_portals} def run(ctl, out, resources, checks): From 7733984e7898787e2e388ee0361475c67e27e9cc Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 21:40:51 +0200 Subject: [PATCH 5/6] levels.rs: per-level block events carry u32 states (#674) Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/levels.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 82a142364..3a84e2f78 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -65,7 +65,7 @@ pub(super) struct Parked { lectern_pulses: Vec<((i32, i32, i32), i32)>, lid_openers: HashMap<(i32, i32, i32), i32>, lan_events: Vec<(i32, [i32; 3], i32, Option)>, - lan_block_events: Vec<([i32; 3], i32, i32, u16)>, + lan_block_events: Vec<([i32; 3], i32, i32, u32)>, lan_entity_events: Vec<(i32, i8, [f64; 3])>, /// Only the per-level parts of these are used (`swap_level`). anims: BlockEntityAnims, From 9240aeb9ff8b315b38895dd24e64243a46bbd49b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 22:05:16 +0200 Subject: [PATCH 6/6] Input capture test: the mock Game has lan_acting (#687) Co-Authored-By: Claude Opus 5.5 --- tests/test_world_input_capture.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_world_input_capture.py b/tests/test_world_input_capture.py index c7fc4629f..5937ad767 100644 --- a/tests/test_world_input_capture.py +++ b/tests/test_world_input_capture.py @@ -67,13 +67,13 @@ struct Remote { chat_input: Option<()> } struct Game { focused: bool, agent_pointer: bool, window: Option, mouse: Mouse, captured: bool, title: Option<()>, screen: Screen, remote: Option, - mining: bool, + mining: bool, lan_acting: Option, } impl Default for Game { fn default() -> Self { Self { focused: true, agent_pointer: false, window: Some(Window::default()), mouse: Mouse::default(), captured: false, title: None, - screen: Screen::Playing, remote: None, mining: false } + screen: Screen::Playing, remote: None, mining: false, lan_acting: None } } } impl Game {