Files
horizon-airdef/crates/horizon-client/src/graphics.rs
T
Ludovic Marie 35f78ae27c Shader packs: run a pack's composite stages over the world, with hot reload
With shaderPack set in horizon-graphics.txt, the world renders into
world_post's target with its depth kept, each composite stage of the
pack (gfx/pack_stages.rs) draws a full-screen pass reading the scene
colour and depth, the previous stage and the Frame uniform (camera,
matrices, time, sun and moon, sky and fog colours and distances,
weather, camera state, dimension), and the last output goes to the
screen through the usual copy/FXAA, under the hand, screen effects and
HUD. The game loads the pack from shaderpacks/, checks its files twice
a second and on F3 + T, and keeps the last good pack on errors, which
go to chat. Without a pack nothing changes: no target, no extra pass,
depth discarded as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:25:23 +02:00

360 lines
12 KiB
Rust

//! Horizon's own graphics settings, beyond vanilla's options: kept in
//! `horizon-graphics.txt` next to `options.txt` so that file stays exactly
//! vanilla's. Every default reproduces vanilla's rendering; only choices the
//! player makes here depart from it.
use std::{fs, path::Path};
pub const FILE: &str = "horizon-graphics.txt";
/// Simple-level presets. `Custom` leaves every option as the player set it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Preset {
Performance,
Balanced,
Quality,
Ultra,
#[default]
Custom,
}
impl Preset {
pub const ALL: [Preset; 5] = [
Preset::Performance,
Preset::Balanced,
Preset::Quality,
Preset::Ultra,
Preset::Custom,
];
pub fn name(self) -> &'static str {
match self {
Preset::Performance => "performance",
Preset::Balanced => "balanced",
Preset::Quality => "quality",
Preset::Ultra => "ultra",
Preset::Custom => "custom",
}
}
pub fn label(self) -> &'static str {
match self {
Preset::Performance => "Performance",
Preset::Balanced => "Balanced",
Preset::Quality => "Quality",
Preset::Ultra => "Ultra",
Preset::Custom => "Custom",
}
}
fn parse(s: &str) -> Self {
Self::ALL
.into_iter()
.find(|p| p.name() == s)
.unwrap_or_default()
}
}
/// How the swapchain presents frames.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum PresentMode {
/// Follow vanilla's VSync option (Mailbox or Fifo on, Immediate off).
#[default]
Auto,
Fifo,
Mailbox,
Immediate,
}
impl PresentMode {
pub const ALL: [PresentMode; 4] = [
PresentMode::Auto,
PresentMode::Fifo,
PresentMode::Mailbox,
PresentMode::Immediate,
];
pub fn name(self) -> &'static str {
match self {
PresentMode::Auto => "auto",
PresentMode::Fifo => "fifo",
PresentMode::Mailbox => "mailbox",
PresentMode::Immediate => "immediate",
}
}
pub fn label(self) -> &'static str {
match self {
PresentMode::Auto => "Auto (VSync)",
PresentMode::Fifo => "FIFO",
PresentMode::Mailbox => "Mailbox",
PresentMode::Immediate => "Immediate",
}
}
fn parse(s: &str) -> Self {
Self::ALL
.into_iter()
.find(|p| p.name() == s)
.unwrap_or_default()
}
}
/// What the frame limiter does in the last half millisecond before a frame.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Pacing {
/// Sleep the whole wait: no CPU spent spinning, a little less precise.
#[default]
Efficient,
/// Vanilla's `FramerateLimiter`: sleep, then spin until the deadline.
Precise,
}
/// The performance overlay drawn over the HUD.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Overlay {
#[default]
Off,
/// Frames per second and frame time.
Fps,
/// The numbers and a graph of recent frame times.
Graph,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Graphics {
pub preset: Preset,
/// Skip sections hidden behind closed ones (vanilla's occlusion graph).
pub cave_culling: bool,
/// Meshed sections uploaded per frame; 0 uploads all that are ready.
pub chunk_updates: u32,
/// Section mesh bytes uploaded per frame, in KiB; 0 is unlimited.
pub upload_budget_kib: u32,
pub sky: bool,
pub fog: bool,
pub weather: bool,
pub animated_textures: bool,
pub present_mode: PresentMode,
pub pacing: Pacing,
/// Chunk worker threads; 0 uses every core but one. Applies at the next start.
pub workers: u32,
pub overlay: Overlay,
/// World resolution as a percentage of the window's (50..=200).
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.
pub battery: bool,
/// The Horizon shader pack in `shaderpacks/` (its folder name); empty:
/// none, the vanilla picture (docs/shader-packs.md).
pub shader_pack: String,
}
impl Default for Graphics {
fn default() -> Self {
Self {
preset: Preset::Custom,
cave_culling: true,
chunk_updates: 0,
upload_budget_kib: 0,
sky: true,
fog: true,
weather: true,
animated_textures: true,
present_mode: PresentMode::Auto,
pacing: Pacing::Efficient,
workers: 0,
overlay: Overlay::Off,
resolution_scale: 100,
fxaa: false,
advanced: false,
battery: false,
shader_pack: String::new(),
}
}
}
fn bool_text(v: bool) -> &'static str {
if v { "true" } else { "false" }
}
impl Graphics {
pub fn load(dir: &Path) -> Self {
fs::read_to_string(dir.join(FILE))
.map(|t| Self::parse(&t))
.unwrap_or_default()
}
pub fn parse(text: &str) -> Self {
let mut g = Self::default();
for line in text.lines() {
let Some((key, value)) = line.split_once(':') else {
continue;
};
let value = value.trim();
let flag = |d: bool| match value {
"true" => true,
"false" => false,
_ => d,
};
let number = |d: u32| value.parse().unwrap_or(d);
match key.trim() {
"preset" => g.preset = Preset::parse(value),
"caveCulling" => g.cave_culling = flag(g.cave_culling),
"chunkUpdates" => g.chunk_updates = number(g.chunk_updates).min(512),
"uploadBudgetKiB" => g.upload_budget_kib = number(g.upload_budget_kib).min(65536),
"sky" => g.sky = flag(g.sky),
"fog" => g.fog = flag(g.fog),
"weather" => g.weather = flag(g.weather),
"animatedTextures" => g.animated_textures = flag(g.animated_textures),
"presentMode" => g.present_mode = PresentMode::parse(value),
"framePacing" => {
g.pacing = if value == "precise" {
Pacing::Precise
} else {
Pacing::Efficient
}
}
"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(),
"overlay" => {
g.overlay = match value {
"fps" => Overlay::Fps,
"graph" => Overlay::Graph,
_ => Overlay::Off,
}
}
_ => {}
}
}
g
}
pub fn serialize(&self) -> String {
format!(
"preset:{}\ncaveCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\n",
self.preset.name(),
bool_text(self.cave_culling),
self.chunk_updates,
self.upload_budget_kib,
bool_text(self.sky),
bool_text(self.fog),
bool_text(self.weather),
bool_text(self.animated_textures),
self.present_mode.name(),
match self.pacing {
Pacing::Efficient => "efficient",
Pacing::Precise => "precise",
},
self.workers,
match self.overlay {
Overlay::Off => "off",
Overlay::Fps => "fps",
Overlay::Graph => "graph",
},
self.resolution_scale,
bool_text(self.fxaa),
if self.advanced { "advanced" } else { "simple" },
bool_text(self.battery),
self.shader_pack,
)
}
pub fn save(&self, dir: &Path) {
let _ = fs::write(dir.join(FILE), self.serialize());
}
/// Worker threads for chunk generation and meshing.
pub fn worker_threads(&self) -> usize {
if self.workers > 0 {
return self.workers as usize;
}
let auto = std::thread::available_parallelism()
.map_or(2, |n| n.get())
.saturating_sub(1)
.max(1);
if self.battery { auto.div_ceil(2) } else { auto }
}
/// The frame cap battery mode adds: 60 in a world, 30 in menus without a
/// world or while another window has focus.
pub fn battery_limit(&self, limit: i32, in_world: bool, focused: bool) -> i32 {
if !self.battery {
limit
} else if in_world && focused {
limit.min(60)
} else {
limit.min(30)
}
}
}
/// A preset's values for vanilla's options and Horizon's own.
pub fn apply_preset(preset: Preset, s: &mut crate::settings::Settings) {
let (rd, sim, clouds, particles, shadows, blend, mipmaps, entity, leaves, weather_r) =
match preset {
Preset::Performance => (8, 6, "false", 2, false, 0, 0, 0.5, false, 3),
Preset::Balanced => (12, 8, "fast", 1, true, 1, 2, 0.75, true, 5),
Preset::Quality => (16, 12, "true", 0, true, 2, 4, 1.0, true, 10),
Preset::Ultra => (24, 12, "true", 0, true, 3, 4, 1.5, true, 10),
Preset::Custom => return,
};
s.render_distance = rd;
s.simulation_distance = sim;
s.clouds = clouds.into();
s.particles = particles;
s.entity_shadows = shadows;
s.biome_blend = blend;
s.mipmap_levels = mipmaps;
s.entity_distance = entity;
s.cutout_leaves = leaves;
s.weather_radius = weather_r;
s.graphics_preset = "custom".into();
let g = &mut s.horizon;
g.preset = preset;
g.cave_culling = true;
g.animated_textures = preset != Preset::Performance;
g.chunk_updates = 0;
g.upload_budget_kib = 0;
g.sky = true;
g.fog = true;
g.weather = true;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips() {
let g = Graphics {
preset: Preset::Balanced,
cave_culling: false,
chunk_updates: 12,
upload_budget_kib: 4096,
sky: false,
fog: false,
weather: false,
animated_textures: false,
present_mode: PresentMode::Mailbox,
pacing: Pacing::Precise,
workers: 6,
overlay: Overlay::Graph,
resolution_scale: 75,
fxaa: true,
advanced: true,
battery: true,
shader_pack: "horizon-sample".into(),
};
assert_eq!(Graphics::parse(&g.serialize()), g);
assert_eq!(Graphics::parse(""), Graphics::default());
assert_eq!(
Graphics::parse("workers:abc\nsky:maybe\n"),
Graphics::default()
);
}
#[test]
fn battery_mode_only_lowers_the_frame_cap() {
let mut g = Graphics::default();
assert_eq!(g.battery_limit(260, true, true), 260);
g.battery = true;
assert_eq!(g.battery_limit(260, true, true), 60);
assert_eq!(g.battery_limit(30, true, true), 30);
assert_eq!(g.battery_limit(260, false, true), 30);
assert_eq!(g.battery_limit(260, true, false), 30);
assert_eq!(g.battery_limit(10, true, false), 10);
}
}