diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index cfbb526ef..bb9d8f0a7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9979,6 +9979,10 @@ impl ApplicationHandler for Game<'_> { self.pause = self.pauses_game(); if let Some(server) = &self.integrated { server.set_paused(self.pause); + server.set_distances( + self.settings.render_distance, + self.settings.simulation_distance, + ); } self.clock.end_frame(self.pause); let finished = self diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 412c41693..b2c0a2e7f 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -28,7 +28,7 @@ use std::{ path::Path, sync::{ Arc, - atomic::{AtomicBool, AtomicU16, AtomicU32, Ordering}, + atomic::{AtomicBool, AtomicI32, AtomicU16, AtomicU32, Ordering}, mpsc::{Receiver, Sender, channel, sync_channel}, }, thread::JoinHandle, @@ -45,6 +45,10 @@ struct Flags { /// while it is not. published: AtomicU16, smoothed_tick_ms: AtomicU32, + /// `options.renderDistance` and `options.simulationDistance`, which the + /// server follows while it runs (IntegratedServer.tickServer). + render_distance: AtomicI32, + simulation_distance: AtomicI32, } /// Work the window hands its server thread (`MinecraftServer.execute`). @@ -66,6 +70,13 @@ impl Integrated { pub fn set_paused(&self, paused: bool) { self.flags.paused.store(paused, Ordering::Relaxed); } + /// The window's render and simulation distances, for the server to follow. + pub fn set_distances(&self, render: i32, simulation: i32) { + self.flags.render_distance.store(render, Ordering::Relaxed); + self.flags + .simulation_distance + .store(simulation, Ordering::Relaxed); + } /// `IntegratedServer.getPort` while `isPublished`. pub fn published(&self) -> Option { Some(self.flags.published.load(Ordering::Relaxed)).filter(|&p| p != 0) @@ -192,6 +203,12 @@ impl Game<'_> { options.dev_mods.clear(); let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone()); let flags = Arc::new(Flags::default()); + flags + .render_distance + .store(settings.render_distance, Ordering::Relaxed); + flags + .simulation_distance + .store(settings.simulation_distance, Ordering::Relaxed); let (ready_tx, ready) = channel(); let (tasks, server_tasks) = channel(); let server_flags = flags.clone(); @@ -249,7 +266,9 @@ impl Game<'_> { launch.create.as_ref(), )?; let saved = Box::new(self.level.clone()); - let view_distance = self.settings.render_distance.clamp(2, 32); + // Math.max(2, options.renderDistance): past vanilla's 32 when the + // window's render distance is (Horizon's options go to 64). + let view_distance = self.settings.render_distance.max(2); let config = HubConfig { default_game_mode: self.level.mode(), // Only the owner until it is opened to the LAN. @@ -257,7 +276,7 @@ impl Game<'_> { force_game_mode: false, hardcore: self.level.hardcore, view_distance, - simulation_distance: self.settings.simulation_distance.clamp(2, 32), + simulation_distance: self.settings.simulation_distance.max(2), dimension: self.dim.id().to_owned(), seed: self.level.seed, max_players: MAX_PLAYERS, @@ -318,6 +337,7 @@ impl Game<'_> { // Only the connections run. self.tick_server(true)?; } else { + self.follow_distances(&flags); let started = Instant::now(); self.tick_server(false)?; self.debug_charts.log_tick(started, started.elapsed()); @@ -438,6 +458,28 @@ impl Game<'_> { } /// Publish or unpublish for real, once the hub is in its place (a /// player's `/publish` runs while it is out). + /// IntegratedServer.tickServer: the server follows the window's render + /// and simulation distances when they change. + fn follow_distances(&mut self, flags: &Flags) { + let Some(host) = self.lan.as_mut() else { + return; + }; + let view = flags.render_distance.load(Ordering::Relaxed).max(2); + let old = host.hub.config.view_distance; + if view != old { + log::info!("Changing view distance to {view}, from {old}"); + host.hub.set_view_distance(view); + self.settings.render_distance = view; + } + let simulation = flags.simulation_distance.load(Ordering::Relaxed).max(2); + let old = host.hub.config.simulation_distance; + if simulation != old { + log::info!("Changing simulation distance to {simulation}, from {old}"); + host.hub.set_simulation_distance(simulation); + self.settings.simulation_distance = simulation; + } + } + fn apply_publish(&mut self) { if self.lan.is_none() { return; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index e5769acde..474e943c0 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -100,6 +100,8 @@ pub(super) struct Remote { was_sprinting: bool, carried: Option, loaded_sent: bool, + /// The view distance last sent in ClientInformation. + sent_view: i8, /// BlockStatePredictionHandler: blocks changed ahead of the server (a predicted break), /// with the sequence of the last action that changed them and the state the server /// last said they have. Until the server acknowledges that sequence its block updates @@ -209,7 +211,7 @@ impl Game<'_> { .and_then(|p| Builtin::load(&p).ok()) .ok_or("Resources are incomplete: registries.json is missing or invalid. Click \"Prepare again\" in the launcher (or run horizon-prepare), then try again.")?; let lang = Arc::new(horizon_client::net::load_language(&root)); - let view = self.settings.render_distance.clamp(2, 32) as i8; + let view = client_view_distance(self.settings.render_distance); if local.is_none() { horizon_client::crash::set_detail( "Server", @@ -296,6 +298,7 @@ impl Game<'_> { was_sprinting: false, carried: None, loaded_sent: false, + sent_view: view, predictions: HashMap::new(), menu: None, menu_title: None, @@ -1153,10 +1156,12 @@ impl Game<'_> { self.streaming.radius = self.settings.render_distance.min(p.chunk_radius + 1).max(2); self.enter_remote_dimension(&p.spawn, false); + let view = client_view_distance(self.settings.render_distance); + if let Some(r) = self.remote.as_mut() { + r.sent_view = view; + } self.send(S::ClientInformation( - horizon_protocol::packets::configuration::ClientInformation::new( - self.settings.render_distance.clamp(2, 32) as i8, - ), + horizon_protocol::packets::configuration::ClientInformation::new(view), )); } C::Respawn(p) => { @@ -2303,6 +2308,17 @@ impl Game<'_> { /// One client tick while connected (Minecraft.tick with a ClientLevel). pub(super) fn tick_remote(&mut self) -> Result<()> { self.ticks += 1; + // Options.broadcastOptions: a changed render distance is sent again. + let view = client_view_distance(self.settings.render_distance); + if let Some(r) = self.remote.as_mut() + && r.joined + && r.sent_view != view + { + r.sent_view = view; + self.send(S::ClientInformation( + horizon_protocol::packets::configuration::ClientInformation::new(view), + )); + } // Minecraft.tick: TickRateManager.tick; ClientLevel.tick advances // the time only while the level runs normally. let running = self.clock.world_runs(); @@ -3749,6 +3765,12 @@ pub(super) fn input_ordinal(input: Input) -> i32 { } } +/// The view distance a client asks for: its render distance, which Horizon +/// lets go past vanilla's 32 (a vanilla server still caps it at its own). +fn client_view_distance(render_distance: i32) -> i8 { + render_distance.clamp(2, i32::from(i8::MAX)) as i8 +} + #[cfg(test)] mod tests { use super::Game; diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index e877fdd64..54b3ba63b 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -299,6 +299,22 @@ impl Hub { g.sender.send(body.clone()); } } + /// PlayerList.setViewDistance: every player is told the new radius, + /// and each one's chunks follow it, up to what they asked for + /// (ChunkMap.getPlayerViewDistance). + pub fn set_view_distance(&mut self, distance: i32) { + self.config.view_distance = distance; + self.broadcast(&C::SetChunkCacheRadius(play::Distance { distance })); + for g in &mut self.guests { + g.view_distance = i32::from(g.info.view_distance).clamp(2, distance); + g.center = None; + } + } + /// PlayerList.setSimulationDistance. + pub fn set_simulation_distance(&mut self, distance: i32) { + self.config.simulation_distance = distance; + self.broadcast(&C::SetSimulationDistance(play::Distance { distance })); + } /// 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 diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 7dc8b2c01..c306504ab 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -23,6 +23,8 @@ address. The script then checks, from both sides, what a guest's game used to ge 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; +- distance: (--server-thread) the server follows the host's render distance, past vanilla's 32 too + (IntegratedServer.tickServer), and the guest's chunks follow the server's (#804) - 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. @@ -79,7 +81,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', 'titles', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'objects', 'projectiles', 'effects', 'portals'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'titles', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'objects', 'projectiles', 'effects', 'portals', 'distance'] class Game: @@ -192,7 +194,7 @@ def check_armour(host, guest, out): face_each_other(host, guest) host.shot(out, 'armour') guest.shot(out, 'armour') - seen = host.raw('lan', 'status')['guests'][0].get('model_armor') + seen = lan_guest(host).get('model_armor') assert seen == [None, 'minecraft:diamond_chestplate', 'minecraft:diamond_leggings', None], \ f'the host draws the guest in {seen}' host_gear = [e for e in remote(guest).get('player_equipment', [])] @@ -355,6 +357,33 @@ def nether_portal(game, x, y, z): game('command', command=f'fill {x} {y} {z} {x + 1} {y + 2} {z} minecraft:nether_portal[axis=x]') +def lan_guest(host): + """The guest's entry in the host's `lan status` (on the server thread the owner is listed too).""" + guests = host.raw('lan', 'status')['guests'] + return next(g for g in guests if g['name'] == GUEST_NAME) + +def check_distance(host, guest, out): + """IntegratedServer.tickServer: the server takes the host's render distance as its view distance + (past 32, which Horizon's options allow) and sends it to every player (SetChunkCacheRadius).""" + if not SERVER_THREAD: + return 'skipped (needs --server-thread)' + seen = {} + try: + for distance in (48, 6): + host.raw('render-distance', distance) + # The pause screen doesn't hold the server here: it follows on its next tick. + host.wait(20) + guest.wait(20) + seen[distance] = (host('status').get('render_distance'), guest('status').get('render_distance')) + finally: + host.raw('render-distance', 12) + # A client streams out to min(its render distance, the server's view distance + 1). + assert seen[48][0] == 48, f'the host at 48 streams {seen[48][0]} chunks out (all: {seen})' + assert seen[6][0] == 6, f'the host at 6 streams {seen[6][0]} chunks out (all: {seen})' + assert seen[6][1] == 7, f'the guest streams {seen[6][1]} with the server at 6 (all: {seen})' + return seen + + def check_portals(host, guest, out): if not SERVER_THREAD: return 'skipped (needs --server-thread)' @@ -470,14 +499,14 @@ def check_hazards(host, guest, out): guest.wait(10) x, y, z = pos_of(guest) guest.raw('look-at', f'{x + 60:.2f}', f'{y + 1.6:.2f}', f'{z:.2f}') - food = host.raw('lan', 'status')['guests'][0]['food'] + food = lan_guest(host)['food'] for k in ('w', 'ctrl', 'space'): guest.raw('key', k, 'down') guest.wait(160) for k in ('space', 'ctrl', 'w'): guest.raw('key', k, 'up') guest.wait(10) - fed = host.raw('lan', 'status')['guests'][0]['food'] + fed = lan_guest(host)['food'] hunger = {'before': food, 'after': fed} hurt = {} hx, hy, hz = (int(v // 1) for v in pos_of(host)) @@ -865,7 +894,7 @@ def changed_pixels(a, b): def sneaking_on_host(host, want, ticks=40): """Whether the host sees the guest crouching, once it matches `want` or after `ticks`.""" for _ in range(ticks // 5): - sneaking = host.raw('lan', 'status')['guests'][0]['sneaking'] + sneaking = lan_guest(host)['sneaking'] if sneaking == want: return sneaking host.wait(5) @@ -988,7 +1017,7 @@ def check_sleep(host, guest, out): guest.raw('interact', *guest_bed) guest.wait(10) asleep = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'), - 'server': host.raw('lan', 'status')['guests'][0].get('sleeping')} + 'server': lan_guest(host).get('sleeping')} guest.shot(out, 'sleep-guest') # Alone in bed: still night 120 ticks later (everyone must sleep). guest.wait(120) @@ -1178,7 +1207,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'commands': check_commands, 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, - 'effects': check_effects, 'portals': check_portals, 'clicks': check_clicks, + 'effects': check_effects, 'portals': check_portals, 'distance': check_distance, 'clicks': check_clicks, 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles}