Section arena in pages; graphics docs and benchmark comparison

At render distance 32 the single section arena grew past the 4 GiB buffer
limit and the renderer panicked. Sections now live in pages of at most
256 MiB (or the device's buffer limit); draws keep their order and bind each
page once per run of consecutive draws in it, so translucent sections stay
back to front. docs/graphics.md describes the settings, the benchmark and
what changed; graphics_bench.py --compare prints a before/after table and
keeps each game's log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-13 17:10:07 +02:00
parent ad9cd6c67e
commit 7f1e197428
19 changed files with 366 additions and 130 deletions
+3 -4
View File
@@ -18,11 +18,10 @@ impl FxHasher {
impl Hasher for FxHasher {
#[inline]
fn write(&mut self, bytes: &[u8]) {
let mut chunks = bytes.chunks_exact(8);
for c in &mut chunks {
self.add(u64::from_le_bytes(c.try_into().expect("eight bytes")));
let (words, rest) = bytes.as_chunks::<8>();
for word in words {
self.add(u64::from_le_bytes(*word));
}
let rest = chunks.remainder();
if !rest.is_empty() {
let mut word = [0u8; 8];
word[..rest.len()].copy_from_slice(rest);
+25 -12
View File
@@ -224,7 +224,9 @@ impl Options {
no_pause: false,
control: None,
offscreen: false,
spikes: std::env::var("HORIZON_SPIKES").ok().and_then(|v| v.parse().ok()),
spikes: std::env::var("HORIZON_SPIKES")
.ok()
.and_then(|v| v.parse().ok()),
server: None,
player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()),
dedicated: None,
@@ -1239,8 +1241,10 @@ impl Game<'_> {
// ServerLevel.tick: only entities in entity-ticking chunks tick.
let ticking = self.entity_ticking_area();
items.retain_mut(|item| {
!ticking(item.position.x.floor() as i32, item.position.z.floor() as i32)
|| item.tick(&self.world, &self.res.facts, self.collision)
!ticking(
item.position.x.floor() as i32,
item.position.z.floor() as i32,
) || item.tick(&self.world, &self.res.facts, self.collision)
});
let Some(p) = self.player.as_ref() else {
self.dropped = items;
@@ -2860,7 +2864,9 @@ impl Game<'_> {
if running {
// ClientLevel.tickBlockEntities (not while paused or frozen):
// chest lids, books, shulker boxes, bells, conduits, heads.
horizon_client::spans::time("tick_block_entity_anims", || self.tick_block_entity_anims());
horizon_client::spans::time("tick_block_entity_anims", || {
self.tick_block_entity_anims()
});
horizon_client::spans::time("tick_particles", || self.tick_particles());
}
if self.right && self.use_delay == 0 && self.screen == Screen::Playing {
@@ -4410,12 +4416,14 @@ impl Game<'_> {
)
};
let visible = r.block_entities().filter(|(p, state)| {
off_screen(*state) || view.is_none_or(|v| {
let o = (glam::DVec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2]))
- camera)
.as_vec3();
v.intersects(o - glam::Vec3::ONE, o + glam::Vec3::splat(2.0))
})
off_screen(*state)
|| view.is_none_or(|v| {
let o =
(glam::DVec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2]))
- camera)
.as_vec3();
v.intersects(o - glam::Vec3::ONE, o + glam::Vec3::splat(2.0))
})
});
self.res
.block_entity_render
@@ -7679,14 +7687,19 @@ impl Game<'_> {
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)
(
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) {
if (limit > 0 && count >= limit)
|| (budget > 0 && bytes > 0 && bytes + size > budget)
{
break;
}
let (key, mesh) = pending.pop().expect("checked above");
+1 -4
View File
@@ -17,10 +17,7 @@ use horizon_core::{
random::{LegacyRandom, RandomSource},
};
use horizon_world::registry::BlockStateId;
use std::{
collections::HashMap,
sync::Arc,
};
use std::{collections::HashMap, sync::Arc};
type Pos = (i32, i32, i32);
+4 -2
View File
@@ -2295,8 +2295,10 @@ impl Game<'_> {
if let Some(view) = &self.view_frustum
&& horizon_client::mobs::guardian::beam(mob, alpha as f32).is_none()
{
let lo = d.as_vec3() - glam::Vec3::new(w as f32 / 2.0 + 0.5, 0.5, w as f32 / 2.0 + 0.5);
let hi = d.as_vec3() + glam::Vec3::new(w as f32 / 2.0 + 0.5, h as f32 + 0.5, w as f32 / 2.0 + 0.5);
let lo =
d.as_vec3() - glam::Vec3::new(w as f32 / 2.0 + 0.5, 0.5, w as f32 / 2.0 + 0.5);
let hi = d.as_vec3()
+ glam::Vec3::new(w as f32 / 2.0 + 0.5, h as f32 + 0.5, w as f32 / 2.0 + 0.5);
if !view.intersects(lo, hi) {
continue;
}
+70 -49
View File
@@ -38,7 +38,8 @@ struct Globals {
}
pub type SectionKey = (i32, i32, i32);
struct SectionGpu {
/// First vertex in the section arena: solid quads, then translucent ones.
/// Arena page and first vertex in it: solid quads, then translucent ones.
page: u32,
start: u64,
solid: u32,
translucent: u32,
@@ -193,6 +194,8 @@ pub struct Renderer {
/// `DrawIndexedIndirectArgs` words: index count, instance count, first
/// index, base vertex, first instance.
draws: Vec<[u32; 5]>,
/// The arena page of each of `draws`.
draw_pages: Vec<u32>,
/// Block-entity blocks per meshed section (world position, state id).
block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>,
/// VisGraph face connectivity per meshed section (cave culling).
@@ -1178,6 +1181,7 @@ impl Renderer {
visible: Vec::new(),
origins: Vec::new(),
draws: Vec::new(),
draw_pages: Vec::new(),
block_entities: HashMap::new(),
occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16),
post,
@@ -1331,14 +1335,14 @@ impl Renderer {
self.indices = Self::quad_indices(&self.device, self.index_quads);
}
let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64;
let start = self.arena.alloc(&self.device, &self.queue, vertices);
let (page, start) = self.arena.alloc(&self.device, &self.queue, vertices);
let stride = std::mem::size_of::<Vertex>() as u64;
for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] {
if !part.is_empty() {
let bytes: &[u8] = bytemuck::cast_slice(part);
self.uploaded_bytes += bytes.len() as u64;
self.queue.write_buffer(
&self.arena.buffer,
self.arena.buffer(page),
(start + offset as u64) * stride,
bytes,
);
@@ -1347,6 +1351,7 @@ impl Renderer {
self.sections.insert(
key,
SectionGpu {
page,
start,
solid,
translucent,
@@ -1355,22 +1360,31 @@ impl Renderer {
}
/// Draws `count` section draws from `first` with the arena and section
/// origins bound: one indirect multi-draw, or a loop without it.
/// Consecutive draws in one arena page share a vertex buffer binding,
/// keeping the list's order (translucent sections go back to front).
fn draw_sections(&self, pass: &mut wgpu::RenderPass<'_>, first: u32, count: u32) {
if count == 0 {
return;
}
if self.multi_draw {
pass.multi_draw_indexed_indirect(&self.indirect, u64::from(first) * 20, count);
} else {
for d in &self.draws[first as usize..(first + count) as usize] {
pass.draw_indexed(0..d[0], d[3] as i32, d[4]..d[4] + 1);
let (mut i, end) = (first as usize, (first + count) as usize);
while i < end {
let page = self.draw_pages[i];
let run = self.draw_pages[i..end]
.iter()
.take_while(|&&p| p == page)
.count();
pass.set_vertex_buffer(0, self.arena.buffer(page).slice(..));
if self.multi_draw {
pass.multi_draw_indexed_indirect(&self.indirect, i as u64 * 20, run as u32);
} else {
for d in &self.draws[i..i + run] {
pass.draw_indexed(0..d[0], d[3] as i32, d[4]..d[4] + 1);
}
}
i += run;
}
}
fn release_section(&mut self, key: SectionKey) {
if let Some(s) = self.sections.remove(&key) {
self.arena
.release(s.start, u64::from(s.solid + s.translucent) * 4);
.release(s.page, s.start, u64::from(s.solid + s.translucent) * 4);
}
}
/// Block-entity blocks of every meshed section (see `SectionMesh::block_entities`).
@@ -1401,11 +1415,13 @@ impl Renderer {
return;
}
self.mipmaps = levels;
let sprite_view = self.sprite_texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
mip_level_count: Some(levels + 1),
..Default::default()
});
let sprite_view = self
.sprite_texture
.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
mip_level_count: Some(levels + 1),
..Default::default()
});
self.group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Horizon terrain resources"),
layout: &self.terrain_layout,
@@ -1710,30 +1726,30 @@ impl Renderer {
visible.clear();
visible.extend(
self.sections
.keys()
.filter(|&&k| !culling || reachable.contains(k))
.filter_map(|&(sx, sy, sz)| {
let origin = DVec3::new(
f64::from(sx * 16),
f64::from(crate::chunk::MIN_Y + sy * 16),
f64::from(sz * 16),
) - camera;
let center = origin + DVec3::splat(8.0);
let horizontal = (center.x * center.x + center.z * center.z).sqrt();
if horizontal > f64::from(frame.distance) + 24.0 {
return None;
}
let min = origin.as_vec3();
let max = min + Vec3::splat(16.0);
if !view.intersects(min, max) {
return None;
}
Some((
(sx, sy, sz),
center.length_squared(),
origin.as_vec3().to_array(),
))
}),
.keys()
.filter(|&&k| !culling || reachable.contains(k))
.filter_map(|&(sx, sy, sz)| {
let origin = DVec3::new(
f64::from(sx * 16),
f64::from(crate::chunk::MIN_Y + sy * 16),
f64::from(sz * 16),
) - camera;
let center = origin + DVec3::splat(8.0);
let horizontal = (center.x * center.x + center.z * center.z).sqrt();
if horizontal > f64::from(frame.distance) + 24.0 {
return None;
}
let min = origin.as_vec3();
let max = min + Vec3::splat(16.0);
if !view.intersects(min, max) {
return None;
}
Some((
(sx, sy, sz),
center.length_squared(),
origin.as_vec3().to_array(),
))
}),
);
visible.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
self.drawn_sections = visible.len();
@@ -1759,20 +1775,27 @@ impl Renderer {
// Solid sections front to back, then translucent ones back to front,
// as one list of indirect draws over the section arena.
self.draws.clear();
self.draw_pages.clear();
let draw = |s: &SectionGpu, i: usize, translucent: bool| {
let (quads, first) = if translucent {
(s.translucent, s.start + u64::from(s.solid) * 4)
} else {
(s.solid, s.start)
};
(quads > 0).then_some([quads * 6, 1, 0, first as u32, i as u32])
(quads > 0).then_some(([quads * 6, 1, 0, first as u32, i as u32], s.page))
};
for (i, (key, _, _)) in visible.iter().enumerate() {
self.draws.extend(draw(&self.sections[key], i, false));
if let Some((d, page)) = draw(&self.sections[key], i, false) {
self.draws.push(d);
self.draw_pages.push(page);
}
}
let solid_draws = self.draws.len() as u32;
for (i, (key, _, _)) in visible.iter().enumerate().rev() {
self.draws.extend(draw(&self.sections[key], i, true));
if let Some((d, page)) = draw(&self.sections[key], i, true) {
self.draws.push(d);
self.draw_pages.push(page);
}
}
let translucent_draws = self.draws.len() as u32 - solid_draws;
if self.multi_draw && !self.draws.is_empty() {
@@ -1880,9 +1903,9 @@ impl Renderer {
.write_buffer(&self.border_uniform, 0, bytemuck::bytes_of(&uniform));
}
let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor {
format: Some(self.config.format.remove_srgb_suffix()),
..Default::default()
});
format: Some(self.config.format.remove_srgb_suffix()),
..Default::default()
});
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
@@ -1959,7 +1982,6 @@ impl Renderer {
}
pass.set_pipeline(&self.solid);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(0, self.arena.buffer.slice(..));
pass.set_vertex_buffer(1, self.instances.slice(..));
self.draw_sections(&mut pass, 0, solid_draws);
if entity_quads > 0 {
@@ -1983,7 +2005,6 @@ impl Renderer {
}
pass.set_pipeline(&self.translucent);
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(0, self.arena.buffer.slice(..));
pass.set_vertex_buffer(1, self.instances.slice(..));
self.draw_sections(&mut pass, solid_draws, translucent_draws);
// LevelRenderer: the world border after translucent terrain and weather.
+72 -25
View File
@@ -38,22 +38,36 @@ impl FreeList {
}
}
pub struct Arena {
pub buffer: wgpu::Buffer,
/// One vertex buffer of the arena; only the newest page grows.
struct Page {
buffer: wgpu::Buffer,
/// Capacity in vertices.
capacity: u64,
stride: u64,
free: FreeList,
}
/// Terrain vertices in pages of at most `page_limit` vertices (devices cap
/// buffer sizes): a section's vertices sit in one page.
pub struct Arena {
pages: Vec<Page>,
stride: u64,
page_limit: u64,
}
impl Arena {
pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self {
let capacity = capacity.next_multiple_of(GRAIN);
// 256 MiB pages, or less where the device's buffers are smaller.
let bytes = device.limits().max_buffer_size.min(256 << 20);
let page_limit = (bytes / stride) / GRAIN * GRAIN;
let capacity = capacity.next_multiple_of(GRAIN).min(page_limit);
Self {
buffer: Self::create(device, stride, capacity),
capacity,
pages: vec![Page {
buffer: Self::create(device, stride, capacity),
capacity,
free: FreeList::new(capacity),
}],
stride,
free: FreeList::new(capacity),
page_limit,
}
}
fn create(device: &wgpu::Device, stride: u64, capacity: u64) -> wgpu::Buffer {
@@ -70,35 +84,68 @@ impl Arena {
fn span(vertices: u64) -> u64 {
vertices.max(1).next_multiple_of(GRAIN)
}
/// A range of `vertices`, growing the buffer (copying its contents on the
/// GPU) when no free range is large enough. Returns the first vertex.
pub fn alloc(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, vertices: u64) -> u64 {
let len = Self::span(vertices);
if let Some(start) = self.free.take(len) {
return start;
pub fn buffer(&self, page: u32) -> &wgpu::Buffer {
&self.pages[page as usize].buffer
}
/// A range of `vertices`: (page, first vertex). Grows the newest page
/// (copying its contents on the GPU) or starts a new one when nothing
/// free is large enough.
pub fn alloc(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
vertices: u64,
) -> (u32, u64) {
let len = Self::span(vertices).min(self.page_limit);
for (i, page) in self.pages.iter_mut().enumerate() {
if let Some(start) = page.free.take(len) {
return (i as u32, start);
}
}
self.grow(device, queue, (self.capacity * 2).max(self.capacity + len));
self.free.take(len).expect("grown arena has room")
let last = self.pages.len() - 1;
let current = self.pages[last].capacity;
if current < self.page_limit {
let grown = (current * 2).max(current + len).min(self.page_limit);
if grown - current >= len || grown == self.page_limit {
self.grow(device, queue, last, grown);
if let Some(start) = self.pages[last].free.take(len) {
return (last as u32, start);
}
}
}
let capacity = (1 << 20u64).max(len).min(self.page_limit);
let mut free = FreeList::new(capacity);
let start = free.take(len).expect("a new page fits one section");
self.pages.push(Page {
buffer: Self::create(device, self.stride, capacity),
capacity,
free,
});
((self.pages.len() - 1) as u32, start)
}
pub fn release(&mut self, start: u64, vertices: u64) {
self.free.give(start, Self::span(vertices));
pub fn release(&mut self, page: u32, start: u64, vertices: u64) {
let len = Self::span(vertices).min(self.page_limit);
self.pages[page as usize].free.give(start, len);
}
fn grow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, capacity: u64) {
let capacity = capacity.next_multiple_of(GRAIN);
fn grow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, page: usize, capacity: u64) {
let capacity = capacity.next_multiple_of(GRAIN).min(self.page_limit);
let buffer = Self::create(device, self.stride, capacity);
let old = &mut self.pages[page];
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Grow section arena"),
});
encoder.copy_buffer_to_buffer(&self.buffer, 0, &buffer, 0, self.capacity * self.stride);
encoder.copy_buffer_to_buffer(&old.buffer, 0, &buffer, 0, old.capacity * self.stride);
// Writes queued for the old buffer run before this copy.
queue.submit([encoder.finish()]);
let old = self.capacity;
self.buffer = buffer;
self.capacity = capacity;
self.free.give(old, capacity - old);
let previous = old.capacity;
old.buffer = buffer;
old.capacity = capacity;
old.free.give(previous, capacity - previous);
}
pub fn clear(&mut self) {
self.free = FreeList::new(self.capacity);
for page in &mut self.pages {
page.free = FreeList::new(page.capacity);
}
}
}
+8 -2
View File
@@ -161,7 +161,9 @@ impl Post {
group,
});
}
self.target.as_ref().map(|t| (t.color.clone(), t.depth.clone()))
self.target
.as_ref()
.map(|t| (t.color.clone(), t.depth.clone()))
}
/// Draw the scaled world onto `screen`.
pub fn finish(&self, encoder: &mut wgpu::CommandEncoder, screen: &wgpu::TextureView) {
@@ -180,7 +182,11 @@ impl Post {
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(if self.antialias { &self.fxaa } else { &self.copy });
pass.set_pipeline(if self.antialias {
&self.fxaa
} else {
&self.copy
});
pass.set_bind_group(0, &target.group, &[]);
pass.draw(0..3, 0..1);
}
+4 -1
View File
@@ -98,7 +98,10 @@ impl GpuTimer {
.buffer
.slice(..)
.map_async(wgpu::MapMode::Read, move |result| {
state.store(if result.is_ok() { MAPPED } else { FREE }, Ordering::Release);
state.store(
if result.is_ok() { MAPPED } else { FREE },
Ordering::Release,
);
});
self.next = (slot + 1) % SLOTS;
}
+5 -4
View File
@@ -195,9 +195,7 @@ impl Graphics {
}
}
"workers" => g.workers = number(g.workers).min(64),
"resolutionScale" => {
g.resolution_scale = number(g.resolution_scale).clamp(50, 200)
}
"resolutionScale" => g.resolution_scale = number(g.resolution_scale).clamp(50, 200),
"fxaa" => g.fxaa = flag(g.fxaa),
"overlay" => {
g.overlay = match value {
@@ -308,6 +306,9 @@ mod tests {
};
assert_eq!(Graphics::parse(&g.serialize()), g);
assert_eq!(Graphics::parse(""), Graphics::default());
assert_eq!(Graphics::parse("workers:abc\nsky:maybe\n"), Graphics::default());
assert_eq!(
Graphics::parse("workers:abc\nsky:maybe\n"),
Graphics::default()
);
}
}
+21 -3
View File
@@ -78,12 +78,26 @@ impl Style {
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) {
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) {
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) {
@@ -146,7 +160,11 @@ impl Style {
fn wrap(atlas: &HudAtlas, text: &str, width: f32, indent: f32) -> Vec<String> {
let mut lines = vec![String::new()];
for word in text.split_whitespace() {
let room = if lines.len() == 1 { width - indent } else { width };
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()
+34 -11
View File
@@ -2,7 +2,7 @@
//! 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::{Overlay, Pacing, PresentMode, Preset},
graphics_style::{Cost, STYLE},
hud::{HudAtlas, HudBatch},
options_ui::Opt,
@@ -73,7 +73,11 @@ fn rows(level: Level) -> Vec<Row> {
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 fov = v(
Opt::Fov,
Low,
"Field of view. Wider shows more terrain at once.",
);
let fps = v(
Opt::MaxFps,
None,
@@ -144,13 +148,17 @@ fn rows(level: Level) -> Vec<Row> {
"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.",
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::EntityShadows, Low, "Round shadows under mobs and items."),
v(
Opt::CutoutLeaves,
Medium,
@@ -317,7 +325,11 @@ impl H {
}
}
H::Overlay => {
g.overlay = step(&[Overlay::Off, Overlay::Fps, Overlay::Graph], g.overlay, back)
g.overlay = step(
&[Overlay::Off, Overlay::Fps, Overlay::Graph],
g.overlay,
back,
)
}
_ => {}
}
@@ -339,7 +351,10 @@ impl Item {
// 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)],
&[
Text::translate("options.guiScale", &[]),
Opt::GuiScale.label(s),
],
),
Item::Vanilla(o) => o.label(s),
Item::Horizon(h) => h.label(s),
@@ -364,7 +379,9 @@ impl Item {
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)
| Item::Vanilla(
Opt::GuiScale | Opt::Fullscreen | Opt::Vsync | Opt::MaxFps | Opt::Fov
)
);
if !presetless {
s.horizon.preset = Preset::Custom;
@@ -529,7 +546,13 @@ impl GraphicsUi {
Action::OpenSimple => "Simple...",
_ => "Done",
};
STYLE.button(batch, atlas, (wd.x, wd.y, wd.w), &Text::literal(label), hover);
STYLE.button(
batch,
atlas,
(wd.x, wd.y, wd.w),
&Text::literal(label),
hover,
);
}
}
}
+3 -3
View File
@@ -47,10 +47,10 @@ pub mod fog;
pub mod font;
pub mod gamerules;
pub mod gfx;
pub mod gossip;
pub mod graphics;
pub mod graphics_style;
pub mod graphics_ui;
pub mod gossip;
pub mod health;
pub mod hotbar;
pub mod hud;
@@ -85,10 +85,10 @@ 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;
pub mod perf_overlay;
pub mod pose;
pub mod projectiles;
pub mod raid;
@@ -110,8 +110,8 @@ pub mod skins;
pub mod snbt;
pub mod sound_engine;
pub mod sound_events;
pub mod sprint;
pub mod spans;
pub mod sprint;
pub mod sprites;
pub mod stations;
pub mod stopwatches;
+13 -2
View File
@@ -53,7 +53,11 @@ impl FrameGraph {
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) };
let color = if i == 0 {
rgba(255, 255, 255, 255)
} else {
rgba(200, 200, 200, 255)
};
batch.text_styled(
atlas,
&Text::literal(line.clone()),
@@ -93,7 +97,14 @@ impl FrameGraph {
}
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));
batch.fill(
atlas,
x + 3.0,
ly,
width - 6.0,
1.0,
rgba(255, 255, 255, 90),
);
}
}
}
+14 -7
View File
@@ -36,13 +36,13 @@ use horizon_world::{
};
use std::{
collections::{BTreeMap, HashMap},
sync::{
Condvar, mpsc,
atomic::{AtomicU64, Ordering},
},
fs,
path::{Path, PathBuf},
sync::{Arc, Mutex, OnceLock},
sync::{
Arc, Condvar, Mutex, OnceLock,
atomic::{AtomicU64, Ordering},
mpsc,
},
};
pub const VERSION_NAME: &str = "26.3";
@@ -1361,7 +1361,11 @@ impl SaveDir {
batch.push((key, record, seq));
}
}
*self.outstanding.count.lock().map_err(|_| "writer poisoned")? += 1;
*self
.outstanding
.count
.lock()
.map_err(|_| "writer poisoned")? += 1;
let mut writer = self.writer.lock().map_err(|_| "writer poisoned")?;
let writer = writer.get_or_insert_with(|| self.start_writer());
if writer.send.send((entities, batch)).is_err() {
@@ -1395,7 +1399,10 @@ impl SaveDir {
// Readers find the files (and a fresh region cache) from here on.
if let Ok(mut pending) = pending.lock() {
for (k, _, seq) in &batch {
if pending.get(&(entities, k.0, k.1)).is_some_and(|p| p.0 == *seq) {
if pending
.get(&(entities, k.0, k.1))
.is_some_and(|p| p.0 == *seq)
{
pending.remove(&(entities, k.0, k.1));
}
}
+1 -1
View File
@@ -2,6 +2,7 @@
//! around the player, closest first. The game thread owns the world and only
//! hands immutable `Arc` snapshots to workers; results carry a sequence number
//! so stale work is dropped.
use crate::fast_hash::{FxHashMap, FxHashSet};
use crate::{
chunk::{Chunk, SECTIONS},
light::{LightTables, light_chunk},
@@ -9,7 +10,6 @@ use crate::{
world::World,
};
use horizon_core::biome::BiomeZoom;
use crate::fast_hash::{FxHashMap, FxHashSet};
use std::{
collections::{BinaryHeap, HashSet},
sync::{
+1
View File
@@ -6,6 +6,7 @@ To play, use [the launcher](../launcher/README.md). These pages are for develope
- [Build from source](../README.md#build-from-source): your own copy of the game, resource preparation, `cargo run`.
- [Native client](native-client.md): options, controls, the dedicated server, `horizon-ctl` scripting, packaging, architecture.
- [Graphics](graphics.md): the Simple and Advanced graphics settings, the graphics benchmark and what it measured.
- [Launcher](../launcher/README.md): installs, updates and starts builds; its CLI and MCP server; releasing it.
## Parity
+54
View File
@@ -0,0 +1,54 @@
# Graphics: settings and performance
## Settings
**Options → Video Settings** starts with two buttons for Horizon's own screens:
- **Horizon Graphics…** (Simple): a preset (Performance, Balanced, Quality, Ultra or Custom), render distance, FOV, max framerate, VSync and GUI scale.
- **Advanced Graphics…**: every setting, grouped under Rendering, Quality, Display, Performance and Overlay.
Every row has a one-line description and its cost in frame time (none, low, medium, high), and applies at once, except worker threads, which apply at the next start. A preset sets the quality settings together; changing one of them turns it into Custom. Display preferences (FOV, framerate, VSync, GUI scale, fullscreen, present mode, pacing) leave the preset as it is.
![Simple](media/settings-simple.png)
![Advanced](media/settings-advanced.png)
| Group | Setting | Stored in |
| --- | --- | --- |
| Rendering | render distance, simulation distance, entity distance | `options.txt` (vanilla keys) |
| | cave culling, chunk updates per frame | `horizon-graphics.txt` |
| Quality | smooth lighting, mipmap levels, biome blend, clouds, cloud distance, weather radius, particles, entity shadows, cutout leaves | `options.txt` |
| | sky, fog, weather, animated textures | `horizon-graphics.txt` |
| Display | FOV, max framerate, VSync, fullscreen, GUI scale | `options.txt` |
| | resolution scale, anti-aliasing (FXAA), present mode, frame pacing | `horizon-graphics.txt` |
| Performance | worker threads, upload budget per frame | `horizon-graphics.txt` |
| Overlay | performance overlay: FPS, frame/CPU/GPU times, frame-time graph | `horizon-graphics.txt` |
`options.txt` keeps exactly vanilla's keys and values, so the options harness still compares it with vanilla; Horizon's settings live in `horizon-graphics.txt` beside it. Their defaults render as vanilla does: cave culling on, no upload budgets, sky, fog and weather on, 100% resolution, no FXAA, the present mode following VSync. Frame pacing defaults to Efficient: the limiter sleeps through the last half millisecond where vanilla spins, which changes timing, not pixels.
The screens' layout is in `crates/horizon-client/src/graphics_ui.rs`; every colour, size and widget call is in `graphics_style.rs`, the one place a menu theme replaces.
Not implemented: distant-terrain LOD, anisotropic filtering (wgpu needs linear magnification for it, which blurs close blocks), MSAA (FXAA instead) and exclusive fullscreen (fullscreen is borderless).
## Benchmark
`tools/graphics_bench.py` opens a fresh creative world (seed 1234) on a virtual screen and flies the camera along four fixed 192-block paths, over a village, a forest, the ocean and a mountain, at render distances 8, 16 and 32, one game per distance. Each flight takes 12 seconds and reports average FPS, 1% lows, frame-time percentiles, CPU time per frame (frame time minus waits for the GPU, the display and the limiter), the split of that CPU time (world update, ticks, frame preparation, renderer) for all frames and for the slowest 1%, and GPU time per frame from timestamp queries.
```sh
cargo build --release -p horizon-client --bins
python3 tools/graphics_bench.py --label mine # lavapipe on vscreen: CPU-side numbers
python3 tools/graphics_bench.py --label mine-gpu --offscreen # the desktop's RTX 4080
python3 tools/graphics_bench.py --compare baseline-4080 mine-gpu # markdown table
```
vscreen is a headless compositor whose frames are software-rendered (lavapipe), so its frame times measure the CPU, rasterisation included. `--offscreen` (`horizon-client --offscreen`) renders into a texture on the most powerful GPU instead of the window, which measures the RTX 4080 under the same compositor. `--distances`, `--scenes` and `--build` pick a subset or another build. Results go to `benchmarks/graphics/<label>.json`, with the load average before and after: the desktop is shared, and other sessions' builds move the numbers.
Two tools find where a slow frame goes: `HORIZON_SPIKES=MS` prints the timed spans (ticks by system, streaming, uploads, saving, renderer) of every frame slower than MS milliseconds, and a frame-pointer build (`RUSTFLAGS="-C force-frame-pointers=yes"`) profiles with `perf record --call-graph fp`.
## What changed
The baseline was CPU-bound everywhere: on the RTX 4080 the GPU spent 0.2 to 16 ms per frame, the CPU 2 to 425.
- **Ticking**: mobs, minecarts and dropped items outside the entity-ticking chunks (the simulation distance, as `DistanceManager.inEntityTickingRange`) only check despawning, as in `ServerLevel.tick`; every loaded one used to tick, so render distance 32 ticked seven times as many as vanilla. Villager POI searches skip sections whose palette holds no POI block. Sky darkening is sampled once per time and weather instead of once per mob, and the world's chunk map uses a fast hash.
- **Stalls**: chunks and entity chunks unloaded while moving are encoded and written by a background region writer (loads see queued records first, saves wait for the queue); deleting entity chunks a region doesn't hold no longer rewrites the region file; unloading drops block entities in one pass instead of one per chunk.
- **Rendering**: terrain sections share one vertex arena drawn with one indirect multi-draw per pass, instead of a buffer and draw call each; the cave-culling search runs on dense arrays; mobs are culled by the view frustum and vanilla's per-entity render distance, block entities by the frustum; per-frame scratch buffers are reused.
- **Streaming**: its bookkeeping uses the fast hash, and a column's readiness for meshing is checked once per frame rather than once per dirty section.
+4
View File
@@ -74,6 +74,10 @@ $C bench 10 # avg/1%-low FPS and p50/p95/p99/max frame tim
$C quit # save and exit
```
`fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH]` moves the camera along a line at
constant speed and replies with the same summary as `bench`, plus CPU and GPU
time per frame; [the graphics benchmark](graphics.md#benchmark) is built on it.
Other commands: `status`, `key KEY down|up|tap`, `mouse left|right|middle
down|up|click`, `turn`, `tp X Y Z`, `hotbar N`, `give ITEM [COUNT]`,
`render-distance N`, `time TICKS`, `resume`, `stats [reset]`, `open WORLD [SEED]
+29
View File
@@ -116,9 +116,33 @@ def run_distance(args, ctl, env, cwd, distance):
if not socket.exists():
break
time.sleep(0.2)
# Keep each game's log (a crash or a slow-frame report) per run.
log = socket.with_suffix(".log")
if log.exists():
shutil.copy(log, cwd / f"{args.label}-rd{distance}.log")
return results
def compare(before, after):
"""A markdown table of two saved runs (labels under benchmarks/graphics)."""
load = lambda label: json.loads((ROOT / "benchmarks/graphics" / f"{label}.json").read_text())
a, b = load(before), load(after)
print(f"| RD | scene | avg FPS | 1% low FPS | p99 ms | CPU ms/frame | GPU ms/frame |")
print("| --- | --- | --- | --- | --- | --- | --- |")
cell = lambda x, y, f: f"{f(x)} → {f(y)}"
for rd, scenes in a["distances"].items():
for name, old in scenes.items():
new = b["distances"].get(rd, {}).get(name)
if name == "renderer" or not new:
continue
ms = lambda v, k: (v.get(k) or {}).get("avg_ms") or 0
print(f"| {rd} | {name} | {cell(old['avg_fps'], new['avg_fps'], lambda v: f'{v:.0f}')} "
f"| {cell(old['low_1pct_fps'], new['low_1pct_fps'], lambda v: f'{v:.1f}')} "
f"| {cell(old['p99_ms'], new['p99_ms'], lambda v: f'{v:.0f}')} "
f"| {cell(ms(old, 'cpu'), ms(new, 'cpu'), lambda v: f'{v:.1f}')} "
f"| {cell(ms(old, 'gpu'), ms(new, 'gpu'), lambda v: f'{v:.2f}')} |")
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--label", default="run")
@@ -130,7 +154,12 @@ def main():
p.add_argument("--resources", default=str(ROOT / ".local/horizon-client/26.3"))
p.add_argument("--build", default=str(ROOT / "target/release"))
p.add_argument("--out", help="JSON file (default benchmarks/graphics/<label>.json)")
p.add_argument("--compare", nargs=2, metavar=("BEFORE", "AFTER"),
help="print a markdown table comparing two saved runs, and exit")
args = p.parse_args()
if args.compare:
compare(*args.compare)
return
ctl = Path(args.build).resolve() / "horizon-ctl"
if not ctl.exists():
sys.exit(f"{ctl} missing: cargo build --release -p horizon-client --bins")