diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d6577d49e..8966854c2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -18,6 +18,10 @@ concurrency:
# A new push to a pull request replaces its running checks; main's runs all finish (releases follow them).
group: checks-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+env:
+ # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
+ HORIZON_TELEMETRY_URL: "off"
+
jobs:
verify:
runs-on: ubuntu-latest
diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml
index 79ea852fb..02c61cdd1 100644
--- a/.github/workflows/launcher.yml
+++ b/.github/workflows/launcher.yml
@@ -49,6 +49,10 @@ concurrency:
group: launcher-${{ github.ref == 'refs/heads/main' && 'release' || github.ref }}
cancel-in-progress: false
+env:
+ # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
+ HORIZON_TELEMETRY_URL: "off"
+
jobs:
decide:
runs-on: ubuntu-latest
@@ -188,9 +192,6 @@ jobs:
retry "$launcher" install latest
"$launcher" versions --installed
"$launcher" links --json
- "$launcher" menu-style classic
- grep -qx 'menuStyle:classic' "$HORIZON_HOME/horizon.txt"
- "$launcher" menu-style horizon
clients=("$HORIZON_LAUNCHER_HOME"/versions/v*/horizon-client*)
client="${clients[0]}"
echo "installed client: $client"
diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml
index 689cdae59..51f9e89cd 100644
--- a/.github/workflows/nightly.yml
+++ b/.github/workflows/nightly.yml
@@ -23,6 +23,10 @@ permissions:
concurrency:
group: nightly-audit
cancel-in-progress: false
+env:
+ # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
+ HORIZON_TELEMETRY_URL: "off"
+
jobs:
audit:
runs-on: [self-hosted, horizon-game]
diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml
index 7289fe4de..a18fc5019 100644
--- a/.github/workflows/parity.yml
+++ b/.github/workflows/parity.yml
@@ -15,6 +15,10 @@ on:
required: true
permissions:
contents: read
+env:
+ # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
+ HORIZON_TELEMETRY_URL: "off"
+
jobs:
parity:
runs-on: [self-hosted, horizon-game]
diff --git a/.github/workflows/run-parity.yml b/.github/workflows/run-parity.yml
index fd3cce6f8..a2b8e3291 100644
--- a/.github/workflows/run-parity.yml
+++ b/.github/workflows/run-parity.yml
@@ -11,6 +11,10 @@ permissions:
concurrency:
group: run-parity-${{ github.event.pull_request.number }}
cancel-in-progress: true
+env:
+ # Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
+ HORIZON_TELEMETRY_URL: "off"
+
jobs:
parity:
if: github.event.label.name == 'run-parity'
diff --git a/README.md b/README.md
index 72b6a3496..4abb52b86 100644
--- a/README.md
+++ b/README.md
@@ -46,7 +46,7 @@ The [documentation](https://playhorizon.dev/docs/) covers each of these.
- **The game:** singleplayer with vanilla's world generation, mobs, villagers, raids, redstone, every command, the HUD and the recipe book, on saves in vanilla's format. Worlds from 1.8 to 26.2 are upgraded as vanilla does. [Status table](#project-status).
- **Horizon's own extras:** new menus (vanilla's are one setting away), graphics presets, distant terrain up to 1024 chunks, controller support, optional zoom, minimap and more, all off by default where they would change the vanilla look. See [Settings](https://playhorizon.dev/docs/settings).
- **Resource packs, shader packs and data packs:** resource packs work, Java shader packs run their full-screen effects (experimental), and data packs load functions, predicates and item modifiers.
-- **Playing with others:** invite friends from the pause menu with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer).
+- **Playing with others:** invite friends from the pause menu's Friends button with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer).
- **Mods:** Horizon has its own mod system (Rust compiled to WebAssembly). Java mod jars do not run. See [Mods and data packs](https://playhorizon.dev/docs/mods).
Screenshots, captured in the Rust client itself with vanilla assets and no mods or shaders:
@@ -56,8 +56,8 @@ Screenshots, captured in the Rust client itself with vanilla assets and no mods
-
-
+
+
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 368813ecf..88d3197af 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -36,3 +36,15 @@ SOFTWARE.
developers, with one upstream fix applied
([gfx-rs/wgpu#10124](https://github.com/gfx-rs/wgpu/pull/10124)). It is licensed under MIT or
Apache-2.0; both licenses are in that folder (`LICENSE.MIT`, `LICENSE.APACHE`).
+
+## Pixelify Sans
+
+`crates/horizon-theme/fonts/PixelifySans-*.ttf` is [Pixelify Sans](https://github.com/eifetx/Pixelify-Sans)
+by The Pixelify Sans Project Authors, licensed under the SIL Open Font License 1.1
+(`crates/horizon-theme/fonts/OFL-PixelifySans.txt`).
+
+## Pixelarticons
+
+`crates/horizon-theme/icons/pixel/*.svg` are icons from
+[Pixelarticons](https://github.com/halfmage/pixelarticons) by Gerrit Halfmann, under the MIT
+license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`).
diff --git a/crates/horizon-client/src/friends_screen.rs b/crates/horizon-client/src/friends_screen.rs
new file mode 100644
index 000000000..7577e2add
--- /dev/null
+++ b/crates/horizon-client/src/friends_screen.rs
@@ -0,0 +1,303 @@
+//! Play with Friends: Horizon's own sharing of the open world behind an
+//! invite code (`game/friends.rs`). The pause menu's Friends button, the icon
+//! vanilla's PauseScreen already has, opens it. It is drawn the way a mod adds
+//! a screen to vanilla: the menu background, a centred title and text,
+//! vanilla's buttons and Done in the footer.
+use crate::{
+ hud::{HudAtlas, HudBatch, rgba},
+ multiplayer::wrap,
+ text::Text,
+ ui,
+};
+
+pub const TITLE: &str = "Play with Friends";
+/// What the screen shows (game/friends.rs fills it).
+#[derive(Clone, Debug, Default)]
+pub struct FriendsView {
+ /// A singleplayer world (not a server): sharing is offered.
+ pub shown: bool,
+ pub sharing: bool,
+ pub code: Option,
+ /// Who can join and what to do when friends on the internet can't (or,
+ /// before the code, what the game is doing).
+ pub status: String,
+ /// Friends on the internet can reach the host.
+ pub reachable: bool,
+ /// Where the troubleshooting is, when they can't.
+ pub help: Option,
+ /// The players in the world besides the host.
+ pub guests: Vec,
+ pub notice: Option,
+ /// The code was just copied.
+ pub copied: bool,
+}
+
+/// A button's action.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Action {
+ Share,
+ Copy,
+ Stop,
+ /// Open the troubleshooting page.
+ Help,
+ Done,
+}
+
+fn grey() -> u32 {
+ rgba(160, 160, 160, 255)
+}
+const WHITE: u32 = u32::MAX;
+const HINT: &str = "Friends paste the code after the title screen's Friends button, in Direct Connection, or on the launcher's Play page.";
+
+struct Button {
+ x: f32,
+ y: f32,
+ w: f32,
+ label: &'static str,
+ action: Action,
+ active: bool,
+}
+
+/// The centred lines (text, colour, y) and the buttons.
+fn layout(
+ atlas: &HudAtlas,
+ (w, h): (f32, f32),
+ view: &FriendsView,
+) -> (Vec<(String, u32, f32)>, Vec) {
+ let width = (w - 40.0).min(310.0);
+ let cx = (w / 2.0).floor();
+ let mut lines = Vec::new();
+ let mut y = 40.0;
+ let add = |lines: &mut Vec<(String, u32, f32)>, text: &str, color: u32, y: &mut f32| {
+ for line in wrap(text, width, atlas) {
+ lines.push((line, color, *y));
+ *y += 10.0;
+ }
+ };
+ let mut buttons = Vec::new();
+ if view.sharing {
+ lines.push(("Invite Code".to_owned(), grey(), y));
+ y += 12.0;
+ match &view.code {
+ Some(code) => {
+ for line in code_lines(atlas, code, width) {
+ lines.push((line, WHITE, y));
+ y += 10.0;
+ }
+ }
+ None => add(&mut lines, &view.status, WHITE, &mut y),
+ }
+ y += 6.0;
+ buttons.push(Button {
+ x: cx - 154.0,
+ y,
+ w: 150.0,
+ label: if view.copied { "Copied" } else { "Copy Code" },
+ action: Action::Copy,
+ active: view.code.is_some(),
+ });
+ buttons.push(Button {
+ x: cx + 4.0,
+ y,
+ w: 150.0,
+ label: "Stop Sharing",
+ action: Action::Stop,
+ active: true,
+ });
+ y += 30.0;
+ if view.code.is_some() {
+ // Who can join: grey when friends anywhere can, white (it asks
+ // for something) when only the LAN and VPNs can.
+ let tint = if view.reachable { grey() } else { WHITE };
+ add(&mut lines, &view.status, tint, &mut y);
+ y += 4.0;
+ }
+ let here = if view.guests.is_empty() {
+ "No friends here yet.".to_owned()
+ } else {
+ format!("Here now: {}", view.guests.join(", "))
+ };
+ add(&mut lines, &here, grey(), &mut y);
+ if let Some(notice) = &view.notice {
+ add(&mut lines, notice, WHITE, &mut y);
+ }
+ // Where friends paste the code, while it fits above the footer.
+ if y + 10.0 * wrap(HINT, width, atlas).len() as f32 <= h - 33.0 {
+ add(&mut lines, HINT, grey(), &mut y);
+ }
+ } else {
+ add(
+ &mut lines,
+ "Share this world behind an invite code: it opens to LAN, and friends on the internet join with the code. No server of ours is involved.",
+ WHITE,
+ &mut y,
+ );
+ y += 4.0;
+ add(&mut lines, HINT, grey(), &mut y);
+ buttons.push(Button {
+ x: cx - 100.0,
+ y: y + 8.0,
+ w: 200.0,
+ label: "Start Sharing",
+ action: Action::Share,
+ active: view.shown,
+ });
+ }
+ // HeaderAndFooterLayout's footer: Done, beside Troubleshooting when
+ // friends on the internet can't reach the host.
+ if view.sharing && view.help.is_some() {
+ buttons.push(Button {
+ x: cx - 154.0,
+ y: h - 27.0,
+ w: 150.0,
+ label: "Troubleshooting...",
+ action: Action::Help,
+ active: true,
+ });
+ buttons.push(Button {
+ x: cx + 4.0,
+ y: h - 27.0,
+ w: 150.0,
+ label: "gui.done",
+ action: Action::Done,
+ active: true,
+ });
+ } else {
+ buttons.push(Button {
+ x: cx - 100.0,
+ y: h - 27.0,
+ w: 200.0,
+ label: "gui.done",
+ action: Action::Done,
+ active: true,
+ });
+ }
+ (lines, buttons)
+}
+/// The code's groups packed into lines of at most `width`.
+fn code_lines(atlas: &HudAtlas, code: &str, width: f32) -> Vec {
+ let mut lines: Vec = Vec::new();
+ for group in code.split('-') {
+ match lines.last_mut() {
+ Some(l) if HudBatch::text_width(atlas, &format!("{l}-{group}")) <= width => {
+ l.push('-');
+ l.push_str(group);
+ }
+ _ => lines.push(group.to_owned()),
+ }
+ }
+ lines
+}
+fn label(key: &str) -> Text {
+ if key.starts_with("gui.") {
+ Text::translate(key, &[])
+ } else {
+ Text::literal(key)
+ }
+}
+pub fn draw(
+ batch: &mut HudBatch,
+ atlas: &HudAtlas,
+ cursor: (f32, f32),
+ view: &FriendsView,
+ in_world: bool,
+) {
+ let (w, h) = (batch.width, batch.height);
+ ui::menu_background(batch, atlas, 0.0, 0.0, w, h, in_world);
+ let title = Text::literal(TITLE);
+ let tw = atlas.font.width_text(&title);
+ batch.text_styled(atlas, &title, ((w - tw) / 2.0).floor(), 15.0, WHITE, true);
+ let (lines, buttons) = layout(atlas, (w, h), view);
+ for (line, color, y) in lines {
+ let lw = HudBatch::text_width(atlas, &line);
+ batch.text(atlas, &line, ((w - lw) / 2.0).floor(), y, color, true);
+ }
+ for b in buttons {
+ let hover = b.active && ui::hovered(cursor, b.x, b.y, b.w, 20.0);
+ ui::button(
+ batch,
+ atlas,
+ b.x,
+ b.y,
+ b.w,
+ 20.0,
+ &label(b.label),
+ b.active,
+ hover,
+ );
+ }
+}
+/// The button under a click, if it is active.
+pub fn click(
+ atlas: &HudAtlas,
+ size: (f32, f32),
+ cursor: (f32, f32),
+ view: &FriendsView,
+) -> Option {
+ layout(atlas, size, view)
+ .1
+ .into_iter()
+ .find(|b| b.active && ui::hovered(cursor, b.x, b.y, b.w, 20.0))
+ .map(|b| b.action)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn atlas() -> HudAtlas {
+ HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
+ }
+
+ #[test]
+ fn share_then_copy_and_stop() {
+ let atlas = atlas();
+ let size = (427.0, 240.0);
+ let idle = FriendsView {
+ shown: true,
+ ..FriendsView::default()
+ };
+ let (_, buttons) = layout(&atlas, size, &idle);
+ let share = buttons.iter().find(|b| b.action == Action::Share).unwrap();
+ assert_eq!(
+ click(&atlas, size, (share.x + 1.0, share.y + 1.0), &idle),
+ Some(Action::Share)
+ );
+ let sharing = FriendsView {
+ shown: true,
+ sharing: true,
+ status: "Finding how friends can reach you…".into(),
+ ..FriendsView::default()
+ };
+ let (_, buttons) = layout(&atlas, size, &sharing);
+ let copy = buttons.iter().find(|b| b.action == Action::Copy).unwrap();
+ assert!(!copy.active, "nothing to copy before the code");
+ let with_code = FriendsView {
+ code: Some("0B33K-Q405Q-1Z5CV-X6NHY-R12N0-VK8T1-60N00-RA134-952PE-1HA08-910P0-K5M01-ST1NB-JDTB6-K4W1P-0".into()),
+ status: "Friends on your network or VPN can join. For friends on the internet: turn on UPnP on your router, or forward TCP port 25580 to 10.0.0.2, or use a relay, or a VPN such as Tailscale or ZeroTier (the code already holds your VPN address).".into(),
+ help: Some("https://example.invalid/help".into()),
+ ..sharing
+ };
+ let (lines, buttons) = layout(&atlas, size, &with_code);
+ assert!(
+ lines.iter().all(|(_, _, y)| y + 9.0 <= size.1 - 27.0),
+ "the text stays above the footer"
+ );
+ for action in [Action::Copy, Action::Stop, Action::Help, Action::Done] {
+ let b = buttons.iter().find(|b| b.action == action).unwrap();
+ assert_eq!(
+ click(&atlas, size, (b.x + 1.0, b.y + 1.0), &with_code),
+ Some(action)
+ );
+ }
+ }
+
+ #[test]
+ fn a_server_offers_no_sharing() {
+ let atlas = atlas();
+ let view = FriendsView::default();
+ let (_, buttons) = layout(&atlas, (427.0, 240.0), &view);
+ let share = buttons.iter().find(|b| b.action == Action::Share).unwrap();
+ assert!(!share.active);
+ }
+}
diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs
deleted file mode 100644
index 75c072eb6..000000000
--- a/crates/horizon-client/src/front.rs
+++ /dev/null
@@ -1,1572 +0,0 @@
-//! The front-end screens in Horizon's menu style (`ui_theme`), laid out like
-//! the launcher: a 200-wide sidebar with the sliding selection (Home,
-//! Singleplayer, Multiplayer, Options), content pages with a page header,
-//! settings rows and 1px dividers, and the launcher's opening (the wordmark,
-//! then the interface). They drive the same state as the classic layouts in
-//! `title` and `multiplayer`; only drawing and hit testing differ. The pause
-//! menu's Horizon layout is `pause`, below.
-use crate::{
- hud::{HudAtlas, HudBatch},
- multiplayer::{Outcome, Ping, Screen},
- title::{Action, Mode, Title, list_worlds},
- ui_theme::{
- self as t, BODY, CONTROL, CONTROL_LARGE, Face, Kind, SIDEBAR, SMALL, Ui, color, id,
- },
-};
-use std::time::Instant;
-
-const NAV: u64 = id("title.nav", 0);
-const QUIT: u64 = id("title.quit", 0);
-const PLAY: u64 = id("home.play", 0);
-const MULTIPLAYER: u64 = id("home.multiplayer", 0);
-const RESUME: u64 = id("home.resume", 0);
-const BACK: u64 = id("front.back", 0);
-const PLAY_WORLD: u64 = id("worlds.play", 0);
-const CREATE: u64 = id("worlds.create", 0);
-const WORLD: u64 = id("worlds.row", 0);
-const DELETE_WORLD: u64 = id("worlds.delete", 0);
-const CONFIRM_DELETE: u64 = id("delete.confirm", 0);
-const NAME: u64 = id("create.name", 0);
-const SEED: u64 = id("create.seed", 0);
-const MODE: u64 = id("create.mode", 0);
-const MAKE: u64 = id("create.make", 0);
-const SERVER: u64 = id("mp.row", 0);
-const JOIN: u64 = id("mp.join", 0);
-const DIRECT: u64 = id("mp.direct", 0);
-const FRIEND: u64 = id("mp.friend", 0);
-const ADD: u64 = id("mp.add", 0);
-const EDIT: u64 = id("mp.edit", 0);
-const DELETE: u64 = id("mp.delete", 0);
-const REFRESH: u64 = id("mp.refresh", 0);
-const FIELD_A: u64 = id("mp.field", 0);
-const FIELD_B: u64 = id("mp.field", 1);
-const DONE: u64 = id("mp.done", 0);
-const CANCEL_RETRY: u64 = id("mp.cancel_retry", 0);
-
-/// The launcher's opening (`launcher/src/main.rs`): the wordmark holds over
-/// the backdrop, then the interface comes in. A click or a key skips ahead.
-#[derive(Clone, Copy, Debug)]
-pub struct Opening {
- started: Instant,
- reveal: Option,
-}
-impl Opening {
- pub fn new() -> Self {
- Self {
- started: Instant::now(),
- reveal: None,
- }
- }
- /// The reveal's progress, 0 to 1; `ready` says the backdrop is showing.
- fn phase(&mut self, ready: bool) -> f32 {
- let held = self.started.elapsed();
- if self.reveal.is_none()
- && ((held >= horizon_theme::OPENING_HOLD && ready)
- || held >= horizon_theme::OPENING_MAX)
- {
- self.reveal = Some(Instant::now());
- }
- self.reveal.map_or(0.0, |at| {
- at.elapsed().as_secs_f32() / horizon_theme::OPENING_REVEAL.as_secs_f32()
- })
- }
- pub fn skip(&mut self) {
- self.reveal.get_or_insert_with(Instant::now);
- }
-}
-impl Default for Opening {
- fn default() -> Self {
- Self::new()
- }
-}
-
-/// Which sidebar item a mode belongs to.
-fn page(mode: &Mode) -> usize {
- match mode {
- Mode::Main => 0,
- Mode::Select { .. }
- | Mode::Create { .. }
- | Mode::Edit { .. }
- | Mode::Backup { .. }
- | Mode::Delete { .. }
- | Mode::Error { .. } => 1,
- Mode::Multiplayer(_) => 2,
- }
-}
-const PAGES: [&str; 4] = ["Home", "Singleplayer", "Multiplayer", "Options"];
-/// World editing and backups still use the classic screens, and so do their
-/// errors; the rest of the singleplayer flow has Horizon pages.
-fn classic(mode: &Mode) -> bool {
- match mode {
- Mode::Edit { .. } | Mode::Backup { .. } => true,
- Mode::Error { return_to, .. } => classic(return_to),
- _ => false,
- }
-}
-
-impl Title {
- /// Horizon's layout for every title mode. `backdrop` is how much of the
- /// live backdrop is visible (0 shows the plain cold background).
- pub fn draw_horizon(&self, ui: &mut Ui, backdrop: f32) {
- if classic(&self.mode) {
- self.draw(ui.atlas, ui.batch, ui.cursor, false);
- return;
- }
- let reveal = self.opening_phase(backdrop >= 1.0);
- if backdrop < 1.0 {
- ui.cold_background(1.0 - backdrop);
- }
- let shade = t::ease_out_cubic(reveal);
- // The world stays in view on the home page; deeper pages veil it more.
- let veil = if matches!(self.mode, Mode::Main) {
- horizon_theme::HOME_VEIL
- } else {
- horizon_theme::VEIL
- };
- ui.muted = if matches!(self.mode, Mode::Main) {
- color::MUTED
- } else {
- color::FAINT
- };
- ui.atmosphere(veil, shade);
- let side = t::ease_out_cubic((reveal - 0.2) / 0.7);
- let main = t::ease_out_cubic((reveal - 0.35) / 0.65);
-
- // The sidebar slides in from the left.
- ui.opacity = side;
- ui.offset = (-16.0 * (1.0 - side), 0.0);
- if side > 0.0 {
- self.sidebar(ui);
- }
- // The content rises; each new page fades in and rises 8 over MOVE.
- let entered = self.entered();
- let p = t::ease_out_quint(entered.elapsed().as_secs_f32() / t::move_());
- ui.opacity = main * p;
- ui.offset = (0.0, 16.0 * (1.0 - main) + 8.0 * (1.0 - p));
- if main > 0.0 {
- let x = SIDEBAR + 48.0;
- let w = (ui.w - x - 48.0).min(760.0);
- match &self.mode {
- Mode::Main => self.home(ui, x, w),
- Mode::Select { worlds, selected } => worlds_page(ui, x, w, worlds, *selected),
- Mode::Create {
- name,
- seed,
- creative,
- focus,
- ..
- } => {
- let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2);
- create_page(ui, x, w, name, seed, *creative, *focus, caret);
- }
- Mode::Delete { world } => delete_page(ui, x, w, world),
- Mode::Error { message, .. } => error_page(ui, x, w, message),
- Mode::Multiplayer(screen) => {
- let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2);
- multiplayer_page(ui, x, w, screen, caret);
- }
- Mode::Edit { .. } | Mode::Backup { .. } => {
- unreachable!("World editing uses the classic layout")
- }
- }
- }
- ui.opacity = 1.0;
- ui.offset = (0.0, 0.0);
- if reveal < 1.0 {
- // The wordmark rises and fades as the interface comes in.
- let word = 1.0 - t::ease_out_cubic(reveal / 0.6);
- ui.opacity = word;
- let tw = ui.measure(Face::Display, t::WORDMARK, "horizon");
- let line = (t::WORDMARK * 1.2).round();
- ui.text_line(
- Face::Display,
- t::WORDMARK,
- line,
- ((ui.w - tw) / 2.0).round(),
- (ui.h - line) / 2.0 - 28.0 * (1.0 - word),
- color::TEXT,
- "horizon",
- );
- ui.opacity = 1.0;
- }
- }
- fn opening_phase(&self, ready: bool) -> f32 {
- let mut opening = self.opening.get();
- let phase = opening.as_mut().map_or(1.0, |o| o.phase(ready));
- self.opening.set(opening.filter(|_| phase < 1.0));
- phase.min(1.0)
- }
- /// A click or key during the opening jumps to the reveal; true if it did.
- pub fn skip_opening(&self) -> bool {
- let mut opening = self.opening.get();
- let skipped = opening.as_mut().is_some_and(|o| {
- let holding = o.reveal.is_none();
- o.skip();
- holding
- });
- self.opening.set(opening);
- skipped
- }
- fn sidebar(&self, ui: &mut Ui) {
- let (h, muted) = (ui.h, ui.muted);
- ui.sidebar_frame("Horizon");
- ui.sidebar_list(NAV, 12.0, 72.0, SIDEBAR - 24.0, &PAGES, page(&self.mode));
- let qy = h - 12.0 - 18.0 - 12.0 - CONTROL;
- let hover = ui.interact(QUIT, 12.0, qy, SIDEBAR - 24.0, CONTROL, true);
- ui.rounded(
- 12.0,
- qy,
- SIDEBAR - 24.0,
- CONTROL,
- t::PILL,
- color::with_alpha(color::RAISED, 0.8 * hover),
- );
- ui.text_line(
- Face::Regular,
- BODY,
- CONTROL,
- 24.0,
- qy,
- color::mix(muted, color::TEXT, hover),
- "Quit game",
- );
- ui.caps(
- 24.0,
- h - 12.0 - 18.0,
- muted,
- &format!("Horizon {}", horizon_core::VANILLA_VERSION),
- );
- }
- /// Home: the launcher's Play page over the backdrop.
- fn home(&self, ui: &mut Ui, x: f32, w: f32) {
- ui.wordmark(x, w, ui.h - 64.0, 220.0);
- let muted = ui.muted;
- let mut y = 36.0 + 28.0;
- ui.caps(
- x,
- y,
- muted,
- &format!(
- "Minecraft {} · Java Edition, rewritten in Rust",
- horizon_core::VANILLA_VERSION
- ),
- );
- y += 24.0;
- let line = (t::HERO * 1.1).round();
- ui.text_line(Face::Display, t::HERO, line, x, y, color::TEXT, "Horizon");
- y += line + 10.0;
- ui.text(
- Face::Regular,
- t::LARGE,
- x,
- y,
- muted,
- "The world you know, rebuilt from the ground up.",
- );
- y += 22.0 + 28.0;
- let pw = ui.button_width("Singleplayer", true).max(132.0);
- ui.button(
- PLAY,
- [x, y, pw, CONTROL_LARGE],
- "Singleplayer",
- Kind::Primary,
- true,
- );
- let mw = ui.button_width("Multiplayer", true);
- ui.button(
- MULTIPLAYER,
- [x + pw + 8.0, y, mw, CONTROL_LARGE],
- "Multiplayer",
- Kind::Secondary,
- true,
- );
- y += CONTROL_LARGE + 32.0;
- ui.row_index = 0;
- ui.divider(x, y, w);
- let worlds = self.recent_worlds();
- let last = worlds.first();
- let value = last.map_or("None yet".to_owned(), |l| {
- let secs = l
- .modified
- .duration_since(std::time::UNIX_EPOCH)
- .map_or(0, |d| d.as_secs());
- format!("{} · {}", l.name, crate::title::date_label(secs))
- });
- let rh = ui.row(x, y, "Last played", &value, w - t::ROW_LABEL - 120.0);
- if last.is_some() {
- let bw = ui.button_width("Resume", false);
- ui.button(
- RESUME,
- [x + w - bw, y + (rh - CONTROL) / 2.0, bw, CONTROL],
- "Resume",
- Kind::Secondary,
- true,
- );
- }
- y += rh;
- ui.divider(x, y, w);
- let count = match worlds.len() {
- 1 => "1 world".to_owned(),
- n => format!("{n} worlds"),
- };
- y += ui.row(x, y, "Saves", &count, w - t::ROW_LABEL - 16.0);
- ui.divider(x, y, w);
- ui.caps(
- x,
- ui.h - 12.0 - 18.0,
- muted,
- "Not affiliated with Mojang or Microsoft",
- );
- }
- /// A click in Horizon's layout (`x`, `y` in GUI pixels).
- pub fn click_horizon(
- &mut self,
- atlas: &HudAtlas,
- batch: &mut HudBatch,
- x: f32,
- y: f32,
- ) -> Action {
- self.remember_direct_address();
- if self.skip_opening() {
- return Action::None;
- }
- if classic(&self.mode) {
- return self.click(x, y, (batch.width, batch.height)).0;
- }
- let hit = {
- let mut ui = Ui::dry(atlas, batch, (x, y));
- self.draw_horizon(&mut ui, 1.0);
- ui.hit((x, y))
- };
- let Some(hit) = hit else {
- if let Mode::Create { focus, .. } = &mut self.mode {
- *focus = 2;
- }
- return Action::None;
- };
- let saves = self.saves.clone();
- let select = |saves: &std::path::Path| Mode::Select {
- worlds: list_worlds(saves),
- selected: None,
- };
- match hit {
- QUIT => return Action::Quit,
- h if h == NAV => {
- self.mode = Mode::Main;
- return Action::None;
- }
- h if h == NAV + 1 => {
- if !matches!(self.mode, Mode::Select { .. }) {
- self.mode = select(&saves);
- }
- return Action::None;
- }
- h if h == NAV + 2 => {
- if !matches!(self.mode, Mode::Multiplayer(_)) {
- self.mode = Mode::Multiplayer(Screen::list(&saves));
- }
- return Action::None;
- }
- h if h == NAV + 3 => return Action::Options,
- _ => {}
- }
- match &mut self.mode {
- Mode::Main => match hit {
- PLAY => self.mode = select(&saves),
- MULTIPLAYER => self.mode = Mode::Multiplayer(Screen::list(&saves)),
- RESUME => {
- if let Some(w) = list_worlds(&saves).into_iter().next() {
- return Action::Play { folder: w.folder };
- }
- }
- _ => {}
- },
- Mode::Select { worlds, selected } => match hit {
- PLAY_WORLD => {
- if let Some(w) = selected.and_then(|i| worlds.get(i)) {
- return Action::Play {
- folder: w.folder.clone(),
- };
- }
- }
- CREATE => self.mode = Title::new_world(),
- DELETE_WORLD => {
- if let Some(world) = selected.and_then(|i| worlds.get(i)).cloned() {
- self.mode = Mode::Delete { world };
- }
- }
- h if (WORLD..WORLD + 10_000).contains(&h) => {
- let i = (h - WORLD) as usize;
- if *selected == Some(i) {
- return Action::Play {
- folder: worlds[i].folder.clone(),
- };
- }
- *selected = Some(i);
- }
- _ => {}
- },
- Mode::Create {
- creative, focus, ..
- } => match hit {
- BACK => self.mode = select(&saves),
- NAME => *focus = 0,
- SEED => *focus = 1,
- h if h == MODE || h == MODE + 1 => *creative = h == MODE + 1,
- MAKE => return self.create_action(),
- _ => {}
- },
- Mode::Delete { .. } => match hit {
- // The selection stays in place: on the world that moved up
- // into the deleted one's row, or the new last one.
- CONFIRM_DELETE => {
- if let Some(row) = self.confirm_delete()
- && let Mode::Select { worlds, selected } = &mut self.mode
- {
- *selected = worlds.len().checked_sub(1).map(|last| row.min(last));
- }
- }
- BACK => self.escape(),
- _ => {}
- },
- Mode::Error { return_to, .. } => {
- if hit == BACK {
- self.mode = *return_to.clone();
- }
- }
- Mode::Edit { .. } | Mode::Backup { .. } => {}
- Mode::Multiplayer(screen) => {
- let id = match hit {
- JOIN => Some(40),
- DIRECT => Some(41),
- FRIEND => Some(47),
- ADD => Some(42),
- EDIT => Some(43),
- DELETE => Some(44),
- REFRESH => Some(45),
- BACK => Some(match screen {
- Screen::List { .. } => 46,
- Screen::Edit { .. } => 51,
- Screen::Direct { .. } => 53,
- Screen::Friend { .. } => 57,
- Screen::Disconnected { .. } => 54,
- Screen::ConfirmDelete { .. } => 59,
- }),
- CONFIRM_DELETE => Some(58),
- CANCEL_RETRY => Some(55),
- DONE => Some(match screen {
- Screen::Direct { .. } => 52,
- Screen::Friend { .. } => 56,
- _ => 50,
- }),
- FIELD_A | FIELD_B => {
- if let Screen::Edit { focus, .. } | Screen::Friend { focus, .. } = screen {
- *focus = u8::from(hit == FIELD_B);
- }
- None
- }
- h if (SERVER..SERVER + 10_000).contains(&h) => {
- let i = (h - SERVER) as usize;
- let again =
- matches!(screen, Screen::List { selected, .. } if *selected == Some(i));
- if again {
- if let Some(address) = screen.address_of(i) {
- return Action::Connect { address };
- }
- } else if let Screen::List { selected, .. } = screen {
- *selected = Some(i);
- }
- None
- }
- _ => None,
- };
- if let Some(id) = id {
- match self.multiplayer_click(Some(id), 0.0, 0.0, (0.0, 0.0)) {
- Outcome::Back => self.mode = Mode::Main,
- Outcome::Connect(address) => return Action::Connect { address },
- Outcome::None => {}
- }
- }
- }
- }
- Action::None
- }
-}
-
-/// The end of `text` that fits `width`, led by an ellipsis when cut.
-fn tail_fit(ui: &Ui, text: &str, width: f32) -> String {
- if ui.measure(Face::Regular, BODY, text) <= width {
- return text.to_owned();
- }
- let chars: Vec = text.chars().collect();
- let mut start = 0;
- while start < chars.len() {
- let tail: String = std::iter::once('…')
- .chain(chars[start..].iter().copied())
- .collect();
- if ui.measure(Face::Regular, BODY, &tail) <= width {
- return tail;
- }
- start += 1;
- }
- String::new()
-}
-
-/// The page header plus a row of actions under it; returns the y below.
-fn header(ui: &mut Ui, x: f32, title: &str, description: &str) -> f32 {
- let y = 36.0;
- y + ui.page_header(x, y, title, description) + 24.0
-}
-/// Actions laid out right to left from `right`; returns the left edge.
-fn actions_right(ui: &mut Ui, right: f32, y: f32, items: &[(u64, &str, Kind, bool)]) -> f32 {
- let mut rx = right;
- for &(bid, label, kind, on) in items {
- let large = kind == Kind::Primary;
- let (bw, bh) = if large {
- (ui.button_width(label, true).max(120.0), CONTROL_LARGE)
- } else {
- (ui.button_width(label, false), CONTROL)
- };
- rx -= bw;
- ui.button(
- bid,
- [rx, y + (CONTROL_LARGE - bh) / 2.0, bw, bh],
- label,
- kind,
- on,
- );
- rx -= 8.0;
- }
- rx
-}
-/// A selectable list row: its number, the name and a line under it, a mono
-/// detail on the right; a soft plate fades in under the pointer and stays
-/// under the selection, reaching past the row. Returns the row height.
-#[allow(clippy::too_many_arguments)]
-fn list_row(
- ui: &mut Ui,
- rid: u64,
- x: f32,
- y: f32,
- w: f32,
- selected: bool,
- title: &str,
- meta: &str,
- right: &str,
- dot: Option,
-) -> f32 {
- let h = 64.0;
- let hover = ui.interact(rid, x - 16.0, y + 2.0, w + 32.0, h - 4.0, true);
- let sel = ui.tween(rid ^ 0x5e1ec7, if selected { 1.0 } else { 0.0 }, t::quick());
- ui.rounded(
- x - 16.0,
- y + 3.0,
- w + 32.0,
- h - 6.0,
- t::RADIUS_PLATE,
- color::with_alpha(color::RAISED, (0.7 * hover).max(sel)),
- );
- ui.row_index += 1;
- let n = format!("{:02}", ui.row_index);
- ui.text(
- Face::Mono,
- t::MICRO,
- x,
- y + 15.0,
- color::mix(color::FAINT, color::TEXT, sel),
- &n,
- );
- let mut tx = x + t::INDEX;
- if let Some(dot) = dot {
- ui.rounded(tx, y + 19.0, 6.0, 6.0, 3.0, dot);
- tx += 16.0;
- }
- let title = ui.fit(Face::Medium, t::LARGE + 2.0, title, w - 240.0);
- ui.text(
- Face::Medium,
- t::LARGE + 2.0,
- tx,
- y + 10.0,
- color::TEXT,
- &title,
- );
- let meta = ui.fit(Face::Regular, SMALL, meta, w - 240.0);
- ui.text(Face::Regular, SMALL, tx, y + 35.0, color::FAINT, &meta);
- let right = right.to_uppercase();
- ui.text_right(Face::Mono, t::MICRO, x + w, y + 25.0, color::FAINT, &right);
- ui.divider(x, y + h, w);
- h
-}
-/// An empty list: a short line in heading type and a hint.
-fn empty(ui: &mut Ui, x: f32, y: f32, title: &str, hint: &str) {
- ui.text_line(
- Face::Display,
- t::HEADING,
- 28.0,
- x,
- y + 32.0,
- color::TEXT,
- title,
- );
- ui.text(Face::Regular, BODY, x, y + 64.0, color::FAINT, hint);
-}
-
-fn worlds_page(
- ui: &mut Ui,
- x: f32,
- w: f32,
- worlds: &[crate::title::WorldEntry],
- selected: Option,
-) {
- let count = match worlds.len() {
- 0 => "No worlds yet. They live in the saves folder.".to_owned(),
- 1 => "1 world in the saves folder.".to_owned(),
- n => format!("{n} worlds in the saves folder."),
- };
- let mut y = header(ui, x, "Singleplayer", &count);
- let mut items = vec![
- (PLAY_WORLD, "Play", Kind::Primary, selected.is_some()),
- (CREATE, "Create world", Kind::Secondary, true),
- ];
- if selected.is_some() {
- items.push((DELETE_WORLD, "Delete", Kind::Danger, true));
- }
- actions_right(ui, x + w, y - 24.0 - 58.0, &items);
- ui.divider(x, y, w);
- if worlds.is_empty() {
- empty(ui, x, y, "A blank map.", "Create a world to begin.");
- return;
- }
- let bottom = ui.h - 36.0;
- for (i, world) in worlds.iter().enumerate() {
- if y + 60.0 > bottom {
- break;
- }
- let secs = world
- .modified
- .duration_since(std::time::UNIX_EPOCH)
- .map_or(0, |d| d.as_secs());
- let meta = format!("{} · {}", crate::title::date_label(secs), world.folder);
- let mode = if world.creative {
- "Creative"
- } else {
- "Survival"
- };
- y += list_row(
- ui,
- WORLD + i as u64,
- x,
- y,
- w,
- selected == Some(i),
- &world.name,
- &meta,
- mode,
- None,
- );
- }
-}
-
-/// The launcher's notice: a plate led by a danger dot, the first line in
-/// medium type, wrapped lines under it. Returns its height.
-fn notice(ui: &mut Ui, x: f32, y: f32, w: f32, title: Option<&str>, text: &str) -> f32 {
- let lines = wrap(ui, text, w - 48.0);
- let title_h = if title.is_some() { 26.0 } else { 0.0 };
- let h = 32.0 + title_h + lines.len() as f32 * 19.0;
- ui.rounded(x, y, w, h, t::RADIUS_PLATE, color::RAISED);
- ui.rounded(x + 16.0, y + 22.0, 6.0, 6.0, 3.0, color::DANGER);
- let mut ty = y + 16.0;
- if let Some(title) = title {
- let title = ui.fit(Face::Medium, t::LARGE + 2.0, title, w - 48.0);
- ui.text_line(
- Face::Medium,
- t::LARGE + 2.0,
- 19.0,
- x + 32.0,
- ty,
- color::TEXT,
- &title,
- );
- ty += title_h;
- }
- for (i, line) in lines.iter().enumerate() {
- let tint = if title.is_some() {
- color::MUTED
- } else {
- color::TEXT
- };
- ui.text_line(
- Face::Regular,
- BODY,
- 19.0,
- x + 32.0,
- ty + i as f32 * 19.0,
- tint,
- line,
- );
- }
- h
-}
-
-/// `ConfirmScreen` for a world: what goes, that it can't come back, then
-/// Delete (danger) and Cancel under it.
-fn delete_page(ui: &mut Ui, x: f32, w: f32, world: &crate::title::WorldEntry) {
- let mut y = header(
- ui,
- x,
- "Delete this world?",
- "It will be lost forever. This can't be undone.",
- );
- ui.divider(x, y, w);
- y += 16.0;
- let secs = world
- .modified
- .duration_since(std::time::UNIX_EPOCH)
- .map_or(0, |d| d.as_secs());
- let text = format!(
- "Last played {}. The folder saves/{} and everything built in it will be removed.",
- crate::title::date_label(secs),
- world.folder
- );
- y += notice(ui, x, y, w, Some(&world.name), &text) + 16.0;
- let dw = ui.button_width("Delete world", false);
- ui.button(
- CONFIRM_DELETE,
- [x, y, dw, CONTROL],
- "Delete world",
- Kind::Danger,
- true,
- );
- let cw = ui.button_width("Cancel", false);
- ui.button(
- BACK,
- [x + dw + 8.0, y, cw, CONTROL],
- "Cancel",
- Kind::Ghost,
- true,
- );
-}
-
-fn error_page(ui: &mut Ui, x: f32, w: f32, message: &str) {
- let mut y = header(
- ui,
- x,
- "Something went wrong",
- "Horizon couldn't finish that.",
- );
- ui.divider(x, y, w);
- y += 16.0;
- y += notice(ui, x, y, w, None, message) + 16.0;
- let bw = ui.button_width("Back", false);
- ui.button(BACK, [x, y, bw, CONTROL], "Back", Kind::Secondary, true);
-}
-
-#[allow(clippy::too_many_arguments)]
-fn create_page(
- ui: &mut Ui,
- x: f32,
- w: f32,
- name: &str,
- seed: &str,
- creative: bool,
- focus: u8,
- caret: bool,
-) {
- let mut y = header(
- ui,
- x,
- "Create world",
- "Generated by Horizon from the seed, as vanilla would.",
- );
- actions_right(
- ui,
- x + w,
- y - 24.0 - 58.0,
- &[
- (MAKE, "Create", Kind::Primary, true),
- (BACK, "Cancel", Kind::Ghost, true),
- ],
- );
- ui.divider(x, y, w);
- let fx = x + t::ROW_LABEL + 16.0;
- let fw = (w - t::ROW_LABEL - 16.0).min(360.0);
- for (i, label) in ["World name", "Seed", "Game mode"].iter().enumerate() {
- let rh = 12.0 + CONTROL + 12.0;
- ui.text_line(Face::Regular, BODY, rh, x, y, color::MUTED, label);
- let r = [fx, y + 12.0, fw, CONTROL];
- match i {
- 0 => ui.field(NAME, r, name, "New World", focus == 0, caret),
- 1 => ui.field(SEED, r, seed, "Random", focus == 1, caret),
- _ => {
- ui.segmented(
- MODE,
- fx,
- y + 12.0,
- &["Survival", "Creative"],
- usize::from(creative),
- );
- }
- }
- y += rh;
- ui.divider(x, y, w);
- }
-}
-
-fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
- match screen {
- Screen::List {
- servers,
- selected,
- pings,
- lan,
- ..
- } => {
- let games = lan.games();
- let sub = match servers.len() {
- 0 => "No saved servers. Worlds opened to LAN show up here too.".to_owned(),
- 1 => "1 saved server, and worlds opened to LAN.".to_owned(),
- n => format!("{n} saved servers, and worlds opened to LAN."),
- };
- let mut y = header(ui, x, "Multiplayer", &sub);
- let has = selected.is_some();
- let saved = selected.is_some_and(|i| i < servers.len());
- let mut items = vec![
- (JOIN, "Join", Kind::Primary, has),
- (FRIEND, "Join a friend", Kind::Secondary, true),
- (ADD, "Add server", Kind::Secondary, true),
- (DIRECT, "Direct connect", Kind::Secondary, true),
- (REFRESH, "Refresh", Kind::Ghost, true),
- ];
- if saved {
- items.push((EDIT, "Edit", Kind::Ghost, true));
- items.push((DELETE, "Delete", Kind::Danger, true));
- }
- actions_right(ui, x + w, y - 24.0 - 58.0, &items);
- ui.divider(x, y, w);
- let pings = pings.lock().map(|p| p.clone()).unwrap_or_default();
- let mut rows: Vec<(String, String, String, u32)> = servers
- .iter()
- .map(|s| {
- let (line, right, dot) = match pings.get(&s.ip) {
- Some(Ping::Ok {
- motd, players, ms, ..
- }) => (
- motd.resolve_legacy()
- .plain()
- .lines()
- .next()
- .unwrap_or("")
- .trim()
- .to_owned(),
- format!("{} · {ms} ms", Ping::player_count(*players).plain()),
- color::ACCENT,
- ),
- Some(Ping::Failed(_)) => (
- "Can't reach the server".to_owned(),
- String::new(),
- color::DANGER,
- ),
- _ => ("Pinging…".to_owned(), String::new(), color::FAINT),
- };
- (s.name.clone(), format!("{line} · {}", s.ip), right, dot)
- })
- .collect();
- rows.extend(games.iter().map(|g| {
- (
- "LAN world".to_owned(),
- format!("{} · {}", g.motd, g.address),
- "On your network".to_owned(),
- color::ACCENT,
- )
- }));
- if rows.is_empty() {
- empty(
- ui,
- x,
- y,
- "Nobody here yet.",
- "Add a server, connect directly, or open a world to LAN.",
- );
- return;
- }
- let bottom = ui.h - 36.0;
- for (i, (name, meta, right, dot)) in rows.iter().enumerate() {
- if y + 60.0 > bottom {
- break;
- }
- y += list_row(
- ui,
- SERVER + i as u64,
- x,
- y,
- w,
- *selected == Some(i),
- name,
- meta,
- right,
- Some(*dot),
- );
- }
- }
- Screen::Edit {
- index,
- name,
- address,
- focus,
- } => {
- let title = if index.is_some() {
- "Edit server"
- } else {
- "Add server"
- };
- let mut y = header(
- ui,
- x,
- title,
- "Saved to servers.dat, like vanilla's server list.",
- );
- let ok = horizon_protocol::servers::parse_address(address).is_some();
- actions_right(
- ui,
- x + w,
- y - 24.0 - 58.0,
- &[
- (DONE, "Save", Kind::Primary, ok),
- (BACK, "Cancel", Kind::Ghost, true),
- ],
- );
- ui.divider(x, y, w);
- let fx = x + t::ROW_LABEL + 16.0;
- let fw = (w - t::ROW_LABEL - 16.0).min(360.0);
- for (i, (label, value, hint)) in [
- ("Name", name, "Minecraft Server"),
- ("Address", address, "play.example.net"),
- ]
- .iter()
- .enumerate()
- {
- let rh = 12.0 + CONTROL + 12.0;
- ui.text_line(Face::Regular, BODY, rh, x, y, color::MUTED, label);
- let fid = if i == 0 { FIELD_A } else { FIELD_B };
- ui.field(
- fid,
- [fx, y + 12.0, fw, CONTROL],
- value,
- hint,
- usize::from(*focus) == i,
- caret,
- );
- y += rh;
- ui.divider(x, y, w);
- }
- }
- Screen::Direct { address } => {
- let y = header(
- ui,
- x,
- "Direct connect",
- "Join a server once without saving it.",
- );
- let ok = horizon_protocol::servers::parse_address(address).is_some();
- actions_right(
- ui,
- x + w,
- y - 24.0 - 58.0,
- &[
- (DONE, "Join", Kind::Primary, ok),
- (BACK, "Cancel", Kind::Ghost, true),
- ],
- );
- ui.divider(x, y, w);
- let rh = 12.0 + CONTROL + 12.0;
- ui.text_line(Face::Regular, BODY, rh, x, y, color::MUTED, "Address");
- let fx = x + t::ROW_LABEL + 16.0;
- ui.field(
- FIELD_A,
- [fx, y + 12.0, (w - t::ROW_LABEL - 16.0).min(360.0), CONTROL],
- address,
- "host:port",
- true,
- caret,
- );
- ui.divider(x, y + rh, w);
- }
- Screen::Friend { code, relay, focus } => {
- let y = header(
- ui,
- x,
- "Join a friend",
- "Paste the invite code your friend sees in their pause menu.",
- );
- let parsed = horizon_friends::invite::parse_detailed(code);
- let ok = parsed.is_ok();
- actions_right(
- ui,
- x + w,
- y - 24.0 - 58.0,
- &[
- (DONE, "Join", Kind::Primary, ok),
- (BACK, "Cancel", Kind::Ghost, true),
- ],
- );
- ui.divider(x, y, w);
- let rh = 12.0 + CONTROL + 12.0;
- let fx = x + t::ROW_LABEL + 16.0;
- let fw = w - t::ROW_LABEL - 16.0;
- let rows = [
- (FIELD_A, "Invite code", code, "Paste the code here", fw),
- (
- FIELD_B,
- "Relay (optional)",
- relay,
- "host:port, for short codes",
- fw.min(360.0),
- ),
- ];
- let mut ry = y;
- for (i, (fid, label, value, hint, width)) in rows.into_iter().enumerate() {
- ui.text_line(Face::Regular, BODY, rh, x, ry, color::MUTED, label);
- // A long code shows its end, where the typing is.
- let shown = tail_fit(ui, value, width - 28.0);
- ui.field(
- fid,
- [fx, ry + 12.0, width, CONTROL],
- &shown,
- hint,
- usize::from(*focus) == i,
- caret,
- );
- ry += rh;
- ui.divider(x, ry, w);
- }
- let note = match parsed {
- _ if code.trim().is_empty() => None,
- Err(e) => Some(e.to_string()),
- Ok(horizon_friends::invite::Parsed::Short(_)) if relay.trim().is_empty() => Some(
- "This is a relay's short code: fill in your friend's relay above, or ask for the full code."
- .to_owned(),
- ),
- Ok(_) => None,
- };
- if let Some(note) = note {
- ui.text(Face::Regular, SMALL, x, ry + 12.0, color::MUTED, ¬e);
- }
- }
- Screen::ConfirmDelete { name, .. } => {
- let mut y = header(
- ui,
- x,
- "Remove this server?",
- "It leaves your list. You can add it again later.",
- );
- ui.divider(x, y, w);
- y += 16.0;
- y += notice(
- ui,
- x,
- y,
- w,
- Some(name),
- "Its address and icon will be forgotten.",
- ) + 16.0;
- let dw = ui.button_width("Delete server", false);
- ui.button(
- CONFIRM_DELETE,
- [x, y, dw, CONTROL],
- "Delete server",
- Kind::Danger,
- true,
- );
- let cw = ui.button_width("Cancel", false);
- ui.button(
- BACK,
- [x + dw + 8.0, y, cw, CONTROL],
- "Cancel",
- Kind::Ghost,
- true,
- );
- }
- Screen::Disconnected { reason, retry } => {
- let mut y = header(
- ui,
- x,
- "Connection lost",
- "The server closed the connection.",
- );
- ui.divider(x, y, w);
- y += 16.0;
- y += notice(ui, x, y, w, None, reason) + 16.0;
- if let Some(r) = retry {
- // Auto-reconnect's countdown, with a way out.
- let text = r.text(std::time::Instant::now());
- ui.text_line(Face::Regular, BODY, 19.0, x, y, color::MUTED, &text);
- y += 19.0 + 12.0;
- }
- let bw = ui.button_width("Back to servers", false);
- ui.button(
- BACK,
- [x, y, bw, CONTROL],
- "Back to servers",
- Kind::Secondary,
- true,
- );
- if retry.is_some() {
- let cw = ui.button_width("Cancel reconnecting", false);
- ui.button(
- CANCEL_RETRY,
- [x + bw + 8.0, y, cw, CONTROL],
- "Cancel reconnecting",
- Kind::Ghost,
- true,
- );
- }
- }
- }
-}
-/// Greedy word wrap in dp.
-pub fn wrap(ui: &Ui, text: &str, width: f32) -> Vec {
- let mut lines = Vec::new();
- for para in text.lines() {
- let mut line = String::new();
- for word in para.split_whitespace() {
- let next = if line.is_empty() {
- word.to_owned()
- } else {
- format!("{line} {word}")
- };
- if !line.is_empty() && ui.measure(Face::Regular, BODY, &next) > width {
- lines.push(std::mem::replace(&mut line, word.to_owned()));
- } else {
- line = next;
- }
- }
- lines.push(line);
- }
- lines
-}
-
-/// The pause menu in Horizon's style: the launcher's sidebar over the
-/// blurred world, with the game's actions as a page. Ids match
-/// `game/screens.rs`'s PauseScreen actions: 0 back to game, 1 options,
-/// 2 save and quit, 3 statistics, 4 advancements, 9 world options.
-/// Play with friends as the pause menu shows it (game/friends.rs fills it).
-#[derive(Clone, Debug, Default)]
-pub struct FriendsView {
- /// A singleplayer world (not a server): the button is offered.
- pub shown: bool,
- pub sharing: bool,
- pub code: Option,
- /// Who can join and what to do when friends on the internet can't (or,
- /// before the code, what the game is doing).
- pub status: String,
- /// Friends on the internet can reach the host.
- pub reachable: bool,
- /// Where the troubleshooting is, when they can't.
- pub help: Option,
- /// The players in the world besides the host.
- pub guests: Vec,
- pub notice: Option,
- /// The code was just copied.
- pub copied: bool,
-}
-
-pub mod pause {
- use super::*;
- fn act(a: u8) -> u64 {
- id("pause", u64::from(a))
- }
- pub fn draw(
- ui: &mut Ui,
- world: &str,
- quit_label: &str,
- opened: Instant,
- friends: &FriendsView,
- remote: bool,
- ) {
- let (w, h) = (ui.w, ui.h);
- let p = t::ease_out_quint(opened.elapsed().as_secs_f32() / t::move_());
- ui.opacity = p;
- ui.atmosphere(horizon_theme::VEIL, 1.0);
- ui.offset = (-16.0 * (1.0 - p), 0.0);
- ui.sidebar_frame("Horizon");
- ui.sidebar_list(
- id("pause.nav", 0),
- 12.0,
- 72.0,
- SIDEBAR - 24.0,
- &["Game", "Advancements", "Statistics", "Options"],
- 0,
- );
- ui.caps(
- 24.0,
- h - 12.0 - 18.0,
- color::FAINT,
- &format!("Horizon {}", horizon_core::VANILLA_VERSION),
- );
- ui.offset = (0.0, 8.0 * (1.0 - p));
- let x = SIDEBAR + 48.0;
- let cw = (w - x - 48.0).min(760.0);
- let mut y = 36.0 + 28.0;
- ui.caps(x, y, color::FAINT, "Game paused");
- y += 24.0;
- let line = (t::HERO * 1.1).round();
- let title = ui.fit(Face::Display, t::HERO, world, cw);
- ui.text_line(Face::Display, t::HERO, line, x, y, color::TEXT, &title);
- y += line + 32.0;
- let bw = ui.button_width("Back to game", true).max(120.0);
- ui.button(
- act(0),
- [x, y, bw, CONTROL_LARGE],
- "Back to game",
- Kind::Primary,
- true,
- );
- let lw = ui.button_width("World Options", true);
- ui.button(
- act(9),
- [x + bw + 8.0, y, lw, CONTROL_LARGE],
- "World Options",
- Kind::Secondary,
- true,
- );
- if friends.shown {
- let iw = ui.button_width("Invite friends", true);
- ui.button(
- act(10),
- [x + bw + lw + 16.0, y, iw, CONTROL_LARGE],
- "Invite friends",
- Kind::Secondary,
- !friends.sharing,
- );
- }
- y += CONTROL_LARGE + 32.0;
- ui.row_index = 0;
- if friends.sharing {
- y = invite(ui, x, y, cw, friends);
- }
- ui.divider(x, y, cw);
- let rh = ui.row(
- x,
- y,
- "Leave",
- if remote {
- "Disconnects from the server, then returns to the title."
- } else {
- "Saves the world, then returns to the title."
- },
- cw - t::ROW_LABEL - 220.0,
- );
- let qw = ui.button_width(quit_label, false);
- ui.button(
- act(2),
- [x + cw - qw, y + (rh - CONTROL) / 2.0, qw, CONTROL],
- quit_label,
- Kind::Danger,
- true,
- );
- y += rh;
- ui.divider(x, y, cw);
- ui.opacity = 1.0;
- ui.offset = (0.0, 0.0);
- }
- /// The invite section while sharing: the code with Copy and Stop
- /// sharing, who is here, and what changed. Returns the y below it.
- /// The code's groups packed into lines of at most `width`.
- fn code_lines(ui: &Ui, code: &str, width: f32) -> Vec {
- let mut lines: Vec = Vec::new();
- for group in code.split('-') {
- match lines.last_mut() {
- Some(l) if ui.measure(Face::Mono, BODY, &format!("{l}-{group}")) <= width => {
- l.push('-');
- l.push_str(group);
- }
- _ => lines.push(group.to_owned()),
- }
- }
- lines
- }
- fn invite(ui: &mut Ui, x: f32, mut y: f32, cw: f32, f: &FriendsView) -> f32 {
- ui.divider(x, y, cw);
- let top = y + 12.0;
- ui.text(
- Face::Regular,
- BODY,
- x,
- top + 6.0,
- color::MUTED,
- "Invite code",
- );
- let vx = x + t::ROW_LABEL + 16.0;
- let stop = "Stop sharing";
- let sw = ui.button_width(stop, false);
- ui.button(
- act(12),
- [x + cw - sw, top, sw, CONTROL],
- stop,
- Kind::Danger,
- true,
- );
- let copy = if f.copied { "Copied" } else { "Copy" };
- let copy_w = ui.button_width("Copied", false);
- let buttons = sw + 8.0 + copy_w;
- ui.button(
- act(11),
- [x + cw - buttons, top, copy_w, CONTROL],
- copy,
- Kind::Secondary,
- f.code.is_some(),
- );
- let line = (BODY * 1.45).round();
- let value_w = (cw - t::ROW_LABEL - 16.0 - buttons - 16.0).max(120.0);
- y = top + 6.0;
- match &f.code {
- Some(code) => {
- for l in code_lines(ui, code, value_w) {
- ui.text(Face::Mono, BODY, vx, y, color::TEXT, &l);
- y += line;
- }
- }
- None => {
- for l in wrap(ui, &f.status, value_w) {
- ui.text(Face::Regular, BODY, vx, y, color::MUTED, &l);
- y += line;
- }
- }
- }
- y = y.max(top + CONTROL) + 10.0;
- let small = (SMALL * 1.45).round();
- if f.code.is_some() {
- // Who can join: plain when friends anywhere can, in the text
- // colour (it asks for something) when only the LAN and VPNs can.
- let tint = if f.reachable {
- color::MUTED
- } else {
- color::TEXT
- };
- for l in wrap(ui, &f.status, cw) {
- ui.text(Face::Regular, SMALL, x, y, tint, &l);
- y += small;
- }
- if let Some(help) = &f.help {
- let l = ui.fit(Face::Regular, SMALL, &format!("Help: {help}"), cw);
- ui.text(Face::Regular, SMALL, x, y, color::FAINT, &l);
- y += small;
- }
- }
- let here = if f.guests.is_empty() {
- "No friends here yet.".to_owned()
- } else {
- format!("Here now: {}", f.guests.join(", "))
- };
- let hint =
- "Friends paste the code in Multiplayer, Join a friend, or on the launcher's Play page.";
- let lines = [
- Some((here, color::MUTED)),
- f.notice.clone().map(|n| (n, color::MUTED)),
- Some((hint.to_owned(), color::FAINT)),
- ];
- for (line, tint) in lines.into_iter().flatten() {
- let line = ui.fit(Face::Regular, SMALL, &line, cw);
- ui.text(Face::Regular, SMALL, x, y, tint, &line);
- y += small;
- }
- y + 12.0
- }
- /// The PauseScreen action under a click, if any.
- pub fn click(
- atlas: &HudAtlas,
- batch: &mut HudBatch,
- x: f32,
- y: f32,
- world: &str,
- quit_label: &str,
- friends: &FriendsView,
- remote: bool,
- ) -> Option {
- let mut ui = Ui::dry(atlas, batch, (x, y));
- draw(
- &mut ui,
- world,
- quit_label,
- Instant::now() - std::time::Duration::from_secs(5),
- friends,
- remote,
- );
- let hit = ui.hit((x, y))?;
- let nav = id("pause.nav", 0);
- match hit {
- h if h == nav => Some(0),
- h if h == nav + 1 => Some(4),
- h if h == nav + 2 => Some(3),
- h if h == nav + 3 => Some(1),
- h => [0u8, 1, 2, 3, 4, 9, 10, 11, 12]
- .into_iter()
- .find(|&a| act(a) == h),
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use horizon_world::nbt::Tag;
-
- #[test]
- fn pause_world_options_and_disconnect_are_clickable_on_servers() {
- let atlas =
- HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap();
- let friends = FriendsView::default();
- for remote in [false, true] {
- let quit = if remote {
- "Disconnect"
- } else {
- "Save and quit"
- };
- for action in [9u8, 2] {
- let mut batch = HudBatch::new([1280, 720]);
- let (rect, density) = {
- let mut ui = Ui::dry(&atlas, &mut batch, (0.0, 0.0));
- pause::draw(
- &mut ui,
- "World",
- quit,
- Instant::now() - std::time::Duration::from_secs(5),
- &friends,
- remote,
- );
- let hit = ui
- .hits
- .iter()
- .find(|h| h.id == id("pause", u64::from(action)))
- .expect("pause action available");
- (hit.rect, ui.density)
- };
- let k = density / batch.scale;
- let x = (rect[0] + rect[2]) / 2.0 * k;
- let y = (rect[1] + rect[3]) / 2.0 * k;
- assert_eq!(
- pause::click(&atlas, &mut batch, x, y, "World", quit, &friends, remote),
- Some(action)
- );
- }
- }
- }
-
- fn world(saves: &std::path::Path, folder: &str, last_played: i64) {
- crate::save::write_dat(
- &saves.join(folder).join("level.dat"),
- Tag::compound([(
- "Data",
- Tag::compound([
- ("LevelName", Tag::String(folder.into())),
- ("GameType", Tag::Int(0)),
- ("LastPlayed", Tag::Long(last_played)),
- ("WorldGenSettings", Tag::compound([("seed", Tag::Long(1))])),
- ]),
- )]),
- )
- .unwrap();
- }
- /// Clicks the middle of button `bid` as the game would; panics if the
- /// page does not show it.
- fn press(title: &mut Title, atlas: &HudAtlas, bid: u64) -> Action {
- let mut batch = HudBatch::new([1280, 720]);
- let (rect, density) = {
- let mut ui = Ui::dry(atlas, &mut batch, (0.0, 0.0));
- title.draw_horizon(&mut ui, 1.0);
- let hit = ui.hits.iter().rev().find(|h| h.id == bid);
- (hit.expect("button on the page").rect, ui.density)
- };
- let k = density / batch.scale;
- let (x, y) = ((rect[0] + rect[2]) / 2.0 * k, (rect[1] + rect[3]) / 2.0 * k);
- title.click_horizon(atlas, &mut batch, x, y)
- }
- fn shows(title: &Title, atlas: &HudAtlas, bid: u64) -> bool {
- let mut batch = HudBatch::new([1280, 720]);
- let mut ui = Ui::dry(atlas, &mut batch, (0.0, 0.0));
- title.draw_horizon(&mut ui, 1.0);
- ui.hits.iter().any(|h| h.id == bid)
- }
- fn selected(title: &Title) -> Option {
- match &title.mode {
- Mode::Select { worlds, selected } => selected.map(|i| worlds[i].folder.clone()),
- _ => panic!("not on the world list"),
- }
- }
-
- #[test]
- fn horizon_direct_connection_remembers_the_address_after_leaving() {
- let atlas =
- HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap();
- let saves =
- std::env::temp_dir().join(format!("horizon-front-direct-{}", std::process::id()));
- let mut title = Title::new(saves.clone(), &saves);
- title.last_server = "localhost:25566".into();
- title.mode = Mode::Multiplayer(Screen::list(&saves));
- press(&mut title, &atlas, DIRECT);
- assert_eq!(title.focused_field().unwrap().1, "localhost:25566");
- *title.focused_field().unwrap().1 = "example.org:25567".into();
- press(&mut title, &atlas, BACK);
- press(&mut title, &atlas, DIRECT);
- assert_eq!(title.focused_field().unwrap().1, "example.org:25567");
- *title.focused_field().unwrap().1 = "localhost:25568".into();
- press(&mut title, &atlas, NAV);
- press(&mut title, &atlas, NAV + 2);
- press(&mut title, &atlas, DIRECT);
- assert_eq!(title.focused_field().unwrap().1, "localhost:25568");
- }
-
- #[test]
- fn horizon_world_delete_confirms_and_keeps_the_selection_in_place() {
- let atlas =
- HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap();
- let root =
- std::env::temp_dir().join(format!("horizon-front-delete-{}", std::process::id()));
- let saves = root.join("saves");
- for (i, folder) in ["C", "B", "A"].iter().enumerate() {
- world(&saves, folder, 1000 * (i as i64 + 1));
- }
- let mut title = Title::new(saves.clone(), &saves);
- title.mode = Mode::Select {
- worlds: list_worlds(&saves),
- selected: None,
- };
- assert!(!shows(&title, &atlas, DELETE_WORLD));
- press(&mut title, &atlas, WORLD + 1);
- assert_eq!(selected(&title).as_deref(), Some("B"));
-
- // Cancel leaves the world and its selection.
- press(&mut title, &atlas, DELETE_WORLD);
- assert!(matches!(&title.mode, Mode::Delete { world } if world.folder == "B"));
- press(&mut title, &atlas, BACK);
- assert_eq!(selected(&title).as_deref(), Some("B"));
- assert!(saves.join("B/level.dat").is_file());
-
- // Deleting selects the world that moved up into the row.
- press(&mut title, &atlas, DELETE_WORLD);
- press(&mut title, &atlas, CONFIRM_DELETE);
- assert!(!saves.join("B").exists());
- assert_eq!(selected(&title).as_deref(), Some("C"));
-
- // A world open elsewhere is refused on a Horizon page; Back returns
- // to the question.
- let open = crate::save::SessionLock::acquire(&saves.join("C")).unwrap();
- press(&mut title, &atlas, DELETE_WORLD);
- press(&mut title, &atlas, CONFIRM_DELETE);
- assert!(matches!(title.mode, Mode::Error { .. }));
- assert!(!classic(&title.mode));
- press(&mut title, &atlas, BACK);
- assert!(matches!(title.mode, Mode::Delete { .. }));
- drop(open);
-
- // The last row: the selection moves to the new last world.
- press(&mut title, &atlas, CONFIRM_DELETE);
- assert_eq!(selected(&title).as_deref(), Some("A"));
- press(&mut title, &atlas, DELETE_WORLD);
- press(&mut title, &atlas, CONFIRM_DELETE);
- assert!(
- matches!(&title.mode, Mode::Select { worlds, selected: None } if worlds.is_empty())
- );
- let _ = std::fs::remove_dir_all(root);
- }
-}
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index f3dd70154..31ef76f5f 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -5,7 +5,6 @@ mod advancements_screen;
mod agent;
mod allays;
mod armor_stands;
-mod backdrop;
mod banners;
mod beacon;
mod beehives;
@@ -456,6 +455,9 @@ enum Screen {
Advancements,
/// WorldOptionsScreen (game/lan_screen.rs).
WorldOptions,
+ /// Play with Friends, from the pause menu's Friends button
+ /// (`friends_screen`, game/friends.rs).
+ Friends,
/// CommandBlockEditScreen (game/command_blocks.rs).
CommandBlock,
}
@@ -1316,10 +1318,6 @@ struct Game<'a> {
settings: Settings,
/// Where the options screen returns: true = title, false = pause menu.
options_from_title: bool,
- /// The live title backdrop (game/backdrop.rs).
- backdrop: backdrop::Backdrop,
- /// When the pause menu opened (Horizon style's entrance).
- pause_since: Option,
dragging: bool,
/// `ClientAvatarState`: walked distance and view bob.
avatar: horizon_client::camera::AvatarBob,
@@ -4456,6 +4454,7 @@ impl Game<'_> {
| Screen::Stats
| Screen::Advancements
| Screen::WorldOptions
+ | Screen::Friends
| Screen::CommandBlock
) || self.book.is_some())
}
@@ -4683,20 +4682,12 @@ impl Game<'_> {
}
}
if let Some(title) = &self.title {
- if horizon_client::ui_theme::horizon() {
- let fade = self.backdrop_fade();
- let mut ui =
- horizon_client::ui_theme::Ui::new(&self.gui.atlas, &mut batch, self.cursor);
- title.draw_horizon(&mut ui, fade);
- ui.finish();
- } else {
- title.draw(
- &self.gui.atlas,
- &mut batch,
- self.cursor,
- self.settings.file.bool("hideSplashTexts"),
- );
- }
+ title.draw(
+ &self.gui.atlas,
+ &mut batch,
+ self.cursor,
+ self.settings.file.bool("hideSplashTexts"),
+ );
return batch;
}
let atlas_ptr: *const HudAtlas = &self.gui.atlas;
@@ -4713,9 +4704,7 @@ impl Game<'_> {
// the sleep overlay, debug screen and open screens still draw.
let spectator = self.spectator();
let (wi, hi) = (w as i32, h as i32);
- // Horizon's pause menu sits over the blurred world alone.
- let horizon_pause = self.horizon_pause();
- let show_hud = !self.ui.hide_gui && !horizon_pause;
+ let show_hud = !self.ui.hide_gui;
if show_hud {
self.draw_spyglass(&mut batch);
// Hud.extractCrosshair / extractItemHotbar / extractPlayerHealth /
@@ -4849,10 +4838,8 @@ impl Game<'_> {
let tw = HudBatch::text_width(atlas, text);
batch.text(atlas, text, (w - tw) / 2.0, h - 59.0, u32::MAX, true);
}
- if !horizon_pause {
- self.draw_chat(&mut batch);
- self.draw_tab_list(&mut batch);
- }
+ self.draw_chat(&mut batch);
+ self.draw_tab_list(&mut batch);
// Screen.extractBlurredBackground blurs the world and HUD, while the
// screen's background, widgets, toasts and debug overlay stay sharp.
batch.blur_at = batch.vertices.len() as u32;
@@ -4876,6 +4863,7 @@ impl Game<'_> {
Screen::Stats => self.draw_stats(&mut batch),
Screen::Advancements => self.draw_advancements(&mut batch),
Screen::WorldOptions => self.draw_world_options(&mut batch),
+ Screen::Friends => self.draw_friends_screen(&mut batch),
Screen::CommandBlock => self.draw_command_block(&mut batch),
Screen::Inventory => {
self.draw_inventory(&mut batch);
@@ -9599,12 +9587,7 @@ impl Game<'_> {
// Camera.getCameraEntityPartialTicks: the view, the hand and the
// player's own model stay smooth while the level is frozen.
let camera_alpha = self.clock.camera_fraction();
- let live = self.backdrop_live();
- let view = if live {
- self.backdrop_view()
- } else {
- self.camera_view(camera_alpha as f32)
- };
+ let view = self.camera_view(camera_alpha as f32);
let (camera, underwater, view_yaw, view_pitch) = match view {
Some((c, yaw, pitch)) => {
let s =
@@ -9752,9 +9735,7 @@ impl Game<'_> {
// LevelLoadingScreen (Reason.OTHER) draws the title's panorama.
let title = self.title.is_some()
|| self.loading_reason() == Some(horizon_client::level_loading::Reason::Other);
- let (yaw, pitch) = if live {
- (view_yaw, view_pitch)
- } else if title {
+ let (yaw, pitch) = if title {
// PanoramaRenderer: the title cube spins at 0.1 degrees per tick, pitched 10 degrees.
(
self.panorama_rotation.update(
@@ -9766,9 +9747,7 @@ impl Game<'_> {
} else {
(view_yaw, view_pitch)
};
- let fov_degrees = if live {
- 72.0
- } else if title {
+ let fov_degrees = if title {
85.0
} else {
self.fov_degrees(camera_alpha as f32, camera.to_array())
@@ -9819,7 +9798,7 @@ impl Game<'_> {
}
.to_owned()
};
- let (celestial, stars) = if title && !live {
+ let (celestial, stars) = if title {
(Vec::new(), None)
} else if self.dim == Dim::Overworld
&& self.potions.effects.get("darkness").is_none()
@@ -9845,12 +9824,11 @@ impl Game<'_> {
if !title {
self.end_geometry(camera, &mut entities);
}
- let weather =
- if (!title || live) && self.dim == Dim::Overworld && self.settings.horizon.weather {
- horizon_client::spans::time("weather", || self.weather_geometry(camera, alpha))
- } else {
- Vec::new()
- };
+ let weather = if !title && self.dim == Dim::Overworld && self.settings.horizon.weather {
+ horizon_client::spans::time("weather", || self.weather_geometry(camera, alpha))
+ } else {
+ Vec::new()
+ };
let border = (!title)
.then(|| self.border_draw(camera.to_array(), alpha as f32))
.flatten();
@@ -9875,7 +9853,7 @@ impl Game<'_> {
detail_distance: (self.streaming.radius * 16) as f32,
depth_far,
underwater,
- title: title && !live,
+ title,
skybox: self.dim == Dim::Overworld && self.settings.horizon.sky,
end_sky: self.dim == Dim::End && self.settings.horizon.sky,
end_sky_sprite: self
@@ -9909,7 +9887,7 @@ impl Game<'_> {
debug_lines_on_top: &debug_lines_on_top,
debug_crosshair: &debug_crosshair,
hud: &hud,
- clouds: ((!title || live)
+ clouds: (!title
&& self.dim == Dim::Overworld
&& horizon_client::clouds::visible(&clouds_mode, sky.cloud_color[3]))
.then(|| self.gui.atlas.sprites.get("horizon/white"))
@@ -9964,13 +9942,6 @@ impl Game<'_> {
darkness: self.darkness_lighting(alpha as f32),
night_vision: self.night_vision_intensity(),
block_flicker: self.fog.block_light_flicker,
- post: if live {
- Some(horizon_client::post::PostGrade::FROST)
- } else if self.horizon_pause() {
- Some(horizon_client::post::PostGrade::PAUSE)
- } else {
- None
- },
menu_blur: self.menu_blur(),
};
let result = match self.renderer.as_mut() {
@@ -10042,15 +10013,14 @@ impl Game<'_> {
/// HUD, when `menuBackgroundBlurriness` is at least 1.
fn menu_blur(&self) -> Option {
let loading = self.loading_reason() == Some(horizon_client::level_loading::Reason::Other);
- let blurred = !horizon_client::ui_theme::horizon()
- && (loading
- || self.title.as_ref().is_some_and(|t| {
- self.screen == Screen::Options
- || !matches!(t.mode, horizon_client::title::Mode::Main)
- })
- || (self.title.is_none()
- && self.player.is_some()
- && self.screen.blurs_background(self.pause_menu)));
+ let blurred = loading
+ || self.title.as_ref().is_some_and(|t| {
+ self.screen == Screen::Options
+ || !matches!(t.mode, horizon_client::title::Mode::Main)
+ })
+ || (self.title.is_none()
+ && self.player.is_some()
+ && self.screen.blurs_background(self.pause_menu));
let radius = self.settings.menu_blur as f32;
(blurred && radius >= 1.0).then_some(radius)
}
@@ -10129,7 +10099,7 @@ impl Game<'_> {
}
Screen::GameModeSwitcher => self.close_gamemode_switcher(false),
Screen::Dead => {}
- Screen::Stats => self.screen = Screen::Paused,
+ Screen::Stats | Screen::Friends => self.screen = Screen::Paused,
Screen::Advancements => self.close_advancements(),
Screen::WorldOptions => self.world_options_escape(),
Screen::CommandBlock => self.close_command_block(),
@@ -10603,15 +10573,6 @@ impl ApplicationHandler for Game<'_> {
) {
self.last_input = Instant::now();
}
- if let WindowEvent::MouseInput {
- state,
- button: MouseButton::Left,
- ..
- } = &event
- {
- // The press state of Horizon-style buttons.
- horizon_client::ui_theme::set_pressed(*state == ElementState::Pressed);
- }
if (self.pending_entry.is_some() || self.world_loader.is_some())
&& matches!(&event, WindowEvent::KeyboardInput { event, .. }
if event.state == ElementState::Pressed
@@ -10711,9 +10672,7 @@ impl ApplicationHandler for Game<'_> {
if matches!(self.screen, Screen::Inventory | Screen::Creative) {
self.inventory_drag_move();
}
- if let Some(title) = &mut self.title
- && !horizon_client::ui_theme::horizon()
- {
+ if let Some(title) = &mut self.title {
title.drag(self.cursor, (b.width, b.height));
title.drag_field(&self.gui.atlas, self.cursor.0);
}
@@ -10739,9 +10698,7 @@ impl ApplicationHandler for Game<'_> {
}) * wheel_sensitivity
};
let d = scaled(raw_y) as f32;
- if let Some(title) = &mut self.title
- && !horizon_client::ui_theme::horizon()
- {
+ if let Some(title) = &mut self.title {
let size = self
.window
.as_ref()
@@ -10829,21 +10786,13 @@ impl ApplicationHandler for Game<'_> {
.as_ref()
.map(|r| [r.config.width, r.config.height])
.unwrap_or([1, 1]);
- let mut b = HudBatch::new(size);
+ let b = HudBatch::new(size);
let atlas = &self.gui.atlas;
let shift = self.has_shift_down();
let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| {
- if horizon_client::ui_theme::horizon() {
- (
- t.click_horizon(atlas, &mut b, self.cursor.0, self.cursor.1),
- false,
- )
- } else {
- let clicked =
- t.click(self.cursor.0, self.cursor.1, (b.width, b.height));
- t.press_field(atlas, self.cursor, (b.width, b.height), shift);
- clicked
- }
+ let clicked = t.click(self.cursor.0, self.cursor.1, (b.width, b.height));
+ t.press_field(atlas, self.cursor, (b.width, b.height), shift);
+ clicked
});
self.save_title_options();
if sound {
@@ -10979,6 +10928,9 @@ impl ApplicationHandler for Game<'_> {
Screen::WorldOptions if pressed && button == MouseButton::Left => {
self.world_options_click()
}
+ Screen::Friends if pressed && button == MouseButton::Left => {
+ self.friends_screen_click()
+ }
Screen::CommandBlock if pressed && button == MouseButton::Left => {
self.command_block_click()
}
@@ -11078,9 +11030,7 @@ impl ApplicationHandler for Game<'_> {
}
}
WindowEvent::KeyboardInput { event, .. } if self.title.is_some() => {
- if event.state == ElementState::Pressed
- && self.title.as_ref().is_some_and(|t| !t.skip_opening())
- {
+ if event.state == ElementState::Pressed {
if let Some(shortcut) = self.edit_shortcut(&event) {
self.title_shortcut(shortcut);
return Ok(());
@@ -11173,11 +11123,6 @@ impl ApplicationHandler for Game<'_> {
+ (turn(KeyCode::ArrowDown) - turn(KeyCode::ArrowUp)) * 90.0 * secs)
.clamp(-90.0, 90.0);
}
- self.update_backdrop()?;
- horizon_client::ui_theme::set_backdrop(self.backdrop_fade());
- if self.screen != Screen::Paused {
- self.pause_since = None;
- }
if self.title.is_none() {
horizon_client::spans::time("update_world", || self.update_world());
horizon_client::spans::time("spawn_player", || self.spawn_player())?;
@@ -11199,8 +11144,6 @@ impl ApplicationHandler for Game<'_> {
}
self.tick_ambience();
self.tick_fov();
- } else if self.title.is_some() {
- self.tick_backdrop();
}
self.tick_music();
self.tick_sound_engine();
@@ -11611,8 +11554,6 @@ impl<'a> Game<'a> {
hand_strength: Default::default(),
settings,
options_from_title: false,
- backdrop: Default::default(),
- pause_since: None,
dragging: false,
avatar: Default::default(),
flash: 0,
@@ -11985,13 +11926,11 @@ impl Progress {
/// Harness and dedicated runs keep the fully-synchronous startup so their
/// output stays byte-identical; only an ordinary launch shows the window first.
fn synchronous_startup(options: &Options) -> bool {
- let classic = std::env::var("HORIZON_MENU_STYLE").ok().as_deref() == Some("classic");
options.frames.is_some()
|| options.world_frames.is_some()
|| options.benchmark.is_some()
|| options.control.is_some()
|| options.dedicated.is_some()
- || classic
|| std::env::var_os("HORIZON_DISPENSE_FIXTURE").is_some()
|| std::env::var_os("HORIZON_SCULK_FIXTURE").is_some()
|| std::env::var_os("HORIZON_COMMAND_SCRIPT").is_some()
@@ -12012,7 +11951,7 @@ fn load_resources(
let requested_root = root.clone();
let threads = settings.horizon.worker_threads();
// Stage A: the menu bundle (atlas and panorama). With a loading screen it is
- // published at once so the title backdrop can appear while the world bundle
+ // published at once so the title screen can appear while the world bundle
// loads; the synchronous launch instead carries it in `Loaded`.
let mut loaded_gui = None;
let mut ui_ready = false;
@@ -12433,7 +12372,6 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> {
darkness: (0.0, 0.0),
night_vision: 0.0,
block_flicker: 0.0,
- post: None,
menu_blur: None,
shader: Default::default(),
}
@@ -12460,18 +12398,8 @@ fn start_game<'a>(
let handoff = prepared.is_some();
let mut settings = match settings {
Some(settings) => settings,
- None => {
- horizon_client::ui_theme::load_preferences(&std::env::current_dir()?);
- Settings::load(&std::env::current_dir()?.join("options.txt"))
- }
+ None => Settings::load(&std::env::current_dir()?.join("options.txt")),
};
- // Scripted and frame-limited runs (the parity harnesses) see vanilla's
- // screens unless HORIZON_MENU_STYLE asks otherwise.
- if (options.frames.is_some() || options.control.is_some())
- && std::env::var_os("HORIZON_MENU_STYLE").is_none()
- {
- horizon_client::ui_theme::set_style(horizon_client::ui_theme::MenuStyle::Classic);
- }
if let Some(d) = options.distance_override {
settings.render_distance = d;
}
@@ -12577,12 +12505,6 @@ fn start_game<'a>(
&game.options.resources,
);
title.last_server = game.settings.file.string("lastServer");
- // The launcher's opening, once per session and only in Horizon's style.
- if horizon_client::ui_theme::horizon() && game.options.frames.is_none() {
- title
- .opening
- .set(Some(horizon_client::front::Opening::new()));
- }
game.title = Some(title);
}
}
@@ -12940,7 +12862,6 @@ fn run_loading(
pack_error: Option,
started: Instant,
) -> Result<()> {
- horizon_client::ui_theme::load_preferences(&std::env::current_dir()?);
let progress = Progress::new();
let (receiver, loader) =
startup_menu::spawn_loader(&options, &settings, &vanilla_root, started, &progress)?;
diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs
index 9a5cd6a58..ea686e711 100644
--- a/crates/horizon-client/src/game/agent.rs
+++ b/crates/horizon-client/src/game/agent.rs
@@ -403,6 +403,7 @@ impl Game<'_> {
Screen::Stats => "stats",
Screen::Advancements => "advancements",
Screen::WorldOptions => "world-options",
+ Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
}
}
diff --git a/crates/horizon-client/src/game/backdrop.rs b/crates/horizon-client/src/game/backdrop.rs
deleted file mode 100644
index 8b32495b1..000000000
--- a/crates/horizon-client/src/game/backdrop.rs
+++ /dev/null
@@ -1,303 +0,0 @@
-//! The live title backdrop (Menu style: Horizon): a frozen landscape that
-//! Horizon generates and renders itself behind the title screens, seen
-//! through a slow orbiting camera, falling snow, an overcast sky and the cold
-//! blur and grade of `gfx::PostGrade`. Nothing is bundled: the chunks come
-//! from the vanilla generator for a fixed seed and are cached in
-//! `saves/.horizon-title/backdrop` (no level.dat, so no world list entry).
-//! The ice-spikes spot is found once with `/locate biome`'s search and kept
-//! in `spot.txt` there. The generator is built and the spot found on a
-//! worker, so the title keeps drawing its panorama until both are ready.
-use super::Game;
-use horizon_client::{
- Result,
- save::{Persistent, SaveDir},
- streaming::Streaming,
- vanillagen::VanillaTerrain,
- world::{Weather, World},
-};
-use horizon_core::biome::{BiomeZoom, obfuscate_seed};
-use std::{
- sync::{Arc, Mutex},
- time::Instant,
-};
-
-/// The world the backdrop is cut from (HORIZON_BACKDROP_SEED overrides it).
-const SEED: i64 = 2_026_031_337;
-/// The biome the camera looks for.
-const BIOME: &str = "minecraft:ice_spikes";
-/// Late morning: the snow reads clearly; the grade (`PostGrade::FROST`) makes it cold.
-const DAY_TIME: i64 = 4_000;
-
-/// The worker's result: the generator for [`SEED`], or why it failed.
-type Built = std::result::Result, String>;
-
-#[derive(Default)]
-pub(super) struct Backdrop {
- pub active: bool,
- /// The generator, once the worker has built it; taken when it is installed.
- terrain: Arc>>,
- /// The generator streams the backdrop's chunks.
- installed: bool,
- /// The search for the spot, then the spot (block x, z).
- spot: Arc>>>,
- centred: bool,
- /// Camera position once the ground under it has loaded.
- pub camera: Option,
- pub ready: Option,
- pub started: Option,
-}
-fn seed() -> i64 {
- std::env::var("HORIZON_BACKDROP_SEED")
- .ok()
- .and_then(|s| s.parse().ok())
- .unwrap_or(SEED)
-}
-impl Game<'_> {
- /// How visible the live backdrop is (0 until its first chunks are drawn).
- pub(super) fn backdrop_fade(&self) -> f32 {
- let Some(at) = self.backdrop.ready else {
- return 0.0;
- };
- let x = (at.elapsed().as_secs_f32() / 1.6).clamp(0.0, 1.0);
- x * x * (3.0 - 2.0 * x)
- }
- /// Whether the frame should draw the backdrop world instead of the panorama.
- pub(super) fn backdrop_live(&self) -> bool {
- self.title.is_some() && self.backdrop.active && self.backdrop.camera.is_some()
- }
- /// The orbiting camera: position, yaw and pitch.
- pub(super) fn backdrop_view(&self) -> Option<(glam::DVec3, f32, f32)> {
- let c = self.backdrop.camera?;
- let t = self
- .backdrop
- .started
- .map_or(0.0, |s| s.elapsed().as_secs_f32());
- // A full turn in about six minutes.
- let yaw = (200.0 + t * 1.0) % 360.0;
- let pitch = 6.0 + (t * 0.05).sin() * 2.0;
- Some((c, yaw, pitch))
- }
- /// Called every frame while the title is up.
- pub(super) fn update_backdrop(&mut self) -> Result<()> {
- let wanted = self.pending_entry.is_none()
- && self.title.is_some()
- && horizon_client::ui_theme::horizon()
- && self.world_renderer_ready
- && self.renderer.is_some()
- && self.options.frames.is_none();
- if !wanted {
- if self.backdrop.active && self.title.is_some() {
- self.stop_backdrop();
- }
- if self.title.is_none() && self.backdrop.active {
- // open_world / connect_server replaced the world and streaming.
- self.backdrop = Backdrop::default();
- }
- return Ok(());
- }
- if !self.backdrop.active {
- self.start_backdrop()?;
- }
- if !self.backdrop.installed {
- let built = self
- .backdrop
- .terrain
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .take();
- match built {
- // Still building: the panorama stays up.
- None => return Ok(()),
- Some(Ok(terrain)) => self.install_backdrop(terrain)?,
- Some(Err(e)) => {
- // The panorama stays up for good.
- log::warn!("Horizon: title backdrop: {e}");
- self.backdrop.installed = true;
- return Ok(());
- }
- }
- }
- let found = *self.backdrop.spot.lock().unwrap_or_else(|e| e.into_inner());
- let Some(Some((x, z))) = found else {
- return Ok(());
- };
- if !self.backdrop.centred {
- self.backdrop.centred = true;
- self.streaming.center = (x >> 4, z >> 4);
- self.streaming.paused = false;
- }
- self.update_world();
- if self.backdrop.camera.is_none()
- && (-2..=2)
- .all(|dz| (-2..=2).all(|dx| self.streaming.is_lit((x >> 4) + dx, (z >> 4) + dz)))
- {
- // Above the tallest block nearby, so no spike pokes through the lens.
- let mut top = 64;
- for dz in (-12..=12).step_by(3) {
- for dx in (-12..=12).step_by(3) {
- if let Some(y) = self.surface_y(x + dx, z + dz) {
- top = top.max(y);
- }
- }
- }
- let ground = self.surface_y(x, z).unwrap_or(top);
- let y = (ground + 22).max(top + 4);
- self.backdrop.camera = Some(glam::DVec3::new(
- f64::from(x) + 0.5,
- f64::from(y),
- f64::from(z) + 0.5,
- ));
- }
- if self.backdrop.camera.is_some()
- && self.backdrop.ready.is_none()
- && self
- .renderer
- .as_ref()
- .is_some_and(|r| r.section_count() > 40)
- {
- self.backdrop.ready = Some(Instant::now());
- log::info!(
- "Horizon: title backdrop ready; world rest ready: {}",
- self.res.rest.get().is_some()
- );
- }
- Ok(())
- }
- /// The world tick of the backdrop: time passes for clouds and snow only.
- pub(super) fn tick_backdrop(&mut self) {
- if self.backdrop.active {
- self.world.game_time += 1;
- // The snow's fall follows the client tick counter.
- self.ticks += 1;
- }
- }
- fn surface_y(&self, x: i32, z: i32) -> Option {
- let air = self.res.facts().air;
- (-60..320).rev().find(|&y| self.world.block(x, y, z) != air)
- }
- /// Start building the generator and finding the spot on a worker
- /// (`VanillaTerrain::new` takes seconds on a cold cache).
- fn start_backdrop(&mut self) -> Result<()> {
- log::info!(
- "Horizon: starting title backdrop after {} ms",
- self.started.elapsed().as_millis()
- );
- let seed = seed();
- let dir = self.backdrop_root()?.join(format!("{seed}"));
- std::fs::create_dir_all(&dir)?;
- // The streaming is replaced once the generator is built.
- self.streaming.paused = true;
- let mut world = World::new(self.res.facts().air, seed);
- world.day_time = DAY_TIME;
- world.game_time = 6000;
- // Light snow: the weather renders as snow in frozen biomes.
- world.weather = Weather {
- clear_time: 0,
- rain_time: i32::MAX / 2,
- thunder_time: i32::MAX / 2,
- raining: true,
- thundering: false,
- rain_level: (0.35, 0.35),
- thunder_level: (0.0, 0.0),
- };
- self.world = world;
- self.dim = super::Dim::Overworld;
- if let Some(r) = self.renderer.as_mut() {
- r.clear_sections();
- }
- self.backdrop = Backdrop {
- active: true,
- started: Some(Instant::now()),
- ..Default::default()
- };
- let (terrain, spot) = (self.backdrop.terrain.clone(), self.backdrop.spot.clone());
- let worldgen = self.options.resources.join("worldgen");
- let registry = self.pack.assets.registry;
- let biomes = self.res.biomes().clone();
- let cache = dir.join("spot.txt");
- std::thread::Builder::new()
- .name("horizon-backdrop".into())
- .spawn(move || {
- let built = Instant::now();
- let inner = match VanillaTerrain::new(&worldgen, registry, &biomes, seed) {
- Ok(t) => Arc::new(t),
- Err(e) => {
- *terrain.lock().unwrap_or_else(|e| e.into_inner()) =
- Some(Err(e.to_string()));
- return;
- }
- };
- log::info!(
- "Horizon: title backdrop generator built in {} ms",
- built.elapsed().as_millis()
- );
- *terrain.lock().unwrap_or_else(|e| e.into_inner()) = Some(Ok(inner.clone()));
- // Find (or recall) the spot.
- let known = std::fs::read_to_string(&cache).ok().and_then(|t| {
- let mut it = t.split_whitespace().map(|v| v.parse::().ok());
- Some((it.next()??, it.next()??))
- });
- let found = known.or_else(|| {
- let allowed = |name: &str| name == BIOME;
- let search = horizon_world::worldgen::generator::BiomeSearch {
- allowed: &allowed,
- origin: [0, 64, 0],
- radius: 6400,
- horizontal: 32,
- vertical: 64,
- min_y: -64,
- max_y: 320,
- };
- let found = inner.find_closest_biome(&search);
- log::info!("Horizon: title backdrop: {BIOME} at {found:?}");
- let (_, p) = found?;
- let _ = std::fs::write(&cache, format!("{} {}\n", p[0], p[2]));
- Some((p[0], p[2]))
- });
- *spot.lock().unwrap_or_else(|e| e.into_inner()) =
- Some(Some(found.unwrap_or((0, 0))));
- })?;
- Ok(())
- }
- fn backdrop_root(&self) -> Result {
- Ok(std::env::current_dir()?
- .join("saves")
- .join(".horizon-title")
- .join("backdrop"))
- }
- /// The built generator streams the backdrop's chunks.
- fn install_backdrop(&mut self, inner: Arc) -> Result<()> {
- let seed = seed();
- let save = Arc::new(SaveDir::new(self.backdrop_root()?.join(format!("{seed}"))));
- let (res, pack) = (&*self.res, &self.pack);
- let mut streaming = Streaming::new(
- Arc::new(Persistent {
- inner,
- save: save.clone(),
- registry: pack.assets.clone(),
- biomes: res.biomes().clone(),
- }),
- pack.context.clone(),
- res.threads().min(6),
- );
- streaming.radius = self.settings.render_distance.clamp(4, 10);
- streaming.biome_blend = self.settings.biome_blend;
- streaming.smooth_lighting = self.settings.smooth_lighting;
- streaming.cutout_leaves = self.settings.cutout_leaves;
- streaming.cull_leaves = self.settings.horizon.cull_leaves;
- streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed));
- streaming.paused = true;
- self.streaming = streaming;
- self.save = save;
- self.backdrop.installed = true;
- Ok(())
- }
- fn stop_backdrop(&mut self) {
- self.streaming.paused = true;
- self.world = World::new(self.res.facts().air, 0);
- if let Some(r) = self.renderer.as_mut() {
- r.clear_sections();
- }
- self.backdrop = Backdrop::default();
- }
-}
diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs
index a04c89ebf..6c5eec301 100644
--- a/crates/horizon-client/src/game/control.rs
+++ b/crates/horizon-client/src/game/control.rs
@@ -564,6 +564,8 @@ impl Game<'_> {
"graphics" => Page::Graphics,
"graphics-advanced" => Page::GraphicsAdvanced,
"extras" => Page::Extras,
+ "horizon" => Page::Horizon,
+ "shader-packs" => Page::ShaderPacks,
other => return Err(format!("unknown options page {other}").into()),
};
if self.screen == Screen::Playing && self.title.is_none() {
@@ -736,6 +738,7 @@ impl Game<'_> {
Screen::Stats => "stats",
Screen::Advancements => "advancements",
Screen::WorldOptions => "world-options",
+ Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
}
}
diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs
index dd8c5335a..969543601 100644
--- a/crates/horizon-client/src/game/creatures.rs
+++ b/crates/horizon-client/src/game/creatures.rs
@@ -330,6 +330,10 @@ impl Game<'_> {
"held": m.extra.main_hand.as_deref(),
"mount": m.extra.mount,
"rider": m.extra.rider,
+ // A player's input this tick, and whether it steers.
+ "ridden": m.rider.map(|r| r.steer),
+ "controlled": horizon_client::mobs::equine::controlled(m),
+ "saddled": m.extra.saddled,
"enchants": horizon_client::mobs::gear::gear(m).map(|g| g.slots.iter().map(|s| s.iter().map(|(e, l)| format!("{e}:{l}")).collect::>()).collect::>()),
"ints": m.extra.ints,
"pois": [m.extra.home, m.extra.bed, m.extra.meeting],
diff --git a/crates/horizon-client/src/game/friends.rs b/crates/horizon-client/src/game/friends.rs
index 69192265e..f55e96392 100644
--- a/crates/horizon-client/src/game/friends.rs
+++ b/crates/horizon-client/src/game/friends.rs
@@ -1,4 +1,5 @@
-//! Play with friends, host side: "Invite friends" opens the world to LAN if
+//! Play with friends, host side: "Start Sharing" on the Play with Friends
+//! screen (`friends_screen`, the pause menu's Friends button) opens the world to LAN if
//! it isn't (with Open to LAN's defaults) and shares that port behind an
//! invite code (horizon-friends). The code holds this computer's addresses
//! and the key, so friends join with no server of ours; a relay the player
@@ -6,7 +7,12 @@
//! LAN one, unchanged: tunnelled guests are LAN guests that connect from the
//! loopback address.
use super::{Game, lan::LanSettings};
-use horizon_client::{Result, front::FriendsView, text::Text};
+use horizon_client::{
+ Result,
+ friends_screen::{self, Action, FriendsView},
+ hud::HudBatch,
+ text::Text,
+};
use horizon_friends::{Host, HostConfig, HostEvent, PathMode, host::DEFAULT_PORT, reach, stun};
use horizon_protocol::{GAME_VERSION, PROTOCOL_VERSION};
use std::time::{Duration, Instant};
@@ -155,7 +161,7 @@ impl Game<'_> {
}
if announce {
self.system_message(Text::literal(
- "Your invite code is ready in the pause menu: copy it and send it to your friends.",
+ "Your invite code is ready: Game Menu, Play with Friends. Copy it and send it to your friends.",
));
}
}
@@ -171,7 +177,40 @@ impl Game<'_> {
}
}
- /// What the pause menu shows.
+ /// Play with Friends. The world is paused under it in singleplayer, so
+ /// new codes and sessions are read while it is drawn.
+ pub(super) fn draw_friends_screen(&mut self, batch: &mut HudBatch) {
+ self.tick_friends();
+ let view = self.friends_view();
+ friends_screen::draw(batch, &self.gui.atlas, self.cursor, &view, true);
+ }
+ pub(super) fn friends_screen_click(&mut self) {
+ let view = self.friends_view();
+ let Some(action) =
+ friends_screen::click(&self.gui.atlas, self.gui_size(), self.cursor, &view)
+ else {
+ return;
+ };
+ self.audio.play_button_click();
+ match action {
+ Action::Share => {
+ if let Err(e) = self.friends_start() {
+ self.system_message(Text::literal(format!("Couldn't share the world: {e}")));
+ }
+ }
+ Action::Copy => self.friends_copy(),
+ Action::Stop => self.friends_stop(),
+ // The system browser, as the Shader Packs page opens its folder.
+ Action::Help => {
+ if let Some(url) = &view.help {
+ super::packs::open_folder(std::path::Path::new(url));
+ }
+ }
+ Action::Done => self.screen = super::Screen::Paused,
+ }
+ }
+
+ /// What Play with Friends shows.
pub(super) fn friends_view(&self) -> FriendsView {
let guests = match &self.lan {
Some(h) => h.hub.guests.iter().map(|g| g.name.clone()).collect(),
diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs
index 17e1e09a3..8864309cc 100644
--- a/crates/horizon-client/src/game/lan.rs
+++ b/crates/horizon-client/src/game/lan.rs
@@ -800,6 +800,16 @@ impl Game<'_> {
self.send_admin_feedback(&mut host, None);
}
let state = self.lan_host_state(&host);
+ // An animal whose rider left the game (or the level) stops taking
+ // its input.
+ for m in &mut self.mobs {
+ if m.rider.is_some()
+ && self.riding != Some(m.id)
+ && !host.hub.guests.iter().any(|g| g.vehicle == Some(m.id))
+ {
+ m.rider = None;
+ }
+ }
// A dedicated server runs the hub without a host player.
if state.is_some() || host.hub.config.dedicated {
let has_guests = !host.hub.guests.is_empty();
diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs
index eccbd7f0b..569f4937b 100644
--- a/crates/horizon-client/src/game/lan_actions.rs
+++ b/crates/horizon-client/src/game/lan_actions.rs
@@ -49,6 +49,8 @@ pub(super) struct GuestPlay {
/// Swings the guest's actions started this tick, for the players around
/// (`LivingEntity.swing` sends ClientboundSwingAnimationPacket).
swings: u32,
+ /// The guest's riding jump charge (`LocalPlayer.jumpRidingTicks`).
+ mount: super::mounts::MountState,
/// The trading screen the guest has open.
pub(super) merchant: Option,
/// The inventory menu and the crafting table the guest crafts in.
@@ -289,6 +291,7 @@ impl Game<'_> {
let attack_ticks = std::mem::replace(&mut self.attack_ticks, play.attack_ticks);
let attack_item = std::mem::replace(&mut self.attack_item, play.attack_item.take());
let swing = std::mem::replace(&mut self.swing, play.swing);
+ std::mem::swap(&mut self.mount, &mut play.mount);
let (left, right) = (self.left, self.right);
self.left = play.digging.is_some();
self.right = play.using.is_some() || self.using.is_some();
@@ -478,6 +481,7 @@ impl Game<'_> {
play.attack_ticks = std::mem::replace(&mut self.attack_ticks, attack_ticks);
play.attack_item = std::mem::replace(&mut self.attack_item, attack_item);
play.swing = std::mem::replace(&mut self.swing, swing);
+ std::mem::swap(&mut self.mount, &mut play.mount);
self.container = container;
self.screen = screen;
self.sign_edit = host_sign;
diff --git a/crates/horizon-client/src/game/lan_vehicles.rs b/crates/horizon-client/src/game/lan_vehicles.rs
index 01195e49e..8198f288e 100644
--- a/crates/horizon-client/src/game/lan_vehicles.rs
+++ b/crates/horizon-client/src/game/lan_vehicles.rs
@@ -26,6 +26,7 @@ pub(super) fn input_keys(flags: u8) -> Keys {
right: flags & 8 != 0,
jump: flags & 16 != 0,
shift: flags & 32 != 0,
+ sprint: flags & 64 != 0,
..Keys::default()
}
}
@@ -96,9 +97,10 @@ impl Game<'_> {
let (keys, dead) = (input_keys(g.input), g.dead || g.health <= 0.0);
let boat = self.boats.iter().position(|b| b.id == vehicle);
let cart = self.carts.iter().any(|c| c.id == vehicle);
+ let mount = self.mobs.iter().any(|m| m.id == vehicle);
// The vehicle is gone (broken, in another level) or the rider died:
// its client drops it with the entity or the death screen.
- if dead || (boat.is_none() && !cart) {
+ if dead || (boat.is_none() && !cart && !mount) {
let g = &mut host.hub.guests[gi];
(g.vehicle, g.vehicle_good) = (None, None);
return;
@@ -122,8 +124,12 @@ impl Game<'_> {
return Some([p.x, p.y + SEAT, p.z]);
}
// The minecart moves with the rider's input, and lets it out when
- // it sneaks or the cart breaks.
- game.tick_cart_riding(keys);
+ // it sneaks or the cart breaks. An animal takes the rider's input
+ // for its own tick (`travelRidden`), or lets it off.
+ if !game.tick_cart_riding(keys) && game.tick_mount_riding(keys) {
+ game.riding?;
+ game.position_rider();
+ }
game.riding?;
let p = game.player.as_ref()?.position;
Some([p.x, p.y, p.z])
@@ -163,12 +169,26 @@ impl Game<'_> {
.find(|c| c.id == vehicle)
.map(|c| c.position)
});
- let g = &mut host.hub.guests[gi];
if let Some(p) = at {
+ let g = &mut host.hub.guests[gi];
g.vehicle_good = Some([p.x, p.y, p.z]);
g.previous_position = g.position;
g.position = [p.x, p.y + SEAT, p.z];
g.on_ground = false;
+ return;
+ }
+ // An animal: the rider sits where `positionRider` puts it.
+ let seat = self.as_guest(host, conn, |game| {
+ game.position_rider();
+ game.player
+ .as_ref()
+ .map(|p| [p.position.x, p.position.y, p.position.z])
+ });
+ if let Some(Some(at)) = seat {
+ let g = &mut host.hub.guests[gi];
+ g.previous_position = g.position;
+ g.position = at;
+ g.on_ground = false;
}
}
diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs
index 42eac1e9b..c5c7dc31c 100644
--- a/crates/horizon-client/src/game/mounts.rs
+++ b/crates/horizon-client/src/game/mounts.rs
@@ -107,6 +107,10 @@ impl Game<'_> {
let held = self.inventory[self.selected].clone();
let m = &self.mobs[index];
let species = m.species();
+ // A server player rides it already (`isVehicle`: no seat, no feeding).
+ if self.ridden_by_guest(m.id) {
+ return false;
+ }
if matches!(species, Species::Pig | Species::Strider) {
return self.interact_steerable(index, item);
}
@@ -246,24 +250,9 @@ impl Game<'_> {
self.consume_held();
true
}
- /// The rider's input for this tick; returns false when not on a mount.
- pub(super) fn tick_mount_riding(&mut self, keys: Keys) -> bool {
- let Some(i) = self.mount_index() else {
- return false;
- };
- if keys.shift || !self.mobs[i].alive() {
- self.dismount_mount();
- return true;
- }
- let strafe = f32::from(u8::from(keys.left)) - f32::from(u8::from(keys.right));
- let forward = f32::from(u8::from(keys.forward)) - f32::from(u8::from(keys.backward));
- // LocalPlayer.aiStep: the riding jump charges while space is held.
- let held = self.held().map(|s| s.item.clone());
- let steer = match self.mobs[i].species() {
- Species::Pig => held.as_deref() == Some("minecraft:carrot_on_a_stick"),
- Species::Strider => held.as_deref() == Some("minecraft:warped_fungus_on_a_stick"),
- _ => false,
- };
+ /// `LocalPlayer.aiStep`'s riding jump: the bar charges while jump is
+ /// held; on release, the jump's strength (0 when there is none).
+ pub(super) fn charge_mount_jump(&mut self, i: usize, keys: Keys) -> f32 {
// PlayerRideableJumping: horses, camels and nautili (the dash).
let saddled = self.mobs[i].extra.saddled
&& (equine::is_equine(self.mobs[i].species())
@@ -299,6 +288,27 @@ impl Game<'_> {
}
st.was_jumping = keys.jump;
}
+ jump
+ }
+ /// The rider's input for this tick; returns false when not on a mount.
+ pub(super) fn tick_mount_riding(&mut self, keys: Keys) -> bool {
+ let Some(i) = self.mount_index() else {
+ return false;
+ };
+ if keys.shift || !self.mobs[i].alive() {
+ self.dismount_mount();
+ return true;
+ }
+ let strafe = f32::from(u8::from(keys.left)) - f32::from(u8::from(keys.right));
+ let forward = f32::from(u8::from(keys.forward)) - f32::from(u8::from(keys.backward));
+ // LocalPlayer.aiStep: the riding jump charges while space is held.
+ let held = self.held().map(|s| s.item.clone());
+ let steer = match self.mobs[i].species() {
+ Species::Pig => held.as_deref() == Some("minecraft:carrot_on_a_stick"),
+ Species::Strider => held.as_deref() == Some("minecraft:warped_fungus_on_a_stick"),
+ _ => false,
+ };
+ let jump = self.charge_mount_jump(i, keys);
let m = &mut self.mobs[i];
if jump > 0.0 {
// onPlayerJump: rear while jumping (horses).
@@ -324,7 +334,7 @@ impl Game<'_> {
pitch: self.pitch,
jump: if jump > 0.0 { jump } else { pending },
steer,
- sprint: self.keys.contains(&winit::keyboard::KeyCode::ControlLeft),
+ sprint: keys.sprint || self.keys.contains(&winit::keyboard::KeyCode::ControlLeft),
jumping: keys.jump,
});
true
diff --git a/crates/horizon-client/src/game/pad_menu.rs b/crates/horizon-client/src/game/pad_menu.rs
index 257586572..32acdd256 100644
--- a/crates/horizon-client/src/game/pad_menu.rs
+++ b/crates/horizon-client/src/game/pad_menu.rs
@@ -113,7 +113,7 @@ impl Game<'_> {
}
/// Where focus can land: buttons drawn last frame, every registered
- /// target (sliders, fields, rows, Horizon-style widgets), and the slots
+ /// target (sliders, fields, rows, keyboard keys), and the slots
/// and tabs of inventories (GUI pixels), on screen.
fn pad_targets(&self) -> Vec {
let mut targets = self.pad_all_targets();
@@ -137,7 +137,7 @@ impl Game<'_> {
})
.collect();
for t in widgets::last_targets() {
- // A Horizon button is both a labelled button and a target.
+ // A button can be both a labelled button and a target.
if let Some(same) = targets.iter_mut().find(|o| o.rect == t.rect) {
same.kind = t.kind;
} else {
@@ -1026,45 +1026,13 @@ impl Game<'_> {
}
}
- /// The focus highlight. Classic screens look as vanilla's keyboard focus
- /// does: buttons, sliders and slots already draw their highlighted
- /// sprite under the (hidden) pointer, and list rows and fields get
- /// vanilla's white one-pixel outline (`AbstractSelectionList`'s focused
- /// selection, `EditBox`'s highlighted border). Horizon-style screens get
- /// the design system's focus colour: a two-dp accent ring.
+ /// The focus highlight, as vanilla's keyboard focus looks: buttons,
+ /// sliders and slots already draw their highlighted sprite under the
+ /// (hidden) pointer, and list rows and fields get vanilla's white
+ /// one-pixel outline (`AbstractSelectionList`'s focused selection,
+ /// `EditBox`'s highlighted border).
fn draw_pad_focus(&self, batch: &mut HudBatch, focus: Target) {
let [x, y, w, h] = focus.rect;
- // The options' sub-pages keep the classic layout under either style.
- let horizon = horizon_client::ui_theme::horizon()
- && if self.screen == Screen::Options {
- self.ui.options.page() == Page::Main
- } else {
- self.title.is_some() || self.screen == Screen::Paused
- };
- if horizon {
- use horizon_client::ui_theme::{self as theme, Ui, color};
- let mut ui = Ui::new(&self.gui.atlas, batch, self.cursor);
- let k = ui.batch.scale / ui.density;
- let (x, y, w, h) = (x * k, y * k, w * k, h * k);
- let radius = match focus.kind {
- Kind::Button | Kind::Tab(_) | Kind::Slider { .. } => (h + 6.0) / 2.0,
- Kind::Field => theme::RADIUS + 3.0,
- _ => theme::RADIUS_PLATE + 3.0,
- };
- for inset in [0.0, 1.0] {
- let o = 3.0 - inset;
- ui.border(
- x - o,
- y - o,
- w + 2.0 * o,
- h + 2.0 * o,
- radius - inset,
- color::ACCENT,
- );
- }
- ui.finish();
- return;
- }
if matches!(focus.kind, Kind::Row | Kind::Field) {
let atlas = &self.gui.atlas;
let white = rgba(255, 255, 255, 255);
diff --git a/crates/horizon-client/src/game/remote_vehicles.rs b/crates/horizon-client/src/game/remote_vehicles.rs
index dc3b2b686..027983145 100644
--- a/crates/horizon-client/src/game/remote_vehicles.rs
+++ b/crates/horizon-client/src/game/remote_vehicles.rs
@@ -112,6 +112,14 @@ impl Game<'_> {
let Some(id) = self.riding else {
return false;
};
+ if let Some(i) = self.mobs.iter().position(|m| m.id == id) {
+ // An animal moves on the server with the rider's input
+ // (PlayerInput); here the jump bar charges for the HUD and the
+ // rider sits where `positionRider` puts it.
+ self.charge_mount_jump(i, keys);
+ self.position_rider();
+ return true;
+ }
let seat = if let Some(i) = self.boats.iter().position(|b| b.id == id) {
// AbstractBoat.tick on the controlling client: steer and move.
let mut b = self.boats[i].clone();
diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs
index 07eacfb49..ae36b44df 100644
--- a/crates/horizon-client/src/game/screens.rs
+++ b/crates/horizon-client/src/game/screens.rs
@@ -13,7 +13,11 @@ impl Screen {
pub(super) fn blurs_background(self, pause_menu: bool) -> bool {
match self {
Self::Paused => pause_menu,
- Self::Options | Self::Stats | Self::Advancements | Self::WorldOptions => true,
+ Self::Options
+ | Self::Stats
+ | Self::Advancements
+ | Self::WorldOptions
+ | Self::Friends => true,
Self::Playing
| Self::GameModeSwitcher
| Self::Chat
@@ -61,6 +65,9 @@ fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static s
}
/// The icon row: report bugs, feedback, friends, player reporting.
+/// `FRIENDS_ICON` (vanilla's `CommonButtons.friends`) opens Horizon's
+/// Play with Friends; the others stay inactive.
+const FRIENDS_ICON: usize = 2;
fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] {
let x0 = ((w - 212.0) * 0.5).floor() + 60.0;
let y = ((h - 166.0) * 0.25).floor() + 98.0;
@@ -87,41 +94,8 @@ impl Game<'_> {
pub(super) fn external_server(&self) -> bool {
self.remote.is_some() && self.integrated.is_none()
}
- /// Whether the pause menu is drawn in Horizon's style (over a blurred world).
- pub(super) fn horizon_pause(&self) -> bool {
- self.screen == Screen::Paused
- && self.pause_menu
- && self.title.is_none()
- && horizon_client::ui_theme::horizon()
- }
- fn pause_labels(&self) -> (String, &'static str) {
- if let Some(server) = &self.integrated {
- return (server.world_name.clone(), "Save and quit");
- }
- if self.external_server() {
- ("Multiplayer".to_owned(), "Disconnect")
- } else {
- (self.level.name.clone(), "Save and quit")
- }
- }
pub(super) fn draw_pause_menu(&mut self, batch: &mut HudBatch) {
- if horizon_client::ui_theme::horizon() {
- let opened = *self.pause_since.get_or_insert_with(std::time::Instant::now);
- let (world, quit) = self.pause_labels();
- self.tick_friends();
- let friends = self.friends_view();
- let mut ui = horizon_client::ui_theme::Ui::new(&self.gui.atlas, batch, self.cursor);
- horizon_client::front::pause::draw(
- &mut ui,
- &world,
- quit,
- opened,
- &friends,
- self.external_server(),
- );
- ui.finish();
- return;
- }
+ let friends = self.friends_view().shown;
let atlas = &self.gui.atlas;
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
@@ -149,12 +123,41 @@ impl Game<'_> {
hover,
);
}
- for (x, y, sprite) in pause_icons(w, h) {
- ui::button(batch, atlas, x, y, 20.0, 20.0, &Text::empty(), false, false);
+ let mut tooltip = None;
+ for (i, (x, y, sprite)) in pause_icons(w, h).into_iter().enumerate() {
+ let active = i == FRIENDS_ICON && friends;
+ let hover = ui::hovered(self.cursor, x, y, 20.0, 20.0);
+ // The icon has no label: name it for controller focus and the
+ // control socket's widget tree.
+ if i == FRIENDS_ICON {
+ horizon_client::widgets::record(
+ horizon_client::friends_screen::TITLE,
+ [x, y, 20.0, 20.0],
+ active,
+ );
+ }
+ ui::button(
+ batch,
+ atlas,
+ x,
+ y,
+ 20.0,
+ 20.0,
+ &Text::empty(),
+ active,
+ active && hover,
+ );
// SpriteIconButton.CenteredIcon: the 15x15 sprite at
// x + width / 2 - 15 / 2 in integer pixels, untinted even
// when the button is inactive.
batch.sprite_scaled(atlas, sprite, x + 3.0, y + 3.0, 15.0, 15.0, u32::MAX);
+ if i == FRIENDS_ICON && hover {
+ tooltip = Some(Text::literal(horizon_client::friends_screen::TITLE));
+ }
+ }
+ // SpriteIconButton.withTootip: the label as a tooltip.
+ if let Some(tip) = tooltip {
+ ui::tooltip(batch, atlas, &[tip], self.cursor);
}
}
pub(super) fn pause_click(&mut self) -> Result<()> {
@@ -166,29 +169,16 @@ impl Game<'_> {
let b = HudBatch::new(size);
(b.width, b.height)
};
- let hit = if horizon_client::ui_theme::horizon() {
- let size = self
- .renderer
- .as_ref()
- .map_or([1, 1], |r| [r.config.width, r.config.height]);
- let mut b = HudBatch::new(size);
- let (world, quit) = self.pause_labels();
- horizon_client::front::pause::click(
- &self.gui.atlas,
- &mut b,
- self.cursor.0,
- self.cursor.1,
- &world,
- quit,
- &self.friends_view(),
- self.external_server(),
- )
- } else {
- pause_buttons(w, h, self.external_server())
- .into_iter()
- .find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0))
- .map(|b| b.4)
- };
+ let friends = pause_icons(w, h)[FRIENDS_ICON];
+ let hit = pause_buttons(w, h, self.external_server())
+ .into_iter()
+ .find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0))
+ .map(|b| b.4)
+ .or_else(|| {
+ (self.friends_view().shown
+ && ui::hovered(self.cursor, friends.0, friends.1, 20.0, 20.0))
+ .then_some(10)
+ });
match hit {
Some(0) => {
self.screen = Screen::Playing;
@@ -198,17 +188,11 @@ impl Game<'_> {
Some(3) => self.open_stats(),
Some(4) => self.open_advancements(true),
Some(9) => self.open_world_options(),
- Some(10) => {
- if let Err(e) = self.friends_start() {
- self.system_message(Text::literal(format!("Couldn't share the world: {e}")));
- }
- }
- Some(11) => self.friends_copy(),
- Some(12) => self.friends_stop(),
+ Some(10) => self.screen = Screen::Friends,
Some(2) => self.close_world()?,
_ => {}
}
- if hit.is_some() && !horizon_client::ui_theme::horizon() {
+ if hit.is_some() {
self.audio.play_button_click();
}
Ok(())
diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs
index ffbbe7193..0c8376397 100644
--- a/crates/horizon-client/src/game/startup_menu.rs
+++ b/crates/horizon-client/src/game/startup_menu.rs
@@ -73,11 +73,6 @@ impl StartupMenu {
&self.root,
);
title.last_server = settings.file.string("lastServer");
- if horizon_client::ui_theme::horizon() {
- title
- .opening
- .set(Some(horizon_client::front::Opening::new()));
- }
self.title = Some(title);
}
}
@@ -152,9 +147,6 @@ impl StartupMenu {
fn title_key(&mut self, event: &KeyEvent) {
let shortcut = self.shortcut(event);
let Some(title) = &mut self.title else { return };
- if title.skip_opening() {
- return;
- }
if let Some(shortcut) = shortcut {
if title.has_caret_field() {
title.field_shortcut(shortcut, &mut self.clipboard);
@@ -422,14 +414,6 @@ impl Loading {
event_loop: &ActiveEventLoop,
event: WindowEvent,
) -> Result<()> {
- if let WindowEvent::MouseInput {
- state,
- button: MouseButton::Left,
- ..
- } = &event
- {
- horizon_client::ui_theme::set_pressed(*state == ElementState::Pressed);
- }
if let WindowEvent::KeyboardInput { event, .. } = &event
&& let PhysicalKey::Code(key) = event.physical_key
{
@@ -455,7 +439,6 @@ impl Loading {
WindowEvent::Focused(false) => {
self.menu.modifiers = ModifiersState::empty();
self.menu.physical_keys.clear();
- horizon_client::ui_theme::set_pressed(false);
self.menu.dragging = false;
if let Some(title) = &mut self.menu.title {
title.release();
@@ -508,41 +491,23 @@ impl Loading {
button: MouseButton::Left,
..
} => {
- let mut batch = HudBatch::new(self.menu_size());
+ let batch = HudBatch::new(self.menu_size());
if let (Some(title), Some(gui)) = (&mut self.menu.title, &self.gui) {
if state == ElementState::Released {
title.release();
title.release_field();
} else {
- let action = if horizon_client::ui_theme::horizon() {
- let action = title.click_horizon(
- &gui.atlas,
- &mut batch,
- self.menu.cursor.0,
- self.menu.cursor.1,
- );
- // Horizon's deeper world-management pages use classic fields.
- title.press_field(
- &gui.atlas,
- self.menu.cursor,
- (batch.width, batch.height),
- self.menu.modifiers.shift_key(),
- );
- action
- } else {
- let (action, _) = title.click(
- self.menu.cursor.0,
- self.menu.cursor.1,
- (batch.width, batch.height),
- );
- title.press_field(
- &gui.atlas,
- self.menu.cursor,
- (batch.width, batch.height),
- self.menu.modifiers.shift_key(),
- );
- action
- };
+ let (action, _) = title.click(
+ self.menu.cursor.0,
+ self.menu.cursor.1,
+ (batch.width, batch.height),
+ );
+ title.press_field(
+ &gui.atlas,
+ self.menu.cursor,
+ (batch.width, batch.height),
+ self.menu.modifiers.shift_key(),
+ );
self.menu_action(event_loop, action);
}
}
@@ -617,18 +582,12 @@ impl Loading {
} else if let Some(title) = &mut self.menu.title {
title.poll_backup();
let _ = title.update_toast(self.settings.notification_display_time);
- if horizon_client::ui_theme::horizon() {
- let mut ui = horizon_client::ui_theme::Ui::new(&gui.atlas, batch, self.menu.cursor);
- title.draw_horizon(&mut ui, 0.0);
- ui.finish();
- } else {
- title.draw(
- &gui.atlas,
- batch,
- self.menu.cursor,
- self.settings.file.bool("hideSplashTexts"),
- );
- }
+ title.draw(
+ &gui.atlas,
+ batch,
+ self.menu.cursor,
+ self.settings.file.bool("hideSplashTexts"),
+ );
}
}
@@ -730,7 +689,6 @@ mod tests {
// Navigate and enter a world name without a registry, biomes, pack
// tables or a Game. Replacing fallback artwork preserves this state.
let title = loading.menu.title.as_mut().unwrap();
- title.opening.set(None);
title.mode = horizon_client::title::Mode::Create {
name: String::new(),
seed: "42".into(),
diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs
index b0389ca4f..9250940da 100644
--- a/crates/horizon-client/src/gfx.rs
+++ b/crates/horizon-client/src/gfx.rs
@@ -239,8 +239,6 @@ pub struct Frame<'a> {
pub night_vision: f32,
/// Torch flicker added to the block light factor of 1.4.
pub block_flicker: f32,
- /// Blur and grade the frame under a Horizon-style menu (`post`).
- pub post: Option,
/// `Screen.extractBlurredBackground`: blur the frame by this radius
/// (`menuBackgroundBlurriness`) before the screen is drawn over it.
pub menu_blur: Option,
@@ -450,8 +448,6 @@ pub struct Renderer {
/// The selected shader pack's stages (Horizon setting; none by default).
pack: Option,
pub hud: HudRenderer,
- /// The menus' backdrop blur, made on first use.
- post: Option,
/// Vanilla's menu background blur, made on first use.
menu_blur: Option,
pub info: wgpu::AdapterInfo,
@@ -2223,7 +2219,6 @@ impl Renderer {
world_post,
pack: None,
hud,
- post: None,
menu_blur: None,
info,
suspended: size.width == 0 || size.height == 0,
@@ -3947,23 +3942,6 @@ impl Renderer {
radius,
);
}
- if let Some(grade) = &frame.post
- && self.config.usage.contains(wgpu::TextureUsages::COPY_SRC)
- {
- let format = self.config.format;
- let device = &self.device;
- self.post
- .get_or_insert_with(|| crate::post::Post::new(device, format))
- .apply(
- &self.device,
- &self.queue,
- &mut encoder,
- &target_texture,
- &view_target,
- [self.config.width, self.config.height],
- grade,
- );
- }
self.hud.draw_range(
&mut encoder,
&view_target,
diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs
index bea0ffaa9..2541168d1 100644
--- a/crates/horizon-client/src/graphics.rs
+++ b/crates/horizon-client/src/graphics.rs
@@ -204,8 +204,6 @@ pub struct Graphics {
pub resolution_scale: u32,
/// FXAA over the world.
pub fxaa: bool,
- /// The settings level last shown: Advanced, or Simple.
- pub advanced: bool,
/// Battery mode: at most 60 frames per second in a world and 30 in menus
/// or behind other windows, and half the worker threads. Off by default;
/// it changes when frames are drawn, never what they show or the ticks.
@@ -236,7 +234,6 @@ impl Default for Graphics {
overlay: Overlay::Off,
resolution_scale: 100,
fxaa: false,
- advanced: false,
battery: false,
shader_pack: String::new(),
api: GraphicsApi::Auto,
@@ -288,7 +285,6 @@ impl Graphics {
"workers" => g.workers = number(g.workers).min(64),
"resolutionScale" => g.resolution_scale = number(g.resolution_scale).clamp(50, 200),
"fxaa" => g.fxaa = flag(g.fxaa),
- "level" => g.advanced = value == "advanced",
"batteryMode" => g.battery = flag(g.battery),
"shaderPack" => g.shader_pack = value.to_string(),
"graphicsApi" => g.api = GraphicsApi::from_name(value).unwrap_or_default(),
@@ -306,7 +302,7 @@ impl Graphics {
}
pub fn serialize(&self) -> String {
format!(
- "preset:{}\nlodDistance:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\ngraphicsApi:{}\n",
+ "preset:{}\nlodDistance:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nbatteryMode:{}\nshaderPack:{}\ngraphicsApi:{}\n",
self.preset.name(),
self.lod_distance,
bool_text(self.cave_culling),
@@ -331,7 +327,6 @@ impl Graphics {
},
self.resolution_scale,
bool_text(self.fxaa),
- if self.advanced { "advanced" } else { "simple" },
bool_text(self.battery),
self.shader_pack,
self.api.name(),
@@ -425,13 +420,14 @@ mod tests {
overlay: Overlay::Graph,
resolution_scale: 75,
fxaa: true,
- advanced: true,
battery: true,
shader_pack: "horizon-sample".into(),
api: GraphicsApi::Dx12,
};
assert_eq!(Graphics::parse(&g.serialize()), g);
assert_eq!(Graphics::parse(""), Graphics::default());
+ // The old menus' Simple / Advanced choice is ignored.
+ assert_eq!(Graphics::parse("level:advanced\n"), Graphics::default());
assert_eq!(
Graphics::parse("workers:abc\nsky:maybe\ncullLeaves:maybe\nentityCulling:maybe\n"),
Graphics::default()
diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs
index 9722ddc21..fddca6f2e 100644
--- a/crates/horizon-client/src/graphics_ui.rs
+++ b/crates/horizon-client/src/graphics_ui.rs
@@ -285,7 +285,7 @@ pub fn rows(level: Level) -> Vec {
const UPLOAD_STEPS: [u32; 8] = [0, 256, 512, 1024, 2048, 4096, 8192, 16384];
-/// Classic's submenus supplement the vanilla options on their parent screens.
+/// Horizon's graphics screens supplement the vanilla options on Video Settings.
fn extra_rows(level: Level) -> Vec {
let mut rows = rows(level);
rows.retain(|row| !matches!(row, Row::Setting(s) if matches!(s.item, Item::Vanilla(_))));
@@ -444,7 +444,7 @@ fn max_workers() -> u32 {
}
impl Item {
- /// On/off settings, drawn as switches by the Horizon menus.
+ /// On/off settings and their value.
pub fn switch(self, s: &Settings) -> Option {
let g = &s.horizon;
Some(match self {
diff --git a/crates/horizon-client/src/heartbeat.rs b/crates/horizon-client/src/heartbeat.rs
index f73c7131f..9f3f3a5a6 100644
--- a/crates/horizon-client/src/heartbeat.rs
+++ b/crates/horizon-client/src/heartbeat.rs
@@ -2,8 +2,8 @@
//! launcher's "N playing now". While the game runs, a thread of its own sends a random session
//! ID made here and kept only in memory, the version, the platform and whether a LAN or
//! play-with-friends world is open, every minute and at once when that last one changes.
-//! It sends nothing when there is no server (`HORIZON_TELEMETRY_URL`, none by default) or
-//! with `HORIZON_NO_HEARTBEAT=1` (automated runs).
+//! It sends nothing when sending is turned off (`HORIZON_TELEMETRY_URL=off`) or with
+//! `HORIZON_NO_HEARTBEAT=1` (automated runs).
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::Thread;
diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs
index b4bfe72ac..8537baa61 100644
--- a/crates/horizon-client/src/hud.rs
+++ b/crates/horizon-client/src/hud.rs
@@ -160,7 +160,7 @@ impl HudAtlas {
)
}
/// Empty slots written at run time: map textures (game/maps.rs), the
- /// minimap, downloaded skins, world icons and the Horizon menu text.
+ /// minimap, downloaded skins, world icons and the on-screen keyboard's text.
fn slots(images: &mut Vec) {
for i in 0..MAP_SLOTS {
images.push((format!("horizon/map{i}"), 128, 128, vec![0; 128 * 128 * 4]));
@@ -184,7 +184,7 @@ impl HudAtlas {
vec![0; 64 * 64 * 4],
));
}
- // Horizon-style menu text and corner masks (ui_theme), rasterized at run time.
+ // The on-screen keyboard's text and corner masks (ui_theme), rasterized at run time.
images.push((
"horizon/ui-text".into(),
2048,
diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs
index a71418f18..612509133 100644
--- a/crates/horizon-client/src/lib.rs
+++ b/crates/horizon-client/src/lib.rs
@@ -69,7 +69,7 @@ pub mod first_person;
pub mod flatgen;
pub mod fog;
pub mod font;
-pub mod front;
+pub mod friends_screen;
pub mod game_mode_switcher;
pub mod gamepad;
pub mod gamerules;
@@ -127,7 +127,6 @@ pub mod nether_portal;
pub mod offline_name;
pub mod options_file;
pub mod options_fixes;
-pub mod options_horizon;
pub mod options_ui;
pub mod osk;
pub mod overlay;
@@ -141,7 +140,6 @@ pub mod player_sync;
pub mod poi_sections;
pub mod portal_sections;
pub mod pose;
-pub mod post;
pub mod projectiles;
pub mod raid;
pub mod random_sequences;
diff --git a/crates/horizon-client/src/mobs/equine.rs b/crates/horizon-client/src/mobs/equine.rs
index e7d73f0fa..5bb5faf53 100644
--- a/crates/horizon-client/src/mobs/equine.rs
+++ b/crates/horizon-client/src/mobs/equine.rs
@@ -338,15 +338,21 @@ pub fn ridden_step(m: &mut Mob) {
// Pig/Strider: always forward along the rider's look, at a fraction
// of the movement speed, boosted by the stick.
m.head_pitch = r.pitch * 0.5;
- m.ai.xxa = 0.0;
- m.ai.zza = 1.0;
+ // Strider.getRiddenSpeed: slower while it shivers out of the warmth.
let factor = if m.species() == Species::Pig {
0.225
+ } else if super::strider::suffocating(m) {
+ 0.35
} else {
0.55
};
let boost = boost_factor(m);
- m.set_speed((m.attrs.speed * factor) as f32 * boost);
+ // travelRidden: setSpeed(getRiddenSpeed), then travel(getRiddenInput);
+ // the input is set after the speed (Mob.setSpeed also sets zza).
+ // getAttributeValue(MOVEMENT_SPEED): with the cold strider's modifier.
+ m.set_speed((m.movement_speed() * factor) as f32 * boost);
+ m.ai.xxa = 0.0;
+ m.ai.zza = 1.0;
return;
}
if super::camel::is_camel(m.species()) {
@@ -366,14 +372,14 @@ pub fn ridden_step(m: &mut Mob) {
} else {
r.forward
};
- m.ai.xxa = r.strafe * 0.5;
- m.ai.zza = forward;
let bonus = if r.sprint && m.extra.anim_ticks == 0 {
0.1
} else {
0.0
};
- m.set_speed(m.attrs.speed as f32 + bonus);
+ m.set_speed(m.movement_speed() as f32 + bonus);
+ m.ai.xxa = r.strafe * 0.5;
+ m.ai.zza = forward;
if r.jump > 0.0 {
let mut ev = Vec::new();
super::camel::dash(m, r.jump, &mut ev);
@@ -394,10 +400,10 @@ pub fn ridden_step(m: &mut Mob) {
} else {
r.forward
};
+ let speed = m.movement_speed() as f32;
+ m.set_speed(speed);
m.ai.xxa = r.strafe * 0.5;
m.ai.zza = forward;
- let speed = m.attrs.speed as f32;
- m.set_speed(speed);
if m.on_ground && r.jump > 0.0 {
// executeRidersJump
let impulse = m.extra.vector[0] as f32 * r.jump;
diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs
index 0497f06b4..b3a836b3a 100644
--- a/crates/horizon-client/src/mod_content.rs
+++ b/crates/horizon-client/src/mod_content.rs
@@ -538,6 +538,37 @@ impl<'a> Plan<'a> {
}
}
"items.json" => self.items(doc, true),
+ "registries.json" => {
+ // Network ids: the game and its server map items and blocks through
+ // this report, so new ones get the ids after vanilla's, in plan order.
+ let new_items = self.items.iter().map(|i| i.rename.to.clone());
+ let new_blocks = self.blocks.iter().map(|b| b.decl.id.clone());
+ for (registry, names) in [
+ ("minecraft:item", new_items.collect::>()),
+ ("minecraft:block", new_blocks.collect()),
+ ] {
+ let Some(J::Obj(entries)) =
+ doc.get_mut(registry).and_then(|r| r.get_mut("entries"))
+ else {
+ return Err(format!("no {registry} entries").into());
+ };
+ let next = entries
+ .iter()
+ .filter_map(|(_, e)| match e {
+ J::Obj(o) => o.iter().find(|(k, _)| k == "protocol_id")?.1.as_u32(),
+ _ => None,
+ })
+ .max()
+ .map_or(0, |m| m + 1);
+ for (i, name) in names.into_iter().enumerate() {
+ if entries.iter().any(|(k, _)| *k == name) {
+ continue;
+ }
+ let id = J::Num((next + i as u32).into());
+ entries.push((name, J::Obj(vec![("protocol_id".into(), id)])));
+ }
+ }
+ }
"command-registries.json" => {
self.names(doc.at("blocks").ok_or("no blocks")?, false);
let new_items = || self.items.iter().map(|i| J::Str(i.rename.to.clone()));
@@ -618,8 +649,9 @@ impl<'a> Plan<'a> {
}
/// The JSON and NBT tables rewritten for new blocks and items.
-const JSON_TABLES: [&str; 13] = [
+const JSON_TABLES: [&str; 14] = [
"facts.json",
+ "registries.json",
"gameplay-facts.json",
"block-behaviours.json",
"model-states.json",
diff --git a/crates/horizon-client/src/mod_content_tests.rs b/crates/horizon-client/src/mod_content_tests.rs
index 1c0907bde..3d38fae4d 100644
--- a/crates/horizon-client/src/mod_content_tests.rs
+++ b/crates/horizon-client/src/mod_content_tests.rs
@@ -148,6 +148,35 @@ fn content_root_loads_with_every_table() {
new.default_state("ruby:ruby_glass"),
Some(BlockStateId(n + 65))
);
+ // Network ids: the new items and blocks follow vanilla's in the registries report, which
+ // the game and its server both read (a missing one travels as air).
+ let report = |root: &Path| {
+ horizon_protocol::registry::Builtin::load(&root.join("registries.json")).unwrap()
+ };
+ let (vanilla_ids, ids) = (report(&base), report(&root));
+ let item = |b: &horizon_protocol::registry::Builtin, name: &str| {
+ b.get("minecraft:item").and_then(|r| r.id(name))
+ };
+ let vanilla_items = (0..)
+ .take_while(|&i| vanilla_ids.get("minecraft:item").unwrap().name(i).is_some())
+ .count() as i32;
+ assert_eq!(
+ item(&ids, "minecraft:stone"),
+ item(&vanilla_ids, "minecraft:stone")
+ );
+ let ruby_item = item(&ids, "ruby:ruby_block").unwrap();
+ assert!(ruby_item >= vanilla_items, "{ruby_item} < {vanilla_items}");
+ assert_eq!(
+ ids.get("minecraft:item").unwrap().name(ruby_item),
+ Some("ruby:ruby_block")
+ );
+ assert!(item(&ids, "ruby:ruby_glass").is_none(), "no item declared");
+ assert!(
+ ids.get("minecraft:block")
+ .unwrap()
+ .id("ruby:ruby_glass")
+ .is_some()
+ );
let old_facts = BlockFacts::load(&base, old).unwrap();
let facts = BlockFacts::load(&root, new).unwrap();
diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs
index 2228d32a2..179685dee 100644
--- a/crates/horizon-client/src/multiplayer.rs
+++ b/crates/horizon-client/src/multiplayer.rs
@@ -78,8 +78,8 @@ pub enum Screen {
name: String,
lines: std::cell::Cell,
},
- /// Join a friend's world with its invite code (Horizon's own, reached
- /// from Horizon's multiplayer page).
+ /// Join a friend's world with its invite code (Horizon's own, behind the
+ /// title screen's Friends button).
Friend {
code: String,
/// The relay for short codes (optional; saved on Join).
@@ -373,13 +373,6 @@ impl Screen {
}
}
- /// The address of list row `row` (saved servers, then LAN games).
- pub fn address_of(&self, row: usize) -> Option {
- match self {
- Self::List { servers, lan, .. } => entry_address(servers, lan, row),
- _ => None,
- }
- }
pub fn list(saves: &Path) -> Self {
let servers = servers::load(&servers_file(saves));
let pings: Pings = Arc::default();
@@ -1162,7 +1155,7 @@ impl Screen {
) => *self = Self::list(saves),
(Self::Disconnected { retry, .. }, Some(55)) => *retry = None,
(Self::Direct { address }, Some(52)) => {
- return Outcome::Connect(address.trim().to_owned());
+ return Outcome::Connect(direct_address(address));
}
(Self::Friend { code, relay, .. }, Some(56)) => {
if horizon_friends::invite::parse(code).is_some() {
@@ -1326,6 +1319,19 @@ impl Screen {
}
}
+/// Direct Connection's address; a full invite code pasted there joins the
+/// friend (a short relay code could be a host name, so it needs Join a Friend).
+fn direct_address(address: &str) -> String {
+ let code: String = address.chars().filter(|c| !c.is_whitespace()).collect();
+ if matches!(
+ horizon_friends::invite::parse(&code),
+ Some(horizon_friends::invite::Parsed::Long(_))
+ ) {
+ format!("{}{code}", crate::net::FRIEND)
+ } else {
+ address.trim().to_owned()
+ }
+}
/// Greedy word wrap to a pixel width.
pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec {
let mut lines = Vec::new();
@@ -1353,6 +1359,24 @@ pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec {
mod tests {
use super::*;
+ #[test]
+ fn direct_connection_joins_a_pasted_invite_and_keeps_host_names() {
+ let invite = horizon_friends::invite::Invite {
+ secret: *b"0123456789",
+ port: 25580,
+ endpoints: vec!["192.168.1.20:25580".parse().unwrap()],
+ relay: None,
+ }
+ .encode();
+ assert_eq!(
+ direct_address(&format!(" {invite} ")),
+ format!("{}{invite}", crate::net::FRIEND)
+ );
+ for host in ["localhost", "example.org:25566", "abcdefgh", "[::1]:25568"] {
+ assert_eq!(direct_address(host), host);
+ }
+ }
+
#[test]
fn ping_tooltip_follows_only_visible_status_bars_and_current_ping() {
let servers: Vec<_> = (0..6)
diff --git a/crates/horizon-client/src/options_horizon.rs b/crates/horizon-client/src/options_horizon.rs
deleted file mode 100644
index 50a42f337..000000000
--- a/crates/horizon-client/src/options_horizon.rs
+++ /dev/null
@@ -1,1259 +0,0 @@
-//! The options screen in Horizon's menu style, laid out like the launcher's
-//! Settings page: a sidebar with the sliding selection (one item per
-//! section), then the section's page header and settings rows (label column,
-//! value, control on the right) between 1px dividers.
-//!
-//! Adding settings (for example the Simple/Advanced graphics menu): add rows
-//! to a section in [`SECTIONS`], or a new section. A row is an [`HRow`]: an
-//! existing option (`Opt`, drawn as a switch, a slider or a value button from
-//! its kind), a header, or a button opening one of vanilla's pages. New kinds
-//! of control belong in `ui_theme` so the launcher-matching look stays in one
-//! place. Everything else (sliders dragging, scrolling, Done) is handled here.
-use crate::{
- extras,
- graphics_style::Cost,
- graphics_ui::{self, Item, Level},
- hud::{HudAtlas, HudBatch},
- options_ui::{self, Event, Kind, Opt, OptionsUi, Page, apply_preset},
- settings::{SOUND_SOURCES, Settings},
- ui_theme::{self as t, CONTROL, Kind as Button, MenuStyle, ROW_LABEL, SIDEBAR, Ui, color, id},
-};
-
-/// One row of a section.
-#[derive(Clone, Copy, Debug)]
-pub enum HRow {
- Header(&'static str),
- Opt(Opt),
- /// A label, a value and a button opening one of vanilla's pages.
- Page(&'static str, &'static str, Page),
- /// Menu style: Horizon / Classic.
- Style,
- /// Graphics settings level: Simple / Advanced.
- Level,
- /// A graphics setting with its frame-time cost and description.
- Graphics(Item, Cost, &'static str),
- /// One of Horizon's extras (`extras`), off by default.
- Extra(extras::Item),
- /// Installed mod `i` (`settings.mods.installed`) and its switch.
- Mod(usize),
- /// Opens the directory where Horizon mods are installed.
- OpenModFolder,
- /// `shaderpacks/`'s path and a button opening it.
- ShaderPackFolder,
- /// Shader pack `i` of `OptionsUi::shader_packs` and its switch.
- ShaderPack(usize),
-}
-
-/// The sidebar section listing the shader packs.
-pub const SHADER_PACKS: &str = "Shader Packs";
-/// A sidebar section: name, description, rows.
-pub struct Section {
- pub name: &'static str,
- pub blurb: &'static str,
- pub rows: fn(&Settings) -> Vec,
-}
-pub const SECTIONS: &[Section] = &[
- Section {
- name: "Video",
- blurb: "Graphics, Simple or Advanced: each setting says what it costs.",
- rows: |s| {
- let level = if s.horizon.advanced {
- Level::Advanced
- } else {
- Level::Simple
- };
- let mut r = vec![HRow::Level];
- r.extend(graphics_ui::rows(level).into_iter().map(|row| match row {
- graphics_ui::Row::Header(name) => HRow::Header(name),
- graphics_ui::Row::Setting(g) => HRow::Graphics(g.item, g.cost, g.text),
- }));
- r
- },
- },
- Section {
- name: "Audio",
- blurb: "Volume for every kind of sound, and subtitles.",
- rows: |_| {
- let mut r: Vec = (0..SOUND_SOURCES.len())
- .map(|i| HRow::Opt(Opt::Volume(i)))
- .collect();
- r.push(HRow::Opt(Opt::ShowSubtitles));
- r
- },
- },
- Section {
- name: "Controls",
- blurb: "Keys, the mouse, controllers and how movement keys behave.",
- rows: |_| {
- let mut r = vec![HRow::Page(
- "Key binds",
- "Every action and its key",
- Page::KeyBinds,
- )];
- r.push(HRow::Header("Mouse"));
- r.extend(
- [
- Opt::Sensitivity,
- Opt::WheelSensitivity,
- Opt::InvertY,
- Opt::DiscreteScroll,
- ]
- .map(HRow::Opt),
- );
- r.push(HRow::Header("Movement"));
- r.extend([Opt::ToggleCrouch, Opt::ToggleSprint, Opt::AutoJump].map(HRow::Opt));
- r.push(HRow::Header("Controller"));
- r.push(HRow::Page(
- "Controller binds",
- "Every action and its button",
- Page::PadBinds,
- ));
- r.extend(
- [
- Opt::PadEnabled,
- Opt::PadVibration,
- Opt::PadAdaptiveTriggers,
- Opt::PadLightbar,
- Opt::PadLookSensitivity,
- Opt::PadToggleSneak,
- Opt::PadInvertX,
- Opt::PadInvertY,
- Opt::PadMoveDeadzone,
- Opt::PadLookDeadzone,
- Opt::PadGlyphs,
- Opt::PadMenuNav,
- Opt::PadKeyboard,
- ]
- .map(HRow::Opt),
- );
- r
- },
- },
- Section {
- name: "Accessibility",
- blurb: "Contrast, motion, text backgrounds and notifications.",
- rows: |_| {
- let mut rows = vec![HRow::Page(
- "Controls",
- "Key binds, mouse and controller",
- Page::Controls,
- )];
- rows.extend(
- options_ui::ACCESSIBILITY_OPTIONS
- .iter()
- .copied()
- .filter(|opt| opt.available())
- .map(HRow::Opt),
- );
- rows
- },
- },
- Section {
- name: "Language",
- blurb: "The game's language and its font.",
- rows: |_| {
- vec![
- HRow::Page("Language", "", Page::Language),
- HRow::Opt(Opt::ForceUnicode),
- HRow::Opt(Opt::JapaneseGlyphs),
- ]
- },
- },
- Section {
- name: "Chat",
- blurb: "What chat shows and how it looks.",
- rows: |_| {
- [
- Opt::ChatVisibility,
- Opt::ChatColors,
- Opt::ChatLinks,
- Opt::ChatOpacity,
- Opt::ChatScale,
- Opt::ChatWidth,
- Opt::ChatHeightFocused,
- Opt::ChatHeightUnfocused,
- Opt::AutoSuggestions,
- Opt::ReducedDebugInfo,
- ]
- .map(HRow::Opt)
- .to_vec()
- },
- },
- Section {
- name: SHADER_PACKS,
- blurb: "Packs that redraw the world. Off is the vanilla look.",
- // The packs follow, from the folder (`horizon_rows`).
- rows: |_| vec![HRow::ShaderPackFolder],
- },
- Section {
- name: "Interface",
- blurb: "Menus and resource packs.",
- rows: |_| {
- vec![
- HRow::Style,
- HRow::Page("Resource packs", "Textures, sounds and fonts", Page::Packs),
- ]
- },
- },
- Section {
- name: "Extras",
- blurb: "Optional additions, all off by default: the game stays vanilla until you turn one on.",
- // A switch's own settings nest under it and show while it is on, so
- // the page stays one row per extra until one is turned on.
- rows: |s| {
- extras::rows()
- .into_iter()
- .filter(|r| {
- r.map_or(true, |item| {
- item.parent()
- .is_none_or(|parent| parent.switch(&s.extras) == Some(true))
- })
- })
- .map(|r| r.map_or_else(HRow::Header, HRow::Extra))
- .collect()
- },
- },
- Section {
- name: "Mods",
- blurb: "Mods made for Horizon, from the horizon-mods folder. Each runs in a sandbox and stays off until you turn it on; check what it may do first.",
- rows: |s| {
- let mut rows = vec![HRow::OpenModFolder];
- if s.mods.installed.is_empty() {
- rows.push(HRow::Header(
- "No mods: put .hmod files in the horizon-mods folder",
- ));
- } else {
- rows.extend((0..s.mods.installed.len()).map(HRow::Mod));
- }
- rows
- },
- },
-];
-
-const NAV: u64 = id("options.nav", 0);
-const DONE: u64 = id("options.done", 0);
-const ROW: u64 = id("options.row", 0);
-const STYLE: u64 = id("options.style", 0);
-const LEVEL: u64 = id("options.level", 0);
-const SEARCH: u64 = id("options.search", 0);
-const ROW_H: f32 = 12.0 + CONTROL + 12.0;
-const HEADER_H: f32 = 40.0;
-pub(crate) fn searchable_section(section: usize) -> bool {
- matches!(
- SECTIONS.get(section).map(|s| s.name),
- Some("Video" | "Controls")
- )
-}
-
-/// Whether an option is an on/off switch, and its value.
-fn switch_value(opt: Opt, s: &Settings) -> Option {
- Some(match opt {
- Opt::HideLightningFlashes => s.file.bool("hideLightningFlashes"),
- Opt::HideSplashTexts => s.file.bool("hideSplashTexts"),
- Opt::InvertY => s.invert_y,
- Opt::DiscreteScroll => s.discrete_scroll,
- Opt::ViewBobbing => s.view_bobbing,
- Opt::Vsync => s.vsync,
- Opt::Fullscreen => s.fullscreen,
- Opt::SmoothLighting => s.smooth_lighting,
- Opt::EntityShadows => s.entity_shadows,
- Opt::Vignette => s.vignette,
- Opt::Autosave => s.autosave_indicator,
- Opt::CutoutLeaves => s.cutout_leaves,
- Opt::ImprovedTransparency => s.improved_transparency,
- Opt::AutoJump => s.auto_jump,
- Opt::ChatColors => s.chat_colors,
- Opt::ChatLinks => s.chat_links,
- Opt::AutoSuggestions => s.auto_suggestions,
- Opt::ReducedDebugInfo => s.reduced_debug_info,
- Opt::HighContrast => s.high_contrast,
- Opt::ShowSubtitles => s.show_subtitles,
- Opt::ForceUnicode => s.force_unicode,
- Opt::JapaneseGlyphs => s.japanese_glyphs,
- Opt::PadEnabled => s.controller.enabled,
- Opt::PadVibration => s.controller.vibration,
- Opt::PadAdaptiveTriggers => s.controller.adaptive_triggers,
- Opt::PadInvertX => s.controller.invert_x,
- Opt::PadInvertY => s.controller.invert_y,
- _ => return None,
- })
-}
-/// The option's caption and value text, from its vanilla label
-/// ("Caption: Value") and its caption key.
-fn caption_value(opt: Opt, s: &Settings) -> (String, String) {
- let label = opt.label(s).plain();
- let caption = crate::text::Text::translate(opt.caption(), &[]).plain();
- if let Some(rest) = label.strip_prefix(&caption) {
- return (caption, rest.trim_start_matches([':', ' ']).to_owned());
- }
- match label.split_once(": ") {
- Some((c, v)) => (c.to_owned(), v.to_owned()),
- None => (caption, label),
- }
-}
-/// What a click hit.
-enum Target {
- Nav(usize),
- Done,
- Search,
- Row(usize),
- Slider(Item, f32),
- Style(usize),
- Level(usize),
-}
-struct HorizonScrollbar {
- x: f32,
- top: f32,
- bottom: f32,
- max: f32,
- thumb: f32,
-}
-impl HorizonScrollbar {
- fn contains(&self, x: f32, y: f32) -> bool {
- x >= self.x && x < self.x + 6.0 && y >= self.top && y < self.bottom
- }
-}
-struct HorizonLayout {
- sliders: Vec<(Item, f32, f32)>,
- scrollbar: Option,
-}
-fn horizon_batch(framebuffer: [i32; 2]) -> HudBatch {
- HudBatch::new([framebuffer[0].max(1) as u32, framebuffer[1].max(1) as u32])
-}
-impl OptionsUi {
- fn horizon_rows(&self, s: &Settings, section: usize) -> Vec {
- let mut rows = (SECTIONS[section].rows)(s);
- if SECTIONS[section].name == SHADER_PACKS {
- if self.shader_packs.packs.is_empty() {
- rows.push(HRow::Header(
- "No shader packs: put a pack's folder or .zip in this folder",
- ));
- }
- rows.extend((0..self.shader_packs.packs.len()).map(HRow::ShaderPack));
- }
- let query = self.settings_search.value.to_lowercase();
- if query.is_empty() || !searchable_section(section) {
- return rows;
- }
- rows.into_iter()
- .filter(|row| match row {
- HRow::Opt(opt) => caption_value(*opt, s).0.to_lowercase().contains(&query),
- HRow::Graphics(item, ..) => item.caption_value(s).0.to_lowercase().contains(&query),
- HRow::Page(label, ..) => label.to_lowercase().contains(&query),
- HRow::Level => true,
- _ => false,
- })
- .collect()
- }
- /// Lay out (and draw, on a real frame) the Horizon options shell.
- /// Returns the sliders' tracks and the scroll area for pointer input.
- fn horizon_layout(&mut self, s: &Settings, ui: &mut Ui, backdrop: f32) -> HorizonLayout {
- let (w, h) = (ui.w, ui.h);
- if self.in_world {
- ui.atmosphere(horizon_theme::VEIL, 1.0);
- } else {
- if backdrop < 1.0 {
- ui.cold_background(1.0 - backdrop);
- }
- ui.atmosphere(horizon_theme::VEIL, 1.0);
- }
- let section = self.section.min(SECTIONS.len() - 1);
- // The sidebar.
- ui.sidebar_frame("Options");
- let names: Vec<&str> = SECTIONS.iter().map(|s| s.name).collect();
- ui.sidebar_list(NAV, 12.0, 72.0, SIDEBAR - 24.0, &names, section);
- let dy = h - 12.0 - CONTROL;
- ui.button(
- DONE,
- [12.0, dy, SIDEBAR - 24.0, CONTROL],
- "Done",
- Button::Secondary,
- true,
- );
- // The page fades in and rises 8 when the section changes.
- let p = ui.tween(id("options.page", section as u64), 1.0, t::move_());
- if self.section_shown != Some(section) {
- self.section_shown = Some(section);
- ui.restart(id("options.page", section as u64), 0.0, 1.0, t::move_());
- }
- let x = SIDEBAR + 48.0;
- let cw = (w - x - 48.0).min(760.0);
- ui.opacity = p;
- ui.offset = (0.0, 8.0 * (1.0 - p));
- let sec = &SECTIONS[section];
- let mut y = 36.0;
- y += ui.page_header(x, y, sec.name, sec.blurb) + 24.0;
- if searchable_section(section) {
- ui.text_field(
- SEARCH,
- [x + cw - 240.0, y, 240.0, CONTROL],
- &self.settings_search.value,
- self.settings_search.focused,
- );
- y += CONTROL + 12.0;
- }
- let top = y;
- let rows = self.horizon_rows(s, section);
- let content: f32 = rows
- .iter()
- .map(|r| {
- if matches!(r, HRow::Header(_)) {
- HEADER_H
- } else {
- ROW_H
- }
- })
- .sum();
- let bottom = h - 24.0;
- let max = (content - (bottom - top)).max(0.0);
- self.hscroll = self.hscroll.clamp(0.0, max);
- y -= self.hscroll;
- let vstart = ui.batch.vertices.len();
- let hstart = ui.hits.len();
- let tstart = crate::widgets::targets_mark();
- let mut sliders = Vec::new();
- ui.divider(x, y, cw);
- let control_x = x + cw;
- for (i, row) in rows.iter().enumerate() {
- match *row {
- HRow::Header(label) => {
- ui.caps(x, y + 20.0, color::FAINT, label);
- y += HEADER_H;
- ui.divider(x, y, cw);
- continue;
- }
- HRow::Opt(opt) => {
- let (caption, value) = caption_value(opt, s);
- let cy = y + ROW_H / 2.0;
- if !opt.available() {
- ui.row(x, y, &caption, "", 0.0);
- let label = "Unavailable";
- let bw = ui.button_width(label, false).max(96.0);
- ui.button(
- ROW + i as u64,
- [control_x - bw, y + 12.0, bw, CONTROL],
- label,
- Button::Secondary,
- false,
- );
- } else if let Some(on) = switch_value(opt, s) {
- ui.row(x, y, &caption, "", 0.0);
- ui.switch(ROW + i as u64, control_x, cy, on);
- } else if let Kind::Slider(v) = opt.kind(s) {
- let sw = 220.0_f32.min(cw - ROW_LABEL - 200.0).max(80.0);
- ui.row(x, y, &caption, &value, cw - ROW_LABEL - 16.0 - sw - 24.0);
- let sx = control_x - sw - 8.0;
- ui.slider(ROW + i as u64, sx, cy, sw, v);
- sliders.push((Item::Vanilla(opt), sx, sw));
- } else {
- ui.row(x, y, &caption, "", 0.0);
- let bw = ui.button_width(&value, false).max(96.0);
- ui.button(
- ROW + i as u64,
- [control_x - bw, y + 12.0, bw, CONTROL],
- &value,
- Button::Secondary,
- true,
- );
- }
- }
- HRow::Page(label, value, _) => {
- let value = if value.is_empty() {
- self.languages
- .iter()
- .find(|l| l.code == s.language)
- .map_or_else(|| s.language.clone(), |l| l.label())
- } else {
- value.to_owned()
- };
- ui.row(x, y, label, &value, cw - ROW_LABEL - 140.0);
- let bw = ui.button_width("Change…", false);
- let open = if label == "Language" {
- "Change…"
- } else {
- "Open…"
- };
- let bw = bw.max(ui.button_width(open, false));
- ui.button(
- ROW + i as u64,
- [control_x - bw, y + 12.0, bw, CONTROL],
- open,
- Button::Secondary,
- true,
- );
- }
- HRow::Level => {
- ui.row(x, y, "Settings", "", 0.0);
- let labels = ["Simple", "Advanced"];
- let probe = ui.segmented(LEVEL, -10_000.0, -10_000.0, &labels, 0);
- let selected = usize::from(s.horizon.advanced);
- ui.segmented(LEVEL, control_x - probe, y + 12.0 - 3.0, &labels, selected);
- }
- HRow::Graphics(item, cost, text) => {
- let (caption, value) = item.caption_value(s);
- let cost = (cost as u8, cost.label());
- let cy = y + ROW_H / 2.0;
- let id = ROW + i as u64;
- if let Some(on) = item.switch(s) {
- ui.described_row(x, y, &caption, "", 0.0, cost, text, cw - 60.0);
- ui.switch(id, control_x, cy, on);
- } else if let Some(v) = item.slider(s) {
- let sw = 220.0_f32.min(cw - ROW_LABEL - 200.0).max(80.0);
- let value_w = cw - ROW_LABEL - 16.0 - sw - 24.0;
- let text_w = cw - sw - 24.0;
- ui.described_row(x, y, &caption, &value, value_w, cost, text, text_w);
- let sx = control_x - sw - 8.0;
- ui.slider(id, sx, cy, sw, v);
- sliders.push((item, sx, sw));
- } else {
- let bw = ui.button_width(&value, false).max(96.0);
- let text_w = cw - bw - 24.0;
- ui.described_row(x, y, &caption, "", 0.0, cost, text, text_w);
- ui.button(
- id,
- [control_x - bw, y + 12.0, bw, CONTROL],
- &value,
- Button::Secondary,
- true,
- );
- }
- }
- HRow::Mod(m) => {
- let installed = &s.mods.installed[m];
- let cost = match (&installed.problem, installed.dev) {
- (Some(_), _) => (3, "Stopped"),
- (None, true) => (1, "Dev"),
- (None, false) => (0, ""),
- };
- let text = installed
- .problem
- .as_deref()
- .unwrap_or(&installed.description);
- ui.described_row(x, y, &installed.title, "", 0.0, cost, text, cw - 60.0);
- ui.switch(ROW + i as u64, control_x, y + ROW_H / 2.0, s.mods.is_on(m));
- }
- HRow::ShaderPackFolder => {
- let label = "Open Folder";
- let bw = ui.button_width(label, false).max(96.0);
- let dir = self.shader_packs.dir.display().to_string();
- ui.described_row(x, y, "Folder", "", 0.0, (0, ""), &dir, cw - bw - 24.0);
- ui.button(
- ROW + i as u64,
- [control_x - bw, y + 12.0, bw, CONTROL],
- label,
- Button::Secondary,
- true,
- );
- }
- HRow::ShaderPack(p) => {
- let (id, info) = &self.shader_packs.packs[p];
- let error = match info {
- Err(e) => Some(e.as_str()),
- Ok(_) => self
- .shader_pack_error
- .as_ref()
- .filter(|(failed, _)| failed == id)
- .map(|(_, e)| e.as_str()),
- };
- let (cost, text) = match (error, info) {
- (Some(e), _) => ((3, "Failed"), e),
- (None, Ok(info)) => ((0, ""), info.description.as_str()),
- (None, Err(_)) => unreachable!(),
- };
- ui.described_row(x, y, id, "", 0.0, cost, text, cw - 60.0);
- let on = s.horizon.shader_pack == *id;
- ui.switch(ROW + i as u64, control_x, y + ROW_H / 2.0, on);
- }
- HRow::OpenModFolder => {
- ui.row(x, y, "Mod folder", "", 0.0);
- let label = "Open Folder";
- let bw = ui.button_width(label, false).max(96.0);
- ui.button(
- ROW + i as u64,
- [control_x - bw, y + 12.0, bw, CONTROL],
- label,
- Button::Secondary,
- true,
- );
- }
- HRow::Extra(item) => {
- let cy = y + ROW_H / 2.0;
- let id = ROW + i as u64;
- let mut cost = item.cost().map_or((0, ""), |c| (c as u8, c.label()));
- let (caption, mut text) = (item.caption(), item.description().to_owned());
- // A vanilla mapping on the same key: both act on it, like
- // the binds list's duplicates; say which.
- let conflicts = extras::zoom_key_conflicts(&s.extras, &s.keys);
- if item == extras::Item::ZoomKey && !conflicts.is_empty() {
- let names: Vec =
- conflicts.iter().map(|c| crate::lang::get(c)).collect();
- cost = (3, "Also bound");
- text = format!("{} uses this key too; both act on it.", names.join(", "));
- }
- let text = text.as_str();
- if let Some(on) = item.switch(&s.extras) {
- ui.described_row(x, y, caption, "", 0.0, cost, text, cw - 60.0);
- ui.switch(id, control_x, cy, on);
- } else {
- let value =
- if item.key_name().is_some() && self.selected_key == item.key_name() {
- "Press a key".to_owned()
- } else {
- item.value(&s.extras)
- };
- let bw = ui.button_width(&value, false).max(96.0);
- ui.described_row(x, y, caption, "", 0.0, cost, text, cw - bw - 24.0);
- ui.button(
- id,
- [control_x - bw, y + 12.0, bw, CONTROL],
- &value,
- Button::Secondary,
- true,
- );
- }
- }
- HRow::Style => {
- ui.row(x, y, "Menu style", "", 0.0);
- let labels = ["Horizon", "Classic"];
- let probe = ui.segmented(STYLE, -10_000.0, -10_000.0, &labels, 0);
- let selected = usize::from(t::style() == MenuStyle::Classic);
- ui.segmented(STYLE, control_x - probe, y + 12.0 - 3.0, &labels, selected);
- }
- }
- y += ROW_H;
- ui.divider(x, y, cw);
- }
- // Clip the rows to the page below the header, like the launcher's scroll view.
- let (ox, oy) = ui.offset;
- let scale = ui.batch.scale;
- let k = ui.density / scale;
- let (y0, y1) = ((top - 1.0 + oy) * k, (bottom + oy) * k);
- ui.batch.clip_since(vstart, 0.0, y0, ui.batch.width, y1);
- if ui.is_real() {
- crate::widgets::clip_targets(tstart, y0, y1);
- }
- let (cy0, cy1) = (top - 1.0 + oy, bottom + oy);
- let kept: Vec<_> = ui
- .hits
- .drain(hstart..)
- .filter(|h| h.rect[1] >= cy0 && h.rect[3] <= cy1)
- .collect();
- ui.hits.extend(kept);
- let mut scrollbar = None;
- if max > 0.0 {
- // A thin scroll indicator.
- let track = bottom - top;
- let bar = (track * track / (track + max)).max(24.0);
- let by = top + (track - bar) * (self.hscroll / max);
- ui.rounded(
- x + cw + 16.0,
- by,
- 3.0,
- bar,
- 1.5,
- color::with_alpha(color::MUTED, 0.35),
- );
- scrollbar = Some(HorizonScrollbar {
- x: x + cw + 14.0,
- top: top + oy,
- bottom: bottom + oy,
- max,
- thumb: bar,
- });
- }
- let _ = ox;
- ui.opacity = 1.0;
- ui.offset = (0.0, 0.0);
- HorizonLayout { sliders, scrollbar }
- }
- pub(crate) fn draw_horizon(
- &mut self,
- s: &Settings,
- batch: &mut HudBatch,
- atlas: &HudAtlas,
- cursor: (f32, f32),
- ) {
- let mut ui = Ui::new(atlas, batch, cursor);
- let backdrop = t::backdrop();
- self.horizon_layout(s, &mut ui, backdrop);
- ui.finish();
- }
- fn horizon_target(
- &mut self,
- s: &Settings,
- atlas: &HudAtlas,
- x: f32,
- y: f32,
- framebuffer: [i32; 2],
- ) -> (Option, Option, (f32, f32)) {
- let mut batch = horizon_batch(framebuffer);
- let mut ui = Ui::dry(atlas, &mut batch, (x, y));
- let layout = self.horizon_layout(s, &mut ui, 1.0);
- let scrollbar = layout.scrollbar;
- // The UI layer transforms raw GUI-pixel input into its own dp.
- let cursor = ui.cursor;
- let Some(hit) = ui.hit((x, y)) else {
- return (None, scrollbar, cursor);
- };
- if hit == SEARCH {
- return (Some(Target::Search), scrollbar, cursor);
- }
- let section = self.section.min(SECTIONS.len() - 1);
- if (NAV..NAV + SECTIONS.len() as u64).contains(&hit) {
- return (Some(Target::Nav((hit - NAV) as usize)), scrollbar, cursor);
- }
- if hit == DONE {
- return (Some(Target::Done), scrollbar, cursor);
- }
- if hit == STYLE || hit == STYLE + 1 {
- return (
- Some(Target::Style((hit - STYLE) as usize)),
- scrollbar,
- cursor,
- );
- }
- if hit == LEVEL || hit == LEVEL + 1 {
- return (
- Some(Target::Level((hit - LEVEL) as usize)),
- scrollbar,
- cursor,
- );
- }
- let Some(i) = hit.checked_sub(ROW).map(|i| i as usize) else {
- return (None, scrollbar, cursor);
- };
- let rows = self.horizon_rows(s, section);
- let item = match rows.get(i) {
- Some(HRow::Opt(opt)) => Some(Item::Vanilla(*opt)),
- Some(HRow::Graphics(item, ..)) => Some(*item),
- _ => None,
- };
- if let Some(item) = item
- && let Some(&(_, sx, sw)) = layout.sliders.iter().find(|(o, ..)| *o == item)
- {
- let v = t::slider_value(&ui, sx, sw, x);
- return (Some(Target::Slider(item, v)), scrollbar, cursor);
- }
- (
- (i < rows.len()).then_some(Target::Row(i)),
- scrollbar,
- cursor,
- )
- }
- /// A click (or a drag with the button held) on the Horizon shell.
- pub(crate) fn click_horizon(
- &mut self,
- s: &mut Settings,
- atlas: &HudAtlas,
- x: f32,
- y: f32,
- framebuffer: [i32; 2],
- drag: bool,
- right: bool,
- ) -> Vec {
- let mut events = Vec::new();
- if drag {
- let mut batch = horizon_batch(framebuffer);
- let mut ui = Ui::dry(atlas, &mut batch, (x, y));
- let layout = self.horizon_layout(s, &mut ui, 1.0);
- // Scrollbar geometry and stored drag positions are in Horizon dp.
- let pointer_y = ui.cursor.1;
- if let Some(previous_y) = self.scrollbar_drag_y {
- if let Some(scrollbar) = layout.scrollbar {
- // AbstractScrollArea.mouseDragged (inherited by AbstractSelectionList)
- // moves by the pointer delta and sends out-of-range drags to an end.
- let track = scrollbar.bottom - scrollbar.top;
- self.hscroll = if pointer_y < scrollbar.top {
- 0.0
- } else if pointer_y > scrollbar.bottom {
- scrollbar.max
- } else {
- self.hscroll
- + (pointer_y - previous_y) * scrollbar.max
- / (track - scrollbar.thumb).max(1.0)
- };
- self.hscroll = self.hscroll.clamp(0.0, scrollbar.max);
- self.scrollbar_drag_y = Some(pointer_y);
- } else {
- self.scrollbar_drag_y = None;
- }
- return events;
- }
- if let Some(item) = self.hdragging
- && let Some(&(_, sx, sw)) = layout.sliders.iter().find(|(o, ..)| *o == item)
- {
- set_item_slider(item, s, t::slider_value(&ui, sx, sw, x));
- events.push(Event::Changed);
- }
- return events;
- }
- // Rebinding consumes the click before sidebar or widget actions.
- if matches!(self.selected_key, Some(extras::ZOOM_KEY | extras::SORT_KEY)) {
- return self.bind_mouse(
- s,
- if right {
- winit::event::MouseButton::Right
- } else {
- winit::event::MouseButton::Left
- },
- );
- }
- let (target, scrollbar, cursor) = self.horizon_target(s, atlas, x, y, framebuffer);
- self.settings_search.focused = false;
- // AbstractScrollArea.updateScrolling grabs anywhere in the scrollbar column.
- if !right
- && let Some(scrollbar) = scrollbar
- && scrollbar.contains(cursor.0, cursor.1)
- {
- self.scrollbar_drag_y = Some(cursor.1);
- return events;
- }
- match target {
- Some(Target::Nav(i)) => self.select_section(i),
- Some(Target::Search) => {
- self.settings_search.focused = true;
- self.settings_search.move_cursor_to_end(false);
- }
- Some(Target::Done) => events.extend(self.back(s)),
- Some(Target::Style(i)) => {
- t::set_style(if i == 1 {
- MenuStyle::Classic
- } else {
- MenuStyle::Horizon
- });
- if let Ok(dir) = std::env::current_dir() {
- t::save_preferences(&dir);
- }
- }
- Some(Target::Level(i)) => {
- s.horizon.advanced = i == 1;
- self.hscroll = 0.0;
- events.push(Event::Changed);
- }
- Some(Target::Slider(item, v)) => {
- self.hdragging = Some(item);
- set_item_slider(item, s, v);
- events.push(Event::Changed);
- }
- Some(Target::Row(i)) => {
- let section = self.section.min(SECTIONS.len() - 1);
- match self.horizon_rows(s, section).get(i) {
- Some(HRow::Opt(opt)) if opt.available() => {
- opt.cycle(s, right, framebuffer);
- if *opt == Opt::Preset {
- apply_preset(s);
- }
- events.push(Event::Changed);
- }
- Some(HRow::Graphics(Item::Horizon(graphics_ui::H::ShaderPack), ..)) => {
- events.push(Event::ButtonClick);
- self.open_section(SHADER_PACKS);
- }
- Some(HRow::Graphics(item, ..)) => {
- item.cycle(s, right, framebuffer);
- events.push(Event::Changed);
- }
- Some(HRow::Page(_, _, page)) => self.open_page(*page),
- Some(HRow::Extra(item)) if item.key_name().is_some() => {
- self.selected_key = item.key_name();
- }
- Some(HRow::Extra(item)) => {
- item.cycle(&mut s.extras, right);
- events.push(Event::Changed);
- }
- Some(HRow::Mod(m)) => {
- s.mods.toggle(*m);
- events.push(Event::Changed);
- }
- Some(HRow::OpenModFolder) if !right => {
- events.push(Event::ButtonClick);
- events.push(Event::OpenModFolder);
- }
- Some(HRow::ShaderPackFolder) if !right => {
- events.push(Event::ButtonClick);
- events.push(Event::OpenShaderPackFolder);
- }
- Some(HRow::ShaderPack(p)) => {
- self.toggle_shader_pack(s, *p);
- events.push(Event::Changed);
- }
- _ => {}
- }
- }
- None => {}
- }
- events
- }
- fn select_section(&mut self, i: usize) {
- if searchable_section(self.section) || searchable_section(i) {
- self.settings_search.set_value("");
- }
- self.section = i;
- self.hscroll = 0.0;
- }
- /// Show the sidebar section called `name`.
- fn open_section(&mut self, name: &str) {
- if let Some(i) = SECTIONS.iter().position(|s| s.name == name) {
- self.select_section(i);
- }
- }
- pub(crate) fn scroll_horizon(&mut self, amount: f32) {
- self.hscroll -= amount * 40.0;
- }
-}
-
-/// A slider moved: vanilla options keep their preset handling, Horizon's own
-/// settings go through `graphics_ui`.
-fn set_item_slider(item: Item, s: &mut Settings, v: f32) {
- match item {
- Item::Vanilla(opt) => options_ui::set_slider(opt, s, v),
- Item::Horizon(_) => item.set_slider(s, v),
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn atlas() -> HudAtlas {
- HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
- }
-
- fn section_ui(name: &str) -> OptionsUi {
- let mut ui = OptionsUi::default();
- ui.section = SECTIONS
- .iter()
- .position(|section| section.name == name)
- .unwrap();
- ui
- }
-
- fn extras_ui() -> OptionsUi {
- section_ui("Extras")
- }
-
- fn scrollbar(
- ui: &mut OptionsUi,
- settings: &Settings,
- atlas: &HudAtlas,
- framebuffer: [i32; 2],
- ) -> HorizonScrollbar {
- let mut batch = horizon_batch(framebuffer);
- let mut draw = Ui::dry(atlas, &mut batch, (0.0, 0.0));
- ui.horizon_layout(settings, &mut draw, 1.0)
- .scrollbar
- .unwrap()
- }
-
- fn gui_pointer(atlas: &HudAtlas, framebuffer: [i32; 2], point: (f32, f32)) -> (f32, f32) {
- let mut batch = horizon_batch(framebuffer);
- let ui = Ui::dry(atlas, &mut batch, (0.0, 0.0));
- let gui_per_dp = ui.density / ui.batch.scale;
- (point.0 * gui_per_dp, point.1 * gui_per_dp)
- }
-
- #[test]
- fn extras_settings_nest_under_their_switch() {
- let mut s = Settings::default();
- let section = SECTIONS.iter().find(|s| s.name == "Extras").unwrap();
- let items = |s: &Settings| -> Vec {
- (section.rows)(s)
- .iter()
- .filter_map(|row| match row {
- HRow::Extra(item) => Some(*item),
- _ => None,
- })
- .collect()
- };
- // Everything off: one row per extra.
- assert!(items(&s).iter().all(|item| item.parent().is_none()));
- s.extras.zoom = true;
- let zoom_on = items(&s);
- assert!(zoom_on.contains(&extras::Item::ZoomKey));
- assert!(zoom_on.contains(&extras::Item::ZoomSensitivity));
- assert!(!zoom_on.contains(&extras::Item::MinimapSize));
- // Every setting shows once its switch is on.
- for item in extras::rows().into_iter().flatten() {
- if let Some(on) = item.switch(&s.extras)
- && item.parent().is_none()
- && !on
- {
- item.cycle(&mut s.extras, false);
- }
- }
- assert_eq!(
- items(&s).len(),
- extras::rows().into_iter().flatten().count()
- );
- }
-
- #[test]
- fn accessibility_section_only_shows_available_options() {
- let s = Settings::default();
- let section = SECTIONS.iter().find(|s| s.name == "Accessibility").unwrap();
- let rows = (section.rows)(&s);
- let options: Vec<_> = rows
- .iter()
- .filter_map(|row| match row {
- HRow::Opt(opt) => Some(*opt),
- _ => None,
- })
- .collect();
- let expected: Vec<_> = options_ui::ACCESSIBILITY_OPTIONS
- .iter()
- .copied()
- .filter(|opt| opt.available())
- .collect();
- assert_eq!(options, expected);
- assert!(options.iter().all(|opt| opt.available()));
- assert!(
- rows.iter()
- .any(|r| matches!(r, HRow::Page(_, _, Page::Controls)))
- );
- }
-
- #[test]
- fn horizon_scrollbar_track_drag_is_bounded_and_stops_on_release() {
- let atlas = atlas();
- let framebuffer = [2560, 1440];
- let mut settings = Settings::default();
- let mut ui = section_ui("Controls");
- let bar = scrollbar(&mut ui, &settings, &atlas, framebuffer);
- let max = bar.max;
- let track = bar.bottom - bar.top;
- assert!(max > 0.0);
-
- // Start on the track below the thumb, then move horizontally away;
- // the held scrollbar keeps following the pointer.
- let x = bar.x + 2.0;
- let y = bar.top + bar.thumb + (track - bar.thumb) / 2.0;
- assert!(y < bar.bottom);
- let (click_x, click_y) = gui_pointer(&atlas, framebuffer, (x, y));
- assert!(
- ui.click_horizon(
- &mut settings,
- &atlas,
- click_x,
- click_y,
- framebuffer,
- false,
- false,
- )
- .is_empty()
- );
- assert_eq!(ui.hscroll, 0.0);
- let delta = 5.0;
- let (drag_x, drag_y) = gui_pointer(&atlas, framebuffer, (x - 100.0, y + delta));
- assert!(
- ui.click_horizon(
- &mut settings,
- &atlas,
- drag_x,
- drag_y,
- framebuffer,
- true,
- false,
- )
- .is_empty()
- );
- assert!((ui.hscroll - delta * max / (track - bar.thumb)).abs() < 0.001);
-
- let (below_x, below_y) = gui_pointer(&atlas, framebuffer, (x, bar.bottom + 100.0));
- assert!(
- ui.click_horizon(
- &mut settings,
- &atlas,
- below_x,
- below_y,
- framebuffer,
- true,
- false,
- )
- .is_empty()
- );
- assert_eq!(ui.hscroll, max);
- let (above_x, above_y) = gui_pointer(&atlas, framebuffer, (x, bar.top - 100.0));
- assert!(
- ui.click_horizon(
- &mut settings,
- &atlas,
- above_x,
- above_y,
- framebuffer,
- true,
- false,
- )
- .is_empty()
- );
- assert_eq!(ui.hscroll, 0.0);
-
- assert!(ui.release().is_empty());
- let (below_x, below_y) = gui_pointer(&atlas, framebuffer, (x, bar.bottom + 100.0));
- assert!(
- ui.click_horizon(
- &mut settings,
- &atlas,
- below_x,
- below_y,
- framebuffer,
- true,
- false,
- )
- .is_empty()
- );
- assert_eq!(ui.hscroll, 0.0);
- assert_eq!(settings.keys, Settings::default().keys);
- }
-
- #[test]
- fn horizon_key_rebinding_takes_precedence_over_scrollbar_press() {
- let atlas = atlas();
- let framebuffer = [2560, 1440];
- let mut settings = Settings::default();
- let mut ui = extras_ui();
- let bar = scrollbar(&mut ui, &settings, &atlas, framebuffer);
- let dp_y = bar.top + bar.thumb + (bar.bottom - bar.top - bar.thumb) / 2.0;
- ui.selected_key = Some(extras::SORT_KEY);
- let (x, y) = gui_pointer(&atlas, framebuffer, (bar.x + 2.0, dp_y));
-
- assert_eq!(
- ui.click_horizon(&mut settings, &atlas, x, y, framebuffer, false, false,),
- vec![Event::Changed]
- );
- assert_eq!(settings.extras.sort_key, "key.mouse.left");
- assert_eq!(ui.selected_key, None);
- assert_eq!(ui.hscroll, 0.0);
-
- let (x, drag_y) = gui_pointer(&atlas, framebuffer, (bar.x + 2.0, dp_y + 10.0));
- ui.click_horizon(&mut settings, &atlas, x, drag_y, framebuffer, true, false);
- assert_eq!(ui.hscroll, 0.0);
- }
-
- /// The Shader Packs section: the folder's path and Open Folder, a switch
- /// per pack; the Video section's Shader Pack row leads here (#941, #925).
- #[test]
- fn shader_packs_section_opens_the_folder_and_picks_a_pack() {
- let atlas = atlas();
- let framebuffer = [2560, 1440];
- let dir =
- std::env::temp_dir().join(format!("horizon-shader-section-{}", std::process::id()));
- let _ = std::fs::remove_dir_all(&dir);
- std::fs::create_dir_all(&dir).unwrap();
- let mut options = section_ui(SHADER_PACKS);
- let mut settings = Settings::default();
- options.shader_packs.poll(dir.clone());
- assert!(matches!(
- options.horizon_rows(&settings, options.section)[..],
- [HRow::ShaderPackFolder, HRow::Header(_)]
- ));
- std::fs::write(dir.join("Pack.zip"), b"").unwrap();
- options.shader_packs = Default::default();
- options.shader_packs.poll(dir.clone());
- // Click the control with hit id `id`, scrolling until it shows.
- let click = |options: &mut OptionsUi, settings: &mut Settings, id: u64| {
- for _ in 0..40 {
- let mut batch = horizon_batch(framebuffer);
- let mut ui = Ui::dry(&atlas, &mut batch, (0.0, 0.0));
- options.horizon_layout(settings, &mut ui, 1.0);
- if let Some(hit) = ui.hits.iter().find(|hit| hit.id == id) {
- let r = hit.rect;
- let scale = ui.density / ui.batch.scale;
- let at = ((r[0] + r[2]) * 0.5 * scale, (r[1] + r[3]) * 0.5 * scale);
- drop(ui);
- return options.click_horizon(
- settings,
- &atlas,
- at.0,
- at.1,
- framebuffer,
- false,
- false,
- );
- }
- drop(ui);
- options.hscroll += 200.0;
- }
- panic!("no control {id}");
- };
- assert_eq!(
- click(&mut options, &mut settings, ROW),
- [Event::ButtonClick, Event::OpenShaderPackFolder]
- );
- assert_eq!(
- click(&mut options, &mut settings, ROW + 1),
- [Event::Changed]
- );
- assert_eq!(settings.horizon.shader_pack, "Pack.zip");
- click(&mut options, &mut settings, ROW + 1);
- assert_eq!(settings.horizon.shader_pack, "");
-
- let mut options = section_ui("Video");
- settings.horizon.advanced = true;
- let video = SECTIONS.iter().position(|s| s.name == "Video").unwrap();
- let row = options
- .horizon_rows(&settings, video)
- .iter()
- .position(|r| {
- matches!(
- r,
- HRow::Graphics(Item::Horizon(graphics_ui::H::ShaderPack), ..)
- )
- })
- .unwrap();
- assert_eq!(
- click(&mut options, &mut settings, ROW + row as u64),
- [Event::ButtonClick]
- );
- assert_eq!(SECTIONS[options.section].name, SHADER_PACKS);
- let _ = std::fs::remove_dir_all(&dir);
- }
-
- #[test]
- fn mods_section_opens_folder_from_its_button() {
- let atlas = atlas();
- let framebuffer = [2560, 1440];
- let mut options = section_ui("Mods");
- let mut settings = Settings::default();
- let mut batch = horizon_batch(framebuffer);
- let mut ui = Ui::dry(&atlas, &mut batch, (0.0, 0.0));
- options.horizon_layout(&settings, &mut ui, 1.0);
- let rect = ui
- .hits
- .iter()
- .find(|hit| hit.id == ROW)
- .expect("Mods section has an Open Folder button")
- .rect;
- let scale = ui.density / ui.batch.scale;
- let cursor = (
- (rect[0] + rect[2]) * 0.5 * scale,
- (rect[1] + rect[3]) * 0.5 * scale,
- );
- drop(ui);
-
- assert_eq!(
- options.click_horizon(
- &mut settings,
- &atlas,
- cursor.0,
- cursor.1,
- framebuffer,
- false,
- false
- ),
- vec![Event::ButtonClick, Event::OpenModFolder]
- );
- assert!(
- options
- .click_horizon(
- &mut settings,
- &atlas,
- cursor.0,
- cursor.1,
- framebuffer,
- false,
- true
- )
- .is_empty()
- );
- }
-}
diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs
index 7d86263df..6431ae613 100644
--- a/crates/horizon-client/src/options_ui.rs
+++ b/crates/horizon-client/src/options_ui.rs
@@ -130,7 +130,7 @@ pub(crate) enum Kind {
Slider(f32),
Cycle,
}
-/// Options shared by the Classic page and Horizon's Accessibility section.
+/// The Accessibility Settings page:
/// `AccessibilityOptionsScreen.options`, with the Controls link inserted separately.
pub(crate) const ACCESSIBILITY_OPTIONS: &[Opt] = &[
Opt::Narrator,
@@ -871,6 +871,9 @@ pub enum Page {
Controller,
PadBinds,
Extras,
+ /// Horizon Settings: every page Horizon adds, as a mod's settings
+ /// screen hangs off vanilla's Options.
+ Horizon,
}
#[derive(Clone, Debug, PartialEq)]
enum Act {
@@ -886,8 +889,6 @@ enum Act {
PadKey(&'static str),
ResetPadKey(&'static str),
ResetPadKeys,
- /// Back to Horizon's own menus (Horizon only, see `list_rows`).
- HorizonMenus,
ToggleMod(usize),
OpenModFolder,
/// Pick shader pack `i` of `OptionsUi::shader_packs` (again: off).
@@ -968,15 +969,8 @@ pub struct OptionsUi {
/// when it last moved: the handle follows the pointer while the option
/// keeps its stepped value, then snaps to it (`resetValue`).
slider_value: Option<(Opt, f32, Instant)>,
- /// The pointer's last y while a Classic or Horizon scrollbar is held.
+ /// The pointer's last y while a scrollbar is held.
pub(crate) scrollbar_drag_y: Option,
- /// Horizon style: the selected sidebar section, the one last drawn and
- /// the rows' scroll in dp (`options_horizon`).
- pub section: usize,
- pub(crate) section_shown: Option,
- pub(crate) hscroll: f32,
- /// The slider being dragged on the Horizon options shell.
- pub(crate) hdragging: Option,
/// Key Binds: the mapping waiting for a key.
pub selected_key: Option<&'static str>,
/// Controller Binds: the action waiting for a pad button.
@@ -1017,10 +1011,6 @@ impl Default for OptionsUi {
dragging: None,
slider_value: None,
scrollbar_drag_y: None,
- section: 0,
- section_shown: None,
- hscroll: 0.0,
- hdragging: None,
selected_key: None,
selected_pad_action: None,
pad_style: GlyphStyle::Xbox,
@@ -1081,6 +1071,27 @@ fn option_widget(s: &Settings, opt: Opt, x: f32, y: f32, w: f32) -> Widget {
Kind::Cycle => button(x, y, w, opt.label(s), Act::Cycle(opt)),
}
}
+/// What a button opening one of Horizon's pages says on hover.
+fn horizon_page_tooltip(page: Page) -> Option<&'static str> {
+ Some(match page {
+ Page::Horizon => {
+ "Horizon's own settings: graphics, shader packs, controllers, extras and mods."
+ }
+ Page::Graphics => "Graphics, simply: each setting says what it costs.",
+ Page::GraphicsAdvanced => {
+ "Every graphics setting, Horizon's included, with what each costs."
+ }
+ Page::ShaderPacks => "Packs that redraw the world. Off is the vanilla look.",
+ Page::Controller => "Controllers: their buttons, sticks, vibration and menu navigation.",
+ Page::Extras => {
+ "Optional additions, all off by default: the game stays vanilla until you turn one on."
+ }
+ Page::Mods => {
+ "Mods made for Horizon, from the horizon-mods folder. Each runs in a sandbox and stays off until you turn it on."
+ }
+ _ => return None,
+ })
+}
/// Rows of an OptionsList: (big?, options) or a header.
enum Row {
Big(Opt),
@@ -1098,10 +1109,7 @@ fn pairs(opts: &[Opt]) -> Vec {
impl OptionsUi {
fn settings_search_active(&self) -> bool {
self.settings_search.focused
- && (matches!(self.page(), Page::Video | Page::Controls | Page::KeyBinds)
- || (crate::ui_theme::horizon()
- && self.page() == Page::Main
- && crate::options_horizon::searchable_section(self.section)))
+ && matches!(self.page(), Page::Video | Page::Controls | Page::KeyBinds)
}
pub fn page(&self) -> Page {
*self.stack.last().unwrap_or(&Page::Main)
@@ -1122,10 +1130,6 @@ impl OptionsUi {
self.in_world = in_world;
self.selected_key = None;
}
- /// Open one of vanilla's pages over the current one.
- pub(crate) fn open_page(&mut self, page: Page) {
- self.push(page);
- }
fn push(&mut self, page: Page) {
self.stack.push(page);
self.scroll = 0.0;
@@ -1164,14 +1168,9 @@ impl OptionsUi {
.as_ref()
.is_some_and(|(e, _)| e == id)
}
- /// Whether the Shader Packs page (or the Horizon menus' section) shows.
+ /// Whether the Shader Packs page shows.
fn shader_packs_shown(&self) -> bool {
self.page() == Page::ShaderPacks
- || crate::ui_theme::horizon()
- && self.page() == Page::Main
- && crate::options_horizon::SECTIONS
- .get(self.section)
- .is_some_and(|s| s.name == crate::options_horizon::SHADER_PACKS)
}
/// The graphics screen level of `page`, if it is one.
fn graphics_level(page: Page) -> Option {
@@ -1200,6 +1199,7 @@ impl OptionsUi {
Page::Controller => "Controller Settings",
Page::PadBinds => "Controller Binds",
Page::Extras => "Horizon Extras",
+ Page::Horizon => "Horizon Settings",
}
}
fn scrollbar_x(&self, width: f32) -> f32 {
@@ -1263,7 +1263,17 @@ impl OptionsUi {
} else {
Text::literal(value)
};
- button(0.0, 0.0, 150.0, label, Act::Extra(item))
+ let widget = button(0.0, 0.0, 150.0, label, Act::Extra(item));
+ // A setting of a switch that is off does nothing: inactive,
+ // as vanilla greys out an option that can't apply.
+ if item
+ .parent()
+ .is_some_and(|parent| parent.switch(&s.extras) == Some(false))
+ {
+ inactive(widget)
+ } else {
+ widget
+ }
};
let mut rows = Vec::new();
let mut section = Vec::new();
@@ -1287,6 +1297,27 @@ impl OptionsUi {
flush(&mut rows, &mut section);
rows
}
+ Page::Horizon => {
+ // Two to a row, as vanilla's OptionsList.addSmall lays out
+ // buttons; each opens a page built from vanilla's widgets.
+ let open = |label: &str, page: Page| {
+ button(0.0, 0.0, 150.0, Text::literal(label), Act::Push(page))
+ };
+ vec![
+ Row::Buttons(
+ open("Graphics...", Page::Graphics),
+ Some(open("Advanced Graphics...", Page::GraphicsAdvanced)),
+ ),
+ Row::Buttons(
+ open("Shader Packs...", Page::ShaderPacks),
+ Some(open("Controller Settings...", Page::Controller)),
+ ),
+ Row::Buttons(
+ open("Extras...", Page::Extras),
+ Some(open("Mods...", Page::Mods)),
+ ),
+ ]
+ }
Page::Video => {
// Horizon's graphics screens, Simple and Advanced.
let mut rows = vec![Row::Buttons(
@@ -1315,22 +1346,6 @@ impl OptionsUi {
),
None,
));
- // The way back from Classic menus. Horizon-only like the row
- // above, here rather than on the main Options screen so that
- // one keeps vanilla's exact layout; vanilla's interface
- // settings (GUI Scale) are on this page too.
- if !crate::ui_theme::horizon() {
- rows.push(Row::Buttons(
- button(
- 0.0,
- 0.0,
- 310.0,
- Text::literal("Menu Style: Classic"),
- Act::HorizonMenus,
- ),
- None,
- ));
- }
rows.push(Row::Header("options.video.display.header"));
rows.extend(pairs(&[
Opt::MaxFps,
@@ -1578,8 +1593,10 @@ impl OptionsUi {
("options.chat", Some(Page::Chat)),
("options.resourcepack", Some(Page::Packs)),
("options.accessibility", Some(Page::Accessibility)),
+ // Vanilla's Telemetry Data and Credits slots: Horizon's
+ // settings and its mods, as a mod adds its button here.
+ ("Horizon Settings...", Some(Page::Horizon)),
("Mods...", Some(Page::Mods)),
- ("Horizon Extras...", Some(Page::Extras)),
];
let gy = (61.0 + 30.0f32).min(h - 33.0 - 120.0);
for (i, (key, page)) in entries.iter().enumerate() {
@@ -2052,10 +2069,6 @@ impl OptionsUi {
);
return;
}
- if crate::ui_theme::horizon() && self.page() == Page::Main {
- self.draw_horizon(s, batch, atlas, cursor);
- return;
- }
if let Some(level) = Self::graphics_level(self.page()) {
self.graphics
.draw(level, s, batch, atlas, cursor, self.in_world);
@@ -2094,6 +2107,14 @@ impl OptionsUi {
{
tooltip = Some(atlas.font.split(&Text::literal(item.description()), 170.0));
}
+ if let WKind::Button {
+ act: Act::Push(page),
+ ..
+ } = &wd.kind
+ && let Some(text) = horizon_page_tooltip(*page)
+ {
+ tooltip = Some(atlas.font.split(&Text::literal(text), 170.0));
+ }
let key = match &wd.kind {
WKind::Button {
act: Act::Cycle(opt),
@@ -2300,9 +2321,6 @@ impl OptionsUi {
}
return Vec::new();
}
- if crate::ui_theme::horizon() && self.page() == Page::Main {
- return self.click_horizon(s, atlas, x, y, framebuffer, drag, right);
- }
if let Some(level) = Self::graphics_level(self.page()) {
use crate::graphics_ui::Action;
let mut events = Vec::new();
@@ -2471,12 +2489,6 @@ impl OptionsUi {
s.controller.reset_bindings();
events.push(Event::Changed);
}
- Act::HorizonMenus => {
- self.horizon_menus();
- if let Ok(dir) = std::env::current_dir() {
- crate::ui_theme::save_preferences(&dir);
- }
- }
Act::ToggleMod(i) => {
s.mods.toggle(i);
events.push(Event::Changed);
@@ -2510,20 +2522,6 @@ impl OptionsUi {
}
events
}
- /// Switch to Horizon's menus and show where the choice lives there
- /// (Options, Interface, Menu style).
- fn horizon_menus(&mut self) {
- crate::ui_theme::set_style(crate::ui_theme::MenuStyle::Horizon);
- self.stack.truncate(1);
- self.scroll = 0.0;
- self.scrollbar_drag_y = None;
- self.section = crate::options_horizon::SECTIONS
- .iter()
- .position(|section| section.name == "Interface")
- .unwrap_or(0);
- self.section_shown = None;
- self.hscroll = 0.0;
- }
/// Where a slider's handle sits: its own position while held (or until
/// a delayed one applies), else the option's stepped value.
fn slider_shown(&self, opt: Opt, value: f32) -> f32 {
@@ -2540,7 +2538,6 @@ impl OptionsUi {
// AbstractSliderButton suppresses the press sound and plays once on
// release, even if the pointer has left the widget or its value stayed.
let slider = self.dragging.take().is_some();
- self.hdragging = None;
let graphics_slider = self.graphics.release();
if slider || graphics_slider {
vec![Event::ButtonClick]
@@ -2558,10 +2555,6 @@ impl OptionsUi {
if self.resource_error.is_some() {
return;
}
- if crate::ui_theme::horizon() && self.page() == Page::Main {
- self.scroll_horizon(amount);
- return;
- }
if let Some(level) = Self::graphics_level(self.page()) {
self.graphics.scroll(level, size.1, amount);
return;
@@ -2783,7 +2776,6 @@ impl OptionsUi {
#[cfg(test)]
mod tests {
use super::*;
- use crate::ui_theme::{MenuStyle, set_style, style};
#[test]
fn accessibility_sliders_and_toggles_survive_options_round_trip() {
@@ -3337,9 +3329,7 @@ mod tests {
}
#[test]
- fn classic_extras_entry_edits_shared_settings_and_returns_without_changing_style() {
- let previous_style = style();
- set_style(MenuStyle::Classic);
+ fn extras_from_horizon_settings_edit_shared_settings_and_return() {
let atlas = atlas();
let mut s = Settings::default();
let mut ui = OptionsUi::default();
@@ -3363,11 +3353,13 @@ mod tests {
false,
)
};
- assert_eq!(
- click(&mut ui, &mut s, Act::Push(Page::Extras)),
- vec![Event::ButtonClick]
- );
- assert_eq!(ui.page(), Page::Extras);
+ for page in [Page::Horizon, Page::Extras] {
+ assert_eq!(
+ click(&mut ui, &mut s, Act::Push(page)),
+ vec![Event::ButtonClick]
+ );
+ assert_eq!(ui.page(), page);
+ }
let (widgets, _, _, _) = ui.layout(&s, size.0, size.1);
assert_eq!(
widgets
@@ -3408,9 +3400,7 @@ mod tests {
ui.key(&mut s, &atlas, winit::keyboard::KeyCode::Escape, None),
vec![Event::Changed]
);
- assert_eq!(ui.page(), Page::Main);
- assert_eq!(style(), MenuStyle::Classic);
- set_style(previous_style);
+ assert_eq!(ui.page(), Page::Horizon);
}
#[test]
@@ -3994,15 +3984,25 @@ mod tests {
let atlas = atlas();
let mut s = Settings::default();
let mut ui = OptionsUi::default();
+ ui.show(Page::Extras);
for (right, expected) in [(false, "key.mouse.left"), (true, "key.mouse.right")] {
ui.selected_key = Some(crate::extras::SORT_KEY);
assert_eq!(
- ui.click_horizon(&mut s, &atlas, 2.0, 2.0, [960, 480], false, right),
+ ui.click(
+ &mut s,
+ &atlas,
+ 2.0,
+ 2.0,
+ (480.0, 240.0),
+ [960, 480],
+ false,
+ right
+ ),
vec![Event::Changed]
);
assert_eq!(s.extras.sort_key, expected);
assert_eq!(ui.selected_key, None);
- assert_eq!(ui.section, 0);
+ assert_eq!(ui.page(), Page::Extras);
}
}
@@ -4116,30 +4116,45 @@ mod tests {
}
#[test]
- fn classic_video_settings_lead_back_to_horizon_menus() {
- let previous_style = style();
- set_style(MenuStyle::Horizon);
+ fn horizon_settings_hang_off_options_and_reach_every_horizon_page() {
let s = Settings::default();
let mut ui = OptionsUi::default();
- ui.push(Page::Video);
- let way_back = |ui: &OptionsUi| {
- ui.list_rows(&s).iter().any(|row| {
- matches!(row, Row::Buttons(w, _)
- if matches!(&w.kind, WKind::Button { act: Act::HorizonMenus, .. }))
- })
+ let pushes = |ui: &mut OptionsUi| -> Vec {
+ let (widgets, _, _, _) = ui.layout(&s, 427.0, 240.0);
+ widgets
+ .iter()
+ .filter_map(|w| match &w.kind {
+ WKind::Button {
+ act: Act::Push(page),
+ active: true,
+ ..
+ } => Some(*page),
+ _ => None,
+ })
+ .collect()
};
- // Horizon's own menus have the choice on their Interface page.
- assert!(!way_back(&ui));
- set_style(MenuStyle::Classic);
- let classic = way_back(&ui);
- ui.horizon_menus();
- assert!(classic, "Classic Video Settings offer Menu Style");
- assert_eq!(style(), MenuStyle::Horizon);
- assert_eq!(ui.stack, vec![Page::Main]);
+ // Vanilla's ten Options buttons, the last two Horizon's.
+ let main = pushes(&mut ui);
+ assert_eq!(&main[main.len() - 2..], [Page::Horizon, Page::Mods]);
+ ui.push(Page::Horizon);
assert_eq!(
- crate::options_horizon::SECTIONS[ui.section].name,
- "Interface"
+ pushes(&mut ui),
+ [
+ Page::Graphics,
+ Page::GraphicsAdvanced,
+ Page::ShaderPacks,
+ Page::Controller,
+ Page::Extras,
+ Page::Mods,
+ ]
);
- set_style(previous_style);
+ // Vanilla's own pages keep the Horizon pages they had.
+ ui.stack = vec![Page::Main, Page::Video];
+ let video = pushes(&mut ui);
+ for page in [Page::Graphics, Page::GraphicsAdvanced, Page::ShaderPacks] {
+ assert!(video.contains(&page), "{page:?}");
+ }
+ ui.stack = vec![Page::Main, Page::Controls];
+ assert!(pushes(&mut ui).contains(&Page::Controller));
}
}
diff --git a/crates/horizon-client/src/post.rs b/crates/horizon-client/src/post.rs
deleted file mode 100644
index 8234d90b3..000000000
--- a/crates/horizon-client/src/post.rs
+++ /dev/null
@@ -1,273 +0,0 @@
-//! The menus' backdrop treatment (`ui_theme`'s Horizon style): the finished
-//! world frame is blurred (dual Kawase: three halvings down, back up) and
-//! colour graded before the HUD is drawn over it. Needs a swapchain that can
-//! be copied from; without one the frame is left as it is.
-
-/// How the frame under a Horizon-style menu is treated.
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub struct PostGrade {
- /// Colour multiplier and lift (`c * tint + lift`).
- pub tint: [f32; 3],
- pub lift: [f32; 3],
- /// Toward grey, 0..1.
- pub desaturate: f32,
- /// Darkening toward the corners, 0..1.
- pub vignette: f32,
-}
-impl PostGrade {
- /// The title backdrop: icy, slightly lifted shadows.
- pub const FROST: Self = Self {
- tint: [0.62, 0.78, 1.0],
- lift: [0.0, 0.01, 0.035],
- desaturate: 0.45,
- vignette: 0.5,
- };
- /// Behind the pause menu: the world stays recognisable.
- pub const PAUSE: Self = Self {
- tint: [0.8, 0.86, 0.98],
- lift: [0.0, 0.004, 0.012],
- desaturate: 0.25,
- vignette: 0.3,
- };
-}
-#[repr(C)]
-#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
-struct Uniform {
- texel: [f32; 4],
- tint: [f32; 4],
- lift: [f32; 4],
- params: [f32; 4],
-}
-const LEVELS: usize = 3;
-pub struct Post {
- layout: wgpu::BindGroupLayout,
- down: wgpu::RenderPipeline,
- up: wgpu::RenderPipeline,
- finish: wgpu::RenderPipeline,
- sampler: wgpu::Sampler,
- /// The copied frame, then the halvings.
- levels: Vec<(wgpu::Texture, wgpu::TextureView, [u32; 2])>,
- uniforms: Vec,
- size: [u32; 2],
- format: wgpu::TextureFormat,
-}
-impl Post {
- pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
- let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
- label: Some("Menu backdrop"),
- source: wgpu::ShaderSource::Wgsl(include_str!("post.wgsl").into()),
- });
- let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: Some("Menu backdrop bindings"),
- entries: &[
- wgpu::BindGroupLayoutEntry {
- binding: 0,
- visibility: wgpu::ShaderStages::FRAGMENT,
- ty: wgpu::BindingType::Texture {
- sample_type: wgpu::TextureSampleType::Float { filterable: true },
- view_dimension: wgpu::TextureViewDimension::D2,
- multisampled: false,
- },
- count: None,
- },
- wgpu::BindGroupLayoutEntry {
- binding: 1,
- visibility: wgpu::ShaderStages::FRAGMENT,
- ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
- count: None,
- },
- wgpu::BindGroupLayoutEntry {
- binding: 2,
- visibility: wgpu::ShaderStages::FRAGMENT,
- ty: wgpu::BindingType::Buffer {
- ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
- },
- count: None,
- },
- ],
- });
- let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
- label: Some("Menu backdrop"),
- bind_group_layouts: &[Some(&layout)],
- ..Default::default()
- });
- let pipeline = |entry: &str| {
- device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
- label: Some("Menu backdrop pass"),
- layout: Some(&pipeline_layout),
- vertex: wgpu::VertexState {
- module: &shader,
- entry_point: Some("vs_main"),
- buffers: &[],
- compilation_options: Default::default(),
- },
- fragment: Some(wgpu::FragmentState {
- module: &shader,
- entry_point: Some(entry),
- targets: &[Some(wgpu::ColorTargetState {
- format,
- blend: None,
- write_mask: wgpu::ColorWrites::ALL,
- })],
- compilation_options: Default::default(),
- }),
- primitive: Default::default(),
- depth_stencil: None,
- multisample: Default::default(),
- multiview_mask: None,
- cache: None,
- })
- };
- let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
- label: Some("Menu backdrop"),
- mag_filter: wgpu::FilterMode::Linear,
- min_filter: wgpu::FilterMode::Linear,
- address_mode_u: wgpu::AddressMode::ClampToEdge,
- address_mode_v: wgpu::AddressMode::ClampToEdge,
- ..Default::default()
- });
- let uniforms = (0..LEVELS * 2 + 1)
- .map(|_| {
- device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("Menu backdrop pass"),
- size: std::mem::size_of::() as u64,
- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- })
- })
- .collect();
- Self {
- down: pipeline("fs_down"),
- up: pipeline("fs_up"),
- finish: pipeline("fs_final"),
- layout,
- sampler,
- levels: Vec::new(),
- uniforms,
- size: [0, 0],
- format,
- }
- }
- fn ensure(&mut self, device: &wgpu::Device, size: [u32; 2]) {
- if self.size == size && !self.levels.is_empty() {
- return;
- }
- self.size = size;
- self.levels = (0..=LEVELS)
- .map(|i| {
- let s = [(size[0] >> i).max(1), (size[1] >> i).max(1)];
- let texture = device.create_texture(&wgpu::TextureDescriptor {
- label: Some("Menu backdrop level"),
- size: wgpu::Extent3d {
- width: s[0],
- height: s[1],
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: self.format,
- usage: wgpu::TextureUsages::TEXTURE_BINDING
- | wgpu::TextureUsages::RENDER_ATTACHMENT
- | wgpu::TextureUsages::COPY_DST,
- view_formats: &[],
- });
- let view = texture.create_view(&Default::default());
- (texture, view, s)
- })
- .collect();
- }
- fn pass(
- &self,
- device: &wgpu::Device,
- queue: &wgpu::Queue,
- encoder: &mut wgpu::CommandEncoder,
- pipeline: &wgpu::RenderPipeline,
- (from, uniform): (usize, usize),
- target: &wgpu::TextureView,
- data: Uniform,
- ) {
- let (_, view, s) = &self.levels[from];
- let mut data = data;
- data.texel = [0.5 / s[0] as f32, 0.5 / s[1] as f32, 0.0, 0.0];
- queue.write_buffer(&self.uniforms[uniform], 0, bytemuck::bytes_of(&data));
- let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("Menu backdrop pass"),
- layout: &self.layout,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::TextureView(view),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::Sampler(&self.sampler),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: self.uniforms[uniform].as_entire_binding(),
- },
- ],
- });
- let attachments = [Some(wgpu::RenderPassColorAttachment {
- view: target,
- resolve_target: None,
- depth_slice: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
- store: wgpu::StoreOp::Store,
- },
- })];
- let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("Menu backdrop pass"),
- color_attachments: &attachments,
- ..Default::default()
- });
- pass.set_pipeline(pipeline);
- pass.set_bind_group(0, &group, &[]);
- pass.draw(0..3, 0..1);
- }
- /// Blur and grade `frame` (the swapchain texture) into `target`.
- #[allow(clippy::too_many_arguments)]
- pub fn apply(
- &mut self,
- device: &wgpu::Device,
- queue: &wgpu::Queue,
- encoder: &mut wgpu::CommandEncoder,
- frame: &wgpu::Texture,
- target: &wgpu::TextureView,
- size: [u32; 2],
- grade: &PostGrade,
- ) {
- self.ensure(device, size);
- encoder.copy_texture_to_texture(
- frame.as_image_copy(),
- self.levels[0].0.as_image_copy(),
- wgpu::Extent3d {
- width: size[0],
- height: size[1],
- depth_or_array_layers: 1,
- },
- );
- let data = Uniform {
- texel: [0.0; 4],
- tint: [grade.tint[0], grade.tint[1], grade.tint[2], 1.0],
- lift: [grade.lift[0], grade.lift[1], grade.lift[2], 0.0],
- params: [grade.desaturate, grade.vignette, 0.0, 0.0],
- };
- let mut u = 0;
- for i in 1..=LEVELS {
- let target = &self.levels[i].1;
- self.pass(device, queue, encoder, &self.down, (i - 1, u), target, data);
- u += 1;
- }
- for i in (1..LEVELS).rev() {
- let target = &self.levels[i].1;
- self.pass(device, queue, encoder, &self.up, (i + 1, u), target, data);
- u += 1;
- }
- self.pass(device, queue, encoder, &self.finish, (1, u), target, data);
- }
-}
diff --git a/crates/horizon-client/src/post.wgsl b/crates/horizon-client/src/post.wgsl
deleted file mode 100644
index ba2d7bfb2..000000000
--- a/crates/horizon-client/src/post.wgsl
+++ /dev/null
@@ -1,51 +0,0 @@
-// Menu backdrop: dual-Kawase blur (down and up passes) and a cold colour grade.
-struct Post {
- // Half a source texel (u, v), unused, unused.
- texel: vec4,
- // Multiplier and lift of the grade.
- tint: vec4,
- lift: vec4,
- // Desaturation, vignette, unused, unused.
- params: vec4,
-}
-@group(0) @binding(0) var src: texture_2d;
-@group(0) @binding(1) var samp: sampler;
-@group(0) @binding(2) var post: Post;
-struct Out {
- @builtin(position) clip: vec4,
- @location(0) uv: vec2,
-}
-@vertex fn vs_main(@builtin(vertex_index) i: u32) -> Out {
- let p = vec2(f32((i << 1u) & 2u), f32(i & 2u));
- var out: Out;
- out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0);
- out.uv = vec2(p.x, 1.0 - p.y);
- return out;
-}
-fn s(uv: vec2) -> vec3 {
- return textureSampleLevel(src, samp, uv, 0.0).rgb;
-}
-@fragment fn fs_down(in: Out) -> @location(0) vec4 {
- let h = post.texel.xy;
- let c = s(in.uv) * 4.0 + s(in.uv - h) + s(in.uv + h) + s(in.uv + vec2(h.x, -h.y)) + s(in.uv - vec2(h.x, -h.y));
- return vec4(c / 8.0, 1.0);
-}
-fn up(uv: vec2) -> vec3 {
- let h = post.texel.xy;
- var c = s(uv + vec2(-h.x * 2.0, 0.0)) + s(uv + vec2(h.x * 2.0, 0.0));
- c += s(uv + vec2(0.0, -h.y * 2.0)) + s(uv + vec2(0.0, h.y * 2.0));
- c += (s(uv + vec2(-h.x, h.y)) + s(uv + vec2(h.x, h.y)) + s(uv + vec2(-h.x, -h.y)) + s(uv + vec2(h.x, -h.y))) * 2.0;
- return c / 12.0;
-}
-@fragment fn fs_up(in: Out) -> @location(0) vec4 {
- return vec4(up(in.uv), 1.0);
-}
-@fragment fn fs_final(in: Out) -> @location(0) vec4 {
- var c = up(in.uv);
- let l = dot(c, vec3(0.2126, 0.7152, 0.0722));
- c = mix(c, vec3(l), post.params.x);
- c = c * post.tint.rgb + post.lift.rgb;
- let d = length((in.uv - 0.5) * vec2(1.25, 1.0));
- c *= 1.0 - post.params.y * smoothstep(0.35, 0.95, d);
- return vec4(clamp(c, vec3(0.0), vec3(1.0)), 1.0);
-}
diff --git a/crates/horizon-client/src/telemetry.rs b/crates/horizon-client/src/telemetry.rs
index ec67fe7f7..4a4da2094 100644
--- a/crates/horizon-client/src/telemetry.rs
+++ b/crates/horizon-client/src/telemetry.rs
@@ -33,7 +33,7 @@ pub fn mark_start() {
STARTED.get_or_init(Instant::now);
}
-/// The menu bundle is ready: the title backdrop can draw. The first writer wins.
+/// The menu bundle is ready: the title screen can draw. The first writer wins.
pub fn mark_ui_ready() {
if let Some(started) = STARTED.get() {
let ms = started.elapsed().as_millis() as u32;
diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs
index 17684602c..8a04df67e 100644
--- a/crates/horizon-client/src/title.rs
+++ b/crates/horizon-client/src/title.rs
@@ -142,10 +142,6 @@ pub struct Title {
toast: Option<(crate::toasts::Slide, BackupToast)>,
icons: RefCell>)>>,
splash: Option,
- /// The mode last drawn and when it appeared (Horizon's screen fades).
- shown: std::cell::Cell<(std::mem::Discriminant, std::time::Instant)>,
- /// The launcher-style opening (Horizon style, first title of the session).
- pub opening: std::cell::Cell>,
/// The saves listed for Home, re-read every couple of seconds.
recent: std::cell::RefCell )>>,
}
@@ -232,7 +228,6 @@ impl Title {
let mode = Mode::Main;
let now = std::time::Instant::now();
Self {
- shown: std::cell::Cell::new((std::mem::discriminant(&mode), now)),
mode,
last_server: String::new(),
saves,
@@ -256,7 +251,6 @@ impl Title {
.subsec_nanos() as usize,
(today.month(), today.day()),
),
- opening: std::cell::Cell::new(None),
recent: std::cell::RefCell::new(None),
}
}
@@ -517,17 +511,6 @@ impl Title {
}
}
}
- /// When the current mode first appeared.
- pub fn entered(&self) -> std::time::Instant {
- let now = std::mem::discriminant(&self.mode);
- let (mode, at) = self.shown.get();
- if mode == now {
- return at;
- }
- let at = std::time::Instant::now();
- self.shown.set((now, at));
- at
- }
/// Create New World: the folder name and options (FileUtil.findAvailableName).
pub fn create_action(&self) -> Action {
let Mode::Create {
@@ -597,7 +580,9 @@ impl Title {
b(cx + 2.0, y + 96.0, 98.0, "Quit Game", true, 2),
];
for (i, (label, enabled, id, icon, size)) in [
- ("Friends", false, 5, "friends/friends", 15.0),
+ // Horizon's Join a Friend (an invite code) behind
+ // vanilla's Friends button.
+ ("Friends", true, 5, "friends/friends", 15.0),
("Language", true, 6, "icon/language", 15.0),
(
"Accessibility Settings",
@@ -1207,6 +1192,10 @@ impl Title {
crate::multiplayer::Outcome::Connect(address) => Action::Connect { address },
crate::multiplayer::Outcome::None => Action::None,
},
+ (Mode::Main, Some(5)) => {
+ self.mode = Mode::Multiplayer(crate::multiplayer::Screen::friend());
+ Action::None
+ }
(Mode::Main, Some(3)) => Action::Options,
(Mode::Main, Some(7)) => Action::Accessibility,
(Mode::Main, Some(6)) => Action::Language,
@@ -1669,7 +1658,7 @@ mod classic_tests {
let cx = (w / 2.0).floor();
let y = (h / 4.0).floor() + 48.0;
for (id, x, enabled, icon) in [
- (5, cx - 34.0, false, "friends/friends"),
+ (5, cx - 34.0, true, "friends/friends"),
(6, cx - 10.0, true, "icon/language"),
(7, cx + 14.0, true, "icon/accessibility"),
] {
@@ -1683,9 +1672,16 @@ mod classic_tests {
match id {
6 => (Action::Language, true),
7 => (Action::Accessibility, true),
- _ => (Action::None, false),
+ _ => (Action::None, true),
}
);
+ if id == 5 {
+ assert!(matches!(
+ title.mode,
+ Mode::Multiplayer(crate::multiplayer::Screen::Friend { .. })
+ ));
+ title.mode = Mode::Main;
+ }
}
for id in [2, 3] {
assert_eq!(buttons.iter().find(|b| b.id == id).unwrap().y, y + 96.0);
diff --git a/crates/horizon-client/src/title/world_management.rs b/crates/horizon-client/src/title/world_management.rs
index 5884a1d88..d5fc9bc58 100644
--- a/crates/horizon-client/src/title/world_management.rs
+++ b/crates/horizon-client/src/title/world_management.rs
@@ -38,7 +38,7 @@ pub(super) fn reset_icon(saves: &Path, folder: &str) -> crate::Result<()> {
Ok(())
}
-/// `LevelStorageAccess.deleteLevel`, shared by both menu styles. The world's
+/// `LevelStorageAccess.deleteLevel`. The world's
/// session lock is taken first, so a world open in this or another instance is
/// refused rather than pulled from under it; everything but the lock goes,
/// then the lock is released and removed with the folder. A failed pass (a
diff --git a/crates/horizon-client/src/ui_theme.rs b/crates/horizon-client/src/ui_theme.rs
index 2e082cd6c..f4581f4b3 100644
--- a/crates/horizon-client/src/ui_theme.rs
+++ b/crates/horizon-client/src/ui_theme.rs
@@ -1,90 +1,21 @@
-//! Horizon's own menu style ("Menu style: Horizon" in the options), shared by
-//! the front-end screens: title, world list, create world, multiplayer,
-//! options and pause. Everything vanilla compares (HUD, inventories, chat,
-//! the pack and key-bind screens) keeps the classic widgets in `ui`.
+//! The design system's widgets drawn in the game (`crates/horizon-theme`:
+//! palette, type scale, radii, control sizes, motion and the bundled fonts;
+//! `docs/design-system.md`). Every menu is vanilla's (`ui`); what is left
+//! here draws Horizon's own overlays that vanilla has no screen for: the
+//! on-screen keyboard a controller types with (`osk`), plus the
+//! `horizon.txt` preferences.
//!
-//! It is the launcher's look, from the same tokens: `crates/horizon-theme`
-//! holds the palette, type scale, spacing, radii, control sizes, motion and
-//! the bundled fonts (`docs/design-system.md` describes them), and
-//! `launcher/src/theme.rs` reads the same values, so changing one changes
-//! both. The components below port the launcher's (`launcher/src/main.rs`):
-//! pill buttons with a hover layer and press state, the sidebar of text items
-//! with the sliding selection, the segmented control with its ink pill, the
-//! switch, numbered settings rows with one-pixel rules, the page header, and
-//! tweens over `QUICK` and `MOVE`.
-//!
-//! How to use it from a screen (or to add options, e.g. the Simple/Advanced
-//! graphics settings): build a [`Ui`] over the frame's `HudBatch` with
-//! [`Ui::new`], lay out in dp (the launcher's logical pixels) with the widgets below, and give every interactive widget a stable
+//! Build a [`Ui`] over the frame's `HudBatch` with [`Ui::new`], lay out in dp
+//! (the launcher's logical pixels) and give every interactive widget a stable
//! `id`. Clicks run the same layout with [`Ui::dry`] and read [`Ui::hit`]: one
-//! function draws and hit-tests, so they never disagree. The options screen
-//! (`options_ui::OptionsUi::draw_horizon`) lists its sections in
-//! `options_ui::HORIZON_SECTIONS`; a section is a title, a short blurb and its
-//! rows (`HRow`), so new settings only need rows.
+//! function draws and hit-tests, so they never disagree.
use crate::hud::{HudAtlas, HudBatch, Rect};
use ab_glyph::{Font as _, FontRef, PxScale, ScaleFont as _};
-use std::{cell::RefCell, collections::HashMap, path::Path, sync::atomic::Ordering, time::Instant};
+use std::{cell::RefCell, collections::HashMap, path::Path};
-/// Which drawing the front-end screens use.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum MenuStyle {
- Horizon,
- /// Vanilla's screens, exactly as the parity harnesses expect them.
- Classic,
-}
-/// 1 for Classic. Unit tests run in parallel threads and switch the style to
-/// lay out a page in it (#802), so under test each thread keeps its own.
-#[cfg(not(test))]
-static STYLE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(1);
-#[cfg(test)]
-thread_local! {
- static STYLE: std::cell::Cell = const { std::cell::Cell::new(1) };
-}
-pub fn style() -> MenuStyle {
- #[cfg(not(test))]
- let flag = STYLE.load(Ordering::Relaxed);
- #[cfg(test)]
- let flag = STYLE.with(std::cell::Cell::get);
- if flag == 1 {
- MenuStyle::Classic
- } else {
- MenuStyle::Horizon
- }
-}
-pub fn horizon() -> bool {
- style() == MenuStyle::Horizon
-}
-pub fn set_style(s: MenuStyle) {
- let flag = u8::from(s == MenuStyle::Classic);
- #[cfg(not(test))]
- STYLE.store(flag, Ordering::Relaxed);
- #[cfg(test)]
- STYLE.with(|style| style.set(flag));
-}
-/// Horizon-only preferences live in `horizon.txt` beside `options.txt`, so
-/// vanilla's options file stays exactly as vanilla writes it.
-pub fn load_preferences(dir: &Path) {
- let saved = preference(dir, "menuStyle");
- // HORIZON_MENU_STYLE=classic forces vanilla's screens (tests, harnesses).
- let forced = std::env::var("HORIZON_MENU_STYLE").ok();
- set_style(preferred_style(saved.as_deref(), forced.as_deref()));
-}
-fn preferred_style(saved: Option<&str>, forced: Option<&str>) -> MenuStyle {
- match forced {
- Some("classic") => MenuStyle::Classic,
- Some("horizon") => MenuStyle::Horizon,
- _ if saved == Some("horizon") => MenuStyle::Horizon,
- _ => MenuStyle::Classic,
- }
-}
-pub fn save_preferences(dir: &Path) {
- let value = match style() {
- MenuStyle::Horizon => "horizon",
- MenuStyle::Classic => "classic",
- };
- set_preference(dir, "menuStyle", Some(value));
-}
-/// A Horizon-only preference from `horizon.txt` (`key:value` lines).
+/// A Horizon-only preference from `horizon.txt` beside `options.txt`
+/// (`key:value` lines), so vanilla's options file stays exactly as vanilla
+/// writes it.
pub fn preference(dir: &Path, key: &str) -> Option {
let text = std::fs::read_to_string(dir.join("horizon.txt")).ok()?;
text.lines().find_map(|l| {
@@ -93,7 +24,7 @@ pub fn preference(dir: &Path, key: &str) -> Option {
})
}
/// Set (or with None remove) one preference, keeping the others.
-pub fn set_preference(dir: &Path, key: &str, value: Option<&str>) {
+pub(crate) fn set_preference(dir: &Path, key: &str, value: Option<&str>) {
let text = std::fs::read_to_string(dir.join("horizon.txt")).unwrap_or_default();
let mut lines: Vec = text
.lines()
@@ -109,9 +40,8 @@ pub fn set_preference(dir: &Path, key: &str, value: Option<&str>) {
}
/// The dark palette (`horizon_theme::DARK`) in the HUD's colour encoding, plus the
-/// translucent surfaces the menus put over the backdrop.
-pub mod color {
- use crate::hud::rgba;
+/// translucent plates the overlays draw over the game.
+pub(crate) mod color {
use horizon_theme::DARK as P;
pub const fn hex(c: u32, a: u8) -> u32 {
(a as u32) << 24 | (c & 0xff) << 16 | (c >> 8 & 0xff) << 8 | (c >> 16 & 0xff)
@@ -130,95 +60,36 @@ pub mod color {
pub const TEXT: u32 = hex(P.ink, 255);
/// Values and secondary text (`ink_soft`).
pub const MUTED: u32 = hex(P.ink_soft, 255);
- /// Labels, indices, descriptions over the veiled backdrop
- /// (`horizon_theme::BACKDROP_MUTED`, which holds AA there).
- pub const FAINT: u32 = hex(horizon_theme::BACKDROP_MUTED, 255);
pub const ACCENT: u32 = hex(P.accent, 255);
pub const ON_ACCENT: u32 = hex(P.on_accent, 255);
- pub const DANGER: u32 = hex(P.danger, 255);
- pub const SUCCESS: u32 = hex(P.success, 255);
- pub const WHITE: u32 = hex(0xffffff, 255);
- pub fn with_alpha(c: u32, a: f32) -> u32 {
+ pub(crate) fn with_alpha(c: u32, a: f32) -> u32 {
let base = (c >> 24) as f32;
(c & 0x00ff_ffff) | ((base * a.clamp(0.0, 1.0)).round() as u32) << 24
}
- /// Linear blend of two colours (with alpha).
- pub fn mix(a: u32, b: u32, t: f32) -> u32 {
- let t = t.clamp(0.0, 1.0);
- let ch = |c: u32, s: u32| ((c >> s) & 255) as f32;
- let m = |s: u32| (ch(a, s) + (ch(b, s) - ch(a, s)) * t).round() as u8;
- rgba(m(0), m(8), m(16), m(24))
- }
}
/// The launcher's type scale and shapes (`horizon_theme`), in dp.
-pub use horizon_theme::{CONTROL, CONTROL_LARGE, SEGMENT, ease_out_cubic, ease_out_quint};
-/// The type scale in dp: indices (mono), captions, labels and buttons, body,
-/// the large button, section heads, list names, page titles, the opening.
-pub const MICRO: f32 = horizon_theme::MICRO.px;
-pub const SMALL: f32 = horizon_theme::CAPTION.px;
-pub const BODY: f32 = horizon_theme::LABEL.px;
-pub const LARGE: f32 = horizon_theme::UI.px;
-pub const HEADING: f32 = horizon_theme::HEADING.px;
-pub const TITLE: f32 = horizon_theme::TITLE.px;
-pub const HERO: f32 = horizon_theme::DISPLAY.px;
-pub const WORDMARK: f32 = 96.;
+pub(crate) const SMALL: f32 = horizon_theme::CAPTION.px;
+pub(crate) const BODY: f32 = horizon_theme::LABEL.px;
/// Fields; plates (hover rows, selection); pills (buttons, segments).
-pub const RADIUS: f32 = horizon_theme::RADIUS;
-pub const RADIUS_PLATE: f32 = horizon_theme::RADIUS_PLATE;
-pub const PILL: f32 = horizon_theme::RADIUS_PILL;
-/// The index column of a numbered row, and the label column after it.
-pub const INDEX: f32 = horizon_theme::INDEX;
-pub const ROW_LABEL: f32 = 150.;
-pub const SIDEBAR: f32 = 200.;
-/// Motion durations in seconds (`horizon_theme::QUICK` and `MOVE`).
-pub fn quick() -> f32 {
- horizon_theme::QUICK.secs()
-}
-pub fn move_() -> f32 {
- horizon_theme::MOVE.secs()
-}
-/// How visible the live title backdrop is (0..1), set by the game each frame.
-static BACKDROP: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
-pub fn set_backdrop(fade: f32) {
- BACKDROP.store(fade.to_bits(), Ordering::Relaxed);
-}
-pub fn backdrop() -> f32 {
- f32::from_bits(BACKDROP.load(Ordering::Relaxed))
-}
-/// The window size of the last drawn frame, for hit-testing passes.
-static WINDOW: std::sync::Mutex<[u32; 2]> = std::sync::Mutex::new([1280, 800]);
-/// An empty batch at the last frame's window size (for [`Ui::dry`]).
-pub fn scratch_batch() -> HudBatch {
- HudBatch::new(*WINDOW.lock().unwrap_or_else(|e| e.into_inner()))
-}
-/// Whether the left mouse button is held (the primary button's press state).
-static PRESSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
-pub fn set_pressed(down: bool) {
- PRESSED.store(down, Ordering::Relaxed);
-}
+pub(crate) const RADIUS: f32 = horizon_theme::RADIUS;
+pub(crate) const RADIUS_PLATE: f32 = horizon_theme::RADIUS_PLATE;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-pub enum Face {
- Display,
+pub(crate) enum Face {
Regular,
Medium,
- Semibold,
- Mono,
}
struct Fonts {
- faces: [FontRef<'static>; 5],
+ faces: [FontRef<'static>; 2],
}
impl Fonts {
fn load() -> Self {
let f = |b: &'static [u8]| FontRef::try_from_slice(b).expect("bundled font");
Self {
faces: [
- f(horizon_theme::fonts::GEIST_MEDIUM),
f(horizon_theme::fonts::GEIST_REGULAR),
f(horizon_theme::fonts::GEIST_MEDIUM),
- f(horizon_theme::fonts::GEIST_SEMIBOLD),
- f(horizon_theme::fonts::GEIST_MONO),
],
}
}
@@ -246,23 +117,6 @@ struct Cached {
top: f32,
}
/// Glyphs and corner masks rasterized into the atlas region `horizon/ui-text`.
-#[derive(Clone, Copy)]
-struct Tween {
- from: f32,
- to: f32,
- start: Instant,
- secs: f32,
-}
-impl Tween {
- fn value(&self) -> f32 {
- let t = if self.secs <= 0.0 {
- 1.0
- } else {
- self.start.elapsed().as_secs_f32() / self.secs
- };
- self.from + (self.to - self.from) * ease_out_quint(t)
- }
-}
struct Cache {
fonts: Fonts,
entries: HashMap,
@@ -270,10 +124,6 @@ struct Cache {
pending: Vec,
/// The atlas the entries were uploaded to (a new atlas starts over).
atlas: usize,
- last_frame: Option,
- /// Tweens by widget id: from, to, start, duration (hover, selection, pages).
- anims: HashMap,
- dt: f32,
}
thread_local! {
static CACHE: RefCell> = const { RefCell::new(None) };
@@ -292,9 +142,6 @@ fn with_cache(atlas: &HudAtlas, f: impl FnOnce(&mut Cache) -> R) -> R {
shelf: (0, 0, 0),
pending: Vec::new(),
atlas: id,
- last_frame: None,
- anims: HashMap::new(),
- dt: 0.0,
});
if cache.atlas != id {
cache.atlas = id;
@@ -432,24 +279,7 @@ impl Cache {
}
}
-/// The launcher's button kinds.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum Kind {
- /// The accent, for the one thing the screen is for.
- Primary,
- /// Raised with a 1px border.
- Secondary,
- /// Muted text until hovered.
- Ghost,
- /// Ghost in the danger colour (leave, delete).
- Danger,
-}
-#[derive(Clone, Copy, Debug)]
-pub struct Hit {
- pub rect: [f32; 4],
- pub id: u64,
-}
-/// One frame (or one hit test) of Horizon-style drawing, in dp: the
+/// One frame of design-system drawing, in dp: the
/// launcher's logical pixels, scaled so the screen reads like the launcher's
/// 1040x700 window at any size.
pub struct Ui<'a> {
@@ -463,22 +293,6 @@ pub struct Ui<'a> {
/// Physical pixels per dp.
pub density: f32,
scale: f32,
- /// Interactive rectangles in drawing order (the last one is on top).
- pub hits: Vec,
- real: bool,
- /// Multiplies every colour's alpha (screen fades).
- pub opacity: f32,
- /// Added to every x / y drawn (screen slides).
- pub offset: (f32, f32),
- /// The number the next settings row shows (`01`, `02`…); `page_header`
- /// starts it again.
- pub row_index: usize,
- /// The caption of the settings row drawn last: the control socket's
- /// label for the switch, slider or segments drawn on it.
- row_label: String,
- /// Secondary text (indices, inactive items, captions): `FAINT`, or `MUTED` over the home
- /// page's lighter veil (`horizon_theme::HOME_VEIL`).
- pub muted: u32,
}
impl<'a> Ui<'a> {
/// `cursor` is in GUI pixels, like every screen's input.
@@ -486,16 +300,6 @@ impl<'a> Ui<'a> {
let scale = batch.scale;
let (pw, ph) = (batch.width * scale, batch.height * scale);
let density = (pw / 1040.0).min(ph / 700.0).clamp(1.0, 4.0);
- if let Ok(mut w) = WINDOW.lock() {
- *w = [pw.round() as u32, ph.round() as u32];
- }
- with_cache(atlas, |c| {
- let now = Instant::now();
- c.dt = c
- .last_frame
- .map_or(0.0, |t| now.duration_since(t).as_secs_f32().min(0.1));
- c.last_frame = Some(now);
- });
Self {
atlas,
w: pw / density,
@@ -504,155 +308,20 @@ impl<'a> Ui<'a> {
density,
scale,
batch,
- hits: Vec::new(),
- real: true,
- opacity: 1.0,
- offset: (0.0, 0.0),
- row_index: 0,
- row_label: String::new(),
- muted: color::FAINT,
}
}
- /// A layout pass for hit testing: nothing is drawn and no tween starts.
- pub fn dry(atlas: &'a HudAtlas, batch: &'a mut HudBatch, cursor: (f32, f32)) -> Self {
- let mut ui = Self::new(atlas, batch, cursor);
- ui.real = false;
- ui
- }
- /// A drawn frame, not a hit-testing pass.
- pub fn is_real(&self) -> bool {
- self.real
- }
/// Move rasterized glyphs into the batch's atlas uploads (real frames only).
pub fn finish(self) {
- if self.real {
- let pending = with_cache(self.atlas, |c| std::mem::take(&mut c.pending));
- self.batch.patches.extend(pending);
- }
- }
- /// The topmost interactive id under a point in GUI pixels.
- pub fn hit(&self, gui: (f32, f32)) -> Option {
- let (x, y) = (
- gui.0 * self.scale / self.density,
- gui.1 * self.scale / self.density,
- );
- self.hits
- .iter()
- .rev()
- .find(|h| x >= h.rect[0] && y >= h.rect[1] && x < h.rect[2] && y < h.rect[3])
- .map(|h| h.id)
- }
- /// A tween towards `target` over `secs` with the launcher's
- /// `ease_out_quint`; a new target restarts it from the current value.
- pub fn tween(&self, id: u64, target: f32, secs: f32) -> f32 {
- let real = self.real;
- with_cache(self.atlas, |c| {
- let now = Instant::now();
- match c.anims.get(&id).copied() {
- Some(t) if t.to == target => t.value(),
- Some(t) if real => {
- let v = t.value();
- c.anims.insert(
- id,
- Tween {
- from: v,
- to: target,
- start: now,
- secs,
- },
- );
- v
- }
- Some(t) => t.value(),
- None => {
- if real {
- c.anims.insert(
- id,
- Tween {
- from: target,
- to: target,
- start: now,
- secs,
- },
- );
- }
- target
- }
- }
- })
- }
- /// Start a tween from `from` (an entrance).
- pub fn restart(&self, id: u64, from: f32, to: f32, secs: f32) {
- with_cache(self.atlas, |c| {
- c.anims.insert(
- id,
- Tween {
- from,
- to,
- start: Instant::now(),
- secs,
- },
- );
- });
- }
- pub fn inside(&self, x: f32, y: f32, w: f32, h: f32) -> bool {
- let (cx, cy) = (self.cursor.0 - self.offset.0, self.cursor.1 - self.offset.1);
- cx >= x && cy >= y && cx < x + w && cy < y + h
- }
- /// Register an interactive rectangle; returns its hover layer (0..1,
- /// eased over `QUICK` like the launcher's `hover_layer`).
- pub fn interact(&mut self, id: u64, x: f32, y: f32, w: f32, h: f32, enabled: bool) -> f32 {
- self.interact_as(id, [x, y, w, h], enabled, crate::widgets::Kind::Button)
- }
- /// [`Ui::interact`] for a controller focus target of a given kind.
- pub fn interact_as(
- &mut self,
- id: u64,
- [x, y, w, h]: [f32; 4],
- enabled: bool,
- kind: crate::widgets::Kind,
- ) -> f32 {
- if enabled && self.real {
- // Where a controller can move focus, in GUI pixels.
- let k = self.density / self.scale;
- let (ox, oy) = self.offset;
- let kind = match kind {
- crate::widgets::Kind::Slider { value, track } => crate::widgets::Kind::Slider {
- value,
- track: [(track[0] + ox) * k, track[1] * k],
- },
- other => other,
- };
- crate::widgets::target_as([(x + ox) * k, (y + oy) * k, w * k, h * k], kind);
- }
- if enabled {
- let (ox, oy) = self.offset;
- self.hits.push(Hit {
- rect: [x + ox, y + oy, x + ox + w, y + oy + h],
- id,
- });
- }
- let over = enabled && self.inside(x, y, w, h);
- self.tween(id, if over { 1.0 } else { 0.0 }, quick())
- }
- /// Whether the pointer is down on this rectangle (a press).
- pub fn pressed(&self, x: f32, y: f32, w: f32, h: f32) -> bool {
- PRESSED.load(Ordering::Relaxed) && self.inside(x, y, w, h)
+ let pending = with_cache(self.atlas, |c| std::mem::take(&mut c.pending));
+ self.batch.patches.extend(pending);
}
// ---- geometry, snapped to physical pixels ----
fn px_x(&self, v: f32) -> f32 {
- ((v + self.offset.0) * self.density).round()
+ (v * self.density).round()
}
fn px_y(&self, v: f32) -> f32 {
- ((v + self.offset.1) * self.density).round()
- }
- fn tint(&self, c: u32) -> u32 {
- if self.opacity >= 1.0 {
- c
- } else {
- color::with_alpha(c, self.opacity)
- }
+ (v * self.density).round()
}
fn raw_fill(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, color: u32) {
if x1 > x0 && y1 > y0 {
@@ -667,66 +336,6 @@ impl<'a> Ui<'a> {
);
}
}
- pub fn fill(&mut self, x: f32, y: f32, w: f32, h: f32, color: u32) {
- let color = self.tint(color);
- if !self.real || color >> 24 == 0 {
- return;
- }
- let (x0, y0, x1, y1) = (
- self.px_x(x),
- self.px_y(y),
- self.px_x(x + w),
- self.px_y(y + h),
- );
- self.raw_fill(x0, y0, x1, y1, color);
- }
- /// A vertical gradient (top colour to bottom colour).
- pub fn gradient(&mut self, x: f32, y: f32, w: f32, h: f32, top: u32, bottom: u32) {
- self.gradient4(x, y, w, h, [top, top, bottom, bottom]);
- }
- /// A horizontal gradient (left colour to right colour).
- pub fn hgradient(&mut self, x: f32, y: f32, w: f32, h: f32, left: u32, right: u32) {
- self.gradient4(x, y, w, h, [left, right, right, left]);
- }
- /// Corner colours: top-left, top-right, bottom-right, bottom-left.
- pub fn gradient4(&mut self, x: f32, y: f32, w: f32, h: f32, c: [u32; 4]) {
- if !self.real {
- return;
- }
- let c = c.map(|c| self.tint(c));
- let white = self.atlas.sprites["horizon/white"];
- let (cu, cv) = ((white.u0 + white.u1) / 2.0, (white.v0 + white.v1) / 2.0);
- let s = self.scale;
- let (x0, y0) = (self.px_x(x) / s, self.px_y(y) / s);
- let (x1, y1) = (self.px_x(x + w) / s, self.px_y(y + h) / s);
- let p = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
- for i in [0, 1, 2, 0, 2, 3] {
- self.batch.vertices.push(crate::hud::HudVertex {
- pos: p[i],
- uv: [cu, cv],
- color: c[i],
- depth: 0.0,
- });
- }
- }
- /// The launcher's 1px divider (`border` colour).
- pub fn divider(&mut self, x: f32, y: f32, w: f32) {
- let c = self.tint(color::BORDER);
- if !self.real {
- return;
- }
- let (x0, y0, x1) = (self.px_x(x), self.px_y(y), self.px_x(x + w));
- self.raw_fill(x0, y0, x1, y0 + 1.0, c);
- }
- /// A 1px vertical line.
- pub fn vline(&mut self, x: f32, y: f32, h: f32, color: u32) {
- let c = self.tint(color);
- if !self.real {
- return;
- }
- let (x0, y0, y1) = (self.px_x(x), self.px_y(y), self.px_y(y + h));
- self.raw_fill(x0, y0, x0 + 1.0, y1, c);
- }
fn corner_quad(&mut self, rect: Rect, x: f32, y: f32, r: f32, flip: (bool, bool), color: u32) {
let (u0, u1) = if flip.0 {
(rect.u1, rect.u0)
@@ -759,9 +368,8 @@ impl<'a> Ui<'a> {
}
}
/// A filled rectangle with rounded corners.
- pub fn rounded(&mut self, x: f32, y: f32, w: f32, h: f32, radius: f32, color: u32) {
- let color = self.tint(color);
- if !self.real || color >> 24 == 0 {
+ pub(crate) fn rounded(&mut self, x: f32, y: f32, w: f32, h: f32, radius: f32, color: u32) {
+ if color >> 24 == 0 {
return;
}
let (x0, y0, x1, y1) = (
@@ -785,9 +393,8 @@ impl<'a> Ui<'a> {
self.corners(x0, y0, x1, y1, r, false, color);
}
/// A 1px rounded border.
- pub fn border(&mut self, x: f32, y: f32, w: f32, h: f32, radius: f32, color: u32) {
- let color = self.tint(color);
- if !self.real || color >> 24 == 0 {
+ pub(crate) fn border(&mut self, x: f32, y: f32, w: f32, h: f32, radius: f32, color: u32) {
+ if color >> 24 == 0 {
return;
}
let (x0, y0, x1, y1) = (
@@ -810,7 +417,7 @@ impl<'a> Ui<'a> {
// ---- text ----
/// The advance of `text` in dp.
- pub fn measure(&self, face: Face, size: f32, text: &str) -> f32 {
+ pub(crate) fn measure(&self, face: Face, size: f32, text: &str) -> f32 {
let px = (size * self.density * 4.0).round() / 4.0;
with_cache(self.atlas, |c| {
let font = c.fonts.face(face);
@@ -831,7 +438,7 @@ impl<'a> Ui<'a> {
/// Draw a line of text in a `line`-tall box whose top is `y` (the
/// launcher's line heights: about 1.45 × size for the interface);
/// returns its width in dp.
- pub fn text_line(
+ pub(crate) fn text_line(
&mut self,
face: Face,
size: f32,
@@ -841,9 +448,8 @@ impl<'a> Ui<'a> {
color: u32,
text: &str,
) -> f32 {
- let color = self.tint(color);
let px = (size * self.density * 4.0).round() / 4.0;
- let real = self.real && color >> 24 != 0;
+ let real = color >> 24 != 0;
let (x0, y0) = (self.px_x(x), self.px_y(y));
let box_px = line * self.density;
let atlas = self.atlas;
@@ -891,10 +497,18 @@ impl<'a> Ui<'a> {
width
}
/// Text in a `1.45 × size` line box whose top is `y`.
- pub fn text(&mut self, face: Face, size: f32, x: f32, y: f32, color: u32, text: &str) -> f32 {
+ pub(crate) fn text(
+ &mut self,
+ face: Face,
+ size: f32,
+ x: f32,
+ y: f32,
+ color: u32,
+ text: &str,
+ ) -> f32 {
self.text_line(face, size, (size * 1.45).round(), x, y, color, text)
}
- pub fn text_centered(
+ pub(crate) fn text_centered(
&mut self,
face: Face,
size: f32,
@@ -906,569 +520,14 @@ impl<'a> Ui<'a> {
let w = self.measure(face, size, text);
self.text(face, size, cx - w / 2.0, y, color, text);
}
- pub fn text_right(
- &mut self,
- face: Face,
- size: f32,
- right: f32,
- y: f32,
- color: u32,
- text: &str,
- ) {
- let w = self.measure(face, size, text);
- self.text(face, size, right - w, y, color, text);
- }
- /// `text` shortened with an ellipsis to fit `max` dp.
- pub fn fit(&self, face: Face, size: f32, text: &str, max: f32) -> String {
- if self.measure(face, size, text) <= max {
- return text.to_owned();
- }
- let mut s: String = text.to_owned();
- while !s.is_empty() && self.measure(face, size, &format!("{s}…")) > max {
- s.pop();
- }
- format!("{}…", s.trim_end())
- }
// ---- the launcher's components ----
- /// The launcher's `page_header`: a display title and a muted line.
- /// Returns the height used, and numbers the rows below from 01.
- pub fn page_header(&mut self, x: f32, y: f32, title: &str, description: &str) -> f32 {
- self.row_index = 0;
- let line = (HERO * 1.1).round();
- self.text_line(Face::Display, HERO, line, x, y, color::TEXT, title);
- self.text(
- Face::Regular,
- LARGE,
- x,
- y + line + 10.0,
- color::FAINT,
- description,
- );
- line + 10.0 + (LARGE * 1.5).round()
- }
- /// Mono capitals: the status above a title, section labels, footnotes.
- pub fn caps(&mut self, x: f32, y: f32, color: u32, text: &str) -> f32 {
- self.text(Face::Mono, MICRO, x, y, color, &text.to_uppercase())
- }
- /// Horizon's mark at `size` dp: two stems, their reflection at a third,
- /// the horizon across in the accent.
- pub fn mark(&mut self, x: f32, y: f32, size: f32) {
- let u = size / 16.0;
- for sx in [4.0, 10.0] {
- self.fill(x + sx * u, y + 3.0 * u, 2.0 * u, 4.0 * u, color::TEXT);
- self.fill(
- x + sx * u,
- y + 8.0 * u,
- 2.0 * u,
- 4.0 * u,
- color::with_alpha(color::TEXT, 0.36),
- );
- }
- self.fill(x + u, y + 7.0 * u, 14.0 * u, u, color::ACCENT);
- }
- /// The sidebar's frame, shared by the title, options and pause screens:
- /// no panel, only the mark and a name at the top, as the launcher's bar.
- pub fn sidebar_frame(&mut self, title: &str) {
- self.mark(22.0, 26.0, 18.0);
- self.text_line(Face::Medium, BODY, 18.0, 48.0, 26.0, color::TEXT, title);
- }
- /// A widget's label for the control socket (`click-button`, `ui`), in GUI pixels.
- fn record_label(
- &self,
- label: &str,
- [x, y, w, h]: [f32; 4],
- enabled: bool,
- kind: crate::widgets::Kind,
- ) {
- if self.real {
- let k = self.density / self.scale;
- let (ox, oy) = self.offset;
- crate::widgets::record_as(
- label,
- [(x + ox) * k, (y + oy) * k, w * k, h * k],
- enabled,
- kind,
- );
- }
- }
- /// The launcher's `button`: a pill 32 tall (or `CONTROL_LARGE` with
- /// `LARGE` text), medium weight, a hover layer easing in over `QUICK`,
- /// and the press state. Returns the hover.
- pub fn button(
- &mut self,
- id: u64,
- [x, y, w, h]: [f32; 4],
- label: &str,
- kind: Kind,
- enabled: bool,
- ) -> f32 {
- self.record_label(label, [x, y, w, h], enabled, crate::widgets::Kind::Button);
- let hover = self.interact(id, x, y, w, h, enabled);
- let saved = self.opacity;
- if !enabled {
- self.opacity *= horizon_theme::DISABLED;
- } else if self.pressed(x, y, w, h) {
- self.opacity *= horizon_theme::PRESSED;
- }
- let fg = match kind {
- Kind::Primary => {
- self.rounded(x, y, w, h, PILL, color::ACCENT);
- self.rounded(
- x,
- y,
- w,
- h,
- PILL,
- color::with_alpha(color::WHITE, 0.12 * hover),
- );
- color::ON_ACCENT
- }
- Kind::Secondary => {
- self.rounded(x, y, w, h, PILL, color::RAISED);
- self.rounded(x, y, w, h, PILL, color::with_alpha(color::HOVER, hover));
- color::TEXT
- }
- Kind::Ghost => {
- self.rounded(x, y, w, h, PILL, color::with_alpha(color::RAISED, hover));
- color::mix(self.muted, color::TEXT, hover)
- }
- Kind::Danger => {
- self.rounded(x, y, w, h, PILL, color::with_alpha(color::RAISED, hover));
- color::DANGER
- }
- };
- let size = if h >= CONTROL_LARGE { LARGE } else { BODY };
- let label = self.fit(Face::Medium, size, label, w - 16.0);
- let lw = self.measure(Face::Medium, size, &label);
- self.text_line(
- Face::Medium,
- size,
- h,
- x + ((w - lw) / 2.0).round(),
- y,
- fg,
- &label,
- );
- self.opacity = saved;
- hover
- }
- /// A search field styled like the launcher's rounded text inputs.
- pub fn text_field(&mut self, id: u64, rect: [f32; 4], value: &str, focused: bool) {
- let [x, y, w, h] = rect;
- self.record_label(value, rect, true, crate::widgets::Kind::Button);
- let hover = self.interact(id, x, y, w, h, true);
- self.rounded(
- x,
- y,
- w,
- h,
- 8.0,
- if focused { color::HOVER } else { color::RAISED },
- );
- self.rounded(
- x,
- y,
- w,
- h,
- 8.0,
- color::with_alpha(color::HOVER, hover * 0.5),
- );
- let display = if value.is_empty() {
- "Search settings".to_owned()
- } else if focused {
- format!("{value}|")
- } else {
- value.to_owned()
- };
- let display = self.fit(Face::Regular, BODY, &display, w - 24.0);
- self.text_line(
- Face::Regular,
- BODY,
- h,
- x + 12.0,
- y,
- if value.is_empty() {
- color::FAINT
- } else {
- color::TEXT
- },
- &display,
- );
- }
- /// The width the launcher's button gives a label (padding 16, or 24 large).
- pub fn button_width(&self, label: &str, large: bool) -> f32 {
- let (size, pad) = if large { (LARGE, 24.0) } else { (BODY, 16.0) };
- (self.measure(Face::Medium, size, label) + pad * 2.0).ceil()
- }
- /// The launcher's navigation as a sidebar: text items 32 tall and 2 apart,
- /// a soft pill that slides to the selected item over `MOVE`, hover layers
- /// on the others. Items are ids `base + index`.
- pub fn sidebar_list(
- &mut self,
- base: u64,
- x: f32,
- y: f32,
- w: f32,
- labels: &[&str],
- selected: usize,
- ) {
- const STEP: f32 = 34.0;
- let pill = self.tween(base ^ 0x9111, selected as f32, move_());
- let py = y + pill * STEP;
- self.rounded(x, py, w, CONTROL, PILL, color::RAISED);
- for (i, label) in labels.iter().enumerate() {
- let iy = y + i as f32 * STEP;
- let active = i == selected;
- self.record_label(
- label,
- [x, iy, w, CONTROL],
- true,
- crate::widgets::Kind::Tab(active),
- );
- let hover = self.interact_as(
- base + i as u64,
- [x, iy, w, CONTROL],
- true,
- crate::widgets::Kind::Tab(active),
- );
- if !active {
- self.rounded(
- x,
- iy,
- w,
- CONTROL,
- PILL,
- color::with_alpha(color::RAISED, 0.8 * hover),
- );
- }
- let (face, fg) = if active {
- (Face::Medium, color::TEXT)
- } else {
- (Face::Regular, color::mix(self.muted, color::TEXT, hover))
- };
- self.text_line(face, BODY, CONTROL, x + 12.0, iy, fg, label);
- }
- }
- /// The launcher's segmented control: a soft pill track (padding 2)
- /// holding 28-tall segments; the selected one is an ink pill with
- /// page-coloured text. Segments are ids `base + index`. Returns the
- /// control's width.
- pub fn segmented(
- &mut self,
- base: u64,
- x: f32,
- y: f32,
- labels: &[&str],
- selected: usize,
- ) -> f32 {
- let widths: Vec = labels
- .iter()
- .map(|l| (self.measure(Face::Medium, BODY, l) + 28.0).ceil())
- .collect();
- let total = widths.iter().sum::() + 2.0 * (labels.len() as f32 - 1.0) + 4.0;
- let h = SEGMENT + 4.0;
- self.rounded(x, y, total, h, PILL, color::RAISED);
- let mut sx = x + 2.0;
- for (i, (label, sw)) in labels.iter().zip(&widths).enumerate() {
- let active = i == selected;
- let name = format!("{} {label}", self.row_label);
- self.record_label(
- &name,
- [sx, y + 2.0, *sw, SEGMENT],
- true,
- crate::widgets::Kind::Tab(active),
- );
- let hover = self.interact(base + i as u64, sx, y + 2.0, *sw, SEGMENT, true);
- if active {
- self.rounded(sx, y + 2.0, *sw, SEGMENT, PILL, color::TEXT);
- }
- let fg = if active {
- color::BG
- } else {
- color::mix(self.muted, color::TEXT, hover)
- };
- let lw = self.measure(Face::Medium, BODY, label);
- self.text_line(
- Face::Medium,
- BODY,
- SEGMENT,
- sx + ((sw - lw) / 2.0).round(),
- y + 2.0,
- fg,
- label,
- );
- sx += sw + 2.0;
- }
- total
- }
- /// The launcher's `switch`: 36x20, accent when on, the plate colour when
- /// off, a white 16px knob sliding over `MOVE`. Right-aligned at `right`.
- pub fn switch(&mut self, id: u64, right: f32, cy: f32, on: bool) {
- let (w, h) = (36.0, 20.0);
- let (x, y) = (right - w, (cy - h / 2.0).round());
- let rect = [x - 4.0, y - 4.0, w + 8.0, h + 8.0];
- if !self.row_label.is_empty() {
- let label = format!("{}: {}", self.row_label, if on { "on" } else { "off" });
- self.record_label(&label, rect, true, crate::widgets::Kind::Button);
- }
- self.interact_as(id, rect, true, crate::widgets::Kind::Button);
- let t = self.tween(id ^ 0x5717c4, if on { 1.0 } else { 0.0 }, move_());
- self.rounded(
- x,
- y,
- w,
- h,
- h / 2.0,
- color::mix(color::HOVER, color::ACCENT, t),
- );
- self.rounded(x + 2.0 + 16.0 * t, y + 2.0, 16.0, 16.0, 8.0, color::WHITE);
- }
- /// The next row's number, in mono, in the index column at `x`.
- fn index(&mut self, x: f32, y: f32) {
- self.row_index += 1;
- let n = format!("{:02}", self.row_index);
- let muted = self.muted;
- self.text(Face::Mono, MICRO, x, y + 2.0, muted, &n);
- }
- /// The launcher's settings `row`: its number, a label column, then the
- /// value; py 12. Returns the row height (draw the action yourself,
- /// right-aligned, and a `divider` under it). `value_w` is measured from
- /// the value column as before the numbers came; the index takes its
- /// share from it.
- pub fn row(&mut self, x: f32, y: f32, label: &str, value: &str, value_w: f32) -> f32 {
- self.row_label = label.to_owned();
- let line = (BODY * 1.45).round();
- let h = 12.0 + line.max(CONTROL) + 12.0;
- let ty = y + (h - line) / 2.0;
- self.index(x, ty);
- self.text(Face::Regular, BODY, x + INDEX, ty, color::TEXT, label);
- let value = self.fit(Face::Regular, BODY, value, (value_w - INDEX).max(0.0));
- self.text(
- Face::Regular,
- BODY,
- x + INDEX + ROW_LABEL + 16.0,
- ty,
- color::MUTED,
- &value,
- );
- h
- }
- /// A settings row with, under its label, a one-line description led by
- /// the setting's frame-time cost (`cost` 0 none .. 3 high, coloured from
- /// the muted colour to the danger colour; 4 saves time, in the success
- /// colour). Same height as [`Ui::row`].
- #[allow(clippy::too_many_arguments)]
- pub fn described_row(
- &mut self,
- x: f32,
- y: f32,
- label: &str,
- value: &str,
- value_w: f32,
- cost: (u8, &str),
- description: &str,
- description_w: f32,
- ) -> f32 {
- self.row_label = label.to_owned();
- let h = 12.0 + CONTROL + 12.0;
- let top = y + 8.0;
- self.index(x, top);
- let x = x + INDEX;
- self.text(Face::Regular, BODY, x, top, color::TEXT, label);
- let value = self.fit(Face::Regular, BODY, value, (value_w - INDEX).max(0.0));
- self.text(
- Face::Regular,
- BODY,
- x + ROW_LABEL + 16.0,
- top,
- color::MUTED,
- &value,
- );
- let dy = top + (BODY * 1.45).round();
- let cost_color = match cost.0 {
- 4 => color::SUCCESS,
- n => color::mix(
- color::FAINT,
- color::DANGER,
- [0.0, 0.2, 0.55, 1.0][usize::from(n.min(3))],
- ),
- };
- self.text(Face::Medium, SMALL, x, dy, cost_color, cost.1);
- // No cost label: the description starts at the row's edge.
- let used = if cost.1.is_empty() {
- -8.0
- } else {
- self.measure(Face::Medium, SMALL, cost.1)
- };
- let rest = self.fit(
- Face::Regular,
- SMALL,
- description,
- (description_w - INDEX - used - 8.0).max(0.0),
- );
- self.text(
- Face::Regular,
- SMALL,
- x + used + 8.0,
- dy,
- color::FAINT,
- &rest,
- );
- h
- }
- /// A slider in the launcher's language: a 2px track in the rule colour
- /// filled with ink, an ink 14px knob that grows under the pointer.
- /// Dragging is the screen's job (see [`slider_value`]).
- pub fn slider(&mut self, id: u64, x: f32, cy: f32, w: f32, value: f32) {
- let v = value.clamp(0.0, 1.0);
- let kind = crate::widgets::Kind::Slider {
- value: v,
- track: [x, w],
- };
- let rect = [x - 8.0, cy - 12.0, w + 16.0, 24.0];
- let label = self.row_label.clone();
- self.record_label(&label, rect, true, kind);
- let hover = self.interact_as(id, rect, true, kind);
- self.rounded(x, cy - 1.0, w, 2.0, 1.0, color::BORDER);
- self.rounded(x, cy - 1.0, w * v, 2.0, 1.0, color::TEXT);
- let r = 7.0 + hover;
- self.rounded(x + w * v - r, cy - r, r * 2.0, r * 2.0, r, color::TEXT);
- }
- /// A text field: a soft plate with no border; focus draws a 1px accent
- /// ring.
- pub fn field(
- &mut self,
- id: u64,
- [x, y, w, h]: [f32; 4],
- value: &str,
- placeholder: &str,
- focused: bool,
- caret: bool,
- ) {
- let hover = self.interact_as(id, [x, y, w, h], true, crate::widgets::Kind::Field);
- let focus = self.tween(id ^ 0xf0c05ed, if focused { 1.0 } else { 0.0 }, quick());
- self.rounded(x, y, w, h, RADIUS, color::RAISED);
- self.rounded(
- x,
- y,
- w,
- h,
- RADIUS,
- color::with_alpha(color::HOVER, hover * 0.6),
- );
- self.border(x, y, w, h, RADIUS, color::with_alpha(color::ACCENT, focus));
- let shown = self.fit(Face::Regular, BODY, value, w - 28.0);
- let tw = if value.is_empty() {
- self.text_line(
- Face::Regular,
- BODY,
- h,
- x + 14.0,
- y,
- color::FAINT,
- placeholder,
- );
- 0.0
- } else {
- self.text_line(Face::Regular, BODY, h, x + 14.0, y, color::TEXT, &shown)
- };
- if focused && caret {
- self.fill(x + 14.0 + tw + 1.0, y + 9.0, 1.0, h - 18.0, color::TEXT);
- }
- }
- /// The veil over the live backdrop: the page colour, flat, at `veil`.
- /// `shade` fades it in with the opening.
- pub fn atmosphere(&mut self, veil: f32, shade: f32) {
- let (w, h) = (self.w, self.h);
- self.fill(
- 0.0,
- 0.0,
- w,
- h,
- color::with_alpha(color::BG, veil * shade.max(0.0)),
- );
- }
- /// The giant faint wordmark, whole, as wide as the column at `x` (`w` wide, at most `max`
- /// tall) with its baseline at `bottom`.
- pub fn wordmark(&mut self, x: f32, w: f32, bottom: f32, max: f32) {
- let unit = self.measure(Face::Display, 100.0, "horizon") / 100.0;
- let size = (w / unit).min(max).floor();
- // Geist's x-height glyphs sit on the baseline; its ascenders reach 0.75 em above it.
- let line = (size * 1.2).round();
- let top = bottom - line * 0.5 - size * 0.36;
- self.text_line(
- Face::Display,
- size,
- line,
- x - size * 0.05,
- top,
- color::with_alpha(color::TEXT, 0.06),
- "horizon",
- );
- }
- /// The plain background while the live backdrop loads: the page colour.
- pub fn cold_background(&mut self, opacity: f32) {
- let (w, h) = (self.w, self.h);
- self.fill(0.0, 0.0, w, h, color::with_alpha(color::BG, opacity));
- }
-}
-/// The slider value (0..1) for a cursor x in GUI pixels over a track at
-/// `x`..`x + w` in dp.
-pub fn slider_value(ui: &Ui, x: f32, w: f32, cursor_gui: f32) -> f32 {
- let cx = cursor_gui * ui.scale / ui.density - ui.offset.0;
- ((cx - x) / w).clamp(0.0, 1.0)
-}
-/// A stable id for a widget from a name and an index.
-pub const fn id(name: &str, index: u64) -> u64 {
- // FNV-1a.
- let bytes = name.as_bytes();
- let mut h: u64 = 0xcbf2_9ce4_8422_2325;
- let mut i = 0;
- while i < bytes.len() {
- h ^= bytes[i] as u64;
- h = h.wrapping_mul(0x100_0000_01b3);
- i += 1;
- }
- h ^ index.wrapping_mul(0x9e37_79b9_7f4a_7c15)
}
#[cfg(test)]
mod tests {
use super::*;
- #[test]
- fn a_test_switching_the_style_leaves_other_tests_classic() {
- set_style(MenuStyle::Horizon);
- assert_eq!(
- std::thread::spawn(style).join().unwrap(),
- MenuStyle::Classic
- );
- assert_eq!(style(), MenuStyle::Horizon);
- set_style(MenuStyle::Classic);
- }
-
- #[test]
- fn classic_is_the_default_and_explicit_menu_preferences_are_preserved() {
- for saved in [None, Some("classic"), Some("invalid")] {
- assert_eq!(preferred_style(saved, None), MenuStyle::Classic);
- }
- assert_eq!(preferred_style(Some("horizon"), None), MenuStyle::Horizon);
- assert_eq!(preferred_style(None, Some("horizon")), MenuStyle::Horizon);
- assert_eq!(
- preferred_style(Some("classic"), Some("horizon")),
- MenuStyle::Horizon
- );
- assert_eq!(
- preferred_style(Some("horizon"), Some("classic")),
- MenuStyle::Classic
- );
- assert_eq!(
- preferred_style(Some("horizon"), Some("invalid")),
- MenuStyle::Horizon
- );
- }
-
#[test]
fn atlas_reload_regenerates_text_and_corners_at_the_same_address() {
let atlas = HudAtlas::build(Path::new("/nonexistent/horizon-test-assets")).unwrap();
diff --git a/crates/horizon-client/src/widgets.rs b/crates/horizon-client/src/widgets.rs
index 8bd94612d..8bd80d3d1 100644
--- a/crates/horizon-client/src/widgets.rs
+++ b/crates/horizon-client/src/widgets.rs
@@ -1,7 +1,7 @@
//! The labelled widgets and focus targets drawn in the last frame, for the
//! control socket: a script clicks a button by its label (`horizon-ctl
//! click-button Respawn`) or any widget by its id in [`tree`] (`horizon-ctl
-//! click done`), whatever screen or menu style drew it.
+//! click done`), whatever screen drew it.
use std::cell::RefCell;
/// A labelled widget in GUI pixels (the coordinates screens take input in).
@@ -21,7 +21,7 @@ pub struct Widget {
/// navigation").
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Kind {
- /// Clicked with A (buttons, switches, segments, sidebar items).
+ /// Clicked with A (buttons, icon buttons, keys).
Button,
/// Left and right move the value instead of focus; A does nothing (a
/// click would jump the handle to the middle). `value` is 0..1 as drawn;
@@ -53,9 +53,8 @@ impl Target {
thread_local! {
/// Buttons drawn since the last `end_frame`, and the last frame's.
static WIDGETS: RefCell<(Vec, Vec, u64)> = const { RefCell::new((Vec::new(), Vec::new(), 0)) };
- /// Every interactive rectangle (Horizon-style menus' sidebar items,
- /// switches, sliders, segments; classic sliders, fields and list rows),
- /// labelled or not: where a controller can move focus. Drawn since
+ /// Every interactive rectangle (sliders, fields, list rows, the
+ /// on-screen keyboard's keys), labelled or not: where a controller can move focus. Drawn since
/// `end_frame`, the last frame's, and how many frames rotated.
static TARGETS: RefCell<(Vec, Vec, u64)> = const { RefCell::new((Vec::new(), Vec::new(), 0)) };
}
diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs
index e6056e519..03b5d7dc9 100644
--- a/crates/horizon-port-pack/src/carry.rs
+++ b/crates/horizon-port-pack/src/carry.rs
@@ -37,6 +37,10 @@ pub struct Report {
pub worldgen: usize,
/// Recipes left as they were: custom types, NeoForge conditions.
pub recipes_kept: Vec,
+ /// Recipes whose result is one of the mod's own items that isn't declared (its block was
+ /// left out), moved to `outside/`: vanilla refuses a recipe for an unknown item, and the
+ /// game would craft air.
+ pub recipes_unregistered: Vec,
pub item_definitions_added: usize,
/// Templates and properties came from the NeoForge oracle's facts, not
/// from guesses.
@@ -578,6 +582,18 @@ fn extra_namespaces(
claimed
}
+/// The namespaces besides `id` the mod in `jar` would own ([`extra_namespaces`]), for the
+/// pack to find the ones several mods claim.
+pub fn namespaces_claimed(
+ jar: &Path,
+ id: &str,
+ pack_mod: &dyn Fn(&str) -> bool,
+) -> Result, String> {
+ let file = fs::File::open(jar).map_err(|e| format!("{}: {e}", jar.display()))?;
+ let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("{}: {e}", jar.display()))?;
+ Ok(extra_namespaces(&mut zip, id, pack_mod))
+}
+
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
haystack.windows(needle.len()).any(|w| w == needle)
}
@@ -1083,6 +1099,9 @@ pub fn carry(
report.items += 1;
}
}
+ let owned: Vec = owned.iter().map(|n| n.to_string()).collect();
+ let owned: Vec<&str> = owned.iter().map(String::as_str).collect();
+ unregistered_recipes(&inside, &outside, id, &owned, &mut report)?;
let q = |s: &str| toml::Value::String(s.to_owned()).to_string();
let name = if info.name.is_empty() { id } else { &info.name };
let mut manifest = format!(
@@ -1109,6 +1128,88 @@ pub fn carry(
Ok(report)
}
+/// The item a recipe makes: `result.id` (1.21 and later), `result.item` or a bare id.
+fn recipe_result(recipe: &Value) -> Option<&str> {
+ let r = &recipe["result"];
+ r.as_str()
+ .or_else(|| r["id"].as_str())
+ .or_else(|| r["item"].as_str())
+}
+
+/// Moves the recipes whose result is an undeclared item of the mod's own namespaces from
+/// `inside` to `outside` ([`Report::recipes_unregistered`]). The declared items are the blocks
+/// with their item and the items under `data//horizon/`.
+fn unregistered_recipes(
+ inside: &Path,
+ outside: &Path,
+ id: &str,
+ owned: &[&str],
+ report: &mut Report,
+) -> Result<(), String> {
+ let decl = inside.join(format!("data/{id}/horizon"));
+ let mut declared = BTreeSet::new();
+ for kind in ["block", "item"] {
+ for f in fs::read_dir(decl.join(kind))
+ .into_iter()
+ .flatten()
+ .flatten()
+ {
+ let path = f.path();
+ let Some(name) = path.file_stem().and_then(|n| n.to_str()) else {
+ continue;
+ };
+ let has_item = kind == "item"
+ || fs::read(&path)
+ .ok()
+ .and_then(|b| serde_json::from_slice::(&b).ok())
+ .is_none_or(|v| v["item"] != json!(false));
+ if has_item {
+ declared.insert(format!("{id}:{name}"));
+ }
+ }
+ }
+ for ns in owned {
+ let dir = inside.join(format!("data/{ns}/recipe"));
+ let mut stack = vec![dir.clone()];
+ while let Some(d) = stack.pop() {
+ for f in fs::read_dir(&d).into_iter().flatten().flatten() {
+ let path = f.path();
+ if path.is_dir() {
+ stack.push(path);
+ continue;
+ }
+ let Some(recipe) = fs::read(&path)
+ .ok()
+ .and_then(|b| serde_json::from_slice::(&b).ok())
+ else {
+ continue;
+ };
+ let Some(result) = recipe_result(&recipe) else {
+ continue;
+ };
+ let unknown = result
+ .split_once(':')
+ .is_some_and(|(n, _)| owned.contains(&n) && !declared.contains(result));
+ if !unknown {
+ continue;
+ }
+ let rel = path.strip_prefix(inside).map_err(|e| e.to_string())?;
+ let to = outside.join(rel);
+ if let Some(parent) = to.parent() {
+ fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
+ }
+ fs::rename(&path, &to).map_err(|e| format!("{}: {e}", to.display()))?;
+ report.copied = report.copied.saturating_sub(1);
+ report
+ .recipes_unregistered
+ .push(rel.to_string_lossy().into_owned());
+ }
+ }
+ }
+ report.recipes_unregistered.sort();
+ Ok(())
+}
+
/// The tags a recipe's ingredients name (`#ns:path` or `{"tag": ...}`).
fn tags_used(v: &Value, out: &mut BTreeSet) {
match v {
diff --git a/crates/horizon-port-pack/src/check.rs b/crates/horizon-port-pack/src/check.rs
new file mode 100644
index 000000000..68331dbc4
--- /dev/null
+++ b/crates/horizon-port-pack/src/check.rs
@@ -0,0 +1,411 @@
+//! One mod jar on its own, as the launcher's mod browser installs it: what
+//! of it Horizon runs, said before install (Works, Partly, Doesn't run),
+//! from the jar itself. The jar is carried over ([`crate::carry`]) into a
+//! folder content mod, and its classes are read ([`crate::classes`]) for
+//! what the carry can't take: block entities, entities, Mixins, behaviour.
+//!
+//! - **Works**: content only. Its blocks, items, recipes, loot, tags and
+//! worldgen port, and its code only registers them.
+//! - **Partly**: the content ports; the code features listed don't.
+//! - **Doesn't run**: nothing to port (everything it does is Java code), or
+//! the jar can't be carried at all.
+use crate::{carry, classes, jar};
+use serde::{Deserialize, Serialize};
+use std::{collections::BTreeMap, fs, io::Read, path::Path};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum Verdict {
+ Works,
+ Partly,
+ No,
+}
+
+impl Verdict {
+ pub fn label(self) -> &'static str {
+ match self {
+ Verdict::Works => "Works",
+ Verdict::Partly => "Partly",
+ Verdict::No => "Doesn't run",
+ }
+ }
+}
+
+/// What checking a jar found. Written as `check.json` beside the carry.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Check {
+ pub mod_id: String,
+ pub name: String,
+ pub version: String,
+ /// `neoforge`, `forge`, `fabric`, `quilt`, or `` for a plain zip.
+ pub loader: String,
+ pub license: String,
+ pub verdict: Verdict,
+ /// One line: why this verdict.
+ pub summary: String,
+ /// What ports: "12 blocks", "40 recipes"...
+ pub ports: Vec,
+ /// What doesn't, with why.
+ pub skipped: Vec,
+ /// Required mods, by id.
+ pub depends: Vec,
+ /// The folder mod's namespaces (its id first): two mods on at once may
+ /// not share one.
+ pub namespaces: Vec,
+ pub code: classes::Code,
+}
+
+/// The loader a jar is made for, from its metadata file.
+fn loader(names: &[String]) -> &'static str {
+ let has = |n: &str| names.iter().any(|x| x == n);
+ if has("META-INF/neoforge.mods.toml") {
+ "neoforge"
+ } else if has("META-INF/mods.toml") {
+ "forge"
+ } else if has("fabric.mod.json") {
+ "fabric"
+ } else if has("quilt.mod.json") {
+ "quilt"
+ } else {
+ ""
+ }
+}
+
+/// Data folders named as before 1.21 (`recipes/`, `loot_tables/`) and none
+/// as 1.21 names them: the game doesn't read them, and the carry upgrades
+/// from 1.21.1 on. (Some jars keep a stale plural folder beside the new one.)
+fn old_layout(names: &[String]) -> bool {
+ let has = |kinds: [&str; 2]| {
+ names.iter().any(|n| {
+ let p: Vec<&str> = n.split('/').collect();
+ p.len() > 3 && p[0] == "data" && kinds.contains(&p[2]) && n.ends_with(".json")
+ })
+ };
+ has(["recipes", "loot_tables"]) && !has(["recipe", "loot_table"])
+}
+
+fn plural(n: usize, one: &str, many: &str) -> String {
+ format!("{n} {}", if n == 1 { one } else { many })
+}
+
+/// Checks `jar` and carries it over into `out/carry/` (`out/check.json`,
+/// `out/carry-report.json` beside it). The carry is the folder mod an
+/// install copies.
+pub fn check(jar_path: &Path, out: &Path) -> Result {
+ let info = jar::read(jar_path)?;
+ let file = fs::File::open(jar_path).map_err(|e| format!("{}: {e}", jar_path.display()))?;
+ let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("{}: {e}", jar_path.display()))?;
+ let names: Vec = zip.file_names().map(str::to_owned).collect();
+ let mut bytes = Vec::new();
+ for n in names.iter().filter(|n| n.ends_with(".class")) {
+ let mut b = Vec::new();
+ if let Ok(mut e) = zip.by_name(n)
+ && e.size() < 1 << 24
+ && e.read_to_end(&mut b).is_ok()
+ {
+ bytes.push(b);
+ }
+ }
+ let code = classes::census(bytes.iter().map(Vec::as_slice));
+ let mut check = Check {
+ mod_id: info.mod_id.clone(),
+ name: info.name.clone(),
+ version: info.version.clone(),
+ loader: loader(&names).to_owned(),
+ license: info.license.clone(),
+ verdict: Verdict::No,
+ summary: String::new(),
+ ports: Vec::new(),
+ skipped: Vec::new(),
+ depends: info.depends.clone(),
+ namespaces: Vec::new(),
+ code,
+ };
+ fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
+ let done = |check: Check| -> Result {
+ crate::pipeline::write_json(&out.join("check.json"), &check)?;
+ Ok(check)
+ };
+ if old_layout(&names) {
+ check.summary = "Made for Minecraft 1.20 or older: Horizon ports mods made for 1.21 \
+ and later."
+ .into();
+ return done(check);
+ }
+ let alone = |m: &str| m == info.mod_id || m == "minecraft";
+ let pack = carry::Pack {
+ loaded: &alone,
+ mods: &alone,
+ };
+ let report = match carry::carry(
+ jar_path,
+ &info,
+ out,
+ None,
+ &|_| true,
+ &pack,
+ &BTreeMap::new(),
+ ) {
+ Ok(r) => r,
+ Err(e) => {
+ check.summary = format!("Can't be carried over: {e}");
+ return done(check);
+ }
+ };
+ check.namespaces = std::iter::once(info.mod_id.clone())
+ .chain(report.namespaces.iter().cloned())
+ .collect();
+ let c = &info.census;
+ let recipes = report
+ .recipes_upgraded
+ .saturating_sub(report.recipes_unregistered.len());
+ let loot = c.loot_tables + report.loot_tables_added;
+ let content =
+ report.blocks.len() + report.items + recipes + loot + report.worldgen + c.structures;
+ for (n, one, many) in [
+ (report.blocks.len(), "block", "blocks"),
+ (report.items, "item", "items"),
+ (recipes, "recipe", "recipes"),
+ (loot, "loot table", "loot tables"),
+ (report.worldgen, "worldgen file", "worldgen files"),
+ (c.textures, "texture", "textures"),
+ ] {
+ if n > 0 {
+ check.ports.push(plural(n, one, many));
+ }
+ }
+ if !report.blocks.is_empty() {
+ check
+ .ports
+ .push("blocks take the closest vanilla block's shape, hardness and sounds".into());
+ }
+ let mut skipped = Vec::new();
+ if !report.blocks_unknown.is_empty() {
+ skipped.push(plural(
+ report.blocks_unknown.len(),
+ "block with no vanilla block to copy (left out)",
+ "blocks with no vanilla block to copy (left out)",
+ ));
+ }
+ if !report.recipes_unregistered.is_empty() {
+ skipped.push(plural(
+ report.recipes_unregistered.len(),
+ "recipe for a left-out block",
+ "recipes for left-out blocks",
+ ));
+ }
+ if !report.recipes_kept.is_empty() {
+ skipped.push(plural(
+ report.recipes_kept.len(),
+ "recipe of a type Horizon doesn't have",
+ "recipes of types Horizon doesn't have",
+ ));
+ }
+ if !report.unreadable.is_empty() {
+ skipped.push(plural(
+ report.unreadable.len(),
+ "file the game can't read",
+ "files the game can't read",
+ ));
+ }
+ let wg = &report.worldgen_types;
+ let dropped = wg.processors_dropped.values().sum::();
+ if dropped > 0 {
+ skipped.push(plural(
+ dropped,
+ "structure processor written in Java",
+ "structure processors written in Java",
+ ));
+ }
+ let unsupported = wg.unsupported.values().sum::();
+ if unsupported > 0 {
+ skipped.push(plural(
+ unsupported,
+ "worldgen file of a type written in Java",
+ "worldgen files of types written in Java",
+ ));
+ }
+ for (f, n) in &check.code.features {
+ let mut line = f.describe(*n);
+ if *f == classes::Feature::Events {
+ let names: Vec<&str> = check
+ .code
+ .events
+ .iter()
+ .take(3)
+ .map(String::as_str)
+ .collect();
+ line.push_str(&format!(" ({}", names.join(", ")));
+ if check.code.events.len() > 3 {
+ line.push_str(", ...");
+ }
+ line.push(')');
+ }
+ skipped.push(line);
+ }
+ check.skipped = skipped;
+ let behaviour = check.code.behaviour();
+ (check.verdict, check.summary) = if content == 0 {
+ let what = if behaviour || check.code.classes > 0 {
+ "everything it does is Java code, which Horizon doesn't run"
+ } else {
+ "it has no blocks, items, recipes or worldgen"
+ };
+ (Verdict::No, format!("Nothing to port: {what}."))
+ } else if check.skipped.is_empty() {
+ (
+ Verdict::Works,
+ format!(
+ "Content only: {} port.",
+ check.ports[..check.ports.len().min(3)].join(", ")
+ ),
+ )
+ } else {
+ (
+ Verdict::Partly,
+ format!(
+ "{} port; not {}.",
+ check.ports[..check.ports.len().min(2)].join(", "),
+ check.skipped[..check.skipped.len().min(2)].join(", ")
+ ),
+ )
+ };
+ done(check)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Write;
+
+ fn jar(dir: &Path, files: &[(&str, &[u8])]) -> std::path::PathBuf {
+ let path = dir.join("m.jar");
+ let mut zip = zip::ZipWriter::new(fs::File::create(&path).unwrap());
+ for (name, bytes) in files {
+ zip.start_file(*name, zip::write::SimpleFileOptions::default())
+ .unwrap();
+ zip.write_all(bytes).unwrap();
+ }
+ zip.finish().unwrap();
+ path
+ }
+
+ const TOML: &[u8] = br#"modLoader = "javafml"
+license = "MIT"
+[[mods]]
+modId = "ruby"
+version = "1.0"
+displayName = "Ruby"
+"#;
+
+ fn temp(name: &str) -> std::path::PathBuf {
+ let dir =
+ std::env::temp_dir().join(format!("port-pack-check-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ #[test]
+ fn content_only_works_and_code_makes_it_partly() {
+ let dir = temp("content");
+ let blockstate = br#"{"variants": {"": {"model": "ruby:block/ruby_block"}}}"#;
+ let recipe = br#"{"type": "minecraft:crafting_shapeless", "ingredients": ["minecraft:red_dye"], "result": {"id": "ruby:ruby"}}"#;
+ let plain = [
+ ("META-INF/neoforge.mods.toml", TOML),
+ ("assets/ruby/blockstates/ruby_block.json", blockstate),
+ ("assets/ruby/models/item/ruby.json", b"{}"),
+ ("data/ruby/recipe/ruby.json", recipe),
+ ];
+ let c = check(&jar(&dir, &plain), &dir.join("out")).unwrap();
+ assert_eq!(c.verdict, Verdict::Works, "{c:?}");
+ assert_eq!(c.loader, "neoforge");
+ assert_eq!(&c.ports[..3], ["1 block", "1 item", "1 recipe"]);
+ assert!(dir.join("out/carry/horizon-mod.toml").is_file());
+ assert!(dir.join("out/check.json").is_file());
+
+ let tile = crate::classes::tests_support::class_file(
+ "ruby/Tile",
+ "net/minecraft/world/level/block/entity/BlockEntity",
+ );
+ let mut coded = plain.to_vec();
+ coded.push(("ruby/Tile.class", &tile));
+ let c = check(&jar(&dir, &coded), &dir.join("out")).unwrap();
+ assert_eq!(c.verdict, Verdict::Partly);
+ assert!(
+ c.skipped[0].starts_with("1 block entity"),
+ "{:?}",
+ c.skipped
+ );
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn recipes_for_left_out_blocks_are_left_out_too() {
+ let dir = temp("left-out");
+ let odd = br#"{"variants": {"wobble=1": {"model": "ruby:block/odd"}}}"#;
+ let plain = br#"{"variants": {"": {"model": "ruby:block/ruby_block"}}}"#;
+ let recipe = |result: &str| {
+ format!(
+ r#"{{"type": "minecraft:crafting_shapeless", "ingredients": ["minecraft:red_dye"], "result": {{"id": "{result}"}}}}"#
+ )
+ };
+ let (odd_recipe, block_recipe) = (recipe("ruby:odd"), recipe("ruby:ruby_block"));
+ let files = [
+ ("META-INF/neoforge.mods.toml", TOML),
+ ("assets/ruby/blockstates/odd.json", odd.as_slice()),
+ ("assets/ruby/blockstates/ruby_block.json", plain.as_slice()),
+ ("data/ruby/recipe/odd.json", odd_recipe.as_bytes()),
+ ("data/ruby/recipe/ruby_block.json", block_recipe.as_bytes()),
+ ];
+ let c = check(&jar(&dir, &files), &dir.join("out")).unwrap();
+ assert_eq!(c.verdict, Verdict::Partly);
+ assert!(c.ports.contains(&"1 recipe".to_string()), "{:?}", c.ports);
+ assert!(
+ c.skipped
+ .contains(&"1 recipe for a left-out block".to_string()),
+ "{:?}",
+ c.skipped
+ );
+ assert!(!dir.join("out/carry/data/ruby/recipe/odd.json").exists());
+ assert!(dir.join("out/outside/data/ruby/recipe/odd.json").exists());
+ assert!(
+ dir.join("out/carry/data/ruby/recipe/ruby_block.json")
+ .exists()
+ );
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn code_only_and_old_layouts_dont_run() {
+ let dir = temp("code");
+ let tile = crate::classes::tests_support::class_file("ruby/Mixin", "java/lang/Object");
+ let c = check(
+ &jar(
+ &dir,
+ &[
+ ("META-INF/neoforge.mods.toml", TOML),
+ ("ruby/A.class", &tile),
+ ],
+ ),
+ &dir.join("out"),
+ )
+ .unwrap();
+ assert_eq!(c.verdict, Verdict::No);
+ assert!(c.summary.starts_with("Nothing to port"), "{}", c.summary);
+ let c = check(
+ &jar(
+ &dir,
+ &[
+ ("META-INF/mods.toml", TOML),
+ ("data/ruby/recipes/ruby.json", b"{}"),
+ ],
+ ),
+ &dir.join("out"),
+ )
+ .unwrap();
+ assert_eq!(c.verdict, Verdict::No);
+ assert!(c.summary.contains("1.20 or older"));
+ fs::remove_dir_all(&dir).unwrap();
+ }
+}
diff --git a/crates/horizon-port-pack/src/classes.rs b/crates/horizon-port-pack/src/classes.rs
new file mode 100644
index 000000000..d39c72e1a
--- /dev/null
+++ b/crates/horizon-port-pack/src/classes.rs
@@ -0,0 +1,642 @@
+//! What a mod's Java code does, read from its class files without running
+//! or decompiling them: each class's superclass, interfaces, declared
+//! methods and the classes and annotations its constant pool names. The
+//! mod's own classes are followed up to the first game class they extend,
+//! and that class says what the code is: a block entity, a menu, an entity,
+//! a block or item with behaviour of its own, a worldgen feature...
+//!
+//! Since 26.1 the game ships unobfuscated, and NeoForge has run on Mojang's
+//! names since 1.20.5, so game classes and methods are read by name. Fabric
+//! jars before 26.1 name them in intermediary (`net/minecraft/class_2248`)
+//! and Forge's methods are SRG (`m_60503_`): a class extending such a game
+//! class is counted as code of its own, whatever it overrides.
+use serde::{Deserialize, Serialize};
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+
+/// One class file, as much as this module reads.
+#[derive(Debug, Default, Clone, PartialEq)]
+pub struct Class {
+ pub name: String,
+ pub superclass: String,
+ pub interfaces: Vec,
+ /// Declared methods, by name (constructors and lambdas left out).
+ pub methods: Vec,
+ /// Every class the constant pool names (`net/minecraft/...`).
+ pub refs: BTreeSet,
+ /// Annotation and descriptor strings (`Lorg/spongepowered/asm/mixin/Mixin;`).
+ pub mixin: bool,
+}
+
+/// Reads a class file's header, constant pool and declared methods.
+pub fn parse(bytes: &[u8]) -> Option {
+ let mut r = Reader { bytes, at: 0 };
+ if r.u4()? != 0xCAFE_BABE {
+ return None;
+ }
+ r.skip(4)?; // minor, major
+ let count = r.u2()? as usize;
+ let mut utf8: HashMap = HashMap::new();
+ let mut class_of: HashMap = HashMap::new();
+ let mut i = 1;
+ while i < count {
+ let tag = r.u1()?;
+ match tag {
+ 1 => {
+ let len = r.u2()? as usize;
+ let s = r.take(len)?;
+ utf8.insert(i, String::from_utf8_lossy(s).into_owned());
+ }
+ 7 => {
+ class_of.insert(i, r.u2()? as usize);
+ }
+ 8 | 16 | 19 | 20 => r.skip(2)?,
+ 3 | 4 | 9..=12 | 17 | 18 => r.skip(4)?,
+ 15 => r.skip(3)?,
+ 5 | 6 => {
+ r.skip(8)?;
+ i += 1;
+ }
+ _ => return None,
+ }
+ i += 1;
+ }
+ let class_name = |idx: usize| -> String {
+ class_of
+ .get(&idx)
+ .and_then(|u| utf8.get(u))
+ .cloned()
+ .unwrap_or_default()
+ };
+ r.skip(2)?; // access flags
+ let name = class_name(r.u2()? as usize);
+ let superclass = class_name(r.u2()? as usize);
+ let n = r.u2()? as usize;
+ let mut interfaces = Vec::with_capacity(n);
+ for _ in 0..n {
+ interfaces.push(class_name(r.u2()? as usize));
+ }
+ // Fields, then methods: flags, name, descriptor, attributes.
+ let mut methods = Vec::new();
+ for member in 0..2 {
+ let n = r.u2()?;
+ for _ in 0..n {
+ r.skip(2)?;
+ let name = r.u2()? as usize;
+ r.skip(2)?;
+ let attributes = r.u2()?;
+ for _ in 0..attributes {
+ r.skip(2)?;
+ let len = r.u4()? as usize;
+ r.skip(len)?;
+ }
+ if member == 1
+ && let Some(m) = utf8.get(&name)
+ && !m.starts_with('<')
+ && !m.starts_with("lambda$")
+ {
+ methods.push(m.clone());
+ }
+ }
+ }
+ let refs = class_of
+ .values()
+ .filter_map(|u| utf8.get(u))
+ .filter(|s| !s.starts_with('['))
+ .cloned()
+ .collect();
+ let mixin = utf8
+ .values()
+ .any(|s| s == "Lorg/spongepowered/asm/mixin/Mixin;");
+ Some(Class {
+ name,
+ superclass,
+ interfaces,
+ methods,
+ refs,
+ mixin,
+ })
+}
+
+struct Reader<'a> {
+ bytes: &'a [u8],
+ at: usize,
+}
+
+impl<'a> Reader<'a> {
+ fn take(&mut self, n: usize) -> Option<&'a [u8]> {
+ let s = self.bytes.get(self.at..self.at.checked_add(n)?)?;
+ self.at += n;
+ Some(s)
+ }
+ fn skip(&mut self, n: usize) -> Option<()> {
+ self.take(n).map(drop)
+ }
+ fn u1(&mut self) -> Option {
+ Some(self.take(1)?[0])
+ }
+ fn u2(&mut self) -> Option {
+ let b = self.take(2)?;
+ Some(u16::from_be_bytes([b[0], b[1]]))
+ }
+ fn u4(&mut self) -> Option {
+ let b = self.take(4)?;
+ Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
+ }
+}
+
+/// What a class does, as the port sees it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum Feature {
+ /// A block with behaviour of its own (use, ticks, collisions...).
+ BlockBehaviour,
+ /// A block with a shape of its own: it ports with its template's.
+ BlockShape,
+ /// An item with behaviour of its own (use, on hit...).
+ ItemBehaviour,
+ BlockEntity,
+ Menu,
+ Entity,
+ Screen,
+ Renderer,
+ /// A worldgen feature, placement or structure type written in Java.
+ Worldgen,
+ /// A recipe type (its recipes don't craft) or ingredient type.
+ Recipe,
+ Effect,
+ Enchantment,
+ Particle,
+ Command,
+ Network,
+ /// Reacts to game events (NeoForge's bus, Fabric's callbacks).
+ Events,
+ /// A Mixin: a patch to the game's own code.
+ Mixin,
+ /// Extends a game class under obfuscated names (Fabric before 26.1,
+ /// Forge's methods): what it does can't be read.
+ Unread,
+}
+
+impl Feature {
+ /// How the coverage line names `n` of them.
+ pub fn describe(self, n: usize) -> String {
+ let (one, many) = match self {
+ Feature::BlockBehaviour => (
+ "block with behaviour of its own (use, ticks, collisions)",
+ "blocks with behaviour of their own (use, ticks, collisions)",
+ ),
+ Feature::BlockShape => (
+ "block with a shape of its own: it ports with its template's",
+ "blocks with shapes of their own: they port with their templates'",
+ ),
+ Feature::ItemBehaviour => (
+ "item with behaviour of its own (use, on hit)",
+ "items with behaviour of their own (use, on hit)",
+ ),
+ Feature::BlockEntity => (
+ "block entity (machine, container or animated block)",
+ "block entities (machines, containers, animated blocks)",
+ ),
+ Feature::Menu => ("menu (a container screen)", "menus (container screens)"),
+ Feature::Entity => ("mob or entity", "mobs or entities"),
+ Feature::Screen => ("screen of its own", "screens of its own"),
+ Feature::Renderer => ("renderer or model in code", "renderers or models in code"),
+ Feature::Worldgen => (
+ "worldgen feature or structure type in code",
+ "worldgen features or structure types in code",
+ ),
+ Feature::Recipe => (
+ "recipe type of its own (its recipes don't craft)",
+ "recipe types of its own (their recipes don't craft)",
+ ),
+ Feature::Effect => ("status effect", "status effects"),
+ Feature::Enchantment => ("enchantment effect in code", "enchantment effects in code"),
+ Feature::Particle => ("particle type", "particle types"),
+ Feature::Command => ("command", "commands"),
+ Feature::Network => ("network message", "network messages"),
+ Feature::Events => ("game event it reacts to", "game events it reacts to"),
+ Feature::Mixin => (
+ "Mixin (a patch to the game's code)",
+ "Mixins (patches to the game's code)",
+ ),
+ Feature::Unread => (
+ "class extending the game under obfuscated names",
+ "classes extending the game under obfuscated names",
+ ),
+ };
+ format!("{n} {}", if n == 1 { one } else { many })
+ }
+}
+
+/// Block methods that only say how it looks or is placed: the template's
+/// do the same for the states a blockstate file lists.
+const BLOCK_LOOKS: [&str; 18] = [
+ "codec",
+ "createBlockStateDefinition",
+ "getStateForPlacement",
+ "rotate",
+ "mirror",
+ "getRenderShape",
+ "skipRendering",
+ "getShadeBrightness",
+ "propagatesSkylightDown",
+ "getCloneItemStack",
+ "isPathfindable",
+ "getFluidState",
+ "updateShape",
+ "canBeReplaced",
+ "getLightBlock",
+ "useShapeForLightOcclusion",
+ "getDescriptionId",
+ "animateTick",
+];
+/// Block methods that only change its outline or collision.
+const BLOCK_SHAPES: [&str; 6] = [
+ "getShape",
+ "getCollisionShape",
+ "getVisualShape",
+ "getOcclusionShape",
+ "getInteractionShape",
+ "getBlockSupportShape",
+];
+/// Item methods that only say how it looks or is named.
+const ITEM_LOOKS: [&str; 6] = [
+ "appendHoverText",
+ "getName",
+ "isFoil",
+ "getDescriptionId",
+ "getBarColor",
+ "getBarWidth",
+];
+
+/// The game's own, loader and library classes: the first of these a mod's
+/// class chain reaches is what it extends.
+fn external(name: &str, own: &BTreeMap) -> bool {
+ !own.contains_key(name)
+}
+
+fn obfuscated_method(m: &str) -> bool {
+ let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
+ m.strip_prefix("method_").is_some_and(digits)
+ || m.strip_prefix("m_")
+ .and_then(|s| s.strip_suffix('_'))
+ .is_some_and(digits)
+}
+
+/// What a game class (Mojang's names) is, by its package and name.
+fn kind_of_game_class(name: &str) -> Option {
+ let rest = name.strip_prefix("net/minecraft/")?;
+ if rest.starts_with("class_") {
+ return Some(Feature::Unread);
+ }
+ let (package, simple) = rest.rsplit_once('/').unwrap_or(("", rest));
+ Some(match package {
+ "world/level/block/entity" => Feature::BlockEntity,
+ p if p.starts_with("world/level/block") => Feature::BlockBehaviour,
+ "world/inventory" if simple.ends_with("Menu") => Feature::Menu,
+ p if p.starts_with("world/entity") => Feature::Entity,
+ p if p.starts_with("world/item/crafting") => Feature::Recipe,
+ p if p.starts_with("world/item/enchantment") => Feature::Enchantment,
+ p if p.starts_with("world/item") => Feature::ItemBehaviour,
+ p if p.starts_with("world/level/levelgen") => Feature::Worldgen,
+ "world/effect" => Feature::Effect,
+ p if p.starts_with("client/gui/screens") || p.starts_with("client/gui/components") => {
+ Feature::Screen
+ }
+ p if p.starts_with("client/renderer") || p.starts_with("client/model") => Feature::Renderer,
+ p if p.starts_with("client/particle") || p.starts_with("core/particles") => {
+ Feature::Particle
+ }
+ _ => return None,
+ })
+}
+
+/// Events a content mod uses to register what it has: not behaviour.
+fn registration_event(name: &str) -> bool {
+ [
+ "BuildCreativeModeTabContentsEvent",
+ "RegisterEvent",
+ "Register",
+ "Lifecycle",
+ "ModConfigEvent",
+ "AddPackFindersEvent",
+ "ItemGroupEvents",
+ "ClientLifecycleEvents",
+ "ServerLifecycleEvents",
+ ]
+ .iter()
+ .any(|k| name.rsplit('/').next().unwrap_or(name).contains(k))
+ || name.contains("/lifecycle/")
+ || name.contains("/registries/")
+ || name.contains("/registry/")
+}
+
+/// The code census: how many of each feature, and examples.
+#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Code {
+ pub classes: usize,
+ pub features: BTreeMap,
+ /// The game events it subscribes to, by simple name.
+ pub events: BTreeSet,
+ /// Blocks and items with behaviour, and the methods they override.
+ pub examples: BTreeMap>,
+}
+
+impl Code {
+ /// Whether it does anything beyond registering blocks and items.
+ pub fn behaviour(&self) -> bool {
+ self.features
+ .keys()
+ .any(|f| *f != Feature::BlockShape && *f != Feature::Particle)
+ }
+}
+
+/// Reads every class of a jar. `classes` are the class files' bytes.
+pub fn census<'a>(classes: impl IntoIterator- ) -> Code {
+ let own: BTreeMap
= classes
+ .into_iter()
+ .filter_map(parse)
+ .map(|c| (c.name.clone(), c))
+ .collect();
+ let mut code = Code {
+ classes: own.len(),
+ ..Code::default()
+ };
+ let mut count = |f: Feature| *code.features.entry(f).or_default() += 1;
+ for c in own.values() {
+ if c.mixin {
+ count(Feature::Mixin);
+ continue;
+ }
+ // The first class outside the jar the chain reaches, and the
+ // methods declared along the way.
+ let mut methods: BTreeSet<&str> = c.methods.iter().map(String::as_str).collect();
+ let mut at = c;
+ let mut seen = 0;
+ while !external(&at.superclass, &own) && seen < 64 {
+ at = &own[&at.superclass];
+ methods.extend(at.methods.iter().map(String::as_str));
+ seen += 1;
+ }
+ let base = at.superclass.as_str();
+ let kind = kind_of_game_class(base).or_else(|| {
+ c.interfaces.iter().find_map(|i| match i.as_str() {
+ "net/minecraft/network/protocol/common/custom/CustomPacketPayload" => {
+ Some(Feature::Network)
+ }
+ "net/minecraft/world/MenuProvider" => Some(Feature::Menu),
+ _ => None,
+ })
+ });
+ let Some(kind) = kind else {
+ continue;
+ };
+ let feature = match kind {
+ Feature::BlockBehaviour => {
+ let behaviour: Vec<&str> = methods
+ .iter()
+ .copied()
+ .filter(|m| !BLOCK_LOOKS.contains(m) && !BLOCK_SHAPES.contains(m))
+ .collect();
+ if !behaviour.is_empty() {
+ code.examples.insert(
+ c.name.rsplit('/').next().unwrap_or("").to_owned(),
+ behaviour.iter().map(|m| m.to_string()).collect(),
+ );
+ if behaviour.iter().any(|m| obfuscated_method(m)) {
+ Some(Feature::Unread)
+ } else {
+ Some(Feature::BlockBehaviour)
+ }
+ } else if methods.iter().any(|m| BLOCK_SHAPES.contains(m)) {
+ Some(Feature::BlockShape)
+ } else {
+ None
+ }
+ }
+ Feature::ItemBehaviour => {
+ let behaviour: Vec<&str> = methods
+ .iter()
+ .copied()
+ .filter(|m| !ITEM_LOOKS.contains(m))
+ .collect();
+ if behaviour.is_empty() {
+ None
+ } else {
+ code.examples.insert(
+ c.name.rsplit('/').next().unwrap_or("").to_owned(),
+ behaviour.iter().map(|m| m.to_string()).collect(),
+ );
+ Some(Feature::ItemBehaviour)
+ }
+ }
+ // A class extending an obfuscated game class without declaring
+ // anything adds nothing to read.
+ Feature::Unread if methods.is_empty() => None,
+ k => Some(k),
+ };
+ if let Some(f) = feature {
+ count(f);
+ }
+ }
+ for c in own.values() {
+ for r in &c.refs {
+ let event = (r.starts_with("net/neoforged/neoforge/event/")
+ || r.starts_with("net/minecraftforge/event/")
+ || r.starts_with("net/fabricmc/fabric/api/event/")
+ || r.starts_with("net/fabricmc/fabric/api/entity/event/"))
+ && !registration_event(r);
+ if event {
+ let simple = r.rsplit('/').next().unwrap_or(r);
+ code.events
+ .insert(simple.split('$').next().unwrap_or(simple).to_owned());
+ }
+ if r.starts_with("com/mojang/brigadier/")
+ && !code.features.contains_key(&Feature::Command)
+ {
+ code.features.insert(Feature::Command, 1);
+ }
+ }
+ }
+ if !code.events.is_empty() {
+ code.features.insert(Feature::Events, code.events.len());
+ }
+ code
+}
+
+#[cfg(test)]
+pub(crate) mod tests_support {
+ /// A class file with `name` extending `superclass`, declaring `methods`
+ /// and naming `refs` in its constant pool.
+ pub fn class_with(
+ name: &str,
+ superclass: &str,
+ methods: &[&str],
+ refs: &[&str],
+ mixin: bool,
+ ) -> Vec {
+ let mut pool: Vec> = Vec::new();
+ let utf = |pool: &mut Vec>, s: &str| -> u16 {
+ let mut e = vec![1];
+ e.extend((s.len() as u16).to_be_bytes());
+ e.extend(s.as_bytes());
+ pool.push(e);
+ pool.len() as u16
+ };
+ let class = |pool: &mut Vec>, s: &str| -> u16 {
+ let u = utf(pool, s);
+ let mut e = vec![7];
+ e.extend(u.to_be_bytes());
+ pool.push(e);
+ pool.len() as u16
+ };
+ let this = class(&mut pool, name);
+ let sup = class(&mut pool, superclass);
+ for r in refs {
+ class(&mut pool, r);
+ }
+ // A long takes two slots.
+ pool.push(vec![5, 0, 0, 0, 0, 0, 0, 0, 1]);
+ pool.push(Vec::new());
+ if mixin {
+ utf(&mut pool, "Lorg/spongepowered/asm/mixin/Mixin;");
+ }
+ let desc = utf(&mut pool, "()V");
+ let names: Vec = methods.iter().map(|m| utf(&mut pool, m)).collect();
+ let mut out = vec![0xCA, 0xFE, 0xBA, 0xBE, 0, 0, 0, 65];
+ out.extend(((pool.len() + 1) as u16).to_be_bytes());
+ for e in &pool {
+ out.extend(e);
+ }
+ out.extend([0, 0x21]);
+ out.extend(this.to_be_bytes());
+ out.extend(sup.to_be_bytes());
+ out.extend([0, 0]); // interfaces
+ out.extend([0, 0]); // fields
+ out.extend((names.len() as u16).to_be_bytes());
+ for n in names {
+ out.extend([0, 1]);
+ out.extend(n.to_be_bytes());
+ out.extend(desc.to_be_bytes());
+ // One attribute, to be skipped.
+ out.extend([0, 1, 0, 1, 0, 0, 0, 2, 0, 0]);
+ }
+ out.extend([0, 0]); // class attributes
+ out
+ }
+
+ /// A class extending `superclass` and declaring nothing.
+ pub fn class_file(name: &str, superclass: &str) -> Vec {
+ class_with(name, superclass, &[], &[], false)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::tests_support::class_with as class_file;
+ use super::*;
+
+ #[test]
+ fn reads_the_header_methods_and_pool() {
+ let bytes = class_file(
+ "a/Lamp",
+ "net/minecraft/world/level/block/Block",
+ &["", "useWithoutItem", "lambda$x$0"],
+ &["net/minecraft/world/item/Item"],
+ false,
+ );
+ let c = parse(&bytes).unwrap();
+ assert_eq!(c.name, "a/Lamp");
+ assert_eq!(c.superclass, "net/minecraft/world/level/block/Block");
+ assert_eq!(c.methods, ["useWithoutItem"]);
+ assert!(c.refs.contains("net/minecraft/world/item/Item"));
+ assert!(!c.mixin);
+ assert!(parse(&bytes[..bytes.len() - 3]).is_none());
+ assert!(parse(b"not a class").is_none());
+ }
+
+ #[test]
+ fn follows_own_classes_to_the_game() {
+ let block = "net/minecraft/world/level/block/Block";
+ let files = [
+ // Looks only: a template covers it.
+ class_file("m/Plain", block, &["getStateForPlacement"], &[], false),
+ class_file("m/Round", block, &["getShape"], &[], false),
+ // Behaviour two levels down.
+ class_file("m/Base", block, &["randomTick"], &[], false),
+ class_file("m/Lamp", "m/Base", &[], &[], false),
+ class_file(
+ "m/Tile",
+ "net/minecraft/world/level/block/entity/BlockEntity",
+ &[],
+ &[],
+ false,
+ ),
+ class_file("m/Mix", "java/lang/Object", &[], &[], true),
+ class_file(
+ "m/Old",
+ "net/minecraft/class_2248",
+ &["method_9534"],
+ &[],
+ false,
+ ),
+ class_file(
+ "m/Events",
+ "java/lang/Object",
+ &[],
+ &[
+ "net/neoforged/neoforge/event/entity/player/PlayerInteractEvent$RightClickBlock",
+ "net/neoforged/neoforge/event/BuildCreativeModeTabContentsEvent",
+ "net/neoforged/neoforge/registries/DeferredRegister",
+ ],
+ false,
+ ),
+ class_file(
+ "m/Gem",
+ "net/minecraft/world/item/Item",
+ &["appendHoverText"],
+ &[],
+ false,
+ ),
+ ];
+ let code = census(files.iter().map(Vec::as_slice));
+ assert_eq!(code.classes, 9);
+ let n = |f| code.features.get(&f).copied().unwrap_or(0);
+ assert_eq!(n(Feature::BlockBehaviour), 2, "{code:?}");
+ assert_eq!(n(Feature::BlockShape), 1);
+ assert_eq!(n(Feature::BlockEntity), 1);
+ assert_eq!(n(Feature::Mixin), 1);
+ assert_eq!(n(Feature::Unread), 1);
+ assert_eq!(n(Feature::ItemBehaviour), 0);
+ assert_eq!(
+ code.events.iter().collect::>(),
+ ["PlayerInteractEvent"]
+ );
+ assert!(code.behaviour());
+ }
+
+ #[test]
+ fn registration_only_is_not_behaviour() {
+ let files = [
+ class_file(
+ "m/Mod",
+ "java/lang/Object",
+ &["register"],
+ &[
+ "net/neoforged/neoforge/registries/DeferredRegister",
+ "net/minecraft/world/level/block/Block",
+ ],
+ false,
+ ),
+ class_file(
+ "m/Pillar",
+ "net/minecraft/world/level/block/RotatedPillarBlock",
+ &[],
+ &[],
+ false,
+ ),
+ ];
+ let code = census(files.iter().map(Vec::as_slice));
+ assert!(!code.behaviour(), "{code:?}");
+ }
+}
diff --git a/crates/horizon-port-pack/src/fetch.rs b/crates/horizon-port-pack/src/fetch.rs
index f8f7b2dc7..f2803baa2 100644
--- a/crates/horizon-port-pack/src/fetch.rs
+++ b/crates/horizon-port-pack/src/fetch.rs
@@ -40,7 +40,7 @@ pub enum How {
Downloaded,
/// Copied from the player's folder.
Local,
- /// Only on CurseForge, whose downloads need an API key.
+ /// Only on CurseForge, whose downloads are coming soon (its API needs a paid key).
NeedsKey,
NotFound,
Failed,
@@ -52,7 +52,7 @@ impl How {
How::Present => "already here",
How::Downloaded => "downloaded",
How::Local => "copied from your folder",
- How::NeedsKey => "needs a CurseForge key",
+ How::NeedsKey => "CurseForge downloads coming soon",
How::NotFound => "not found",
How::Failed => "failed",
}
@@ -163,7 +163,7 @@ pub fn fetch(
}
write_json(&work.join("fetch.json"), &fetched)?;
log(format!(
- "jars: {} downloaded, {} copied, {} already here, {} need a CurseForge key, {} not found, {} failed",
+ "jars: {} downloaded, {} copied, {} already here, {} on CurseForge only (CurseForge downloads coming soon), {} not found, {} failed",
fetched.count(How::Downloaded),
fetched.count(How::Local),
fetched.count(How::Present),
diff --git a/crates/horizon-port-pack/src/lib.rs b/crates/horizon-port-pack/src/lib.rs
index 08f9b273f..f729b6c52 100644
--- a/crates/horizon-port-pack/src/lib.rs
+++ b/crates/horizon-port-pack/src/lib.rs
@@ -6,6 +6,8 @@
//! jars they downloaded and what is carried over from them stay there and
//! are never uploaded or committed.
pub mod carry;
+pub mod check;
+pub mod classes;
pub mod classify;
pub mod fetch;
pub mod import;
diff --git a/crates/horizon-port-pack/src/main.rs b/crates/horizon-port-pack/src/main.rs
index e766a442d..2598b47ed 100644
--- a/crates/horizon-port-pack/src/main.rs
+++ b/crates/horizon-port-pack/src/main.rs
@@ -19,6 +19,10 @@
//! - `report `: the coverage report, per mod ported, partial, not yet
//! or not needed with the reason, in `/coverage.json` and
//! `coverage.md`.
+//! - `check `: one mod jar on its own, as the launcher's mod
+//! browser installs it: carried over into `/carry/`, its classes
+//! read, and the verdict (Works, Partly, Doesn't run) in
+//! `/check.json`.
//! - `port [--from ] [--resources ]`: every
//! step for the portable mods, as the launcher's "Import modpack" runs it.
//!
@@ -30,7 +34,7 @@ use std::{
process::ExitCode,
};
-const USAGE: &str = "usage: horizon-port-pack import | inventory [--offline] | fetch [--from ] [...] | carry [--resources ] [...] | report | port [--from ] [--resources ]";
+const USAGE: &str = "usage: horizon-port-pack import | inventory [--offline] | fetch [--from ] [...] | carry [--resources ] [...] | report | check | port [--from ] [--resources ]";
fn main() -> ExitCode {
let mut args: Vec = std::env::args().skip(1).collect();
@@ -66,6 +70,17 @@ fn main() -> ExitCode {
println!("{}", work.join("coverage.md").display());
Ok(())
}
+ Some("check") => {
+ let c = horizon_port_pack::check::check(path(1)?, path(2)?)?;
+ println!("{}: {}. {}", c.mod_id, c.verdict.label(), c.summary);
+ for p in &c.ports {
+ println!(" ports: {p}");
+ }
+ for s in &c.skipped {
+ println!(" skipped: {s}");
+ }
+ Ok(())
+ }
Some("port") => {
let work = path(2)?;
pipeline::import(path(1)?, work, log)?;
diff --git a/crates/horizon-port-pack/src/pipeline.rs b/crates/horizon-port-pack/src/pipeline.rs
index 26744d7bd..c34f58411 100644
--- a/crates/horizon-port-pack/src/pipeline.rs
+++ b/crates/horizon-port-pack/src/pipeline.rs
@@ -150,7 +150,16 @@ pub fn carry(
})
.flatten()
.collect();
- let in_pack = |m: &str| in_pack.contains(m);
+ // A namespace two carried mods both claim (a library's they both use, such as YUNG's API's
+ // `yungsapi`, whose own jar isn't read) is neither's: either would refuse the other in the
+ // game. Its files stay outside both.
+ let claims = records.iter().filter(|r| chosen(r)).filter_map(|r| {
+ let (jar, info) = (r.jar.as_ref()?, r.info.as_ref()?);
+ let owned = carry::namespaces_claimed(jar, &info.mod_id, &|m| in_pack.contains(m)).ok()?;
+ Some((r.key.as_str(), owned))
+ });
+ let shared = shared_namespaces(claims, log);
+ let in_pack = |m: &str| in_pack.contains(m) || shared.contains(m);
let pack = carry::Pack {
loaded: &loaded,
mods: &in_pack,
@@ -219,6 +228,61 @@ pub fn carry(
Ok(done)
}
+/// Which carried-over mods (`mods//carry` folders) the game loads together, in the order
+/// given: as the game does, the first of two owning one namespace stays on. Returns the ones on,
+/// and a line for each one left off.
+pub fn loadable(mods: &[std::path::PathBuf]) -> (Vec, Vec) {
+ let mut on: Vec<(std::path::PathBuf, String, Vec)> = Vec::new();
+ let mut off = Vec::new();
+ for path in mods {
+ let manifest = fs::read_to_string(path.join(horizon_mods::manifest::MANIFEST))
+ .map_err(|e| e.to_string())
+ .and_then(|t| horizon_mods::Manifest::parse(&t));
+ let m = match manifest {
+ Ok(m) => m,
+ Err(e) => {
+ off.push(format!("{}: {e}", path.display()));
+ continue;
+ }
+ };
+ let owned: Vec = std::iter::once(m.id.clone())
+ .chain(m.namespaces.iter().cloned())
+ .collect();
+ let clash = on
+ .iter()
+ .find_map(|(_, id, ns)| horizon_mods::content::clash((id, ns), (&m.id, &owned)));
+ match clash {
+ Some(why) => off.push(format!("{} not loaded: {why}", m.id)),
+ None => on.push((path.clone(), m.id, owned)),
+ }
+ }
+ (on.into_iter().map(|(p, _, _)| p).collect(), off)
+}
+
+/// The namespaces more than one mod claims, from each mod's (key, claimed namespaces).
+fn shared_namespaces<'a>(
+ claims: impl Iterator- )>,
+ log: Log,
+) -> BTreeSet
{
+ let mut by_namespace: BTreeMap> = BTreeMap::new();
+ for (key, owned) in claims {
+ for ns in owned {
+ by_namespace.entry(ns).or_default().push(key);
+ }
+ }
+ by_namespace
+ .into_iter()
+ .filter(|(_, mods)| mods.len() > 1)
+ .map(|(ns, mods)| {
+ log(format!(
+ "namespace {ns} is claimed by {}: left to none of them",
+ mods.join(", ")
+ ));
+ ns
+ })
+ .collect()
+}
+
/// The pack's title as the report heads it.
pub fn title(pack: &import::Pack) -> String {
format!(
@@ -279,3 +343,51 @@ pub fn port(
}
Ok((fetched, report(work, log)?))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_namespace_two_mods_claim_is_neither_s() {
+ let claims = [
+ ("betterdungeons", vec!["yungsapi".to_owned()]),
+ ("betterfortresses", vec!["yungsapi".to_owned()]),
+ (
+ "towns_and_towers",
+ vec!["kaisyn".to_owned(), "towns_and_towers".to_owned()],
+ ),
+ ];
+ let shared = shared_namespaces(claims.into_iter(), &|_| {});
+ assert_eq!(shared.into_iter().collect::>(), ["yungsapi"]);
+ }
+
+ #[test]
+ fn the_first_of_two_mods_owning_a_namespace_loads() {
+ let root = std::env::temp_dir().join(format!("port-pack-loadable-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&root);
+ let carry = |key: &str, namespaces: &str| {
+ let dir = root.join(key).join("carry");
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(
+ dir.join("horizon-mod.toml"),
+ format!(
+ "id = \"{key}\"\nname = \"{key}\"\nversion = \"1\"\napi = \"0.2\"\n\
+ capabilities = [\"registries\"]\nnamespaces = [{namespaces}]\n"
+ ),
+ )
+ .unwrap();
+ dir
+ };
+ let mods = [
+ carry("betterdungeons", "\"yungsapi\""),
+ carry("betterfortresses", "\"yungsapi\""),
+ carry("ruby", ""),
+ ];
+ let (on, off) = loadable(&mods);
+ assert_eq!(on, [mods[0].clone(), mods[2].clone()]);
+ assert_eq!(off.len(), 1);
+ assert!(off[0].starts_with("betterfortresses not loaded"), "{off:?}");
+ fs::remove_dir_all(&root).unwrap();
+ }
+}
diff --git a/crates/horizon-telemetry-server/README.md b/crates/horizon-telemetry-server/README.md
index dc1f51248..ed54024a1 100644
--- a/crates/horizon-telemetry-server/README.md
+++ b/crates/horizon-telemetry-server/README.md
@@ -5,7 +5,7 @@ This server receives what players choose to send (performance summaries, crash a
cargo run --release # in this folder: its own workspace, like the launcher's
PORT=8080 HORIZON_TELEMETRY_DB=/data/telemetry.sqlite3 horizon-telemetry-server
-The launcher sends to it when `HORIZON_TELEMETRY_URL` is set (and to `DEFAULT_ENDPOINT` in `crates/horizon-telemetry` once there is one).
+It runs at **https://telemetry.playhorizon.dev** (`DEFAULT_ENDPOINT` in `crates/horizon-telemetry`). The game and the launcher use it unless `HORIZON_TELEMETRY_URL` names another server, or is `off` (tests and automated runs send nothing).
## Endpoints
@@ -14,11 +14,34 @@ The launcher sends to it when `HORIZON_TELEMETRY_URL` is set (and to `DEFAULT_EN
| `POST /v1/batch` | A zstd batch (`Content-Encoding: zstd`, at most 256 KiB, 1 MiB inflated, 64 items). Returns 204. Returns 400 for a bad batch, 413 for one too large, 415 if it is not zstd, 429 when over a limit. |
| `DELETE /v1/installs/` | Deletes everything that install sent. Its share of the daily totals is rebuilt at once. |
| `GET /v1/aggregate?days=30` | The totals the website reads. Cached 10 minutes, with `Access-Control-Allow-Origin` set to the website. |
+| `GET /v1/benchmarks/summary` | Players' benchmark uploads grouped by GPU, CPU, render distance and game, for the website's Benchmarks page (below). Cached 10 minutes, same `Access-Control-Allow-Origin`. |
| `POST /v1/live` | A game's "I'm playing" ping (JSON, at most 512 bytes). Returns 204. Returns 400 for a bad ping, 413 for one too large, 429 over the address's limit, 503 when it holds `LIVE_MAX_SESSIONS` already. |
| `GET /v1/live` | How many play now, rounded: `playing`, `lan`, `versions`, `platforms`. Made again at most every 15 seconds, with the same `Access-Control-Allow-Origin`. |
| `GET /healthz` | `ok` |
-The totals are grouped per version, OS, GPU vendor and render distance. Each group has its sessions, install-days, hours played, the 14 frame-time buckets summed, and the mean p50 and p99 frame times. Groups with fewer than 5 install-days are left out. The totals also list crash counts per version and the newest 50 benchmark uploads.
+The totals are grouped per version, OS, GPU vendor and render distance. Each group has its sessions, install-days, hours played, the 14 frame-time buckets summed, and the mean p50 and p99 frame times. Groups with fewer than 5 install-days are left out. The totals also list crash counts per version. Benchmark uploads are published only through the summary below, never one by one.
+
+## Benchmarks summary
+
+`src/summary.rs` makes it with the same rules as `website/scripts/benchmarks.mjs`, which bakes the page's fallback copy; both are tested against the same fixtures (`website/scripts/fixtures/benchmarks/`).
+
+- Only reports that compare: a version 1 `horizon-benchmark-report` of the standard flight over the four scenes, VSync off, no frame cap, on screen, from Horizon or plain vanilla, naming its GPU and CPU.
+- A group (GPU, CPU, render distance, game) is published only with **at least 3 different installs**. Each install counts once: the median of its runs, then the median across installs.
+- Out go the names, the counts, the newest three versions and the medians. Never an install ID, a day, an OS version, a driver, a memory size or a screen.
+
+```json
+{
+ "format": "horizon-benchmark-summary", "version": 1, "generated": "2026-10-22T20:00:00Z", "min_installs": 3,
+ "groups": [{
+ "gpu": "NVIDIA GeForce RTX 4080", "cpu": "13th Gen Intel Core i7-13700KF", "render_distance": 12,
+ "game": "horizon", "source": "players", "installs": 3, "reports": 4, "versions": ["v0.2.1", "v0.2.0"],
+ "medians": { "avg_fps": 515, "low_1pct_fps": 120, "p95_ms": 3.5, "world_ms": 4500,
+ "chunk_load_ms": 1400, "rss_peak_mb": 1450, "rss_steady_mb": 1250 }
+ }]
+}
+```
+
+Frame rates are whole numbers, milliseconds have one decimal under 10, megabytes are whole. Groups come most installs first. A deleted install leaves its groups at once.
## Storage
@@ -45,7 +68,7 @@ All are environment variables:
- `HORIZON_TELEMETRY_MIN_INSTALL_DAYS` (5)
- `HORIZON_TELEMETRY_REQUESTS_PER_HOUR` per address (60, bursts of 6)
- `HORIZON_TELEMETRY_ITEMS_PER_DAY` per install (100)
-- `HORIZON_TELEMETRY_TRUST_PROXY=1` behind a proxy (the client's address is then the first of `X-Forwarded-For`)
+- `HORIZON_TELEMETRY_TRUST_PROXY=1` behind a proxy (the client's address is then the proxy's `X-Real-IP`, else the last `X-Forwarded-For` entry; it is used only for the rate limits, in memory, and never stored or logged)
- `HORIZON_TELEMETRY_ALLOW_ORIGIN` (`https://playhorizon.dev`)
- `HORIZON_TELEMETRY_LIVE_PER_HOUR` per address, pings and reads (600, bursts of 60: ten players behind one address)
- `HORIZON_TELEMETRY_LIVE_WINDOW_SECONDS` (120)
@@ -55,6 +78,14 @@ All are environment variables:
`Dockerfile` builds it from the repository root (`docker build -f crates/horizon-telemetry-server/Dockerfile .`). The database goes on a volume mounted at `/data`.
+On Railway it is a service of the same project as the website:
+
+- Source: this repository, root directory `/` (the Dockerfile needs the shared crate), config file `/crates/horizon-telemetry-server/railway.json` (Dockerfile build, health check `/healthz`, one replica in `europe-west4`, Amsterdam: one SQLite file can't be shared).
+- A volume mounted at `/data`. The Dockerfile already sets `HORIZON_TELEMETRY_DB=/data/telemetry.sqlite3` and `HORIZON_TELEMETRY_TRUST_PROXY=1`; Railway sets `PORT`.
+- The custom domain `telemetry.playhorizon.dev`: a `CNAME` at Porkbun to the target Railway gives.
+
+Check it with `curl https://telemetry.playhorizon.dev/healthz`.
+
At Railway's prices (RAM $10/GB-month, CPU $20/vCPU-month, volumes $0.15/GB-month, egress $0.05/GB), one more service with a 1 GB volume uses about $0.35 a month:
- RAM about 15 MB: $0.15
diff --git a/crates/horizon-telemetry-server/railway.json b/crates/horizon-telemetry-server/railway.json
new file mode 100644
index 000000000..30eb18c33
--- /dev/null
+++ b/crates/horizon-telemetry-server/railway.json
@@ -0,0 +1,21 @@
+{
+ "$schema": "https://railway.com/railway.schema.json",
+ "build": {
+ "builder": "DOCKERFILE",
+ "dockerfilePath": "crates/horizon-telemetry-server/Dockerfile",
+ "watchPatterns": [
+ "/crates/horizon-telemetry/**",
+ "/crates/horizon-telemetry-server/**",
+ "/Cargo.toml"
+ ]
+ },
+ "deploy": {
+ "healthcheckPath": "/healthz",
+ "healthcheckTimeout": 60,
+ "restartPolicyType": "ON_FAILURE",
+ "restartPolicyMaxRetries": 5,
+ "multiRegionConfig": {
+ "europe-west4-drams3a": { "numReplicas": 1 }
+ }
+ }
+}
diff --git a/crates/horizon-telemetry-server/src/lib.rs b/crates/horizon-telemetry-server/src/lib.rs
index 061a9ca37..c00002531 100644
--- a/crates/horizon-telemetry-server/src/lib.rs
+++ b/crates/horizon-telemetry-server/src/lib.rs
@@ -3,6 +3,8 @@
//! - `POST /v1/batch`: a zstd batch from the launcher, checked by `horizon_telemetry::batch`.
//! - `DELETE /v1/installs/`: everything an install sent goes.
//! - `GET /v1/aggregate?days=30`: the anonymous totals the website reads, cached.
+//! - `GET /v1/benchmarks/summary`: players' benchmark results grouped by GPU and CPU, groups of at
+//! least 3 installs only (`summary`), cached; the website's Benchmarks page reads it.
//! - `POST /v1/live`: a game's anonymous "I'm playing" ping (`live`, in memory only).
//! - `GET /v1/live`: how many play now, rounded, cached briefly.
//! - `GET /healthz`.
@@ -26,6 +28,7 @@ use horizon_telemetry::batch;
pub mod live;
pub mod store;
+pub mod summary;
use horizon_telemetry::live::{MAX_PING_BYTES, Ping};
use live::Live;
@@ -40,7 +43,8 @@ pub struct Config {
pub requests_per_hour: f64,
/// Items one install may send a day.
pub items_per_day: u32,
- /// Behind a proxy (Railway, Fly…): the client's address is the first of X-Forwarded-For.
+ /// Behind a proxy (Railway, Fly…): the client's address is the proxy's `X-Real-IP`, else the
+ /// last `X-Forwarded-For` entry.
pub trust_proxy: bool,
/// The website allowed to read the totals from a browser.
pub allow_origin: String,
@@ -117,6 +121,8 @@ pub struct App {
live_cache: Mutex>,
/// `/v1/aggregate` answers by `days`, with when they were made.
cache: Mutex>,
+ /// `/v1/benchmarks/summary`'s answer and when it was made.
+ summary_cache: Mutex>,
/// Today, in days since 1970 (a test moves it).
today: Box u32 + Send + Sync>,
}
@@ -148,6 +154,7 @@ impl App {
live: Mutex::new(live),
live_cache: Mutex::default(),
cache: Mutex::default(),
+ summary_cache: Mutex::default(),
today,
})
}
@@ -170,20 +177,26 @@ impl App {
self.live.lock().unwrap_or_else(|e| e.into_inner())
}
+ /// The address requests are counted under, for the rate limits only: kept in memory, never
+ /// stored or logged. Behind a proxy (Railway) the TCP peer is the proxy, so it is the proxy's
+ /// `X-Real-IP`, else the last `X-Forwarded-For` entry: the one the proxy added, which a client
+ /// can't choose (the first one it can).
fn client(&self, headers: &HeaderMap, peer: Option) -> IpAddr {
+ let header = |name: &str| headers.get(name)?.to_str().ok();
let forwarded = self
.config
.trust_proxy
.then(|| {
- headers
- .get("x-forwarded-for")?
- .to_str()
- .ok()?
- .split(',')
- .next()?
- .trim()
- .parse()
- .ok()
+ header("x-real-ip")
+ .and_then(|ip| ip.trim().parse().ok())
+ .or_else(|| {
+ header("x-forwarded-for")?
+ .rsplit(',')
+ .next()?
+ .trim()
+ .parse()
+ .ok()
+ })
})
.flatten();
forwarded
@@ -196,6 +209,12 @@ impl App {
self.store().newest_day(install).ok().flatten()
}
+ /// Drops the cached public answers (after a deletion or expiry).
+ fn forget_cached(&self) {
+ self.cache.lock().unwrap_or_else(|e| e.into_inner()).clear();
+ *self.summary_cache.lock().unwrap_or_else(|e| e.into_inner()) = None;
+ }
+
/// Daily upkeep: totals rebuilt, expired rows removed, idle rate-limit entries and live
/// sessions forgotten.
pub fn maintain(&self) -> rusqlite::Result {
@@ -209,7 +228,7 @@ impl App {
}
self.live().forget_expired(Instant::now());
if removed > 0 {
- self.cache.lock().unwrap_or_else(|e| e.into_inner()).clear();
+ self.forget_cached();
}
Ok(removed)
}
@@ -288,7 +307,7 @@ async fn forget(State(app): State>, Path(id): Path, req: Reques
};
match app.store().delete_install(&install) {
Ok(_) => {
- app.cache.lock().unwrap_or_else(|e| e.into_inner()).clear();
+ app.forget_cached();
StatusCode::NO_CONTENT.into_response()
}
Err(e) => {
@@ -338,6 +357,60 @@ async fn aggregate(State(app): State>, Query(window): Query) ->
json_response(&app, json, CACHE_FOR.as_secs())
}
+/// `GET /v1/benchmarks/summary`: players' benchmark groups (`summary`), made again at most every
+/// ten minutes.
+async fn benchmarks(State(app): State>) -> Response {
+ let cached = app
+ .summary_cache
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .as_ref()
+ .filter(|(at, _)| at.elapsed() < CACHE_FOR)
+ .map(|(_, json)| json.clone());
+ let json = match cached {
+ Some(json) => json,
+ None => {
+ let oldest = (app.today)().saturating_sub(app.config.retention_days);
+ let uploads = match app.store().benchmark_uploads(oldest) {
+ Ok(uploads) => uploads,
+ Err(e) => {
+ eprintln!("horizon-telemetry-server: could not read the benchmarks: {e}");
+ return status(StatusCode::SERVICE_UNAVAILABLE, "try again later");
+ }
+ };
+ let json = summary::summary(&uploads, summary::MIN_INSTALLS, &utc_now()).to_string();
+ *app.summary_cache.lock().unwrap_or_else(|e| e.into_inner()) =
+ Some((Instant::now(), json.clone()));
+ json
+ }
+ };
+ json_response(&app, json, CACHE_FOR.as_secs())
+}
+
+/// Now as `YYYY-MM-DDTHH:MM:SSZ`.
+fn utc_now() -> String {
+ let secs = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_or(0, |d| d.as_secs());
+ let (days, rest) = (secs / 86_400, secs % 86_400);
+ // Days since 1970 to a civil date (Howard Hinnant's algorithm).
+ let z = days as i64 + 719_468;
+ let era = z.div_euclid(146_097);
+ let doe = z - era * 146_097;
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let day = doy - (153 * mp + 2) / 5 + 1;
+ let month = if mp < 10 { mp + 3 } else { mp - 9 };
+ let year = yoe + era * 400 + i64::from(month <= 2);
+ format!(
+ "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
+ rest / 3600,
+ rest / 60 % 60,
+ rest % 60
+ )
+}
+
/// `POST /v1/live`: one "I'm playing". 204, or 400 for a bad ping, 413 for one too large, 429
/// over the address's limit, 503 when the table is full.
async fn ping(State(app): State>, req: Request) -> Response {
@@ -407,6 +480,7 @@ pub fn router(app: Arc) -> Router {
.route("/v1/live", post(ping).get(playing))
.route("/v1/installs/{id}", delete(forget))
.route("/v1/aggregate", get(aggregate))
+ .route("/v1/benchmarks/summary", get(benchmarks))
.route("/healthz", get(|| async { "ok" }))
.with_state(app)
}
diff --git a/crates/horizon-telemetry-server/src/store.rs b/crates/horizon-telemetry-server/src/store.rs
index 0bac20e50..5188657ee 100644
--- a/crates/horizon-telemetry-server/src/store.rs
+++ b/crates/horizon-telemetry-server/src/store.rs
@@ -357,27 +357,33 @@ impl Store {
})?
.collect::>()?
};
- let benchmarks: Vec = {
- let mut q = self.db.prepare(
- "SELECT day, version, body FROM reports WHERE kind = ?1 AND day BETWEEN ?2 AND ?3
- ORDER BY rowid DESC LIMIT 50",
- )?;
- q.query_map(params![kind_code(Kind::Benchmark), from, to], |r| {
- let body: Vec = r.get(2)?;
- Ok(serde_json::json!({
- "day": r.get::<_, u32>(0)?, "version": r.get::<_, String>(1)?, "report": inflate(&body),
- }))
- })?
- .collect::>()?
- };
Ok(serde_json::json!({
"from_day": from, "to_day": to, "min_install_days": k,
"bucket_edges_ms": BUCKET_EDGES_MS.map(|e| (f64::from(e) * 10.0).round() / 10.0),
"totals": { "sessions": sessions, "hours": (hours * 10.0).round() / 10.0 },
- "groups": out, "crashes_by_version": crashes, "benchmarks": benchmarks,
+ "groups": out, "crashes_by_version": crashes,
}))
}
+ /// Every benchmark upload received since `from_day`, with its install (to count installs, never shown)
+ /// and release, for `summary`.
+ pub fn benchmark_uploads(
+ &self,
+ from_day: u32,
+ ) -> rusqlite::Result> {
+ let mut q = self
+ .db
+ .prepare("SELECT install, version, body FROM reports WHERE kind = ?1 AND day >= ?2")?;
+ q.query_map(params![kind_code(Kind::Benchmark), from_day], |r| {
+ Ok(crate::summary::Upload {
+ install: r.get(0)?,
+ version: r.get(1)?,
+ report: inflate(&r.get::<_, Vec>(2)?),
+ })
+ })?
+ .collect()
+ }
+
/// The day an install's newest row came in, if any (tests, and checking a deletion).
pub fn newest_day(&self, install: &[u8]) -> rusqlite::Result> {
self.db
diff --git a/crates/horizon-telemetry-server/src/summary.rs b/crates/horizon-telemetry-server/src/summary.rs
new file mode 100644
index 000000000..6cec9200e
--- /dev/null
+++ b/crates/horizon-telemetry-server/src/summary.rs
@@ -0,0 +1,266 @@
+//! `GET /v1/benchmarks/summary`: players' benchmark uploads, grouped for the website's Benchmarks page.
+//!
+//! The same rules as `website/scripts/benchmarks.mjs` (which builds the page's baked copy), checked against the
+//! same fixtures (`website/scripts/fixtures/benchmarks/`):
+//!
+//! - Only reports that compare: `horizon-benchmark-report` version 1, kind `game`, Horizon or plain vanilla, the
+//! standard flight over the four scenes, VSync off, no frame cap, drawn on a screen, with a GPU and CPU name.
+//! - Groups by GPU, CPU, render distance and game. A group is published only with at least `min_installs`
+//! different installs, so no one can be picked out.
+//! - Each install counts once: the median of its runs first, then the median across installs.
+//! - Out go the group's names, its counts, the newest three versions and the medians. Never the install ID, the
+//! day, the OS version, the driver, the memory size or the screen.
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+
+use serde_json::{Value, json};
+
+pub const FORMAT: &str = "horizon-benchmark-summary";
+pub const MIN_INSTALLS: usize = 3;
+pub const SCENES: [&str; 4] = ["village", "forest", "ocean", "mountain"];
+pub const FIELDS: [&str; 7] = [
+ "avg_fps",
+ "low_1pct_fps",
+ "p95_ms",
+ "world_ms",
+ "chunk_load_ms",
+ "rss_peak_mb",
+ "rss_steady_mb",
+];
+
+/// One stored upload: who sent it (only to count installs), the release, and the report.
+pub struct Upload {
+ pub install: Vec,
+ pub version: String,
+ pub report: Value,
+}
+
+/// "Intel(R) Core(TM) i7" -> "Intel Core i7", spaces collapsed.
+fn trim(s: &str) -> String {
+ s.replace("(R)", "")
+ .replace("(TM)", "")
+ .replace("(tm)", "")
+ .split_whitespace()
+ .collect::>()
+ .join(" ")
+}
+
+fn game(app: &Value) -> Option<&'static str> {
+ match app.get("name").and_then(Value::as_str) {
+ Some("horizon-client") => Some("horizon"),
+ Some("minecraft") => {
+ let mods = app.get("mods").and_then(Value::as_array);
+ let plain = mods.is_none_or(|m| {
+ m.iter()
+ .all(|m| m.get("name").and_then(Value::as_str) == Some("fabric-loader"))
+ });
+ plain.then_some("vanilla")
+ }
+ _ => None,
+ }
+}
+
+/// Why a report can't be compared with the others, or `None` when it can.
+pub fn rejection(report: &Value) -> Option<&'static str> {
+ if report.get("format").and_then(Value::as_str) != Some("horizon-benchmark-report")
+ || report.get("version").and_then(Value::as_u64) != Some(1)
+ {
+ return Some("not a version 1 benchmark report");
+ }
+ if report.get("kind").and_then(Value::as_str) != Some("game") {
+ return Some("not a game run");
+ }
+ game(&report["app"])?;
+ let c = &report["conditions"];
+ let scenario = c.get("scenario").and_then(Value::as_str).unwrap_or("");
+ if !(scenario == "standard" || scenario == "flight" || scenario.starts_with("perf_bench:")) {
+ return Some("not the standard flight");
+ }
+ if c.get("vsync") != Some(&Value::Bool(false)) {
+ return Some("VSync on or unknown");
+ }
+ if c.get("fps_cap").is_some_and(|v| !v.is_null()) {
+ return Some("frame rate capped");
+ }
+ if c.get("offscreen") == Some(&Value::Bool(true)) {
+ return Some("offscreen");
+ }
+ if !c.get("render_distance").is_some_and(Value::is_number) {
+ return Some("no render distance");
+ }
+ let phases: BTreeSet<&str> = report["frames"]
+ .as_array()
+ .map(|f| f.iter().filter_map(|f| f["phase"].as_str()).collect())
+ .unwrap_or_default();
+ if !SCENES.iter().all(|s| phases.contains(s)) {
+ return Some("not every scene");
+ }
+ let named = |v: &Value| v.as_str().is_some_and(|s| !trim(s).is_empty());
+ if !named(&report["hardware"]["gpu"]["name"]) || !named(&report["hardware"]["cpu"]) {
+ return Some("no GPU or CPU name");
+ }
+ None
+}
+
+fn mean(xs: &[f64]) -> Option {
+ (!xs.is_empty()).then(|| xs.iter().sum::() / xs.len() as f64)
+}
+
+pub fn median(xs: &[f64]) -> Option {
+ let mut v: Vec = xs.iter().copied().filter(|x| x.is_finite()).collect();
+ if v.is_empty() {
+ return None;
+ }
+ v.sort_by(f64::total_cmp);
+ let m = v.len() / 2;
+ Some(if v.len() % 2 == 1 {
+ v[m]
+ } else {
+ (v[m - 1] + v[m]) / 2.0
+ })
+}
+
+/// fps to integers, milliseconds to a tenth under 10 and to integers above, megabytes to integers.
+pub fn round(field: &str, x: f64) -> f64 {
+ if field.ends_with("_ms") && x < 10.0 {
+ (x * 10.0).round() / 10.0
+ } else {
+ x.round()
+ }
+}
+
+/// Whole numbers as integers (`515`, not `515.0`), as JavaScript writes them.
+fn number(x: f64) -> Value {
+ if x.fract() == 0.0 && x.abs() < 9e15 {
+ json!(x as i64)
+ } else {
+ json!(x)
+ }
+}
+
+/// A report's figures: frame figures averaged over every flight, the rest from its metrics.
+pub fn figures(report: &Value) -> [Option; 7] {
+ let frames = report["frames"]
+ .as_array()
+ .map(Vec::as_slice)
+ .unwrap_or(&[]);
+ let avg = |key: &str| {
+ mean(
+ &frames
+ .iter()
+ .filter_map(|f| f[key].as_f64())
+ .collect::>(),
+ )
+ };
+ let metrics = report["metrics"].as_object();
+ let metric = |name: &str| metrics.and_then(|m| m.get(name)?.get("mean")?.as_f64());
+ let loads: Vec = metrics
+ .map(|m| {
+ m.iter()
+ .filter(|(k, _)| {
+ k.strip_prefix("chunks.")
+ .and_then(|k| k.strip_suffix(".load_ms"))
+ .is_some_and(|scene| !scene.contains('.'))
+ })
+ .filter_map(|(_, v)| v.get("mean")?.as_f64())
+ .collect()
+ })
+ .unwrap_or_default();
+ [
+ avg("avg_fps"),
+ avg("low_1pct_fps"),
+ avg("p95_ms"),
+ metric("startup.world_ms"),
+ mean(&loads),
+ metric("memory.rss_peak_mb"),
+ metric("memory.rss_steady_mb"),
+ ]
+}
+
+/// "v0.2.10" after "v0.2.9", dated tags by their numbers: newest first.
+fn newest_first(a: &str, b: &str) -> std::cmp::Ordering {
+ let n = |v: &str| -> Vec {
+ v.split(|c: char| !c.is_ascii_digit())
+ .filter(|p| !p.is_empty())
+ .filter_map(|p| p.parse().ok())
+ .collect()
+ };
+ n(b).cmp(&n(a))
+}
+
+#[derive(Default)]
+struct Group {
+ installs: HashMap, Vec<[Option; 7]>>,
+ reports: usize,
+ versions: BTreeSet,
+}
+
+/// Players' groups of at least `min_installs` installs, as `website/scripts/benchmarks.mjs` makes them.
+pub fn groups(uploads: &[Upload], min_installs: usize) -> Vec {
+ let mut by: BTreeMap<(String, String, i64, &str), Group> = BTreeMap::new();
+ for u in uploads {
+ if u.install.is_empty() || rejection(&u.report).is_some() {
+ continue;
+ }
+ let r = &u.report;
+ let key = (
+ trim(r["hardware"]["gpu"]["name"].as_str().unwrap_or_default()),
+ trim(r["hardware"]["cpu"].as_str().unwrap_or_default()),
+ r["conditions"]["render_distance"]
+ .as_f64()
+ .unwrap_or_default() as i64,
+ game(&r["app"]).unwrap_or_default(),
+ );
+ let g = by.entry(key).or_default();
+ g.reports += 1;
+ if !u.version.is_empty() {
+ g.versions.insert(u.version.clone());
+ }
+ g.installs
+ .entry(u.install.clone())
+ .or_default()
+ .push(figures(r));
+ }
+ let mut out: Vec<(usize, Value)> = by
+ .into_iter()
+ .filter(|(_, g)| g.installs.len() >= min_installs)
+ .map(|((gpu, cpu, rd, game), g)| {
+ let per_install: Vec<[Option; 7]> = g
+ .installs
+ .values()
+ .map(|runs| {
+ std::array::from_fn(|i| median(&runs.iter().filter_map(|r| r[i]).collect::>()))
+ })
+ .collect();
+ let medians: serde_json::Map = FIELDS
+ .iter()
+ .enumerate()
+ .map(|(i, f)| {
+ let m = median(&per_install.iter().filter_map(|r| r[i]).collect::>());
+ (f.to_string(), m.map_or(Value::Null, |m| number(round(f, m))))
+ })
+ .collect();
+ let mut versions: Vec = g.versions.into_iter().collect();
+ versions.sort_by(|a, b| newest_first(a, b));
+ versions.truncate(3);
+ let installs = g.installs.len();
+ (
+ installs,
+ json!({
+ "gpu": gpu, "cpu": cpu, "render_distance": rd, "game": game, "source": "players",
+ "installs": installs, "reports": g.reports, "versions": versions, "medians": medians,
+ }),
+ )
+ })
+ .collect();
+ // Most installs first, then by GPU and render distance (the map's order).
+ out.sort_by_key(|g| std::cmp::Reverse(g.0));
+ out.into_iter().map(|(_, v)| v).collect()
+}
+
+/// The whole answer; `generated` is an RFC 3339 UTC time.
+pub fn summary(uploads: &[Upload], min_installs: usize, generated: &str) -> Value {
+ json!({
+ "format": FORMAT, "version": 1, "generated": generated, "min_installs": min_installs,
+ "groups": groups(uploads, min_installs),
+ })
+}
diff --git a/crates/horizon-telemetry-server/tests/server.rs b/crates/horizon-telemetry-server/tests/server.rs
index f8c78f085..5d5b17b6a 100644
--- a/crates/horizon-telemetry-server/tests/server.rs
+++ b/crates/horizon-telemetry-server/tests/server.rs
@@ -198,14 +198,30 @@ async fn an_address_is_rate_limited() {
s.post(&install(9), vec![perf("x", 8)]).await,
StatusCode::TOO_MANY_REQUESTS
);
+ let from = |forwarded: &str, real: Option<&str>| {
+ let body = batch::encode(&Batch::new(&install(9), vec![perf("x", 8)]));
+ let mut req = Request::post("/v1/batch")
+ .header("x-forwarded-for", forwarded)
+ .header("content-encoding", "zstd");
+ if let Some(ip) = real {
+ req = req.header("x-real-ip", ip);
+ }
+ req.body(Body::from(body)).unwrap()
+ };
+ // A client can't pick its address: the proxy adds the real one last, or sets X-Real-IP.
+ assert_eq!(
+ s.send(from("198.51.100.7, 203.0.113.9", None)).await.0,
+ StatusCode::TOO_MANY_REQUESTS
+ );
+ assert_eq!(
+ s.send(from("198.51.100.7", Some("203.0.113.9"))).await.0,
+ StatusCode::TOO_MANY_REQUESTS
+ );
// Another address has its own allowance.
- let body = batch::encode(&Batch::new(&install(9), vec![perf("x", 8)]));
- let req = Request::post("/v1/batch")
- .header("x-forwarded-for", "198.51.100.7, 10.0.0.1")
- .header("content-encoding", "zstd")
- .body(Body::from(body))
- .unwrap();
- assert_eq!(s.send(req).await.0, StatusCode::NO_CONTENT);
+ assert_eq!(
+ s.send(from("203.0.113.9, 198.51.100.7", None)).await.0,
+ StatusCode::NO_CONTENT
+ );
}
#[tokio::test]
diff --git a/crates/horizon-telemetry-server/tests/summary.rs b/crates/horizon-telemetry-server/tests/summary.rs
new file mode 100644
index 000000000..5a59aa8a1
--- /dev/null
+++ b/crates/horizon-telemetry-server/tests/summary.rs
@@ -0,0 +1,180 @@
+//! `GET /v1/benchmarks/summary` against the website's fixtures (website/scripts/fixtures/benchmarks/): the same
+//! uploads must give the groups `website/scripts/benchmarks.mjs` gives.
+use std::sync::Arc;
+use std::sync::atomic::AtomicU32;
+
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use horizon_telemetry::Item;
+use horizon_telemetry::batch::{self, Batch};
+use horizon_telemetry::payload::{Payload, Source};
+use horizon_telemetry_server::store::Store;
+use horizon_telemetry_server::summary::{self, Upload};
+use horizon_telemetry_server::{App, Config, router};
+use http_body_util::BodyExt;
+use serde_json::Value;
+use tower::ServiceExt;
+
+const FIXTURES: &str = concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/../../website/scripts/fixtures/benchmarks"
+);
+
+fn items() -> Vec {
+ std::fs::read_to_string(format!("{FIXTURES}/items.jsonl"))
+ .unwrap()
+ .lines()
+ .filter(|l| !l.trim().is_empty())
+ .map(|l| serde_json::from_str(l).unwrap())
+ .collect()
+}
+
+fn expected() -> Value {
+ serde_json::from_str(&std::fs::read_to_string(format!("{FIXTURES}/expected.json")).unwrap())
+ .unwrap()
+}
+
+/// The fixtures' short install names as the 32 hex digits real installs have.
+fn install_id(name: &str) -> String {
+ format!(
+ "{:032x}",
+ name.bytes().fold(0u128, |n, b| n * 257 + u128::from(b))
+ )
+}
+
+#[test]
+fn the_fixtures_give_the_websites_groups() {
+ let uploads: Vec = items()
+ .into_iter()
+ .map(|i| Upload {
+ install: i["install_id"]
+ .as_str()
+ .unwrap_or_default()
+ .as_bytes()
+ .to_vec(),
+ version: i["version"].as_str().unwrap_or_default().to_owned(),
+ report: i["data"].clone(),
+ })
+ .collect();
+ let s = summary::summary(&uploads, summary::MIN_INSTALLS, "2026-11-03T00:00:00Z");
+ let want = expected();
+ assert_eq!(s["format"], "horizon-benchmark-summary");
+ assert_eq!(s["version"], 1);
+ assert_eq!(s["min_installs"], want["min_installs"]);
+ assert_eq!(s["groups"], want["groups"]);
+}
+
+#[test]
+fn only_comparable_runs_count() {
+ let reasons: Vec<&str> = items()
+ .iter()
+ .filter_map(|i| summary::rejection(&i["data"]))
+ .collect();
+ assert_eq!(
+ reasons,
+ [
+ "VSync on or unknown",
+ "offscreen",
+ "frame rate capped",
+ "not every scene",
+ "not the standard flight",
+ "not a version 1 benchmark report"
+ ]
+ );
+}
+
+#[test]
+fn medians_and_rounding() {
+ assert_eq!(summary::median(&[3.0, 1.0, 2.0]), Some(2.0));
+ assert_eq!(summary::median(&[4.0, 1.0, 2.0, 3.0]), Some(2.5));
+ assert_eq!(summary::median(&[f64::NAN]), None);
+ assert_eq!(summary::round("p95_ms", 3.46), 3.5);
+ assert_eq!(summary::round("world_ms", 4512.4), 4512.0);
+ assert_eq!(summary::round("avg_fps", 99.5), 100.0);
+}
+
+async fn get(app: &Arc, uri: &str) -> (StatusCode, String, Option) {
+ let res = router(app.clone())
+ .oneshot(Request::get(uri).body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+ let code = res.status();
+ let origin = res
+ .headers()
+ .get("access-control-allow-origin")
+ .map(|v| v.to_str().unwrap().to_owned());
+ let body = res.into_body().collect().await.unwrap().to_bytes();
+ (code, String::from_utf8_lossy(&body).into_owned(), origin)
+}
+
+/// Uploaded through `POST /v1/batch` as the launcher sends them, then read back from the endpoint.
+#[tokio::test]
+async fn uploads_come_back_grouped_and_anonymous() {
+ let day = Arc::new(AtomicU32::new(20_396));
+ let clock = day.clone();
+ let config = Config {
+ requests_per_hour: 1e6,
+ ..Config::default()
+ };
+ let app = App::with_clock(
+ Store::open(":memory:").unwrap(),
+ config,
+ Box::new(move || clock.load(std::sync::atomic::Ordering::SeqCst)),
+ );
+ for i in items() {
+ let Some(name) = i["install_id"].as_str() else {
+ continue; // an item without an install can't be sent
+ };
+ let item = Item::new(
+ Source::Game,
+ i["version"].as_str().unwrap(),
+ Payload::Benchmark(i["data"].clone()),
+ );
+ let body = batch::encode(&Batch::new(&install_id(name), vec![item]));
+ let res = router(app.clone())
+ .oneshot(
+ Request::post("/v1/batch")
+ .header("content-encoding", "zstd")
+ .body(Body::from(body))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(res.status(), StatusCode::NO_CONTENT, "{name}");
+ }
+
+ let (code, body, origin) = get(&app, "/v1/benchmarks/summary").await;
+ assert_eq!(code, StatusCode::OK);
+ assert_eq!(origin.as_deref(), Some("https://playhorizon.dev"));
+ let s: Value = serde_json::from_str(&body).unwrap();
+ assert_eq!(s["groups"], expected()["groups"]);
+ let generated = s["generated"].as_str().unwrap();
+ assert!(
+ generated.len() == 20 && generated.ends_with('Z'),
+ "{generated}"
+ );
+ for secret in [
+ install_id("a1").as_str(),
+ "install_id",
+ "secret-os-version",
+ "secret-driver",
+ "20394",
+ "ram_mb",
+ ] {
+ assert!(!body.contains(secret), "{secret} in {body}");
+ }
+
+ // Deleting one of the three installs takes the group below three: it goes at once.
+ let res = router(app.clone())
+ .oneshot(
+ Request::delete(format!("/v1/installs/{}", install_id("a3")))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(res.status(), StatusCode::NO_CONTENT);
+ let (_, body, _) = get(&app, "/v1/benchmarks/summary").await;
+ let s: Value = serde_json::from_str(&body).unwrap();
+ assert_eq!(s["groups"], serde_json::json!([]));
+}
diff --git a/crates/horizon-telemetry/src/lib.rs b/crates/horizon-telemetry/src/lib.rs
index 8d2840a08..018c13df8 100644
--- a/crates/horizon-telemetry/src/lib.rs
+++ b/crates/horizon-telemetry/src/lib.rs
@@ -33,16 +33,21 @@ pub const SCHEMA: u32 = 1;
/// and until the player answers nothing new is kept or sent.
pub const CONSENT_VERSION: u32 = 1;
-/// The ingest server, or none while there isn't one: then nothing is ever sent (no ping either)
-/// and the outbox stays within its caps. `HORIZON_TELEMETRY_URL` overrides it (tests, a local
-/// server).
-pub const DEFAULT_ENDPOINT: Option<&str> = None;
+/// The ingest server (`crates/horizon-telemetry-server`, on Railway). `HORIZON_TELEMETRY_URL`
+/// overrides it (a local server); `HORIZON_TELEMETRY_URL=off` sends nothing at all, no ping
+/// either (tests and automated runs). What is sent still depends on the player's switches.
+pub const DEFAULT_ENDPOINT: &str = "https://telemetry.playhorizon.dev";
/// Where items are sent, if anywhere.
pub fn endpoint() -> Option {
- match std::env::var("HORIZON_TELEMETRY_URL") {
- Ok(url) if !url.trim().is_empty() => Some(url.trim().trim_end_matches('/').to_owned()),
- _ => DEFAULT_ENDPOINT.map(str::to_owned),
+ resolve(std::env::var("HORIZON_TELEMETRY_URL").ok().as_deref())
+}
+
+fn resolve(var: Option<&str>) -> Option {
+ match var.map(str::trim) {
+ Some("off" | "none" | "0") => None,
+ Some(url) if !url.is_empty() => Some(url.trim_end_matches('/').to_owned()),
+ _ => Some(DEFAULT_ENDPOINT.to_owned()),
}
}
@@ -100,3 +105,20 @@ pub(crate) mod test_home {
dir
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_endpoint_defaults_to_the_server_and_can_be_moved_or_turned_off() {
+ assert_eq!(resolve(None).as_deref(), Some(DEFAULT_ENDPOINT));
+ assert_eq!(resolve(Some(" ")).as_deref(), Some(DEFAULT_ENDPOINT));
+ assert_eq!(
+ resolve(Some("http://127.0.0.1:8080/")).as_deref(),
+ Some("http://127.0.0.1:8080")
+ );
+ assert_eq!(resolve(Some("off")), None);
+ assert!(DEFAULT_ENDPOINT.starts_with("https://") && !DEFAULT_ENDPOINT.ends_with('/'));
+ }
+}
diff --git a/crates/horizon-theme/Cargo.toml b/crates/horizon-theme/Cargo.toml
index a2fc2eead..3cc6d2324 100644
--- a/crates/horizon-theme/Cargo.toml
+++ b/crates/horizon-theme/Cargo.toml
@@ -3,6 +3,6 @@ name = "horizon-theme"
version = "0.1.0"
edition = "2021"
license = "MIT"
-description = "Horizon's design tokens and fonts, shared by the launcher and the game's menus"
+description = "Horizon's design tokens, fonts and icons, shared by the launcher, the website and the game's menus"
[dependencies]
diff --git a/crates/horizon-theme/fonts/OFL-PixelifySans.txt b/crates/horizon-theme/fonts/OFL-PixelifySans.txt
new file mode 100644
index 000000000..6aa5bfbae
--- /dev/null
+++ b/crates/horizon-theme/fonts/OFL-PixelifySans.txt
@@ -0,0 +1,93 @@
+Copyright 2021 The Pixelify Sans Project Authors (https://github.com/eifetx/Pixelify-Sans)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/crates/horizon-theme/fonts/PixelifySans-Bold.ttf b/crates/horizon-theme/fonts/PixelifySans-Bold.ttf
new file mode 100644
index 000000000..5f8040b71
Binary files /dev/null and b/crates/horizon-theme/fonts/PixelifySans-Bold.ttf differ
diff --git a/crates/horizon-theme/fonts/PixelifySans-Medium.ttf b/crates/horizon-theme/fonts/PixelifySans-Medium.ttf
new file mode 100644
index 000000000..5bf69961d
Binary files /dev/null and b/crates/horizon-theme/fonts/PixelifySans-Medium.ttf differ
diff --git a/crates/horizon-theme/fonts/PixelifySans-SemiBold.ttf b/crates/horizon-theme/fonts/PixelifySans-SemiBold.ttf
new file mode 100644
index 000000000..45cd4e2af
Binary files /dev/null and b/crates/horizon-theme/fonts/PixelifySans-SemiBold.ttf differ
diff --git a/crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt b/crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt
new file mode 100644
index 000000000..4be35e8f2
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2019 Gerrit Halfmann
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/crates/horizon-theme/icons/pixel/archive.svg b/crates/horizon-theme/icons/pixel/archive.svg
new file mode 100644
index 000000000..03033f96d
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/archive.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/arrow-left.svg b/crates/horizon-theme/icons/pixel/arrow-left.svg
new file mode 100644
index 000000000..96905e6c1
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/arrow-left.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/book-open.svg b/crates/horizon-theme/icons/pixel/book-open.svg
new file mode 100644
index 000000000..b9b134ccc
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/book-open.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/box.svg b/crates/horizon-theme/icons/pixel/box.svg
new file mode 100644
index 000000000..68f58c8ed
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/box.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/bug.svg b/crates/horizon-theme/icons/pixel/bug.svg
new file mode 100644
index 000000000..cdc707a44
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/bug.svg
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/check.svg b/crates/horizon-theme/icons/pixel/check.svg
new file mode 100644
index 000000000..e8dec6fe8
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/check.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/chevron-down.svg b/crates/horizon-theme/icons/pixel/chevron-down.svg
new file mode 100644
index 000000000..472e5e0d0
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/chevron-down.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/chevron-right.svg b/crates/horizon-theme/icons/pixel/chevron-right.svg
new file mode 100644
index 000000000..ad8a9142c
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/chevron-right.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/clock.svg b/crates/horizon-theme/icons/pixel/clock.svg
new file mode 100644
index 000000000..e17594f98
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/clock.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/close.svg b/crates/horizon-theme/icons/pixel/close.svg
new file mode 100644
index 000000000..6e6d81257
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/close.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/download.svg b/crates/horizon-theme/icons/pixel/download.svg
new file mode 100644
index 000000000..122cfbd80
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/download.svg
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/external-link.svg b/crates/horizon-theme/icons/pixel/external-link.svg
new file mode 100644
index 000000000..7058bc5b7
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/external-link.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/folder.svg b/crates/horizon-theme/icons/pixel/folder.svg
new file mode 100644
index 000000000..40533e4bb
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/folder.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/gamepad.svg b/crates/horizon-theme/icons/pixel/gamepad.svg
new file mode 100644
index 000000000..9936d5e66
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/gamepad.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/globe.svg b/crates/horizon-theme/icons/pixel/globe.svg
new file mode 100644
index 000000000..3b984aa0c
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/globe.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/heart.svg b/crates/horizon-theme/icons/pixel/heart.svg
new file mode 100644
index 000000000..7c0ccb9eb
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/heart.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/home.svg b/crates/horizon-theme/icons/pixel/home.svg
new file mode 100644
index 000000000..f71cb8c00
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/home.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/image.svg b/crates/horizon-theme/icons/pixel/image.svg
new file mode 100644
index 000000000..cf2892770
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/image.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/info-box.svg b/crates/horizon-theme/icons/pixel/info-box.svg
new file mode 100644
index 000000000..04128032b
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/info-box.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/message.svg b/crates/horizon-theme/icons/pixel/message.svg
new file mode 100644
index 000000000..c5dc11a7e
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/message.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/monitor.svg b/crates/horizon-theme/icons/pixel/monitor.svg
new file mode 100644
index 000000000..52edf4d4f
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/monitor.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/notes.svg b/crates/horizon-theme/icons/pixel/notes.svg
new file mode 100644
index 000000000..beb8d97e5
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/notes.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/package.svg b/crates/horizon-theme/icons/pixel/package.svg
new file mode 100644
index 000000000..cc6ce0788
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/package.svg
@@ -0,0 +1,4 @@
+
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/play.svg b/crates/horizon-theme/icons/pixel/play.svg
new file mode 100644
index 000000000..02e3c17aa
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/play.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/plus.svg b/crates/horizon-theme/icons/pixel/plus.svg
new file mode 100644
index 000000000..cd35642b9
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/plus.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/reload.svg b/crates/horizon-theme/icons/pixel/reload.svg
new file mode 100644
index 000000000..3458d03f0
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/reload.svg
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/search.svg b/crates/horizon-theme/icons/pixel/search.svg
new file mode 100644
index 000000000..7dce1b5ea
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/search.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/server.svg b/crates/horizon-theme/icons/pixel/server.svg
new file mode 100644
index 000000000..7979820e7
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/server.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/sliders.svg b/crates/horizon-theme/icons/pixel/sliders.svg
new file mode 100644
index 000000000..c2b4912d0
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/sliders.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/crates/horizon-theme/icons/pixel/terminal.svg b/crates/horizon-theme/icons/pixel/terminal.svg
new file mode 100644
index 000000000..e000cd104
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/terminal.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/trash.svg b/crates/horizon-theme/icons/pixel/trash.svg
new file mode 100644
index 000000000..f67fe4eca
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/trash.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/user.svg b/crates/horizon-theme/icons/pixel/user.svg
new file mode 100644
index 000000000..13773d116
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/user.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/icons/pixel/zap.svg b/crates/horizon-theme/icons/pixel/zap.svg
new file mode 100644
index 000000000..93ab75cbf
--- /dev/null
+++ b/crates/horizon-theme/icons/pixel/zap.svg
@@ -0,0 +1,3 @@
+
+
+
diff --git a/crates/horizon-theme/src/lib.rs b/crates/horizon-theme/src/lib.rs
index ced8731c1..dac5bf8d2 100644
--- a/crates/horizon-theme/src/lib.rs
+++ b/crates/horizon-theme/src/lib.rs
@@ -1,5 +1,5 @@
//! Horizon's design tokens, the one source of truth for the launcher (`launcher/src/theme.rs`),
-//! the game's own menus (`horizon-client`'s `ui_theme`) and the website (`website/src/tokens.css`,
+//! the game's on-screen keyboard (`horizon-client`'s `ui_theme`) and the website (`website/src/tokens.css`,
//! generated from [`css`] by `cargo run -p xtask -- tokens`). Change a value here and all three
//! follow. The system is described in `docs/design-system.md`.
//!
@@ -11,6 +11,9 @@ use std::time::Duration;
pub const FONT: &str = "Geist";
pub const MONO: &str = "Geist Mono";
+/// The launcher's and the website's display face (headings, navigation, buttons, badges only):
+/// Pixelify Sans, bundled under the SIL Open Font License (`fonts/OFL-PixelifySans.txt`).
+pub const PIXEL: &str = "Pixelify Sans";
/// The bundled font files.
pub mod fonts {
@@ -18,6 +21,62 @@ pub mod fonts {
pub const GEIST_MEDIUM: &[u8] = include_bytes!("../fonts/Geist-Medium.ttf");
pub const GEIST_SEMIBOLD: &[u8] = include_bytes!("../fonts/Geist-SemiBold.ttf");
pub const GEIST_MONO: &[u8] = include_bytes!("../fonts/GeistMono-Regular.ttf");
+ pub const PIXEL_MEDIUM: &[u8] = include_bytes!("../fonts/PixelifySans-Medium.ttf");
+ pub const PIXEL_SEMIBOLD: &[u8] = include_bytes!("../fonts/PixelifySans-SemiBold.ttf");
+ pub const PIXEL_BOLD: &[u8] = include_bytes!("../fonts/PixelifySans-Bold.ttf");
+}
+
+/// The launcher's pixel icons: Pixelarticons (MIT, `icons/pixel/LICENSE-pixelarticons.txt`), 24
+/// unit SVGs filled with `currentColor`, by name (`"home"`, `"play"`…).
+pub mod icons {
+ macro_rules! icons {
+ ($($name:literal),* $(,)?) => {
+ /// Every icon, `(name, svg)`.
+ pub const ALL: &[(&str, &[u8])] = &[
+ $(($name, include_bytes!(concat!("../icons/pixel/", $name, ".svg")))),*
+ ];
+ };
+ }
+ icons!(
+ "archive",
+ "arrow-left",
+ "book-open",
+ "box",
+ "bug",
+ "check",
+ "chevron-down",
+ "chevron-right",
+ "clock",
+ "close",
+ "download",
+ "external-link",
+ "folder",
+ "gamepad",
+ "globe",
+ "heart",
+ "home",
+ "image",
+ "info-box",
+ "message",
+ "monitor",
+ "notes",
+ "package",
+ "play",
+ "plus",
+ "reload",
+ "search",
+ "server",
+ "sliders",
+ "terminal",
+ "trash",
+ "user",
+ "zap",
+ );
+
+ /// An icon's SVG by name.
+ pub fn get(name: &str) -> Option<&'static [u8]> {
+ ALL.iter().find(|(n, _)| *n == name).map(|(_, svg)| *svg)
+ }
}
/// Horizon's icon at 64 px (PNG), for window title bars and task bars at run time. Rendered from
@@ -275,6 +334,113 @@ pub const DARK: Palette = Palette {
dark: true,
};
+/// The launcher's and the website's blocky look ("Blocks" in `docs/design-system.md`): stone-dark
+/// (or lavender-light) neutrals with a violet cast, panels with a dark outline, a light bevel on top
+/// and a darker lip below, and the violet `face` of the one big action. The game's menus keep
+/// [`LIGHT`] and [`DARK`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Blocks {
+ /// The window behind everything, tiled with a faint stone texture.
+ pub page: u32,
+ /// The top bar and the sidebar.
+ pub side: u32,
+ /// Panels: rows, cards, dialogs.
+ pub panel: u32,
+ /// A selected or hovered panel or row, the open tab.
+ pub raised: u32,
+ /// Buttons and the chosen segment.
+ pub button: u32,
+ /// A button's top bevel.
+ pub button_bevel: u32,
+ /// Sunk wells: fields, tracks, switch and checkbox boxes, segmented tracks.
+ pub well: u32,
+ /// The light top (and left) edge of a panel.
+ pub bevel: u32,
+ /// The darker bottom edge of a panel or button.
+ pub lip: u32,
+ /// The 2 px outline around panels, buttons and wells.
+ pub outline: u32,
+ /// Rules between rows inside a panel.
+ pub rule: u32,
+ pub ink: u32,
+ pub ink_soft: u32,
+ pub muted: u32,
+ /// Links, focus, progress, the selection marker; text-safe on every background.
+ pub accent: u32,
+ /// The main action's face (Play, Install, Download), its top bevel and bottom lip.
+ pub face: u32,
+ pub face_bevel: u32,
+ pub face_lip: u32,
+ pub on_face: u32,
+ pub danger: u32,
+ pub success: u32,
+ /// "Partly": a mod or pack that runs in part.
+ pub warn: u32,
+ pub dark: bool,
+}
+
+pub const BLOCKS_DARK: Blocks = Blocks {
+ page: 0x0f0d17,
+ side: 0x0b0a11,
+ panel: 0x1a1727,
+ raised: 0x221e34,
+ button: 0x2b2641,
+ button_bevel: 0x3d3560,
+ well: 0x0c0b12,
+ bevel: 0x342d52,
+ lip: 0x07060b,
+ outline: 0x05040a,
+ rule: 0x120f1c,
+ ink: 0xecedf3,
+ ink_soft: 0xc5c7d1,
+ muted: 0xa29cb8,
+ accent: 0x9a86ff,
+ face: 0x5b3fd6,
+ face_bevel: 0x8a74ff,
+ face_lip: 0x3a2694,
+ on_face: 0xffffff,
+ danger: 0xf07a68,
+ success: 0x45c27a,
+ warn: 0xf0b84f,
+ dark: true,
+};
+
+pub const BLOCKS_LIGHT: Blocks = Blocks {
+ page: 0xece7f7,
+ side: 0xe2dbf2,
+ panel: 0xf8f6fd,
+ raised: 0xe9e3f8,
+ button: 0xddd4f3,
+ button_bevel: 0xf4f0fe,
+ well: 0xf3f0fb,
+ bevel: 0xffffff,
+ lip: 0xc3b8e2,
+ outline: 0x2b2244,
+ rule: 0xe4ddf4,
+ ink: 0x1b1530,
+ ink_soft: 0x3b3354,
+ muted: 0x585071,
+ accent: 0x5333c9,
+ face: 0x5b3fd6,
+ face_bevel: 0x8069ef,
+ face_lip: 0x3a2694,
+ on_face: 0xffffff,
+ danger: 0xa3301d,
+ success: 0x136336,
+ warn: 0x7a4f00,
+ dark: false,
+};
+
+/// Pixel sizes of the blocky look: outlines, bevels and lips, the cut corner, and the stone tile.
+pub const BLOCK_OUTLINE: f32 = 2.;
+pub const BLOCK_BEVEL: f32 = 2.;
+pub const BLOCK_LIP: f32 = 4.;
+/// The stone texture: a 16 by 16 tile, each texel this many logical pixels.
+pub const TILE_TEXELS: usize = 16;
+pub const TILE_TEXEL: f32 = 4.;
+/// The texture's shades: the page colour moved this many levels (of 255) lighter or darker.
+pub const TILE_SHADES: [i16; 5] = [0, 2, -2, 5, -4];
+
/// How strongly the game's menus veil the live backdrop (the title panorama, or the world behind
/// the pause and options screens) with the page colour. Every text colour the menus use keeps
/// WCAG AA over it, even on a selected row's plate, with a backdrop as bright as
@@ -308,6 +474,41 @@ impl Palette {
}
}
+impl Blocks {
+ /// Every colour by its CSS name. The website reads the Blocks palettes; the first twelve keep
+ /// the names of [`Palette::named`] (`plate-soft` is `raised`, `plate` is `button`, `surface`
+ /// is `panel`, `on-accent` is `on_face`), so styles written for those still apply.
+ pub fn named(&self) -> [(&'static str, u32); 25] {
+ [
+ ("page", self.page),
+ ("plate-soft", self.raised),
+ ("plate", self.button),
+ ("surface", self.panel),
+ ("rule", self.rule),
+ ("ink", self.ink),
+ ("ink-soft", self.ink_soft),
+ ("muted", self.muted),
+ ("accent", self.accent),
+ ("on-accent", self.on_face),
+ ("danger", self.danger),
+ ("success", self.success),
+ ("warn", self.warn),
+ ("side", self.side),
+ ("panel", self.panel),
+ ("raised", self.raised),
+ ("button", self.button),
+ ("button-bevel", self.button_bevel),
+ ("well", self.well),
+ ("bevel", self.bevel),
+ ("lip", self.lip),
+ ("outline", self.outline),
+ ("face", self.face),
+ ("face-bevel", self.face_bevel),
+ ("face-lip", self.face_lip),
+ ]
+ }
+}
+
/// The WCAG 2 contrast ratio of two colours.
pub fn contrast(a: u32, b: u32) -> f32 {
fn luminance(c: u32) -> f32 {
@@ -333,10 +534,12 @@ pub fn css() -> String {
let t = format!("{v:.3}");
t.trim_end_matches('0').trim_end_matches('.').to_string()
};
- let colors = |s: &mut String, p: &Palette| {
+ // The website wears the launcher's Blocks look; the game's menus keep LIGHT and DARK.
+ let colors = |s: &mut String, p: &Blocks| {
for (name, c) in p.named() {
let _ = writeln!(s, " --{name}: #{c:06x};");
}
+ let _ = writeln!(s, " --on-face: #{:06x};", p.on_face);
let _ = writeln!(
s,
" color-scheme: {};",
@@ -347,11 +550,18 @@ pub fn css() -> String {
"/* Generated from crates/horizon-theme by `cargo run -p xtask -- tokens`; do not edit.\n \
docs/design-system.md describes the tokens. */\n\n:root {\n",
);
- colors(&mut s, &LIGHT);
+ colors(&mut s, &BLOCKS_LIGHT);
let _ = writeln!(
s,
- " --font: \"{FONT}\", ui-sans-serif, system-ui, sans-serif;\n --mono: \"{MONO}\", ui-monospace, monospace;"
+ " --font: \"{FONT}\", ui-sans-serif, system-ui, sans-serif;\n --mono: \"{MONO}\", ui-monospace, monospace;\n --pixel: \"{PIXEL}\", \"{FONT}\", ui-sans-serif, sans-serif;"
);
+ for (name, v) in [
+ ("block-outline", BLOCK_OUTLINE),
+ ("block-bevel", BLOCK_BEVEL),
+ ("block-lip", BLOCK_LIP),
+ ] {
+ let _ = writeln!(s, " --{name}: {}px;", num(v));
+ }
for step in TYPE {
let size = match step.web {
Web::Fixed => format!("{}px", num(step.px)),
@@ -410,7 +620,7 @@ pub fn css() -> String {
"}\n\n@media (prefers-color-scheme: dark) {\n :root:not([data-theme=\"light\"]) {\n",
);
let mut dark = String::new();
- colors(&mut dark, &DARK);
+ colors(&mut dark, &BLOCKS_DARK);
for line in dark.lines() {
let _ = writeln!(s, " {line}");
}
@@ -458,6 +668,63 @@ mod tests {
}
}
+ /// The blocky look: every text colour on every background it is drawn on reaches AA, the
+ /// main action's label too, and the focus ring (the accent) reaches 3:1 (WCAG 1.4.11).
+ #[test]
+ fn blocks_text_meets_wcag_aa_in_both_appearances() {
+ for p in [BLOCKS_DARK, BLOCKS_LIGHT] {
+ let theme = if p.dark { "dark" } else { "light" };
+ let backgrounds = [
+ ("page", p.page),
+ ("side", p.side),
+ ("panel", p.panel),
+ ("raised", p.raised),
+ ("button", p.button),
+ ("well", p.well),
+ ];
+ let texts = [
+ ("ink", p.ink),
+ ("ink_soft", p.ink_soft),
+ ("muted", p.muted),
+ ("accent", p.accent),
+ ("danger", p.danger),
+ ("success", p.success),
+ ("warn", p.warn),
+ ];
+ for (bn, bg) in backgrounds {
+ for (tn, fg) in texts {
+ let ratio = contrast(fg, bg);
+ assert!(ratio >= 4.5, "{theme} {tn} on {bn}: {ratio:.2}");
+ }
+ // The texture's lightest shade under the page's text.
+ let lifted = TILE_SHADES.iter().max().copied().unwrap_or(0) as i32;
+ let shade = [16, 8, 0].iter().fold(0, |out, s| {
+ let c = (((p.page >> s) & 255) as i32 + lifted).clamp(0, 255) as u32;
+ out | c << s
+ });
+ for (tn, fg) in texts {
+ let ratio = contrast(fg, shade);
+ assert!(
+ ratio >= 4.5,
+ "{theme} {tn} on the stone texture: {ratio:.2}"
+ );
+ }
+ }
+ let label = contrast(p.on_face, p.face);
+ assert!(label >= 4.5, "{theme} the main action's label: {label:.2}");
+ }
+ }
+
+ #[test]
+ fn every_icon_is_a_pixel_svg() {
+ for (name, svg) in icons::ALL {
+ let svg = std::str::from_utf8(svg).unwrap();
+ assert!(svg.contains("viewBox=\"0 0 24 24\""), "{name}");
+ assert!(svg.contains("currentColor"), "{name}");
+ }
+ assert!(icons::get("play").is_some());
+ }
+
/// The game's menus over the brightest backdrop: the page colour veiled over it, and a
/// selected row's plate (ink at 8 %) on top.
#[test]
diff --git a/docs/README.md b/docs/README.md
index 1e268b4d7..b4398ebfc 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -20,7 +20,7 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor
- [Resource packs](resource-packs.md): everything a 26.3 resource pack can change, whether Horizon honours it, and the proof.
- [Opt-in data collection](telemetry.md): the consent, exactly what is sent, how it is stored and sent.
- [Benchmark report format](benchmark-report.md): the versioned JSON every benchmark writes (game, launcher, `tools/perf_bench.py`), the local log and, with consent, the upload.
-- Menus: the title, world list, create world, multiplayer, options and pause screens share the launcher's design tokens and fonts (`crates/horizon-theme`), drawn by `ui_theme` over a live frozen backdrop (`game/backdrop.rs`, blurred and graded by `post.rs`). Options → Interface → Menu style switches to vanilla's screens (Classic, kept in `horizon.txt`; `HORIZON_MENU_STYLE=horizon|classic` overrides it, and scripted runs default to Classic). [Title](media/menu-title.png) ([webm](media/menu-title.webm)), [worlds](media/menu-worlds.png), [options](media/menu-options.png), [pause](media/menu-pause.png).
+- Menus: every screen is vanilla's (title, world list, create world, multiplayer, options, pause). Horizon's own settings hang off vanilla's Options the way mods add theirs: **Horizon Settings...** and **Mods...** in the last two slots of the Options grid (Horizon Settings opens Graphics, Advanced Graphics, Shader Packs, Controller Settings, Extras and Mods, each a vanilla options list), with Horizon Graphics, Advanced Graphics and Shader Packs also at the top of Video Settings and Controller Settings at the bottom of Controls. The title screen's and pause menu's Friends buttons open Join a Friend and Play with Friends ([play-with-friends.md](play-with-friends.md)).
## Parity
diff --git a/docs/agent-control.md b/docs/agent-control.md
index fe318c562..8fc59b484 100644
--- a/docs/agent-control.md
+++ b/docs/agent-control.md
@@ -29,7 +29,6 @@ Legend: **yes** complete, **part** partial (see note), **no** missing, **—** n
| Dedicated server: start, console, log, stop | yes | yes | yes | |
| Accounts (no secrets) | yes | yes | yes | names and UUIDs only; sign-in is a device code the player enters |
| Launcher settings (game folder, auto-install, opening animation, desktop entry) | yes | part | no | CLI has `desktop-entry`; the rest only in the window |
-| Game menu style | yes | yes | yes | |
| Logs, crash report | yes | yes | yes | |
| Updates (Horizon and launcher) | yes | yes | yes | MCP only checks |
| Patch notes, links | yes | yes | yes | |
@@ -76,7 +75,7 @@ Legend: **yes** complete, **part** partial (see note), **no** missing, **—** n
| Capability | Before | After |
| --- | --- | --- |
-| Screens: widgets | labelled buttons only | every widget of every screen (`ui`): id, kind, label, bounds, slider value, tab selected, slots with stacks; both menu styles |
+| Screens: widgets | labelled buttons only | every widget of every screen (`ui`): id, kind, label, bounds, slider value, tab selected, slots with stacks |
| Screens: act on a widget | `click-button LABEL`, `click-at X Y` | `click ID [right\|middle] [shift]`, `set ID VALUE` (sliders), `click` focuses fields |
| Options | open a page; `render-distance` only | `options-get` all 193 `options.txt` options typed with ranges/choices; `options-set` validates, applies, saves |
| Waits | `wait TICKS`, `wait-ready` | `wait-for screen\|widget\|loaded\|chat\|event` with timeout errors |
@@ -111,7 +110,7 @@ Legend: **yes** complete, **part** partial (see note), **no** missing, **—** n
### Structured UI: the widget tree
`ui` returns every interactive element the last frame drew, on every screen (title menus,
-pause, options pages, inventories and stations, chat, death, Horizon-style menus):
+pause, options pages, inventories and stations, chat, death, Play with Friends):
```json
{"screen": "options", "gui_size": [427, 240], "frame": 3061,
@@ -126,8 +125,7 @@ pause, options pages, inventories and stations, chat, death, Horizon-style menus
`Video Settings...` → `video-settings`); a repeated slug gets `-2`, `-3` in draw order;
unlabelled elements are `-` in draw order. The id of a slider does not change
when its value (and so its label) does. World, server and language rows carry their
- names; Horizon-style switches, sliders and segments carry their settings row's caption
- (`vsync`, `menu-style-horizon`); inventory, creative and menu slots are `slot-` with
+ names; inventory, creative and menu slots are `slot-` with
their stack (an item tab's display slots are `slot-900` up).
- **Kinds**: `button`, `slider` (`value` 0..1 as drawn), `field` (text box), `row` (list
entry: world, server, pack, language), `tab` (`selected`), `slot`.
diff --git a/docs/controllers.md b/docs/controllers.md
index 4e3d82a75..c2ac6b5d3 100644
--- a/docs/controllers.md
+++ b/docs/controllers.md
@@ -97,9 +97,8 @@ real mouse hands control back at once.
Every interactive rectangle a screen draws registers itself as a focus
target with its kind (`widgets::target_as`): classic buttons, sliders, edit
-boxes and list rows (worlds, servers, languages), every Horizon-style widget
-(`ui_theme::Ui::interact`: sidebar items, switches, segments, sliders,
-fields, buttons), inventory and container slots, creative and recipe-book
+boxes and list rows (worlds, servers, languages), icon buttons (the title's
+and pause menu's Friends button), inventory and container slots, creative and recipe-book
tabs, and the stations' own buttons (trades, loom patterns, beacon effects,
enchantments, stonecutter recipes, the recipe book's recipes, pages and
filter). A screen that registers nothing falls back to the pointer.
@@ -137,16 +136,11 @@ the crafting result, armour to the player's grid.
- **Where focus lands** when a screen opens: the held hotbar slot in an
inventory, else the first button.
-How it looks follows the menu style:
-
-- **Classic screens** look as vanilla's own keyboard focus does: buttons,
- sliders and slots show their highlighted sprite (`isHoveredOrFocused`,
- drawn because the hidden pointer is over them), and list rows and text
- fields get vanilla's white one-pixel outline (`AbstractSelectionList`'s
- focused selection, `EditBox`'s highlighted border).
-- **Horizon-style screens** get the design system's focus colour: a two-dp
- ring in the accent colour around the focused widget, pill-shaped on
- buttons, tabs and sliders.
+It looks as vanilla's own keyboard focus does: buttons, sliders and slots
+show their highlighted sprite (`isHoveredOrFocused`, drawn because the hidden
+pointer is over them), and list rows and text fields get vanilla's white
+one-pixel outline (`AbstractSelectionList`'s focused selection, `EditBox`'s
+highlighted border).
### Pointer
@@ -183,8 +177,8 @@ Steam + X opens it at any time. "On-Screen Keyboard: Auto / Horizon / Steam"
Both modes reach every screen through the pointer events. Focus mode
registers targets on: the title menus (main, world list and its search, create
and edit world, delete, multiplayer list and its edit screens), every options
-page (classic pages and the Horizon-style sections, key and controller binds,
-language list), pause, death, chat, signs and books (their buttons), the
+page (vanilla's and Horizon Settings with the pages it opens, key and
+controller binds, language list), pause and Play with Friends, death, chat, signs and books (their buttons), the
survival and creative inventories, every container and station (chests,
furnaces, brewing, crafter, crafting table with its recipe book, anvil,
grindstone, smithing, stonecutter, loom, cartography, enchanting, beacon,
@@ -212,8 +206,10 @@ hints, "Press X to dismount") only while the pad is the last-used input.
## Options and remapping
-Controller settings are Horizon's own and live in `horizon-controller.txt`
-next to `options.txt`, like `horizon-graphics.txt`: `options.txt` stays
+Controller settings are Horizon's own: **Options → Controls → Controller
+Settings...** (or **Options → Horizon Settings... → Controller Settings...**),
+a vanilla options list with **Controller Binds...** at the top. They live in
+`horizon-controller.txt` next to `options.txt`, like `horizon-graphics.txt`: `options.txt` stays
exactly vanilla's, so a vanilla client can share the game folder.
```
@@ -490,8 +486,8 @@ The first round (input layer, menus, glyphs and options, rumble) shipped in
PRs #120, #129, #145 and #149. The second round, each shippable alone:
1. **Focus navigation** (this section above): the menu navigation option,
- focus targets and vanilla's arrow-key step, the focus highlight in both
- menu styles, the on-screen keyboard.
+ focus targets and vanilla's arrow-key step, vanilla's focus highlight,
+ the on-screen keyboard.
2. **Button prompts**: contextual hints with the pad's glyphs in menus and
optionally in game, and rebinding from them.
3. **DualSense output** (above): the HID output layer and rumble through it
diff --git a/docs/design-system.md b/docs/design-system.md
index 40b5c1b84..1980adc9c 100644
--- a/docs/design-system.md
+++ b/docs/design-system.md
@@ -1,8 +1,9 @@
# Horizon's design system
-One design language for the launcher, the website and the game's own menus (what "Menu style:
-Horizon" draws). Vanilla's classic screens and the HUD are not part of it: they stay exactly
-vanilla, because parity is the point of the game.
+One design language for the launcher, the website and the few overlays the game draws that
+vanilla has no screen for (the on-screen keyboard a controller types with). Every game screen
+and the HUD are not part of it: they are vanilla's, because parity is the point of the game, and
+Horizon's own settings are pages built from vanilla's widgets, the way mods add theirs.
The tokens live in one place, `crates/horizon-theme`. The launcher (`launcher/src/theme.rs`)
and the game (`crates/horizon-client/src/ui_theme.rs`) read them as Rust constants, and the
@@ -139,16 +140,35 @@ Geist (400, 500, 600) and Geist Mono (400), bundled under the SIL Open Font Lice
are index lists with the release name as the title; Settings is an index list of switches and
values. The opening is the faint wordmark drawn letter by letter, then the interface arrives.
The sunset photograph is gone: the window is the page colour, light or dark with the system.
-- **Website** (`website/`): the same page structure as before (what it is, screenshots,
- parity, launcher, patch notes, community), each section a `micro` mono label, a `display`
- heading and a short paragraph, its content an index list. Screenshots stay as images (radius
- 12, no frame). Light and dark follow the system, with a toggle. A giant faint wordmark sits
- above the footer. No hero photograph: the first screen is the headline, one paragraph, the
- download button and the parity score as an index row.
-- **Game menus** (Horizon style): the title backdrop under a page-colour veil; text sidebar;
- index lists for worlds and servers; options pages as index lists of rows (label left, value
- in mono, the control right). The pause menu is a centred column of plain rows over a darker
- veil.
+- **Website** (`website/`): the Blocks look below. The same page structure as before (what it
+ is, screenshots, parity, launcher, patch notes, community), headings in Pixelify Sans, lists as
+ stacks of panels, the stone texture behind the page and Horizon's pixel landscape (a dawn or a
+ sunset) behind the hero. Light and dark follow the system, with a toggle. A giant wordmark in
+ pixels sits in the footer.
+- **Game**: vanilla's screens. The on-screen keyboard is a rounded plate of keys in the page
+ colour, the focused key in the accent.
+
+## Blocks
+
+A blocky, Minecraft-like look in Horizon's purple, for the website and the redesigned launcher:
+Minecraft's inventory rather than a document. Its colours are `horizon_theme::Blocks`
+(`BLOCKS_LIGHT`, `BLOCKS_DARK`), which `tokens.css` carries under the same names as before plus
+`--panel`, `--raised`, `--button`, `--well`, `--bevel`, `--lip`, `--outline` and the `--face`
+of the main action. The game's menus keep `LIGHT` and `DARK`.
+
+- **Pixel type for what names and what you act on.** Headings, navigation, buttons and the
+ wordmark use Pixelify Sans (OFL; Medium, SemiBold, Bold); paragraphs and numbers stay in Geist
+ and Geist Mono so long text reads easily.
+- **Blocks, not rounded cards.** Every surface is square: a 2 px dark outline, a 2 px light bevel
+ along the top and a darker lip along the bottom. The main action is the violet face with its own
+ bevel and a 4 px lip; it sinks a pixel when pressed. Code and fields are sunk wells.
+- **Pixel art drawn in code.** The stone behind the pages is 64 texels of the page colour in five
+ close shades (`TILE_SHADES`), never Minecraft's stone; the landscape is a banded sky, a sun cut in
+ slices like the mark, hills and square trees. `website/scripts/art.mjs` draws both.
+- **Icons** (the launcher): Pixelarticons (MIT), 24 unit pixel SVGs in
+ `crates/horizon-theme/icons/pixel/`.
+- **Contrast**: every text colour meets WCAG AA (4.5:1) on the panels, the page and the lightest
+ stone shade in both palettes (`blocks_text_meets_wcag_aa_in_both_appearances`).
## The mark
diff --git a/docs/extras.md b/docs/extras.md
index 2c65b1dbe..e27e142ea 100644
--- a/docs/extras.md
+++ b/docs/extras.md
@@ -19,11 +19,12 @@ again restores vanilla's behaviour completely.
| Game glue (input hooks, per-frame update) | `crates/horizon-client/src/game/extras.rs` |
| Mouse Tweaks-style controls, sort buttons | `crates/horizon-client/src/game/tweaks.rs` |
| Sort order and its clicks | `crates/horizon-client/src/inv_sort.rs` (pure, unit tested) |
-| The settings page | `options_horizon.rs`: the **Extras** section of Horizon's Options |
+| The settings page | `options_ui.rs` (`Page::Extras`): **Options → Horizon Settings... → Extras...** |
-The settings are grouped by extra. On Horizon's page an extra's own settings
-(its key, corner, size...) show under its switch while it is on (`Item::parent`);
-Classic's Horizon Extras screen lists them all, two buttons to a row.
+The settings are grouped by extra, under a header each, two buttons to a row as
+vanilla's options lists are, and each says what it does in its tooltip. An
+extra's own settings (its key, corner, size...) are greyed out while its switch
+is off (`Item::parent`).
`game.rs` only gets one-line hooks (key, wheel, mouse, frame, HUD), so the
extras stay out of the way of other input and options work.
diff --git a/docs/graphics.md b/docs/graphics.md
index 34032a641..7629ad47d 100644
--- a/docs/graphics.md
+++ b/docs/graphics.md
@@ -2,17 +2,17 @@
## Settings
-In the Horizon menu style, the Options screen's **Video** section holds the graphics settings, with a Simple / Advanced switch at the top (remembered between sessions):
+Horizon's graphics settings are two screens built from vanilla's widgets, opened from the top of **Video Settings** (**Horizon Graphics...** and **Advanced Graphics...**, beside **Shader Packs...**, where Sodium and Iris put theirs) or from **Options → Horizon Settings...**:
-- **Simple**: a preset (Performance, Balanced, Quality, Ultra or Custom), render distance, LOD distance, FOV, max framerate, VSync and GUI scale.
-- **Advanced**: every setting, grouped under Rendering, Quality, Display, Preferences, Performance and Overlay.
+- **Graphics** (Simple): a preset (Performance, Balanced, Quality, Ultra or Custom) and LOD distance.
+- **Advanced Graphics**: every Horizon setting, grouped under Rendering, Quality, Display, Preferences, Performance and Overlay.
-In the Classic style, Video Settings starts with two buttons opening the same settings as vanilla-looking screens.
+Vanilla's own settings (render distance, FOV, framerate, VSync, GUI scale, smooth lighting...) stay where vanilla has them, in Video Settings; both screens leave them out.
Every row has a one-line description and its cost in frame time (none, low, medium, high, or saves time for culling that makes frames faster), and applies at once, except worker threads, which apply at the next start. A preset sets the quality settings together; changing one of them turns it into Custom. Display preferences (FOV, framerate, VSync, GUI scale, fullscreen, present mode, pacing) leave the preset as it is.
-
-
+
+
| Group | Setting | Stored in |
| --- | --- | --- |
@@ -29,7 +29,7 @@ Every row has a one-line description and its cost in frame time (none, low, medi
**Battery mode** (Performance, off by default) is for laptops and handhelds: at most 60 frames per second in a world, 30 in menus without a world or while another window has focus, and half the automatic worker threads (chunks load slower). It changes only when frames are drawn: what they show and the game's 20 ticks per second stay as they are.
-Which settings each level shows, their descriptions and costs are in `crates/horizon-client/src/graphics_ui.rs` (`rows`); the Horizon shell draws them in `options_horizon.rs` with `ui_theme::described_row`, and the Classic screens use `graphics_style.rs`.
+Which settings each screen shows, their descriptions and costs are in `crates/horizon-client/src/graphics_ui.rs` (`rows`); `graphics_style.rs` draws them.
## Distant terrain
diff --git a/docs/media/accessibility-settings-horizon.png b/docs/media/accessibility-settings-horizon.png
deleted file mode 100644
index 7b1722129..000000000
Binary files a/docs/media/accessibility-settings-horizon.png and /dev/null differ
diff --git a/docs/media/menu-options.png b/docs/media/menu-options.png
deleted file mode 100644
index c674f6845..000000000
Binary files a/docs/media/menu-options.png and /dev/null differ
diff --git a/docs/media/menu-pause.png b/docs/media/menu-pause.png
deleted file mode 100644
index 9c25724d2..000000000
Binary files a/docs/media/menu-pause.png and /dev/null differ
diff --git a/docs/media/menu-title.png b/docs/media/menu-title.png
deleted file mode 100644
index 133f393bc..000000000
Binary files a/docs/media/menu-title.png and /dev/null differ
diff --git a/docs/media/menu-title.webm b/docs/media/menu-title.webm
deleted file mode 100644
index 9c19e3e25..000000000
Binary files a/docs/media/menu-title.webm and /dev/null differ
diff --git a/docs/media/menu-title.webp b/docs/media/menu-title.webp
deleted file mode 100644
index cf41ccf67..000000000
Binary files a/docs/media/menu-title.webp and /dev/null differ
diff --git a/docs/media/menu-worlds.png b/docs/media/menu-worlds.png
deleted file mode 100644
index 16f41104b..000000000
Binary files a/docs/media/menu-worlds.png and /dev/null differ
diff --git a/docs/media/menu-worlds.webp b/docs/media/menu-worlds.webp
deleted file mode 100644
index b70168080..000000000
Binary files a/docs/media/menu-worlds.webp and /dev/null differ
diff --git a/docs/media/settings-advanced.png b/docs/media/settings-advanced.png
index cf34e61e0..c6d4f90e9 100644
Binary files a/docs/media/settings-advanced.png and b/docs/media/settings-advanced.png differ
diff --git a/docs/media/settings-simple.png b/docs/media/settings-simple.png
index c674f6845..13fece531 100644
Binary files a/docs/media/settings-simple.png and b/docs/media/settings-simple.png differ
diff --git a/docs/media/settings.webp b/docs/media/settings.webp
index 9ad5252c9..70f409259 100644
Binary files a/docs/media/settings.webp and b/docs/media/settings.webp differ
diff --git a/docs/mod-browser.md b/docs/mod-browser.md
index 115877075..745f51d9b 100644
--- a/docs/mod-browser.md
+++ b/docs/mod-browser.md
@@ -1,25 +1,69 @@
# The launcher's mod browser
-Search Modrinth (and CurseForge, once the launcher has a key) for packs Horizon loads, see how well each one runs,
-and install it with its checksum checked. This is item 16 of the roadmap and issue #577. The code is in
+Search Modrinth (CurseForge support is coming soon) for Java mods, modpacks, resource packs and shader
+packs, see how well each one runs before installing it, and install it with its checksum checked. This is item 16 of the roadmap and issue #577. The code is in
`launcher/src/browser.rs` and `launcher/src/browser/`.
## What it offers
-Only what Horizon actually loads is offered. Java mod jars (Fabric, NeoForge, Forge) don't run in Horizon
-([mods.md](mods.md), [research/java-mod-compat.md](research/java-mod-compat.md)), so they are never searched.
-Horizon `.hmod` mods aren't on Modrinth or CurseForge yet (Modrinth has no `horizon` loader).
+Horizon doesn't run Java code ([research/java-mod-compat.md](research/java-mod-compat.md)). It ports what a Java mod
+carries as data (blocks, items, recipes, loot tables, tags, worldgen, textures, names) with `horizon-port-pack`, and
+says before install which of the mod's features that leaves out. Horizon `.hmod` mods aren't on Modrinth or CurseForge
+yet (Modrinth has no `horizon` loader).
| Kind | Goes to | How well it runs |
|---|---|---|
+| Java mods (Fabric, NeoForge, Forge, Quilt) | ported into `horizon-mods//` and turned on | Checked from its jar before install: **Works**, **Partly** or **Doesn't run** ([below](#java-mods)) |
| Resource packs | `resourcepacks/` beside `options.txt` | **Works** when made for 26.3 ([resource-packs.md](resource-packs.md) lists what Horizon reads). Older packs are **Partly**: they load with vanilla's compatibility warning |
| Shader packs (Iris, OptiFine) | `shaderpacks/` | **Partly**: translated to WGSL, the full-screen passes draw and the world and shadow passes don't yet ([shader-packs.md](shader-packs.md)). Packs for other loaders (Canvas, core-shader packs) **don't run** and can't be installed |
| Modpacks (`.mrpack`, CurseForge zip) | the Modpacks page's import | **Partly**: Horizon runs the mods it can port, from the player's own downloads ([modpacks.md](modpacks.md)) |
-By default a search shows only what runs: resource packs made for 26.3, shader packs for Iris or OptiFine, and every
-modpack. **Show everything** lists the rest of the kind too, each marked with how well it runs; what doesn't run is
+By default a search shows only what runs: Java mods made for 26.3, resource packs made for 26.3, shader packs for Iris
+or OptiFine, and every modpack. **Show everything** lists the rest of the kind too, each marked with how well it runs; what doesn't run is
never offered for install.
+## Java mods
+
+Before a mod is offered for install, the launcher reads its jar. For each result it picks the version it would
+install (the newest for 26.3; with **Show everything**, else the newest for 1.21 or later, the versions port-pack
+upgrades from), downloads that file with the checks below, and runs `horizon-port-pack check` on it
+([modpacks.md](modpacks.md#the-pipeline-horizon-port-pack)): the jar is carried over into a folder content mod and its
+class files are read, not run, for what the carry can't take. Two checks run at once; the row says **Checking** until
+its answer comes.
+
+- **Works**: content only. Its blocks, items, recipes, loot, tags and worldgen port, and its code only registers
+ them. Blocks take the closest vanilla block's shape, hardness and sounds (a block's numbers live in Java code; the
+ NeoForge oracle that reads them for modpacks is a developer tool).
+- **Partly**: the content ports; the row lists what doesn't: blocks with no vanilla block to copy, recipes of the
+ mod's own types, block entities (machines, containers), menus, mobs and entities, blocks and items with behaviour
+ of their own, worldgen written in Java, Mixins, the game events it reacts to.
+- **Doesn't run**: nothing to port (performance mods, libraries, everything in code), a jar made for 1.20 or older,
+ or a mod id with characters Horizon mods can't use (`fabric-api`). Never offered for install.
+
+The answer is kept in `mod-browser/checks-1//` under the game folder, with the carry when something
+ports; the jar itself isn't kept. A file is checked once. On ten 26.3 jars a check took 0.2 to 3 s (24 s for an
+18 MB jar with 9,360 recipes).
+
+**Install** copies the carry into `horizon-mods/