From 35f78ae27c803e47c90d6d95ba1f0a80b54e49ee Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:25:23 +0200 Subject: [PATCH] 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 --- crates/horizon-client/src/game.rs | 6 + crates/horizon-client/src/game/debug_keys.rs | 1 + crates/horizon-client/src/game/options.rs | 8 + crates/horizon-client/src/game/render_tick.rs | 33 ++ .../horizon-client/src/game/shader_packs.rs | 92 +++++ crates/horizon-client/src/gfx.rs | 133 ++++++- crates/horizon-client/src/gfx/pack_stages.rs | 325 ++++++++++++++++++ crates/horizon-client/src/gfx/world_post.rs | 59 ++-- crates/horizon-client/src/graphics.rs | 9 +- 9 files changed, 640 insertions(+), 26 deletions(-) create mode 100644 crates/horizon-client/src/game/shader_packs.rs create mode 100644 crates/horizon-client/src/gfx/pack_stages.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 16fa59240..e999e9832 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -99,6 +99,7 @@ mod scoreboard; mod screens; mod sculk; mod sculk_fixture; +mod shader_packs; mod shield; mod sign_edit; mod sniffers; @@ -711,6 +712,8 @@ struct Game<'a> { modifiers: winit::keyboard::ModifiersState, /// The window's fullscreen request and reported state. fullscreen: horizon_client::window::FullscreenState, + /// The selected Horizon shader pack (`game/shader_packs.rs`). + shader_packs: shader_packs::ShaderPacks, /// MouseHandler's accumulated look and wheel state. mouse: MouseLook, /// An agent moved the mouse (`mouse-move`) since the pointer was last @@ -8132,6 +8135,7 @@ impl Game<'_> { Ok(()) } fn render(&mut self) -> Result { + self.poll_shader_pack(); let Some(size) = self .renderer .as_ref() @@ -8325,6 +8329,7 @@ impl Game<'_> { .then(|| self.border_draw(camera.to_array(), alpha as f32)) .flatten(); let frame = Frame { + shader: self.shader_inputs(camera, alpha as f32), nether_lighting: self.dim == Dim::Nether, camera, yaw, @@ -9645,6 +9650,7 @@ pub fn run() -> Result<()> { focused: true, modifiers: winit::keyboard::ModifiersState::empty(), fullscreen: horizon_client::window::FullscreenState::new(false), + shader_packs: Default::default(), mouse: MouseLook::default(), agent_pointer: false, smooth_camera: false, diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 05380d980..6f38e2704 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -375,6 +375,7 @@ impl Game<'_> { DebugAction::ReloadResourcePacks => { self.debug_translated("debug.reload_resourcepacks.message"); self.reload_packs(); + self.load_shader_pack(); true } DebugAction::CopyLocation if player => { diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index cdeb68d0a..5aebd8cb1 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -204,6 +204,14 @@ impl Game<'_> { font.reset_cache(); self.ui.chat.rescale(&self.res.atlas); } + // A new renderer (resource reload, first window) takes the loaded pack. + let stale = self + .renderer + .as_ref() + .is_some_and(|r| r.shader_pack_id() != self.shader_packs.id()); + if stale && let Err(e) = self.apply_shader_pack() { + log::warn!("Horizon: shader pack: {e}"); + } } /// `Window.updateFullscreenState`: a fullscreen change made by the window /// system is adopted by the option (`Minecraft.fullscreenStateChanged`). diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 10e8ffd13..bc08df07c 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -97,6 +97,39 @@ impl Game<'_> { boss_world_fog: self.dragon_bar_shown(), }) } + /// What a shader pack's `Frame` uniform reads of the game this frame. + pub(super) fn shader_inputs( + &self, + camera: glam::DVec3, + partial_tick: f32, + ) -> horizon_client::gfx::ShaderInputs { + let (rain, thunder) = if self.dim == Dim::Overworld { + self.world.weather.levels(self.clock.fraction() as f32) + } else { + (0.0, 0.0) + }; + let at = [camera.x, camera.y, camera.z]; + let day = self.world.day_time; + horizon_client::gfx::ShaderInputs { + rain, + thunder, + submerged: match fog_type(&self.world, &self.res.facts, at, self.forward()) { + FogType::Atmospheric => 0, + FogType::Water => 1, + FogType::Lava => 2, + FogType::PowderSnow => 3, + }, + dimension: match self.dim { + Dim::Overworld => 0, + Dim::Nether => -1, + Dim::End => 1, + }, + has_sky_light: self.dim == Dim::Overworld, + moon_phase: day.div_euclid(24_000).rem_euclid(8) as u8, + day_fraction: (day.rem_euclid(24_000) as f32 + partial_tick) / 24_000.0, + partial_tick, + } + } /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water. pub(super) fn dark_disc(&self, camera: glam::DVec3) -> bool { camera.y < 63.0 diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs new file mode 100644 index 000000000..ddccdcee6 --- /dev/null +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -0,0 +1,92 @@ +//! The selected Horizon shader pack (`shaderPack` in `horizon-graphics.txt`, +//! docs/shader-packs.md): loaded from `shaderpacks/`, given to the renderer, +//! and loaded again when the selection changes, on F3 + T, or when its files +//! change (checked twice a second). A pack that fails leaves the last good +//! one (or the vanilla picture) on and says why in chat. +use super::Game; +use horizon_client::shader_pack::{self, ShaderPack, Stamp}; +use horizon_client::text::Text; +use std::{ + path::PathBuf, + time::{Duration, Instant}, +}; + +#[derive(Default)] +pub(super) struct ShaderPacks { + /// The pack the renderer runs. + pack: Option, + /// The selection and its files at the last load, success or not. + selected: String, + stamp: Stamp, + checked: Option, +} + +impl ShaderPacks { + /// The loaded pack's folder name. + pub(super) fn id(&self) -> Option<&str> { + self.pack.as_ref().map(|p| p.id.as_str()) + } +} + +/// `shaderpacks/` beside `options.txt`. +pub(super) fn dir() -> PathBuf { + std::env::current_dir() + .unwrap_or_default() + .join(shader_pack::DIR) +} + +impl Game<'_> { + /// Load the selected pack and give it to the renderer. + pub(super) fn load_shader_pack(&mut self) { + let id = self.settings.horizon.shader_pack.clone(); + let dir = dir(); + let state = &mut self.shader_packs; + state.selected = id.clone(); + state.checked = Some(Instant::now()); + let pack = if id.is_empty() { + state.stamp = Stamp::default(); + None + } else { + state.stamp = Stamp::of(&dir.join(&id)); + match ShaderPack::load(&dir.join(&id), &shader_pack::load_values(&dir, &id)) { + Ok(pack) => Some(pack), + Err(e) => return self.shader_pack_error(&id, &e), + } + }; + if let Some(r) = self.renderer.as_mut() + && let Err(e) = r.set_shader_pack(pack.as_ref()) + { + return self.shader_pack_error(&id, &e.to_string()); + } + self.shader_packs.pack = pack; + } + /// Give the loaded pack to the renderer (also after it is rebuilt). + pub(super) fn apply_shader_pack(&mut self) -> horizon_client::Result<()> { + match self.renderer.as_mut() { + Some(r) => r.set_shader_pack(self.shader_packs.pack.as_ref()), + None => Ok(()), + } + } + /// Every frame: a new selection or edited pack files load it again. + pub(super) fn poll_shader_pack(&mut self) { + let state = &mut self.shader_packs; + if self.settings.horizon.shader_pack != state.selected { + return self.load_shader_pack(); + } + if state.selected.is_empty() + || state + .checked + .is_some_and(|t| t.elapsed() < Duration::from_millis(500)) + { + return; + } + state.checked = Some(Instant::now()); + if Stamp::of(&dir().join(&state.selected)) != state.stamp { + self.load_shader_pack(); + } + } + fn shader_pack_error(&mut self, id: &str, error: &str) { + log::warn!("Horizon: shader pack {id}: {error}"); + self.system_message(Text::literal(format!("Shader pack {id}: {error}"))); + } +} diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 8b7f26125..4079efa4d 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -59,6 +59,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] mod arena; mod occlusion; +mod pack_stages; pub mod panorama; mod timing; mod world_post; @@ -173,6 +174,25 @@ pub struct Frame<'a> { /// `Screen.extractBlurredBackground`: blur the frame by this radius /// (`menuBackgroundBlurriness`) before the screen is drawn over it. pub menu_blur: Option, + /// What a shader pack's `Frame` uniform reads beyond the rest of the frame. + pub shader: ShaderInputs, +} +/// A shader pack's view of the game this frame (docs/shader-packs.md, `Frame`). +#[derive(Clone, Copy, Debug, Default)] +pub struct ShaderInputs { + /// `Level.getRainLevel` and `getThunderLevel` at the partial tick. + pub rain: f32, + pub thunder: f32, + /// The camera's fog type: 0 air, 1 water, 2 lava, 3 powder snow. + pub submerged: u8, + /// 0 overworld, -1 the Nether, 1 the End. + pub dimension: i8, + pub has_sky_light: bool, + /// `DimensionType.moonPhase`, 0..=7. + pub moon_phase: u8, + /// The time of day as a fraction (0 sunrise, 0.25 noon) and the partial tick. + pub day_fraction: f32, + pub partial_tick: f32, } /// One frame of the world border wall (`WorldBorderRenderer.render`). #[derive(Clone, Debug)] @@ -291,6 +311,8 @@ pub struct Renderer { occlusion: occlusion::Occlusion, /// Resolution scale and FXAA (Horizon settings). world_post: world_post::Post, + /// The selected shader pack's stages (Horizon setting; none by default). + pack: Option, pub hud: HudRenderer, /// The menus' backdrop blur, made on first use. post: Option, @@ -1440,6 +1462,7 @@ impl Renderer { block_entities: HashMap::new(), occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16), world_post, + pack: None, hud, post: None, menu_blur: None, @@ -1659,6 +1682,23 @@ impl Renderer { self.occlusion.remove(key); self.release_section(key); } + /// Run `pack`'s stages over the world from now on (`None`: no pack, the + /// vanilla frame). On error the previous pack stays. + pub fn set_shader_pack(&mut self, pack: Option<&crate::shader_pack::ShaderPack>) -> Result<()> { + self.pack = match pack { + Some(pack) => Some(pack_stages::PackStages::new( + &self.device, + self.config.format.remove_srgb_suffix(), + pack, + )?), + None => None, + }; + Ok(()) + } + /// The folder name of the pack `set_shader_pack` gave. + pub fn shader_pack_id(&self) -> Option<&str> { + self.pack.as_ref().map(|p| p.id.as_str()) + } /// Horizon's resolution scale (world pixels per window pixel) and FXAA. pub fn set_world_post(&mut self, scale: f32, antialias: bool) { self.world_post.scale = scale.clamp(0.25, 2.0); @@ -1965,6 +2005,15 @@ impl Renderer { }; self.queue .write_buffer(&self.globals, 0, bytemuck::bytes_of(&globals)); + let pack_uniform = shader_pack_uniform( + frame, + view, + world_projection(frame.fov_degrees, aspect, frame.depth_far) * frame.bob, + sun, + fog_color, + globals.fog, + globals.fog_ends, + ); // GameRenderer.render3dHud: the hand's projection at hudFov, with the // bob in its pose rather than the projection (same product). let hand_projection = Mat4::from_cols_array(&crate::camera::hand_projection( @@ -2185,9 +2234,10 @@ impl Renderer { timer.begin(&mut encoder); } // The world's targets: the screen, or the scaled target of `post`. - let scaled = self - .world_post - .prepare(&self.device, [self.config.width, self.config.height]); + let pack = self.pack.is_some() && !frame.title; + let scaled = + self.world_post + .prepare(&self.device, [self.config.width, self.config.height], pack); let (world_view, world_depth) = match &scaled { Some((color, depth)) => (color, depth), None => (&view_target, &self.depth), @@ -2220,7 +2270,12 @@ impl Renderer { view: world_depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0.0), - store: wgpu::StoreOp::Discard, + // A shader pack reads the world's depth. + store: if pack { + wgpu::StoreOp::Store + } else { + wgpu::StoreOp::Discard + }, }), stencil_ops: None, }), @@ -2330,7 +2385,22 @@ impl Renderer { ); } } - if scaled.is_some() { + if let (true, Some((color, depth)), Some(size), Some(stages)) = + (pack, &scaled, self.world_post.size(), self.pack.as_mut()) + { + let output = stages.run( + &self.device, + &self.queue, + &mut encoder, + color, + depth, + size, + &self.world_post, + pack_uniform, + ); + self.world_post + .finish_with(&mut encoder, &view_target, output); + } else if scaled.is_some() { self.world_post.finish(&mut encoder, &view_target); } if hand_quads > 0 { @@ -2595,6 +2665,59 @@ impl Frustum { /// Vanilla's `Projection`: reversed depth (near maps to 1, far to 0, tests /// are GREATER_THAN_OR_EQUAL), which keeps far faces a hair apart, like /// fire_side's 0.01 pixel in front of its block, from z-fighting. +/// The prelude's `Frame` (`shader_pack_prelude.wgsl`); `resolution` and the +/// time are filled per stage. +fn shader_pack_uniform( + frame: &Frame, + view: Mat4, + projection: Mat4, + sun: Vec3, + fog_color: [f32; 4], + fog: [f32; 4], + fog_ends: [f32; 4], +) -> pack_stages::FrameUniform { + let s = frame.shader; + let sky = frame.sky.sky_color; + pack_stages::FrameUniform { + view: view.to_cols_array_2d(), + projection: projection.to_cols_array_2d(), + inverse_view: view.inverse().to_cols_array_2d(), + inverse_projection: projection.inverse().to_cols_array_2d(), + camera_position: [ + frame.camera.x as f32, + frame.camera.y as f32, + frame.camera.z as f32, + 0.0, + ], + time: [0.0, 0.0, s.day_fraction, s.partial_tick], + sun: [sun.x, sun.y, sun.z, frame.sky.sun_angle.to_radians()], + moon: [-sun.x, -sun.y, -sun.z, f32::from(s.moon_phase)], + sky_color: [sky[0], sky[1], sky[2], 1.0], + fog_color, + fog: [fog[0], fog[1], fog_ends[0], fog_ends[1]], + weather: [s.rain, s.thunder, 0.0, 0.0], + camera_state: [ + f32::from(s.submerged), + frame.night_vision, + frame.darkness.1, + 0.0, + ], + view_params: [ + 0.05, + frame.depth_far, + frame.distance, + frame.fov_degrees.to_radians(), + ], + dimension: [ + f32::from(s.dimension), + f32::from(u8::from(s.has_sky_light)), + 0.0, + 0.0, + ], + ..Default::default() + } +} + fn world_projection(fov_degrees: f32, aspect: f32, far: f32) -> Mat4 { Mat4::perspective_rh(fov_degrees.to_radians(), aspect, far, 0.05) } diff --git a/crates/horizon-client/src/gfx/pack_stages.rs b/crates/horizon-client/src/gfx/pack_stages.rs new file mode 100644 index 000000000..87d22d07d --- /dev/null +++ b/crates/horizon-client/src/gfx/pack_stages.rs @@ -0,0 +1,325 @@ +//! A Horizon shader pack on the GPU (docs/shader-packs.md): each `composite` +//! stage is one full-screen pass that reads the world's colour and depth and +//! the previous stage's output and writes its own target; the last target +//! goes to the screen through `world_post` (copy or FXAA) under the hand and +//! HUD. Only exists while a pack is selected. +use crate::shader_pack::{ShaderPack, VERTEX_ENTRY}; + +/// The `Frame` uniform of the prelude (`shader_pack_prelude.wgsl`). +#[repr(C)] +#[derive(Clone, Copy, Default, bytemuck::Pod, bytemuck::Zeroable)] +pub struct FrameUniform { + pub view: [[f32; 4]; 4], + pub projection: [[f32; 4]; 4], + pub inverse_view: [[f32; 4]; 4], + pub inverse_projection: [[f32; 4]; 4], + pub camera_position: [f32; 4], + pub resolution: [f32; 4], + pub time: [f32; 4], + pub sun: [f32; 4], + pub moon: [f32; 4], + pub sky_color: [f32; 4], + pub fog_color: [f32; 4], + pub fog: [f32; 4], + pub weather: [f32; 4], + pub camera_state: [f32; 4], + pub view_params: [f32; 4], + pub dimension: [f32; 4], +} + +struct Pass { + pipeline: wgpu::RenderPipeline, + scale: f32, + uniform: wgpu::Buffer, +} +/// A stage's output and the bindings that read the world into it. +struct Target { + size: [u32; 2], + view: wgpu::TextureView, + group: wgpu::BindGroup, +} + +pub struct PackStages { + pub id: String, + layout: wgpu::BindGroupLayout, + linear: wgpu::Sampler, + nearest: wgpu::Sampler, + passes: Vec, + format: wgpu::TextureFormat, + /// Built for this world target size. + targets: Vec, + /// `world_post`'s bindings of the last stage's output. + output: Option, + world_size: [u32; 2], + started: std::time::Instant, + frames: u32, +} + +impl PackStages { + /// The pipelines of a loaded (already validated) pack, or wgpu's error. + pub fn new( + device: &wgpu::Device, + format: wgpu::TextureFormat, + pack: &ShaderPack, + ) -> Result { + let texture = |binding, sample_type| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }; + let float = wgpu::TextureSampleType::Float { filterable: true }; + let sampler = |binding, ty| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(ty), + count: None, + }; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Shader pack stage"), + entries: &[ + texture(0, float), + texture(1, wgpu::TextureSampleType::Depth), + texture(2, float), + sampler(3, wgpu::SamplerBindingType::Filtering), + sampler(4, wgpu::SamplerBindingType::NonFiltering), + wgpu::BindGroupLayoutEntry { + binding: 5, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Shader pack stage"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let constants = pack.constants(); + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let passes = pack + .stages + .iter() + .map(|stage| { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(&stage.file), + source: wgpu::ShaderSource::Wgsl(stage.source.as_str().into()), + }); + // Only the overrides a stage declares may be passed to it. + let constants: Vec<(&str, f64)> = constants + .iter() + .copied() + .filter(|(key, _)| declares_override(&stage.source, key)) + .collect(); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(&stage.file), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some(VERTEX_ENTRY), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some(&stage.entry), + compilation_options: wgpu::PipelineCompilationOptions { + constants: &constants, + ..Default::default() + }, + targets: &[Some(wgpu::ColorTargetState { + format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + Pass { + pipeline, + scale: stage.scale, + uniform: device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Shader pack frame"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), + } + }) + .collect(); + if let Some(error) = pollster::block_on(scope.pop()) { + return Err(error.to_string()); + } + let sampler = |filter| { + device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Shader pack"), + mag_filter: filter, + min_filter: filter, + ..Default::default() + }) + }; + Ok(Self { + id: pack.id.clone(), + layout, + linear: sampler(wgpu::FilterMode::Linear), + nearest: sampler(wgpu::FilterMode::Nearest), + passes, + format, + targets: Vec::new(), + output: None, + world_size: [0, 0], + started: std::time::Instant::now(), + frames: 0, + }) + } + + /// Run every stage over the world's `color` and `depth` (`size`) and + /// return `post`'s bindings of the last stage's output. + #[allow(clippy::too_many_arguments)] + pub fn run( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + color: &wgpu::TextureView, + depth: &wgpu::TextureView, + size: [u32; 2], + post: &super::world_post::Post, + mut uniform: FrameUniform, + ) -> &wgpu::BindGroup { + if self.world_size != size || self.targets.len() != self.passes.len() { + self.world_size = size; + self.targets.clear(); + for pass in &self.passes { + let target_size = size.map(|v| ((v as f32 * pass.scale).round() as u32).max(1)); + let view = device + .create_texture(&wgpu::TextureDescriptor { + label: Some("Shader pack stage"), + size: wgpu::Extent3d { + width: target_size[0], + height: target_size[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: self.format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + .create_view(&Default::default()); + let previous = self.targets.last().map_or(color, |t: &Target| &t.view); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Shader pack stage"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(color), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(depth), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(previous), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::Sampler(&self.linear), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Sampler(&self.nearest), + }, + wgpu::BindGroupEntry { + binding: 5, + resource: pass.uniform.as_entire_binding(), + }, + ], + }); + self.targets.push(Target { + size: target_size, + view, + group, + }); + } + let last = &self.targets.last().expect("a pack has a stage").view; + self.output = Some(post.bind(device, last)); + } + uniform.time[0] = self.started.elapsed().as_secs_f32(); + uniform.time[1] = self.frames as f32; + self.frames = self.frames.wrapping_add(1); + for (pass, target) in self.passes.iter().zip(&self.targets) { + let [w, h] = target.size.map(|v| v as f32); + uniform.resolution = [w, h, 1.0 / w, 1.0 / h]; + queue.write_buffer(&pass.uniform, 0, bytemuck::bytes_of(&uniform)); + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: &target.view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + })]; + let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Shader pack stage"), + color_attachments: &attachments, + ..Default::default() + }); + render.set_pipeline(&pass.pipeline); + render.set_bind_group(0, &target.group, &[]); + render.draw(0..3, 0..1); + } + self.output.as_ref().expect("bound with the targets") + } +} + +/// `override ` appears in the source (a declaration, not just a use). +fn declares_override(source: &str, key: &str) -> bool { + source.lines().any(|line| { + line.trim_start() + .strip_prefix("override") + .and_then(|rest| rest.trim_start().strip_prefix(key)) + .is_some_and(|rest| rest.trim_start().starts_with([':', '='])) + }) +} + +#[cfg(test)] +mod tests { + #[test] + fn the_frame_uniform_matches_the_prelude() { + // 4 matrices and 12 vectors, as `struct Frame` in the prelude. + assert_eq!(std::mem::size_of::(), 4 * 64 + 12 * 16); + let prelude = crate::shader_pack::PRELUDE; + let body = prelude.split("struct Frame {").nth(1).unwrap(); + let body = &body[..body.find('}').unwrap()]; + assert_eq!(body.matches("mat4x4").count(), 4); + assert_eq!(body.matches("vec4").count(), 12); + } + #[test] + fn only_declared_overrides_are_passed() { + let source = + "override saturation: f32 = 1.0;\noverride vignette = true;\nlet x = saturation_2;"; + assert!(super::declares_override(source, "saturation")); + assert!(super::declares_override(source, "vignette")); + assert!(!super::declares_override(source, "saturation_2")); + assert!(!super::declares_override(source, "haze")); + } +} diff --git a/crates/horizon-client/src/gfx/world_post.rs b/crates/horizon-client/src/gfx/world_post.rs index bd067ec76..797ee03b7 100644 --- a/crates/horizon-client/src/gfx/world_post.rs +++ b/crates/horizon-client/src/gfx/world_post.rs @@ -1,7 +1,8 @@ //! Resolution scale and FXAA (Horizon settings): the world renders into its //! own target at the scaled size, then one full-screen pass copies or -//! anti-aliases it onto the screen, under the hand and HUD. With neither -//! setting on, the world renders straight to the screen as before. +//! anti-aliases it onto the screen, under the hand and HUD. A shader pack +//! also needs the target (its stages read the world's colour and depth). +//! With none of them on, the world renders straight to the screen as before. struct WorldTarget { size: [u32; 2], @@ -99,13 +100,14 @@ impl Post { } } /// The world's colour and depth targets this frame, or `None` to draw - /// it straight to the screen. + /// it straight to the screen. `pack`: a shader pack runs this frame. pub fn prepare( &mut self, device: &wgpu::Device, window: [u32; 2], + pack: bool, ) -> Option<(wgpu::TextureView, wgpu::TextureView)> { - if self.scale == 1.0 && !self.antialias { + if self.scale == 1.0 && !self.antialias && !pack { self.target = None; return None; } @@ -138,22 +140,9 @@ impl Post { let depth = texture( "Scaled world depth", wgpu::TextureFormat::Depth32Float, - wgpu::TextureUsages::RENDER_ATTACHMENT, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, ); - let group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("Horizon post"), - layout: &self.layout, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::TextureView(&color), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::Sampler(&self.sampler), - }, - ], - }); + let group = self.bind(device, &color); self.target = Some(WorldTarget { size, color, @@ -165,9 +154,39 @@ impl Post { .as_ref() .map(|t| (t.color.clone(), t.depth.clone())) } + /// The world target's size, once `prepare` made one. + pub fn size(&self) -> Option<[u32; 2]> { + self.target.as_ref().map(|t| t.size) + } + /// Bindings that copy (or anti-alias) `view` onto the screen in `finish_with`. + pub fn bind(&self, device: &wgpu::Device, view: &wgpu::TextureView) -> wgpu::BindGroup { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Horizon post"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&self.sampler), + }, + ], + }) + } /// Draw the scaled world onto `screen`. pub fn finish(&self, encoder: &mut wgpu::CommandEncoder, screen: &wgpu::TextureView) { let Some(target) = &self.target else { return }; + self.finish_with(encoder, screen, &target.group); + } + /// Draw what `group` binds (`bind`) onto `screen`. + pub fn finish_with( + &self, + encoder: &mut wgpu::CommandEncoder, + screen: &wgpu::TextureView, + group: &wgpu::BindGroup, + ) { let attachments = [Some(wgpu::RenderPassColorAttachment { view: screen, resolve_target: None, @@ -187,7 +206,7 @@ impl Post { } else { &self.copy }); - pass.set_bind_group(0, &target.group, &[]); + pass.set_bind_group(0, group, &[]); pass.draw(0..3, 0..1); } } diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index 5ef24247e..3a74750a8 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -140,6 +140,9 @@ pub struct Graphics { /// 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 { @@ -160,6 +163,7 @@ impl Default for Graphics { fxaa: false, advanced: false, battery: false, + shader_pack: String::new(), } } } @@ -207,6 +211,7 @@ impl Graphics { "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, @@ -221,7 +226,7 @@ impl Graphics { } pub fn serialize(&self) -> String { format!( - "preset:{}\ncaveCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\n", + "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, @@ -245,6 +250,7 @@ impl Graphics { bool_text(self.fxaa), if self.advanced { "advanced" } else { "simple" }, bool_text(self.battery), + self.shader_pack, ) } pub fn save(&self, dir: &Path) { @@ -329,6 +335,7 @@ mod tests { fxaa: true, advanced: true, battery: true, + shader_pack: "horizon-sample".into(), }; assert_eq!(Graphics::parse(&g.serialize()), g); assert_eq!(Graphics::parse(""), Graphics::default());