Merge main into #1265: riding for a server's players

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-23 01:52:02 +02:00
213 changed files with 13021 additions and 5711 deletions
+4
View File
@@ -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
+4 -3
View File
@@ -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"
+4
View File
@@ -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]
+4
View File
@@ -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]
+4
View File
@@ -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'
+3 -3
View File
@@ -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
<td colspan="2"><img src="docs/media/sunset.webp" alt="Sunset over a savanna river valley and a plains village"></td>
</tr>
<tr>
<td width="50%"><img src="docs/media/menu-title.webp" alt="Horizon's title screen over a veiled snowy landscape"></td>
<td width="50%"><img src="docs/media/settings.webp" alt="The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs"></td>
<td width="50%"><img src="docs/media/survival.webp" alt="Survival at dusk: a zombie walks up, with the hotbar, health, hunger and experience"></td>
<td width="50%"><img src="docs/media/settings.webp" alt="Vanilla's Video Settings screen with Horizon's own buttons at the top: Horizon Graphics, Advanced Graphics and Shader Packs"></td>
</tr>
<tr>
<td width="50%"><img src="docs/media/village.webp" alt="A plains village among savanna hills, with farms, villagers and an iron golem"></td>
+12
View File
@@ -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`).
+303
View File
@@ -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<String>,
/// 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<String>,
/// The players in the world besides the host.
pub guests: Vec<String>,
pub notice: Option<String>,
/// 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<Button>) {
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<String> {
let mut lines: Vec<String> = 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<Action> {
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);
}
}
File diff suppressed because it is too large Load Diff
+46 -125
View File
@@ -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<Instant>,
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<f32> {
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<String>,
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)?;
+1
View File
@@ -403,6 +403,7 @@ impl Game<'_> {
Screen::Stats => "stats",
Screen::Advancements => "advancements",
Screen::WorldOptions => "world-options",
Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
}
}
-303
View File
@@ -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<Arc<VanillaTerrain>, 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<Mutex<Option<Built>>>,
/// The generator streams the backdrop's chunks.
installed: bool,
/// The search for the spot, then the spot (block x, z).
spot: Arc<Mutex<Option<Option<(i32, i32)>>>>,
centred: bool,
/// Camera position once the ground under it has loaded.
pub camera: Option<glam::DVec3>,
pub ready: Option<Instant>,
pub started: Option<Instant>,
}
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<i32> {
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::<i32>().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<std::path::PathBuf> {
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<VanillaTerrain>) -> 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();
}
}
@@ -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",
}
}
@@ -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::<Vec<_>>()).collect::<Vec<_>>()),
"ints": m.extra.ints,
"pois": [m.extra.home, m.extra.bed, m.extra.meeting],
+43 -4
View File
@@ -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(),
+10
View File
@@ -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();
@@ -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<super::lan_trading::GuestMerchant>,
/// 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;
+24 -4
View File
@@ -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;
}
}
+29 -19
View File
@@ -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
+7 -39
View File
@@ -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<Target> {
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);
@@ -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();
+52 -68
View File
@@ -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(())
+18 -60
View File
@@ -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(),
-22
View File
@@ -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<crate::post::PostGrade>,
/// `Screen.extractBlurredBackground`: blur the frame by this radius
/// (`menuBackgroundBlurriness`) before the screen is drawn over it.
pub menu_blur: Option<f32>,
@@ -450,8 +448,6 @@ pub struct Renderer {
/// The selected shader pack's stages (Horizon setting; none by default).
pack: Option<Pack>,
pub hud: HudRenderer,
/// The menus' backdrop blur, made on first use.
post: Option<crate::post::Post>,
/// Vanilla's menu background blur, made on first use.
menu_blur: Option<crate::menu_blur::MenuBlur>,
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,
+3 -7
View File
@@ -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()
+2 -2
View File
@@ -285,7 +285,7 @@ pub fn rows(level: Level) -> Vec<Row> {
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<Row> {
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<bool> {
let g = &s.horizon;
Some(match self {
+2 -2
View File
@@ -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;
+2 -2
View File
@@ -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<PackedImage>) {
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,
+1 -3
View File
@@ -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;
+14 -8
View File
@@ -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;
+33 -1
View File
@@ -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::<Vec<_>>()),
("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",
@@ -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();
+34 -10
View File
@@ -78,8 +78,8 @@ pub enum Screen {
name: String,
lines: std::cell::Cell<usize>,
},
/// 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<String> {
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<String> {
let mut lines = Vec::new();
@@ -1353,6 +1359,24 @@ pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec<String> {
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)
File diff suppressed because it is too large Load Diff
+128 -113
View File
@@ -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<f32>,
/// 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<usize>,
pub(crate) hscroll: f32,
/// The slider being dragged on the Horizon options shell.
pub(crate) hdragging: Option<crate::graphics_ui::Item>,
/// 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<Row> {
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<crate::graphics_ui::Level> {
@@ -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<Page> {
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));
}
}
-273
View File
@@ -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<wgpu::Buffer>,
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::<Uniform>() 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);
}
}
-51
View File
@@ -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<f32>,
// Multiplier and lift of the grade.
tint: vec4<f32>,
lift: vec4<f32>,
// Desaturation, vignette, unused, unused.
params: vec4<f32>,
}
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var samp: sampler;
@group(0) @binding(2) var<uniform> post: Post;
struct Out {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
}
@vertex fn vs_main(@builtin(vertex_index) i: u32) -> Out {
let p = vec2<f32>(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<f32>) -> vec3<f32> {
return textureSampleLevel(src, samp, uv, 0.0).rgb;
}
@fragment fn fs_down(in: Out) -> @location(0) vec4<f32> {
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<f32>) -> vec3<f32> {
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<f32> {
return vec4(up(in.uv), 1.0);
}
@fragment fn fs_final(in: Out) -> @location(0) vec4<f32> {
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);
}
+1 -1
View File
@@ -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;
+16 -20
View File
@@ -142,10 +142,6 @@ pub struct Title {
toast: Option<(crate::toasts::Slide, BackupToast)>,
icons: RefCell<std::collections::HashMap<PathBuf, (std::time::SystemTime, Option<Vec<u8>>)>>,
splash: Option<String>,
/// The mode last drawn and when it appeared (Horizon's screen fades).
shown: std::cell::Cell<(std::mem::Discriminant<Mode>, std::time::Instant)>,
/// The launcher-style opening (Horizon style, first title of the session).
pub opening: std::cell::Cell<Option<crate::front::Opening>>,
/// The saves listed for Home, re-read every couple of seconds.
recent: std::cell::RefCell<Option<(std::time::Instant, Vec<WorldEntry>)>>,
}
@@ -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);
@@ -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
File diff suppressed because it is too large Load Diff
+4 -5
View File
@@ -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<Widget>, Vec<Widget>, 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<Target>, Vec<Target>, u64)> = const { RefCell::new((Vec::new(), Vec::new(), 0)) };
}
+101
View File
@@ -37,6 +37,10 @@ pub struct Report {
pub worldgen: usize,
/// Recipes left as they were: custom types, NeoForge conditions.
pub recipes_kept: Vec<String>,
/// 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<String>,
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<Vec<String>, 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<String> = 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/<id>/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::<Value>(&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::<Value>(&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<String>) {
match v {
+411
View File
@@ -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<String>,
/// What doesn't, with why.
pub skipped: Vec<String>,
/// Required mods, by id.
pub depends: Vec<String>,
/// The folder mod's namespaces (its id first): two mods on at once may
/// not share one.
pub namespaces: Vec<String>,
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<Check, String> {
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<String> = 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<Check, String> {
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::<usize>();
if dropped > 0 {
skipped.push(plural(
dropped,
"structure processor written in Java",
"structure processors written in Java",
));
}
let unsupported = wg.unsupported.values().sum::<usize>();
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();
}
}
+642
View File
@@ -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<String>,
/// Declared methods, by name (constructors and lambdas left out).
pub methods: Vec<String>,
/// Every class the constant pool names (`net/minecraft/...`).
pub refs: BTreeSet<String>,
/// 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<Class> {
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<usize, String> = HashMap::new();
let mut class_of: HashMap<usize, usize> = 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<u8> {
Some(self.take(1)?[0])
}
fn u2(&mut self) -> Option<u16> {
let b = self.take(2)?;
Some(u16::from_be_bytes([b[0], b[1]]))
}
fn u4(&mut self) -> Option<u32> {
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<String, Class>) -> 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<Feature> {
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<Feature, usize>,
/// The game events it subscribes to, by simple name.
pub events: BTreeSet<String>,
/// Blocks and items with behaviour, and the methods they override.
pub examples: BTreeMap<String, Vec<String>>,
}
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<Item = &'a [u8]>) -> Code {
let own: BTreeMap<String, Class> = 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<u8> {
let mut pool: Vec<Vec<u8>> = Vec::new();
let utf = |pool: &mut Vec<Vec<u8>>, 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<Vec<u8>>, 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<u16> = 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<u8> {
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",
&["<init>", "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::<Vec<_>>(),
["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:?}");
}
}
+3 -3
View File
@@ -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),
+2
View File
@@ -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;
+16 -1
View File
@@ -19,6 +19,10 @@
//! - `report <work>`: the coverage report, per mod ported, partial, not yet
//! or not needed with the reason, in `<work>/coverage.json` and
//! `coverage.md`.
//! - `check <jar> <out>`: one mod jar on its own, as the launcher's mod
//! browser installs it: carried over into `<out>/carry/`, its classes
//! read, and the verdict (Works, Partly, Doesn't run) in
//! `<out>/check.json`.
//! - `port <pack> <work> [--from <folder>] [--resources <prepared>]`: 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 <pack> <work> | inventory <work> [--offline] | fetch <work> [--from <folder>] [<mod id>...] | carry <work> [--resources <prepared>] [<mod id>...] | report <work> | port <pack> <work> [--from <folder>] [--resources <prepared>]";
const USAGE: &str = "usage: horizon-port-pack import <pack> <work> | inventory <work> [--offline] | fetch <work> [--from <folder>] [<mod id>...] | carry <work> [--resources <prepared>] [<mod id>...] | report <work> | check <jar> <out> | port <pack> <work> [--from <folder>] [--resources <prepared>]";
fn main() -> ExitCode {
let mut args: Vec<String> = 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)?;
+113 -1
View File
@@ -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/<key>/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<std::path::PathBuf>, Vec<String>) {
let mut on: Vec<(std::path::PathBuf, String, Vec<String>)> = 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<String> = 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<Item = (&'a str, Vec<String>)>,
log: Log,
) -> BTreeSet<String> {
let mut by_namespace: BTreeMap<String, Vec<&str>> = 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::<Vec<_>>(), ["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();
}
}
+34 -3
View File
@@ -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/<id>` | 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
@@ -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 }
}
}
}
+86 -12
View File
@@ -3,6 +3,8 @@
//! - `POST /v1/batch`: a zstd batch from the launcher, checked by `horizon_telemetry::batch`.
//! - `DELETE /v1/installs/<id>`: 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<Option<(Instant, String)>>,
/// `/v1/aggregate` answers by `days`, with when they were made.
cache: Mutex<HashMap<u32, (Instant, String)>>,
/// `/v1/benchmarks/summary`'s answer and when it was made.
summary_cache: Mutex<Option<(Instant, String)>>,
/// Today, in days since 1970 (a test moves it).
today: Box<dyn Fn() -> 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<SocketAddr>) -> 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<usize> {
@@ -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<Arc<App>>, Path(id): Path<String>, 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<Arc<App>>, Query(window): Query<Window>) ->
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<Arc<App>>) -> 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<Arc<App>>, req: Request) -> Response {
@@ -407,6 +480,7 @@ pub fn router(app: Arc<App>) -> 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)
}
+20 -14
View File
@@ -357,27 +357,33 @@ impl Store {
})?
.collect::<Result<_, _>>()?
};
let benchmarks: Vec<serde_json::Value> = {
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<u8> = r.get(2)?;
Ok(serde_json::json!({
"day": r.get::<_, u32>(0)?, "version": r.get::<_, String>(1)?, "report": inflate(&body),
}))
})?
.collect::<Result<_, _>>()?
};
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<Vec<crate::summary::Upload>> {
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<u8>>(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<Option<u32>> {
self.db
@@ -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<u8>,
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::<Vec<_>>()
.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<f64> {
(!xs.is_empty()).then(|| xs.iter().sum::<f64>() / xs.len() as f64)
}
pub fn median(xs: &[f64]) -> Option<f64> {
let mut v: Vec<f64> = 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<f64>; 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::<Vec<_>>(),
)
};
let metrics = report["metrics"].as_object();
let metric = |name: &str| metrics.and_then(|m| m.get(name)?.get("mean")?.as_f64());
let loads: Vec<f64> = 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<u64> {
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<u8>, Vec<[Option<f64>; 7]>>,
reports: usize,
versions: BTreeSet<String>,
}
/// Players' groups of at least `min_installs` installs, as `website/scripts/benchmarks.mjs` makes them.
pub fn groups(uploads: &[Upload], min_installs: usize) -> Vec<Value> {
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<f64>; 7]> = g
.installs
.values()
.map(|runs| {
std::array::from_fn(|i| median(&runs.iter().filter_map(|r| r[i]).collect::<Vec<_>>()))
})
.collect();
let medians: serde_json::Map<String, Value> = FIELDS
.iter()
.enumerate()
.map(|(i, f)| {
let m = median(&per_install.iter().filter_map(|r| r[i]).collect::<Vec<_>>());
(f.to_string(), m.map_or(Value::Null, |m| number(round(f, m))))
})
.collect();
let mut versions: Vec<String> = 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),
})
}
@@ -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]
@@ -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<Value> {
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<Upload> = 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<App>, uri: &str) -> (StatusCode, String, Option<String>) {
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!([]));
}
+29 -7
View File
@@ -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<String> {
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<String> {
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('/'));
}
}
+1 -1
View File
@@ -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]
@@ -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.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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.
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M3 2h18v2H3zm0 5h18v2H3zM1 4h2v3H1zm20 0h2v3h-2zm-2 5h2v11h-2zM3 9h2v11H3zm2 11h14v2H5zm4-9h6v2H9z"/>
</svg>

After

Width:  |  Height:  |  Size: 224 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M20 11v2H4v-2zM8 13v2H6v-2zm2 2v2H8v-2zm2 2v2h-2v-2zm-4-6V9H6v2z"/>
<path d="M10 15V7H8v8zm2 2V5h-2v12z"/>
</svg>

After

Width:  |  Height:  |  Size: 231 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M2 3h9v2H2zM0 19h11v2H0zM13 3h9v2h-9zm0 16h11v2H13zM11 5h2v18h-2zM0 5h2v14H0zm22 0h2v14h-2zm-7 2h5v2h-5zm0 4h5v2h-5zm0 4h2v2h-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 254 B

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M14 4h4v2h-4zm-4-2h4v2h-4zM6 8h4v2H6zm0 10h4v2H6zm4-8h4v2h-4zm0 10h4v2h-4zm4-12h4v2h-4zm0 10h4v2h-4zM6 4h4v2H6zM2 6h4v2H2zm0 10h4v2H2zM18 6h4v2h-4zm0 10h4v2h-4z"/>
<path d="M2 6h2v12H2zm18 0h2v12h-2zm-8 6h2v8h-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 340 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M2 5h2v4H2zm20 0h-2v4h2zM4 9h2v2H4zm16 0h-2v2h2zM2 13h4v2H2zm20 0h-4v2h4zM4 17h2v2H4zm16 0h-2v2h2zM2 19h2v2H2zm20 0h-2v2h2zM6 11h12v2H6z"/>
<path d="M6 7h2v12H6zm10 0h2v12h-2zM8 19h8v2H8zM8 5h8v2H8z"/>
<path d="M11 15h2v6h-2zM8 1h2v6H8zm6 0h2v6h-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 378 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M10 18H8v-2h2v2Zm-2-2H6v-2h2v2Zm4-2v2h-2v-2h2Zm-6 0H4v-2h2v2Zm8 0h-2v-2h2v2Zm2-2h-2v-2h2v2Zm2-2h-2V8h2v2Zm2-2h-2V6h2v2Z"/>
</svg>

After

Width:  |  Height:  |  Size: 245 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M13 16h-2v-2h2v2Zm-2-2H9v-2h2v2Zm4 0h-2v-2h2v2Zm-6-2H7v-2h2v2Zm8 0h-2v-2h2v2ZM7 10H5V8h2v2Zm12 0h-2V8h2v2Z"/>
</svg>

After

Width:  |  Height:  |  Size: 232 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M16 13v-2h-2v2h2Zm-2-2V9h-2v2h2Zm0 4v-2h-2v2h2Zm-2-6V7h-2v2h2Zm0 8v-2h-2v2h2ZM10 7V5H8v2h2Zm0 12v-2H8v2h2Z"/>
</svg>

After

Width:  |  Height:  |  Size: 232 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M6 2h12v2H6zM2 6h2v12H2zm18 0h2v12h-2zm-2-2h2v2h-2zM4 4h2v2H4zm2 18h12v-2H6zm12-2h2v-2h-2zM4 20h2v-2H4zm7-14h2v7h-2zm2 7h2v2h-2zm2 2h2v2h-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 266 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M7 19H5V17H7V19ZM19 19H17V17H19V19ZM9 15V17H7V15H9ZM17 17H15V15H17V17ZM11 15H9V13H11V15ZM15 15H13V13H15V15ZM13 13H11V11H13V13ZM11 11H9V9H11V11ZM15 11H13V9H15V11ZM9 9H7V7H9V9ZM17 9H15V7H17V9ZM7 7H5V5H7V7ZM19 7H17V5H19V7Z"/>
</svg>

After

Width:  |  Height:  |  Size: 343 B

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M21 15v4h-2v-4zm-2 4v2H5v-2zM5 15v4H3v-4zm8-12v14h-2V3z"/>
<path d="M7 11v2h10v-2zm2 2v2h2v-2zm4 0v2h2v-2z"/>
<path d="M15 11v2h2v-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 263 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M11 5H5v2h6V5ZM5 7H3v12h2V7Zm12 12H5v2h12v-2Zm2-6h-2v6h2v-6Zm-8 0H9v2h2v-2Zm2-2h-2v2h2v-2Zm2-2h-2v2h2V9Zm2-2h-2v2h2V7Zm2-2h-2v2h2V5Zm2-2h-2v8h2V3Z"/>
<path d="M21 3h-8v2h8V3Z"/>
</svg>

After

Width:  |  Height:  |  Size: 302 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M4 4h6v2H4zm0 14h16v2H4zM20 8h2v10h-2zM2 6h2v12H2zm8 0h10v2H10z"/>
</svg>

After

Width:  |  Height:  |  Size: 189 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M4 4h16v2H4zm0 14h16v2H4zM2 6h2v12H2zm18 0h2v12h-2zM8 9h2v6H8z"/>
<path d="M6 11h6v2H6zm8-2h2v2h-2zm2 4h2v2h-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 239 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M6 2h12v2H6zm0 18h12v2H6zM4 4h2v2H4zm5 0h2v2H9zm0 14h2v2H9zm4 0h2v2h-2zM7 6h2v12H7zm8 0h2v12h-2zm-2-2h2v2h-2zm7 0h-2v2h2zM2 6h2v12H2zm20 0h-2v12h2zM4 18h2v2H4zm16 0h-2v2h2z"/>
<path d="M3 11h18v2H3z"/>
</svg>

After

Width:  |  Height:  |  Size: 326 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M13 22h-2v-2h2v2Zm-2-2H9v-2h2v2Zm4 0h-2v-2h2v2Zm-6-2H7v-2h2v2Zm8 0h-2v-2h2v2ZM7 16H5v-2h2v2Zm12 0h-2v-2h2v2ZM5 14H3v-2h2v2Zm16 0h-2v-2h2v2ZM3 12H1V6h2v6Zm20 0h-2V6h2v6ZM13 8h-2V6h2v2ZM5 6H3V4h2v2Zm6 0H9V4h2v2Zm4 0h-2V4h2v2Zm6 0h-2V4h2v2ZM9 4H5V2h4v2Zm10 0h-4V2h4v2Z"/>
</svg>

After

Width:  |  Height:  |  Size: 391 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M4 20h16v2H4zm16-10h2v10h-2zM2 10h2v10H2zm2-2h2v2H4zm2-2h2v2H6zm2-2h2v2H8zm2-2h4v2h-4zm4 2h2v2h-2zm2 2h2v2h-2zm2 2h2v2h-2zM8 14h2v6H8zm2-2h4v2h-4zm4 2h2v6h-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 284 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M4 2h16v2H4zm0 18h16v2H4zM2 4h2v16H2zm18 0h2v16h-2zm-4 8h2v2h-2zm-2 2h2v2h-2zm4 0h2v2h-2zm-8 0h2v2h-2zm2 2h2v2h-2zm2 2h2v2h-2z"/>
<path d="M20 16h2v2h-2zM8 16h2v2H8zm-2 2h2v2H6zM8 6h2v2H8zM6 8h2v2H6zm2 2h2v2H8zm2-2h2v2h-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 350 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M4 2h16v2H4zm0 18h16v2H4zM2 4h2v16H2zm18 0h2v16h-2zm-9 5h2V7h-2zm0 8h2v-6h-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 203 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M20 2H4v2h16zm0 14H6v2h14zm2-12h-2v12h2zM4 4H2v18h2zm2 14H4v2h2z"/>
</svg>

After

Width:  |  Height:  |  Size: 190 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M4 2h16v2H4zm0 14h16v2H4zM2 4h2v12H2zm18 0h2v12h-2zm-9 14h2v2h-2zm-3 2h8v2H8z"/>
</svg>

After

Width:  |  Height:  |  Size: 203 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M6 8h2v12H6zM2 4h2v12H2zm18 4h2v8h-2zM8 6h12v2H8zM4 2h12v2H4zm14 14h2v2h-2zm-2 2h2v2h-2zm-8 2h8v2H8zm6-6h6v2h-6z"/>
<path d="M14 14h2v6h-2zm2-10h2v2h-2zM4 16h2v2H4z"/>
</svg>

After

Width:  |  Height:  |  Size: 292 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M10 20h4v2h-4zm0-16h4V2h-4zm0 6h4v2h-4zm4 8h4v2h-4zm0-12h4V4h-4zm0 2h4v2h-4zm4 8h4v2h-4zm0-8h4V6h-4zM6 18h4v2H6zM6 6h4V4H6zm0 2h4v2H6zm-4 8h4v2H2zm0-8h4V6H2z"/>
<path d="M2 6h2v12H2zm18 0h2v12h-2zm-8 6h2v8h-2zm-2-6h4v2h-4z"/>
</svg>

After

Width:  |  Height:  |  Size: 350 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M15 11h-2V9h2zm0 4h-2v-2h2zm-2 2h-2v-2h2zm0-8h-2V7h2zm-2-2H9V5h2zM9 21H7V3h2zm6-8h2v-2h-2zm-6 4h2v2H9z"/>
</svg>

After

Width:  |  Height:  |  Size: 228 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M13 11h7v2h-7v7h-2v-7H4v-2h7V4h2v7Z"/>
</svg>

After

Width:  |  Height:  |  Size: 161 B

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M16 4h2v6h-2zm-2-2h2v2h-2zm0 2h2v8h-2zM4 8H2v5h2z"/>
<path d="M4 6h16v2H4zm4 14H6v-6h2zm2 2H8v-2h2zm0-2H8v-8h2zm10-4h2v-5h-2z"/>
<path d="M20 18H4v-2h16z"/>
</svg>

After

Width:  |  Height:  |  Size: 283 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M22 22h-2v-2h2v2Zm-2-2h-2v-2h2v2Zm-6-2H6v-2h8v2Zm4 0h-2v-2h2v2ZM6 16H4v-2h2v2Zm10 0h-2v-2h2v2ZM4 14H2V6h2v8Zm14 0h-2V6h2v8ZM6 6H4V4h2v2Zm10 0h-2V4h2v2Zm-2-2H6V2h8v2Z"/>
</svg>

After

Width:  |  Height:  |  Size: 291 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M6 7h4v2H6zm0 8h4v2H6zM2 5h2v14H2zm18 0h2v14h-2zM4 19h16v2H4zM4 3h16v2H4zm0 8h16v2H4z"/>
</svg>

After

Width:  |  Height:  |  Size: 211 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24"><path d="M8 14H7v6H5v-6H2v-2h6v2Zm5 6h-2V10h2v10Zm9-2h-3v2h-2v-2h-1v-2h6v2Zm-3-4h-2V4h2v10ZM7 10H5V4h2v6Zm6-4h2v2H9V6h2V4h2v2Z"/></svg>

After

Width:  |  Height:  |  Size: 215 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M4 2h16v2H4zm0 18h16v2H4zM2 4h2v16H2zm18 0h2v16h-2zM6 16h2v2H6zm2-2h2v2H8zm-2-2h2v2H6z"/>
</svg>

After

Width:  |  Height:  |  Size: 212 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M18 22H6V20H18V22ZM9 6H15V4H17V6H22V8H20V20H18V8H6V20H4V8H2V6H7V4H9V6ZM15 4H9V2H15V4Z"/>
</svg>

After

Width:  |  Height:  |  Size: 209 B

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M9 2h6v2H9zm0 8h6v2H9zm6-6h2v6h-2zM7 4h2v6H7zM4 18h2v4H4zm14 0h2v4h-2zM8 14h8v2H8zm-2 2h2v2H6zm10 0h2v2h-2z"/>
</svg>

After

Width:  |  Height:  |  Size: 233 B

+3
View File
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path d="M4 13h8v6h2v2h-2v2h-2v-8H2v-4h2v2Zm12 6h-2v-2h2v2Zm2-2h-2v-2h2v2Zm2-2h-2v-2h2v2Zm-6-6h8v4h-2v-2h-8V5h-2V3h2V1h2v8Zm-8 2H4V9h2v2Zm2-2H6V7h2v2Zm2-2H8V5h2v2Z"/>
</svg>

After

Width:  |  Height:  |  Size: 280 B

+272 -5
View File
@@ -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]
+1 -1
View File
@@ -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
+3 -5
View File
@@ -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 `<kind>-<n>` 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-<ID>` with
names; inventory, creative and menu slots are `slot-<ID>` 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`.
+15 -19
View File
@@ -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

Some files were not shown because too many files have changed in this diff Show More