Merge pull request #414 from ludovic111/fix/f3-on-top

F3 overlay like vanilla: on top of menus, debug GUI scale, default entries
This commit is contained in:
Ludovic Marie
2026-10-16 03:45:54 +02:00
committed by GitHub
7 changed files with 548 additions and 114 deletions
+2 -1
View File
@@ -164,7 +164,8 @@ fn operating_system() -> String {
)
}
fn cpu() -> String {
/// Logical processors and the CPU's name (`12x AMD Ryzen 5 5600X ...`).
pub fn cpu() -> String {
let threads = std::thread::available_parallelism().map_or(0, |n| n.get());
let name = if cfg!(target_os = "linux") {
read("/proc/cpuinfo").and_then(|t| {
+4
View File
@@ -72,6 +72,8 @@ pub struct DebugCharts {
pub ping: SampleLogger,
/// `bandwidthLogger`: bytes received per tick.
pub bandwidth: SampleLogger,
/// `MinecraftServer.smoothedTickTimeMillis`.
pub smoothed_tick_ms: f32,
previous_tick: Option<Instant>,
bytes_seen: Option<i64>,
}
@@ -110,6 +112,7 @@ impl DebugCharts {
self.bandwidth.reset();
self.previous_tick = None;
self.bytes_seen = None;
self.smoothed_tick_ms = 0.0;
}
/// One integrated server tick that started at `started` and ran its
/// tick method for `method` (`MinecraftServer.logFullTickTime` and
@@ -123,6 +126,7 @@ impl DebugCharts {
.max(method);
self.previous_tick = Some(started);
self.tick_times.log_full([full, method, 0, full - method]);
self.smoothed_tick_ms = self.smoothed_tick_ms * 0.8 + method as f32 / 1e6 * 0.199_999_99;
}
/// `BandwidthDebugMonitor.tick`: the bytes received since the last
/// tick, from the connection's running total.
+340
View File
@@ -0,0 +1,340 @@
//! `DebugScreenOverlay`: the F3 text. The entries of the default profile
//! (`DebugScreenEntries.PROFILES`) report priority lines, regular lines and
//! groups; the overlay splits them into a left and a right column and draws
//! them last, over any screen, at the debug GUI scale.
use crate::{
font::Font,
hud_layout::{GuiDraw, PoseOp, fill},
text::Text,
};
/// `extractLines`'s background: ARGB 0x90505050.
const BACKGROUND: u32 = 0x9050_5050;
/// `extractLines`'s text colour: ARGB 0xFFE0E0E0.
const TEXT: u32 = 0xFFE0_E0E0;
/// `Font.lineHeight`.
const LINE_HEIGHT: i32 = 9;
/// What the enabled entries reported (`DebugScreenDisplayer`).
#[derive(Default, Debug)]
pub struct Displayer {
left: Vec<String>,
right: Vec<String>,
lines: Vec<String>,
groups: Vec<(&'static str, Vec<String>)>,
}
impl Displayer {
/// `addPriorityLine`: to the shorter column, the left one first.
pub fn priority(&mut self, line: impl Into<String>) {
if self.left.len() > self.right.len() {
self.right.push(line.into());
} else {
self.left.push(line.into());
}
}
/// `addLine`: split between the columns after the priority lines.
pub fn line(&mut self, line: impl Into<String>) {
self.lines.push(line.into());
}
/// `addToGroup`: lines kept together, groups in the order first added.
pub fn group(&mut self, group: &'static str, lines: impl IntoIterator<Item = String>) {
let index = match self.groups.iter().position(|(g, _)| *g == group) {
Some(i) => i,
None => {
self.groups.push((group, Vec::new()));
self.groups.len() - 1
}
};
self.groups[index].1.extend(lines);
}
/// `extractRenderState`: the left and right columns, then `footer` (the
/// chart keys, shown while the overlay is open) under the left one.
pub fn columns(self, footer: &[String]) -> (Vec<String>, Vec<String>) {
let (mut left, mut right) = (self.left, self.right);
if !left.is_empty() {
left.push(String::new());
}
if !right.is_empty() {
right.push(String::new());
}
if !self.lines.is_empty() {
let mid = self.lines.len().div_ceil(2);
left.extend_from_slice(&self.lines[..mid]);
right.extend_from_slice(&self.lines[mid..]);
left.push(String::new());
if mid < self.lines.len() {
right.push(String::new());
}
}
let mid = self.groups.len().div_ceil(2);
for (i, (_, lines)) in self.groups.into_iter().enumerate() {
if lines.is_empty() {
continue;
}
let column = if i < mid { &mut left } else { &mut right };
column.extend(lines);
column.push(String::new());
}
if !footer.is_empty() {
left.push(String::new());
left.extend_from_slice(footer);
}
(left, right)
}
}
/// `Mth.wrapDegrees`.
fn wrap_degrees(angle: f32) -> f32 {
let wrapped = angle % 360.0;
if wrapped >= 180.0 {
wrapped - 360.0
} else if wrapped < -180.0 {
wrapped + 360.0
} else {
wrapped
}
}
/// `DebugEntryPosition` and `DebugEntrySectionPosition` for a camera at
/// `pos` looking `yaw`/`pitch` in `dimension` with `forced` force-loaded chunks.
pub fn position(
pos: [f64; 3],
yaw: f32,
pitch: f32,
dimension: &str,
forced: usize,
) -> Vec<String> {
let block = pos.map(|v| v.floor() as i32);
let (cx, sy, cz) = (block[0] >> 4, block[1] >> 4, block[2] >> 4);
// Direction.fromYRot: floor(yRot / 90 + 0.5) & 3 as a 2D data value.
let (direction, towards) = match ((f64::from(yaw) / 90.0 + 0.5).floor() as i32) & 3 {
0 => ("south", "Towards positive Z"),
1 => ("west", "Towards negative X"),
2 => ("north", "Towards negative Z"),
_ => ("east", "Towards positive X"),
};
vec![
format!("XYZ: {:.3} / {:.5} / {:.3}", pos[0], pos[1], pos[2]),
format!("Block: {} {} {}", block[0], block[1], block[2]),
format!(
"Chunk: {cx} {sy} {cz} [{} {} in r.{}.{}.mca]",
cx & 31,
cz & 31,
cx >> 5,
cz >> 5
),
format!(
"Facing: {direction} ({towards}) ({:.1} / {:.1})",
wrap_degrees(yaw),
wrap_degrees(pitch)
),
format!("{dimension} FC: {forced}"),
format!(
"Section-relative: {:02} {:02} {:02}",
block[0] & 15,
block[1] & 15,
block[2] & 15
),
]
}
/// `VideoMode.refreshRateLabel`: whole rates without decimals.
pub fn refresh_rate_label(hz: f64) -> String {
if hz == hz.round() {
format!("{}", hz as i64)
} else {
format!("{hz:.2}")
}
}
/// `DeviceInfo.vendorName` for a PCI vendor id.
pub fn vendor_name(id: u32) -> String {
match id {
0x10de => "NVIDIA Corporation".into(),
0x1002 | 0x1022 => "AMD".into(),
0x8086 => "Intel".into(),
0x106b => "Apple".into(),
0x5143 => "Qualcomm".into(),
0x13b5 => "ARM".into(),
0x10005 => "Mesa".into(),
0 => "unknown".into(),
other => format!("{other:#06x}"),
}
}
/// The overlay's scale against the GUI scale and the scaled screen size it
/// lays out in. `debugGuiScale`: -1 keeps the GUI scale, 0 (the default) is
/// half the largest automatic scale, n is `calculateScale(n)`; only a scale
/// below the GUI scale applies.
pub fn scale(
framebuffer: [i32; 2],
gui_scale: i32,
option: i32,
unicode: bool,
gui_size: [i32; 2],
) -> (f32, [i32; 2]) {
let scale = match option {
-1 => gui_scale,
0 => crate::window::calculate_scale(framebuffer, 0, unicode) / 2,
n => crate::window::calculate_scale(framebuffer, n, unicode),
};
if scale < gui_scale && scale > 0 {
(
scale as f32 / gui_scale as f32,
[framebuffer[0] / scale, framebuffer[1] / scale],
)
} else {
(1.0, gui_size)
}
}
/// `extractLines` for both columns under the overlay's pose: each line's
/// background first, then the text, right-aligned in the right column.
pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec<GuiDraw> {
let mut out = vec![GuiDraw::Push(vec![PoseOp::Scale(scale, scale)])];
for (lines, align_left) in [(columns[0], true), (columns[1], false)] {
let placed: Vec<(&String, i32, i32)> = lines
.iter()
.enumerate()
.filter(|(_, l)| !l.is_empty())
.map(|(i, l)| {
let w = font.width(l) as i32;
let left = if align_left { 2 } else { width - 2 - w };
(l, left, 2 + LINE_HEIGHT * i as i32)
})
.collect();
for (line, left, top) in &placed {
let w = font.width(line) as i32;
out.push(fill(
left - 1,
top - 1,
left + w + 1,
top + LINE_HEIGHT - 1,
BACKGROUND,
));
}
for (line, left, top) in placed {
out.push(GuiDraw::Text {
text: Text::literal(line.clone()),
x: left,
y: top,
color: TEXT,
shadow: false,
});
}
}
out.push(GuiDraw::Pop);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn lines(v: &[&str]) -> Vec<String> {
v.iter().map(|s| (*s).to_owned()).collect()
}
#[test]
fn columns_follow_the_vanilla_split() {
// The default profile's entries, sorted by identifier as
// DebugScreenEntryList.rebuildCurrentList does: fps, game_version,
// memory, player_position, player_section_position,
// simple_performance_impactors, system_specs, tps.
let mut d = Displayer::default();
d.priority("112 fps T: 120 (fifo) @165Hz");
d.priority("Minecraft 26.3 (26.3/vanilla)");
d.group("memory", lines(&["Mem: 25% 1046/4096MiB"]));
d.group("position", lines(&["XYZ: 1 / 2 / 3", "Block: 1 2 3"]));
d.group("position", lines(&["Section-relative: 01 02 03"]));
d.line("fancy-clouds B: 2");
d.line("Filtering: RGSS");
d.line("Terrain Rendering: multidrawindirect");
d.group(
"system",
lines(&["CPU: 12x Ryzen", "Display: 854x709 (NVIDIA)"]),
);
d.line("Integrated server @ 6.6/50.0 ms, 28 tx, 492 rx");
let footer = lines(&["Debug charts: ...", "To edit: press [F3+F6]"]);
let (left, right) = d.columns(&footer);
// As the issue's vanilla screenshot (#376) shows them.
assert_eq!(
left,
lines(&[
"112 fps T: 120 (fifo) @165Hz",
"",
"fancy-clouds B: 2",
"Filtering: RGSS",
"",
"Mem: 25% 1046/4096MiB",
"",
"XYZ: 1 / 2 / 3",
"Block: 1 2 3",
"Section-relative: 01 02 03",
"",
"",
"Debug charts: ...",
"To edit: press [F3+F6]",
])
);
assert_eq!(
right,
lines(&[
"Minecraft 26.3 (26.3/vanilla)",
"",
"Terrain Rendering: multidrawindirect",
"Integrated server @ 6.6/50.0 ms, 28 tx, 492 rx",
"",
"CPU: 12x Ryzen",
"Display: 854x709 (NVIDIA)",
"",
])
);
}
#[test]
fn position_lines_match_vanilla() {
// The issue's vanilla screenshot (#376).
assert_eq!(
position([108.5, 104.0, -51.5], -1.0, 7.1, "minecraft:overworld", 0),
lines(&[
"XYZ: 108.500 / 104.00000 / -51.500",
"Block: 108 104 -52",
"Chunk: 6 6 -4 [6 28 in r.0.-1.mca]",
"Facing: south (Towards positive Z) (-1.0 / 7.1)",
"minecraft:overworld FC: 0",
"Section-relative: 12 08 12",
])
);
assert_eq!(
position([0.0, 64.0, 0.0], 450.0, 0.0, "minecraft:the_nether", 2)[3],
"Facing: west (Towards negative X) (90.0 / 0.0)"
);
assert_eq!(refresh_rate_label(165.0), "165");
assert_eq!(refresh_rate_label(59.94), "59.94");
}
#[test]
fn debug_scale_is_half_the_automatic_scale() {
// The issue's window: 854x709 at GUI scale 2 draws F3 at scale 1.
assert_eq!(
scale([854, 709], 2, 0, false, [427, 355]),
(0.5, [854, 709])
);
// 1920x1080 at GUI scale 4: auto is 4, so F3 is at 2.
assert_eq!(
scale([1920, 1080], 4, 0, false, [480, 270]),
(0.5, [960, 540])
);
// A GUI scale already at or under the debug scale is kept.
assert_eq!(
scale([1920, 1080], 2, 0, false, [960, 540]),
(1.0, [960, 540])
);
assert_eq!(
scale([1920, 1080], 3, -1, false, [640, 360]),
(1.0, [640, 360])
);
}
}
+3 -111
View File
@@ -3615,6 +3615,9 @@ impl Game<'_> {
}
fn hud(&mut self, size: [u32; 2]) -> HudBatch {
let mut batch = self.hud_layers(size);
// Gui.extractRenderState: the debug overlay comes after the screen
// and the toasts, so it is over everything, menus included.
self.draw_debug_overlay(&mut batch, size);
self.frame_graph
.draw(self.settings.horizon.overlay, &mut batch, &self.res.atlas);
self.draw_pad_cursor(&mut batch);
@@ -3795,117 +3798,6 @@ impl Game<'_> {
}
}
let atlas = &self.res.atlas;
if self.debug {
let p = self
.player
.as_ref()
.map(|p| p.position)
.unwrap_or(Vec3::ZERO);
let block = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32];
let biome = self
.world
.chunks
.get(&(block[0] >> 4, block[2] >> 4))
.map(|c| {
self.res
.biomes
.get(c.biome(block[0], block[1], block[2]))
.name
.clone()
})
.unwrap_or_default();
let light = self.world.light(block[0], block[1], block[2]);
let facing = match ((self.yaw.rem_euclid(360.0) + 45.0) / 90.0) as i32 % 4 {
0 => "south (Towards positive Z)",
1 => "west (Towards negative X)",
2 => "north (Towards negative Z)",
_ => "east (Towards positive X)",
};
let mut lines = vec![
format!("Horizon 26.3 (Rust) {:.0} fps", self.fps),
format!(
"C: {} chunks, {} sections drawn / {}",
self.world.chunks.len(),
self.renderer.as_ref().map_or(0, |r| r.drawn_sections),
self.renderer.as_ref().map_or(0, |r| r.section_count())
),
format!("Pending jobs: {}", self.streaming.pending()),
String::new(),
format!("XYZ: {:.3} / {:.5} / {:.3}", p.x, p.y, p.z),
format!("Block: {} {} {}", block[0], block[1], block[2]),
format!(
"Chunk: {} {} {} in {} {} {}",
block[0] & 15,
block[1] & 15,
block[2] & 15,
block[0] >> 4,
block[1] >> 4,
block[2] >> 4
),
format!(
"Facing: {facing} ({:.1} / {:.1})",
self.yaw.rem_euclid(360.0)
- if self.yaw.rem_euclid(360.0) > 180.0 {
360.0
} else {
0.0
},
self.pitch
),
format!(
"Light: {} (sky {}, block {})",
(light >> 4).max(light & 15),
light >> 4,
light & 15
),
format!("Biome: {biome}"),
format!(
"Day {} time {}",
self.world.day_time / 24000,
self.world.day_time % 24000
),
String::new(),
];
lines.extend(self.debug_chart_lines());
for (i, line) in lines.iter().enumerate() {
if line.is_empty() {
continue;
}
let tw = HudBatch::text_width(atlas, line);
batch.fill(
atlas,
1.0,
2.0 + i as f32 * 9.0 - 1.0,
tw + 2.0,
9.0,
rgba(80, 80, 80, 144),
);
batch.text(
atlas,
line,
2.0,
2.0 + i as f32 * 9.0,
rgba(224, 224, 224, 255),
false,
);
}
let charts = self.debug_charts.draw(
&atlas.font,
w as i32,
h as i32,
self.settings.max_fps,
1000.0 / self.clock.rate(),
self.remote.is_some(),
);
hud_layout::paint(&mut batch, atlas, &charts);
if self.debug_charts.lightmap
&& let Some(r) = &self.renderer
{
let view =
horizon_client::debug_chart::lightmap(&r.lightmap_pixels, w as i32, h as i32);
hud_layout::paint(&mut batch, atlas, &view);
}
}
if !self.ui.hide_gui
&& let Some((text, at)) = &self.message
&& at.elapsed() < Duration::from_secs(3)
+197 -1
View File
@@ -6,8 +6,11 @@ use horizon_client::{
Result,
command::args::GameMode,
debug_keys::{CrashNotice, DebugAction, DebugHost, KeyAction, OpenScreen},
debug_overlay,
gizmos::Gizmos,
keybinds,
hud::HudBatch,
hud_layout, keybinds,
save::VERSION_NAME,
text::Text,
};
use horizon_core::geometry::Axis;
@@ -253,6 +256,199 @@ impl Game<'_> {
format!("To edit: press {}", key("key.debug.debugOptions")),
]
}
/// `DebugScreenOverlay.extractRenderState` with the default profile's
/// entries, over everything the frame drew (menus too), at the debug GUI
/// scale. F1 hides it unless a screen is open.
pub(super) fn draw_debug_overlay(&self, batch: &mut HudBatch, size: [u32; 2]) {
let screen_open = self.title.is_some() || self.screen != Screen::Playing;
if !self.debug || (self.ui.hide_gui && !screen_open) {
return;
}
let framebuffer = size.map(|v| v as i32);
let (scale, [width, height]) = debug_overlay::scale(
framebuffer,
batch.scale as i32,
self.settings.file.int("debugGuiScale"),
self.settings.force_unicode,
[batch.width as i32, batch.height as i32],
);
let mut d = debug_overlay::Displayer::default();
// fps: DebugEntryFps.
let limit = self.framerate_limit();
let present = self
.renderer
.as_ref()
.map_or("", |r| match r.config.present_mode {
wgpu::PresentMode::Immediate => " (immediate)",
wgpu::PresentMode::Mailbox => " (mailbox)",
wgpu::PresentMode::Fifo => " (fifo)",
wgpu::PresentMode::FifoRelaxed => " (fifo relaxed)",
_ => "",
});
let refresh = self
.window
.as_ref()
.and_then(|w| w.current_monitor())
.and_then(|m| m.refresh_rate_millihertz())
.map_or("0".into(), |mhz| {
debug_overlay::refresh_rate_label(f64::from(mhz) / 1000.0)
});
d.priority(format!(
"{} fps T: {}{present} @{refresh}Hz",
self.fps.round() as i32,
if limit == 260 {
"inf".into()
} else {
limit.to_string()
},
));
// game_version: DebugEntryVersion (the launched version and brand).
d.priority(format!("Minecraft {VERSION_NAME} ({VERSION_NAME}/horizon)"));
// player_position, player_section_position.
if let Some(p) = self.player.as_ref() {
let mut lines = debug_overlay::position(
[p.position.x, p.position.y, p.position.z],
self.yaw,
self.pitch,
self.dim.id(),
self.streaming.forced.len(),
);
let section = lines.pop().unwrap_or_default();
if !self.reduced_debug_info() {
d.group("position", lines);
}
d.group("position", [section]);
}
// simple_performance_impactors.
let s = &self.settings;
d.line(format!(
"{}{}B: {}",
if s.improved_transparency {
"improved-transparency "
} else {
""
},
match s.clouds.as_str() {
"false" => "",
"fast" => "fast-clouds ",
_ => "fancy-clouds ",
},
s.biome_blend
));
d.line("Filtering: None");
d.line(format!(
"Terrain Rendering: {}",
if self.renderer.as_ref().is_some_and(|r| r.multi_draw) {
"multidrawindirect"
} else {
"naive"
}
));
// system_specs (no Java line: Horizon has no JVM).
if let Some(r) = self.renderer.as_ref() {
static CPU: std::sync::OnceLock<String> = std::sync::OnceLock::new();
d.group(
"system",
[format!(
"CPU: {}",
CPU.get_or_init(horizon_client::crash::cpu)
)],
);
let info = &r.info;
d.group(
"system",
[format!(
"Display: {}x{} ({})",
framebuffer[0],
framebuffer[1],
// Metal adapters report no PCI vendor.
if info.vendor == 0 && info.backend == wgpu::Backend::Metal {
"Apple".into()
} else {
debug_overlay::vendor_name(info.vendor)
}
)],
);
if let Some(w) = self.window.as_ref() {
let density = w.scale_factor();
let logical = w.inner_size().to_logical::<f64>(density);
d.group(
"system",
[format!(
"Window: {}x{} ({density:.2}x pixel density)",
logical.width.round() as i32,
logical.height.round() as i32
)],
);
}
let kind = match info.device_type {
wgpu::DeviceType::IntegratedGpu => " (iGPU)",
wgpu::DeviceType::DiscreteGpu => " (dGPU)",
wgpu::DeviceType::VirtualGpu => " (vGPU)",
wgpu::DeviceType::Cpu => " (software)",
wgpu::DeviceType::Other => "",
};
let driver = format!("{} {}", info.driver, info.driver_info);
d.group(
"system",
[
format!("{}{kind}", info.name),
format!(
"{:?} {}",
info.backend,
driver.trim().lines().next().unwrap_or("")
)
.trim_end()
.to_owned(),
],
);
}
// tps: DebugEntryTps for the integrated server (it counts no packets).
if self.player.is_some() && self.remote.is_none() {
let (target, status) = if self.clock.sprinting() {
("-".to_owned(), " (sprinting)")
} else if self.clock.stepping() {
(
format!("{:.1}", 1000.0 / self.clock.rate()),
" (frozen - stepping)",
)
} else if self.clock.frozen() {
(format!("{:.1}", 1000.0 / self.clock.rate()), " (frozen)")
} else {
(format!("{:.1}", 1000.0 / self.clock.rate()), "")
};
d.line(format!(
"Integrated server @ {:.1}/{target} ms{status}, 0 tx, 0 rx",
self.debug_charts.smoothed_tick_ms
));
}
let (left, right) = d.columns(&self.debug_chart_lines());
let atlas = &self.res.atlas;
let mut draws = debug_overlay::draw(&atlas.font, [&left, &right], scale, width);
let charts = self.debug_charts.draw(
&atlas.font,
width,
height,
self.settings.max_fps,
1000.0 / self.clock.rate(),
self.remote.is_some(),
);
draws.push(hud_layout::GuiDraw::Push(vec![hud_layout::PoseOp::Scale(
scale, scale,
)]));
draws.extend(charts);
if self.debug_charts.lightmap
&& let Some(r) = &self.renderer
{
draws.extend(horizon_client::debug_chart::lightmap(
&r.lightmap_pixels,
width,
height,
));
}
draws.push(hud_layout::GuiDraw::Pop);
hud_layout::paint(batch, atlas, &draws);
}
/// `KeyMapping.getTranslatedKeyMessage`.
fn key_text(&self, mapping: &str) -> Text {
keybinds::display_name(self.settings.keys.get(mapping))
+1 -1
View File
@@ -292,7 +292,7 @@ pub struct Renderer {
indirect: wgpu::Buffer,
indirect_capacity: u64,
/// Indirect draws may set `first_instance` (the section origin).
multi_draw: bool,
pub multi_draw: bool,
/// Per-frame scratch, kept to avoid allocating every frame.
visible: Vec<Visible>,
origins: Vec<[f32; 4]>,
+1
View File
@@ -47,6 +47,7 @@ pub mod data_cmd;
pub mod datapack;
pub mod debug_chart;
pub mod debug_keys;
pub mod debug_overlay;
pub mod effects;
pub mod enchant;
pub mod end_crystal;