From 4e45a3bddfd2f0a3090d729ac95a02ab9d11a43e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:36:09 +0200 Subject: [PATCH 01/16] Credits and end poem (WinScreen) Leaving the End through the exit portal for the first time now rolls the end poem, the credits and the post-credits text (WinScreen), as does a server's WIN_GAME event; Options -> Credits & Attribution -> Credits rolls the credits alone. The texts come from the resource root (texts/end.txt, credits.json, postcredits.txt), so packs can replace them. - win_screen.rs: vanilla's line building (PLAYERNAME, the obfuscated names from LegacyRandom(8124371), wrapping at 256), scroll speeds and keys (Space, Ctrl, Up, Escape), the last line pinned mid-screen, the logo, the vignette and the backgrounds. - HUD: Blend::Vignette (RenderPipelines.VIGNETTE) and Blend::EndPortal (the End portal effect as a GUI fill, the poem's background). - Obfuscated text draws a random glyph of the same width each frame. - seenCredits is read and saved; the player stays out of the world while the poem rolls and arrives in the Overworld after it. - horizon-ctl `credits [poem] [SCROLL]` and `options credits`. Fixes #338 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/font.rs | 71 +++ crates/horizon-client/src/game.rs | 27 +- crates/horizon-client/src/game/agent.rs | 1 + crates/horizon-client/src/game/control.rs | 25 + crates/horizon-client/src/game/end.rs | 5 +- crates/horizon-client/src/game/music.rs | 8 +- crates/horizon-client/src/game/options.rs | 1 + crates/horizon-client/src/game/remote.rs | 4 + .../horizon-client/src/game/startup_menu.rs | 40 ++ crates/horizon-client/src/game/win.rs | 150 ++++++ crates/horizon-client/src/hud.rs | 108 ++++- crates/horizon-client/src/hud.wgsl | 51 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/options_ui.rs | 52 +- crates/horizon-client/src/save.rs | 4 + crates/horizon-client/src/win_screen.rs | 452 ++++++++++++++++++ 16 files changed, 982 insertions(+), 18 deletions(-) create mode 100644 crates/horizon-client/src/game/win.rs create mode 100644 crates/horizon-client/src/win_screen.rs diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index aeedb92bd..3039fdb40 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -52,6 +52,10 @@ struct Cache { cursor: (u32, u32), pending: Vec, hex: Option>, + /// `FontSet.glyphsByWidth` for obfuscated text (built on first use). + by_width: Option>>, + /// `Font.random`: picks obfuscated glyphs. + random: horizon_core::random::LegacyRandom, } pub struct Font { bitmap: HashMap, @@ -285,6 +289,12 @@ impl Font { cursor: (0, 0), pending: Vec::new(), hex: None, + by_width: None, + random: horizon_core::random::LegacyRandom::new( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as i64), + ), }), uniform: false, japanese: false, @@ -353,6 +363,7 @@ impl Font { cache.glyphs.clear(); cache.cursor = (0, 0); cache.hex = None; + cache.by_width = None; } /// The glyph for a character (FontSet.getGlyph). pub fn glyph(&self, c: char) -> Glyph { @@ -427,6 +438,66 @@ impl Font { offset: 0.5, }) } + /// `FontSet.getRandomGlyph`: what an obfuscated character draws, a random + /// glyph as wide as `advance` (rounded up), else the missing glyph. + /// + /// Vanilla picks among every glyph of the font set, Unifont's included. + /// Those are rasterized into a fixed atlas region on demand, which a + /// line of obfuscated text would fill in seconds, so the candidates are + /// the glyphs already in the atlas (the bitmap sheets and spaces), or with + /// "Force Unicode Font" the Unifont glyphs below U+0250. + pub fn random_glyph(&self, advance: f32) -> Glyph { + use horizon_core::random::RandomSource; + let width = advance.ceil() as u32; + let pick = { + let mut cache = self.cache.borrow_mut(); + if cache.by_width.is_none() { + let by_width = self.glyphs_by_width(&mut cache); + cache.by_width = Some(by_width); + } + let Cache { + by_width, random, .. + } = &mut *cache; + by_width + .as_ref() + .and_then(|m| m.get(&width)) + .and_then(|chars| { + let i = random.next_int_bound(chars.len() as i32).ok()?; + chars.get(i as usize).copied() + }) + }; + pick.map_or(self.missing, |c| self.glyph(c)) + } + fn glyphs_by_width(&self, cache: &mut Cache) -> HashMap> { + let mut chars: Vec<(char, f32)> = self.space.iter().map(|(c, a)| (*c, *a)).collect(); + if self.uniform { + if cache.hex.is_none() { + cache.hex = Some(self.load_hex()); + } + for code in 0..0x250u32 { + let hex = cache.hex.iter().flatten().find_map(|p| p.glyphs.get(&code)); + if let (Some(c), Some(h)) = (char::from_u32(code), hex) + && !self.space.contains_key(&c) + { + let width = h.right.saturating_sub(h.left) + 1; + chars.push((c, (width / 2 + 1) as f32)); + } + } + } else { + chars.extend( + self.bitmap + .iter() + .filter(|(c, _)| !self.space.contains_key(c)) + .map(|(c, g)| (*c, g.advance)), + ); + } + chars.sort_by_key(|(c, _)| *c); + let mut out: HashMap> = HashMap::new(); + for (c, advance) in chars { + out.entry(advance.ceil() as u32).or_default().push(c); + } + out + } /// Atlas pixels rasterized since the last call. pub fn take_patches(&self) -> Vec { std::mem::take(&mut self.cache.borrow_mut().pending) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index bad635c5c..02d31b494 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -155,6 +155,7 @@ mod ui_control; mod vault; mod villagers; mod wandering_trader; +mod win; mod wind; mod wither; mod world_loading; @@ -453,6 +454,8 @@ enum Screen { WorldOptions, /// CommandBlockEditScreen (game/command_blocks.rs). CommandBlock, + /// WinScreen: the end poem and the credits (game/win.rs). + Win, } struct Mining { pos: [i32; 3], @@ -1341,6 +1344,8 @@ struct Game<'a> { respawn_travel: Option, /// The next enter_dimension call comes from an End portal. end_portal_travel: bool, + /// The open WinScreen (game/win.rs). + win: Option, end: end::EndState, block_ticks: Ticks, tick_chunks: horizon_client::tick_chunk_membership::TickChunkMembership, @@ -3748,6 +3753,9 @@ impl Game<'_> { return Ok(()); } if let Some((_, target)) = &self.travelling { + if self.win_screen_holds_arrival() { + return Ok(()); + } let (cx, cz) = ( (target.x.floor() as i32) >> 4, (target.z.floor() as i32) >> 4, @@ -4429,7 +4437,8 @@ impl Game<'_> { | Screen::Advancements | Screen::WorldOptions | Screen::CommandBlock - ) || self.book.is_some()) + ) || self.book.is_some() + || self.win_screen_pauses()) } /// `MouseHandler.grabMouse` / `releaseMouse`. Both put the pointer at /// the window's centre, so a screen opened from gameplay (inventory, @@ -4637,6 +4646,10 @@ impl Game<'_> { fn hud_layers(&mut self, size: [u32; 2]) -> HudBatch { let mut batch = HudBatch::new(size); let (w, h) = (batch.width, batch.height); + if self.screen == Screen::Win { + self.draw_win_screen(&mut batch); + return batch; + } if self.screen == Screen::Options { self.draw_options(&mut batch); return batch; @@ -4846,7 +4859,7 @@ impl Game<'_> { self.draw_creative(&mut batch); } Screen::Chat => self.draw_chat_screen(&mut batch), - Screen::Playing | Screen::Options => {} + Screen::Playing | Screen::Options | Screen::Win => {} } self.draw_toasts(&mut batch); self.remote_hud(&mut batch); @@ -9846,7 +9859,7 @@ impl Game<'_> { let blurred = !horizon_client::ui_theme::horizon() && (loading || self.title.as_ref().is_some_and(|t| { - self.screen == Screen::Options + matches!(self.screen, Screen::Options | Screen::Win) || !matches!(t.mode, horizon_client::title::Mode::Main) })); let radius = self.settings.menu_blur as f32; @@ -9932,6 +9945,7 @@ impl Game<'_> { Screen::WorldOptions => self.world_options_escape(), Screen::CommandBlock => self.close_command_block(), Screen::Chat => self.close_chat(), + Screen::Win => self.close_win_screen()?, }, KeyCode::Digit1 | KeyCode::Digit2 @@ -10539,6 +10553,7 @@ impl ApplicationHandler for Game<'_> { let d = scaled(raw_y) as f32; if let Some(title) = &mut self.title && !horizon_client::ui_theme::horizon() + && self.screen != Screen::Win { let size = self .window @@ -10597,6 +10612,7 @@ impl ApplicationHandler for Game<'_> { self.advancements_scroll(scaled(raw_x) as f32, d); } } + WindowEvent::MouseInput { .. } if self.screen == Screen::Win => {} WindowEvent::MouseInput { state, button, .. } if self.screen == Screen::Options => { if self.options_waiting_for_key() && state == ElementState::Pressed { self.options_bind_mouse(button)?; @@ -10858,6 +10874,9 @@ impl ApplicationHandler for Game<'_> { { self.world_options_key(&event) } + WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Win => { + self.win_key(&event)? + } WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::CommandBlock => { self.command_block_key(&event) } @@ -10994,6 +11013,7 @@ impl ApplicationHandler for Game<'_> { } else if self.title.is_some() { self.tick_backdrop(); } + self.tick_win_screen()?; self.tick_music(); self.tick_sound_engine(); self.clock.record(started.elapsed()); @@ -11420,6 +11440,7 @@ impl<'a> Game<'a> { respawn_config: None, respawn_travel: None, end_portal_travel: false, + win: None, end: Default::default(), block_ticks: Ticks::new(0), tick_chunks: Default::default(), diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 9a5cd6a58..1fa422f92 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -404,6 +404,7 @@ impl Game<'_> { Screen::Advancements => "advancements", Screen::WorldOptions => "world-options", Screen::CommandBlock => "command-block", + Screen::Win => "win", } } pub(super) fn inventory_counts(&self) -> BTreeMap { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 6cbbf5007..6a79419a1 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -42,6 +42,7 @@ const HELP: &[&str] = &[ "chat MESSAGE send chat or a /command to the server", "disconnect leave the server for the server list", "respawn respawn after death on a server", + "credits [poem] [SCROLL] roll the credits (with the end poem), or hold them SCROLL pixels in", "quit save and exit", ]; @@ -555,6 +556,7 @@ impl Game<'_> { "graphics" => Page::Graphics, "graphics-advanced" => Page::GraphicsAdvanced, "extras" => Page::Extras, + "credits" => Page::Credits, other => return Err(format!("unknown options page {other}").into()), }; if self.screen == Screen::Playing && self.title.is_none() { @@ -630,6 +632,25 @@ impl Game<'_> { self.connect_server(arg(1)?, &name)?; ok() } + "credits" => { + let poem = words.get(1) == Some(&"poem"); + let hold = words + .get(1 + usize::from(poem)) + .map(|s| s.parse::()) + .transpose()?; + if self.screen != Screen::Win { + let finish = if self.screen == Screen::Options { + super::win::Finish::Options + } else { + super::win::Finish::Closed + }; + self.open_win_screen(poem, finish); + } + if let Some(scroll) = hold { + self.hold_win_screen(scroll); + } + ok() + } "respawn" => { if self.remote.is_none() || self.screen != Screen::Dead { return Err("respawn needs the death screen on a server".into()); @@ -712,6 +733,9 @@ impl Game<'_> { } fn screen_name(&self) -> &'static str { + if self.screen == Screen::Win { + return "win"; + } if self.title.is_some() { return "title"; } @@ -728,6 +752,7 @@ impl Game<'_> { Screen::Advancements => "advancements", Screen::WorldOptions => "world-options", Screen::CommandBlock => "command-block", + Screen::Win => "win", } } diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index a7813c767..f5ddf537b 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -377,7 +377,10 @@ impl Game<'_> { f64::from(p.dimensions.width), f64::from(p.dimensions.height), ); - if portal { + if portal && self.dim == Dim::End && !self.level.seen_credits { + // EndPortalBlock.entityInside: the first exit shows the credits. + self.show_end_credits()?; + } else if portal { if self.portals.player.cooldown == 0 { let target = if self.dim == Dim::End { Dim::Overworld diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 9198a78a1..6f8b5e7ae 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -12,7 +12,7 @@ impl Game<'_> { pub(super) fn tick_music(&mut self) { let (music, volume) = self.situational_music(); // LevelLoadingScreen: no new track before the player is in the world. - let loading = self.title.is_none() && self.player.is_none(); + let loading = self.title.is_none() && self.player.is_none() && self.win.is_none(); self.music .tick(music.as_ref(), volume, loading, &mut self.audio); } @@ -59,7 +59,11 @@ impl Game<'_> { None => (empty, 1.0), }; let situation = Situation { - screen_music: None, + // WinScreen.getBackgroundMusic. + screen_music: self + .win + .is_some() + .then(horizon_client::music::Music::credits), in_world: eye.is_some(), in_end: self.dim == super::Dim::End, boss_music: self.boss_music(), diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index 61036d18c..ff9e4f28f 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -235,6 +235,7 @@ impl Game<'_> { let _ = std::fs::create_dir_all(&dir); super::packs::open_folder(&dir); } + Event::Credits => self.open_win_screen(false, super::win::Finish::Options), } } Ok(()) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 09e03e719..fcc7bee08 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1840,6 +1840,10 @@ impl Game<'_> { ); } } + // WIN_GAME: the poem and credits, then PERFORM_RESPAWN. + 4 if self.screen != Screen::Win => { + self.open_win_screen(true, super::win::Finish::RemoteRespawn); + } 1 => { self.world.weather.raining = true; self.world.weather.rain_level = (0.0, 0.0); diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index ffbbe7193..4253cbe65 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -12,6 +12,8 @@ pub(super) struct StartupMenu { title: Option, options: OptionsUi, options_open: bool, + /// The credits from Credits & Attribution, and their last frame. + win: Option<(horizon_client::win_screen::WinScreen, Instant)>, root: PathBuf, cursor: (f32, f32), pointer: (f64, f64), @@ -378,6 +380,21 @@ impl Loading { let _ = std::fs::create_dir_all(&dir); packs::open_folder(&dir); } + Event::Credits => { + if let Some(gui) = &self.gui { + let name = self.options.as_ref().map_or_else( + || horizon_client::offline_name::generate(0), + Options::player_name, + ); + let screen = horizon_client::win_screen::WinScreen::new( + false, + &self.menu.root, + &name, + &gui.atlas.font, + ); + self.menu.win = Some((screen, Instant::now())); + } + } Event::ButtonClick => {} } } @@ -473,6 +490,20 @@ impl Loading { } } _ if self.gui.is_none() || self.menu.pending.is_some() => {} + WindowEvent::KeyboardInput { event, .. } if self.menu.win.is_some() => { + if let PhysicalKey::Code(code) = event.physical_key { + let pressed = event.state == ElementState::Pressed; + if code == KeyCode::Escape && pressed { + self.menu.win = None; + } else if let Some(key) = horizon_client::win_screen::Key::from_code(code) + && let Some((win, _)) = &mut self.menu.win + { + win.key(key, pressed); + } + } + } + WindowEvent::MouseInput { .. } | WindowEvent::MouseWheel { .. } + if self.menu.win.is_some() => {} WindowEvent::CursorMoved { position, .. } => { self.menu.pointer = (position.x, position.y); self.update_menu_cursor(); @@ -610,6 +641,15 @@ impl Loading { self.progress.line(), self.progress.fraction(), ); + } else if let Some((win, frame)) = &mut self.menu.win { + let now = Instant::now(); + // 20 ticks a second: the startup menu runs no tick rate. + let delta_ticks = now.duration_since(*frame).as_secs_f32() * 20.0; + *frame = now; + win.draw(batch, &gui.atlas, delta_ticks, Default::default()); + if win.finished(batch.height) { + self.menu.win = None; + } } else if self.menu.options_open { self.menu .options diff --git a/crates/horizon-client/src/game/win.rs b/crates/horizon-client/src/game/win.rs new file mode 100644 index 000000000..a9cf6379a --- /dev/null +++ b/crates/horizon-client/src/game/win.rs @@ -0,0 +1,150 @@ +//! `WinScreen` in the game: the poem and credits after leaving the End for +//! the first time (`EndPortalBlock.entityInside` -> `ServerPlayer.showEndCredits`, +//! or a server's `WIN_GAME` event), and the credits from Credits & +//! Attribution. +use super::{Game, Screen}; +use horizon_client::{ + Result, + hud::{EndPortalFill, HudBatch}, + win_screen::{Key, WinScreen}, +}; +use std::time::Instant; +use winit::{ + event::{ElementState, KeyEvent}, + keyboard::{KeyCode, PhysicalKey}, +}; + +/// What closing the screen does (`WinScreen.onFinished`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Finish { + /// `PERFORM_RESPAWN` in single player: the player, out of the End since + /// the credits began, arrives in the Overworld. + Respawn, + /// `PERFORM_RESPAWN` sent to the server. + RemoteRespawn, + /// Back to Credits & Attribution. + Options, + /// Back to the game (`horizon-ctl credits`). + Closed, +} +pub(super) struct Win { + screen: WinScreen, + finish: Finish, + /// The last drawn frame, for the scroll's game-time delta. + frame: Instant, +} +impl Game<'_> { + pub(super) fn open_win_screen(&mut self, poem: bool, finish: Finish) { + let screen = WinScreen::new( + poem, + &self.options.resources, + &self.options.player_name(), + &self.gui.atlas.font, + ); + self.win = Some(Win { + screen, + finish, + frame: Instant::now(), + }); + self.keys.clear(); + self.screen = Screen::Win; + self.capture(false); + } + /// `ServerPlayer.showEndCredits`: the player leaves the End now (no + /// longer in any level until the credits end) and has seen the credits. + pub(super) fn show_end_credits(&mut self) -> Result<()> { + self.level.seen_credits = true; + self.open_win_screen(true, Finish::Respawn); + self.end_portal_travel = true; + let result = self.enter_dimension(super::Dim::Overworld); + self.end_portal_travel = false; + result + } + /// Stop the scroll `scroll` pixels in (`horizon-ctl credits ... SCROLL`). + pub(super) fn hold_win_screen(&mut self, scroll: f32) { + if let Some(win) = self.win.as_mut() { + win.screen.hold(scroll); + } + } + /// `WinScreen.isPauseScreen`: only the credits without the poem pause. + pub(super) fn win_screen_pauses(&self) -> bool { + self.win.as_ref().is_some_and(|w| !w.screen.poem) + } + /// The player waits out of the world while the poem rolls. + pub(super) fn win_screen_holds_arrival(&self) -> bool { + self.win + .as_ref() + .is_some_and(|w| w.finish == Finish::Respawn) + } + pub(super) fn draw_win_screen(&mut self, batch: &mut HudBatch) { + let Some(win) = self.win.as_mut() else { + return; + }; + let now = Instant::now(); + // DeltaTracker.getGameTimeDeltaTicks: the frame's length in ticks. + let delta_ticks = + now.duration_since(win.frame).as_secs_f32() / self.clock.tick_duration().as_secs_f32(); + win.frame = now; + let sprite = |n: &str| { + self.gui + .atlas + .sprites + .get(n) + .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]) + }; + let fill = EndPortalFill { + sprites: [ + sprite("environment/end_sky"), + sprite("entity/end_portal/end_portal"), + ], + game_time: (self.world.game_time % 24000) as f32 / 24000.0, + }; + win.screen.draw(batch, &self.gui.atlas, delta_ticks, fill); + } + /// `WinScreen.keyPressed` / `keyReleased`; Escape closes it (`onClose`). + pub(super) fn win_key(&mut self, event: &KeyEvent) -> Result<()> { + let PhysicalKey::Code(code) = event.physical_key else { + return Ok(()); + }; + let pressed = event.state == ElementState::Pressed; + if code == KeyCode::Escape && pressed { + return self.close_win_screen(); + } + let Some(key) = Key::from_code(code) else { + return Ok(()); + }; + if let Some(win) = self.win.as_mut() { + win.screen.key(key, pressed); + } + Ok(()) + } + /// `WinScreen.tick`: done once everything has rolled past the top. + pub(super) fn tick_win_screen(&mut self) -> Result<()> { + let height = self.gui_size().1; + if self.win.as_ref().is_some_and(|w| w.screen.finished(height)) { + self.close_win_screen()?; + } + Ok(()) + } + /// `WinScreen.respawn` (`onFinished`) and `removed`: the credits music stops. + pub(super) fn close_win_screen(&mut self) -> Result<()> { + let Some(win) = self.win.take() else { + return Ok(()); + }; + let credits = horizon_client::music::Music::credits(); + self.music + .stop_playing_music(&credits, None, &mut self.audio); + match win.finish { + Finish::Options => self.screen = Screen::Options, + Finish::Closed if self.title.is_some() => self.screen = Screen::Playing, + Finish::Respawn | Finish::RemoteRespawn | Finish::Closed => { + if win.finish == Finish::RemoteRespawn { + self.remote_respawn(); + } + self.screen = Screen::Playing; + self.capture(true); + } + } + Ok(()) + } +} diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 0cc99b07b..29faf5a2a 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -363,6 +363,8 @@ pub struct HudBatch { pub patches: Vec<crate::font::Patch>, /// Vertex ranges with another blend or depth/scissor state, in order. pub blends: Vec<(std::ops::Range<u32>, Blend)>, + /// The textures and time of the `Blend::EndPortal` runs. + pub end_portal: EndPortalFill, } /// How a run of HUD vertices blends and tests depth. #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -375,6 +377,19 @@ pub enum Blend { Additive, /// Alpha blending with an isolated depth buffer and a pixel scissor. Depth([u32; 4]), + /// `RenderPipelines.VIGNETTE`: the destination darkened by the texture + /// (`ZERO, ONE_MINUS_SRC_COLOR`). + Vignette, + /// `RenderPipelines.END_PORTAL` as a GUI fill: the End portal's layers + /// projected from the screen (`HudBatch::end_portal` sets the textures). + EndPortal, +} +/// What a `Blend::EndPortal` fill samples: the atlas rects (u0, v0, width, +/// height) of `end_sky.png` and `end_portal.png`, and the `GameTime` uniform. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct EndPortalFill { + pub sprites: [[f32; 4]; 2], + pub game_time: f32, } pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 { u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r) @@ -398,6 +413,7 @@ impl HudBatch { height: (window[1] as f32 / scale as f32).ceil(), patches: Vec::new(), blends: Vec::new(), + end_portal: EndPortalFill::default(), } } /// Draw the vertices added since `start` with the inverting blend. @@ -695,7 +711,12 @@ impl HudBatch { let mut glyphs = Vec::new(); let mut cursor = x; for (i, (ch, style)) in text.chars().enumerate() { - let g = font.glyph(ch); + let mut g = font.glyph(ch); + // Font.StringRenderOutput.accept: obfuscated characters draw a + // random glyph of the same width each frame. + if style.obfuscated == Some(true) && ch != ' ' { + g = font.random_glyph(g.advance); + } let c = style.color.map_or(color, |rgb| { rgba((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8, alpha) }); @@ -789,6 +810,20 @@ impl HudBatch { #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] struct HudUniform { size: [f32; 4], + /// `EndPortalFill`: the two sprites, then the game time in x. + end_portal: [[f32; 4]; 3], +} +impl HudUniform { + fn new(size: [f32; 4], fill: EndPortalFill) -> Self { + Self { + size, + end_portal: [ + fill.sprites[0], + fill.sprites[1], + [fill.game_time, 0.0, 0.0, 0.0], + ], + } + } } pub struct HudRenderer { pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation, usize)>, @@ -799,6 +834,8 @@ pub struct HudRenderer { invert_pipeline: wgpu::RenderPipeline, additive_pipeline: wgpu::RenderPipeline, depth_pipeline: wgpu::RenderPipeline, + vignette_pipeline: wgpu::RenderPipeline, + end_portal_pipeline: wgpu::RenderPipeline, group: wgpu::BindGroup, uniform: wgpu::Buffer, buffer: wgpu::Buffer, @@ -821,7 +858,7 @@ impl HudRenderer { }); let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("HUD size"), - contents: bytemuck::bytes_of(&HudUniform { size: [1.0; 4] }), + contents: bytemuck::bytes_of(&HudUniform::new([1.0; 4], EndPortalFill::default())), usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, }); let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { @@ -829,7 +866,7 @@ impl HudRenderer { entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, - visibility: wgpu::ShaderStages::VERTEX, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, @@ -957,6 +994,31 @@ impl HudRenderer { "fs_main", false, ); + // RenderPipelines.VIGNETTE: ZERO, ONE_MINUS_SRC_COLOR, ZERO, ONE. + let vignette_pipeline = create( + "HUD vignette", + wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::OneMinusSrc, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + }, + "fs_main", + false, + ); + // RenderPipelines.END_PORTAL: opaque. + let end_portal_pipeline = create( + "HUD end portal", + wgpu::BlendState::REPLACE, + "fs_end_portal", + false, + ); let capacity = 1 << 16; let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("HUD vertices"), @@ -971,6 +1033,8 @@ impl HudRenderer { invert_pipeline, additive_pipeline, depth_pipeline, + vignette_pipeline, + end_portal_pipeline, group, uniform, buffer, @@ -1064,9 +1128,10 @@ impl HudRenderer { encoder, &self.uniform, 0, - bytemuck::bytes_of(&HudUniform { - size: [size[0] as f32, size[1] as f32, batch.scale, 0.0], - }), + bytemuck::bytes_of(&HudUniform::new( + [size[0] as f32, size[1] as f32, batch.scale, 0.0], + batch.end_portal, + )), ); } /// Draw the batch `prepare` staged. @@ -1135,6 +1200,8 @@ impl HudRenderer { Blend::Invert => &self.invert_pipeline, Blend::Additive => &self.additive_pipeline, Blend::Depth(_) => &self.depth_pipeline, + Blend::Vignette => &self.vignette_pipeline, + Blend::EndPortal => &self.end_portal_pipeline, }); pass.draw(range.clone(), 0..1); } @@ -1147,10 +1214,10 @@ impl HudRenderer { mod tests { use super::*; - #[test] - fn the_fonts_only_atlas_measures_text_like_the_full_one() { - // A synthetic default font: two 8x8 glyphs, 3 and 5 pixels wide. - let root = std::env::temp_dir().join(format!("horizon-fonts-atlas-{}", std::process::id())); + /// A synthetic default font: two 8x8 glyphs, 3 and 5 pixels wide. + fn two_glyph_font(name: &str) -> std::path::PathBuf { + let root = + std::env::temp_dir().join(format!("horizon-fonts-{name}-{}", std::process::id())); let font = root.join("assets/minecraft/font"); let textures = root.join("assets/minecraft/textures/font"); fs::create_dir_all(&font).unwrap(); @@ -1175,6 +1242,11 @@ mod tests { .unwrap() .write_image_data(&pixels) .unwrap(); + root + } + #[test] + fn the_fonts_only_atlas_measures_text_like_the_full_one() { + let root = two_glyph_font("atlas"); let full = HudAtlas::build(&root).unwrap(); let fonts = HudAtlas::fonts(&root).unwrap(); let _ = fs::remove_dir_all(&root); @@ -1183,6 +1255,21 @@ mod tests { assert!(width > 0.0); assert_eq!(fonts.font.width("abba"), width); } + #[test] + fn obfuscated_glyphs_keep_the_width() { + let root = two_glyph_font("obfuscated"); + let fonts = HudAtlas::fonts(&root).unwrap(); + let _ = fs::remove_dir_all(&root); + let (a, b) = (fonts.font.glyph('a').advance, fonts.font.glyph('b').advance); + assert_ne!(a, b); + for _ in 0..20 { + assert_eq!(fonts.font.random_glyph(a).advance, a); + assert_eq!(fonts.font.random_glyph(b).advance, b); + } + // No glyph that wide: FontSet's missing glyph. + let missing = fonts.font.random_glyph(30.0); + assert!(missing.rect.is_none() && missing.right == 5.0); + } #[test] fn effect_icons_are_painted_from_the_mob_effect_directory() { @@ -1340,6 +1427,7 @@ mod tests { height: height as f32, patches: Vec::new(), blends: Vec::new(), + end_portal: EndPortalFill::default(), }; for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] { assert_eq!( diff --git a/crates/horizon-client/src/hud.wgsl b/crates/horizon-client/src/hud.wgsl index 17d50d51a..ebb6dc2cb 100644 --- a/crates/horizon-client/src/hud.wgsl +++ b/crates/horizon-client/src/hud.wgsl @@ -1,4 +1,9 @@ -struct Hud { size: vec4<f32> } +struct Hud { + size: vec4<f32>, + // Blend::EndPortal: atlas rects (u0, v0, width, height) of end_sky.png and + // end_portal.png, then vanilla's GameTime in x. + end_portal: array<vec4<f32>, 3>, +} @group(0) @binding(0) var<uniform> hud: Hud; @group(0) @binding(1) var atlas: texture_2d<f32>; @group(0) @binding(2) var atlas_sampler: sampler; @@ -6,6 +11,8 @@ struct Out { @builtin(position) clip: vec4<f32>, @location(0) uv: vec2<f32>, @location(1) color: vec4<f32>, + // projection_from_position(gl_Position): the End portal's texProj0. + @location(2) proj: vec4<f32>, } @vertex fn vs_main(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>, @location(2) color: vec4<f32>, @location(3) depth: f32) -> Out { let pixels = pos * hud.size.z; @@ -13,6 +20,7 @@ struct Out { out.clip = vec4(pixels.x / hud.size.x * 2.0 - 1.0, 1.0 - pixels.y / hud.size.y * 2.0, depth, 1.0); out.uv = uv; out.color = color; + out.proj = vec4(out.clip.xy * 0.5 + 0.5, out.clip.zw); return out; } @fragment fn fs_main(in: Out) -> @location(0) vec4<f32> { @@ -31,3 +39,44 @@ struct Out { if c.a == 0.0 { discard; } return c; } +// rendertype_end_portal.fsh (entity.wgsl has the same for portal blocks). +const PORTAL_COLORS = array<vec3<f32>, 16>( + vec3(0.022087, 0.098399, 0.110818), + vec3(0.011892, 0.095924, 0.089485), + vec3(0.027636, 0.101689, 0.100326), + vec3(0.046564, 0.109883, 0.114838), + vec3(0.064901, 0.117696, 0.097189), + vec3(0.063761, 0.086895, 0.123646), + vec3(0.084817, 0.111994, 0.166380), + vec3(0.097489, 0.154120, 0.091064), + vec3(0.106152, 0.131144, 0.195191), + vec3(0.097721, 0.110188, 0.187229), + vec3(0.133516, 0.138278, 0.148582), + vec3(0.070006, 0.243332, 0.235792), + vec3(0.196766, 0.142899, 0.214696), + vec3(0.047281, 0.315338, 0.321970), + vec3(0.204675, 0.390010, 0.302066), + vec3(0.080955, 0.314821, 0.661491), +); +fn portal_sample(rect: vec4<f32>, p: vec4<f32>) -> vec3<f32> { + let st = fract(p.xy / p.w); + return textureSampleLevel(atlas, atlas_sampler, rect.xy + st * rect.zw, 0.0).rgb; +} +fn portal_layer(p: vec4<f32>, layer: f32) -> vec4<f32> { + let a = radians((layer * layer * 4321.0 + layer * 9.0) * 2.0); + let c = cos(a); + let s = sin(a); + let k = (4.5 - layer / 4.0) * 2.0; + var v = vec4(k * (c * p.x - s * p.y), k * (s * p.x + c * p.y), p.z, p.w); + v = vec4(v.x + 17.0 / layer * v.w, v.y + (2.0 + layer / 1.5) * (hud.end_portal[2].x * 1.5) * v.w, v.z, v.w); + return vec4(0.5 * v.x + 0.25 * v.w, 0.5 * v.y + 0.25 * v.w, v.z, v.w); +} +// RenderPipelines.END_PORTAL (WinScreen's poem background): end_sky and 15 +// layers of end_portal.png. +@fragment fn fs_end_portal(in: Out) -> @location(0) vec4<f32> { + var c = portal_sample(hud.end_portal[0], in.proj) * PORTAL_COLORS[0]; + for (var i = 0; i < 15; i++) { + c += portal_sample(hud.end_portal[1], portal_layer(in.proj, f32(i + 1))) * PORTAL_COLORS[i]; + } + return vec4(c, 1.0); +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 4cf0c5c48..25be4a0c4 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -186,6 +186,7 @@ pub mod vanillagen; pub mod vault; pub mod weather; pub mod widgets; +pub mod win_screen; pub mod window; pub mod world; pub mod world_spawn; diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 7d86263df..2290e9632 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -871,6 +871,8 @@ pub enum Page { Controller, PadBinds, Extras, + /// CreditsAndAttributionScreen. + Credits, } #[derive(Clone, Debug, PartialEq)] enum Act { @@ -893,6 +895,8 @@ enum Act { /// Pick shader pack `i` of `OptionsUi::shader_packs` (again: off). ToggleShaderPack(usize), OpenShaderPackFolder, + /// Credits & Attribution's Credits button (WinScreen without the poem). + Credits, } enum WKind { Button { @@ -942,6 +946,8 @@ pub enum Event { OpenModFolder, /// Create `shaderpacks/` if needed and open it. OpenShaderPackFolder, + /// Roll the credits (`CreditsAndAttributionScreen.openCreditsScreen`). + Credits, } /// `SliderableValueSet.applyValueImmediately`: these apply 600 ms after /// the last change (`OptionInstanceSliderButton.delayedApplyAt`). @@ -1200,6 +1206,7 @@ impl OptionsUi { Page::Controller => "Controller Settings", Page::PadBinds => "Controller Binds", Page::Extras => "Horizon Extras", + Page::Credits => "credits_and_attribution.screen.title", } } fn scrollbar_x(&self, width: f32) -> f32 { @@ -1580,8 +1587,10 @@ impl OptionsUi { ("options.accessibility", Some(Page::Accessibility)), ("Mods...", Some(Page::Mods)), ("Horizon Extras...", Some(Page::Extras)), + ("options.credits_and_attribution", Some(Page::Credits)), ]; - let gy = (61.0 + 30.0f32).min(h - 33.0 - 120.0); + let rows = entries.len().div_ceil(2) as f32; + let gy = (61.0 + 30.0f32).min(h - 33.0 - rows * 24.0); for (i, (key, page)) in entries.iter().enumerate() { let x = cx - 158.0 + 4.0 + (i % 2) as f32 * 158.0; let y = gy + (i / 2) as f32 * 24.0; @@ -1592,6 +1601,46 @@ impl OptionsUi { top = 0.0; bottom = 0.0; } + Page::Credits => { + // CreditsAndAttributionScreen: the title header, three 210-wide + // buttons 8 apart (HeaderAndFooterLayout: 30 below the header + // unless the footer is closer), Done. + out.push(Widget { + x: 0.0, + y: 12.0, + w, + h: 9.0, + kind: WKind::Text { + text: tr(Self::title(page)), + color: u32::MAX, + centered: true, + }, + list: false, + }); + let y = (33.0 + 30.0f32).min(h - 33.0 - 76.0); + let x = cx - 105.0; + out.push(button( + x, + y, + 210.0, + tr("credits_and_attribution.button.credits"), + Act::Credits, + )); + // ConfirmLinkScreen to minecraft.net: Horizon opens no links. + for (i, key) in [ + "credits_and_attribution.button.attribution", + "credits_and_attribution.button.licenses", + ] + .into_iter() + .enumerate() + { + let y = y + 28.0 * (i + 1) as f32; + out.push(inactive(button(x, y, 210.0, tr(key), Act::None))); + } + out.push(done(h - 27.0)); + top = 0.0; + bottom = 0.0; + } Page::KeyBinds => { top = 38.0; out.push(Widget { @@ -2487,6 +2536,7 @@ impl OptionsUi { events.push(Event::Changed); } Act::OpenShaderPackFolder => events.push(Event::OpenShaderPackFolder), + Act::Credits => events.push(Event::Credits), Act::None => {} } } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 2e1eb8455..0428670f4 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2209,6 +2209,8 @@ pub struct Level { pub inventory_components: HashMap<u8, Box<crate::item_data::StackData>>, /// Player.XpSeed: the enchanting table seed. pub xp_seed: i32, + /// ServerPlayer.seenCredits: the end poem has been shown. + pub seen_credits: bool, /// Player.active_effects: (id, duration, amplifier, ambient, show_icon). pub active_effects: Vec<(String, i32, i32, bool, bool)>, /// Player.EnderItems: the ender chest inventory (27 slots). @@ -2400,6 +2402,7 @@ impl Level { self.selected_slot = n("SelectedItemSlot").unwrap_or(0) as i32; self.fall_distance = f("fall_distance").unwrap_or(0.0); self.on_ground = n("OnGround").unwrap_or(0) != 0; + self.seen_credits = n("seenCredits").unwrap_or(0) != 0; if let Some(mode) = n("playerGameType") { self.creative = mode == 1; self.game_mode = mode as i32; @@ -2621,6 +2624,7 @@ impl Level { if let Some(pos) = self.position { entries.push(("Pos", doubles(&pos))); } + entries.push(("seenCredits", Tag::Byte(i8::from(self.seen_credits)))); // A respawn point other than the world spawn: an anchor elsewhere, or a bed. if let Some((dimension, block, yaw, forced)) = &self.respawn_elsewhere { let mut respawn = vec![ diff --git a/crates/horizon-client/src/win_screen.rs b/crates/horizon-client/src/win_screen.rs new file mode 100644 index 000000000..8d2a1c145 --- /dev/null +++ b/crates/horizon-client/src/win_screen.rs @@ -0,0 +1,452 @@ +//! `WinScreen`: the end poem, the credits and the post-credits text rolling up +//! under the logo, after the player leaves the End for the first time (with +//! the poem) or from Credits & Attribution (the credits alone). The texts come +//! from the resource root, so resource packs can replace them. +use crate::{ + font::Font, + hud::{Blend, EndPortalFill, HudAtlas, HudBatch}, + text::{self, Style, Text}, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use std::{collections::HashSet, path::Path}; + +/// `WinScreen.OBFUSCATE_TOKEN`: `§f§k§a§b` marks where the poem hides a name. +const OBFUSCATE_TOKEN: &str = "\u{a7}f\u{a7}k\u{a7}a\u{a7}b"; +/// `WinScreen.NAME_PREFIX`. +const NAME_PREFIX: &str = " "; +/// `WinScreen.SECTION_HEADING`. +const SECTION_HEADING: &str = "============"; +/// A key the screen reacts to (`keyPressed` / `keyReleased`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Key { + /// `KeyEvent.isUp`: the up arrow scrolls back. + Up, + /// Space speeds the scroll up. + Space, + /// Each held Control key speeds it up more. + LeftControl, + RightControl, +} +impl Key { + pub fn from_code(code: winit::keyboard::KeyCode) -> Option<Self> { + use winit::keyboard::KeyCode; + match code { + KeyCode::ArrowUp => Some(Self::Up), + KeyCode::Space => Some(Self::Space), + KeyCode::ControlLeft => Some(Self::LeftControl), + KeyCode::ControlRight => Some(Self::RightControl), + _ => None, + } + } +} +pub struct WinScreen { + pub poem: bool, + lines: Vec<Text>, + centered: HashSet<usize>, + total_scroll_length: i32, + scroll: f32, + speedup_active: bool, + speedup_modifiers: HashSet<Key>, + unmodified_scroll_speed: f32, + scroll_speed: f32, + direction: i32, +} +impl WinScreen { + /// `WinScreen.<init>` and `init`: the poem (`texts/end.txt`) when `poem`, + /// the credits (`texts/credits.json`), then `texts/postcredits.txt`. + pub fn new(poem: bool, root: &Path, player: &str, font: &Font) -> Self { + let speed = if poem { 0.5 } else { 0.75 }; + let mut screen = Self { + poem, + lines: Vec::new(), + centered: HashSet::new(), + total_scroll_length: 0, + scroll: 0.0, + speedup_active: false, + speedup_modifiers: HashSet::new(), + unmodified_scroll_speed: speed, + scroll_speed: speed, + direction: 1, + }; + let texts = root.join("assets/minecraft/texts"); + let read = |name: &str| match std::fs::read_to_string(texts.join(name)) { + Ok(s) => Some(s), + Err(e) => { + log::error!("Couldn't load credits from file minecraft:texts/{name}: {e}"); + None + } + }; + if poem && let Some(s) = read("end.txt") { + screen.add_poem_file(&s, player, font); + } + if let Some(s) = read("credits.json") { + match serde_json::from_str(&s) { + Ok(json) => screen.add_credits_file(&json), + Err(e) => { + log::error!("Couldn't load credits from file minecraft:texts/credits.json: {e}") + } + } + } + if poem && let Some(s) = read("postcredits.txt") { + screen.add_poem_file(&s, player, font); + } + screen.total_scroll_length = screen.lines.len() as i32 * 12; + screen + } + /// `addPoemFile`: each line with the player's name in, its obfuscated + /// spans turned into 3 to 6 scrambled characters, wrapped at 256 pixels + /// and followed by an empty line; 8 more empty lines at the end. + fn add_poem_file(&mut self, file: &str, player: &str, font: &Font) { + let mut random = LegacyRandom::new(8124371); + // BufferedReader.readLine: \n, \r or \r\n end a line; no empty last line. + let mut lines: Vec<&str> = file + .split('\n') + .map(|l| l.strip_suffix('\r').unwrap_or(l)) + .collect(); + if file.ends_with('\n') { + lines.pop(); + } + for line in lines.iter().flat_map(|l| l.split('\r')) { + let mut line = line.replace("PLAYERNAME", player); + while let Some(pos) = line.find(OBFUSCATE_TOKEN) { + let n = random.next_int_bound(4).unwrap_or(0) as usize + 3; + line = format!( + "{}\u{a7}f\u{a7}k{}{}", + &line[..pos], + &"XXXXXXXX"[..n], + &line[pos + OBFUSCATE_TOKEN.len()..] + ); + } + let text = Text::legacy(&line); + self.lines + .extend(font.split_lines(&text, 256.0).into_iter().map(|(t, _)| t)); + self.add_empty_line(); + } + for _ in 0..8 { + self.add_empty_line(); + } + } + /// `addCreditsFile`: each section's heading, then each discipline's name + /// and its titles with the names under them. + fn add_credits_file(&mut self, json: &serde_json::Value) { + let colored = |s: &str, color: u32| Text::styled(s, Style::color(color)); + let heading = || colored(SECTION_HEADING, text::WHITE); + for section in json.as_array().into_iter().flatten() { + let name = section["section"].as_str().unwrap_or_default(); + self.add_credits_line(heading(), true); + self.add_credits_line(colored(name, text::YELLOW), true); + self.add_credits_line(heading(), true); + self.add_empty_line(); + self.add_empty_line(); + for discipline in section["disciplines"].as_array().into_iter().flatten() { + let name = discipline["discipline"].as_str().unwrap_or_default(); + if !name.is_empty() { + self.add_credits_line(colored(name, text::YELLOW), true); + self.add_empty_line(); + self.add_empty_line(); + } + for title in discipline["titles"].as_array().into_iter().flatten() { + let name = title["title"].as_str().unwrap_or_default(); + self.add_credits_line(colored(name, text::GRAY), false); + for name in title["names"].as_array().into_iter().flatten() { + let line = format!("{NAME_PREFIX}{}", name.as_str().unwrap_or_default()); + self.add_credits_line(colored(&line, text::WHITE), false); + } + self.add_empty_line(); + self.add_empty_line(); + } + } + } + } + fn add_empty_line(&mut self) { + self.lines.push(Text::empty()); + } + fn add_credits_line(&mut self, line: Text, centered: bool) { + if centered { + self.centered.insert(self.lines.len()); + } + self.lines.push(line); + } + /// The lines in order and whether each is centred. + pub fn lines(&self) -> impl Iterator<Item = (&Text, bool)> { + self.lines + .iter() + .enumerate() + .map(|(i, l)| (l, self.centered.contains(&i))) + } + fn calculate_scroll_speed(&self) -> f32 { + let speed = if self.speedup_active { + self.unmodified_scroll_speed * (5.0 + self.speedup_modifiers.len() as f32 * 15.0) + } else { + self.unmodified_scroll_speed + }; + speed * self.direction as f32 + } + /// `keyPressed` / `keyReleased` (Escape closes the screen: `onClose`). + pub fn key(&mut self, key: Key, pressed: bool) { + match (key, pressed) { + (Key::Up, _) => self.direction = if pressed { -1 } else { 1 }, + (Key::Space, _) => self.speedup_active = pressed, + (_, true) => { + self.speedup_modifiers.insert(key); + } + (_, false) => { + self.speedup_modifiers.remove(&key); + } + } + self.scroll_speed = self.calculate_scroll_speed(); + } + /// `tick`: once the text has rolled past the top, the screen is done + /// (`respawn`, or back to the screen that opened it). + pub fn finished(&self, height: f32) -> bool { + let height = height as i32; + self.scroll > (self.total_scroll_length + height + height + 24) as f32 + } + pub fn scroll(&self) -> f32 { + self.scroll + } + /// Stay `scroll` pixels in (until a key changes the speed), for + /// screenshots. + pub fn hold(&mut self, scroll: f32) { + self.scroll = scroll; + self.scroll_speed = 0.0; + } + /// `extractRenderState` after a frame of `delta_ticks` game ticks: + /// `extractBackground`, the vignette, then the logo and the lines + /// scrolled up. The poem's End portal background samples `end_portal`; + /// the credits draw the scrolling menu background (over the blurred + /// panorama on the title screen). + pub fn draw( + &mut self, + batch: &mut HudBatch, + atlas: &HudAtlas, + delta_ticks: f32, + end_portal: EndPortalFill, + ) { + let (w, h) = (batch.width, batch.height); + if self.poem { + let start = batch.vertices.len(); + batch.fill(atlas, 0.0, 0.0, w, h, u32::MAX); + batch.blend_since(start, Blend::EndPortal); + batch.end_portal = end_portal; + } else { + self.menu_background(batch, atlas, w, h); + } + // extractVignette: credits_vignette.png stretched over the screen. + if let Some(r) = atlas.sprites.get("misc/credits_vignette").copied() { + let start = batch.vertices.len(); + batch.rect_uv(0.0, 0.0, w, h, r, u32::MAX); + batch.blend_since(start, Blend::Vignette); + } + self.scroll = (self.scroll + delta_ticks * self.scroll_speed).max(0.0); + let logo_x = (w / 2.0).floor() - 128.0; + let logo_y = h + 50.0; + // Everything below is drawn translated by `y_offs`. + let y_offs = -self.scroll; + // LogoRenderer(false) at full alpha. + let edition_x = (w / 2.0).floor() - 64.0; + batch.sprite_region( + atlas, + "gui/title/minecraft", + [logo_x, logo_y + y_offs, 256.0, 44.0], + 256.0, + 64.0, + ); + batch.sprite_region( + atlas, + crate::title_edition::SPRITE, + [edition_x, logo_y + 44.0 - 7.0 + y_offs, 128.0, 14.0], + 128.0, + 16.0, + ); + let mut y_pos = logo_y + 100.0; + let last = self.lines.len().saturating_sub(1); + for (i, line) in self.lines.iter().enumerate() { + let mut shift = y_offs; + if i == last { + // The last line stops in the middle of the screen. + let diff = y_pos + y_offs - ((h as i32 / 2) as f32 - 6.0); + if diff < 0.0 { + shift -= diff; + } + } + if y_pos + y_offs + 12.0 + 8.0 > 0.0 && y_pos + y_offs < h { + let x = if self.centered.contains(&i) { + // GuiGraphicsExtractor.centeredText: x - width / 2. + logo_x + 128.0 - (atlas.font.width_text(line) as i32 / 2) as f32 + } else { + logo_x + }; + batch.text_styled(atlas, line, x, y_pos + shift, u32::MAX, true); + } + y_pos += 12.0; + } + } + /// `extractMenuBackground`: `menu_background.png` tiled at 32 pixels, + /// scrolled by half the text's scroll. + fn menu_background(&self, batch: &mut HudBatch, atlas: &HudAtlas, w: f32, h: f32) { + let v = (self.scroll * 0.5).rem_euclid(32.0); + let start = batch.vertices.len(); + crate::ui::tiled( + batch, + atlas, + "gui/menu_background", + 0.0, + -v, + w, + h + 32.0, + 32.0, + u32::MAX, + ); + batch.clip_since(start, 0.0, 0.0, w, h); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A resource root with only the credits texts: every glyph is the + /// missing one, 6 pixels wide. + fn screen(poem: bool, end: &str, credits: &str, post: &str) -> WinScreen { + let root = std::env::temp_dir().join(format!( + "horizon-win-screen-{}-{poem}-{}", + std::process::id(), + end.len() + )); + let texts = root.join("assets/minecraft/texts"); + std::fs::create_dir_all(&texts).unwrap(); + std::fs::write(texts.join("end.txt"), end).unwrap(); + std::fs::write(texts.join("credits.json"), credits).unwrap(); + std::fs::write(texts.join("postcredits.txt"), post).unwrap(); + let atlas = HudAtlas::fonts(&root).unwrap(); + let screen = WinScreen::new(poem, &root, "Steve", &atlas.font); + let _ = std::fs::remove_dir_all(&root); + screen + } + const CREDITS: &str = r#"[{"section":"Studio","disciplines":[ + {"discipline":"","titles":[{"title":"Head","names":["Ada","Bo"]}]}, + {"discipline":"Art","titles":[{"title":"Artist","names":[]}]}]}]"#; + + #[test] + fn the_poem_names_the_player_and_scrambles_its_hidden_names() { + let s = screen( + true, + "\u{a7}3Hello PLAYERNAME.\r\n\n\u{a7}2\u{a7}f\u{a7}k\u{a7}a\u{a7}bkey\n", + "[]", + "End.", + ); + let lines: Vec<(String, bool)> = s.lines().map(|(t, c)| (t.plain(), c)).collect(); + // Each line then an empty one; the empty line adds no text line; 8 + // empty lines after each file. + let mut want = vec!["Hello Steve.", ""]; + want.push(""); + // LegacyRandom(8124371).nextInt(4) + 3 scrambled characters. + let n = LegacyRandom::new(8124371).next_int_bound(4).unwrap() as usize + 3; + let hidden = format!("{}key", &"XXXXXXXX"[..n]); + want.extend([hidden.as_str(), ""]); + want.extend([""; 8]); + want.extend(["End.", ""]); + want.extend([""; 8]); + assert_eq!( + lines, + want.iter() + .map(|l| (l.to_string(), false)) + .collect::<Vec<_>>() + ); + let hidden_line = s.lines().nth(3).unwrap().0; + let styles: Vec<_> = hidden_line.chars().map(|(_, s)| s.obfuscated).collect(); + assert!(styles[..n].iter().all(|o| *o == Some(true))); + assert_eq!(s.total_scroll_length, lines.len() as i32 * 12); + } + + #[test] + fn long_poem_lines_wrap_at_256_pixels() { + // 6-pixel glyphs: 42 fit a line, and the space at each break goes. + let line = vec!["a"; 50].join(" "); + let s = screen(true, &line, "[]", ""); + let lines: Vec<String> = s.lines().take(4).map(|(t, _)| t.plain()).collect(); + assert_eq!( + lines.iter().map(|l| l.chars().count()).collect::<Vec<_>>(), + [41, 41, 15, 0] + ); + assert!(lines.iter().all(|l| !l.starts_with(' '))); + } + #[test] + fn credits_centre_the_headings_and_list_the_names() { + let s = screen(false, "ignored", CREDITS, "ignored"); + let lines: Vec<(String, bool)> = s.lines().map(|(t, c)| (t.plain(), c)).collect(); + let l = |s: &str, c| (s.to_string(), c); + let names = |n: &str| l(&format!("{NAME_PREFIX}{n}"), false); + assert_eq!( + lines, + vec![ + l(SECTION_HEADING, true), + l("Studio", true), + l(SECTION_HEADING, true), + l("", false), + l("", false), + l("Head", false), + names("Ada"), + names("Bo"), + l("", false), + l("", false), + l("Art", true), + l("", false), + l("", false), + l("Artist", false), + l("", false), + l("", false), + ] + ); + let color = |i: usize| s.lines().nth(i).unwrap().0.chars().next().unwrap().1.color; + assert_eq!( + [color(0), color(1), color(5), color(6), color(10)], + [ + Some(text::WHITE), + Some(text::YELLOW), + Some(text::GRAY), + Some(text::WHITE), + Some(text::YELLOW) + ] + ); + } + + #[test] + fn keys_set_the_scroll_speed_and_direction() { + let mut s = screen(false, "", CREDITS, ""); + assert_eq!(s.scroll_speed, 0.75); + s.key(Key::Space, true); + assert_eq!(s.scroll_speed, 0.75 * 5.0); + s.key(Key::LeftControl, true); + s.key(Key::RightControl, true); + assert_eq!(s.scroll_speed, 0.75 * 35.0); + s.key(Key::Up, true); + assert_eq!(s.scroll_speed, -0.75 * 35.0); + s.key(Key::Space, false); + assert_eq!(s.scroll_speed, -0.75); + s.key(Key::Up, false); + s.key(Key::LeftControl, false); + assert_eq!(s.scroll_speed, 0.75); + // The poem rolls at 0.5 pixels a tick. + assert_eq!(screen(true, "", CREDITS, "").scroll_speed, 0.5); + } + + #[test] + fn the_screen_ends_once_everything_rolled_past() { + let mut s = screen(false, "", CREDITS, ""); + let atlas = HudAtlas::fonts(Path::new("/nonexistent")).unwrap(); + let mut batch = HudBatch::new([640, 480]); + let h = batch.height; + let end = (s.total_scroll_length as f32 + 2.0 * h + 24.0) / 0.75; + s.draw(&mut batch, &atlas, end - 1.0, EndPortalFill::default()); + assert!(!s.finished(h)); + // Scrolling back never goes above the start. + s.key(Key::Up, true); + s.draw(&mut batch, &atlas, end * 2.0, EndPortalFill::default()); + assert_eq!(s.scroll(), 0.0); + s.key(Key::Up, false); + s.draw(&mut batch, &atlas, end + 1.0, EndPortalFill::default()); + assert!(s.finished(h)); + } +} From 7e410d93b3f38dd92b349c1608fb5eb5ad85479a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:27:47 +0200 Subject: [PATCH 02/16] Fonts: TrueType providers and the font picked by text components Every font definition of the resources (and packs) is now loaded, not just font/default.json, and a text component's "font" field picks one: "minecraft:alt" draws the enchanting table's Galactic alphabet, "minecraft:illageralt" the illager runes, a pack's own font its glyphs, and a font that doesn't exist draws every character as the missing glyph (FontManager.getFontSetRaw). - font.rs: one FontSet per font id with its providers in order (space, bitmap, unihex, ttf) and their filters ("uniform", "jp"). Bitmap sheets outside the atlas (another namespace or folder) are copied into the glyph region when first drawn. - TrueTypeGlyphProvider: "ttf" providers (file under font/, size, oversample, shift, skip; CFF fonts refused) rasterized with ab_glyph into the glyph region as rrrr coverage (text_intensity), metrics as GlyphBitmap (bearings over the oversampling, whole-pixel advances). - text::Style gains the font id; it is parsed from JSON and SNBT components, pack descriptions and scoreboard number formats, inherited by children and written back. - Obfuscated text picks its random glyph in the style's font. Fixes #336 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/horizon-client/src/component.rs | 23 + crates/horizon-client/src/font.rs | 1053 +++++++++++++++++------ crates/horizon-client/src/hud.rs | 11 +- crates/horizon-client/src/packs.rs | 1 + crates/horizon-client/src/scoreboard.rs | 1 + crates/horizon-client/src/text.rs | 16 +- 6 files changed, 835 insertions(+), 270 deletions(-) diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client/src/component.rs index 0e04eab5e..68460054b 100644 --- a/crates/horizon-client/src/component.rs +++ b/crates/horizon-client/src/component.rs @@ -167,6 +167,7 @@ fn object_style(o: &serde_json::Map<String, Value>) -> Style { style.underlined = flag("underlined"); style.strikethrough = flag("strikethrough"); style.obfuscated = flag("obfuscated"); + style.font = o.get("font").and_then(crate::text::font_id); style } /// `ComponentSerialization.CODEC` decoding into text. `selector` components @@ -266,4 +267,26 @@ mod tests { let (v, _) = parse_snbt("[\"a\",{\"text\":\"b\"}]").unwrap(); assert_eq!(to_text(&v, &mut |_| Text::empty()).plain(), "ab"); } + + #[test] + fn the_font_is_inherited_and_kept() { + let (v, _) = + parse_snbt(r#"{text:"a",font:"alt",extra:["b",{text:"c",font:"minecraft:uniform"}]}"#) + .unwrap(); + let t = to_text(&v, &mut |_| Text::empty()); + let fonts: Vec<_> = t.chars().map(|(_, s)| s.font.clone()).collect(); + let (alt, uniform) = ( + Some("minecraft:alt".into()), + Some("minecraft:uniform".into()), + ); + assert_eq!(fonts, [alt.clone(), alt, uniform]); + // Back to JSON with the field, which a re-read keeps. + let again = to_text(&t.component(), &mut |_| Text::empty()); + let kept: Vec<_> = again.chars().map(|(_, s)| s.font.clone()).collect(); + assert_eq!(kept, fonts); + // Not an identifier: no font. + let (v, _) = parse_snbt(r#"{text:"a",font:"Bad Font"}"#).unwrap(); + let t = to_text(&v, &mut |_| Text::empty()); + assert_eq!(t.spans[0].style.font, None); + } } diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index 3039fdb40..c5e5760f3 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -1,19 +1,27 @@ -//! The default font (FontSet over `font/default.json`): space and bitmap -//! providers from the shared atlas, the unihex (GNU Unifont) fallback whose -//! glyphs are rasterized on demand into a reserved atlas region, vanilla -//! glyph metrics (ascent, oversampling, advances, bold/shadow offsets), -//! styled drawing and StringSplitter-style line wrapping. +//! Fonts (FontManager / FontSet): `font/default.json` and every other font a +//! text component names (`minecraft:alt`, `minecraft:uniform`, a pack's own), +//! each a list of providers tried in order: `space`, `bitmap` (sheets in the +//! shared atlas, or rasterized on demand when a pack's sheet is not in it), +//! `unihex` (GNU Unifont) and `ttf` (TrueTypeGlyphProvider, rasterized with +//! ab_glyph). Glyphs drawn at run time go into a reserved atlas region. +//! Vanilla glyph metrics (ascent, oversampling, advances, bold/shadow +//! offsets), styled drawing and StringSplitter-style line wrapping. use crate::{ hud::Rect, text::{Style, Text}, zip::Zip, }; +use ab_glyph::{Font as _, ScaleFont as _}; use std::{ cell::RefCell, collections::HashMap, path::{Path, PathBuf}, + sync::Arc, }; +/// `FontDescription.DEFAULT`. +pub const DEFAULT: &str = "minecraft:default"; + /// A glyph ready to draw: atlas UVs and its box relative to the pen /// position (GlyphBitmap left/top/right/bottom), in GUI pixels. #[derive(Clone, Copy, Debug)] @@ -24,7 +32,7 @@ pub struct Glyph { pub right: f32, pub bottom: f32, pub advance: f32, - /// Shadow and bold offset (1 for bitmap glyphs, 0.5 for unihex). + /// Shadow and bold offset (1 for bitmap and TrueType glyphs, 0.5 for unihex). pub offset: f32, } /// Pixels to copy into the shared atlas before the next HUD draw. @@ -43,23 +51,77 @@ struct HexGlyph { left: u32, right: u32, } -#[derive(Default)] -struct HexProvider { - glyphs: HashMap<u32, HexGlyph>, +/// A provider's `filter` (`FontOption.Filter`): the options it needs. +#[derive(Clone, Copy, Default)] +struct Filter { + uniform: Option<bool>, + jp: Option<bool>, +} +impl Filter { + fn of(provider: &serde_json::Value) -> Self { + let f = &provider["filter"]; + Self { + uniform: f["uniform"].as_bool(), + jp: f["jp"].as_bool(), + } + } + fn passes(self, uniform: bool, japanese: bool) -> bool { + self.uniform.is_none_or(|v| v == uniform) && self.jp.is_none_or(|v| v == japanese) + } +} +/// A bitmap glyph whose sheet is not in the atlas: the cell to copy. +struct SheetCell { + sheet: Arc<(u32, Vec<u8>)>, + x: u32, + y: u32, + w: u32, + h: u32, + glyph: Glyph, +} +enum BitmapGlyph { + Atlas(Glyph), + Sheet(SheetCell), +} +/// `TrueTypeGlyphProvider`. +struct TrueType { + font: ab_glyph::FontVec, + ids: HashMap<char, ab_glyph::GlyphId>, + /// FT_Set_Pixel_Sizes: `size * oversample` pixels to the em. + scale: ab_glyph::PxScale, + oversample: f32, + /// FT_Set_Transform's delta, in oversampled pixels (y down). + shift: (f32, f32), +} +enum Provider { + Space(HashMap<char, f32>), + Bitmap(Filter, HashMap<char, BitmapGlyph>), + /// The definition, and its glyphs once read. + Unihex(Filter, serde_json::Value, Option<HashMap<u32, HexGlyph>>), + TrueType(Filter, Box<TrueType>), +} +/// One font (`FontSet`): its providers and the glyphs resolved so far. +struct FontSet { + providers: Vec<Provider>, + glyphs: HashMap<char, Glyph>, + /// `glyphsByWidth` for obfuscated text (built on first use). + by_width: Option<HashMap<u32, Vec<char>>>, +} +/// The atlas region glyphs are rasterized into, filled in rows. +struct Region { + cursor: (u32, u32), + row: u32, + pending: Vec<Patch>, } struct Cache { - glyphs: HashMap<char, Glyph>, - cursor: (u32, u32), - pending: Vec<Patch>, - hex: Option<Vec<HexProvider>>, - /// `FontSet.glyphsByWidth` for obfuscated text (built on first use). - by_width: Option<HashMap<u32, Vec<char>>>, + /// Every font by id, the default one first (the common lookup). + sets: Vec<(String, FontSet)>, + region: Region, /// `Font.random`: picks obfuscated glyphs. random: horizon_core::random::LegacyRandom, } pub struct Font { - bitmap: HashMap<char, Glyph>, - space: HashMap<char, f32>, + /// The atlas rects of the sheets under `textures/font`. + sheets: HashMap<String, Rect>, missing: Glyph, white: Rect, root: PathBuf, @@ -67,9 +129,9 @@ pub struct Font { atlas: (u32, u32), region: (u32, u32), cache: RefCell<Cache>, - /// "Force Unicode Font": skip the bitmap providers (font/uniform.json). + /// "Force Unicode Font": the `uniform` filter option. pub uniform: bool, - /// "Japanese Glyph Variants": enable providers filtered on `jp`. + /// "Japanese Glyph Variants": the `jp` filter option. pub japanese: bool, } fn parse_hex_digit(b: u8) -> Option<u32> { @@ -178,9 +240,324 @@ fn glyph_rect(x: u32, y: u32, w: u32, h: u32, atlas: (u32, u32)) -> Rect { h, } } +/// The unscaled pixel width of a bitmap cell (`BitmapProvider.getActualGlyphWidth`). +fn used_width(pixels: &[u8], stride: u32, (cx, cy, cw, ch): (u32, u32, u32, u32)) -> u32 { + (0..cw) + .rev() + .find(|&x| { + (0..ch).any(|y| { + pixels + .get((((cy + y) * stride + cx + x) * 4 + 3) as usize) + .is_some_and(|a| *a != 0) + }) + }) + .map_or(0, |x| x + 1) +} +/// `BitmapProvider.Definition.load`: each character's glyph, from the atlas +/// when the sheet is in it (`pixels` its RGBA), else from the sheet's own +/// pixels, copied into the atlas when first drawn. +fn load_bitmap( + root: &Path, + p: &serde_json::Value, + sheets: &HashMap<String, Rect>, + pixels: &[u8], + atlas: (u32, u32), +) -> HashMap<char, BitmapGlyph> { + let mut out = HashMap::new(); + let file = p["file"].as_str().unwrap_or(""); + let (ns, name) = file.split_once(':').unwrap_or(("minecraft", file)); + let in_atlas = (ns == "minecraft") + .then(|| sheets.get(name.trim_end_matches(".png")).copied()) + .flatten(); + // The sheet: its size, and its pixels when they are not in the atlas. + let (sw, sh, sheet) = match in_atlas { + Some(rect) => (rect.w, rect.h, None), + None => match crate::hud::decode(&root.join(resource_path(file, "textures", ""))) { + Ok((w, h, rgba)) => (w, h, Some(Arc::new((w, rgba)))), + Err(_) => { + log::warn!("font sheet {file} could not be read"); + return out; + } + }, + }; + let rows: Vec<Vec<char>> = p["chars"] + .as_array() + .into_iter() + .flatten() + .filter_map(|r| r.as_str().map(|s| s.chars().collect())) + .collect(); + if rows.is_empty() || rows[0].is_empty() { + return out; + } + let cell_w = sw / rows[0].len() as u32; + let cell_h = sh / rows.len() as u32; + let height = p["height"].as_f64().unwrap_or(8.0) as f32; + let ascent = p["ascent"].as_f64().unwrap_or(7.0) as f32; + let scale = height / cell_h as f32; + let origin = in_atlas.map_or((0, 0), |rect| { + ( + (rect.u0 * atlas.0 as f32).round() as u32, + (rect.v0 * atlas.1 as f32).round() as u32, + ) + }); + for (r, row) in rows.iter().enumerate() { + for (c, ch) in row.iter().enumerate() { + if *ch == '\0' || out.contains_key(ch) { + continue; + } + let (x, y) = (c as u32 * cell_w, r as u32 * cell_h); + let used = match &sheet { + Some(s) => used_width(&s.1, s.0, (x, y, cell_w, cell_h)), + None => used_width( + pixels, + atlas.0, + (origin.0 + x, origin.1 + y, cell_w, cell_h), + ), + }; + let top = 7.0 - ascent; + let glyph = Glyph { + rect: None, + left: 0.0, + top, + right: cell_w as f32 * scale, + bottom: top + cell_h as f32 * scale, + advance: (0.5 + used as f32 * scale).floor() + 1.0, + offset: 1.0, + }; + let glyph = match &sheet { + None => BitmapGlyph::Atlas(Glyph { + rect: Some(glyph_rect( + origin.0 + x, + origin.1 + y, + cell_w, + cell_h, + atlas, + )), + ..glyph + }), + Some(s) => BitmapGlyph::Sheet(SheetCell { + sheet: s.clone(), + x, + y, + w: cell_w, + h: cell_h, + glyph, + }), + }; + out.insert(*ch, glyph); + } + } + out +} +/// `TrueTypeGlyphProviderDefinition.load`: a TrueType file (not CFF) under +/// `font/`, its Unicode characters but the `skip` ones. +fn load_true_type(root: &Path, p: &serde_json::Value) -> Option<TrueType> { + let file = p["file"].as_str()?; + let data = std::fs::read(root.join(resource_path(file, "font", ""))) + .map_err(|e| log::warn!("font file {file}: {e}")) + .ok()?; + // FT_Get_Font_Format must say TrueType: CFF outlines ("OTTO") are refused. + if data.starts_with(b"OTTO") { + log::warn!("font file {file} is not in TTF format"); + return None; + } + let font = ab_glyph::FontVec::try_from_vec(data) + .map_err(|e| log::warn!("font file {file}: {e}")) + .ok()?; + let size = p["size"].as_f64().unwrap_or(11.0) as f32; + let oversample = p["oversample"].as_f64().unwrap_or(1.0) as f32; + let shift = p["shift"].as_array().map_or((0.0, 0.0), |s| { + let f = |i: usize| s.get(i).and_then(|v| v.as_f64()).unwrap_or(0.0) as f32; + (f(0), f(1)) + }); + let skip: Vec<char> = match &p["skip"] { + serde_json::Value::String(s) => s.chars().collect(), + serde_json::Value::Array(a) => a + .iter() + .filter_map(|v| v.as_str()) + .flat_map(str::chars) + .collect(), + _ => Vec::new(), + }; + let ids = font + .codepoint_ids() + .filter(|(id, c)| id.0 != 0 && !skip.contains(c)) + .map(|(id, c)| (c, id)) + .collect(); + let pixels_per_em = (size * oversample).round(); + // ab_glyph scales by the font's height; FreeType by its em. + let units = font.units_per_em().unwrap_or(1000.0); + let scale = ab_glyph::PxScale::from(pixels_per_em * font.height_unscaled() / units); + Some(TrueType { + font, + ids, + scale, + oversample, + shift: (shift.0 * oversample, shift.1 * oversample), + }) +} +impl TrueType { + /// The advance in GUI pixels: hinted FreeType advances are whole + /// oversampled pixels. + fn advance(&self, id: ab_glyph::GlyphId) -> f32 { + self.font.as_scaled(self.scale).h_advance(id).round() / self.oversample + } + /// `loadGlyph` and its bitmap: the grey coverage as `rrrr` texels + /// (`text_intensity`), below 0.1 cut (its discard). + fn glyph(&self, id: ab_glyph::GlyphId) -> (Glyph, Option<(u32, u32, Vec<u8>)>) { + let advance = self.advance(id); + let glyph = + id.with_scale_and_position(self.scale, ab_glyph::point(self.shift.0, self.shift.1)); + let empty = Glyph { + rect: None, + left: 0.0, + top: 0.0, + right: 0.0, + bottom: 0.0, + advance, + offset: 1.0, + }; + let Some(outline) = self.font.outline_glyph(glyph) else { + return (empty, None); + }; + let bounds = outline.px_bounds(); + let (w, h) = (bounds.width() as u32, bounds.height() as u32); + if w == 0 || h == 0 { + return (empty, None); + } + let mut rgba = vec![0u8; (w * h * 4) as usize]; + outline.draw(|x, y, coverage| { + let v = if coverage < 0.1 { + 0 + } else { + (coverage.min(1.0) * 255.0).round() as u8 + }; + let i = ((y * w + x) * 4) as usize; + if let Some(px) = rgba.get_mut(i..i + 4) { + px.copy_from_slice(&[v; 4]); + } + }); + let os = self.oversample; + // GlyphBitmap: bitmap_left / bitmap_top over the oversampling, and + // top = 7 - bearingTop. + let (left, top) = (bounds.min.x / os, 7.0 + bounds.min.y / os); + ( + Glyph { + rect: None, + left, + top, + right: left + w as f32 / os, + bottom: top + h as f32 / os, + advance, + offset: 1.0, + }, + Some((w, h, rgba)), + ) + } +} +fn load_hex(root: &Path, p: &serde_json::Value) -> HashMap<u32, HexGlyph> { + let mut glyphs = HashMap::new(); + let Some(file) = p["hex_file"].as_str() else { + return glyphs; + }; + let path = root.join(resource_path(file, "", "").replace("//", "/")); + let Ok(zip) = Zip::open(&path) else { + return glyphs; + }; + let names: Vec<String> = zip + .names() + .filter(|n| n.ends_with(".hex")) + .map(str::to_owned) + .collect(); + for name in names { + if let Ok(bytes) = zip.read(&name) { + parse_hex(&bytes, &mut glyphs); + } + } + for o in p["size_overrides"].as_array().into_iter().flatten() { + let bound = |k: &str| { + o[k].as_str() + .and_then(|s| s.chars().next()) + .map_or(0, u32::from) + }; + let (left, right) = ( + o["left"].as_u64().unwrap_or(0) as u32, + o["right"].as_u64().unwrap_or(15) as u32, + ); + for c in bound("from")..=bound("to") { + if let Some(g) = glyphs.get_mut(&c) { + g.left = left; + g.right = right; + } + } + } + glyphs +} +/// The ids of every font definition (`font/**/*.json` of each namespace). +fn font_ids(root: &Path) -> Vec<String> { + fn walk(dir: &Path, prefix: &str, out: &mut Vec<String>) { + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + let name = entry.file_name().to_string_lossy().into_owned(); + if path.is_dir() { + walk(&path, &format!("{prefix}{name}/"), out); + } else if let Some(stem) = name.strip_suffix(".json") { + out.push(format!("{prefix}{stem}")); + } + } + } + let mut ids = Vec::new(); + for ns in std::fs::read_dir(root.join("assets")) + .into_iter() + .flatten() + .flatten() + { + let ns = ns.file_name().to_string_lossy().into_owned(); + walk( + &root.join("assets").join(&ns).join("font"), + &format!("{ns}:"), + &mut ids, + ); + } + ids.sort(); + ids +} +impl Region { + /// Place `w x h` pixels in the region (rows left to right); their atlas + /// position, or none when it is full. + fn place( + &mut self, + w: u32, + h: u32, + rgba: Vec<u8>, + atlas: (u32, u32), + region: (u32, u32), + ) -> Option<(u32, u32)> { + let (mut x, mut y) = self.cursor; + if x + w + 1 > atlas.0 { + x = 0; + y += self.row + 1; + self.row = 0; + } + if y + h > region.1 { + return None; + } + let (ax, ay) = (x, region.0 + y); + self.pending.push(Patch { + x: ax, + y: ay, + width: w, + height: h, + rgba, + }); + self.cursor = (x + w + 1, y); + self.row = self.row.max(h); + Some((ax, ay)) + } +} impl Font { - /// Build from the atlas holding the bitmap font sheets. `pixels` is the - /// RGBA atlas (for glyph widths) and `region` the reserved rows. + /// Build from the atlas holding the bitmap font sheets (`sprites`, of + /// `atlas` size) with `region` the reserved rows. pub fn load( root: &Path, sprites: &HashMap<String, Rect>, @@ -189,107 +566,33 @@ impl Font { region: (u32, u32), white: Rect, ) -> Self { - let mut bitmap = HashMap::new(); - let mut space = HashMap::new(); - let mut all = Vec::new(); - providers(root, "minecraft:default", 0, &mut all); - for provider in &all { - match provider["type"].as_str() { - Some("space") => { - for (k, v) in provider["advances"].as_object().into_iter().flatten() { - if let (Some(c), Some(a)) = (k.chars().next(), v.as_f64()) { - space.entry(c).or_insert(a as f32); - } - } - } - Some("bitmap") => { - // Only non-uniform bitmap sheets exist in the default font. - let file = provider["file"].as_str().unwrap_or(""); - let name = file - .trim_start_matches("minecraft:") - .trim_end_matches(".png"); - let name = name.to_string(); - let Some(rect) = sprites.get(&name).copied() else { - continue; - }; - let rows: Vec<Vec<char>> = provider["chars"] - .as_array() - .into_iter() - .flatten() - .filter_map(|r| r.as_str().map(|s| s.chars().collect())) - .collect(); - if rows.is_empty() || rows[0].is_empty() { - continue; - } - let cell_w = rect.w / rows[0].len() as u32; - let cell_h = rect.h / rows.len() as u32; - let height = provider["height"].as_f64().unwrap_or(8.0) as f32; - let ascent = provider["ascent"].as_f64().unwrap_or(7.0) as f32; - let scale = height / cell_h as f32; - let (ax, ay) = ( - (rect.u0 * atlas.0 as f32).round() as u32, - (rect.v0 * atlas.1 as f32).round() as u32, - ); - for (r, row) in rows.iter().enumerate() { - for (c, ch) in row.iter().enumerate() { - if *ch == '\0' || bitmap.contains_key(ch) { - continue; - } - let (cx, cy) = (ax + c as u32 * cell_w, ay + r as u32 * cell_h); - // BitmapProvider.getActualGlyphWidth. - let mut used = 0; - for x in (0..cell_w).rev() { - if (0..cell_h).any(|y| { - pixels - .get((((cy + y) * atlas.0 + cx + x) * 4 + 3) as usize) - .is_some_and(|a| *a != 0) - }) { - used = x + 1; - break; - } - } - let top = 7.0 - ascent; - bitmap.insert( - *ch, - Glyph { - rect: Some(glyph_rect(cx, cy, cell_w, cell_h, atlas)), - left: 0.0, - top, - right: cell_w as f32 * scale, - bottom: top + cell_h as f32 * scale, - advance: (0.5 + used as f32 * scale).floor() + 1.0, - offset: 1.0, - }, - ); - } - } - } - _ => {} - } - } - let missing = Glyph { - rect: None, - left: 0.0, - top: 0.0, - right: 5.0, - bottom: 8.0, - advance: 6.0, - offset: 1.0, - }; - Self { - bitmap, - space, - missing, + let sheets = sprites + .iter() + .filter(|(k, _)| k.starts_with("font/")) + .map(|(k, v)| (k.clone(), *v)) + .collect(); + let font = Self { + sheets, + missing: Glyph { + rect: None, + left: 0.0, + top: 0.0, + right: 5.0, + bottom: 8.0, + advance: 6.0, + offset: 1.0, + }, white, root: root.to_owned(), atlas, region, cache: RefCell::new(Cache { - glyphs: HashMap::new(), - cursor: (0, 0), - pending: Vec::new(), - hex: None, - by_width: None, + sets: Vec::new(), + region: Region { + cursor: (0, 0), + row: 0, + pending: Vec::new(), + }, random: horizon_core::random::LegacyRandom::new( std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -298,120 +601,161 @@ impl Font { }), uniform: false, japanese: false, - } + }; + // FontManager.prepare: every font definition of the resources. + let mut ids = font_ids(root); + ids.sort_by_key(|id| id != DEFAULT); + let sets = ids + .into_iter() + .map(|id| { + let set = font.load_set(&id, pixels); + (id, set) + }) + .collect(); + font.cache.borrow_mut().sets = sets; + font } - fn load_hex(&self) -> Vec<HexProvider> { + /// `FontManager`: a font's providers with references expanded. + fn load_set(&self, id: &str, pixels: &[u8]) -> FontSet { let mut all = Vec::new(); - providers(&self.root, "minecraft:default", 0, &mut all); - let mut out = Vec::new(); - for p in all.iter().filter(|p| p["type"] == "unihex") { - if let Some(filter) = p["filter"].as_object() { - let pass = filter.iter().all(|(k, v)| match k.as_str() { - "jp" => v.as_bool() == Some(self.japanese), - "uniform" => v.as_bool() == Some(self.uniform), - _ => true, - }); - if !pass { - continue; - } - } - let Some(file) = p["hex_file"].as_str() else { - continue; - }; - let path = self - .root - .join(resource_path(file, "", "").replace("//", "/")); - let Ok(zip) = Zip::open(&path) else { continue }; - let mut provider = HexProvider::default(); - let names: Vec<String> = zip - .names() - .filter(|n| n.ends_with(".hex")) - .map(str::to_owned) - .collect(); - for name in names { - if let Ok(bytes) = zip.read(&name) { - parse_hex(&bytes, &mut provider.glyphs); - } - } - for o in p["size_overrides"].as_array().into_iter().flatten() { - let from = o["from"] - .as_str() - .and_then(|s| s.chars().next()) - .map_or(0, u32::from); - let to = o["to"] - .as_str() - .and_then(|s| s.chars().next()) - .map_or(0, u32::from); - let (left, right) = ( - o["left"].as_u64().unwrap_or(0) as u32, - o["right"].as_u64().unwrap_or(15) as u32, - ); - for c in from..=to { - if let Some(g) = provider.glyphs.get_mut(&c) { - g.left = left; - g.right = right; - } - } - } - out.push(provider); + providers(&self.root, id, 0, &mut all); + let providers = all + .iter() + .filter_map(|p| match p["type"].as_str()? { + "space" => Some(Provider::Space( + p["advances"] + .as_object() + .into_iter() + .flatten() + .filter_map(|(k, v)| Some((k.chars().next()?, v.as_f64()? as f32))) + .collect(), + )), + "bitmap" => Some(Provider::Bitmap( + Filter::of(p), + load_bitmap(&self.root, p, &self.sheets, pixels, self.atlas), + )), + "unihex" => Some(Provider::Unihex(Filter::of(p), p.clone(), None)), + "ttf" => Some(Provider::TrueType( + Filter::of(p), + Box::new(load_true_type(&self.root, p)?), + )), + _ => None, + }) + .collect(); + FontSet { + providers, + glyphs: HashMap::new(), + by_width: None, } - out } - /// Forget rasterized fallback glyphs (after changing font options). + /// Forget rasterized glyphs (after changing font options). pub fn reset_cache(&self) { let mut cache = self.cache.borrow_mut(); - cache.glyphs.clear(); - cache.cursor = (0, 0); - cache.hex = None; - cache.by_width = None; + for (_, set) in &mut cache.sets { + set.glyphs.clear(); + set.by_width = None; + } + cache.region.cursor = (0, 0); + cache.region.row = 0; } - /// The glyph for a character (FontSet.getGlyph). + /// The glyph for a character in the default font (FontSet.getGlyph). pub fn glyph(&self, c: char) -> Glyph { - if let Some(a) = self.space.get(&c) { - return Glyph { - rect: None, - left: 0.0, - top: 0.0, - right: 0.0, - bottom: 0.0, - advance: *a, - offset: 1.0, - }; - } - if !self.uniform - && let Some(g) = self.bitmap.get(&c) - { - return *g; - } - if let Some(g) = self.cache.borrow().glyphs.get(&c) { - return *g; + self.glyph_of(DEFAULT, c) + } + /// The glyph for a character drawn in `style`'s font (its id is + /// already complete, see `text::font_id`). + pub fn glyph_styled(&self, c: char, style: &Style) -> Glyph { + self.glyph_of(style.font.as_deref().unwrap_or(DEFAULT), c) + } + /// The glyph for a character in the font `id` (`alt` is `minecraft:alt`). + pub fn glyph_in(&self, id: &str, c: char) -> Glyph { + if id.contains(':') { + self.glyph_of(id, c) + } else { + self.glyph_of(&format!("minecraft:{id}"), c) } + } + /// The first active provider's glyph, else the missing glyph. + fn glyph_of(&self, id: &str, c: char) -> Glyph { let mut cache = self.cache.borrow_mut(); - if cache.hex.is_none() { - cache.hex = Some(self.load_hex()); - } - let hex = cache.hex.as_ref().and_then(|providers| { - providers - .iter() - .find_map(|p| p.glyphs.get(&u32::from(c)).copied()) - }); - let glyph = match hex { - Some(h) => self.rasterize(&mut cache, h).unwrap_or(self.missing), - None => self.missing, + let Cache { sets, region, .. } = &mut *cache; + // FontManager.getFontSetRaw: a font that doesn't exist draws every + // character as the missing glyph. + let Some((_, set)) = sets.iter_mut().find(|(k, _)| k == id) else { + return self.missing; }; - cache.glyphs.insert(c, glyph); + if let Some(g) = set.glyphs.get(&c) { + return *g; + } + let glyph = self.resolve(set, region, c).unwrap_or(self.missing); + set.glyphs.insert(c, glyph); glyph } - fn rasterize(&self, cache: &mut Cache, h: HexGlyph) -> Option<Glyph> { + fn resolve(&self, set: &mut FontSet, region: &mut Region, c: char) -> Option<Glyph> { + let (uniform, japanese) = (self.uniform, self.japanese); + for provider in &mut set.providers { + match provider { + Provider::Space(advances) => { + if let Some(a) = advances.get(&c) { + return Some(Glyph { + rect: None, + left: 0.0, + top: 0.0, + right: 0.0, + bottom: 0.0, + advance: *a, + offset: 1.0, + }); + } + } + Provider::Bitmap(filter, glyphs) if filter.passes(uniform, japanese) => { + match glyphs.get(&c) { + Some(BitmapGlyph::Atlas(g)) => return Some(*g), + Some(BitmapGlyph::Sheet(cell)) => { + let (stride, pixels) = (&cell.sheet.0, &cell.sheet.1); + let mut rgba = Vec::with_capacity((cell.w * cell.h * 4) as usize); + for y in cell.y..cell.y + cell.h { + let at = ((y * stride + cell.x) * 4) as usize; + rgba.extend_from_slice(&pixels[at..at + (cell.w * 4) as usize]); + } + let (x, y) = + region.place(cell.w, cell.h, rgba, self.atlas, self.region)?; + return Some(Glyph { + rect: Some(glyph_rect(x, y, cell.w, cell.h, self.atlas)), + ..cell.glyph + }); + } + None => {} + } + } + Provider::Unihex(filter, def, glyphs) if filter.passes(uniform, japanese) => { + let glyphs = glyphs.get_or_insert_with(|| load_hex(&self.root, def)); + if let Some(h) = glyphs.get(&u32::from(c)).copied() { + return self.rasterize_hex(region, h); + } + } + Provider::TrueType(filter, ttf) if filter.passes(uniform, japanese) => { + if let Some(id) = ttf.ids.get(&c) { + let (glyph, bitmap) = ttf.glyph(*id); + return match bitmap { + Some((w, h, rgba)) => { + let (x, y) = region.place(w, h, rgba, self.atlas, self.region)?; + Some(Glyph { + rect: Some(glyph_rect(x, y, w, h, self.atlas)), + ..glyph + }) + } + None => Some(glyph), + }; + } + } + _ => {} + } + } + None + } + fn rasterize_hex(&self, region: &mut Region, h: HexGlyph) -> Option<Glyph> { let width = h.right.saturating_sub(h.left) + 1; - let (mut x, mut y) = cache.cursor; - if x + width + 1 > self.atlas.0 { - x = 0; - y += 17; - } - if y + 16 > self.region.1 { - return None; - } let mut rgba = Vec::with_capacity((width * 16 * 4) as usize); for row in h.rows { for bit in h.left..=h.right { @@ -419,17 +763,9 @@ impl Font { rgba.extend(if set { [255; 4] } else { [0; 4] }); } } - let (ax, ay) = (x, self.region.0 + y); - cache.pending.push(Patch { - x: ax, - y: ay, - width, - height: 16, - rgba, - }); - cache.cursor = (x + width + 1, y); + let (x, y) = region.place(width, 16, rgba, self.atlas, self.region)?; Some(Glyph { - rect: Some(glyph_rect(ax, ay, width, 16, self.atlas)), + rect: Some(glyph_rect(x, y, width, 16, self.atlas)), left: 0.0, top: 0.0, right: width as f32 / 2.0, @@ -439,26 +775,29 @@ impl Font { }) } /// `FontSet.getRandomGlyph`: what an obfuscated character draws, a random - /// glyph as wide as `advance` (rounded up), else the missing glyph. + /// glyph of the font as wide as `advance` (rounded up), else the missing + /// glyph. /// /// Vanilla picks among every glyph of the font set, Unifont's included. /// Those are rasterized into a fixed atlas region on demand, which a /// line of obfuscated text would fill in seconds, so the candidates are - /// the glyphs already in the atlas (the bitmap sheets and spaces), or with - /// "Force Unicode Font" the Unifont glyphs below U+0250. - pub fn random_glyph(&self, advance: f32) -> Glyph { + /// the glyphs already in the atlas (the bitmap sheets there and spaces), + /// or for a font without any (Force Unicode Font, a TrueType font) its + /// glyphs below U+0250. + pub fn random_glyph(&self, style: &Style, advance: f32) -> Glyph { use horizon_core::random::RandomSource; + let id = style.font.as_deref().unwrap_or(DEFAULT); let width = advance.ceil() as u32; let pick = { let mut cache = self.cache.borrow_mut(); - if cache.by_width.is_none() { - let by_width = self.glyphs_by_width(&mut cache); - cache.by_width = Some(by_width); + let Cache { sets, random, .. } = &mut *cache; + let Some((_, set)) = sets.iter_mut().find(|(k, _)| k == id) else { + return self.missing; + }; + if set.by_width.is_none() { + set.by_width = Some(self.glyphs_by_width(set)); } - let Cache { - by_width, random, .. - } = &mut *cache; - by_width + set.by_width .as_ref() .and_then(|m| m.get(&width)) .and_then(|chars| { @@ -466,44 +805,79 @@ impl Font { chars.get(i as usize).copied() }) }; - pick.map_or(self.missing, |c| self.glyph(c)) + pick.map_or(self.missing, |c| self.glyph_of(id, c)) } - fn glyphs_by_width(&self, cache: &mut Cache) -> HashMap<u32, Vec<char>> { - let mut chars: Vec<(char, f32)> = self.space.iter().map(|(c, a)| (*c, *a)).collect(); - if self.uniform { - if cache.hex.is_none() { - cache.hex = Some(self.load_hex()); - } - for code in 0..0x250u32 { - let hex = cache.hex.iter().flatten().find_map(|p| p.glyphs.get(&code)); - if let (Some(c), Some(h)) = (char::from_u32(code), hex) - && !self.space.contains_key(&c) - { - let width = h.right.saturating_sub(h.left) + 1; - chars.push((c, (width / 2 + 1) as f32)); + fn glyphs_by_width(&self, set: &mut FontSet) -> HashMap<u32, Vec<char>> { + let (uniform, japanese) = (self.uniform, self.japanese); + let mut chars = std::collections::BTreeSet::new(); + let mut in_atlas = false; + for provider in &set.providers { + match provider { + Provider::Space(advances) => chars.extend(advances.keys().copied()), + Provider::Bitmap(filter, glyphs) if filter.passes(uniform, japanese) => { + for (c, g) in glyphs { + if matches!(g, BitmapGlyph::Atlas(_)) { + in_atlas = true; + chars.insert(*c); + } + } } + _ => {} } - } else { - chars.extend( - self.bitmap - .iter() - .filter(|(c, _)| !self.space.contains_key(c)) - .map(|(c, g)| (*c, g.advance)), - ); } - chars.sort_by_key(|(c, _)| *c); + if !in_atlas { + // Nothing in the atlas: the glyphs below U+0250, rasterized as used. + chars.extend((0..0x250u32).filter_map(char::from_u32)); + } let mut out: HashMap<u32, Vec<char>> = HashMap::new(); - for (c, advance) in chars { - out.entry(advance.ceil() as u32).or_default().push(c); + for c in chars { + if let Some(advance) = self.provider_advance(set, c) { + out.entry(advance.ceil() as u32).or_default().push(c); + } } out } + /// A character's advance in `set` (its first provider that has it), + /// without rasterizing it. + fn provider_advance(&self, set: &mut FontSet, c: char) -> Option<f32> { + let (uniform, japanese) = (self.uniform, self.japanese); + for provider in &mut set.providers { + match provider { + Provider::Space(advances) => { + if let Some(a) = advances.get(&c) { + return Some(*a); + } + } + Provider::Bitmap(filter, glyphs) if filter.passes(uniform, japanese) => { + match glyphs.get(&c) { + Some(BitmapGlyph::Atlas(g)) => return Some(g.advance), + Some(BitmapGlyph::Sheet(cell)) => return Some(cell.glyph.advance), + None => {} + } + } + Provider::Unihex(filter, def, glyphs) if filter.passes(uniform, japanese) => { + let glyphs = glyphs.get_or_insert_with(|| load_hex(&self.root, def)); + if let Some(h) = glyphs.get(&u32::from(c)) { + let width = h.right.saturating_sub(h.left) + 1; + return Some((width / 2 + 1) as f32); + } + } + Provider::TrueType(filter, ttf) if filter.passes(uniform, japanese) => { + if let Some(id) = ttf.ids.get(&c) { + return Some(ttf.advance(*id)); + } + } + _ => {} + } + } + None + } /// Atlas pixels rasterized since the last call. pub fn take_patches(&self) -> Vec<Patch> { - std::mem::take(&mut self.cache.borrow_mut().pending) + std::mem::take(&mut self.cache.borrow_mut().region.pending) } pub fn advance(&self, c: char, style: &Style) -> f32 { - let g = self.glyph(c); + let g = self.glyph_styled(c, style); g.advance + if style.is_bold() { g.offset } else { 0.0 } } /// Font.width of plain text (legacy codes are formatting, not glyphs). @@ -689,4 +1063,155 @@ mod tests { assert_eq!(r.v1, ((y + h) as f32 - 0.01) / 4096.0); } } + + /// A resource root with these font definitions and files. + fn root(name: &str, files: &[(&str, &[u8])]) -> PathBuf { + let root = std::env::temp_dir().join(format!("horizon-font-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + for (path, bytes) in files { + let path = root.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + } + root + } + fn white() -> Rect { + Rect { + u0: 0.0, + v0: 0.0, + u1: 0.0, + v1: 0.0, + w: 1, + h: 1, + } + } + fn load(root: &Path) -> Font { + Font::load( + root, + &HashMap::new(), + &[], + (4096, 1024), + (512, 512), + white(), + ) + } + fn png(width: u32, height: u32, opaque: impl Fn(u32, u32) -> bool) -> Vec<u8> { + let mut pixels = Vec::new(); + for y in 0..height { + for x in 0..width { + pixels.extend(if opaque(x, y) { [255; 4] } else { [0; 4] }); + } + } + let mut out = Vec::new(); + let mut encoder = png::Encoder::new(&mut out, width, height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + encoder + .write_header() + .unwrap() + .write_image_data(&pixels) + .unwrap(); + out + } + + #[test] + fn true_type_glyphs_are_rasterized_at_the_provider_size() { + let def = br#"{"providers":[{"type":"ttf","file":"minecraft:mono.ttf","size":11,"oversample":2,"shift":[0.5,1],"skip":["B"]}]}"#; + let root = root( + "ttf", + &[ + ("assets/minecraft/font/default.json", def), + ( + "assets/minecraft/font/mono.ttf", + horizon_theme::fonts::GEIST_MONO, + ), + ], + ); + let font = load(&root); + let _ = std::fs::remove_dir_all(&root); + let a = font.glyph('A'); + let rect = a.rect.expect("A is drawn"); + // Oversampled 2x: the bitmap is twice the glyph's GUI size. + assert_eq!(rect.w as f32 / 2.0, a.right - a.left); + assert_eq!(rect.h as f32 / 2.0, a.bottom - a.top); + // A monospaced font: every advance is the same, in half pixels. + assert_eq!(a.advance, font.glyph('i').advance); + assert_eq!((a.advance * 2.0).fract(), 0.0); + assert!(a.advance > 4.0 && a.advance < 9.0, "{}", a.advance); + // Capitals sit on the baseline at y = 7, shifted down a pixel. + assert!((a.bottom - 8.0).abs() <= 0.5, "{}", a.bottom); + assert_eq!(a.offset, 1.0); + // The space has an advance and nothing to draw. + let space = font.glyph(' '); + assert!(space.rect.is_none() && space.advance > 0.0); + // Skipped characters fall through to the missing glyph. + assert_eq!(font.glyph('B').advance, 6.0); + // Coverage as `rrrr` texels, faint coverage cut. + let patches = font.take_patches(); + assert_eq!(patches.len(), 2); + let texels: Vec<&[u8]> = patches.iter().flat_map(|p| p.rgba.chunks(4)).collect(); + assert!(texels.iter().all(|t| t.iter().all(|v| *v == t[0]))); + assert!(texels.iter().all(|t| t[0] == 0 || t[0] >= 25)); + assert!(texels.iter().any(|t| t[0] == 255)); + } + + #[test] + fn styles_pick_their_font_and_unknown_fonts_draw_missing_glyphs() { + let sheet = png(16, 8, |x, _| x < 2 || (8..14).contains(&x)); + let default = br#"{"providers":[{"type":"space","advances":{" ":4}},{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["ab"]}]}"#; + let alt = br#"{"providers":[{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["ba"]}]}"#; + let root = root( + "styles", + &[ + ("assets/minecraft/font/default.json", default), + ("assets/minecraft/font/alt.json", alt), + ("assets/minecraft/textures/font/a.png", &sheet), + ], + ); + let font = load(&root); + let _ = std::fs::remove_dir_all(&root); + // The sheet is not in this atlas: glyphs are copied in when first drawn. + assert_eq!(font.glyph('a').advance, 3.0); + assert_eq!(font.glyph('b').advance, 7.0); + let alt = Style { + font: Some("minecraft:alt".into()), + ..Style::default() + }; + assert_eq!(font.glyph_styled('a', &alt).advance, 7.0); + assert_eq!(font.glyph_in("alt", 'b').advance, 3.0); + assert!(font.glyph_styled('a', &alt).rect.is_some()); + // Not in alt (no space provider there), or no such font at all. + assert_eq!(font.glyph_styled(' ', &alt).advance, 6.0); + let missing = Style { + font: Some("minecraft:nope".into()), + ..Style::default() + }; + assert_eq!(font.glyph_styled(' ', &missing).advance, 6.0); + assert_eq!(font.advance('a', &alt), 7.0); + let text = Text::literal("ab").with_style(&alt); + assert_eq!(font.width_text(&text), 10.0); + assert_eq!(font.random_glyph(&alt, 7.0).advance, 7.0); + assert!(!font.take_patches().is_empty()); + } + + #[test] + fn provider_filters_follow_the_font_options() { + let sheet = png(8, 8, |x, _| x < 4); + let default = br#"{"providers":[{"type":"reference","id":"minecraft:include/sheet","filter":{"uniform":false}},{"type":"space","advances":{"a":2}}]}"#; + let sheet_def = br#"{"providers":[{"type":"bitmap","file":"minecraft:font/s.png","ascent":7,"chars":["a"]}]}"#; + let root = root( + "filters", + &[ + ("assets/minecraft/font/default.json", default), + ("assets/minecraft/font/include/sheet.json", sheet_def), + ("assets/minecraft/textures/font/s.png", &sheet), + ], + ); + let mut font = load(&root); + let _ = std::fs::remove_dir_all(&root); + assert_eq!(font.glyph('a').advance, 5.0); + font.uniform = true; + font.reset_cache(); + assert_eq!(font.glyph('a').advance, 2.0); + } } diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 29faf5a2a..3c33ecb18 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -711,11 +711,12 @@ impl HudBatch { let mut glyphs = Vec::new(); let mut cursor = x; for (i, (ch, style)) in text.chars().enumerate() { - let mut g = font.glyph(ch); + // The style's font (`Style.getFont`), the default one unless set. + let mut g = font.glyph_styled(ch, style); // Font.StringRenderOutput.accept: obfuscated characters draw a // random glyph of the same width each frame. if style.obfuscated == Some(true) && ch != ' ' { - g = font.random_glyph(g.advance); + g = font.random_glyph(style, g.advance); } let c = style.color.map_or(color, |rgb| { rgba((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8, alpha) @@ -1263,11 +1264,11 @@ mod tests { let (a, b) = (fonts.font.glyph('a').advance, fonts.font.glyph('b').advance); assert_ne!(a, b); for _ in 0..20 { - assert_eq!(fonts.font.random_glyph(a).advance, a); - assert_eq!(fonts.font.random_glyph(b).advance, b); + assert_eq!(fonts.font.random_glyph(&Default::default(), a).advance, a); + assert_eq!(fonts.font.random_glyph(&Default::default(), b).advance, b); } // No glyph that wide: FontSet's missing glyph. - let missing = fonts.font.random_glyph(30.0); + let missing = fonts.font.random_glyph(&Default::default(), 30.0); assert!(missing.rect.is_none() && missing.right == 5.0); } diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index 7af7518f8..7bd4fd782 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -87,6 +87,7 @@ fn style_of(o: &serde_json::Map<String, serde_json::Value>) -> Style { underlined: flag("underlined"), strikethrough: flag("strikethrough"), obfuscated: flag("obfuscated"), + font: o.get("font").and_then(crate::text::font_id), ..Style::default() } } diff --git a/crates/horizon-client/src/scoreboard.rs b/crates/horizon-client/src/scoreboard.rs index e063c6f09..4796be51a 100644 --- a/crates/horizon-client/src/scoreboard.rs +++ b/crates/horizon-client/src/scoreboard.rs @@ -118,6 +118,7 @@ pub fn style_from_json(v: &Value) -> Style { s.underlined = flag("underlined"); s.strikethrough = flag("strikethrough"); s.obfuscated = flag("obfuscated"); + s.font = o.get("font").and_then(text::font_id); s } impl NumberFormat { diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index 3874efd17..9f39155d1 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -61,6 +61,13 @@ pub struct Style { pub click: Option<ClickEvent>, /// Hover text. pub hover: Option<Box<Text>>, + /// The font (`FontDescription.Resource`), a full id like + /// `minecraft:alt`; the default font when unset. + pub font: Option<String>, +} +/// A style's `font` field: an identifier (`alt` is `minecraft:alt`). +pub fn font_id(v: &Value) -> Option<String> { + crate::command::args::parse_identifier(v.as_str()?) } impl Style { pub fn color(c: u32) -> Self { @@ -83,6 +90,9 @@ impl Style { if self.hover.is_none() { self.hover.clone_from(&base.hover); } + if self.font.is_none() { + self.font.clone_from(&base.font); + } } pub fn is_bold(&self) -> bool { self.bold == Some(true) @@ -451,7 +461,7 @@ impl Text { } /// The style fields of a component's JSON. -const STYLE_KEYS: [&str; 8] = [ +const STYLE_KEYS: [&str; 9] = [ "color", "bold", "italic", @@ -460,6 +470,7 @@ const STYLE_KEYS: [&str; 8] = [ "obfuscated", "click_event", "hover_event", + "font", ]; /// Style.Serializer: the fields a style sets. fn style_json(style: &Style) -> Vec<(String, Value)> { @@ -500,6 +511,9 @@ fn style_json(style: &Style) -> Vec<(String, Value)> { json!({ "action": "show_text", "value": hover.component() }), )); } + if let Some(font) = &style.font { + out.push(("font".to_owned(), font.clone().into())); + } out } From bd36508c298cfee286986088a1b30ecdac68d34b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:34:20 +0200 Subject: [PATCH 03/16] lan_e2e levels: players in their own levels on the server thread; design note A new `levels` check (--server-thread) runs the host and a guest in different dimensions: execute in ... tp, mobs ticking in two levels at once with unique ids, rejoin and save/reload with the guest in the Nether, death there, the host through a Nether portal alone, the guest through an End portal and the exit portal alone. All of it already works on the server thread. docs/server-levels.md says how the server's levels map onto vanilla's, what the dedicated server and the server thread share, the cost of an extra level and what's left. docs/server.md no longer says players can't change dimension. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/server-levels.md | 90 ++++++++++++++++++ docs/server.md | 2 +- tools/lan_e2e.py | 212 +++++++++++++++++++++++++++++++++++++++++- 3 files changed, 301 insertions(+), 3 deletions(-) create mode 100644 docs/server-levels.md diff --git a/docs/server-levels.md b/docs/server-levels.md new file mode 100644 index 000000000..0190c0c03 --- /dev/null +++ b/docs/server-levels.md @@ -0,0 +1,90 @@ +# A server's levels: one per dimension + +Vanilla's `MinecraftServer` holds a `ServerLevel` per dimension, and each player is in one of them. +Horizon's server does the same. That covers the dedicated server and single player's server thread +(`Game::serving`, the default since #1114). So a LAN world's host and each guest can be in different +dimensions at the same time. + +## How the single-level `Game` maps onto vanilla's levels + +The game's tick code reads one level: the one held in `Game`'s own fields (the world, its streaming +and save, block ticks, entities, block entities and their per-level queues). `game/levels.rs` keeps +the other dimensions' levels as `Parked` values and swaps one into place (`enter_level`). The swap is +`mem::swap` of each per-level field, so the tick code runs unchanged, one level at a time. + +| Vanilla | Horizon | +| --- | --- | +| `MinecraftServer.levels` | the level in place plus `Levels::parked` | +| `MinecraftServer.tickChildren`, every level | `tick_server`: each level with a player in it, in Overworld, Nether, End order. The first pass reads the network and runs the shared parts (clock, weather, functions, autosave). | +| `ServerLevel.players` | `Hub::here`: the guests whose `dimension` is the level in place | +| `ServerPlayer.teleport` into another level | `server_travel.rs`: a Respawn packet, then the teleport once the destination has loaded (portals and `execute in … tp`) | +| `PlayerList.respawn` | `guest_respawn`: back into the Overworld's level | +| `ServerLevel.noPlayersEmptyTime`, chunk unloading | `close_idle_levels`: a level other than the Overworld with nobody in it for 300 ticks is saved and closed | +| the levels' shared `LevelData` | not swapped: game time, day time, weather, game rules, scoreboard, maps, entity ids (`next_entity`, unique across levels) | + +The packets of a guest are read in its own level's pass (`Hub::tick_level`), so its actions and +commands run with its level in place. + +The window's own game (`--no-server-thread`, `HORIZON_SERVER_THREAD=0`, and the command harness) keeps +one level, which follows its player (`enter_dimension`). LAN guests of a world run that way stay in the +host's dimension. That mode is the escape hatch now, so it gets no multi-level work. + +## One code path for both + +The dedicated server and the server thread are the same code. The server thread runs a `Game` with +`options.dedicated` set and a hub without a host player. The window joins it through memory as one +more player. Everything above serves both, and `server_dimension_players` (vanilla clients on Horizon's +dedicated server) and `lan_e2e --server-thread` (Horizon clients on the server thread) check it from +the two sides. + +## Cost of an extra level + +Measured on the Mac mini (M4 Pro) at render distance 12, on 2026-10-22. The host and a guest each +played a fresh world on the server thread. RSS is the host's whole process, window included. Tick time +is `/tick query`'s average over 100 ticks. + +| Where the players are | Average tick | P95 | Host RSS | +| --- | --- | --- | --- | +| both in the Overworld | 1.0 ms | 1.3 ms | 1194 MB | +| guest in the Nether (two levels tick) | 2.2 ms | 2.9 ms | 1238 MB | +| guest in the End (the Nether still parked) | 0.9 ms | 1.1 ms | 1324 MB | +| both back, the Nether and End closed after 300 idle ticks | 0.8 ms | 0.9 ms | 1335 MB | + +- A level costs only while a player is in it: its chunks around that player, their entities, and the + tick. With nobody outside the Overworld, `tick_server` runs one pass, as before. +- A closed level's memory goes back to the allocator, not always to the system. +- Entering a level the first time opens its region files and streaming (`open_level`). That cost + comes once, before the player's chunks load. + +## Saving + +`save_game` saves the level in place, then every parked level (`save_parked_levels`). Each level has +its own region folder, as in vanilla (`DIM-1`, `DIM1`). A level closed for being idle is saved first. +Each player's saved data holds its dimension (`Dimension`). A guest who leaves in +the Nether, or whose host saves and quits, joins again in the Nether where it was. + +## What's checked + +`python3 tools/lan_e2e.py --server-thread --check portals --check levels`: + +- `portals`: the guest goes to the Nether through a portal while the host stays. The host then goes + to the End while the guest is in the Nether, so three levels run at once, and both come back. +- `levels`, with the host and the guest each in a level of its own: + - `execute in the_nether run tp` moves the guest alone. + - Mobs and armour stands fall in two levels at once, and every entity id is unique across the + levels. + - The guest leaves in the Nether and joins again there. + - The guest dies in the Nether and respawns in the Overworld. + - The host takes a Nether portal alone. + - The guest takes an End portal and then the exit portal alone. + - The host saves, quits and opens the world again with the guest in the Nether, and the guest + joins again there. + +## Not done yet + +- **End credits for server players.** The first exit from the End should show a player the credits + (`EndPortalBlock.entityInside`, `seenCredits`). The client's WinScreen is #338. +- **Entities through portals between levels.** Mobs, items and minecarts that enter a portal on a + server, and portal tickets (`TeleportTransition.PLACE_PORTAL_TICKET`), are not handled. +- **Unlimited selectors.** `@e` without a distance or volume reads only the source's level. Vanilla's + reads every level. diff --git a/docs/server.md b/docs/server.md index d7959aed0..6a73e768f 100644 --- a/docs/server.md +++ b/docs/server.md @@ -90,7 +90,7 @@ not tick cost, so it is in scope here (see section 9). |---|---| | `online-mode=true` | **Works** (ServerLoginPacketListenerImpl): a 1024-bit RSA key pair at start ("Generating keypair"), the encryption request, the shared secret and challenge, AES/CFB8, and the session service's `hasJoined` check (with the address when `prevent-proxy-connections` is on), with vanilla's log lines and messages. `test_online_mode_parity.py` runs the same logins against vanilla's server and Horizon's with a mock session service. | | Secure chat | **Works** (`SignedMessageChain`, `LastSeenMessagesValidator`, `MessageSignatureCache`): the chat session update and its profile key, checked against the services' `playerCertificateKeys`; signed chat, `say`, `me` and `msg`, relayed with their signatures and last-seen lists; `enforce-secure-profile` (with `online-mode`) refuses unsigned chat; and vanilla's log lines (`[Not Secure]`, the decoder's warnings, the kicks). Offline servers and players without a chat session chat unsigned, as on vanilla. `test_secure_chat_parity.py` runs the same signed and unsigned players against vanilla's server and Horizon's, with test keys and a mock services server. | -| Nether and End | **Players can't change dimension.** The engine keeps one dimension loaded (`Game::enter_dimension` moves only the local single-player player), and the hub serves one `dimension` to everyone. | +| Nether and End | **Works**: the server holds a level per dimension, and each player is in its own (portals, `execute in … tp`, respawn). `test_server_dimension_players_parity.py` checks it against vanilla. How it works, its cost and what's left: [server-levels.md](server-levels.md). | | Refused logins | Logged as vanilla does: `Disconnecting <name> (/address): <reason>`, then `<name> (/address) lost connection: <reason>`, and the session errors (`Username '<name>' tried to join with an invalid session`, `Couldn't verify username because servers are unavailable`). | | Gameplay for remote players | Checked against vanilla's server with a vanilla-codec client (#484, `tools/test_dedicated_server_parity.py`): a right click with an item on a block uses it once, a dead player's commands run, players on a team without friendly fire don't hurt each other, and a player's projectiles are theirs (their ender pearl takes them). The recipe book, status effects and block sync while digging (#500) work. Left: a player's projectiles don't hit other players (no bow PvP between guests), and a mob a guest kills counts in the host's statistics and advancements, not the guest's (`mob_died` runs as the host). | | Defaults that surprise owners | `white-list=true` is vanilla 26.3's default, so a fresh server refuses everyone until they are added. That matches vanilla, so the first-run flow (section 3) asks about the whitelist up front. | diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 9b883b163..304668322 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -67,6 +67,10 @@ address. The script then checks, from both sides, what a guest's game used to ge - 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. +- levels: (--server-thread) the host and the guest each in a level of their own: `execute in` builds + and teleports into another level, mobs fall in two levels at once with ids unique across + them, the guest rejoins in the Nether, dies there and respawns in the Overworld, the host + takes a Nether portal alone, the guest takes an End portal and the exit portal alone, and the host saves, quits and reopens with the guest in the Nether. - commands: the guest's chat completes commands and their arguments over the server's command tree (Tab), and runs what it completed; - recipes: the guest's recipe book lists the planks recipe the logs unlock, and clicking it @@ -155,7 +159,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', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'levels'] class Game: @@ -525,6 +529,209 @@ def portals(host, guest, out, x, y, z, hx, hy, hz): return {'guest_nether': arrived, 'host_end': [ex, ey, ez], 'back': pos_of(guest)} +NETHER, END, OVERWORLD = 'minecraft:the_nether', 'minecraft:the_end', 'minecraft:overworld' + + +def check_levels(host, guest, out): + """(--server-thread) Each player in its own level (MinecraftServer.levels), the host and the guest + apart: the steps run in order, each reported, and the check fails if any did.""" + if not SERVER_THREAD: + return 'skipped (needs --server-thread)' + start = {g.name: pos_of(g) for g in (host, guest)} + steps, failed = {}, [] + guest('command', command='gamemode creative') + try: + for name, step in LEVEL_STEPS: + try: + steps[name] = step(host, guest, out) + except (Failed, AssertionError, StopIteration, KeyError) as e: + steps[name], failed = repr(e), failed + [name] + for g in (host, guest): + back_to_game(g) + print(f'[lan] levels {name}: {"FAIL" if name in failed else "PASS"} {steps[name]}') + finally: + for g in (host, guest): + back_to_game(g) + if g('state').get('screen') == 'dead': + g.raw('respawn') + g.wait(20) + x, y, z = start[g.name] + g('command', command=f'execute in {OVERWORLD} run tp @s {x:.2f} {y:.2f} {z:.2f}') + guest('command', command='gamemode survival') + guest.wait(40) + assert not failed, f'failed: {failed}; {steps}' + return steps + + +def level_floor(game, x, y, z): + """An obsidian floor under x y z with air above it, in the level `game` is in (fill needs the + chunks loaded: ServerLevel.hasChunksAt).""" + game('command', command=f'fill {x - 4} {y - 1} {z - 4} {x + 4} {y - 1} {z + 4} minecraft:obsidian') + game('command', command=f'fill {x - 4} {y} {z - 4} {x + 4} {y + 4} {z + 4} minecraft:air') + + +def into_level(game, dimension, x, y, z): + """`execute in DIMENSION run tp` to x y z, onto a floor built once the level has loaded around it.""" + game('command', command=f'execute in {dimension} run tp @s {x + 0.5} {y} {z + 0.5}') + state = wait_dimension(game, dimension, 400) + game.wait(20) + level_floor(game, x, y, z) + game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + game.wait(20) + return state + + +def dims(host, guest): + return host('state').get('dimension'), guest('state').get('dimension') + + +def level_execute(host, guest, out): + """`execute in the_nether run tp` takes the guest alone.""" + x, z = (int(v // 1) for v in pos_of(guest)[::2]) + there = into_level(guest, NETHER, x, 100, z) + below = guest.raw('block', x, 99, z) + assert dims(host, guest) == (OVERWORLD, NETHER), f'host, guest in {dims(host, guest)}' + assert there.get('dimension') == NETHER and below.get('block') == 'minecraft:obsidian', f'{there} on {below}' + return {'guest': pos_of(guest)} + + +def level_ticking(host, guest, out): + """Mobs and objects fall in both levels at once (each level with a player ticks); every entity + has its own id across the levels.""" + gx, gy, gz = pos_of(guest) + hx, hy, hz = pos_of(host) + # A floor of its own beside the host (earlier checks may have broken the open one there). + bx, by, bz = int(hx // 1), int(hy // 1), int(hz // 1) + host('command', command=f'fill {bx - 4} {by - 1} {bz - 4} {bx + 4} {by - 1} {bz - 2} minecraft:stone') + host('command', command=f'fill {bx - 4} {by} {bz - 4} {bx + 4} {by + 4} {bz - 2} minecraft:air') + guest('command', command=f'summon minecraft:pig {gx + 2.5:.2f} {gy + 3:.2f} {gz:.2f}') + guest('command', command=f'summon minecraft:armor_stand {gx - 2.5:.2f} {gy + 3:.2f} {gz:.2f}') + host('command', command=f'summon minecraft:pig {hx + 2.5:.2f} {hy + 3:.2f} {hz - 3:.2f}') + host('command', command=f'summon minecraft:armor_stand {hx - 2.5:.2f} {hy + 3:.2f} {hz - 3:.2f}') + try: + guest.wait(60) + seen = {} + for name, g, floor in (('guest', guest, gy), ('host', host, hy)): + mobs = [m for m in g.raw('mobs', 8)['near'] if m['kind'] == 'minecraft:pig'] + stands = [o for o in g('status')['objects'] if o['kind'] == 'minecraft:armor_stand'] + seen[name] = {'pigs': [(m['id'], round(m['pos'][1], 2)) for m in mobs], + 'stands': [(o['id'], round(o['position'][1], 2)) for o in stands], 'floor': floor} + finally: + guest('command', command='kill @e[type=!minecraft:player,distance=..8]') + host('command', command='kill @e[type=!minecraft:player,distance=..8]') + for name, s in seen.items(): + heights = [y for _, y in s['pigs'] + s['stands']] + assert len(s['pigs']) == 1 and len(s['stands']) == 1, f'{name} sees {s}' + assert all(abs(y - s['floor']) < 0.1 for y in heights), f"{name}'s did not fall to the floor: {seen}" + ids = [i for s in seen.values() for i, _ in s['pigs'] + s['stands']] + assert len(set(ids)) == len(ids), f'ids shared across the levels: {seen}' + return seen + + +def level_rejoin(host, guest, out): + """The guest leaves in the Nether and joins again there (its player data keeps its level).""" + before = pos_of(guest) + port = host.raw('lan', 'status')['port'] + guest.raw('disconnect') + time.sleep(2) + guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME) + guest.raw('wait-for', 'loaded', '--timeout', 300) + guest.wait(20) + after = pos_of(guest) + assert dims(host, guest) == (OVERWORLD, NETHER), f'host, guest in {dims(host, guest)}' + assert all(abs(a - b) < 1 for a, b in zip(before, after)), f'left at {before}, back at {after}' + return {'at': after} + + +def level_death(host, guest, out): + """The guest dies in the Nether and respawns in the Overworld; the host stays where it is.""" + guest('command', command='kill @s') + guest.wait(20) + guest.raw('respawn') + back = wait_dimension(guest, OVERWORLD, 400) + guest.wait(20) + assert back.get('dimension') == OVERWORLD, f'the guest respawned in {back.get("dimension")}' + assert dims(host, guest) == (OVERWORLD, OVERWORLD), f'host, guest in {dims(host, guest)}' + return {'respawned': back['player']['position']} + + +def level_host_nether(host, guest, out): + """The host goes through a Nether portal while the guest stays in the Overworld.""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + nether_portal(host, hx, hy, hz - 3) + try: + host('command', command=f'tp @s {hx + 0.5} {hy} {hz - 2.5}') + there = wait_dimension(host, NETHER, 600) + host.wait(20) + result = dims(host, guest) + assert there.get('dimension') == NETHER, f'the host is in {there.get("dimension")}' + assert result == (NETHER, OVERWORLD), f'host, guest in {result}' + return {'host': there['player']['position']} + finally: + host('command', command=f'execute in {OVERWORLD} run fill {hx - 1} {hy} {hz - 3} {hx + 2} {hy + 3} {hz - 3} ' + 'minecraft:air') + host('command', command=f'execute in {OVERWORLD} run tp @s {hx + 0.5} {hy} {hz + 0.5}') + wait_dimension(host, OVERWORLD, 400) + + +def level_guest_end(host, guest, out): + """The guest steps into an End portal alone and lands on the obsidian platform; an exit portal + takes it back to the Overworld.""" + x, y, z = (int(v // 1) for v in pos_of(guest)) + guest('command', command=f'setblock {x + 2} {y} {z} minecraft:end_portal') + try: + guest('command', command=f'tp @s {x + 2.5} {y} {z + 0.5}') + wait_dimension(guest, END, 600) + # The arrival waits for the platform's chunks; its portal cooldown (10 ticks) runs out after, + # and a player who stands in a portal while it runs stays (Entity.setAsInsidePortal). + guest.wait(60) + landed = pos_of(guest) + assert dims(host, guest) == (OVERWORLD, END), f'host, guest in {dims(host, guest)}' + assert [int(v // 1) for v in landed] == [100, 49, 0], f'the guest landed at {landed}' + finally: + guest('command', command=f'execute in {OVERWORLD} run setblock {x + 2} {y} {z} minecraft:air') + ex, ey, ez = (int(v // 1) for v in landed) + guest('command', command=f'setblock {ex + 2} {ey} {ez} minecraft:end_portal') + guest('command', command=f'tp @s {ex + 2.5} {ey} {ez + 0.5}') + home = wait_dimension(guest, OVERWORLD, 600) + guest.wait(20) + assert dims(host, guest) == (OVERWORLD, OVERWORLD), f'host, guest in {dims(host, guest)}' + return {'landed': landed, 'home': home['player']['position']} + + +def level_reload(host, guest, out): + """The host saves and quits with the guest in the Nether, opens the world again and opens it to the + LAN; the guest joins again where it was, in the Nether.""" + x, z = (int(v // 1) for v in pos_of(guest)[::2]) + into_level(guest, NETHER, x, 100, z) + before = pos_of(guest) + host.raw('disconnect') + # The world saves on its server thread before the title screen shows. + for attempt in range(60): + time.sleep(1) + try: + host.raw('open', 'Lan') + break + except Failed: + if attempt == 59: + raise + host('wait_ready', seconds=400) + port = host.raw('lan', 'open', 0, 'commands')['port'] + back_to_game(guest) + guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME) + guest.raw('wait-for', 'loaded', '--timeout', 300) + guest.wait(20) + after = pos_of(guest) + assert dims(host, guest) == (OVERWORLD, NETHER), f'host, guest in {dims(host, guest)}' + assert all(abs(a - b) < 1 for a, b in zip(before, after)), f'left at {before}, back at {after}' + return {'at': after} + + +LEVEL_STEPS = [('execute', level_execute), ('ticking', level_ticking), ('rejoin', level_rejoin), + ('death', level_death), ('host_nether', level_host_nether), + ('guest_end', level_guest_end), ('reload', level_reload)] + + def check_damage(host, guest, out): guest('command', command='gamemode survival') guest.wait(10) @@ -2591,7 +2798,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, + 'levels': check_levels} def run(ctl, out, resources, checks): From 84171cfc94c048807520c426cf9a4af05aaf289f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:19:17 +0200 Subject: [PATCH 04/16] lan_e2e portals: wait for the guest to be placed in its Nether portal On a server the guest is held where it entered the Nether until the chunks around the destination are lit, then placed in its portal. The check read the guest's position 40 ticks after the dimension changed, which on a busy machine was still the held spot, and then stepped the guest out of a portal that wasn't there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- tools/lan_e2e.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 304668322..e781cdea6 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -496,12 +496,17 @@ def portals(host, guest, out, x, y, z, hx, hy, hz): 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) + # On a server the guest is held where it entered until the chunks around the destination are + # lit, then placed in its portal: wait for that before reading where it arrived. + for _ in range(30): + guest.wait(20) + arrived = [int(v // 1) for v in pos_of(guest)] + if guest.raw('block', *arrived).get('block') == 'minecraft:nether_portal': + break 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. From 9fe228cd1e2753e252f40a2f49150779316423cf Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:51:16 +0200 Subject: [PATCH 05/16] Server commands run in their source's level (execute in, execute at) On a server (dedicated, or single player's server thread) each dimension is its own level, but a command ran in whichever level was in place. So a guest in the Nether running `execute in minecraft:overworld run setblock ...` got "That position is not loaded", and `execute at <a player in another level>` used the wrong level's blocks. with_source now puts the source's level in place for the command (CommandSourceStack.getLevel), as as_target already does for a player in another level, and puts the old one back after. `execute at` takes the entity's level (withLevel(entity.level())), and a player's level is the guest's own (target_level) even while another level is in place. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/horizon-client/src/game/commands.rs | 32 +++++++++++-------- .../src/game/commands/execute.rs | 14 ++++++-- crates/horizon-client/src/game/levels.rs | 18 +++++++++++ docs/server-levels.md | 4 ++- tools/lan_e2e.py | 29 ++++++++++++++--- 5 files changed, 74 insertions(+), 23 deletions(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index f174f98c1..570a64c09 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -294,6 +294,18 @@ impl Game<'_> { } // ---- entities ------------------------------------------------------- + /// The level `t` is in (`Entity.level`): a server's players have their + /// own, which need not be the one in place; everything else is in the + /// level in place. + pub(super) fn target_level(&self, t: Target) -> Dim { + let conn = match t { + Target::Player => self.lan_acting, + Target::Guest(conn) => Some(conn), + _ => None, + }; + conn.and_then(|c| self.command_guest(c)) + .map_or(self.dim, |g| Dim::from_id(&g.dimension)) + } pub(super) fn target_position(&self, t: Target) -> Option<[f64; 3]> { match t { Target::Player => self @@ -1191,15 +1203,12 @@ impl Game<'_> { pos: [f64; 3], rotation: Option<[f32; 2]>, ) -> bool { - let (conn, at) = match t { - Target::Player => (self.lan_acting, self.dim), - Target::Guest(conn) => ( - Some(conn), - self.command_guest(conn) - .map_or(self.dim, |g| super::Dim::from_id(&g.dimension)), - ), - _ => (None, self.dim), + let conn = match t { + Target::Player => self.lan_acting, + Target::Guest(conn) => Some(conn), + _ => None, }; + let at = self.target_level(t); let Some(conn) = conn.filter(|_| at != level && self.options.dedicated.is_some()) else { return false; }; @@ -1222,12 +1231,7 @@ impl Game<'_> { let dest = self.entities(ctx, "destination", false)?[0]; let pos = self.target_position(dest).unwrap_or(self.source_position()); // Into the destination's level. - let level = match dest { - Target::Guest(conn) => self - .command_guest(conn) - .map_or(self.dim, |g| super::Dim::from_id(&g.dimension)), - _ => self.dim, - }; + let level = self.target_level(dest); // TeleportCommand.teleportToEntity: the destination's rotation too. let rotation = Some(self.target_rotation(dest)); for &t in &targets { diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 221ebb238..463cd542e 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -155,14 +155,20 @@ impl Game<'_> { _ => s.pos, } } - /// Evaluate `f` with `source` as the command source. + /// Evaluate `f` with `source` as the command source, in the source's + /// level (`CommandSourceStack.getLevel`): a server puts that level in + /// place for it. pub(in crate::game) fn with_source<T>( &mut self, source: Source, f: impl FnOnce(&mut Self) -> T, ) -> T { let previous = self.command_source.replace(source); + let back = self.enter_command_level(source.dimension); let out = f(self); + if let Some(back) = back { + self.enter_command_level(back); + } self.command_source = previous; out } @@ -447,11 +453,13 @@ impl Game<'_> { "at" => targets(self)? .into_iter() .filter_map(|t| { + // CommandSourceStack.withLevel(entity.level()). + let level = self.target_level(t); Some(Source { pos: self.target_position(t)?, rot: self.target_rotation(t), - dimension: self.dim, - level: None, + dimension: level, + level: (level != self.dim).then_some(level), ..s }) }) diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 7df5541b4..3b73a2e20 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -253,6 +253,24 @@ impl Game<'_> { Ok(()) } + /// Put `dim`'s level in place for a command whose source is there + /// (`execute in`, `execute at` a player in another level), opening it if + /// nobody is in it; returns the level to put back afterwards. Only a + /// server holds other levels. + pub(super) fn enter_command_level(&mut self, dim: Dim) -> Option<Dim> { + if self.options.dedicated.is_none() || dim == self.dim { + return None; + } + let back = self.dim; + match self.enter_level(None, dim) { + Ok(()) => Some(back), + Err(e) => { + log::error!("could not open {}: {e}", dim.id()); + None + } + } + } + /// 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 diff --git a/docs/server-levels.md b/docs/server-levels.md index 0190c0c03..45fbf03e3 100644 --- a/docs/server-levels.md +++ b/docs/server-levels.md @@ -20,6 +20,7 @@ the other dimensions' levels as `Parked` values and swaps one into place (`enter | `ServerPlayer.teleport` into another level | `server_travel.rs`: a Respawn packet, then the teleport once the destination has loaded (portals and `execute in … tp`) | | `PlayerList.respawn` | `guest_respawn`: back into the Overworld's level | | `ServerLevel.noPlayersEmptyTime`, chunk unloading | `close_idle_levels`: a level other than the Overworld with nobody in it for 300 ticks is saved and closed | +| `CommandSourceStack.getLevel` | `with_source` puts the source's level in place for a command (`execute in`, `execute at` a player in another level) | | the levels' shared `LevelData` | not swapped: game time, day time, weather, game rules, scoreboard, maps, entity ids (`next_entity`, unique across levels) | The packets of a guest are read in its own level's pass (`Hub::tick_level`), so its actions and @@ -70,7 +71,8 @@ the Nether, or whose host saves and quits, joins again in the Nether where it wa - `portals`: the guest goes to the Nether through a portal while the host stays. The host then goes to the End while the guest is in the Nether, so three levels run at once, and both come back. - `levels`, with the host and the guest each in a level of its own: - - `execute in the_nether run tp` moves the guest alone. + - `execute in the_nether run tp` moves the guest alone. From the Nether, `execute in overworld` and + `execute at` the host change and test blocks in the host's level. - Mobs and armour stands fall in two levels at once, and every entity id is unique across the levels. - The guest leaves in the Nether and joins again there. diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index e781cdea6..66297b909 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -67,10 +67,12 @@ address. The script then checks, from both sides, what a guest's game used to ge - 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. -- levels: (--server-thread) the host and the guest each in a level of their own: `execute in` builds - and teleports into another level, mobs fall in two levels at once with ids unique across - them, the guest rejoins in the Nether, dies there and respawns in the Overworld, the host - takes a Nether portal alone, the guest takes an End portal and the exit portal alone, and the host saves, quits and reopens with the guest in the Nether. +- levels: (--server-thread) the host and the guest each in a level of their own: `execute in` + teleports into another level, and `execute in` and `at` change and test blocks there; + mobs fall in two levels at once, with ids unique across them; the guest rejoins in the + Nether, dies there and respawns in the Overworld; the host takes a Nether portal alone; + the guest takes an End portal and the exit portal alone; and the host saves, quits and + reopens with the guest in the Nether. - commands: the guest's chat completes commands and their arguments over the server's command tree (Tab), and runs what it completed; - recipes: the guest's recipe book lists the planks recipe the logs unlock, and clicking it @@ -591,12 +593,29 @@ def dims(host, guest): def level_execute(host, guest, out): - """`execute in the_nether run tp` takes the guest alone.""" + """`execute in the_nether run tp` takes the guest alone. From the Nether, the guest's commands + reach the host's level (CommandSourceStack.getLevel): `execute in overworld` and `execute at` + the host put a block beside the host, and `execute if block` reads it.""" x, z = (int(v // 1) for v in pos_of(guest)[::2]) + hx, hy, hz = (int(v // 1) for v in pos_of(host)) there = into_level(guest, NETHER, x, 100, z) below = guest.raw('block', x, 99, z) + gold = f'{hx} {hy} {hz + 2} minecraft:gold_block' + try: + guest('command', command=f'execute in {OVERWORLD} run setblock {gold}') + guest('command', command=f'execute at {host.player} run setblock ~ ~ ~-2 minecraft:diamond_block') + guest('command', command=f'execute in {OVERWORLD} if block {gold} in {NETHER} ' + f'run setblock {x} 99 {z} minecraft:gold_block') + host.wait(10) + placed = [host.raw('block', hx, hy, hz + 2), host.raw('block', hx, hy, hz - 2)] + found = guest.raw('block', x, 99, z) + finally: + host('command', command=f'fill {hx} {hy} {hz - 2} {hx} {hy} {hz + 2} minecraft:air') assert dims(host, guest) == (OVERWORLD, NETHER), f'host, guest in {dims(host, guest)}' assert there.get('dimension') == NETHER and below.get('block') == 'minecraft:obsidian', f'{there} on {below}' + assert [p.get('block') for p in placed] == ['minecraft:gold_block', 'minecraft:diamond_block'], \ + f'beside the host: {placed}' + assert found.get('block') == 'minecraft:gold_block', f'execute in overworld if block: {found}' return {'guest': pos_of(guest)} From 86fdc720696f99f591b8f1519aedbab56340577d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:51:16 +0200 Subject: [PATCH 06/16] Server players go through End gateways handle_server_portal ignored End gateways, so on a server (dedicated, or single player's server thread) no player could use one: the in-frame game's gateway code moved only its own player. A gateway that is not cooling down now takes a server player at once (EndGatewayBlock.entityInside, triggerCooldown, setAsInsidePortal), within the End, keeping its motion and look (Relative.DELTA and ROTATION). An exact exit is reached straight away; otherwise the player waits at the destination while it loads, and the exit is found or built there (the in-frame resolve_gateway, shared through gateway_job). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/horizon-client/src/game/end.rs | 26 ++++++--- .../horizon-client/src/game/server_travel.rs | 57 ++++++++++++++++++- crates/horizon-client/src/lan/hub.rs | 21 ++++++- docs/server-levels.md | 4 +- tools/lan_e2e.py | 31 ++++++++-- 5 files changed, 117 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index a7813c767..08eb8ad33 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -23,7 +23,7 @@ const GATEWAY_FILE: &str = "horizon-end-gateways.json"; /// A gateway teleport waiting for its destination chunks. #[derive(Clone, Copy, Debug)] -enum GatewayJob { +pub(super) enum GatewayJob { /// TheEndGatewayBlockEntity.findOrCreateValidTeleportPos from this gateway. Find { gateway: [i32; 3] }, /// A known exit (exact, or findExitPosition around it). @@ -735,6 +735,20 @@ impl Game<'_> { fn enter_gateway(&mut self, gateway: [i32; 3]) -> Result<()> { // TheEndGatewayBlockEntity.triggerCooldown: 40 ticks. self.end.gateway_cooldown = 40; + let (job, destination) = self.gateway_job(gateway); + let Some(player) = self.player.take() else { + return Ok(()); + }; + self.end.job = Some(job); + self.end_travel = true; + self.travelling = Some((player, destination)); + Ok(()) + } + + /// Where `gateway` leads (TheEndGatewayBlockEntity.getPortalPosition): + /// its exit, or the search for one, and the spot to load before either + /// is resolved ([`Game::resolve_gateway`]). + pub(super) fn gateway_job(&mut self, gateway: [i32; 3]) -> (GatewayJob, Vec3) { let known = self.gateway_exits().get(&gateway).copied(); let job = match known { Some((exit, exact)) => GatewayJob::Known { exit, exact }, @@ -760,13 +774,7 @@ impl Game<'_> { Vec3::new(d.x, 75.0, d.y) } }; - let Some(player) = self.player.take() else { - return Ok(()); - }; - self.end.job = Some(job); - self.end_travel = true; - self.travelling = Some((player, destination)); - Ok(()) + (job, destination) } fn chunk_empty(&self, x: f64, z: f64) -> Option<bool> { @@ -803,7 +811,7 @@ impl Game<'_> { /// The teleport position of a gateway job, creating the exit gateway (and /// an island when the chunk has no landing spot) for new destinations. - fn resolve_gateway(&mut self, job: GatewayJob, target: Vec3) -> Result<Vec3> { + pub(super) fn resolve_gateway(&mut self, job: GatewayJob, target: Vec3) -> Result<Vec3> { let bottom_center = |p: [i32; 3]| { Vec3::new( f64::from(p[0]) + 0.5, diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index 1d857c1fe..b7462baa8 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -7,6 +7,7 @@ //! another level: a Respawn packet keeping all data, then a teleport to the //! exit once the destination has loaded around them. +use super::end::GatewayJob; use super::nether_portal::{PLAYER_DELAY, Plan}; use super::{Dim, Game, lan::LanHost}; use horizon_client::lan::hub::TickCtx; @@ -22,6 +23,9 @@ pub(super) struct Trip { end: bool, /// The Nether portal plan, whose exit is found or built on arrival. plan: Option<Plan>, + /// Through an End gateway, within the level: its exit, found or built + /// on arrival. + gateway: Option<GatewayJob>, /// Sent by a command: the player is already where it goes. placed: bool, } @@ -95,7 +99,7 @@ impl Game<'_> { if let Some(pos) = self.nether_portal_inside(at) { self.portals.player.set_inside(pos, PLAYER_DELAY); } - let (end_portal, _) = self.inside_end_portals(at, WIDTH, HEIGHT); + let (end_portal, gateway) = self.inside_end_portals(at, WIDTH, HEIGHT); if end_portal { if self.portals.player.cooldown == 0 { let target = if self.dim == Dim::End { @@ -109,6 +113,19 @@ impl Game<'_> { self.portals.player.cooldown = 10; return; } + // EndGatewayBlock.entityInside: a gateway that is not cooling down + // takes the player at once (no transition time) and cools down + // (triggerCooldown), even for a player still on its own cooldown. + if let Some(g) = gateway + && self.gateway_enter(g) + { + if self.portals.player.cooldown == 0 { + self.start_gateway_trip(host, conn, g); + } + // setPortalCooldown: after the trip, or again while cooling down. + self.portals.player.cooldown = 10; + return; + } let rule = if invulnerable { "players_nether_portal_creative_delay" } else { @@ -197,6 +214,7 @@ impl Game<'_> { target: destination, end, plan, + gateway: None, placed: false, }); if let Err(e) = self.enter_level(Some(host), source) { @@ -204,6 +222,32 @@ impl Game<'_> { } } + /// `TheEndGatewayBlockEntity.getPortalPosition` and the teleport within + /// the End (keeping the player's motion and look): straight to an exact + /// exit, else once the destination has loaded around the player, who + /// waits there (its exit is found among those blocks, or built). + fn start_gateway_trip(&mut self, host: &mut LanHost, conn: u32, gateway: [i32; 3]) { + let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return; + }; + let (job, destination) = self.gateway_job(gateway); + let at = [destination.x, destination.y, destination.z]; + // Relative.union(DELTA, ROTATION). + host.hub.teleport_keeping_motion(i, at); + if let GatewayJob::Known { exact: true, .. } = job { + return; + } + self.server_trips.push(Trip { + conn, + dim: self.dim, + target: destination, + end: false, + plan: None, + gateway: Some(job), + placed: false, + }); + } + /// 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. @@ -232,7 +276,15 @@ impl Game<'_> { } self.resolve_arrivals(); let yaw = host.hub.guests[i].yaw; - let (position, yaw) = if trip.end { + let (position, yaw) = if let Some(job) = trip.gateway { + match self.resolve_gateway(job, trip.target) { + Ok(at) => (at, yaw), + Err(e) => { + log::error!("End gateway exit: {e}"); + (trip.target, yaw) + } + } + } else if trip.end { match self.end_arrival(trip.target) { Ok((at, turned)) => (at, turned.unwrap_or(yaw)), Err(e) => { @@ -293,6 +345,7 @@ impl Game<'_> { target: Vec3::new(t.at[0], t.at[1], t.at[2]), end: false, plan: None, + gateway: None, placed: true, }); if let Err(e) = self.enter_level(Some(host), source) { diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index af0c1ac83..5be044e5d 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -818,6 +818,20 @@ impl Hub { /// ServerGamePacketListenerImpl.teleport: move the client and wait for its confirmation. pub fn teleport(&mut self, i: usize, position: Option<[f64; 3]>) { + self.teleport_relative(i, position, 0); + } + + /// A teleport to `position` that keeps the player's motion and look + /// (`Relative.DELTA` and `Relative.ROTATION`: an End gateway's). + pub fn teleport_keeping_motion(&mut self, i: usize, position: [f64; 3]) { + use play::relative::{DELTA_X, DELTA_Y, DELTA_Z, ROTATE_DELTA, X_ROT, Y_ROT}; + let relatives = Y_ROT | X_ROT | DELTA_X | DELTA_Y | DELTA_Z | ROTATE_DELTA; + self.teleport_relative(i, Some(position), relatives); + } + + /// ServerGamePacketListenerImpl.teleport with `relatives`: the rotation + /// and motion they name are sent as zero changes. + fn teleport_relative(&mut self, i: usize, position: Option<[f64; 3]>, relatives: i32) { let ticks = self.ticks; let g = &mut self.guests[i]; g.teleport_tick = ticks; @@ -828,13 +842,14 @@ impl Hub { g.teleport_counter = (g.teleport_counter + 1) & 0x7FFF_FFFF; let id = g.teleport_counter; g.awaiting_teleport = Some((id, g.position)); + let turn = relatives & (play::relative::Y_ROT | play::relative::X_ROT) != 0; g.send(&C::PlayerPosition(play::PlayerPosition { teleport: id, position: g.position, delta: [0.0; 3], - yaw: g.yaw, - pitch: g.pitch, - relatives: 0, + yaw: if turn { 0.0 } else { g.yaw }, + pitch: if turn { 0.0 } else { g.pitch }, + relatives, })); } diff --git a/docs/server-levels.md b/docs/server-levels.md index 45fbf03e3..eee730f89 100644 --- a/docs/server-levels.md +++ b/docs/server-levels.md @@ -17,7 +17,7 @@ the other dimensions' levels as `Parked` values and swaps one into place (`enter | `MinecraftServer.levels` | the level in place plus `Levels::parked` | | `MinecraftServer.tickChildren`, every level | `tick_server`: each level with a player in it, in Overworld, Nether, End order. The first pass reads the network and runs the shared parts (clock, weather, functions, autosave). | | `ServerLevel.players` | `Hub::here`: the guests whose `dimension` is the level in place | -| `ServerPlayer.teleport` into another level | `server_travel.rs`: a Respawn packet, then the teleport once the destination has loaded (portals and `execute in … tp`) | +| `ServerPlayer.teleport` into another level | `server_travel.rs`: a Respawn packet, then the teleport once the destination has loaded (portals and `execute in … tp`). An End gateway teleports within the End. | | `PlayerList.respawn` | `guest_respawn`: back into the Overworld's level | | `ServerLevel.noPlayersEmptyTime`, chunk unloading | `close_idle_levels`: a level other than the Overworld with nobody in it for 300 ticks is saved and closed | | `CommandSourceStack.getLevel` | `with_source` puts the source's level in place for a command (`execute in`, `execute at` a player in another level) | @@ -78,7 +78,7 @@ the Nether, or whose host saves and quits, joins again in the Nether where it wa - The guest leaves in the Nether and joins again there. - The guest dies in the Nether and respawns in the Overworld. - The host takes a Nether portal alone. - - The guest takes an End portal and then the exit portal alone. + - The guest takes an End portal, an End gateway and then the exit portal alone. - The host saves, quits and opens the world again with the guest in the Nether, and the guest joins again there. diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 66297b909..ddbec78af 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -71,8 +71,8 @@ address. The script then checks, from both sides, what a guest's game used to ge teleports into another level, and `execute in` and `at` change and test blocks there; mobs fall in two levels at once, with ids unique across them; the guest rejoins in the Nether, dies there and respawns in the Overworld; the host takes a Nether portal alone; - the guest takes an End portal and the exit portal alone; and the host saves, quits and - reopens with the guest in the Nether. + the guest takes an End portal, an End gateway and the exit portal alone; and the host + saves, quits and reopens with the guest in the Nether. - commands: the guest's chat completes commands and their arguments over the server's command tree (Tab), and runs what it completed; - recipes: the guest's recipe book lists the planks recipe the logs unlock, and clicking it @@ -699,8 +699,8 @@ def level_host_nether(host, guest, out): def level_guest_end(host, guest, out): - """The guest steps into an End portal alone and lands on the obsidian platform; an exit portal - takes it back to the Overworld.""" + """The guest steps into an End portal alone and lands on the obsidian platform, an End gateway + takes it across the End, and an exit portal takes it back to the Overworld.""" x, y, z = (int(v // 1) for v in pos_of(guest)) guest('command', command=f'setblock {x + 2} {y} {z} minecraft:end_portal') try: @@ -714,13 +714,32 @@ def level_guest_end(host, guest, out): assert [int(v // 1) for v in landed] == [100, 49, 0], f'the guest landed at {landed}' finally: guest('command', command=f'execute in {OVERWORLD} run setblock {x + 2} {y} {z} minecraft:air') - ex, ey, ez = (int(v // 1) for v in landed) + # A gateway far out with an exact exit at the End spawn, as end_gateway_return's + # (TheEndGatewayBlockEntity.getPortalPosition), takes the guest back there within the End. + guest('command', command='tp @s 700.5 80 0.5') + guest.wait(60) + level_floor(guest, 700, 80, 0) + guest('command', command='tp @s 700.5 80 0.5') + guest.wait(20) + guest('command', command='setblock 702 80 0 minecraft:end_gateway{exit_portal:[I;100,50,0],exact_teleport:1b}') + guest('command', command='tp @s 702.5 80 0.5') + gateway = None + for _ in range(20): + guest.wait(10) + gateway = pos_of(guest) + if abs(gateway[0] - 702.5) > 50: + break + assert dims(host, guest) == (OVERWORLD, END), f'host, guest in {dims(host, guest)}' + assert abs(gateway[0] - 100.5) < 1 and abs(gateway[2] - 0.5) < 1 and 49 <= gateway[1] <= 50, \ + f'the gateway left the guest at {gateway}' + guest.wait(40) + ex, ey, ez = (int(v // 1) for v in pos_of(guest)) guest('command', command=f'setblock {ex + 2} {ey} {ez} minecraft:end_portal') guest('command', command=f'tp @s {ex + 2.5} {ey} {ez + 0.5}') home = wait_dimension(guest, OVERWORLD, 600) guest.wait(20) assert dims(host, guest) == (OVERWORLD, OVERWORLD), f'host, guest in {dims(host, guest)}' - return {'landed': landed, 'home': home['player']['position']} + return {'landed': landed, 'gateway': gateway, 'home': home['player']['position']} def level_reload(host, guest, out): From 2ced9a451dcb900d73719308e86d740fd923306f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 12:51:16 +0200 Subject: [PATCH 07/16] Server players respawn at their point in the Nether (anchors, spawnpoint) A server's player (a LAN guest, and since the server thread the single player too) always respawned in the Overworld. Its respawn anchor was dropped when its action ended, and its save kept only an Overworld point. - The guest keeps a respawn point outside the Overworld (respawn_elsewhere, saved as the player's `respawn`) and has it in place while it acts, so an anchor it uses is its own. - guest_respawn respawns it in that point's level, waits there for the chunks, then resolves the point through its block (findRespawnAndUseSpawnBlock): beside the anchor, using a charge, or the world spawn and block.minecraft.spawn.not_valid when the block is gone. - `spawnpoint` in another level than the Overworld sets a forced point there (SetSpawnCommand) instead of Overworld coordinates, and a forced point that is no anchor holds where a player fits (isPossibleToRespawnInThis), in the window's own game too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/horizon-client/src/game.rs | 19 ++--- crates/horizon-client/src/game/commands.rs | 23 ++++-- crates/horizon-client/src/game/lan_actions.rs | 43 ++++++++--- .../horizon-client/src/game/respawn_anchor.rs | 41 +++++++++- .../horizon-client/src/game/server_travel.rs | 77 ++++++++++++++++++- crates/horizon-client/src/lan/guest.rs | 5 ++ crates/horizon-client/src/lan/playerdata.rs | 2 + docs/server-levels.md | 5 +- tools/lan_e2e.py | 48 +++++++++++- 9 files changed, 224 insertions(+), 39 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f706e9348..04c8d5ed1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7437,16 +7437,11 @@ impl Game<'_> { self.sleep_timer = 0; self.spawn = None; self.respawn_travel = None; - self.respawn_config = - self.level - .respawn_elsewhere - .as_ref() - .map(|(dim, pos, yaw, forced)| respawn_anchor::RespawnConfig { - dim: Dim::from_id(dim), - pos: *pos, - yaw: *yaw, - forced: *forced, - }); + self.respawn_config = self + .level + .respawn_elsewhere + .as_ref() + .map(respawn_anchor::RespawnConfig::from_saved); self.spawn_origin = None; self.spawn_spiral = Default::default(); self.player_spawn = None; @@ -9424,9 +9419,7 @@ impl Game<'_> { level.weather = self.world.weather; level.day_time = self.world.day_time; level.spawn = self.spawn.map(|s| [s.x, s.y, s.z]); - level.respawn_elsewhere = self - .respawn_config - .map(|c| (c.dim.id().to_owned(), c.pos, c.yaw, c.forced)); + level.respawn_elsewhere = self.respawn_config.map(|c| c.saved()); level.rotation = [self.yaw, self.pitch]; level.xp_level = self.experience.level; level.xp_progress = self.experience.progress; diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 570a64c09..c6877a839 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2285,12 +2285,23 @@ impl Game<'_> { }; let yaw = ((rot[0] + 180.0).rem_euclid(360.0)) - 180.0; let pitch = rot[1].clamp(-90.0, 90.0); - self.spawn = Some(Vec3::new( - f64::from(pos[0]) + 0.5, - f64::from(pos[1]), - f64::from(pos[2]) + 0.5, - )); - self.respawn_config = None; + // SetSpawnCommand: a forced point in the source's level. + if self.dim == Dim::Overworld { + self.spawn = Some(Vec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + )); + self.respawn_config = None; + } else { + self.spawn = None; + self.respawn_config = Some(super::respawn_anchor::RespawnConfig { + dim: self.dim, + pos, + yaw, + forced: true, + }); + } let dim = Text::literal(self.dim.id()); let p = pos.map(|v| Text::literal(v.to_string())); let mut args = vec![ diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index bc224da9e..60a403871 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -5,7 +5,7 @@ //! blocks, attacking and the commands all behave exactly as they do for the //! host, and every world change they cause reaches all players through the //! block log, the level events and the entity tracker. -use super::{Game, GuestUse, Hit, Mining, Screen, lan::LanHost}; +use super::{Game, GuestUse, Hit, Mining, Screen, lan::LanHost, respawn_anchor::RespawnConfig}; use horizon_client::{ command::vanilla, containers::BlockEntity, @@ -303,6 +303,7 @@ impl Game<'_> { g.spawn.map(|s| Vec3::new(s[0], s[1], s[2])), ); let respawn = (self.respawn_config.take(), self.level.spawn); + self.respawn_config = g.respawn_elsewhere.as_ref().map(RespawnConfig::from_saved); let message = self.message.take(); // The guest's own ender inventory; one the host has open goes back // into the host's while the guest acts. @@ -464,7 +465,8 @@ impl Game<'_> { let bed = std::mem::replace(&mut self.sleeping, sleeping); let guest_sleep_timer = std::mem::replace(&mut self.sleep_timer, sleep_timer); let guest_spawn = std::mem::replace(&mut self.spawn, spawn).map(|s| [s.x, s.y, s.z]); - (self.respawn_config, self.level.spawn) = respawn; + let guest_respawn = std::mem::replace(&mut self.respawn_config, respawn.0); + self.level.spawn = respawn.1; // ServerPlayer.displayClientMessage(_, true): the guest's action bar. let guest_message = std::mem::replace(&mut self.message, message); self.riding = riding; @@ -493,6 +495,7 @@ impl Game<'_> { let g = &mut host.hub.guests[i]; let fell_asleep = bed.is_some() && g.bed.is_none(); (g.bed, g.sleep_timer, g.spawn) = (bed, guest_sleep_timer, guest_spawn); + g.respawn_elsewhere = guest_respawn.map(|c| c.saved()); g.sleeping = g.bed.is_some(); if let Some((text, _)) = guest_message { g.send(&C::SystemChat(play::SystemChat { @@ -1417,17 +1420,32 @@ impl Game<'_> { if !host.hub.guests[i].dead { return; } - // PlayerList.respawn: a server's player comes back in the Overworld, - // where the world spawn is (respawn anchors and beds aside). + // PlayerList.respawn: a server's player comes back in its respawn + // point's level: the Overworld, where the world spawn and beds are, + // or another one's anchor or forced point, which its block resolves + // once the level has loaded around it. + let server = self.options.dedicated.is_some(); + let elsewhere = host.hub.guests[i] + .respawn_elsewhere + .as_ref() + .filter(|_| server) + .map(RespawnConfig::from_saved); + let level = elsewhere.map_or(super::Dim::Overworld, |c| c.dim); + let spawn = elsewhere.map_or(spawn, |c| { + [ + f64::from(c.pos[0]) + 0.5, + f64::from(c.pos[1]), + f64::from(c.pos[2]) + 0.5, + ] + }); let back = self.dim; - let away = self.options.dedicated.is_some() - && host.hub.guests[i].dimension != super::Dim::Overworld.id(); - if away { + let away = server && host.hub.guests[i].dimension != level.id(); + if server { 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; - } + } + if away && let Err(e) = self.enter_level(Some(host), level) { + log::error!("could not open {}: {e}", level.id()); + return; } let g = &mut host.hub.guests[i]; g.dead = false; @@ -1466,6 +1484,9 @@ impl Game<'_> { collision: Some(self.collision), }; host.hub.respawn(i, spawn, &ctx); + if let Some(config) = elsewhere { + self.respawn_trip(conn, config); + } if away && let Err(e) = self.enter_level(Some(host), back) { log::error!("could not reopen {}: {e}", back.id()); } diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index 4604c076f..9b6ecc203 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -31,6 +31,24 @@ pub(super) struct RespawnConfig { pub forced: bool, } +/// A respawn point as a player's save keeps it (`respawn`): dimension, +/// block, yaw and whether it is forced. +pub(super) type SavedRespawn = (String, [i32; 3], f32, bool); + +impl RespawnConfig { + pub(super) fn from_saved((dim, pos, yaw, forced): &SavedRespawn) -> Self { + Self { + dim: Dim::from_id(dim), + pos: *pos, + yaw: *yaw, + forced: *forced, + } + } + pub(super) fn saved(&self) -> SavedRespawn { + (self.dim.id().to_owned(), self.pos, self.yaw, self.forced) + } +} + /// `RespawnAnchorBlock.RESPAWN_HORIZONTAL_OFFSETS`, then the same a block /// below, a block above, and straight above. const HORIZONTAL: [[i32; 3]; 8] = [ @@ -415,6 +433,16 @@ impl Game<'_> { let (lz, hz) = (bounds.min(Axis::Z), bounds.max(Axis::Z) - 1.0e-5); (self.border.contains(lo, lz) && self.border.contains(hi, hz)).then_some(position) } + /// `Block.isPossibleToRespawnInThis`: neither solid nor liquid; banners, + /// signs and pressure plates override it to always. + fn possible_to_respawn_in(&self, state: BlockStateId) -> bool { + let f = self.res.facts().get(state); + let name = &*f.name; + name.ends_with("_banner") + || name.ends_with("_sign") + || name.ends_with("_pressure_plate") + || !(f.legacy_solid || matches!(name, "minecraft:water" | "minecraft:lava")) + } /// `RespawnAnchorBlock.findStandUpPosition`: a safe spot around the /// anchor, else any spot. pub(super) fn anchor_stand_up(&self, pos: [i32; 3]) -> Option<Vec3> { @@ -428,8 +456,9 @@ impl Game<'_> { } None } - /// `ServerPlayer.findRespawnAndUseSpawnBlock` for an anchor config in the - /// loaded dimension: the position and yaw, using a charge. + /// `ServerPlayer.findRespawnAndUseSpawnBlock` for a config in the loaded + /// dimension: the position and yaw, using an anchor's charge. A forced + /// point (`spawnpoint`) that is no anchor holds if a player fits in it. pub(super) fn find_respawn_and_use( &mut self, c: RespawnConfig, @@ -440,7 +469,13 @@ impl Game<'_> { && (c.forced || self.anchor_charges(state) > 0) && self.anchor_works()) { - return Ok(None); + let [x, y, z] = c.pos; + let free = c.forced + && !self.is_anchor(state) + && self.possible_to_respawn_in(state) + && self.possible_to_respawn_in(self.world.block(x, y + 1, z)); + let at = Vec3::new(f64::from(x) + 0.5, f64::from(y) + 0.1, f64::from(z) + 0.5); + return Ok(free.then_some((at, c.yaw))); } let stand = self.anchor_stand_up(c.pos); if !c.forced diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index b7462baa8..1b1ec3a6d 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -9,8 +9,9 @@ use super::end::GatewayJob; use super::nether_portal::{PLAYER_DELAY, Plan}; +use super::respawn_anchor::RespawnConfig; use super::{Dim, Game, lan::LanHost}; -use horizon_client::lan::hub::TickCtx; +use horizon_client::{lan::hub::TickCtx, text::Text}; use horizon_core::{geometry::Vec3, position::BlockPos}; /// A trip under way: the player is in the destination's level, whose @@ -26,6 +27,9 @@ pub(super) struct Trip { /// Through an End gateway, within the level: its exit, found or built /// on arrival. gateway: Option<GatewayJob>, + /// A respawn at this point outside the Overworld, resolved through its + /// block on arrival. + respawn: Option<RespawnConfig>, /// Sent by a command: the player is already where it goes. placed: bool, } @@ -215,6 +219,7 @@ impl Game<'_> { end, plan, gateway: None, + respawn: None, placed: false, }); if let Err(e) = self.enter_level(Some(host), source) { @@ -222,6 +227,64 @@ impl Game<'_> { } } + /// A respawned player waits at its point outside the Overworld for the + /// level to load around it. + pub(super) fn respawn_trip(&mut self, conn: u32, config: RespawnConfig) { + let [x, y, z] = config.pos; + self.server_trips.push(Trip { + conn, + dim: config.dim, + target: Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5), + end: false, + plan: None, + gateway: None, + respawn: Some(config), + placed: false, + }); + } + + /// `findRespawnAndUseSpawnBlock` for the player in place, at its point + /// in the level in place: where it stands up, facing the anchor, with + /// the deplete sound; else the point is forgotten + /// (`block.minecraft.spawn.not_valid`). + fn resolve_server_respawn(&mut self, config: RespawnConfig) -> Option<(Vec3, f32)> { + match self.find_respawn_and_use(config, true) { + Ok(Some((at, yaw))) => { + if !config.forced { + let [x, y, z] = config.pos.map(f64::from); + self.audio.play( + "minecraft:block.respawn_anchor.deplete", + Some([x, y, z]), + 1.0, + 1.0, + ); + } + Some((at, yaw)) + } + Ok(None) | Err(_) => { + self.respawn_config = None; + self.system_message(Text::translate("block.minecraft.spawn.not_valid", &[])); + None + } + } + } + + /// TeleportTransition.missingRespawnBlock: the world spawn, in the + /// Overworld. + fn respawn_at_world_spawn(&mut self, host: &mut LanHost, conn: u32) { + let at = self.level.world_spawn.map_or( + self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]), + |[x, y, z]| [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5], + ); + self.level_teleports.push(LevelTeleport { + conn, + dim: Dim::Overworld, + at, + rotation: None, + }); + self.run_level_teleports(host); + } + /// `TheEndGatewayBlockEntity.getPortalPosition` and the teleport within /// the End (keeping the player's motion and look): straight to an exact /// exit, else once the destination has loaded around the player, who @@ -244,6 +307,7 @@ impl Game<'_> { end: false, plan: None, gateway: Some(job), + respawn: None, placed: false, }); } @@ -276,7 +340,15 @@ impl Game<'_> { } self.resolve_arrivals(); let yaw = host.hub.guests[i].yaw; - let (position, yaw) = if let Some(job) = trip.gateway { + let (position, yaw) = if let Some(config) = trip.respawn { + match self.as_guest(host, trip.conn, |g| g.resolve_server_respawn(config)) { + Some(Some(found)) => found, + _ => { + self.respawn_at_world_spawn(host, trip.conn); + continue; + } + } + } else if let Some(job) = trip.gateway { match self.resolve_gateway(job, trip.target) { Ok(at) => (at, yaw), Err(e) => { @@ -346,6 +418,7 @@ impl Game<'_> { end: false, plan: None, gateway: None, + respawn: None, placed: true, }); if let Err(e) = self.enter_level(Some(host), source) { diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 4be5aa29f..6f939ac9d 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -86,6 +86,10 @@ pub struct Guest { /// Where the player respawns (a bed's spot; `ServerPlayer.respawnConfig`), /// None for the world spawn. pub spawn: Option<[f64; 3]>, + /// A respawn point outside the Overworld (a respawn anchor, or one + /// `spawnpoint` set there): its dimension, block, yaw and whether it is + /// forced, as the player's save keeps it (`respawn`). + pub respawn_elsewhere: Option<(String, [i32; 3], f32, bool)>, /// Pending ClientboundPlayerPositionPacket id; movement is ignored until /// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient). pub awaiting_teleport: Option<(i32, [f64; 3])>, @@ -242,6 +246,7 @@ impl Guest { sleep_timer: 0, sent_bed: None, spawn: None, + respawn_elsewhere: None, awaiting_teleport: None, teleport_counter: 0, teleport_tick: 0, diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 8797f25a2..24a4a9d65 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -72,6 +72,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.flying = level.flying; guest.selected = (level.selected_slot.max(0) as usize).min(8); guest.spawn = level.spawn.map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); + guest.respawn_elsewhere = level.respawn_elsewhere.clone(); guest.saved = level.player_extra.clone(); guest.recipe_book = level.recipe_book.clone(); guest.dimension = match level.dimension.as_str() { @@ -135,6 +136,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.flying = guest.flying; level.selected_slot = guest.selected as i32; level.spawn = guest.spawn.map(|s| [s[0] - 0.5, s[1], s[2] - 0.5]); + level.respawn_elsewhere = guest.respawn_elsewhere.clone(); level.on_ground = guest.on_ground; level.player_extra = guest.saved.clone(); level.recipe_book = guest.recipe_book.clone(); diff --git a/docs/server-levels.md b/docs/server-levels.md index eee730f89..a44f290c4 100644 --- a/docs/server-levels.md +++ b/docs/server-levels.md @@ -18,7 +18,7 @@ the other dimensions' levels as `Parked` values and swaps one into place (`enter | `MinecraftServer.tickChildren`, every level | `tick_server`: each level with a player in it, in Overworld, Nether, End order. The first pass reads the network and runs the shared parts (clock, weather, functions, autosave). | | `ServerLevel.players` | `Hub::here`: the guests whose `dimension` is the level in place | | `ServerPlayer.teleport` into another level | `server_travel.rs`: a Respawn packet, then the teleport once the destination has loaded (portals and `execute in … tp`). An End gateway teleports within the End. | -| `PlayerList.respawn` | `guest_respawn`: back into the Overworld's level | +| `PlayerList.respawn` | `guest_respawn`: into the respawn point's level, the Overworld unless the player has an anchor or a `spawnpoint` elsewhere (`Guest::respawn_elsewhere`), resolved through its block once that level has loaded | | `ServerLevel.noPlayersEmptyTime`, chunk unloading | `close_idle_levels`: a level other than the Overworld with nobody in it for 300 ticks is saved and closed | | `CommandSourceStack.getLevel` | `with_source` puts the source's level in place for a command (`execute in`, `execute at` a player in another level) | | the levels' shared `LevelData` | not swapped: game time, day time, weather, game rules, scoreboard, maps, entity ids (`next_entity`, unique across levels) | @@ -76,7 +76,8 @@ the Nether, or whose host saves and quits, joins again in the Nether where it wa - Mobs and armour stands fall in two levels at once, and every entity id is unique across the levels. - The guest leaves in the Nether and joins again there. - - The guest dies in the Nether and respawns in the Overworld. + - The guest dies in the Nether and respawns in the Overworld. With a `spawnpoint` and then a + respawn anchor set in the Nether, it respawns there, and the anchor loses a charge. - The host takes a Nether portal alone. - The guest takes an End portal, an End gateway and then the exit portal alone. - The host saves, quits and opens the world again with the guest in the Nether, and the guest diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index ddbec78af..dffa2bde0 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -70,7 +70,8 @@ address. The script then checks, from both sides, what a guest's game used to ge - levels: (--server-thread) the host and the guest each in a level of their own: `execute in` teleports into another level, and `execute in` and `at` change and test blocks there; mobs fall in two levels at once, with ids unique across them; the guest rejoins in the - Nether, dies there and respawns in the Overworld; the host takes a Nether portal alone; + Nether, dies there and respawns in the Overworld, then in the Nether at a `spawnpoint` + and at a respawn anchor set there; the host takes a Nether portal alone; the guest takes an End portal, an End gateway and the exit portal alone; and the host saves, quits and reopens with the guest in the Nether. - commands: the guest's chat completes commands and their arguments over the server's command @@ -679,6 +680,48 @@ def level_death(host, guest, out): return {'respawned': back['player']['position']} +def level_respawn_points(host, guest, out): + """Respawn points outside the Overworld (ServerPlayer.findRespawnAndUseSpawnBlock): a point + `spawnpoint` sets in the Nether (forced), then a charged respawn anchor the guest uses there, + each bring the guest back in the Nether; the anchor loses a charge.""" + home = pos_of(guest) + x, z = (int(v // 1) for v in home[::2]) + into_level(guest, NETHER, x, 100, z) + results = {} + try: + guest('command', command=f'spawnpoint @s {x} 100 {z}') + results['spawnpoint'] = die_and_respawn(guest) + guest('command', command=f'setblock {x + 2} 100 {z} minecraft:respawn_anchor[charges=2]') + guest.wait(10) + guest.raw('interact', x + 2, 100, z) + guest.wait(10) + results['anchor'] = die_and_respawn(guest) + results['charges'] = guest.raw('block', x + 2, 100, z).get('state') + finally: + sx, sy, sz = (int(v // 1) for v in pos_of(host)) + guest('command', command=f'execute in {OVERWORLD} run spawnpoint @s {sx} {sy} {sz}') + guest('command', command=f'execute in {NETHER} run setblock {x + 2} 100 {z} minecraft:air') + guest('command', command=f'execute in {OVERWORLD} run tp @s {home[0]:.2f} {home[1]:.2f} {home[2]:.2f}') + wait_dimension(guest, OVERWORLD, 400) + point, anchor = results['spawnpoint'], results['anchor'] + assert point[0] == NETHER and abs(point[1][0] - x - 0.5) < 0.6 and abs(point[1][2] - z - 0.5) < 0.6, \ + f'the spawnpoint brought the guest to {point}' + assert anchor[0] == NETHER and abs(anchor[1][0] - x - 2.5) < 2 and abs(anchor[1][2] - z - 0.5) < 2, \ + f'the anchor brought the guest to {anchor}' + assert 'charges=1' in (results['charges'] or ''), f'the anchor after the respawn: {results["charges"]}' + return results + + +def die_and_respawn(guest): + """Kill the guest and respawn it: the dimension and position it comes back at, once settled.""" + guest('command', command='kill @s') + guest.wait(20) + guest.raw('respawn') + guest.wait(80) + state = guest('state') + return state.get('dimension'), state['player']['position'] + + def level_host_nether(host, guest, out): """The host goes through a Nether portal while the guest stays in the Overworld.""" hx, hy, hz = (int(v // 1) for v in pos_of(host)) @@ -771,7 +814,8 @@ def level_reload(host, guest, out): LEVEL_STEPS = [('execute', level_execute), ('ticking', level_ticking), ('rejoin', level_rejoin), - ('death', level_death), ('host_nether', level_host_nether), + ('death', level_death), ('respawn_points', level_respawn_points), + ('host_nether', level_host_nether), ('guest_end', level_guest_end), ('reload', level_reload)] From 9f54087a8694a4d9b620240a93b29bad14020ef4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:04:29 +0200 Subject: [PATCH 08/16] Win screen: cover main's menu-blur match (Screen::Win) Main's Screen::blurs_background (in-world menu blur) has no arm for the new Screen::Win. WinScreen.extractBackground fills the screen with the End portal while the poem rolls and falls back to Screen.extractBackground (blurred) for the credits alone, so Game::menu_blur blurs only for the credits without the poem. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/horizon-client/src/game.rs | 3 ++- crates/horizon-client/src/game/screens.rs | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 9e06e12bb..8e4f96d46 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10061,7 +10061,8 @@ impl Game<'_> { }) || (self.title.is_none() && self.player.is_some() - && self.screen.blurs_background(self.pause_menu))); + && (self.screen.blurs_background(self.pause_menu) + || (self.screen == Screen::Win && self.win_screen_pauses())))); let radius = self.settings.menu_blur as f32; (blurred && radius >= 1.0).then_some(radius) } diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 07eacfb49..b2b869340 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -21,6 +21,9 @@ impl Screen { | Self::Inventory | Self::Dead | Self::CommandBlock => false, + // WinScreen.extractBackground: the poem fills the screen with the End portal, the + // credits alone blur. Game::menu_blur knows which one rolls. + Self::Win => false, } } } @@ -375,6 +378,7 @@ mod tests { Screen::Inventory, Screen::Dead, Screen::CommandBlock, + Screen::Win, ] { assert!(!screen.blurs_background(true)); assert!(!screen.blurs_background(false)); From 18bf8cd2ef0fda0582bf59540ade05d0ce5a9d27 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Fri, 23 Oct 2026 02:52:48 +0500 Subject: [PATCH 09/16] Minecarts push each other in their own ticks, as vanilla does OldMinecartBehavior.tick ends with pushAndPickupEntities: after a cart moves, every other cart in its box (0.2 wider) gets push(cart). Horizon pushed all pairs once before any cart moved, so carts placed inside each other stayed exactly overlapping (push skips distances under 1e-4) and never split apart. Pushes now run per cart, after its move, with pushOtherMinecart's Mth sin table facing and float thresholds. --- crates/horizon-client/src/game/minecarts.rs | 119 +++++++++++--------- 1 file changed, 68 insertions(+), 51 deletions(-) diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 756202530..b9d7f3893 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -16,7 +16,7 @@ use horizon_client::{ sound_engine::{CartSound, SoundEngine, SoundInstance, Sounds}, }; use horizon_core::{ - geometry::{Aabb, Vec3}, + geometry::{Aabb, Vec3, trig}, random::RandomSource, }; use horizon_world::registry::BlockStateId; @@ -683,8 +683,7 @@ impl Game<'_> { } } } - /// `AbstractMinecart.push(player)` when the player walks into a cart, - /// and carts pushing each other (`pushOtherMinecart`). + /// `AbstractMinecart.push(player)` when the player walks into a cart. fn push_carts(&mut self) { let player = self.player.as_ref().map(|p| p.position); let riding = self.riding; @@ -719,55 +718,71 @@ impl Game<'_> { } } } - for j in i + 1..self.carts.len() { - let (a, b) = (&self.carts[i], &self.carts[j]); - if !a - .bounds() - .inflate(Vec3::new(0.2, 0.0, 0.2)) - .intersects(b.bounds()) - { - continue; - } - let (mut xa, mut za) = (b.position.x - a.position.x, b.position.z - a.position.z); - let dd = xa * xa + za * za; - if dd < 1.0e-4 { - continue; - } - let d = dd.sqrt(); - let pow = (1.0 / d).min(1.0); - xa = xa / d * pow * f64::from(0.1f32) * 0.5; - za = za / d * pow * f64::from(0.1f32) * 0.5; - let dir = - glam::DVec2::new(b.position.x - a.position.x, b.position.z - a.position.z) - .normalize_or_zero(); - let r = a.yaw.to_radians(); - let facing = - glam::DVec2::new(f64::from(r.cos()), f64::from(r.sin())).normalize_or_zero(); - if dir.dot(facing).abs() < f64::from(0.8f32) { - continue; - } - let (ma, mb) = (a.velocity, b.velocity); - let (fa, fb) = (a.kind == CartKind::Furnace, b.kind == CartKind::Furnace); - let (na, nb) = if fb && !fa { - ( - Vec3::new(ma.x * 0.2 + mb.x - xa, ma.y, ma.z * 0.2 + mb.z - za), - Vec3::new(mb.x * 0.95, mb.y, mb.z * 0.95), - ) - } else if fa && !fb { - ( - Vec3::new(ma.x * 0.95, ma.y, ma.z * 0.95), - Vec3::new(mb.x * 0.2 + ma.x + xa, mb.y, mb.z * 0.2 + ma.z + za), - ) - } else { - let (xdd, zdd) = ((mb.x + ma.x) / 2.0, (mb.z + ma.z) / 2.0); - ( - Vec3::new(ma.x * 0.2 + xdd - xa, ma.y, ma.z * 0.2 + zdd - za), - Vec3::new(mb.x * 0.2 + xdd + xa, mb.y, mb.z * 0.2 + zdd + za), - ) - }; - self.carts[i].velocity = na; - self.carts[j].velocity = nb; + } + } + /// `OldMinecartBehavior.pushAndPickupEntities` for carts, at the end of + /// cart `i`'s own tick: each other cart in its box (0.2 wider on each + /// side) gets `push(cart i)`. Running it per cart, after that cart moved + /// and before the next one does, is what splits stacked carts apart. + fn push_from_cart(&mut self, i: usize) { + let reach = f64::from(0.2f32); + let hitbox = self.carts[i].bounds().inflate(Vec3::new(reach, 0.0, reach)); + for j in 0..self.carts.len() { + if j == i || !hitbox.intersects(self.carts[j].bounds()) { + continue; } + // AbstractMinecart.push(entity): `this` is cart j, `entity` cart i. + let (this, other) = (&self.carts[j], &self.carts[i]); + let (mut xa, mut za) = ( + other.position.x - this.position.x, + other.position.z - this.position.z, + ); + let dd = xa * xa + za * za; + if dd < f64::from(1.0e-4f32) { + continue; + } + let d = dd.sqrt(); + xa /= d; + za /= d; + let pow = (1.0 / d).min(1.0); + xa = xa * pow * f64::from(0.1f32) * 0.5; + za = za * pow * f64::from(0.1f32) * 0.5; + // pushOtherMinecart (old movement): only along this cart's facing. + let dir = glam::DVec2::new( + other.position.x - this.position.x, + other.position.z - this.position.z, + ) + .normalize_or_zero(); + let r = f64::from(this.yaw * 0.017453292f32); + let facing = glam::DVec2::new(f64::from(trig::cos(r)), f64::from(trig::sin(r))) + .normalize_or_zero(); + if dir.dot(facing).abs() < f64::from(0.8f32) { + continue; + } + let (mt, mo) = (this.velocity, other.velocity); + let (ft, fo) = ( + this.kind == CartKind::Furnace, + other.kind == CartKind::Furnace, + ); + let (nt, no) = if fo && !ft { + ( + Vec3::new(mt.x * 0.2 + (mo.x - xa), mt.y, mt.z * 0.2 + (mo.z - za)), + Vec3::new(mo.x * 0.95, mo.y, mo.z * 0.95), + ) + } else if !fo && ft { + ( + Vec3::new(mt.x * 0.95, mt.y, mt.z * 0.95), + Vec3::new(mo.x * 0.2 + (mt.x + xa), mo.y, mo.z * 0.2 + (mt.z + za)), + ) + } else { + let (xdd, zdd) = ((mo.x + mt.x) / 2.0, (mo.z + mt.z) / 2.0); + ( + Vec3::new(mt.x * 0.2 + (xdd - xa), mt.y, mt.z * 0.2 + (zdd - za)), + Vec3::new(mo.x * 0.2 + (xdd + xa), mo.y, mo.z * 0.2 + (zdd + za)), + ) + }; + self.carts[j].velocity = nt; + self.carts[i].velocity = no; } } /// Every cart but the ridden one (which ticks with its rider). @@ -794,6 +809,7 @@ impl Game<'_> { } if alive { self.carts[i] = c; + self.push_from_cart(i); i += 1; } else { self.carts.remove(i); @@ -867,6 +883,7 @@ impl Game<'_> { } if alive { self.carts[i] = c; + self.push_from_cart(i); } else { self.carts.remove(i); self.riding = None; From 18078e058d52e7aef20cea156326d3816ca61918 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Fri, 23 Oct 2026 03:47:04 +0500 Subject: [PATCH 10/16] Explosions hurt and push minecarts, so TNT minecarts chain ServerExplosion.hurtEntities skipped minecarts: a TNT minecart's blast never reached the carts beside it. Carts now take the explosion's damage through VehicleEntity.hurtServer (destroyed past 40, where MinecartTNT.destroy primes a TNT cart with a 0-39 tick fuse, as damageSourceIgnitesTnt counts explosions) and the knockback from their eyes. The exploding cart is the explosion's source, so it is removed before the blast and can't hit itself. Cart ticks now look carts up by id, since a blast can remove or prime other carts mid-loop. --- crates/horizon-client/src/game/explosion.rs | 30 ++++++++++++++++++++- crates/horizon-client/src/game/minecarts.rs | 30 ++++++++++++++------- 2 files changed, 50 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 5cf67f586..0923b4110 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -224,7 +224,7 @@ impl Game<'_> { } set.entries().map(|(k, _)| k.0).collect() } - /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT); + /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT, minecarts); /// the player takes `damage_type`. /// `ServerExplosion.hurtEntities` for the player: damage scaled by /// distance and exposure, through a raised shield (`hurtServer` blocks @@ -460,6 +460,34 @@ impl Game<'_> { ); } self.tnts = tnts; + // Minecarts: VehicleEntity.hurtServer (explosions ignite TNT carts), + // then the push from their eyes (0.85 of their height). + let ids: Vec<u32> = self.carts.iter().map(|c| c.id).collect(); + for id in ids { + let Some(i) = self.carts.iter().position(|c| c.id == id) else { + continue; + }; + let bounds = self.carts[i].bounds(); + let feet = self.carts[i].position; + let dist = distance([feet.x, feet.y, feet.z]) / diameter; + if dist > 1.0 { + continue; + } + let (lo, hi) = (bounds.min_position(), bounds.max_position()); + let exposure = self.seen_percent(center, [lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]); + self.hurt_cart(i, damage(dist, exposure), false, true); + let Some(c) = self.carts.iter_mut().find(|c| c.id == id) else { + continue; + }; + let eye_height = f64::from((hi.y - lo.y) as f32 * 0.85f32); + let dir = direction([feet.x, feet.y + eye_height, feet.z]); + let power = (1.0 - dist) * f64::from(exposure); + c.velocity = Vec3::new( + c.velocity.x + dir[0] * power, + c.velocity.y + dir[1] * power, + c.velocity.z + dir[2] * power, + ); + } } /// `Level.explode` on the server: positions, entities, blocks, fire; then /// the client's explosion sound. diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index b9d7f3893..9173139aa 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -637,6 +637,9 @@ impl Game<'_> { let r = self.world.random.next_double(); let power = (4.0 + r * 1.5 * speed) as f32; let at = [c.position.x, c.position.y, c.position.z]; + // The cart is the explosion's source: it is gone before the blast + // looks for entities, so it can't hit itself. + self.carts.retain(|x| x.id != c.id); let _ = self.server_explode(at, power, BlockInteraction::Destroy, false); } /// `MinecartHopper.suckInItems`: items above, into the five slots. @@ -792,14 +795,17 @@ impl Game<'_> { let ticking = self.entity_ticking_area(); // A server player's minecart moves with its rider (lan_vehicles.rs). let ridden = self.guest_vehicles(); - let mut i = 0; - while i < self.carts.len() { + // By id: an exploding cart can destroy or prime others mid-loop. + let ids: Vec<u32> = self.carts.iter().map(|c| c.id).collect(); + for id in ids { + let Some(i) = self.carts.iter().position(|c| c.id == id) else { + continue; + }; let p = self.carts[i].position; - if Some(self.carts[i].id) == self.riding - || ridden.contains(&self.carts[i].id) + if Some(id) == self.riding + || ridden.contains(&id) || !ticking(p.x.floor() as i32, p.z.floor() as i32) { - i += 1; continue; } let mut c = self.carts[i].clone(); @@ -807,10 +813,12 @@ impl Game<'_> { if c.kind == CartKind::Hopper { self.hopper_cart_pickup(&mut c); } + let Some(i) = self.carts.iter().position(|c| c.id == id) else { + continue; + }; if alive { self.carts[i] = c; self.push_from_cart(i); - i += 1; } else { self.carts.remove(i); } @@ -881,6 +889,10 @@ impl Game<'_> { p.velocity = Vec3::ZERO; p.fall_distance = 0.0; } + let Some(i) = self.carts.iter().position(|x| x.id == c.id) else { + self.riding = None; + return true; + }; if alive { self.carts[i] = c; self.push_from_cart(i); @@ -1138,8 +1150,8 @@ impl Game<'_> { } /// `VehicleEntity.hurtServer`: shake, add the damage, break past 40 (at /// once for creative players); TNT minecarts prime instead when moving - /// or hurt by fire. - fn hurt_cart(&mut self, i: usize, damage: f32, creative: bool, fire: bool) { + /// or hurt by fire or an explosion (`damageSourceIgnitesTnt`). + pub(super) fn hurt_cart(&mut self, i: usize, damage: f32, creative: bool, fire: bool) { let c = &mut self.carts[i]; c.hurt_dir = -c.hurt_dir; c.hurt_time = 10; @@ -1148,7 +1160,7 @@ impl Game<'_> { if destroyed { let mut c = self.carts.remove(i); let speed = c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z; - if c.kind == CartKind::Tnt && (fire || speed >= 0.01) { + if c.kind == CartKind::Tnt && (fire || speed >= f64::from(0.01f32)) { // MinecartTNT.destroy: prime instead of breaking. if c.fuse < 0 { self.prime_cart(&mut c); From 3f58e512e091751e95046504842054768ac3f2d8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 02:16:54 +0200 Subject: [PATCH 11/16] Options test: Credits & Attribution follows Horizon's two buttons main (#1271) pins Horizon Settings and Mods as the grid's last buttons; this branch adds Credits & Attribution after them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/horizon-client/src/options_ui.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 617c2ee9d..383946991 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -4184,9 +4184,13 @@ mod tests { }) .collect() }; - // Vanilla's ten Options buttons, the last two Horizon's. + // Vanilla's Options buttons, Horizon's two in the Telemetry and Credits slots, then + // Credits & Attribution (WinScreen's credits). let main = pushes(&mut ui); - assert_eq!(&main[main.len() - 2..], [Page::Horizon, Page::Mods]); + assert_eq!( + &main[main.len() - 3..], + [Page::Horizon, Page::Mods, Page::Credits] + ); ui.push(Page::Horizon); assert_eq!( pushes(&mut ui), From 7acebbae45fb84ec7c905e05f4ac4e4220914d0b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 04:23:58 +0200 Subject: [PATCH 12/16] Server players: the HUD's bubbles and golden hearts follow the server, absorption is saved, Nether lava pushes harder The server sends a player's own air supply and absorption amount (Entity.DATA_AIR_SUPPLY_ID, Player.DATA_PLAYER_ABSORPTION_ID) when they change, and the client applies them: on the server thread and as a LAN guest the breath meter follows the server's Respiration-extended air (#1304) and the golden hearts show (#1306). The connected client's tick sets the helmet's Respiration and the Nether's FAST_LAVA as the window's own tick does (#1309). AbsorptionAmount is written from the live body and read back on load, in the window's world and for a server's players (#1307). lan_e2e: absorption, breath and lava checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../horizon-client/src/attribute_updates.rs | 5 + crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/agent.rs | 2 + crates/horizon-client/src/game/lan.rs | 3 + crates/horizon-client/src/game/lan_actions.rs | 6 + crates/horizon-client/src/game/remote.rs | 31 ++++- crates/horizon-client/src/lan/guest.rs | 9 ++ crates/horizon-client/src/lan/hub.rs | 25 +++- crates/horizon-client/src/lan/playerdata.rs | 7 + crates/horizon-client/src/motion.rs | 2 + crates/horizon-client/src/save.rs | 10 +- tools/lan_e2e.py | 122 +++++++++++++++++- 12 files changed, 215 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/attribute_updates.rs b/crates/horizon-client/src/attribute_updates.rs index b81db5835..1dcc21028 100644 --- a/crates/horizon-client/src/attribute_updates.rs +++ b/crates/horizon-client/src/attribute_updates.rs @@ -22,6 +22,11 @@ impl PlayerMotion { pub fn refresh_attributes(&mut self) -> Result<()> { live_updates::refresh(self) } + /// `Player.internalSetAbsorptionAmount`: the amount as given, unclamped + /// (the saved `AbsorptionAmount`, or what a client's server sent). + pub fn internal_set_absorption(&mut self, value: f32) -> Result<()> { + self.store_absorption(value) + } } impl HealthWorld for PlayerMotion { type Error = Box<dyn std::error::Error>; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5da86dfaf..d689ad8fc 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9516,6 +9516,7 @@ impl Game<'_> { if let Some(p) = &self.player { level.position = Some([p.position.x, p.position.y, p.position.z]); level.health = p.health.health(); + level.absorption = p.health.absorption(); let extra = level .player_extra .get_or_insert_with(|| horizon_world::nbt::Tag::Compound(Default::default())); diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index ea686e711..b30adca5c 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -459,6 +459,8 @@ impl Game<'_> { "sneaking": self.keys.contains(&KeyCode::ShiftLeft), "sprinting": self.keys.contains(&KeyCode::ControlLeft), "health": p.health.health(), + "absorption": p.health.absorption(), + "air": p.air, "food": p.health.food.food, "saturation": p.health.food.saturation, "xp": { "level": self.experience.level, "progress": self.experience.progress, "total": self.experience.total }, diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 4e05ea600..0ea2a6faa 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -393,6 +393,9 @@ impl Game<'_> { "sneaking": g.sneaking, "sleeping": g.bed, "health": g.health, + // The server's body: its air supply and golden hearts. + "air": g.motion.as_ref().map(|m| m.air), + "absorption": g.motion.as_ref().map(|m| m.health.absorption()), // FoodData: food level, saturation and exhaustion. "food": [ f64::from(g.food), diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0d70b16f6..65cbf2e5f 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -217,6 +217,12 @@ impl Game<'_> { host.hub.guests[i].position[2], ); host.hub.guests[i].motion = PlayerMotion::new(self.motion, p).ok().map(Box::new); + // The saved golden hearts go on the first body of a player who + // has been here before. + let saved = host.hub.guests[i].saved_absorption.take(); + if let (Some(m), Some(amount)) = (host.hub.guests[i].motion.as_mut(), saved) { + let _ = m.internal_set_absorption(amount); + } let kept = host.hub.guests[i].logs_kept.take(); if let (Some(m), Some((hurts, attacks))) = (host.hub.guests[i].motion.as_mut(), kept) { m.hurt_log = hurts; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5461a4cd0..70096277f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1867,11 +1867,27 @@ impl Game<'_> { // player lies down in the bed, or gets up. if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { for (index, _, value) in &p.values { - if let (14, Value::OptPos(bed)) = (index, value) { - if bed.is_some() && self.sleeping.is_none() { - self.sleep_timer = 0; + match (index, value) { + (14, Value::OptPos(bed)) => { + if bed.is_some() && self.sleeping.is_none() { + self.sleep_timer = 0; + } + self.sleeping = *bed; } - self.sleeping = *bed; + // Entity.DATA_AIR_SUPPLY_ID and + // Player.DATA_PLAYER_ABSORPTION_ID: the bubbles + // and golden hearts the server's player has. + (1, Value::Int(air)) => { + if let Some(pl) = self.player.as_mut() { + pl.air = *air; + } + } + (17, Value::Float(amount)) => { + if let Some(pl) = self.player.as_mut() { + let _ = pl.internal_set_absorption(*amount); + } + } + _ => {} } } } @@ -2997,6 +3013,13 @@ impl Game<'_> { ); let was_flying = player.flying; player.yaw = self.yaw; + // As the window's own tick has them: the helmet's Respiration + // (decreaseAirSupply) and the dimension's FAST_LAVA, the Nether's + // stronger lava current. + player.respiration = self.armor[0] + .as_ref() + .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); + player.fluids.fast_lava = self.dim == Dim::Nether; let dead = self.screen == Screen::Dead; // LivingEntity.isImmobile: a sleeper lies still in the bed. if let Some(head) = self.sleeping { diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 1916344bb..3c5d4b50c 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -149,6 +149,9 @@ pub struct Guest { /// The ender chest inventory (`PlayerEnderChestContainer`, 27 slots). pub ender_items: Vec<Option<ItemStack>>, pub health: f32, + /// The saved `AbsorptionAmount`, until the player's first body on the + /// server takes it (the body holds the live amount). + pub saved_absorption: Option<f32>, pub food: i32, pub saturation: f32, pub xp_level: i32, @@ -168,6 +171,10 @@ pub struct Guest { /// `lastSentHealth`, `lastSentFood` and `lastFoodSaturationZero`. pub sent_health: Option<(f32, i32, bool)>, pub sent_xp: Option<(f32, i32, i32)>, + /// The air supply and absorption the player's client was last sent + /// (Entity.DATA_AIR_SUPPLY_ID, Player.DATA_PLAYER_ABSORPTION_ID); their + /// defaults until either changes. + pub sent_air: (i32, f32), /// Where the player last died (Player.lastDeathLocation), sent with the respawn. pub last_death: Option<[i32; 3]>, /// The last action sequence to acknowledge at the next tick (-1: none). @@ -280,6 +287,7 @@ impl Guest { craft_result: None, ender_items: vec![None; 27], health: 20.0, + saved_absorption: None, food: 20, saturation: 5.0, xp_level: 0, @@ -292,6 +300,7 @@ impl Guest { menu_state: 0, sent_health: None, sent_xp: None, + sent_air: (300, 0.0), last_death: None, ack_up_to: std::cell::Cell::new(-1), sent_selected: 0, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index bf66f979b..1455e60b8 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1755,6 +1755,27 @@ impl Hub { })); } } + // ServerEntity.sendDirtyEntityData: the air supply and the absorption + // amount the server's body changed go to the player, whose HUD draws + // them (bubbles, golden hearts). + let g = &mut self.guests[i]; + if let Some(m) = g.motion.as_ref() { + let now = (m.air, m.health.absorption()); + let mut values = Vec::new(); + if now.0 != g.sent_air.0 { + values.push((1, serializer::INT, Value::Int(now.0))); + } + if now.1.to_bits() != g.sent_air.1.to_bits() { + values.push((17, serializer::FLOAT, Value::Float(now.1))); + } + if !values.is_empty() { + g.sent_air = now; + g.send(&C::SetEntityData(play::SetEntityData { + id: g.entity_id, + values, + })); + } + } // Sent when the health or the food level changes, or the saturation // reaches or leaves zero; a dead player's health of 0 too. let g = &mut self.guests[i]; @@ -2465,9 +2486,11 @@ impl Hub { global: false, })); } - // lastSentExp, lastSentHealth and lastSentFood. + // lastSentExp, lastSentHealth and lastSentFood; the client's new + // player starts with the default air and no absorption. g.sent_health = None; g.sent_xp = None; + g.sent_air = (300, 0.0); let (cx, cz) = g.chunk(); g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { x: cx, diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 8797f25a2..6a26306fb 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -61,6 +61,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.head_yaw = guest.yaw; guest.on_ground = level.on_ground; guest.health = level.health; + guest.saved_absorption = Some(level.absorption); guest.food = level.food; guest.saturation = level.saturation; guest.xp_level = level.xp_level; @@ -123,6 +124,12 @@ pub fn store(guest: &Guest, level: &mut Level) { level.dimension = guest.dimension.clone(); level.rotation = [guest.yaw, guest.pitch]; level.health = guest.health; + level.absorption = guest + .motion + .as_ref() + .map_or(guest.saved_absorption.unwrap_or(0.0), |m| { + m.health.absorption() + }); level.food = guest.food; level.saturation = guest.saturation; level.xp_level = guest.xp_level; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 1920026b9..c0c882e0f 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -338,6 +338,8 @@ impl PlayerMotion { .and_then(|t| crate::save::number(t.get("Air"))) .unwrap_or(300) as i32; self.set_health(level.health, false)?; + // LivingEntity.readAdditionalSaveData: internalSetAbsorptionAmount. + self.internal_set_absorption(level.absorption)?; self.health.food.food = level.food; self.health.food.saturation = level.saturation; self.flying = level.flying; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0cfe3c585..2fbb04dc4 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2266,6 +2266,8 @@ pub struct Level { pub position: Option<[f64; 3]>, pub rotation: [f32; 2], pub health: f32, + /// LivingEntity `AbsorptionAmount`: the golden hearts left. + pub absorption: f32, pub food: i32, pub saturation: f32, /// (slot, item, count, damage): 0..36 inventory, 100..103 armor (feet..head), 150 offhand. @@ -2455,6 +2457,7 @@ impl Level { } self.motion = read_doubles::<3>(p.get("Motion")).unwrap_or_default(); self.health = f("Health").map_or(20.0, |v| v as f32); + self.absorption = f("AbsorptionAmount").map_or(0.0, |v| v as f32); self.food = n("foodLevel").map_or(20, |v| v as i32); self.saturation = f("foodSaturationLevel").map_or(5.0, |v| v as f32); self.food_exhaustion = f("foodExhaustionLevel").unwrap_or(0.0) as f32; @@ -2626,6 +2629,7 @@ impl Level { ("OnGround", Tag::Byte(i8::from(self.on_ground))), ("fall_distance", Tag::Double(self.fall_distance.to_bits())), ("Health", Tag::Float(self.health.to_bits())), + ("AbsorptionAmount", Tag::Float(self.absorption.to_bits())), ("foodLevel", Tag::Int(self.food)), ("foodSaturationLevel", Tag::Float(self.saturation.to_bits())), ( @@ -2731,7 +2735,6 @@ impl Level { ("seenCredits", Tag::Byte(0)), ("HurtTime", Tag::Short(0)), ("DeathTime", Tag::Short(0)), - ("AbsorptionAmount", Tag::Float(0)), ("FallFlying", Tag::Byte(0)), ] { map.entry(key.into()).or_insert(value); @@ -4114,6 +4117,7 @@ mod tests { position: Some([1.5, 70.0, -3.25]), rotation: [90.0, 10.0], health: 17.0, + absorption: 5.0, food: 15, saturation: 2.5, inventory: vec![ @@ -4144,6 +4148,7 @@ mod tests { assert_eq!(back.position, Some([1.5, 70.0, -3.25])); assert_eq!(back.rotation, [90.0, 10.0]); assert_eq!((back.health, back.food, back.saturation), (17.0, 15, 2.5)); + assert_eq!(back.absorption, 5.0); let mut inv = back.inventory.clone(); inv.sort(); assert_eq!( @@ -4178,10 +4183,13 @@ mod tests { let mut again = Level { player_extra: Some(extra), ender_items: ender, + // The live amount, not the one the loaded compound held (#1307). + absorption: 2.0, ..back }; again.write(&dir).unwrap(); let third = Level::read(&dir).unwrap(); + assert_eq!(third.absorption, 2.0); assert!(matches!( third .player_extra diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c5a90150f..a4fdafe71 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -131,6 +131,12 @@ address. The script then checks, from both sides, what a guest's game used to ge get off by sneaking; the other side sees the animal move. - lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the sky (on its server thread the host's window is a client of it too). +- absorption: the host and the guest each take Absorption II and a hit of 3: their own HUD has the + server's golden hearts, 8 then 5 (#1306). +- breath: the host and the guest each stay underwater for 15 s in a Respiration III helmet: their + own bubbles follow the server's air, which the enchantment makes last (#1304). +- lava: (--server-thread) the host and the guest each stand in a Nether lava current with Fire + Resistance, which pushes them at the Nether's strength (#1309). - flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: the guest, and on the server thread the host's window too, take what may fly from the server's abilities (ClientPacketListener.handlePlayerAbilities). @@ -172,7 +178,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', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'absorption', 'breath', 'lava'] class Game: @@ -2297,6 +2303,117 @@ def check_flight(host, guest, out): +def own(game): + """The player's own state, as its client has it.""" + return game('state')['player'] + + +def server_player(host, game): + """The player's entry on the server: the guest's in the host's `lan status`, on the server + thread the host's too; the host's own world otherwise.""" + if game is host and not SERVER_THREAD: + return own(host) + name = GUEST_NAME if game is not host else host.player + return next(g for g in host.raw('lan', 'status')['guests'] if g['name'] == name) + + +def check_absorption(host, guest, out): + """Absorption II's golden hearts on each player's own HUD: 8 of them, and 5 once a hit of 3 took + its share: the client shows what the server's player has (#1306).""" + seen = {} + for game in (host, guest): + game('command', command='gamemode survival') + game('command', command='effect give @s minecraft:absorption 120 1') + game.wait(10) + given = own(game)['absorption'] + game('command', command='damage @s 3 minecraft:generic') + game.wait(20) + me = own(game) + server = server_player(host, game) + game.shot(out, 'absorption') + game('command', command='effect clear @s minecraft:absorption') + seen[game.name] = {'given': given, 'left': me['absorption'], 'health': me['health'], + 'server': server.get('absorption')} + for name, s in seen.items(): + assert s['given'] == 8.0 and s['left'] == 5.0 == s['server'] and s['health'] == 20.0, \ + f'{name}: {seen}' + return seen + + +def check_breath(host, guest, out): + """Underwater in a Respiration III helmet for 15 s: the enchantment makes the air last on the + server, and each player's own bubbles follow the server's air (#1304).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + for game, dz in ((host, -4), (guest, 4)): + x, y, z = hx + 3, hy, hz + dz + game('command', command='gamemode survival') + game('command', command='item replace entity @s armor.head with ' + 'minecraft:diamond_helmet[minecraft:enchantments={"minecraft:respiration":3}]') + game('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:stone') + game('command', command=f'fill {x} {y} {z} {x} {y + 1} {z} minecraft:water') + game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + host.wait(300) + for game in (host, guest): + game.shot(out, 'breath') + seen[game.name] = {'own': own(game)['air'], 'server': server_player(host, game).get('air')} + for game, dz in ((host, -4), (guest, 4)): + x, y, z = hx + 3, hy, hz + dz + game('command', command='item replace entity @s armor.head with minecraft:air') + host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:air') + host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y - 1} {z + 1} minecraft:stone') + guest.wait(40) + # 300 ticks lose about 75 of the 300 with Respiration III, all of it without. + for name, s in seen.items(): + assert s['server'] > 150 and abs(s['own'] - s['server']) <= 10, f'{name}: {seen}' + return seen + + +def check_lava(host, guest, out): + """(--server-thread) Standing in a settled Nether lava current with Fire Resistance: the + Nether's FAST_LAVA pushes each player about three times as hard as the Overworld's (#1309).""" + if not SERVER_THREAD: + return 'skipped (needs --server-thread)' + seen = {} + back = {g.name: pos_of(g) for g in (host, guest)} + try: + for game, z in ((host, 0), (guest, 6)): + game('command', command=f'execute in minecraft:the_nether run tp @s 0.5 100 {z + 0.5}') + state = wait_dimension(game, 'minecraft:the_nether', 600) + assert state.get('dimension') == 'minecraft:the_nether', f'{game.name} is in {state.get("dimension")}' + game.wait(40) + # A one-wide obsidian channel along x: a source at x = -3, the current flowing east. + game('command', command=f'fill -5 98 {z - 2} 6 104 {z + 2} minecraft:air') + game('command', command=f'fill -5 98 {z - 1} 6 98 {z + 1} minecraft:obsidian') + game('command', command=f'fill -5 99 {z - 1} 6 99 {z - 1} minecraft:obsidian') + game('command', command=f'fill -5 99 {z + 1} 6 99 {z + 1} minecraft:obsidian') + game('command', command=f'fill -4 99 {z} -4 99 {z} minecraft:obsidian') + game('command', command='effect give @s minecraft:fire_resistance 120 0 true') + game('command', command='gamemode survival') + game('command', command=f'setblock -3 99 {z} minecraft:lava') + host.wait(100) + for game, z in ((host, 0), (guest, 6)): + game('command', command=f'tp @s 0.5 99 {z + 0.5}') + host.wait(60) + for game, z in ((host, 0), (guest, 6)): + v = own(game)['velocity'] + seen[game.name] = {'vx': v[0], 'level': game.raw('block', 0, 99, z).get('state')} + game.shot(out, 'lava') + finally: + for game, z in ((host, 0), (guest, 6)): + host('command', command=f'execute in minecraft:the_nether run fill -5 98 {z - 2} 6 104 {z + 2} minecraft:air') + x, y, zz = back[game.name] + game('command', command='effect clear @s minecraft:fire_resistance') + game('command', command=f'execute in minecraft:overworld run tp @s {x:.2f} {y:.2f} {zz:.2f}') + for game in (host, guest): + wait_dimension(game, 'minecraft:overworld', 600) + guest.wait(40) + # The Overworld's current settles at about 0.0047 a tick, the Nether's at about 0.014. + for name, s in seen.items(): + assert s['vx'] > 0.009, f'{name}: {seen}' + return seen + + def check_ladder(host, guest, out): """#1255: climbing down a ladder doesn't hurt where the guest lands.""" x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -3075,7 +3192,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'absorption': check_absorption, 'breath': check_breath, 'lava': check_lava} def run(ctl, out, resources, checks): From ed28e1dd0d6f6959179ba5f1914cfb69de14d1ae Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 04:56:08 +0200 Subject: [PATCH 13/16] Contact damage: magma, cactus, lit campfires and sweet berry bushes hurt in both modes Entity.applyEffectsFromBlocks: MagmaBlock.stepOn burns a player standing on it who is not sneaking (hot_floor, 1), CactusBlock and CampfireBlock.entityInside hurt what touches them (cactus 1, campfire 1, soul campfire 2, lit only). A server's players (LAN guests, and the host on the server thread) now get these and the grown sweet berry bush prick along the moves their client sent that tick: the server rebuilds the tick's movement history and runs the damage half of the block effects. lan_e2e `contacts`: magma, sneaking on magma, a lit campfire, a cactus, grown and young berry bushes, for the host and the guest. Fixes #1305, #1311, #1312, #1313. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/horizon-client/src/game/lan_actions.rs | 25 +++++++ crates/horizon-client/src/motion.rs | 73 ++++++++++++++++++- .../horizon-client/src/motion/environment.rs | 2 +- tools/lan_e2e.py | 64 +++++++++++++++- 4 files changed, 158 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0d70b16f6..9d1181b80 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1765,6 +1765,7 @@ impl Game<'_> { } let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height()); let at = g.position; + let sneaking = g.sneaking; let sounds = self.as_guest(host, conn, |game| { let (rules, motion) = (game.world.health_rules, game.motion); let health = &motion.health; @@ -1783,6 +1784,26 @@ impl Game<'_> { let _ = w.fluid_base_tick(); w.player.ground.on_ground = from_ground; let travelled: Vec<[f64; 3]> = moves.iter().map(|m| m.0).collect(); + // Entity.move's movementThisTick: each move, from where the + // tick's first one started. + let end = w.player.position; + let start = travelled + .iter() + .fold(end, |p, d| p.subtract(Vec3::new(d[0], d[1], d[2]))); + w.player.history.clear(); + let mut from = start; + for d in &travelled { + let delta = Vec3::new(d[0], d[1], d[2]); + let to = from.add_vector(delta); + w.player + .history + .add(horizon_world::entity_move::MovementRecord { + from, + to, + original: Some(delta), + }); + from = to; + } for (moved, on_ground) in moves { let movement = Vec3::new(moved[0], moved[1], moved[2]); if w.player.ground.on_ground && !on_ground && moved[1] > 0.0 { @@ -1808,6 +1829,10 @@ impl Game<'_> { if w.climbable().unwrap_or(false) { w.player.fall_distance = 0.0; } + // Entity.applyEffectsFromBlocks along those moves: magma, cactus, + // lit campfires and grown sweet berry bushes hurt (#1305). + w.player.shift_key_down = sneaking; + let _ = w.server_block_damage(start); let _ = w.tick_environment_damage(); let _ = w.apply_fire_contact(); let _ = w.server_hazards_tick(in_wall); diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 1920026b9..8831a5912 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -1029,9 +1029,22 @@ impl MotionWorld<'_, '_, '_> { } /// `Entity.applyEffectsFromBlocks` for the blocks Horizon's player reacts /// to inside its movement path: powder snow (`PowderSnowBlock.entityInside` - /// and the FREEZE / EXTINGUISH effects), cobwebs and sweet berry bushes. Pressure plates, tripwires and - /// rails are the world tick's scan. + /// and the FREEZE / EXTINGUISH effects), cobwebs, sweet berry bushes, + /// cactus and lit campfires, and the magma block it stands on + /// (`stepOn`). Pressure plates, tripwires and rails are the world tick's + /// scan. pub fn apply_effects_from_blocks(&mut self) -> Result<()> { + self.effects_from_blocks(false) + } + /// What `applyEffectsFromBlocks` does to a server's player along the + /// moves its client sent since `from` (in its history): the damage of + /// magma, cactus, lit campfires and grown sweet berry bushes. Its client + /// moves it, so the slowing and the rest are the client's. + pub fn server_block_damage(&mut self, from: Vec3) -> Result<()> { + self.player.old_position = from; + self.effects_from_blocks(true) + } + fn effects_from_blocks(&mut self, damage_only: bool) -> Result<()> { use horizon_world::entity_move::MovementRecord; let mut movements: Vec<MovementRecord> = self.player.history.records().iter().copied().collect(); @@ -1056,6 +1069,19 @@ impl MotionWorld<'_, '_, '_> { if self.player.spectator { return Ok(()); } + // Block.stepOn for the block under an entity on the ground: + // MagmaBlock's hot floor hurts unless it steps carefully (sneaks). + if self.player.ground.on_ground { + let on = self.legacy_on_position()?; + let magma = self + .assets + .registry + .state(self.block(on)) + .is_some_and(|s| s.name == "minecraft:magma_block"); + if magma && !self.player.shift_key_down { + self.environment_hurt("minecraft:hot_floor", 1.0)?; + } + } let mut visited = std::collections::HashSet::new(); let mut entered = Vec::new(); for movement in &movements { @@ -1081,6 +1107,7 @@ impl MotionWorld<'_, '_, '_> { &mut visited, &mut entered, budget, + damage_only, )?; from = to; } @@ -1093,11 +1120,19 @@ impl MotionWorld<'_, '_, '_> { &mut visited, &mut entered, 16, + damage_only, )?; } } if budget <= 0 { - self.check_inside_blocks(movement.to, movement.to, &mut visited, &mut entered, 1)?; + self.check_inside_blocks( + movement.to, + movement.to, + &mut visited, + &mut entered, + 1, + damage_only, + )?; } } // InsideBlockEffectApplier.StepBasedCollector: the blocks entered @@ -1137,6 +1172,7 @@ impl MotionWorld<'_, '_, '_> { visited: &mut std::collections::HashSet<i64>, entered: &mut Vec<(i32, BlockPos)>, max_iterations: i32, + damage_only: bool, ) -> Result<i32> { let deflated = self.player.dimensions.bounds(to).deflate(Vec3::new( f64::from(1.0e-5_f32), @@ -1213,6 +1249,33 @@ impl MotionWorld<'_, '_, '_> { } }; if inside && visited.insert(p.pack()) { + // CactusBlock and CampfireBlock.entityInside (`entity.hurt`). + match name { + "minecraft:cactus" => self.environment_hurt("minecraft:cactus", 1.0)?, + "minecraft:campfire" | "minecraft:soul_campfire" => { + let lit = self + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("lit")) + .is_some_and(|v| v == "true"); + let damage = if name == "minecraft:campfire" { + 1.0 + } else { + 2.0 + }; + if lit { + self.environment_hurt("minecraft:campfire", damage)?; + } + } + "minecraft:sweet_berry_bush" if damage_only => { + self.sweet_berry_bush_damage(state)?; + } + _ => {} + } + if damage_only { + continue; + } match name { "minecraft:powder_snow" => { self.powder_snow_inside(p)?; @@ -1261,6 +1324,10 @@ impl MotionWorld<'_, '_, '_> { /// is at least 0.003 on X or Z. fn sweet_berry_bush_inside(&mut self, state: BlockStateId) -> Result<()> { self.make_stuck_in_block(Vec3::new(f64::from(0.8_f32), 0.75, f64::from(0.8_f32))); + self.sweet_berry_bush_damage(state) + } + /// The server's half of `SweetBerryBushBlock.entityInside`: the prick. + fn sweet_berry_bush_damage(&mut self, state: BlockStateId) -> Result<()> { let age = self .assets .registry diff --git a/crates/horizon-client/src/motion/environment.rs b/crates/horizon-client/src/motion/environment.rs index a9bb33678..fc3c63c77 100644 --- a/crates/horizon-client/src/motion/environment.rs +++ b/crates/horizon-client/src/motion/environment.rs @@ -6,7 +6,7 @@ use horizon_world::{ living_fluid::{LivingFluidWorld, TravelFluidTag}, }; impl MotionWorld<'_, '_, '_> { - fn environment_hurt(&mut self, source: &str, damage: f32) -> Result<()> { + pub(super) fn environment_hurt(&mut self, source: &str, damage: f32) -> Result<()> { if self.player.invulnerable || self.player.spectator { return Ok(()); } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c5a90150f..4226f8521 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -131,6 +131,9 @@ address. The script then checks, from both sides, what a guest's game used to ge get off by sneaking; the other side sees the animal move. - lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the sky (on its server thread the host's window is a client of it too). +- contacts: the host and the guest each stand on magma (and sneak on it), stand on a lit campfire, + walk against a cactus and through grown sweet berry bushes: the server hurts them, but + not the sneaking player or young bushes (#1305, #1311, #1312, #1313). - flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: the guest, and on the server thread the host's window too, take what may fly from the server's abilities (ClientPacketListener.handlePlayerAbilities). @@ -172,7 +175,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', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'contacts'] class Game: @@ -2297,6 +2300,62 @@ def check_flight(host, guest, out): +def own(game): + """The player's own state, as its client has it.""" + return game('state')['player'] + + +def check_contacts(host, guest, out): + """Blocks that hurt what touches them, on the server: standing on magma (but not sneaking on it) + and on a lit campfire, walking against a cactus and through grown sweet berry bushes, for the + host and the guest (#1305, #1311, #1312, #1313); a young bush pricks no one.""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + host('command', command='gamerule natural_health_regeneration false') + seen = {} + try: + for game, dz in ((host, -4), (guest, 4)): + x, y, z = hx + 2, hy, hz + dz + game('command', command='gamemode survival') + game('command', command='effect clear @s') + for case, blocks, walk in ( + ('magma', [(0, -1, 'minecraft:magma_block')], False), + ('sneaking', [(0, -1, 'minecraft:magma_block')], False), + ('campfire', [(0, 0, 'minecraft:campfire[lit=true]')], False), + ('cactus', [(2, -1, 'minecraft:sand'), (2, 0, 'minecraft:cactus')], True), + ('berries', [(k, -1, 'minecraft:grass_block') for k in range(1, 4)] + + [(k, 0, 'minecraft:sweet_berry_bush[age=3]') for k in range(1, 4)], True), + ('young', [(k, -1, 'minecraft:grass_block') for k in range(1, 4)] + + [(k, 0, 'minecraft:sweet_berry_bush[age=0]') for k in range(1, 4)], True)): + game('command', command='effect give @s minecraft:instant_health 1 5 true') + game('command', command=f'fill {x - 1} {y - 2} {z - 1} {x + 4} {y - 1} {z + 1} minecraft:stone') + game('command', command=f'fill {x - 1} {y} {z - 1} {x + 4} {y + 2} {z + 1} minecraft:air') + # A wall ends the walk before the player leaves the floor. + game('command', command=f'fill {x + 5} {y - 1} {z - 1} {x + 5} {y + 2} {z + 1} minecraft:stone') + for dx, dy, block in blocks: + game('command', command=f'setblock {x + dx} {y + dy} {z} {block}') + stand = 0.5 if case == 'campfire' else 0.0 + game('command', command=f'tp @s {x + 0.5} {y + stand} {z + 0.5}') + game.raw('look-at', f'{x + 10:.2f}', f'{y + 1.6:.2f}', f'{z + 0.5:.2f}') + game.wait(30) + before = own(game)['health'] + keys = (['shift'] if case == 'sneaking' else []) + (['w'] if walk else []) + for k in keys: + game.raw('key', k, 'down') + game.wait(60) + for k in keys: + game.raw('key', k, 'up') + game.wait(10) + seen[f'{game.name}-{case}'] = (before, own(game)['health']) + game.shot(out, f'contacts-{case}') + host('command', command=f'fill {x - 1} {y} {z - 1} {x + 5} {y + 2} {z + 1} minecraft:air') + finally: + host('command', command='gamerule natural_health_regeneration true') + for case, (before, after) in seen.items(): + safe = case.endswith(('sneaking', 'young')) + assert (after == before) if safe else (after < before), f'{case}: {before} -> {after} (all: {seen})' + return seen + + def check_ladder(host, guest, out): """#1255: climbing down a ladder doesn't hurt where the guest lands.""" x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -3075,7 +3134,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'contacts': check_contacts} def run(ctl, out, resources, checks): From 2898b40670eb253a924560d5edfe8c3a4256a725 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 04:58:56 +0200 Subject: [PATCH 14/16] Server players: an axe-disabled shield stays down 5 s, death forgets the digging ItemCooldowns ticks once a tick for each player: a server's players count their shield cooldown down in tick_guests, and the host's world in tick_world (it was in tick_using, which ran for the host and again for every guest's swap, so a guest's shield came back early on the server thread). A guest that dies stops digging (its mining, the delay and the crack go), so the block it was breaking doesn't break once it respawns. lan_e2e: `shield` (a vindicator's axe disables each player's shield; the server's cooldown then falls 40 in 40 ticks) and `deathmining` (die while breaking obsidian, respawn, the obsidian stays). `lan status` and the agent state report the shield cooldown. Fixes #1315, #1316. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/horizon-client/src/game.rs | 5 +- crates/horizon-client/src/game/agent.rs | 1 + crates/horizon-client/src/game/lan.rs | 2 + crates/horizon-client/src/game/lan_actions.rs | 30 ++++ tools/lan_e2e.py | 133 +++++++++++++++++- 5 files changed, 167 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5da86dfaf..f15b6e9f6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3581,8 +3581,6 @@ impl Game<'_> { } } fn tick_using(&mut self) { - // ItemCooldowns.tick for the shield. - self.shield_cooldown = self.shield_cooldown.saturating_sub(1); let Some(hand) = self.used_hand() else { return; }; @@ -4285,6 +4283,9 @@ impl Game<'_> { fn tick_world(&mut self, running: bool) -> Result<()> { self.update_chunk_tickets(); horizon_client::spans::time("tick_effects", || self.tick_effects()); + // Player.tick's ItemCooldowns.tick for the window's player (a + // server's players count theirs down in `tick_guests`). + self.shield_cooldown = self.shield_cooldown.saturating_sub(1); horizon_client::spans::time("tick_using", || self.tick_using()); horizon_client::spans::time("tick_hud", || self.tick_hud()); // The player's digging comes in with its packets, before the level diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index ea686e711..f9a8e8c04 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -461,6 +461,7 @@ impl Game<'_> { "health": p.health.health(), "food": p.health.food.food, "saturation": p.health.food.saturation, + "shield_cooldown": self.shield_cooldown, "xp": { "level": self.experience.level, "progress": self.experience.progress, "total": self.experience.total }, "effects": self.potions.effects.list.iter().map(|e| json!({ "id": e.id, "duration_ticks": e.duration, "amplifier": e.amplifier })).collect::<Vec<_>>(), }) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 4e05ea600..f09d2cc22 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -390,6 +390,8 @@ impl Game<'_> { "placed": g.placed, "loaded": g.loaded, "game_mode": g.game_mode, + // ItemCooldowns: the ticks the shield an axe disabled stays down. + "shield_cooldown": h.play.get(&g.conn).map_or(0, |p| p.shield_cooldown), "sneaking": g.sneaking, "sleeping": g.bed, "health": g.health, diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0d70b16f6..4cf5d0a0e 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -34,6 +34,8 @@ pub(super) struct GuestPlay { destroy_delay: u32, using: Option<(usize, u32)>, use_delay: u32, + /// The shield's ItemCooldowns entry: an axe disabled it for this many ticks. + pub(super) shield_cooldown: u32, attack_ticks: u32, /// The main hand's item at the guest's last tick (`Game::attack_item`). attack_item: Option<std::sync::Arc<str>>, @@ -117,6 +119,7 @@ pub(super) struct GuestSwap { destroy_delay: u32, using: Option<(usize, u32)>, use_delay: u32, + pub(super) shield_cooldown: u32, attack_ticks: u32, attack_item: Option<std::sync::Arc<str>>, swing: horizon_client::first_person::SwingState, @@ -290,6 +293,7 @@ impl Game<'_> { let destroy_delay = std::mem::replace(&mut self.destroy_delay, play.destroy_delay); let using = std::mem::replace(&mut self.using, play.using.take()); let use_delay = std::mem::replace(&mut self.use_delay, play.use_delay); + let shield_cooldown = std::mem::replace(&mut self.shield_cooldown, play.shield_cooldown); let attack_ticks = std::mem::replace(&mut self.attack_ticks, play.attack_ticks); let attack_item = std::mem::replace(&mut self.attack_item, play.attack_item.take()); let swing = std::mem::replace(&mut self.swing, play.swing); @@ -369,6 +373,7 @@ impl Game<'_> { destroy_delay, using, use_delay, + shield_cooldown, attack_ticks, attack_item, swing, @@ -421,6 +426,7 @@ impl Game<'_> { destroy_delay, using, use_delay, + shield_cooldown, attack_ticks, attack_item, swing, @@ -480,6 +486,7 @@ impl Game<'_> { play.destroy_delay = std::mem::replace(&mut self.destroy_delay, destroy_delay); play.using = std::mem::replace(&mut self.using, using); play.use_delay = std::mem::replace(&mut self.use_delay, use_delay); + play.shield_cooldown = std::mem::replace(&mut self.shield_cooldown, shield_cooldown); play.attack_ticks = std::mem::replace(&mut self.attack_ticks, attack_ticks); play.attack_item = std::mem::replace(&mut self.attack_item, attack_item); play.swing = std::mem::replace(&mut self.swing, swing); @@ -1562,6 +1569,9 @@ impl Game<'_> { continue; } let play = host.play.entry(conn).or_default(); + // Player.tick's ItemCooldowns.tick, once a tick for each player + // (the shield an axe disabled). + play.shield_cooldown = play.shield_cooldown.saturating_sub(1); let digging = play.digging; let using = play.using.is_some(); let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100; @@ -1616,6 +1626,9 @@ impl Game<'_> { self.guest_dig_feedback(host, conn); self.guest_pickups(host, gi); self.guest_orbs(host, gi); + if host.hub.guests[gi].health <= 0.0 && !host.hub.guests[gi].dead { + self.guest_forget_digging(host, conn); + } let g = &mut host.hub.guests[gi]; if g.health <= 0.0 && !g.dead { g.dead = true; @@ -1968,6 +1981,23 @@ impl Game<'_> { /// `level.destroyBlockProgress(id, pos, -1)` for a guest: its crack on `pos` is gone, for the /// host and the other guests. + /// A player who dies digs and uses nothing any more: the block it was + /// breaking, or had left to break (`hasDelayedDestroy`), stays, and its + /// crack goes. Respawning gives it a new ServerPlayerGameMode (#1315). + fn guest_forget_digging(&mut self, host: &mut LanHost, conn: u32) { + let Some(play) = host.play.get_mut(&conn) else { + return; + }; + let cracked = play.digging.take().filter(|_| play.last_progress >= 0); + play.mining = None; + play.delayed = None; + play.destroy_delay = 0; + play.using = None; + play.last_progress = -1; + if let Some((pos, _)) = cracked { + self.guest_crack_gone(host, conn, pos); + } + } fn guest_crack_gone(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) { let Some(id) = host.hub.guest(conn).map(|g| g.entity_id) else { return; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c5a90150f..c68fbff7d 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -131,6 +131,10 @@ address. The script then checks, from both sides, what a guest's game used to ge get off by sneaking; the other side sees the animal move. - lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the sky (on its server thread the host's window is a client of it too). +- shield: the host axes the guest's raised shield, then the guest the host's: it stays disabled + for 5 s on that player's own cooldown, then blocks again (#1316). +- deathmining: the host and the guest each die while breaking obsidian and let go on the death + screen: once respawned, the obsidian stays (#1315). - flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: the guest, and on the server thread the host's window too, take what may fly from the server's abilities (ClientPacketListener.handlePlayerAbilities). @@ -172,7 +176,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', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'shield', 'deathmining'] class Game: @@ -2297,6 +2301,130 @@ def check_flight(host, guest, out): +def own(game): + """The player's own state, as its client has it.""" + return game('state')['player'] + + +def server_player(host, game): + """The player's entry on the server: the guest's in the host's `lan status`, on the server + thread the host's too; the host's own world otherwise.""" + if game is host and not SERVER_THREAD: + return own(host) + name = GUEST_NAME if game is not host else host.player + return next(g for g in host.raw('lan', 'status')['guests'] if g['name'] == name) + + +def check_shield(host, guest, out): + """An axe disables a raised shield for 5 s (100 ticks), counted down once a tick on the + server: a vindicator's axe hits each player's shield, then the cooldown left falls by about 40 + over 40 ticks (#1316).""" + host('command', command='gamerule natural_health_regeneration false') + rates = {} + try: + for game, dz in ((host, -4), (guest, 4)): + x, y, z = (int(v // 1) for v in pos_of(host)) + z += dz + game('command', command='gamemode survival') + game('command', command='effect give @s minecraft:resistance 60 4 true') + game('command', command='effect give @s minecraft:instant_health 1 5 true') + game('command', command='item replace entity @s weapon.mainhand with minecraft:air') + game('command', command='item replace entity @s weapon.offhand with minecraft:shield') + game('command', command=f'fill {x - 1} {y} {z - 1} {x + 4} {y + 2} {z + 1} minecraft:air') + game('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 4} {y - 1} {z + 1} minecraft:stone') + game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + game.wait(10) + game.raw('look-at', f'{x + 2.5:.2f}', f'{y + 1.5:.2f}', f'{z + 0.5:.2f}') + game.raw('mouse', 'right', 'down') + game.wait(10) + host('command', command=f'summon minecraft:vindicator {x + 2.5} {y} {z + 0.5} ' + '{PersistenceRequired:1b,Rotation:[90f,0f]}') + host('command', command='item replace entity @e[type=minecraft:vindicator] weapon.mainhand ' + 'with minecraft:iron_axe') + first = None + for _ in range(60): + game.wait(5) + first = server_player(host, game).get('shield_cooldown', 0) + if first: + break + host('command', command='kill @e[type=minecraft:vindicator]') + game.raw('mouse', 'right', 'up') + assert first, f'{game.name}: the vindicator never disabled the shield' + start = server_player(host, game)['shield_cooldown'] + game.wait(40) + end = server_player(host, game)['shield_cooldown'] + rates[game.name] = {'first': first, 'start': start, 'end': end} + game.shot(out, 'shield') + game('command', command='item replace entity @s weapon.offhand with minecraft:air') + game('command', command='effect clear @s') + finally: + host('command', command='kill @e[type=minecraft:vindicator]') + host('command', command='gamerule natural_health_regeneration true') + for name, r in rates.items(): + assert r['first'] <= 100, f'{name}: {rates}' + # Once a tick: 40 down over 40 ticks, give or take the ticks the two queries straddle. + assert 30 <= r['start'] - r['end'] <= 50, f'{name}: {rates}' + return rates + + +def respawn_when_ready(game): + """Press Respawn once the death screen lets it (DeathScreen's 20-tick delay, counted from when + the screen opens).""" + for _ in range(20): + try: + return game.raw('respawn') + except Failed as e: + if 'not active yet' not in str(e): + raise + game.wait(10) + return game.raw('respawn') + + +def check_death_mining(host, guest, out): + """A player who dies while breaking obsidian, and lets go of attack on the death screen, doesn't + break it once respawned: death forgets the digging (#1315).""" + host('command', command='gamerule keep_inventory true') + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + try: + for game, dz in ((host, -3), (guest, 3)): + x, y, z = hx + 2, hy, hz + dz + game('command', command='gamemode survival') + game('command', command='item replace entity @s weapon.mainhand with minecraft:diamond_pickaxe') + game('command', command=f'setblock {x + 2} {y} {z} minecraft:obsidian') + game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + game.wait(10) + game.raw('look-at', f'{x + 2.5:.2f}', f'{y + 0.5:.2f}', f'{z + 0.5:.2f}') + game.wait(5) + game.raw('mouse', 'left', 'down') + game.wait(10) + game('command', command='kill @s') + game.wait(10) + # The death screen lets go of the button (Minecraft.setScreen); let go again once back. + try: + game.raw('mouse', 'left', 'up') + except Failed: + pass + game.wait(10) + respawn_when_ready(game) + game.wait(2) + try: + game.raw('mouse', 'left', 'up') + except Failed: + pass + # Obsidian takes a diamond pickaxe about 190 ticks. + game.wait(240) + seen[game.name] = host.raw('block', x + 2, y, z).get('block') + game.shot(out, 'death-mining') + host('command', command=f'setblock {x + 2} {y} {z} minecraft:air') + game('command', command='item replace entity @s weapon.mainhand with minecraft:air') + finally: + host('command', command='gamerule keep_inventory false') + for name, block in seen.items(): + assert block == 'minecraft:obsidian', f'{name}: {seen}' + return seen + + def check_ladder(host, guest, out): """#1255: climbing down a ladder doesn't hurt where the guest lands.""" x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -3075,7 +3203,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'shield': check_shield, 'deathmining': check_death_mining} def run(ctl, out, resources, checks): From 5c4600e4034ed5a5a0fc50c3d498dccbc8ab04cf Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 04:59:14 +0200 Subject: [PATCH 15/16] /setworldspawn moves the world spawn, not the player's respawn point SetWorldSpawnCommand sets the level's spawn and its angle; a player without a bed or anchor respawns there (it used to set the player's own spawn point, so other players and later deaths kept the old one). The angle is saved in level.dat's spawn (yaw, pitch), and a guest whose saved respawn point is the world spawn follows it when it moves. lan_e2e `worldspawn`: /setworldspawn 24 blocks east, then the host and the guest die and respawn there. Fixes #1310. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/horizon-client/src/game/commands.rs | 14 +++++- crates/horizon-client/src/lan/playerdata.rs | 7 ++- crates/horizon-client/src/save.rs | 13 +++++- tools/lan_e2e.py | 50 ++++++++++++++++++++- 4 files changed, 78 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index f174f98c1..f35354f74 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2322,7 +2322,19 @@ impl Game<'_> { Some(Arg::Coords(c)) => c.rotation(self.source_rotation()), _ => [0.0, 0.0], }; - self.level.spawn = Some([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]); + // LevelData.setRespawnData: the world's spawn (level.dat `spawn`). + let old = self.level.world_spawn.replace(pos); + self.level.world_spawn_angle = rot; + // A player whose respawn point is the world spawn (no bed, anchor or + // spawnpoint of its own) respawns at the new one. + let floor = |s: Vec3| [s.x.floor() as i32, s.y.floor() as i32, s.z.floor() as i32]; + if self.respawn_config.is_none() && self.spawn.map(floor) == old { + self.spawn = Some(Vec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + )); + } let args = [ Text::literal(pos[0].to_string()), Text::literal(pos[1].to_string()), diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 8797f25a2..841f4da38 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -71,7 +71,12 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.game_mode = level.mode(); guest.flying = level.flying; guest.selected = (level.selected_slot.max(0) as usize).min(8); - guest.spawn = level.spawn.map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); + // A point that is the world spawn is none of the player's own: it + // respawns wherever the world spawn is then (`setworldspawn`). + guest.spawn = level + .spawn + .filter(|s| Some(s.map(|v| v.floor() as i32)) != level.world_spawn) + .map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); guest.saved = level.player_extra.clone(); guest.recipe_book = level.recipe_book.clone(); guest.dimension = match level.dimension.as_str() { diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0cfe3c585..8787415d9 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2288,6 +2288,8 @@ pub struct Level { pub dimension: String, /// World spawn (`level.dat` `spawn`), distinct from a bed respawn point. pub world_spawn: Option<[i32; 3]>, + /// The world spawn's yaw and pitch (`setworldspawn`'s rotation). + pub world_spawn_angle: [f32; 2], pub difficulty: String, pub hardcore: bool, /// `difficulty_settings.locked` (LevelData.isDifficultyLocked). @@ -2365,6 +2367,11 @@ impl Level { ] }), }; + let angle = |k: &str| match data.get("spawn").and_then(|s| s.get(k)) { + Some(Tag::Float(b)) => f32::from_bits(*b), + _ => 0.0, + }; + level.world_spawn_angle = [angle("yaw"), angle("pitch")]; if let Some(d) = data.get("difficulty_settings") { level.difficulty = text(d.get("difficulty")).unwrap_or_else(|| "normal".into()); level.hardcore = n(d.get("hardcore")) != 0; @@ -2857,8 +2864,8 @@ impl Level { Tag::compound([ ("pos", Tag::IntArray(spawn.to_vec())), ("dimension", string("minecraft:overworld")), - ("yaw", Tag::Float(0f32.to_bits())), - ("pitch", Tag::Float(0f32.to_bits())), + ("yaw", Tag::Float(self.world_spawn_angle[0].to_bits())), + ("pitch", Tag::Float(self.world_spawn_angle[1].to_bits())), ]), ), ("difficulty_settings", difficulty), @@ -4126,6 +4133,7 @@ mod tests { xp_total: 30, dimension: "minecraft:the_nether".into(), world_spawn: Some([8, 64, 8]), + world_spawn_angle: [45.0, -10.0], spawn: Some([20.0, 70.0, 20.0]), difficulty_locked: true, flying: true, @@ -4160,6 +4168,7 @@ mod tests { ); assert_eq!(back.dimension, "minecraft:the_nether"); assert_eq!(back.world_spawn, Some([8, 64, 8])); + assert_eq!(back.world_spawn_angle, [45.0, -10.0]); assert_eq!(back.spawn, Some([20.0, 70.0, 20.0])); assert!(back.difficulty_locked); assert!(back.weather.raining); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c5a90150f..6f416306b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -131,6 +131,8 @@ address. The script then checks, from both sides, what a guest's game used to ge get off by sneaking; the other side sees the animal move. - lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the sky (on its server thread the host's window is a client of it too). +- worldspawn: the host moves the world spawn (`setworldspawn`): the host and the guest, with no bed, + respawn there (#1310). - flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: the guest, and on the server thread the host's window too, take what may fly from the server's abilities (ClientPacketListener.handlePlayerAbilities). @@ -172,7 +174,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', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn'] class Game: @@ -2297,6 +2299,49 @@ def check_flight(host, guest, out): +def respawn_when_ready(game): + """Press Respawn once the death screen lets it (DeathScreen's 20-tick delay, counted from when + the screen opens).""" + for _ in range(20): + try: + return game.raw('respawn') + except Failed as e: + if 'not active yet' not in str(e): + raise + game.wait(10) + return game.raw('respawn') + + +def check_world_spawn(host, guest, out): + """`setworldspawn` moves the world spawn: the host and the guest, with no bed of their own, + respawn there once killed (#1310).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + sx, sz = hx + 24, hz + host('command', command='gamerule respawn_radius 0') + host('command', command=f'fill {sx - 2} {hy - 1} {sz - 2} {sx + 2} {hy - 1} {sz + 2} minecraft:stone') + host('command', command=f'fill {sx - 2} {hy} {sz - 2} {sx + 2} {hy + 3} {sz + 2} minecraft:air') + seen = {} + try: + host('command', command=f'setworldspawn {sx} {hy} {sz}') + for game in (host, guest): + game('command', command='gamemode survival') + game('command', command='kill @s') + game.wait(20) + respawn_when_ready(game) + game.wait(60) + seen[game.name] = [round(v, 2) for v in pos_of(game)] + game.shot(out, 'world-spawn') + finally: + host('command', command=f'setworldspawn {hx} {hy} {hz}') + host('command', command='gamerule respawn_radius 10') + for game in (host, guest): + game('command', command=f'tp @s {hx + 0.5} {hy} {hz + 0.5}') + guest.wait(20) + for name, at in seen.items(): + assert abs(at[0] - (sx + 0.5)) < 1 and abs(at[2] - (sz + 0.5)) < 1, f'{name}: {seen}, spawn {sx} {sz}' + return seen + + def check_ladder(host, guest, out): """#1255: climbing down a ladder doesn't hurt where the guest lands.""" x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -3075,7 +3120,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'worldspawn': check_world_spawn} def run(ctl, out, resources, checks): From 65bd2d0d45e15710af70cad00f642ae80f48b86e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 04:59:19 +0200 Subject: [PATCH 16/16] Items push out of blocks; a server's client digs at the server's speed ItemEntity.tick: an item stuck inside a full block (one set on it) has no physics on the server and moves toward the closest free side (Entity.moveTowardsClosestSpace: north, south, west, east, up; 0.1 to 0.3 a tick), instead of staying in the block (#1252). A server's client (LAN guests, and the window on the server thread) digs at the same speed as the server: getDestroyProgress with the submerged mining speed, haste, fatigue and efficiency, not the plain tool speed, so it no longer finishes early under water and gets the block put back (#1254). lan_e2e: `drops` (a diamond under a block set on it comes out, in both views) and `underwater` (dirt by hand at eye height under water: about halfway at 35 ticks on client and server, broken by 105). Fixes #1252, #1254. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/horizon-client/src/entities.rs | 78 ++++++++++++++++++++++-- crates/horizon-client/src/game.rs | 9 ++- crates/horizon-client/src/game/agent.rs | 2 + crates/horizon-client/src/game/remote.rs | 19 ++---- tests/test_remote_mining.py | 4 ++ tools/lan_e2e.py | 77 ++++++++++++++++++++++- 6 files changed, 167 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index cfbdb0636..65536d710 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -98,12 +98,73 @@ impl ItemEntity { lava_hurt, } } - /// Returns false when the item should be removed. + /// `ItemEntity.tick` on a server: an item whose box is inside a block + /// (one placed where it lay) has no physics this tick + /// (`level.noCollision(box.deflate(1.0E-7))`). + pub fn inside_block(&self, world: &World, collision: &BlockCollisionRegistry<'_>) -> bool { + let mut scene = SceneCollisions { + world, + binding: collision, + subject: None, + }; + let inner = self.bounds().deflate(Vec3::new(1.0e-7, 1.0e-7, 1.0e-7)); + !crate::collisions::no_collision_empty(&mut scene, inner) + } + /// `Entity.moveTowardsClosestSpace` from the middle of the item's box: + /// towards the nearest side of its block (north, south, west, east or + /// up) without a full collision cube, at `speed` (`nextFloat() * 0.2 + + /// 0.1`). + pub fn move_towards_closest_space(&mut self, world: &World, facts: &BlockFacts, speed: f32) { + let bounds = self.bounds(); + let at = Vec3::new( + self.position.x, + (bounds.min_position().y + bounds.max_position().y) / 2.0, + self.position.z, + ); + let pos = [ + at.x.floor() as i32, + at.y.floor() as i32, + at.z.floor() as i32, + ]; + let delta = [ + at.x - f64::from(pos[0]), + at.y - f64::from(pos[1]), + at.z - f64::from(pos[2]), + ]; + // (axis, step): NORTH, SOUTH, WEST, EAST, UP. + let mut closest = (1, 1); + let mut nearest = f64::MAX; + for (axis, step) in [(2, -1), (2, 1), (0, -1), (0, 1), (1, 1)] { + let mut n = pos; + n[axis] += step; + if !facts.get(world.block(n[0], n[1], n[2])).full_collision { + let d = if step > 0 { + 1.0 - delta[axis] + } else { + delta[axis] + }; + if d < nearest { + nearest = d; + closest = (axis, step); + } + } + } + let push = f64::from(closest.1 as f32 * speed); + let v = self.velocity.scale(0.75); + self.velocity = match closest.0 { + 0 => Vec3::new(push, v.y, v.z), + 1 => Vec3::new(v.x, push, v.z), + _ => Vec3::new(v.x, v.y, push), + }; + } + /// Returns false when the item should be removed. `no_physics`: the item + /// moves through blocks this tick ([`ItemEntity::inside_block`]). pub fn tick( &mut self, world: &World, facts: &BlockFacts, collision: &BlockCollisionRegistry<'_>, + no_physics: bool, ) -> bool { self.ticks += 1; self.previous = self.position; @@ -140,15 +201,22 @@ impl ItemEntity { subject: None, }; let wanted = self.velocity; - let moved = scene - .resolve(self.bounds(), wanted, 0.0, self.on_ground) - .unwrap_or(Vec3::ZERO); + // Entity.move with noPhysics: straight through, the ground as it was. + let moved = if no_physics { + wanted + } else { + scene + .resolve(self.bounds(), wanted, 0.0, self.on_ground) + .unwrap_or(Vec3::ZERO) + }; self.position = Vec3::new( self.position.x + moved.x, self.position.y + moved.y, self.position.z + moved.z, ); - self.on_ground = wanted.y < 0.0 && moved.y != wanted.y; + if !no_physics { + self.on_ground = wanted.y < 0.0 && moved.y != wanted.y; + } if moved.x != wanted.x { self.velocity.x = 0.0; } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5da86dfaf..0b1ca23fd 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2101,7 +2101,14 @@ impl Game<'_> { ) { continue; } - let alive = item.tick(&self.world, self.res.facts(), self.collision); + // ItemEntity.tick's noPhysics (servers only): out of a block + // placed on it, towards the closest open side (#1252). + let no_physics = merging && item.inside_block(&self.world, self.collision); + if no_physics { + let speed = self.world.random.next_float() * 0.2 + 0.1; + item.move_towards_closest_space(&self.world, self.res.facts(), speed); + } + let alive = item.tick(&self.world, self.res.facts(), self.collision, no_physics); cells.moved(i, item.previous, item.position); // ItemEntity.tick: merge every 2 ticks while moving between // blocks, every 40 otherwise, before the lifetime check. diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index ea686e711..15564dc3e 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -478,6 +478,8 @@ impl Game<'_> { "sleeping": self.sleeping, // The item in use: its slot and for how many ticks. "using": self.using.map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })), + // The block being dug: how far along, after how many ticks. + "mining": self.mining.as_ref().map(|m| json!({ "pos": m.pos, "progress": m.progress, "ticks": m.ticks })), // The arm swings started (LivingEntity.swing). "swings": self.swings_started, "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) }, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5461a4cd0..563ab4170 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3469,22 +3469,13 @@ impl Game<'_> { return; } let facts = self.res.facts().get(state).clone(); - let held = self.held().cloned(); - let mut speed = self.res.items().mining_speed(held.as_ref(), &facts.name); - if self.player.as_ref().is_some_and(|p| !p.ground.on_ground) { - speed /= 5.0; - } - let harvest = !facts.requires_tool - || self - .res - .items() - .correct_for_drops(held.as_ref(), &facts.name); - let progress = if facts.hardness < 0.0 { - 0.0 - } else if facts.hardness == 0.0 { + // The server's own getDestroyProgress: under water, off the ground, + // with haste, fatigue and efficiency, so the client stops digging + // when the server is done too (#1254). + let progress = if facts.hardness == 0.0 { 1.0 } else { - speed / facts.hardness / if harvest { 30.0 } else { 100.0 } + self.destroy_progress(hit.pos) }; let same = self .remote diff --git a/tests/test_remote_mining.py b/tests/test_remote_mining.py index 236b85c28..1a35b3865 100644 --- a/tests/test_remote_mining.py +++ b/tests/test_remote_mining.py @@ -79,6 +79,10 @@ impl Game { } fn pick(&self) -> Option<Hit> { Some(self.hit) } fn held(&self) -> Option<&()> { None } + // Game::destroy_progress (hand.rs) for a harvestable block on the ground. + fn destroy_progress(&self, _: [i32; 3]) -> f32 { + self.res.speed / self.res.facts.hardness / 30.0 + } fn next_sequence(&mut self) -> i32 { self.sequence += 1; self.sequence } fn predict_break(&mut self, pos: [i32; 3], _: u32, _: i32) { self.world.broken.push(pos); } fn send(&mut self, S::PlayerAction(packet): S) { self.packets.push(packet); } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c5a90150f..6bdc52905 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -131,6 +131,10 @@ address. The script then checks, from both sides, what a guest's game used to ge get off by sneaking; the other side sees the animal move. - lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the sky (on its server thread the host's window is a client of it too). +- drops: an item lies where the host, then the guest, places a block: it comes out of the block + on the server, and both sides see it outside (#1252). +- underwater: the host and the guest each dig dirt by hand standing under water: five times slower + than in the air on their own client as on the server, and it breaks (#1254). - flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: the guest, and on the server thread the host's window too, take what may fly from the server's abilities (ClientPacketListener.handlePlayerAbilities). @@ -172,7 +176,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', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'drops', 'underwater'] class Game: @@ -2297,6 +2301,74 @@ def check_flight(host, guest, out): +def check_drops(host, guest, out): + """A dropped item lying where a block is then placed comes out of it (#1252): the server moves + it towards the closest open side (ItemEntity.tick's noPhysics, Entity.moveTowardsClosestSpace), + and both sides see it outside the block. The host places one, then the guest.""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + for game, dz in ((host, -3), (guest, 3)): + x, y, z = hx + 3, hy, hz + dz + game('command', command=f'fill {x - 1} {y} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:air') + game('command', command=f'summon minecraft:item {x + 0.5} {y} {z + 0.5} ' + '{Item:{id:"minecraft:diamond",count:1},PickupDelay:32767}') + game.wait(20) + game('command', command=f'setblock {x} {y} {z} minecraft:stone') + game.wait(60) + for viewer in (host, guest): + near = [e['pos'] for e in viewer.raw('entities', 24, 'minecraft:item')['entities'] + if abs(e['pos'][0] - x - 0.5) < 2 and abs(e['pos'][2] - z - 0.5) < 2] + seen[f'{game.name} places, {viewer.name} sees'] = ([x, y, z], near) + game.shot(out, 'drops') + host('command', command='kill @e[type=minecraft:item]') + host('command', command=f'setblock {x} {y} {z} minecraft:air') + for name, (block, near) in seen.items(): + inside = [p for p in near if all(block[i] <= p[i] < block[i] + 1 for i in range(3))] + assert near and not inside, f'{name}: items {near} in block {block} (all: {seen})' + return seen + + +def check_underwater(host, guest, out): + """Digging dirt by hand underwater, standing on the bottom of a pool: five times slower than in + the air (SUBMERGED_MINING_SPEED), on the player's own client as on the server. Halfway through + the client is about halfway (it doesn't break the block early, which the server would put + back), and the block breaks (#1254). The dirt is at eye height, the player's head under water. + The host, then the guest.""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + for game, dz in ((host, -4), (guest, 4)): + x, y, z = hx + 3, hy, hz + dz + game('command', command='gamemode survival') + game('command', command='item replace entity @s weapon.mainhand with minecraft:air') + game('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 2} {y + 3} {z + 1} minecraft:stone') + game('command', command=f'fill {x} {y} {z} {x} {y + 2} {z} minecraft:water') + game('command', command=f'setblock {x + 1} {y + 1} {z} minecraft:dirt') + game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + game.wait(40) + game.raw('look-at', f'{x + 1.5:.2f}', f'{y + 1.5:.2f}', f'{z + 0.5:.2f}') + game.wait(5) + game.raw('mouse', 'left', 'down') + # Dirt by hand: 15 ticks in the air, 75 under water. + game.wait(35) + halfway = {'mining': game('state').get('mining'), 'client': game.raw('block', x + 1, y + 1, z).get('block'), + 'server': host.raw('block', x + 1, y + 1, z).get('block'), 'y': y + 1} + game.wait(70) + game.raw('mouse', 'left', 'up') + game.wait(10) + done = host.raw('block', x + 1, y + 1, z).get('block') + game.shot(out, 'underwater') + seen[game.name] = {'halfway': halfway, 'done': done} + host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 2} {y + 3} {z + 1} minecraft:air') + host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 2} {y - 1} {z + 1} minecraft:stone') + for name, s in seen.items(): + h = s['halfway'] + assert h['client'] == 'minecraft:dirt' == h['server'], f'{name} broke it early: {seen}' + assert h['mining'] and h['mining']['pos'][1] == h['y'] and 0.3 < h['mining']['progress'] < 0.7, f'{name} digs at the wrong speed: {seen}' + # Broken: air, or the pool's water flowing in. + assert s['done'] in ('minecraft:air', 'minecraft:water'), f'{name} never broke it: {seen}' + return seen + + def check_ladder(host, guest, out): """#1255: climbing down a ladder doesn't hurt where the guest lands.""" x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -3075,7 +3147,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'drops': check_drops, 'underwater': check_underwater} def run(ctl, out, resources, checks):