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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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),