diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 89a7449ab..497fa8418 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -784,6 +784,10 @@ struct Game<'a> { /// Control replies waiting for a rendered frame or a benchmark deadline. pending_screenshot: Option>, pending_bench: Option<(Instant, std::sync::mpsc::Sender)>, + /// Recent frame times for the performance overlay. + frame_graph: horizon_client::perf_overlay::FrameGraph, + /// Meshed sections waiting for an upload budget (Horizon settings). + pending_uploads: Vec<((i32, i32, i32), horizon_client::mesher::SectionMesh)>, /// This frame's view frustum, for culling entities and block entities. view_frustum: Option, /// A scripted flight from the control socket (`fly`). @@ -2981,6 +2985,12 @@ impl Game<'_> { hud_layout::paint(batch, &self.res.atlas, &draws); } fn hud(&mut self, size: [u32; 2]) -> HudBatch { + let mut batch = self.hud_layers(size); + self.frame_graph + .draw(self.settings.horizon.overlay, &mut batch, &self.res.atlas); + batch + } + fn hud_layers(&mut self, size: [u32; 2]) -> HudBatch { let mut batch = HudBatch::new(size); let (w, h) = (batch.width, batch.height); if self.screen == Screen::Options { @@ -7338,9 +7348,11 @@ impl Game<'_> { horizon_client::spans::time("clouds", || { self.cloud_geometry(&sky, camera, alpha, &mut entities) }); - horizon_client::spans::time("weather", || { - self.weather_geometry(camera, alpha, &mut entities) - }); + if self.settings.horizon.weather { + horizon_client::spans::time("weather", || { + self.weather_geometry(camera, alpha, &mut entities) + }); + } } let water_fog = { let c = info.water_fog; @@ -7363,23 +7375,36 @@ impl Game<'_> { distance, underwater, title, - skybox: self.dim == Dim::Overworld, - end_sky: self.dim == Dim::End, + skybox: self.dim == Dim::Overworld && self.settings.horizon.sky, + end_sky: self.dim == Dim::End && self.settings.horizon.sky, environment_fog: (self.dim == Dim::Nether).then_some((sky.fog_start, sky.fog_end)), // The camera inside an opaque block sees nothing through it: disable. - cave_culling: !self - .res - .facts - .get(self.world.block(block[0], block[1], block[2])) - .solid_render, + cave_culling: self.settings.horizon.cave_culling + && !self + .res + .facts + .get(self.world.block(block[0], block[1], block[2])) + .solid_render, water_fog, - fog: Some(self.frame_fog(camera, &sky, biome)), + fog: Some({ + let mut fog = self.frame_fog(camera, &sky, biome); + // Horizon's fog setting: no distance fog (fluids keep theirs). + if !self.settings.horizon.fog && !underwater && fog.environmental_end >= distance { + (fog.render_distance_start, fog.render_distance_end) = (1e9, 2e9); + (fog.environmental_start, fog.environmental_end) = (1e9, 2e9); + } + fog + }), dark_disc: self.dark_disc(camera), outline, hud: &hud, entities: &entities, additive: &additive, - celestial: &celestial, + celestial: if self.settings.horizon.sky || title { + &celestial + } else { + &[] + }, hand: &hand, screen: &screen, border, @@ -7631,11 +7656,45 @@ impl Game<'_> { eprintln!("Horizon: failed to save unloaded chunks: {e}"); } if let Some(renderer) = self.renderer.as_mut() { - horizon_client::spans::time("upload", || { - for (key, mesh) in uploads { + let g = &self.settings.horizon; + let budgeted = g.chunk_updates > 0 || g.upload_budget_kib > 0; + if !budgeted && self.pending_uploads.is_empty() { + horizon_client::spans::time("upload", || { + for (key, mesh) in uploads { + renderer.upload(key, &mesh); + } + }); + } else { + // Horizon's chunk-update and upload budgets: the nearest + // sections go first, the rest wait for later frames; a newer + // mesh of a waiting section replaces it. + let pending = &mut self.pending_uploads; + let fresh: horizon_client::fast_hash::FxHashSet<(i32, i32, i32)> = + uploads.iter().map(|(k, _)| *k).collect(); + let gone: horizon_client::fast_hash::FxHashSet<(i32, i32)> = + unloaded.iter().map(|c| (c.x, c.z)).collect(); + pending.retain(|(k, _)| !fresh.contains(k) && !gone.contains(&(k.0, k.2))); + pending.extend(uploads); + let centre = self.streaming.center; + let far = |k: &(i32, i32, i32)| (k.0 - centre.0).pow(2) + (k.2 - centre.1).pow(2); + pending.sort_unstable_by_key(|(k, _)| std::cmp::Reverse(far(k))); + let (limit, budget) = if budgeted { + (g.chunk_updates as usize, u64::from(g.upload_budget_kib) * 1024) + } else { + (0, 0) + }; + let (mut count, mut bytes) = (0, 0u64); + while let Some((_, mesh)) = pending.last() { + let size = ((mesh.solid.len() + mesh.translucent.len()) * 32) as u64; + if (limit > 0 && count >= limit) || (budget > 0 && bytes > 0 && bytes + size > budget) { + break; + } + let (key, mesh) = pending.pop().expect("checked above"); renderer.upload(key, &mesh); + count += 1; + bytes += size; } - }); + } for c in unloaded { for sy in 0..(HEIGHT / 16) { renderer.remove((c.x, sy, c.z)); @@ -8120,6 +8179,11 @@ impl ApplicationHandler for Game<'_> { let cpu = now.elapsed().saturating_sub(r.last_wait); if rendered { let ms = |d: Duration| d.as_secs_f32() * 1000.0; + self.frame_graph.record( + ms(elapsed), + ms(cpu), + r.gpu_times.last().copied(), + ); self.frame_stats.record_cpu(ms(cpu)); let render = r.last_encode; self.frame_stats.record_phases([ @@ -8537,6 +8601,8 @@ pub fn run() -> Result<()> { pending_bench: None, flight: None, view_frustum: None, + pending_uploads: Vec::new(), + frame_graph: Default::default(), sky_darken_memo: Default::default(), persist: Default::default(), remote: None, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 64960ac23..269f2b839 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -29,7 +29,7 @@ const HELP: &[&str] = &[ "chat TEXT send a chat line or /command as if typed", "type TEXT type into the open chat box (key enter tap sends)", "chat-log [N] the newest N chat messages (default 10)", - "options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs)", + "options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs graphics graphics-advanced)", "stats [reset] frame-time summary since the last reset", "bench SECONDS reset stats, wait, then reply with the summary", "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH] fly the camera along a line at constant speed, then reply with the frame summary", @@ -361,6 +361,8 @@ impl Game<'_> { "language" => Page::Language, "font" => Page::Font, "packs" => Page::Packs, + "graphics" => Page::Graphics, + "graphics-advanced" => Page::GraphicsAdvanced, other => return Err(format!("unknown options page {other}").into()), }; if self.screen == Screen::Playing && self.title.is_none() { @@ -573,7 +575,7 @@ impl Game<'_> { "using": self.using, "render_distance": self.streaming.radius, "chunks": self.world.chunks.len(), - "pending_chunks": self.streaming.pending(), + "pending_chunks": self.streaming.pending() + self.pending_uploads.len(), "generated_chunks": self.streaming.generated_total, "meshed_sections": self.streaming.meshed_total, "renderer": renderer, diff --git a/crates/horizon-client/src/graphics_style.rs b/crates/horizon-client/src/graphics_style.rs new file mode 100644 index 000000000..ccb3f2d47 --- /dev/null +++ b/crates/horizon-client/src/graphics_style.rs @@ -0,0 +1,163 @@ +//! The look of Horizon's graphics settings screens, in one place: sizes, +//! colours and the widgets they draw with. The screens (`graphics_ui`) only +//! lay out rows and handle input; a menu theme replaces this module. +use crate::{ + hud::{HudAtlas, HudBatch}, + text::Text, + ui, +}; + +/// What a setting costs in frame time, shown beside its description. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Cost { + None, + Low, + Medium, + High, +} +impl Cost { + pub fn label(self) -> &'static str { + match self { + Cost::None => "No cost", + Cost::Low => "Low cost", + Cost::Medium => "Medium cost", + Cost::High => "High cost", + } + } +} + +pub struct Style { + /// Width of a setting's button or slider. + pub control_width: f32, + /// Space between the control and its description. + pub gap: f32, + /// Widest description column; narrower on small screens. + pub max_text_width: f32, + /// Vertical distance between setting rows. + pub row_height: f32, + pub header_height: f32, + /// Top and bottom bands holding the title and the buttons. + pub band: f32, + pub title_color: u32, + pub header_color: u32, + pub description_color: u32, + /// Colour of each `Cost`, in its order. + pub cost_colors: [u32; 4], +} + +/// `hud::rgba` with full alpha, usable in constants. +const fn opaque(r: u8, g: u8, b: u8) -> u32 { + 0xFF00_0000 | (b as u32) << 16 | (g as u32) << 8 | r as u32 +} + +pub const STYLE: Style = Style { + control_width: 150.0, + gap: 8.0, + max_text_width: 250.0, + row_height: 25.0, + header_height: 16.0, + band: 33.0, + title_color: u32::MAX, + header_color: opaque(255, 255, 85), + description_color: opaque(170, 170, 170), + cost_colors: [ + opaque(120, 200, 120), + opaque(170, 220, 120), + opaque(240, 200, 90), + opaque(240, 110, 90), + ], +}; + +impl Style { + /// Width of the description column on a screen `screen_width` wide. + pub fn text_width(&self, screen_width: f32) -> f32 { + (screen_width - self.control_width - self.gap - 24.0).clamp(120.0, self.max_text_width) + } + /// Left edge of a row's control, centring control and description. + pub fn row_x(&self, screen_width: f32) -> f32 { + let total = self.control_width + self.gap + self.text_width(screen_width); + ((screen_width - total) / 2.0).floor() + } + pub fn background(&self, batch: &mut HudBatch, atlas: &HudAtlas, top: f32, bottom: f32, in_world: bool) { + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, in_world); + ui::list_background(batch, atlas, top, bottom, in_world); + } + pub fn frame(&self, batch: &mut HudBatch, atlas: &HudAtlas, top: f32, bottom: f32, in_world: bool) { + ui::separators(batch, atlas, top, bottom, in_world); + } + pub fn title(&self, batch: &mut HudBatch, atlas: &HudAtlas, text: &Text) { + let w = batch.width; + ui::centered_text(batch, atlas, text, 0.0, 12.0, w, self.title_color); + } + pub fn header(&self, batch: &mut HudBatch, atlas: &HudAtlas, text: &Text, x: f32, y: f32) { + batch.text_styled(atlas, text, x, y + 4.0, self.header_color, true); + } + pub fn button( + &self, + batch: &mut HudBatch, + atlas: &HudAtlas, + (x, y, w): (f32, f32, f32), + label: &Text, + hover: bool, + ) { + ui::button(batch, atlas, x, y, w, 20.0, label, true, hover); + } + pub fn slider( + &self, + batch: &mut HudBatch, + atlas: &HudAtlas, + (x, y, w): (f32, f32, f32), + label: &Text, + value: f32, + hover: bool, + ) { + ui::slider(batch, atlas, x, y, w, label, value, hover, true); + } + /// The cost tag and the description beside a control, wrapped to two lines. + pub fn description( + &self, + batch: &mut HudBatch, + atlas: &HudAtlas, + x: f32, + y: f32, + cost: Cost, + text: &str, + ) { + let tag = Text::literal(cost.label()); + batch.text_styled(atlas, &tag, x, y, self.cost_colors[cost as usize], true); + let indent = atlas.font.width_text(&tag) + 4.0; + let lines = wrap(atlas, text, self.text_width(batch.width), indent); + for (i, line) in lines.iter().take(2).enumerate() { + let lx = if i == 0 { x + indent } else { x }; + batch.text_styled( + atlas, + &Text::literal(line.clone()), + lx, + y + i as f32 * 10.0, + self.description_color, + true, + ); + } + } +} + +/// Greedy word wrap; the first line is `indent` narrower. +fn wrap(atlas: &HudAtlas, text: &str, width: f32, indent: f32) -> Vec { + let mut lines = vec![String::new()]; + for word in text.split_whitespace() { + let room = if lines.len() == 1 { width - indent } else { width }; + let line = lines.last().expect("one line"); + let candidate = if line.is_empty() { + word.to_owned() + } else { + format!("{line} {word}") + }; + if atlas.font.width(&candidate) <= room || line.is_empty() { + *lines.last_mut().expect("one line") = candidate; + } else { + lines.push(word.to_owned()); + } + } + lines +} diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs new file mode 100644 index 000000000..6c87d7f10 --- /dev/null +++ b/crates/horizon-client/src/graphics_ui.rs @@ -0,0 +1,624 @@ +//! Horizon's graphics settings screens, Simple and Advanced: which settings +//! they show, in what groups, with what description and cost, and their +//! input. How they look comes from `graphics_style`. +use crate::{ + graphics::{Overlay, Pacing, Preset, PresentMode}, + graphics_style::{Cost, STYLE}, + hud::{HudAtlas, HudBatch}, + options_ui::Opt, + settings::Settings, + text::Text, + ui, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Level { + Simple, + Advanced, +} + +/// Horizon's own settings (`graphics::Graphics`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum H { + Preset, + CaveCulling, + ChunkUpdates, + UploadBudget, + Sky, + Fog, + Weather, + AnimatedTextures, + PresentMode, + Pacing, + Workers, + Overlay, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Item { + Vanilla(Opt), + Horizon(H), +} + +struct Setting { + item: Item, + cost: Cost, + text: &'static str, +} +enum Row { + Header(&'static str), + Setting(Setting), +} +fn v(opt: Opt, cost: Cost, text: &'static str) -> Row { + Row::Setting(Setting { + item: Item::Vanilla(opt), + cost, + text, + }) +} +fn h(opt: H, cost: Cost, text: &'static str) -> Row { + Row::Setting(Setting { + item: Item::Horizon(opt), + cost, + text, + }) +} + +fn rows(level: Level) -> Vec { + use Cost::*; + let render = v( + Opt::RenderDistance, + High, + "How far terrain is drawn, in chunks. The biggest lever on frame time.", + ); + let fov = v(Opt::Fov, Low, "Field of view. Wider shows more terrain at once."); + let fps = v( + Opt::MaxFps, + None, + "Caps frames per second; a cap saves power and heat.", + ); + let vsync = v( + Opt::Vsync, + None, + "Waits for the display's refresh: no tearing, a little latency.", + ); + let gui = v(Opt::GuiScale, None, "Size of menus and the HUD."); + let preset = h( + H::Preset, + None, + "Sets the options below together. Changing one makes it Custom.", + ); + match level { + Level::Simple => vec![preset, render, fov, fps, vsync, gui], + Level::Advanced => vec![ + Row::Header("Rendering"), + render, + v( + Opt::SimulationDistance, + Medium, + "How far mobs, crops and machines keep working. CPU time.", + ), + v( + Opt::EntityDistance, + Medium, + "How far away mobs and items are drawn, as a share of normal.", + ), + h( + H::CaveCulling, + None, + "Skips terrain hidden behind closed sections. Off costs a lot.", + ), + h( + H::ChunkUpdates, + Low, + "Meshed sections uploaded per frame. Lower is smoother while loading.", + ), + Row::Header("Quality"), + v( + Opt::SmoothLighting, + Low, + "Soft shadows in corners. Costs chunk building time only.", + ), + v( + Opt::BiomeBlend, + Low, + "Blends grass and water colours across biomes when building chunks.", + ), + v( + Opt::Clouds, + Medium, + "Cloud layer: off, flat (fast) or 3D (fancy).", + ), + v(Opt::CloudRange, Low, "How far clouds reach, in chunks."), + h(H::Sky, Low, "Draws the sky, sun, moon and stars."), + h( + H::Fog, + None, + "Distance fog. Off shows the edge of the loaded world.", + ), + h(H::Weather, Low, "Draws rain and snow."), + v(Opt::WeatherRadius, Low, "How far rain and snow fall around you."), + v( + Opt::Particles, + Medium, + "How many particles effects spawn.", + ), + v(Opt::EntityShadows, Low, "Round shadows under mobs and items."), + v( + Opt::CutoutLeaves, + Medium, + "Leaves with see-through gaps. Off draws them solid.", + ), + h( + H::AnimatedTextures, + Low, + "Animates water, lava, fire and other moving textures.", + ), + Row::Header("Display"), + fov, + fps, + vsync, + h( + H::PresentMode, + None, + "How frames reach the screen. Auto follows VSync.", + ), + h( + H::Pacing, + None, + "Efficient sleeps until the next frame; Precise spins, like vanilla.", + ), + v(Opt::Fullscreen, None, "Fills the screen (borderless)."), + gui, + Row::Header("Performance"), + h( + H::Workers, + None, + "Threads that generate, light and mesh chunks. Next start.", + ), + h( + H::UploadBudget, + Low, + "Mesh data sent to the GPU per frame. Lower is smoother while loading.", + ), + Row::Header("Overlay"), + h( + H::Overlay, + None, + "Frame rate and frame times over the game, with a graph.", + ), + ], + } +} + +const UPLOAD_STEPS: [u32; 8] = [0, 256, 512, 1024, 2048, 4096, 8192, 16384]; + +fn on_off(on: bool) -> &'static str { + if on { "On" } else { "Off" } +} +fn labelled(caption: &str, value: impl std::fmt::Display) -> Text { + Text::literal(format!("{caption}: {value}")) +} + +impl H { + fn slider(self, s: &Settings) -> Option { + let g = &s.horizon; + match self { + H::ChunkUpdates => Some(g.chunk_updates as f32 / 64.0), + H::UploadBudget => { + let i = UPLOAD_STEPS + .iter() + .position(|&b| b >= g.upload_budget_kib) + .unwrap_or(UPLOAD_STEPS.len() - 1); + Some(i as f32 / (UPLOAD_STEPS.len() - 1) as f32) + } + H::Workers => Some(g.workers as f32 / max_workers() as f32), + _ => None, + } + } + fn label(self, s: &Settings) -> Text { + let g = &s.horizon; + match self { + H::Preset => labelled("Preset", g.preset.label()), + H::CaveCulling => labelled("Cave Culling", on_off(g.cave_culling)), + H::ChunkUpdates => match g.chunk_updates { + 0 => labelled("Chunk Updates", "Unlimited"), + n => labelled("Chunk Updates", format!("{n} per frame")), + }, + H::UploadBudget => match g.upload_budget_kib { + 0 => labelled("Upload Budget", "Unlimited"), + k if k >= 1024 => labelled("Upload Budget", format!("{} MiB/frame", k / 1024)), + k => labelled("Upload Budget", format!("{k} KiB/frame")), + }, + H::Sky => labelled("Sky", on_off(g.sky)), + H::Fog => labelled("Fog", on_off(g.fog)), + H::Weather => labelled("Weather", on_off(g.weather)), + H::AnimatedTextures => labelled("Animated Textures", on_off(g.animated_textures)), + H::PresentMode => labelled("Present Mode", g.present_mode.label()), + H::Pacing => labelled( + "Frame Pacing", + match g.pacing { + Pacing::Efficient => "Efficient", + Pacing::Precise => "Precise", + }, + ), + H::Workers => match g.workers { + 0 => labelled("Worker Threads", format!("Auto ({})", g.worker_threads())), + n => labelled("Worker Threads", n), + }, + H::Overlay => labelled( + "Performance Overlay", + match g.overlay { + Overlay::Off => "Off", + Overlay::Fps => "FPS", + Overlay::Graph => "FPS and Graph", + }, + ), + } + } + fn set_slider(self, s: &mut Settings, v: f32) { + let g = &mut s.horizon; + match self { + H::ChunkUpdates => g.chunk_updates = (v * 64.0).round() as u32, + H::UploadBudget => { + g.upload_budget_kib = + UPLOAD_STEPS[(v * (UPLOAD_STEPS.len() - 1) as f32).round() as usize] + } + H::Workers => g.workers = (v * max_workers() as f32).round() as u32, + _ => {} + } + } + fn cycle(self, s: &mut Settings, back: bool) { + fn step(all: &[T], now: T, back: bool) -> T { + let i = all.iter().position(|x| *x == now).unwrap_or(0); + let n = all.len(); + all[if back { (i + n - 1) % n } else { (i + 1) % n }] + } + if self == H::Preset { + let preset = step(&Preset::ALL, s.horizon.preset, back); + crate::graphics::apply_preset(preset, s); + s.horizon.preset = preset; + return; + } + let g = &mut s.horizon; + match self { + H::CaveCulling => g.cave_culling = !g.cave_culling, + H::Sky => g.sky = !g.sky, + H::Fog => g.fog = !g.fog, + H::Weather => g.weather = !g.weather, + H::AnimatedTextures => g.animated_textures = !g.animated_textures, + H::PresentMode => g.present_mode = step(&PresentMode::ALL, g.present_mode, back), + H::Pacing => { + g.pacing = match g.pacing { + Pacing::Efficient => Pacing::Precise, + Pacing::Precise => Pacing::Efficient, + } + } + H::Overlay => { + g.overlay = step(&[Overlay::Off, Overlay::Fps, Overlay::Graph], g.overlay, back) + } + _ => {} + } + } +} +fn max_workers() -> u32 { + std::thread::available_parallelism().map_or(8, |n| n.get() as u32) +} + +impl Item { + fn slider(self, s: &Settings) -> Option { + match self { + Item::Vanilla(o) => o.slider_position(s), + Item::Horizon(h) => h.slider(s), + } + } + fn label(self, s: &Settings) -> Text { + match self { + // The vanilla button shows the scale alone, under its own caption. + Item::Vanilla(Opt::GuiScale) => Text::translate( + "options.generic_value", + &[Text::translate("options.guiScale", &[]), Opt::GuiScale.label(s)], + ), + Item::Vanilla(o) => o.label(s), + Item::Horizon(h) => h.label(s), + } + } + fn set_slider(self, s: &mut Settings, v: f32) { + match self { + Item::Vanilla(o) => o.set_slider(s, v), + Item::Horizon(h) => h.set_slider(s, v), + } + self.touched(s); + } + fn cycle(self, s: &mut Settings, back: bool) { + match self { + Item::Vanilla(o) => o.cycle(s, back), + Item::Horizon(h) => h.cycle(s, back), + } + self.touched(s); + } + /// A preset no longer describes the settings once one of them changes. + fn touched(self, s: &mut Settings) { + let presetless = matches!( + self, + Item::Horizon(H::Preset | H::Overlay | H::Pacing | H::PresentMode | H::Workers) + | Item::Vanilla(Opt::GuiScale | Opt::Fullscreen | Opt::Vsync | Opt::MaxFps | Opt::Fov) + ); + if !presetless { + s.horizon.preset = Preset::Custom; + } + } +} + +/// What the options screens must do after an interaction here. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Action { + Changed, + OpenAdvanced, + OpenSimple, + Done, +} + +#[derive(Clone, Copy)] +enum Target { + Item(Item), + Button(Action), +} +struct Widget { + x: f32, + y: f32, + w: f32, + target: Target, + /// In the scrolling list (clipped to it). + list: bool, +} + +#[derive(Default)] +pub struct GraphicsUi { + scroll: f32, + dragging: Option, +} + +impl GraphicsUi { + pub fn reset(&mut self) { + self.scroll = 0.0; + self.dragging = None; + } + fn bounds(h: f32) -> (f32, f32) { + (STYLE.band, h - STYLE.band) + } + /// Widgets and the list's content height. + fn layout(&self, level: Level, w: f32, h: f32) -> (Vec, Vec<(f32, &'static str)>, f32) { + let (top, _) = Self::bounds(h); + let x = STYLE.row_x(w); + let mut y = top + 4.0 - self.scroll; + let start = y; + let mut widgets = Vec::new(); + let mut headers = Vec::new(); + for row in rows(level) { + match row { + Row::Header(name) => { + headers.push((y, name)); + y += STYLE.header_height; + } + Row::Setting(s) => { + widgets.push(Widget { + x, + y, + w: STYLE.control_width, + target: Target::Item(s.item), + list: true, + }); + y += STYLE.row_height; + } + } + } + let content = y - start + 4.0; + let cx = (w / 2.0).floor(); + let by = h - 27.0; + let other = match level { + Level::Simple => Action::OpenAdvanced, + Level::Advanced => Action::OpenSimple, + }; + widgets.push(Widget { + x: cx - 155.0, + y: by, + w: 150.0, + target: Target::Button(other), + list: false, + }); + widgets.push(Widget { + x: cx + 5.0, + y: by, + w: 150.0, + target: Target::Button(Action::Done), + list: false, + }); + (widgets, headers, content) + } + fn clamp_scroll(&mut self, h: f32, content: f32) { + let (top, bottom) = Self::bounds(h); + self.scroll = self.scroll.clamp(0.0, (content - (bottom - top)).max(0.0)); + } + pub fn draw( + &mut self, + level: Level, + s: &Settings, + batch: &mut HudBatch, + atlas: &HudAtlas, + cursor: (f32, f32), + in_world: bool, + ) { + let (w, h) = (batch.width, batch.height); + let (_, _, content) = self.layout(level, w, h); + self.clamp_scroll(h, content); + let (widgets, headers, _) = self.layout(level, w, h); + let (top, bottom) = Self::bounds(h); + STYLE.background(batch, atlas, top, bottom, in_world); + let shown = |y: f32, height: f32| y >= top && y + height <= bottom; + let x = STYLE.row_x(w); + for (y, name) in headers { + if shown(y, STYLE.header_height) { + STYLE.header(batch, atlas, &Text::literal(name), x, y); + } + } + let descriptions: Vec<(Cost, &'static str)> = rows(level) + .into_iter() + .filter_map(|r| match r { + Row::Setting(s) => Some((s.cost, s.text)), + Row::Header(_) => None, + }) + .collect(); + let mut index = 0; + for wd in &widgets { + let hover = ui::hovered(cursor, wd.x, wd.y, wd.w, 20.0) + && (!wd.list || (cursor.1 >= top && cursor.1 < bottom)); + match wd.target { + Target::Item(item) => { + let (cost, text) = descriptions[index]; + index += 1; + if !shown(wd.y, 20.0) { + continue; + } + let label = item.label(s); + match item.slider(s) { + Some(value) => STYLE.slider( + batch, + atlas, + (wd.x, wd.y, wd.w), + &label, + value, + hover || self.dragging == Some(item), + ), + None => STYLE.button(batch, atlas, (wd.x, wd.y, wd.w), &label, hover), + } + STYLE.description( + batch, + atlas, + wd.x + wd.w + STYLE.gap, + wd.y + 1.0, + cost, + text, + ); + } + Target::Button(action) => { + let label = match action { + Action::OpenAdvanced => "Advanced...", + Action::OpenSimple => "Simple...", + _ => "Done", + }; + STYLE.button(batch, atlas, (wd.x, wd.y, wd.w), &Text::literal(label), hover); + } + } + } + STYLE.frame(batch, atlas, top, bottom, in_world); + ui::scrollbar( + batch, + atlas, + x + STYLE.control_width + STYLE.gap + STYLE.text_width(w) + 6.0, + top, + bottom, + content, + self.scroll, + ); + let title = match level { + Level::Simple => "Graphics", + Level::Advanced => "Graphics: Advanced", + }; + STYLE.title(batch, atlas, &Text::literal(title)); + } + /// A press (or a drag with `drag`) at `(x, y)`. + pub fn click( + &mut self, + level: Level, + s: &mut Settings, + (x, y): (f32, f32), + (w, h): (f32, f32), + drag: bool, + right: bool, + ) -> Vec { + let (widgets, _, _) = self.layout(level, w, h); + let (top, bottom) = Self::bounds(h); + if drag { + if let Some(item) = self.dragging + && let Some(wd) = widgets + .iter() + .find(|wd| matches!(wd.target, Target::Item(i) if i == item)) + { + item.set_slider(s, ui::slider_value(wd.x, wd.w, x)); + return vec![Action::Changed]; + } + return Vec::new(); + } + for wd in widgets { + if !ui::hovered((x, y), wd.x, wd.y, wd.w, 20.0) { + continue; + } + if wd.list && (y < top || y >= bottom || wd.y < top || wd.y + 20.0 > bottom) { + continue; + } + return match wd.target { + Target::Button(action) => vec![action], + Target::Item(item) => { + if item.slider(s).is_some() { + self.dragging = Some(item); + item.set_slider(s, ui::slider_value(wd.x, wd.w, x)); + } else { + item.cycle(s, right); + } + vec![Action::Changed] + } + }; + } + Vec::new() + } + pub fn release(&mut self) { + self.dragging = None; + } + pub fn scroll(&mut self, amount: f32) { + self.scroll -= amount * 18.0; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_advanced_setting_has_a_description() { + for level in [Level::Simple, Level::Advanced] { + for row in rows(level) { + if let Row::Setting(s) = row { + assert!(!s.text.is_empty(), "{:?}", s.item); + assert!(s.text.len() < 80, "one line: {:?}", s.item); + } + } + } + } + + #[test] + fn presets_set_vanilla_and_horizon_options() { + let mut s = Settings::default(); + Item::Horizon(H::Preset).cycle(&mut s, false); + assert_eq!(s.horizon.preset, Preset::Performance); + assert_eq!(s.render_distance, 8); + assert_eq!(s.clouds, "false"); + // Any quality change leaves the preset. + Item::Vanilla(Opt::Clouds).cycle(&mut s, false); + assert_eq!(s.horizon.preset, Preset::Custom); + // Display preferences keep it. + Item::Horizon(H::Preset).cycle(&mut s, true); + Item::Vanilla(Opt::Vsync).cycle(&mut s, false); + assert_eq!(s.horizon.preset, Preset::Ultra); + } + + #[test] + fn upload_budget_slider_steps() { + let mut s = Settings::default(); + H::UploadBudget.set_slider(&mut s, 1.0); + assert_eq!(s.horizon.upload_budget_kib, 16384); + assert_eq!(H::UploadBudget.slider(&s), Some(1.0)); + H::UploadBudget.set_slider(&mut s, 0.0); + assert_eq!(s.horizon.upload_budget_kib, 0); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 3ad3e2d0f..7e085c9fb 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -48,6 +48,8 @@ pub mod font; pub mod gamerules; pub mod gfx; pub mod graphics; +pub mod graphics_style; +pub mod graphics_ui; pub mod gossip; pub mod health; pub mod hotbar; @@ -83,6 +85,7 @@ pub mod options_file; pub mod options_fixes; pub mod options_ui; pub mod pack_screen; +pub mod perf_overlay; pub mod packs; pub mod particles; pub mod patrol; diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 7e0b2b0da..b47fbecf8 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -190,6 +190,13 @@ impl Opt { _ => Kind::Cycle, } } + /// A slider's position (0..1), or `None` for a cycle button. + pub fn slider_position(self, s: &Settings) -> Option { + match self.kind(s) { + Kind::Slider(v) => Some(v), + Kind::Cycle => None, + } + } /// The widget message (OptionInstance.toString / CycleButton full name). pub fn label(self, s: &Settings) -> Text { let c = self.caption(); @@ -532,6 +539,9 @@ pub enum Page { Language, Font, Packs, + /// Horizon's graphics settings (`graphics_ui`). + Graphics, + GraphicsAdvanced, } #[derive(Clone, Debug, PartialEq)] enum Act { @@ -606,6 +616,7 @@ pub struct OptionsUi { pub in_world: bool, /// Scroll the selected language into the middle on the next layout. center_language: bool, + pub graphics: crate::graphics_ui::GraphicsUi, } impl Default for OptionsUi { fn default() -> Self { @@ -625,6 +636,7 @@ impl Default for OptionsUi { pack_focus: std::time::Instant::now(), in_world: false, center_language: false, + graphics: Default::default(), } } } @@ -704,6 +716,17 @@ impl OptionsUi { if page == Page::Packs { self.pack_screen = None; } + if matches!(page, Page::Graphics | Page::GraphicsAdvanced) { + self.graphics.reset(); + } + } + /// The graphics screen level of `page`, if it is one. + fn graphics_level(page: Page) -> Option { + match page { + Page::Graphics => Some(crate::graphics_ui::Level::Simple), + Page::GraphicsAdvanced => Some(crate::graphics_ui::Level::Advanced), + _ => None, + } } fn title(page: Page) -> &'static str { match page { @@ -718,12 +741,30 @@ impl OptionsUi { Page::Language => "options.language.title", Page::Font => "options.font.title", Page::Packs => "resourcePack.title", + Page::Graphics | Page::GraphicsAdvanced => "options.videoTitle", } } fn list_rows(&self, s: &Settings) -> Vec { match self.page() { Page::Video => { - let mut rows = vec![Row::Header("options.video.display.header")]; + // Horizon's graphics screens, Simple and Advanced. + let mut rows = vec![Row::Buttons( + button( + 0.0, + 0.0, + 150.0, + Text::literal("Horizon Graphics..."), + Act::Push(Page::Graphics), + ), + Some(button( + 0.0, + 0.0, + 150.0, + Text::literal("Advanced Graphics..."), + Act::Push(Page::GraphicsAdvanced), + )), + )]; + rows.push(Row::Header("options.video.display.header")); rows.extend(pairs(&[ Opt::MaxFps, Opt::Vsync, @@ -1175,6 +1216,11 @@ impl OptionsUi { cursor: (f32, f32), ) { let (w, h) = (batch.width, batch.height); + if let Some(level) = Self::graphics_level(self.page()) { + self.graphics + .draw(level, s, batch, atlas, cursor, self.in_world); + return; + } if self.page() == Page::Packs { ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.in_world); let blink = self.pack_focus.elapsed().as_millis() as u64; @@ -1324,6 +1370,28 @@ impl OptionsUi { drag: bool, right: bool, ) -> Vec { + if let Some(level) = Self::graphics_level(self.page()) { + use crate::graphics_ui::Action; + let mut events = Vec::new(); + for action in self.graphics.click(level, s, (x, y), size, drag, right) { + match action { + Action::Changed => events.push(Event::Changed), + Action::OpenAdvanced => self.push(Page::GraphicsAdvanced), + Action::OpenSimple => { + if self.stack.len() >= 2 + && self.stack[self.stack.len() - 2] == Page::Graphics + { + events.extend(self.back(s)); + } else { + self.stack.pop(); + self.push(Page::Graphics); + } + } + Action::Done => events.extend(self.back(s)), + } + } + return events; + } if self.page() == Page::Packs { let mut events = Vec::new(); if drag || right { @@ -1421,12 +1489,17 @@ impl OptionsUi { } pub fn release(&mut self) { self.dragging = None; + self.graphics.release(); } pub fn scroll(&mut self, amount: f32) { self.scroll -= amount * 18.0; } /// The mouse wheel at the cursor. pub fn scroll_at(&mut self, cursor: (f32, f32), amount: f32) { + if Self::graphics_level(self.page()).is_some() { + self.graphics.scroll(amount); + return; + } match &mut self.pack_screen { Some(p) if self.stack.last() == Some(&Page::Packs) => { p.scroll(cursor.0 as f64, cursor.1 as f64, amount as f64) diff --git a/crates/horizon-client/src/perf_overlay.rs b/crates/horizon-client/src/perf_overlay.rs new file mode 100644 index 000000000..361dac9b6 --- /dev/null +++ b/crates/horizon-client/src/perf_overlay.rs @@ -0,0 +1,99 @@ +//! The performance overlay (Horizon's Overlay setting): frames per second, +//! frame, CPU and GPU times, and a graph of recent frame times. +use crate::{ + graphics::Overlay, + hud::{HudAtlas, HudBatch, rgba}, + text::Text, +}; +use std::collections::VecDeque; + +const HISTORY: usize = 160; + +#[derive(Default)] +pub struct FrameGraph { + /// Frame, CPU and GPU milliseconds of recent frames, oldest first. + frames: VecDeque<(f32, f32, f32)>, +} +impl FrameGraph { + pub fn record(&mut self, frame_ms: f32, cpu_ms: f32, gpu_ms: Option) { + let gpu = gpu_ms.unwrap_or_else(|| self.frames.back().map_or(0.0, |f| f.2)); + if self.frames.len() == HISTORY { + self.frames.pop_front(); + } + self.frames.push_back((frame_ms, cpu_ms, gpu)); + } + pub fn draw(&self, mode: Overlay, batch: &mut HudBatch, atlas: &HudAtlas) { + if mode == Overlay::Off || self.frames.is_empty() { + return; + } + let n = self.frames.len() as f32; + let avg = |f: fn(&(f32, f32, f32)) -> f32| self.frames.iter().map(f).sum::() / n; + let (frame, cpu, gpu) = (avg(|f| f.0), avg(|f| f.1), avg(|f| f.2)); + let worst = self.frames.iter().map(|f| f.0).fold(0.0f32, f32::max); + let lines = [ + format!("{:.0} fps", 1000.0 / frame.max(0.001)), + format!("frame {frame:.1} ms max {worst:.1}"), + format!("cpu {cpu:.1} gpu {gpu:.1} ms"), + ]; + let width = 120.0f32.max( + lines + .iter() + .map(|l| atlas.font.width(l)) + .fold(0.0, f32::max) + + 6.0, + ); + let x = batch.width - width - 2.0; + let graph = if mode == Overlay::Graph { 42.0 } else { 0.0 }; + batch.fill( + atlas, + x, + 2.0, + width, + 4.0 + lines.len() as f32 * 10.0 + graph, + rgba(0, 0, 0, 144), + ); + for (i, line) in lines.iter().enumerate() { + let color = if i == 0 { rgba(255, 255, 255, 255) } else { rgba(200, 200, 200, 255) }; + batch.text_styled( + atlas, + &Text::literal(line.clone()), + x + 3.0, + 4.0 + i as f32 * 10.0, + color, + true, + ); + } + if mode != Overlay::Graph { + return; + } + // Bars of frame time on a 0..33 ms scale; lines at 60 and 30 fps. + let (gy, gh) = (4.0 + lines.len() as f32 * 10.0 + 2.0, 36.0); + let scale = gh / 33.3; + let bar = (width - 6.0) / HISTORY as f32; + for (i, &(ms, cpu, _)) in self.frames.iter().enumerate() { + let height = (ms * scale).min(gh); + let bx = x + 3.0 + i as f32 * bar; + let color = if ms > 33.3 { + rgba(240, 90, 80, 255) + } else if ms > 16.7 { + rgba(240, 200, 90, 255) + } else { + rgba(110, 210, 120, 255) + }; + batch.fill(atlas, bx, gy + gh - height, bar.max(1.0), height, color); + let cpu_height = (cpu * scale).min(height); + batch.fill( + atlas, + bx, + gy + gh - cpu_height, + bar.max(1.0), + cpu_height, + rgba(80, 140, 230, 200), + ); + } + for target in [16.7, 33.3] { + let ly = gy + gh - target * scale; + batch.fill(atlas, x + 3.0, ly, width - 6.0, 1.0, rgba(255, 255, 255, 90)); + } + } +} diff --git a/docs/media/settings-advanced.png b/docs/media/settings-advanced.png new file mode 100644 index 000000000..b2c3a92ad Binary files /dev/null and b/docs/media/settings-advanced.png differ diff --git a/docs/media/settings-simple.png b/docs/media/settings-simple.png new file mode 100644 index 000000000..a51a62fd0 Binary files /dev/null and b/docs/media/settings-simple.png differ