From eafe97da7468315d1bd159ccee038a8cee72e62d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 14:02:12 +0200 Subject: [PATCH] Shader packs: keep what Iris does, drop what doesn't work, apply settings on Done Review fixes for #1414 (contribution gate): - Java packs no longer get Horizon's shadow map: it was mirrored in y and reversed in depth against the GL conventions the packs sample with, had no distortion and only the camera's sections, so BSL drew no shadows while the pass cost 0.65 ms (MakeUp, M4 Pro). shadowtex* stays a far depth, as on main; the packs' own shadow programs are #1326. - Invented uniforms removed (centerDepthSmooth fixed at 0.5, ambientOcclusionLevel and shadowMapResolution as uniforms, constant temp/rainfall/biome/held items); an unknown uniform stays zero as before. wetness keeps its Iris smoothing. Unused directives removed. - texture.. is scoped to Iris's stages (final reads the composite ones) instead of overriding the sampler in every pass; texture.noise replaces noisetex. One noise generator and one RGBA upload for both pack kinds. - The G-buffer pass, the opaque-depth copy and the shadow pass run only for a pack that reads them (naga's per-entry-point binding use, not a text search): every pack paid all three before. - Api 2's prelude additions go in their own file after api 1's, so api 1 packs keep the names they declare (aces_tonemap, material_at...). - Stage kinds shadow, gbuffer, deferred and final ran as composite: only composite is accepted; api 2 adds formats (validated), profiles, option descriptions and a noise texture. - Shader Pack Settings applies once when the page closes, as Iris's Done (each click or slider step rebuilt the pack: 2.7 s per click, 12.7 s for one drag with BSL). Labels follow Iris (.lang, else the name). A pack whose options can't be read isn't read again every frame. - Saved option values an option doesn't list are ignored, as OptiFine's ShaderOption.setValue (a stale file broke BSL's compile). - Import: the blocking file dialog (osascript/zenity/kdialog/PowerShell on the event loop) is gone; a pack dropped on the Shader Packs page is copied and picked, as Iris's onFilesDrop. Drops elsewhere do nothing, an existing pack isn't overwritten, links aren't followed. - Docs and the example say what the code does (SSAO, not GTAO). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 2 +- crates/horizon-client/src/game/options.rs | 3 - crates/horizon-client/src/game/packs.rs | 54 ---- .../horizon-client/src/game/shader_packs.rs | 29 +- .../horizon-client/src/game/startup_menu.rs | 29 +- crates/horizon-client/src/gfx.rs | 28 +- crates/horizon-client/src/gfx/java_stages.rs | 190 +++--------- crates/horizon-client/src/gfx/pack_stages.rs | 111 ++++--- crates/horizon-client/src/gfx/world_post.rs | 37 +-- crates/horizon-client/src/java_pack.rs | 67 +++-- crates/horizon-client/src/options_ui.rs | 221 +++++++++----- crates/horizon-client/src/shader_pack.rs | 281 ++++++++++-------- .../src/shader_pack_prelude.wgsl | 108 +------ .../src/shader_pack_prelude_api2.wgsl | 108 +++++++ crates/horizon-shaderpack/src/options.rs | 18 +- crates/horizon-shaderpack/src/pipeline.rs | 112 +------ crates/horizon-shaderpack/src/translate.rs | 19 +- docs/shader-packs.md | 74 ++++- examples/shaderpacks/horizon-ultra/pack.toml | 15 +- .../horizon-ultra/shaders/bloom_godrays.wgsl | 4 +- .../shaders/deferred_lighting.wgsl | 6 +- 21 files changed, 732 insertions(+), 784 deletions(-) create mode 100644 crates/horizon-client/src/shader_pack_prelude_api2.wgsl diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c763bd58a..ae7b182b4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10728,7 +10728,7 @@ impl ApplicationHandler for Game<'_> { self.pending_save.as_mut().unwrap().quit = true; } WindowEvent::DroppedFile(path) => { - self.import_shader_pack_path(&path); + self.drop_shader_pack(&path); } WindowEvent::Focused(focused) => { self.focused = focused; diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index c715b4d1a..d422f0218 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -243,9 +243,6 @@ impl Game<'_> { super::packs::open_folder(&dir); } Event::Credits => self.open_win_screen(false, super::win::Finish::Options), - Event::ImportShaderPack => { - self.import_shader_pack_dialog(); - } Event::ReloadShaderPack => { self.load_shader_pack(); } diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 13de550e1..94e61d948 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -34,60 +34,6 @@ pub fn open_folder(dir: &Path) { log::warn!("Horizon: could not open {}: {e}", dir.display()); } } -/// Open a native file dialog to pick a shader pack `.zip` or folder, falling -/// back to opening `dir` in the system file manager when no dialog helper is present. -pub fn pick_shader_pack(dir: &Path) -> Option { - let _ = std::fs::create_dir_all(dir); - let output = if cfg!(target_os = "windows") { - std::process::Command::new("powershell") - .args([ - "-NoProfile", - "-Command", - "Add-Type -AssemblyName System.Windows.Forms; $f = New-Object System.Windows.Forms.OpenFileDialog; $f.Filter = 'Shader Packs (*.zip;pack.toml)|*.zip;pack.toml|All Files (*.*)|*.*'; if ($f.ShowDialog() -eq 'OK') { Write-Output $f.FileName }", - ]) - .output() - .ok() - } else if cfg!(target_os = "macos") { - std::process::Command::new("osascript") - .args([ - "-e", - "POSIX path of (choose file with prompt \"Select Shader Pack (.zip)\")", - ]) - .output() - .ok() - } else { - std::process::Command::new("zenity") - .args([ - "--file-selection", - "--title=Import Shader Pack (.zip)", - "--file-filter=Shader Packs (*.zip) | *.zip", - ]) - .output() - .ok() - .filter(|o| o.status.success()) - .or_else(|| { - std::process::Command::new("kdialog") - .args(["--getopenfilename", ".", "*.zip|Shader Packs (*.zip)"]) - .output() - .ok() - }) - }; - if let Some(out) = output - && out.status.success() - { - let raw = String::from_utf8_lossy(&out.stdout).trim().to_owned(); - if !raw.is_empty() { - let p = PathBuf::from(raw); - if p.file_name().is_some_and(|n| n == "pack.toml") { - return p.parent().map(Path::to_path_buf); - } - return Some(p); - } - return None; - } - open_folder(dir); - None -} /// The resource root to load from, given the vanilla root and the selection. pub fn startup_root(vanilla: &Path, selected: &[String]) -> std::io::Result { let all = packs::discover(vanilla, &packs_dir()); diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs index d7ec206ec..a501543bd 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -101,30 +101,19 @@ impl Game<'_> { self.load_shader_pack(); } } - /// Import a shader pack from `source` into `shaderpacks/`, activate it, and reload. - pub(super) fn import_shader_pack_path(&mut self, source: &std::path::Path) { - let dest = dir(); - match shader_pack::import_pack(source, &dest) { - Ok(id) => { - self.ui.options.shader_packs = Default::default(); - self.ui.options.shader_packs.poll(dest); - self.settings.horizon.shader_pack = id; - self.ui.options.shader_pack_config = None; - self.ui.options.sync_shader_pack_config(&self.settings); + /// A file dropped on the window: a shader pack while the Shader Packs + /// page shows (`OptionsUi::drop_shader_pack`). + pub(super) fn drop_shader_pack(&mut self, path: &std::path::Path) { + match self.ui.options.drop_shader_pack(&mut self.settings, path) { + Some(Ok(())) => { self.settings.save(&Self::options_path()); self.load_shader_pack(); } - Err(e) => { - log::warn!("Horizon: shader pack import failed: {e}"); - self.system_message(Text::literal(format!("Shader pack import: {e}"))); + Some(Err(e)) => { + log::warn!("Horizon: shader pack {}: {e}", path.display()); + self.system_message(Text::literal(format!("Shader pack: {e}"))); } - } - } - /// Open the system file picker (or `shaderpacks/` folder) to import a shader pack. - pub(super) fn import_shader_pack_dialog(&mut self) { - let dest = dir(); - if let Some(chosen) = super::packs::pick_shader_pack(&dest) { - self.import_shader_pack_path(&chosen); + None => {} } } fn shader_pack_error(&mut self, id: &str, error: &str) { diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index e01dd6dc6..ebf062a83 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -387,19 +387,6 @@ impl Loading { self.menu.win = Some((screen, Instant::now())); } } - Event::ImportShaderPack => { - let dir = horizon_client::shader_pack::folder(); - if let Some(chosen) = packs::pick_shader_pack(&dir) - && let Ok(id) = horizon_client::shader_pack::import_pack(&chosen, &dir) - { - self.menu.options.shader_packs = Default::default(); - self.menu.options.shader_packs.poll(dir); - self.settings.horizon.shader_pack = id; - self.menu.options.shader_pack_config = None; - self.menu.options.sync_shader_pack_config(&self.settings); - self.save_menu_settings(); - } - } Event::ReloadShaderPack => { self.save_menu_settings(); } @@ -469,14 +456,14 @@ impl Loading { self.apply_menu_settings(); } WindowEvent::DroppedFile(path) => { - let dir = horizon_client::shader_pack::folder(); - if let Ok(id) = horizon_client::shader_pack::import_pack(&path, &dir) { - self.menu.options.shader_packs = Default::default(); - self.menu.options.shader_packs.poll(dir); - self.settings.horizon.shader_pack = id; - self.menu.options.shader_pack_config = None; - self.menu.options.sync_shader_pack_config(&self.settings); - self.save_menu_settings(); + match self + .menu + .options + .drop_shader_pack(&mut self.settings, &path) + { + Some(Ok(())) => self.save_menu_settings(), + Some(Err(e)) => log::warn!("Horizon: shader pack {}: {e}", path.display()), + None => {} } } WindowEvent::RedrawRequested => self.draw(), diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 38a3e0521..255f4dd0a 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -3679,14 +3679,16 @@ impl Renderer { } // The world's targets: the screen, or the scaled target of `post`. let pack = self.pack.is_some() && !frame.title; - let shadow_cfg = if pack { - self.pack.as_ref().and_then(|p| match p { - Pack::Horizon(s) if s.needs_shadow => Some((s.shadow_res, s.shadow_dist)), - Pack::Java(s) if s.needs_shadow() => Some(s.shadow_config(frame.shader.dimension)), - _ => None, - }) - } else { - None + // What the pack reads beyond the world's colour and depth: each costs + // a pass (the shadow map, the G-buffer) or a copy (the opaque depth). + let (shadow_cfg, gbuffer, opaque_depth) = match self.pack.as_ref().filter(|_| pack) { + Some(Pack::Horizon(s)) => ( + s.needs_shadow.then_some((s.shadow_res, s.shadow_dist)), + s.needs_gbuffer, + s.needs_opaque_depth, + ), + Some(Pack::Java(s)) => (None, false, s.reads_opaque_depth), + None => (None, false, false), }; if let Some((shadow_res, shadow_dist)) = shadow_cfg { self.world_post @@ -3944,7 +3946,7 @@ impl Renderer { pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..)); pass.draw(0..4, debug_depth..debug_depth + debug_top); } - if pack { + if opaque_depth { drop(pass); self.world_post.capture_opaque_depth(&mut encoder); let attachments = [Some(wgpu::RenderPassColorAttachment { @@ -4042,7 +4044,7 @@ impl Renderer { ); } } - if pack && scaled.is_some() { + if gbuffer && scaled.is_some() { self.world_post.build_gbuffer( &self.queue, &mut encoder, @@ -4617,7 +4619,11 @@ mod tests { ); assert!(files.len() >= 10, "{files:?}"); for path in files { - let text = std::fs::read_to_string(&path).unwrap(); + let mut text = std::fs::read_to_string(&path).unwrap(); + // Api 2's prelude follows api 1's (`shader_pack::ShaderPack::load`). + if path.ends_with("shader_pack_prelude_api2.wgsl") { + text = format!("{}\n{text}", crate::shader_pack::PRELUDE); + } // entity.wgsl comes after the overlay's constants (entity_shader). let module = naga::front::wgsl::parse_str(&text) .or_else(|_| { diff --git a/crates/horizon-client/src/gfx/java_stages.rs b/crates/horizon-client/src/gfx/java_stages.rs index 8091b0703..f86055919 100644 --- a/crates/horizon-client/src/gfx/java_stages.rs +++ b/crates/horizon-client/src/gfx/java_stages.rs @@ -1,16 +1,17 @@ //! A Java (OptiFine/Iris) shader pack on the GPU (docs/shader-packs.md): //! Iris's colour targets (`colortex0..`, each with a main and an alternate -//! side), pre-translucent depth (`depthtex1`/`depthtex2`), directional -//! shadow map (`shadowtex0`/`shadowtex1`) and the pack's `begin`, `prepare`, -//! `deferred`, `composite` and `final` programs as full-screen passes over -//! them, as Iris's `CompositeRenderer` runs them. Horizon's world enters -//! `colortex0` and `depthtex0..2` after `prepare`, where Iris's gbuffers -//! programs would have drawn, and the last picture goes to `world_post`. The +//! side) and the pack's `begin`, `prepare`, `deferred`, `composite` and +//! `final` programs as full-screen passes over them, as Iris's +//! `CompositeRenderer` runs them. Horizon's world enters `colortex0` and +//! `depthtex0` after `prepare`, where Iris's gbuffers programs would have +//! drawn (`depthtex1`/`depthtex2`: its depth before translucent geometry), +//! and the last picture goes to `world_post`. The //! targets keep GL's layout (row 0 at the bottom, which the translated vertex //! programs produce), so the world is flipped going in and the picture coming //! out. -use super::pack_stages::FrameUniform; -use crate::java_pack::{JavaFolder, JavaPasses}; +use super::pack_stages::{FrameUniform, noise, rgba_view}; +use crate::java_pack::{JavaFolder, JavaPasses, NOISE_KEY, texture_key}; +use crate::shader_pack::Rgba; use glam::{Mat3, Mat4, Vec3, Vec4}; use horizon_shaderpack::pipeline::TargetSettings; use horizon_shaderpack::pipeline::{Directives, Program, target_index}; @@ -30,8 +31,6 @@ pub struct JavaFrame { pub moon_angle: f32, } -/// Iris's `noisetex` size (`noiseTextureResolution`'s default). -const NOISE_SIZE: u32 = 256; /// The vertex buffers a pass may read (wgpu's default limit). const MAX_ATTRIBUTES: usize = 8; @@ -173,7 +172,8 @@ enum Source { /// `depthtex1` / `depthtex2`: the opaque world's depth (before translucent water). OpaqueDepth, Noise, - /// `shadowtex*`: directional sun/moon shadow map depth (or far depth for DH/Voxy). + /// `shadowtex*`: no shadow map yet, so a far depth (nothing in shadow); + /// also Distant Horizons' and Voxy's depth, as without those mods. Shadow, /// Anything else (`shadowcolor*`, custom textures): white or black. Blank(bool), @@ -267,11 +267,13 @@ struct Folder { passes: Vec, final_pass: Option, directives: Directives, - shadow_enabled: bool, } pub struct JavaStages { pub id: String, + /// A pass samples `depthtex1`/`depthtex2`: the world's depth is kept + /// before translucent geometry draws. + pub reads_opaque_depth: bool, format: wgpu::TextureFormat, common: Common, folders: Vec, @@ -285,25 +287,12 @@ pub struct JavaStages { uniform_state: UniformState, /// `eyeBrightnessSmooth`, block then sky. eye_smooth: [SmoothFloat; 2], - /// `wetness`, smoothed with `wetnessHalflife` / `drynessHalflife`. + /// `wetness`: `rainStrength` smoothed with `wetnessHalflife` going up + /// and `drynessHalflife` going down. wetness_smooth: SmoothFloat, - /// `centerDepthSmooth`, smoothed with `centerDepthHalflife`. - center_depth_smooth: SmoothFloat, } impl JavaStages { - /// Whether any dimension folder in this pack reads directional shadow maps. - pub fn needs_shadow(&self) -> bool { - self.folders.iter().any(|f| f.shadow_enabled) - } - - /// Shadow map resolution and distance for `dimension`. - pub fn shadow_config(&self, dimension: i8) -> (u32, f32) { - let idx = self.folder_for[(dimension.clamp(-1, 1) + 1) as usize].unwrap_or(0); - let d = &self.folders[idx].directives; - (d.shadow_map_resolution, d.shadow_distance) - } - /// The pipelines of a loaded Java pack, or wgpu's error. pub fn new( device: &wgpu::Device, @@ -342,15 +331,20 @@ impl JavaStages { passes, final_pass, directives: plan.directives, - shadow_enabled: plan.shadow_enabled, }) }) .collect::, _>>()?; if let Some(error) = pollster::block_on(scope.pop()) { return Err(error.to_string()); } + let reads_opaque_depth = folders + .iter() + .flat_map(|f| f.passes.iter().chain(&f.final_pass)) + .flat_map(|p| &p.samplers) + .any(|s| s.source == Source::OpaqueDepth); Ok(Self { id: id.to_owned(), + reads_opaque_depth, format, common, folders, @@ -364,7 +358,6 @@ impl JavaStages { uniform_state: UniformState::default(), eye_smooth: [SmoothFloat::default(); 2], wetness_smooth: SmoothFloat::default(), - center_depth_smooth: SmoothFloat::default(), }) } @@ -405,10 +398,6 @@ impl JavaStages { self.previous, ); inputs.set_world(&world, directives.sun_path_rotation); - inputs.shadow_view = post.shadow_view; - inputs.shadow_projection = post.gl_shadow_projection(); - inputs.ambient_occlusion_level = directives.ambient_occlusion_level; - inputs.shadow_map_resolution = directives.shadow_map_resolution as f32; let half_life = directives.eye_brightness_half_life; for (i, smooth) in self.eye_smooth.iter_mut().enumerate() { inputs.eye_smooth[i] = smooth.update(inputs.eye[i], half_life, half_life, frame_time); @@ -419,12 +408,6 @@ impl JavaStages { directives.dryness_half_life, frame_time, ); - inputs.center_depth_smooth = self.center_depth_smooth.update( - 0.5, - directives.center_depth_half_life, - directives.center_depth_half_life, - frame_time, - ); self.uniforms .update(&mut self.uniform_state, frame_time, &|name| { inputs.builtin(name) @@ -599,7 +582,6 @@ impl JavaStages { &targets, &depth, &opaque_depth, - post, &self.common, &mut blank, ) @@ -780,11 +762,8 @@ fn blit_pipeline( } impl Common { - fn new( - device: &wgpu::Device, - queue: &wgpu::Queue, - custom_map: &BTreeMap)>, - ) -> Self { + /// `custom` holds the pack's `texture.*` images (`JavaPasses::custom_textures`). + fn new(device: &wgpu::Device, queue: &wgpu::Queue, custom: &BTreeMap) -> Self { let sampler = |filter, address, compare| { device.create_sampler(&wgpu::SamplerDescriptor { label: Some("Java shader pack"), @@ -798,68 +777,15 @@ impl Common { }) }; use wgpu::{AddressMode::*, FilterMode::*}; - // Iris's noise: random RGB, opaque. - let mut seed = 0x2545_f491_u32; - let noise_bytes: Vec = (0..NOISE_SIZE * NOISE_SIZE * 4) - .map(|i| { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - if i % 4 == 3 { 255 } else { (seed >> 24) as u8 } - }) + let noise = match custom.get(NOISE_KEY) { + Some(image) => rgba_view(device, queue, "noisetex", image), + None => rgba_view(device, queue, "noisetex", &noise()), + }; + let custom_textures = custom + .iter() + .filter(|(key, _)| *key != NOISE_KEY) + .map(|(key, image)| (key.clone(), rgba_view(device, queue, key, image))) .collect(); - let noise = device.create_texture(&wgpu::TextureDescriptor { - label: Some("noisetex"), - size: wgpu::Extent3d { - width: NOISE_SIZE, - height: NOISE_SIZE, - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Rgba8Unorm, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - queue.write_texture( - noise.as_image_copy(), - &noise_bytes, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(NOISE_SIZE * 4), - rows_per_image: None, - }, - noise.size(), - ); - let mut custom_textures = BTreeMap::new(); - for (name, (w, h, bytes)) in custom_map { - let tex = device.create_texture(&wgpu::TextureDescriptor { - label: Some(name), - size: wgpu::Extent3d { - width: *w, - height: *h, - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Rgba8Unorm, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - queue.write_texture( - tex.as_image_copy(), - bytes, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(*w * 4), - rows_per_image: None, - }, - tex.size(), - ); - custom_textures.insert(name.clone(), tex.create_view(&Default::default())); - } // The full-screen triangle (0, 0), (2, 0), (0, 2): the pack's // projection maps 0..1 to the screen. Texture coordinates are the // position; colours white; normals up. @@ -899,7 +825,7 @@ impl Common { nearest: sampler(Nearest, ClampToEdge, None), repeat: sampler(Linear, Repeat, None), compare: sampler(Linear, ClampToEdge, Some(wgpu::CompareFunction::LessEqual)), - noise: noise.create_view(&Default::default()), + noise, custom_textures, vertices, world_layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { @@ -1239,21 +1165,22 @@ impl PassGpu { targets: &BTreeMap, depth: &wgpu::TextureView, opaque_depth: &wgpu::TextureView, - post: &super::world_post::Post, common: &Common, blank: &mut Vec, ) -> wgpu::BindGroup { let mut views = Vec::new(); for s in &self.samplers { - let view = if let Some(custom) = common - .custom_textures - .get(&s.name) - .filter(|_| !s.compare && s.dimension == wgpu::TextureViewDimension::D2) - { + let custom = (!s.compare && s.dimension == wgpu::TextureViewDimension::D2) + .then(|| { + common + .custom_textures + .get(&texture_key(&self.program, &s.name)) + }) + .flatten(); + let view = if let Some(custom) = custom { custom.clone() } else { match (s.compare, s.source) { - (true, Source::Shadow) if post.shadow_active => post.shadow_depth().clone(), (true, _) => blank_view(device, queue, blank, s, BlankKind::FarDepth), (false, Source::Target(i)) if s.dimension == wgpu::TextureViewDimension::D2 => { match targets.get(&i) { @@ -1612,8 +1539,6 @@ struct Inputs { view: Mat4, /// GL's: near at -1, far at 1. projection: Mat4, - shadow_view: Mat4, - shadow_projection: Mat4, camera: Vec3, previous: (Mat4, Mat4, Vec3), size: [f32; 2], @@ -1624,10 +1549,8 @@ struct Inputs { /// `eyeBrightness` and `eyeBrightnessSmooth`: block, sky light × 16. eye: [f32; 2], eye_smooth: [f32; 2], + /// `wetness` (`JavaStages::wetness_smooth`). wetness: f32, - center_depth_smooth: f32, - ambient_occlusion_level: f32, - shadow_map_resolution: f32, /// `CelestialUniforms`, in view space. sun_position: Vec3, moon_position: Vec3, @@ -1676,8 +1599,6 @@ impl Inputs { let mut out = Self { view, projection, - shadow_view: Mat4::IDENTITY, - shadow_projection: Mat4::IDENTITY, camera, previous: previous.unwrap_or((view, projection, camera)), size: size.map(|v| v as f32), @@ -1688,9 +1609,6 @@ impl Inputs { eye: [0.0; 2], eye_smooth: [0.0; 2], wetness: frame.weather[0], - center_depth_smooth: 0.5, - ambient_occlusion_level: 1.0, - shadow_map_resolution: 2048.0, sun_position: Vec3::ZERO, moon_position: Vec3::ZERO, up_position: Vec3::ZERO, @@ -1790,35 +1708,21 @@ impl Inputs { "skyColor" => f.sky_color[..3].to_vec(), "isEyeInWater" => vec![f.camera_state[0]], "nightVision" => vec![f.camera_state[1]], - "darknessFactor" | "darknessLightFactor" => vec![f.camera_state[2]], - "blindness" => vec![f.camera_state[3]], + "darknessFactor" => vec![f.camera_state[2]], "screenBrightness" => vec![1.0], - "centerDepthSmooth" => vec![self.center_depth_smooth], - "ambientOcclusionLevel" => vec![self.ambient_occlusion_level], - "shadowMapResolution" => vec![self.shadow_map_resolution], "eyeBrightness" => self.eye.to_vec(), // An ivec2: the smoothed value truncated. "eyeBrightnessSmooth" => self.eye_smooth.map(f32::trunc).to_vec(), "hasSkylight" => vec![f.dimension[1]], - "heldItemId" | "heldItemId2" | "heldBlockLightValue" | "heldBlockLightValue2" => { - vec![0.0] - } - "biome" | "biome_category" => vec![0.0], - "biome_precipitation" => vec![if f.weather[0] > 0.01 { 1.0 } else { 0.0 }], - "temp" => vec![0.8], - "rainfall" => vec![0.4], - "alphaTestRef" => vec![0.1], - "renderStage" => vec![0.0], - "playerMood" | "currentColorSpace" => vec![0.0], "iris_ModelViewMatrix" | "iris_ModelViewMatrixInverse" => mat(Mat4::IDENTITY), "iris_ProjectionMatrix" | "iris_ModelViewProjectionMatrix" => mat(screen), "iris_ProjectionMatrixInverse" => mat(screen.inverse()), "iris_TextureMatrix" => (0..8).flat_map(|_| mat(Mat4::IDENTITY)).collect(), "iris_NormalMatrix" => Mat3::IDENTITY.to_cols_array().to_vec(), - "shadowModelView" => mat(self.shadow_view), - "shadowModelViewInverse" => mat(self.shadow_view.inverse()), - "shadowProjection" => mat(self.shadow_projection), - "shadowProjectionInverse" => mat(self.shadow_projection.inverse()), + "shadowModelView" + | "shadowModelViewInverse" + | "shadowProjection" + | "shadowProjectionInverse" => mat(Mat4::IDENTITY), _ => return None, }) } diff --git a/crates/horizon-client/src/gfx/pack_stages.rs b/crates/horizon-client/src/gfx/pack_stages.rs index 08a6b9aea..f80a64ce1 100644 --- a/crates/horizon-client/src/gfx/pack_stages.rs +++ b/crates/horizon-client/src/gfx/pack_stages.rs @@ -5,7 +5,7 @@ //! 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, StageKind, VERTEX_ENTRY}; +use crate::shader_pack::{Rgba, ShaderPack, VERTEX_ENTRY}; use horizon_shaderpack::uniforms::SmoothFloat; /// The `Frame` uniform of the prelude (`shader_pack_prelude.wgsl`). @@ -45,7 +45,59 @@ pub struct FrameExtUniform { pub environment: [f32; 4], } -const NOISE_SIZE: u32 = 256; +/// Iris's `noisetex` without a `texture.noise`: 256² random RGB, opaque. +/// Horizon packs get the same one unless `[textures] noise` replaces it. +pub(super) fn noise() -> Rgba { + const SIZE: u32 = 256; + let mut seed = 0x2545_f491_u32; + let pixels = (0..SIZE * SIZE * 4) + .map(|i| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + if i % 4 == 3 { 255 } else { (seed >> 24) as u8 } + }) + .collect(); + Rgba { + width: SIZE, + height: SIZE, + pixels, + } +} + +/// `image` as a sampled RGBA8 texture. +pub(super) fn rgba_view( + device: &wgpu::Device, + queue: &wgpu::Queue, + label: &str, + image: &Rgba, +) -> wgpu::TextureView { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { + width: image.width, + height: image.height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + queue.write_texture( + texture.as_image_copy(), + &image.pixels, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(image.width * 4), + rows_per_image: None, + }, + texture.size(), + ); + texture.create_view(&Default::default()) +} struct Pass { pipeline: wgpu::RenderPipeline, @@ -64,6 +116,10 @@ struct Target { pub struct PackStages { pub id: String, pub needs_shadow: bool, + /// The stages read the G-buffer (`build_gbuffer`) or the depth before + /// translucent geometry (`capture_opaque_depth`). + pub needs_gbuffer: bool, + pub needs_opaque_depth: bool, pub shadow_res: u32, pub shadow_dist: f32, layout: wgpu::BindGroupLayout, @@ -162,7 +218,7 @@ impl PackStages { .iter() .enumerate() .map(|(idx, stage)| { - let is_last = idx + 1 == stage_count || stage.kind == StageKind::Final; + let is_last = idx + 1 == stage_count; let target_format = if is_last { format } else { @@ -240,49 +296,16 @@ impl PackStages { ..Default::default() }) }; - let (nw, nh, noise_bytes) = match &pack.custom_noise { - Some((w, h, bytes)) => (*w, *h, bytes.clone()), - None => { - let mut seed = 0x2545_f491_u32; - let bytes: Vec = (0..NOISE_SIZE * NOISE_SIZE * 4) - .map(|i| { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - if i % 4 == 3 { 255 } else { (seed >> 24) as u8 } - }) - .collect(); - (NOISE_SIZE, NOISE_SIZE, bytes) - } + let noise_view = match &pack.custom_noise { + Some(image) => rgba_view(device, queue, "Shader pack noise", image), + None => rgba_view(device, queue, "Shader pack noise", &noise()), }; - let noise_tex = device.create_texture(&wgpu::TextureDescriptor { - label: Some("Shader pack noise"), - size: wgpu::Extent3d { - width: nw, - height: nh, - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::Rgba8Unorm, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - queue.write_texture( - noise_tex.as_image_copy(), - &noise_bytes, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(nw * 4), - rows_per_image: None, - }, - noise_tex.size(), - ); - let (shadow_res, shadow_dist, _) = pack.shadow_config(0); + let (shadow_res, shadow_dist) = pack.shadow_config(); Ok(Self { id: pack.id.clone(), needs_shadow: pack.needs_shadow(), + needs_gbuffer: pack.needs_gbuffer(), + needs_opaque_depth: pack.needs_opaque_depth(), shadow_res, shadow_dist, layout, @@ -302,7 +325,7 @@ impl PackStages { wgpu::AddressMode::ClampToEdge, Some(wgpu::CompareFunction::GreaterEqual), ), - noise_view: noise_tex.create_view(&Default::default()), + noise_view, passes, targets: Vec::new(), output: None, @@ -462,7 +485,7 @@ impl PackStages { f32::from(eye_light[0]) * 16.0, f32::from(eye_light[1]) * 16.0, wet, - uniform.view_params[2] * 0.5, + 0.0, ], }; uniform.time[0] = self.started.elapsed().as_secs_f32(); diff --git a/crates/horizon-client/src/gfx/world_post.rs b/crates/horizon-client/src/gfx/world_post.rs index 69d95aae6..f592e8a1f 100644 --- a/crates/horizon-client/src/gfx/world_post.rs +++ b/crates/horizon-client/src/gfx/world_post.rs @@ -1,19 +1,19 @@ //! Resolution scale, FXAA, and shader-pack G-buffer/shadow targets (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. When a shader pack is active, `Post` also maintains: -//! - `opaque_depth` (`depthtex1`/`depthtex2`): depth captured before -//! translucent terrain (water, stained glass, ice) renders; -//! - `normal` (`colortex1`/`scene_normal`) and `material` -//! (`colortex2`/`scene_material`): G-buffer surface normals and material -//! properties reconstructed from depth and scene colour; -//! - `shadow_depth` (`shadowtex0`/`shadowtex1`): the directional sun/moon -//! shadow map and its light-space `shadow_view` and `shadow_proj` matrices. +//! hand and HUD. For a shader pack that reads them, `Post` also keeps: +//! - `opaque_depth`: the depth before translucent terrain (water, stained +//! glass, ice) draws, a Java pack's `depthtex1`/`depthtex2`; +//! - `normal` and `material`, an api 2 pack's `scene_normal` and +//! `scene_material`: surface normals and material properties +//! reconstructed from depth and scene colour; +//! - `shadow_depth`, an api 2 pack's: the sun/moon shadow map and its +//! light-space `shadow_view` and `shadow_proj` matrices. //! //! With none of them on, the world renders straight to the screen as before. use super::pack_stages::FrameUniform; -use glam::{Mat4, Vec3, Vec4}; +use glam::{Mat4, Vec3}; const GBUFFER_WGSL: &str = r#" struct GbufferParams { @@ -632,45 +632,34 @@ impl Post { self.target.as_ref().map(|t| t.size) } - /// Pre-translucent depth view (`depthtex1`/`depthtex2` / `opaque_depth`). + /// The depth before translucent geometry (`capture_opaque_depth`). pub fn opaque_depth(&self) -> &wgpu::TextureView { self.target .as_ref() .map_or(&self.fallback_shadow, |t| &t.opaque_depth) } - /// Reconstructed world-space normal G-buffer view (`colortex1` / `scene_normal`). + /// Reconstructed world-space normals (`scene_normal`). pub fn normal(&self) -> &wgpu::TextureView { self.target .as_ref() .map_or(&self.fallback_color, |t| &t.normal) } - /// Reconstructed material/lightmap G-buffer view (`colortex2` / `scene_material`). + /// Reconstructed material and light (`scene_material`). pub fn material(&self) -> &wgpu::TextureView { self.target .as_ref() .map_or(&self.fallback_color, |t| &t.material) } - /// Directional sun/moon shadow map view (`shadowtex0`/`shadowtex1` / `shadow_depth`). + /// The sun/moon shadow map (`shadow_depth` of api 2 packs). pub fn shadow_depth(&self) -> &wgpu::TextureView { self.shadow .as_ref() .map_or(&self.fallback_shadow, |s| &s.depth) } - /// OpenGL-convention (-1..1 Z) shadow projection for Java/Iris shader packs. - pub fn gl_shadow_projection(&self) -> Mat4 { - let to_gl = Mat4::from_cols( - Vec4::X, - Vec4::Y, - Vec4::new(0.0, 0.0, -2.0, 0.0), - Vec4::new(0.0, 0.0, 1.0, 1.0), - ); - to_gl * self.shadow_proj - } - /// 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 { diff --git a/crates/horizon-client/src/java_pack.rs b/crates/horizon-client/src/java_pack.rs index 5a37aa223..5e592d1b6 100644 --- a/crates/horizon-client/src/java_pack.rs +++ b/crates/horizon-client/src/java_pack.rs @@ -1,9 +1,9 @@ //! Java (OptiFine/Iris) shader packs in `shaderpacks/` (docs/shader-packs.md): //! a folder holding `shaders/`, or a `.zip`. `horizon-shaderpack` translates //! their full-screen programs (`begin`, `prepare`, `deferred`, `composite`, -//! `final`) to WGSL, and `gfx/java_stages.rs` runs them over Horizon's world, -//! G-buffers, pre-translucent depth (`depthtex1`) and directional shadow map -//! (`shadowtex0`/`shadowtex1`) as Iris runs them over its own. +//! `final`) to WGSL, and `gfx/java_stages.rs` runs them over Horizon's world +//! as Iris runs them over its own. Geometry programs (`gbuffers_*`, +//! `shadow`) don't run yet: the world is drawn by Horizon. use horizon_shaderpack::{ JavaPack, pipeline::{Directives, Program, TargetSettings}, @@ -30,10 +30,24 @@ pub struct JavaFolder { pub final_pass: Option, /// The targets whose alternate side holds the frame's last write. pub flipped_at_end: BTreeSet, - /// `sunPathRotation`, `eyeBrightnessHalflife`, shadow and wetness directives. + /// `sunPathRotation`, `eyeBrightnessHalflife`, `wetnessHalflife` and + /// `drynessHalflife`. pub directives: Directives, - /// Whether this dimension's passes read directional shadow maps. - pub shadow_enabled: bool, +} + +/// The key of `texture.noise` (`noisetex`) in [`JavaPasses::custom_textures`]. +pub const NOISE_KEY: &str = "noise"; + +/// The key of `texture..` in [`JavaPasses::custom_textures`] +/// for a pass of `program` (`world0/composite2`): Iris's texture stages, where +/// `final` reads the `composite` ones. +pub fn texture_key(program: &str, sampler: &str) -> String { + let name = program.rsplit('/').next().unwrap_or(program); + let stage = match name.trim_end_matches(|c: char| c.is_ascii_digit()) { + "final" => "composite", + stage => stage, + }; + format!("{stage}.{sampler}") } /// A loaded Java pack. @@ -43,8 +57,9 @@ pub struct JavaPasses { pub uniforms: CustomUniforms, /// What the pack keeps of the vanilla sky (`clouds`, `sun`, `moon`). pub sky: SkyDirectives, - /// Decoded RGBA8 custom textures (`sampler_name` → `(width, height, rgba)`). - pub custom_textures: BTreeMap)>, + /// `texture..` and `texture.noise` images, by + /// `"."` and [`NOISE_KEY`]. + pub custom_textures: BTreeMap, } impl JavaPasses { @@ -135,7 +150,6 @@ pub fn load( final_pass, flipped_at_end: plan.flipped_at_end, directives: plan.directives, - shadow_enabled: plan.shadow_enabled, }); } if folders.is_empty() { @@ -143,15 +157,23 @@ pub fn load( } let mut custom_textures = BTreeMap::new(); for tex in properties.custom_textures() { - if let Some(bytes) = pack.files.read_bytes(&tex.path) { - match crate::shader_pack::decode_png_rgba(&bytes) { - Ok(decoded) => { - custom_textures.insert(tex.sampler, decoded); - } - Err(e) => { - log::warn!("Horizon: shader pack texture {}: {e}", tex.path); - } + let key = match tex.stage { + Some(stage) => format!("{stage}.{}", tex.sampler), + None if tex.sampler == NOISE_KEY => NOISE_KEY.to_owned(), + None => continue, + }; + // Only PNGs for now: resource locations and raw `.dat` textures are + // skipped and the sampler reads what it would without them. + let image = pack + .files + .read_bytes(&tex.path) + .ok_or_else(|| "not in the pack".to_owned()) + .and_then(|bytes| crate::shader_pack::decode_png(&bytes)); + match image { + Ok(image) => { + custom_textures.insert(key, image); } + Err(e) => log::warn!("Horizon: shader pack texture {}: {e}", tex.path), } } let uniforms = properties.custom_uniforms(); @@ -170,6 +192,17 @@ pub fn load( mod tests { use super::*; + #[test] + fn custom_textures_belong_to_iris_s_stages() { + assert_eq!(texture_key("world0/composite2", "gaux1"), "composite.gaux1"); + assert_eq!(texture_key("final", "colortex4"), "composite.colortex4"); + assert_eq!( + texture_key("world-1/deferred10", "noisetex"), + "deferred.noisetex" + ); + assert_eq!(texture_key("prepare", "depthtex2"), "prepare.depthtex2"); + } + #[test] fn loads_the_full_screen_passes_of_a_java_pack() { let dir = Path::new(env!("CARGO_MANIFEST_DIR")) diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 4ae78da40..1bb9953bf 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -10,6 +10,7 @@ use crate::{ keybinds::{self, CATEGORIES, KeyBinds, MAPPINGS}, lang::{self, LanguageInfo}, settings::{SOUND_SOURCES, Settings}, + shader_pack::PackConfig, text::{self, Style, Text}, ui, }; @@ -903,8 +904,6 @@ enum Act { /// Credits & Attribution's Credits button (WinScreen without the poem). Credits, CopyAgentDetails, - /// Pick and import a shader pack `.zip` or folder into `shaderpacks/`. - ImportShaderPack, ShaderPackProfile, ShaderPackSubscreen(String), ShaderPackBackScreen, @@ -968,9 +967,8 @@ pub enum Event { Credits, /// Copy how an agent connects (the AI Agent page). CopyAgentDetails, - /// Pick and import a shader pack `.zip` or folder into `shaderpacks/`. - ImportShaderPack, - /// Reload the active shader pack after its options file changed. + /// The shader pack settings page closed with changes: they are saved, + /// the pack is built again with them. ReloadShaderPack, } /// `SliderableValueSet.applyValueImmediately`: these apply 600 ms after @@ -1030,11 +1028,12 @@ pub struct OptionsUi { /// The AI Agent page's status lines (set by the game while it shows). pub agent_status: Vec, /// Loaded interactive configuration for the currently selected shader pack. - pub shader_pack_config: Option, - /// Classic shader option slider currently being dragged. + pub shader_pack_config: Option, + /// The shader pack option slider being dragged. pub(crate) dragging_shader_option: Option, - /// Horizon shader option slider currently being dragged. - pub(crate) hdragging_shader_option: Option, + /// `shader_pack_config` changed since the settings page opened: leaving + /// it saves the values and reloads the pack. + shader_pack_edited: bool, } impl Default for OptionsUi { fn default() -> Self { @@ -1068,7 +1067,7 @@ impl Default for OptionsUi { agent_status: Vec::new(), shader_pack_config: None, dragging_shader_option: None, - hdragging_shader_option: None, + shader_pack_edited: false, } } } @@ -1225,22 +1224,58 @@ impl OptionsUi { { return; } - let dir = if self.shader_packs.dir.as_os_str().is_empty() { + // A pack whose options can't be read has none, rather than being + // read again every frame. + let config = PackConfig::load(&self.shader_pack_dir(), id).unwrap_or_else(|e| { + log::warn!("Horizon: shader pack {id} options: {e}"); + PackConfig { + id: id.to_owned(), + ..Default::default() + } + }); + self.shader_pack_config = Some(config); + self.shader_pack_edited = false; + } + fn shader_pack_dir(&self) -> std::path::PathBuf { + if self.shader_packs.dir.as_os_str().is_empty() { crate::shader_pack::folder() } else { self.shader_packs.dir.clone() - }; - self.shader_pack_config = crate::shader_pack::PackConfig::load(&dir, id).ok(); + } + } + /// A file or folder dropped on the window: on the Shader Packs page (as + /// Iris's `ShaderPackScreen.onFilesDrop`), a pack copied into + /// `shaderpacks/` and picked. `None` elsewhere; the caller saves the + /// settings and loads the pack on `Some(Ok)`. + pub fn drop_shader_pack( + &mut self, + s: &mut Settings, + path: &std::path::Path, + ) -> Option> { + if self.page() != Page::ShaderPacks { + return None; + } + let dir = self.shader_pack_dir(); + Some(crate::shader_pack::import_pack(path, &dir).map(|id| { + self.shader_packs = Default::default(); + self.shader_packs.poll(dir); + s.horizon.shader_pack = id; + self.sync_shader_pack_config(s); + })) + } + /// Change the shader pack's options, applied when its page closes. + fn edit_shader_pack(&mut self, edit: impl FnOnce(&mut PackConfig)) { + if let Some(cfg) = &mut self.shader_pack_config { + edit(cfg); + self.shader_pack_edited = true; + } } /// Save the active shader pack options to `shaderpacks/.txt`. - pub(crate) fn save_shader_pack_config(&self) { - if let Some(cfg) = &self.shader_pack_config { - let dir = if self.shader_packs.dir.as_os_str().is_empty() { - crate::shader_pack::folder() - } else { - self.shader_packs.dir.clone() - }; - let _ = cfg.save(&dir); + fn save_shader_pack_config(&self) { + if let Some(cfg) = &self.shader_pack_config + && let Err(e) = cfg.save(&self.shader_pack_dir()) + { + log::warn!("Horizon: shader pack {} options: {e}", cfg.id); } } pub(crate) fn shader_pack_failed(&self, id: &str) -> bool { @@ -1658,27 +1693,10 @@ impl OptionsUi { button( 0.0, 0.0, - 150.0, + 310.0, Text::literal("Shader Pack Settings..."), Act::Push(Page::ShaderPackOptions), ), - Some(button( - 0.0, - 0.0, - 150.0, - Text::literal("Import Shader Pack..."), - Act::ImportShaderPack, - )), - )); - } else { - rows.push(Row::Buttons( - button( - 0.0, - 0.0, - 310.0, - Text::literal("Import Shader Pack..."), - Act::ImportShaderPack, - ), None, )); } @@ -2725,14 +2743,12 @@ impl OptionsUi { }) { let v = ui::slider_value(wd.x, wd.w, x); - if let Some(cfg) = &mut self.shader_pack_config - && let Some(opt) = cfg.options.get_mut(idx) - { - opt.set_slider_pos(v); - } - self.save_shader_pack_config(); + self.edit_shader_pack(|cfg| { + if let Some(opt) = cfg.options.get_mut(idx) { + opt.set_slider_pos(v); + } + }); events.push(Event::Changed); - events.push(Event::ReloadShaderPack); } return events; } @@ -2821,14 +2837,9 @@ impl OptionsUi { Act::OpenShaderPackFolder => events.push(Event::OpenShaderPackFolder), Act::Credits => events.push(Event::Credits), Act::CopyAgentDetails => events.push(Event::CopyAgentDetails), - Act::ImportShaderPack => events.push(Event::ImportShaderPack), Act::ShaderPackProfile => { - if let Some(cfg) = &mut self.shader_pack_config { - cfg.cycle_profile(right); - } - self.save_shader_pack_config(); + self.edit_shader_pack(|cfg| cfg.cycle_profile(false)); events.push(Event::Changed); - events.push(Event::ReloadShaderPack); } Act::ShaderPackSubscreen(sub) => { if let Some(cfg) = &mut self.shader_pack_config { @@ -2843,22 +2854,16 @@ impl OptionsUi { self.scroll = 0.0; } Act::ShaderPackOption(i) => { - if let Some(cfg) = &mut self.shader_pack_config - && let Some(opt) = cfg.options.get_mut(i) - { - opt.cycle(right); - } - self.save_shader_pack_config(); + self.edit_shader_pack(|cfg| { + if let Some(opt) = cfg.options.get_mut(i) { + opt.cycle(false); + } + }); events.push(Event::Changed); - events.push(Event::ReloadShaderPack); } Act::ResetShaderPackOptions => { - if let Some(cfg) = &mut self.shader_pack_config { - cfg.reset_all(); - } - self.save_shader_pack_config(); + self.edit_shader_pack(PackConfig::reset_all); events.push(Event::Changed); - events.push(Event::ReloadShaderPack); } Act::None => {} } @@ -2873,14 +2878,12 @@ impl OptionsUi { WKind::ShaderOptionSlider { index, .. } => { self.dragging_shader_option = Some(index); let v = ui::slider_value(wd.x, wd.w, x); - if let Some(cfg) = &mut self.shader_pack_config - && let Some(opt) = cfg.options.get_mut(index) - { - opt.set_slider_pos(v); - } - self.save_shader_pack_config(); + self.edit_shader_pack(|cfg| { + if let Some(opt) = cfg.options.get_mut(index) { + opt.set_slider_pos(v); + } + }); events.push(Event::Changed); - events.push(Event::ReloadShaderPack); } WKind::LanguageRow { code, .. } => { if self.language_choice.as_deref() == Some(code.as_str()) { @@ -2910,9 +2913,7 @@ impl OptionsUi { } // AbstractSliderButton suppresses the press sound and plays once on // release, even if the pointer has left the widget or its value stayed. - let slider = self.dragging.take().is_some() - || self.dragging_shader_option.take().is_some() - || self.hdragging_shader_option.take().is_some(); + let slider = self.dragging.take().is_some() || self.dragging_shader_option.take().is_some(); let graphics_slider = self.graphics.release(); if slider || graphics_slider { vec![Event::ButtonClick] @@ -2992,6 +2993,12 @@ impl OptionsUi { events.push(Event::Language(code)); } } + // Iris's ShaderPackScreen applies its edits on Done, so the + // pack is rebuilt once, not on every click or slider step. + Page::ShaderPackOptions if std::mem::take(&mut self.shader_pack_edited) => { + self.save_shader_pack_config(); + events.push(Event::ReloadShaderPack); + } Page::Packs => { // PackSelectionScreen.onClose: PackSelectionModel.commit. if let Some(p) = self.pack_screen.take() @@ -3416,19 +3423,73 @@ mod tests { false, ); assert_eq!(s.horizon.shader_pack, "", "a second click turns it off"); - let import_btn = find(&mut ui, &s, &|a| *a == Act::ImportShaderPack).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_dropped_pack_is_picked_and_its_settings_apply_on_done() { + let atlas = atlas(); + let mut s = Settings::default(); + let mut ui = OptionsUi::default(); + let size = (480.0, 240.0); + let dir = + std::env::temp_dir().join(format!("horizon-shaderpack-drop-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + ui.shader_packs.poll(dir.clone()); + let sample = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../examples/shaderpacks/horizon-sample"); assert_eq!( + ui.drop_shader_pack(&mut s, &sample), + None, + "only on its page" + ); + ui.show(Page::ShaderPacks); + assert_eq!(ui.drop_shader_pack(&mut s, &sample), Some(Ok(()))); + assert_eq!(s.horizon.shader_pack, "horizon-sample"); + assert!(dir.join("horizon-sample/pack.toml").is_file()); + let again = ui.drop_shader_pack(&mut s, &sample).unwrap().unwrap_err(); + assert!(again.contains("already"), "{again}"); + + let click = |ui: &mut OptionsUi, s: &mut Settings, act: &dyn Fn(&Act) -> bool| { + let w = ui + .layout(s, size.0, size.1) + .0 + .into_iter() + .find(|w| matches!(&w.kind, WKind::Button { act: a, active: true, .. } if act(a))) + .unwrap(); ui.click( - &mut s, + s, &atlas, - import_btn.x + 1.0, - import_btn.y + 1.0, + w.x + 1.0, + w.y + 1.0, size, [480, 240], false, false, - ), - vec![Event::ButtonClick, Event::ImportShaderPack] + ) + }; + click(&mut ui, &mut s, &|a| { + *a == Act::Push(Page::ShaderPackOptions) + }); + assert_eq!(ui.page(), Page::ShaderPackOptions); + for _ in 0..3 { + let events = click(&mut ui, &mut s, &|a| matches!(a, Act::ShaderPackOption(_))); + assert!(!events.contains(&Event::ReloadShaderPack), "{events:?}"); + } + let txt = dir.join("horizon-sample.txt"); + assert!(!txt.exists(), "nothing is saved before Done"); + let events = click(&mut ui, &mut s, &|a| *a == Act::Done); + assert!(events.contains(&Event::ReloadShaderPack), "{events:?}"); + assert_eq!(ui.page(), Page::ShaderPacks); + assert!(txt.is_file(), "Done saves the values"); + click(&mut ui, &mut s, &|a| { + *a == Act::Push(Page::ShaderPackOptions) + }); + let events = click(&mut ui, &mut s, &|a| *a == Act::Done); + assert!( + !events.contains(&Event::ReloadShaderPack), + "no change: no reload" ); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/horizon-client/src/shader_pack.rs b/crates/horizon-client/src/shader_pack.rs index f5a15ca79..d00384748 100644 --- a/crates/horizon-client/src/shader_pack.rs +++ b/crates/horizon-client/src/shader_pack.rs @@ -18,6 +18,13 @@ pub const API: u32 = 2; /// The folder beside `options.txt` that holds the packs. pub const DIR: &str = "shaderpacks"; pub const PRELUDE: &str = include_str!("shader_pack_prelude.wgsl"); +/// What api 2 adds after [`PRELUDE`] (`api = 2` packs only). +pub const PRELUDE_API2: &str = include_str!("shader_pack_prelude_api2.wgsl"); +/// [`PRELUDE_API2`]'s bindings that cost a pass when a stage reads them. +const BINDING_SCENE_NORMAL: u32 = 7; +const BINDING_SCENE_MATERIAL: u32 = 8; +const BINDING_OPAQUE_DEPTH: u32 = 9; +const BINDING_SHADOW_DEPTH: u32 = 10; /// The prelude's vertex entry point, shared by every stage. pub const VERTEX_ENTRY: &str = "horizon_stage_vertex"; const MAX_STAGES: usize = 16; @@ -58,8 +65,6 @@ struct StageEntry { entry: Option, scale: Option, format: Option, - #[serde(default)] - mipmap: bool, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] @@ -74,20 +79,11 @@ struct OptionEntry { values: Option>, } -/// Where a stage runs. Api 1 has `composite` only; Api 2 adds `shadow`, -/// `gbuffer`, `deferred` and `final`. +/// Where a stage runs: `composite` only so far (docs/shader-packs.md, Stages). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum StageKind { - /// Directional sun/moon shadow map pass. - Shadow, - /// Material / G-buffer evaluation pass over world colour, depth and normals. - Gbuffer, - /// Opaque world lighting pass (runs before translucent water/weather). - Deferred, /// After the world pass, before the hand: reads the scene's colour and depth. Composite, - /// Final tonemapping / anti-aliasing pass before HUD and menus. - Final, } #[derive(Clone, Debug)] pub struct Stage { @@ -99,11 +95,13 @@ pub struct Stage { pub entry: String, /// Target size relative to the world's. pub scale: f32, - /// Optional target format name (`rgba16float`, `rgba8unorm`). + /// The target's format ([`STAGE_FORMATS`]); `None`: the screen's. pub format: Option, - /// Whether the previous stage's output is mipmapped before this stage runs. - pub mipmap: bool, + /// The prelude bindings (group 0) the stage reads. + pub bindings: BTreeSet, } +/// The `format`s a stage's target can have. +pub const STAGE_FORMATS: [&str; 3] = ["rgba8unorm", "rgba16float", "rgb10a2unorm"]; #[derive(Clone, Copy, Debug, PartialEq)] pub enum OptionKind { Bool, @@ -377,22 +375,18 @@ impl PackConfig { fn load_java(path: &Path, id: &str, saved: &BTreeMap) -> Result { let pack = JavaPack::open(path)?; let values = pack.values(saved); + // The menus don't know the GPU: `shaders.properties` is read as on an + // unknown one (the screens and profiles of the packs tested don't + // depend on it). let env = Environment::iris("Unknown", "", 4); let props = pack.properties(&values, &env).unwrap_or_default(); let lang = pack.translations("en_us"); let sliders: BTreeSet<&str> = props.sliders().into_iter().collect(); - let option_label = |name: &str, comment: Option<&str>| -> String { - lang.get(&format!("option.{name}")) - .cloned() - .or_else(|| { - comment - .map(str::trim) - .filter(|c| !c.is_empty() && c.len() <= 40 && !c.contains('.')) - .map(str::to_owned) - }) - .unwrap_or_else(|| humanize_identifier(name)) - }; + // Iris's names: the `.lang` entry, else the name itself; the tooltip + // from `.lang`, else the option's comment. + let named = |key: String, name: &str| lang.get(&key).cloned().unwrap_or(name.to_owned()); + let option_label = |name: &str| named(format!("option.{name}"), name); let option_desc = |name: &str, comment: Option<&str>| -> String { lang.get(&format!("option.{name}.comment")) .cloned() @@ -407,7 +401,7 @@ impl PackConfig { let idx = options.len(); options.push(PackOption { key: name.clone(), - label: option_label(name, b.comment.as_deref()), + label: option_label(name), description: option_desc(name, b.comment.as_deref()), kind: OptionKind::Bool, values: Vec::new(), @@ -428,19 +422,12 @@ impl PackConfig { let choices: Vec<(String, String)> = s .allowed .iter() - .map(|raw| { - let label = lang - .get(&format!("value.{name}.{raw}")) - .or_else(|| lang.get(&format!("option.{name}.value.{raw}"))) - .cloned() - .unwrap_or_else(|| raw.clone()); - (raw.clone(), label) - }) + .map(|raw| (raw.clone(), named(format!("value.{name}.{raw}"), raw))) .collect(); let idx = options.len(); options.push(PackOption { key: name.clone(), - label: option_label(name, s.comment.as_deref()), + label: option_label(name), description: option_desc(name, s.comment.as_deref()), kind: OptionKind::Choice { slider: sliders.contains(name.as_str()), @@ -460,10 +447,7 @@ impl PackConfig { .unwrap_or_default() .into_iter() .map(|p| { - let label = lang - .get(&format!("profile.{}", p.name)) - .cloned() - .unwrap_or_else(|| humanize_identifier(&p.name)); + let label = named(format!("profile.{}", p.name), &p.name); PackProfile { name: p.name, label, @@ -501,10 +485,7 @@ impl PackConfig { } } MenuElement::Screen(sub) => { - let label = lang - .get(&format!("screen.{sub}")) - .cloned() - .unwrap_or_else(|| humanize_identifier(&sub)); + let label = named(format!("screen.{sub}"), &sub); items.push(ScreenItem::Subscreen(sub, label)); } MenuElement::Option(opt) => { @@ -523,10 +504,7 @@ impl PackConfig { } let name_str = screen_name.unwrap_or("").to_owned(); let label = match screen_name { - Some(n) => lang - .get(&format!("screen.{n}")) - .cloned() - .unwrap_or_else(|| humanize_identifier(n)), + Some(n) => named(format!("screen.{n}"), n), None => id.to_owned(), }; PackScreen { @@ -700,7 +678,7 @@ pub struct ShaderPack { pub stages: Vec, pub options: Vec, /// Optional custom noise/LUT texture bytes (RGBA8, width, height) from `[textures]`. - pub custom_noise: Option<(u32, u32, Vec)>, + pub custom_noise: Option, /// A Java (OptiFine/Iris) pack's translated passes, instead of `stages`. pub java: Option, dir: PathBuf, @@ -813,6 +791,9 @@ pub fn import_pack(source: &Path, target_dir: &Path) -> Result { if dest.canonicalize().ok() == source.canonicalize().ok() { return Ok(name); } + if dest.exists() { + return Err(format!("{name} is already in {DIR}/")); + } if source.is_file() { fs::copy(&source, &dest).map_err(|e| format!("failed to copy {name}: {e}"))?; } else { @@ -827,10 +808,13 @@ fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), String> { for entry in entries.flatten() { let path = entry.path(); let target = dst.join(entry.file_name()); - if path.is_dir() { - copy_dir_recursive(&path, &target)?; - } else { - fs::copy(&path, &target).map_err(|e| format!("{}: {e}", target.display()))?; + // Links aren't followed: one pointing up the tree would never end. + match entry.file_type() { + Ok(t) if t.is_dir() => copy_dir_recursive(&path, &target)?, + Ok(t) if t.is_file() => { + fs::copy(&path, &target).map_err(|e| format!("{}: {e}", target.display()))?; + } + _ => {} } } Ok(()) @@ -858,17 +842,13 @@ impl Folder { self.dir = dir; self.read = Some(std::time::Instant::now()); } - - pub fn invalidate(&mut self) { - self.read = None; - } } /// A Java pack has no manifest: its name is its file name. fn java_info(name: String) -> Info { Info { name, - description: "Iris/OptiFine pack: G-buffers, shadow map and post passes.".into(), + description: "Iris/OptiFine pack: its full-screen passes run.".into(), authors: Vec::new(), version: String::new(), license: String::new(), @@ -888,7 +868,16 @@ fn manifest(dir: &Path) -> Result { Ok(manifest) } -pub(crate) fn decode_png_rgba(bytes: &[u8]) -> Result<(u32, u32, Vec), String> { +/// An RGBA8 image (`decode_png`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Rgba { + pub width: u32, + pub height: u32, + pub pixels: Vec, +} + +/// A PNG of any colour type as [`Rgba`]. +pub(crate) fn decode_png(bytes: &[u8]) -> Result { let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes)); decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); let mut reader = decoder.read_info().map_err(|e| e.to_string())?; @@ -913,7 +902,11 @@ pub(crate) fn decode_png_rgba(bytes: &[u8]) -> Result<(u32, u32, Vec), Strin png::ColorType::Grayscale => buf.into_iter().flat_map(|g| [g, g, g, 255]).collect(), _ => return Err("unsupported PNG color format".into()), }; - Ok((w, h, rgba)) + Ok(Rgba { + width: w, + height: h, + pixels: rgba, + }) } impl ShaderPack { @@ -936,18 +929,25 @@ impl ShaderPack { .collect::, _>>()?; let mut stages = Vec::new(); for entry in manifest.stage { - let kind = match (pack_api, entry.kind.as_str()) { - (_, "composite") => StageKind::Composite, - (2.., "shadow") => StageKind::Shadow, - (2.., "gbuffer") => StageKind::Gbuffer, - (2.., "deferred") => StageKind::Deferred, - (2.., "final") => StageKind::Final, - (_, other) => { + let kind = match entry.kind.as_str() { + "composite" => StageKind::Composite, + other => { return Err(format!( - "pack.toml: stage kind `{other}` isn't supported (api {pack_api} has `composite`)" + "pack.toml: stage kind `{other}` isn't supported (api {API} has `composite`)" )); } }; + if pack_api == 1 && entry.format.is_some() { + return Err(format!("pack.toml: {}: `format` needs api 2", entry.shader)); + } + if let Some(format) = entry.format.as_deref() + && !STAGE_FORMATS.contains(&format) + { + return Err(format!( + "pack.toml: stage format `{format}` isn't one of {}", + STAGE_FORMATS.join(", ") + )); + } let scale = entry.scale.unwrap_or(1.0); if !(0.25..=2.0).contains(&scale) { return Err(format!( @@ -961,8 +961,17 @@ impl ShaderPack { } let code = fs::read_to_string(&path).map_err(|e| format!("{}: {e}", entry.shader))?; let entry_point = entry.entry.unwrap_or_else(|| "fs_main".into()); - let source = format!("{PRELUDE}\n{code}"); - validate(&source, &entry.shader, &entry_point)?; + let prelude = match pack_api { + 1 => PRELUDE.to_owned(), + _ => format!("{PRELUDE}\n{PRELUDE_API2}"), + }; + let source = format!("{prelude}\n{code}"); + let bindings = validate( + &source, + prelude.lines().count(), + &entry.shader, + &entry_point, + )?; stages.push(Stage { kind, file: entry.shader, @@ -970,20 +979,21 @@ impl ShaderPack { entry: entry_point, scale, format: entry.format, - mipmap: entry.mipmap, + bindings, }); } let mut custom_noise = None; - if let Some(rel) = manifest - .textures - .get("noise") - .or_else(|| manifest.textures.values().next()) - { + for (name, rel) in &manifest.textures { + if name != "noise" { + return Err(format!( + "pack.toml: texture `{name}` isn't supported (api {API} has `noise`)" + )); + } if rel.contains("..") { return Err(format!("pack.toml: texture {rel} is outside the pack")); } let bytes = fs::read(dir.join(rel)).map_err(|e| format!("{rel}: {e}"))?; - custom_noise = Some(decode_png_rgba(&bytes).map_err(|e| format!("{rel}: {e}"))?); + custom_noise = Some(decode_png(&bytes).map_err(|e| format!("{rel}: {e}"))?); } Ok(Self { id: dir @@ -1016,43 +1026,38 @@ impl ShaderPack { .file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); - let options = PackConfig::load_java(path, &id, values) - .map(|c| c.options) - .unwrap_or_default(); Ok(Self { info: java_info(id.clone()), id, stages: Vec::new(), - options, + options: Vec::new(), custom_noise: None, java: Some(java), dir: path.to_path_buf(), stamp, }) } - /// Whether this pack requests directional shadow map rendering. - pub fn needs_shadow(&self) -> bool { - if let Some(java) = &self.java { - return java.folders.iter().any(|f| f.shadow_enabled); - } - self.stages.iter().any(|s| { - s.kind == StageKind::Shadow - || s.source.contains("sample_shadow") - || s.source.contains("shadow_depth") - }) + /// Whether a stage reads one of the prelude's `bindings`. + fn reads(&self, bindings: &[u32]) -> bool { + self.stages + .iter() + .any(|s| bindings.iter().any(|b| s.bindings.contains(b))) } - /// Shadow map resolution requested by this pack, and shadow distance in blocks. - pub fn shadow_config(&self, dimension: i8) -> (u32, f32, f32) { - if let Some(java) = &self.java - && let Some(idx) = java.folder_for(dimension) - { - let d = &java.folders[idx].directives; - return ( - d.shadow_map_resolution, - d.shadow_distance, - d.sun_path_rotation, - ); - } + /// Whether a stage reads the shadow map (`shadow_depth`, `sample_shadow`). + pub fn needs_shadow(&self) -> bool { + self.reads(&[BINDING_SHADOW_DEPTH]) + } + /// Whether a stage reads the G-buffer (`scene_normal`, `scene_material`). + pub fn needs_gbuffer(&self) -> bool { + self.reads(&[BINDING_SCENE_NORMAL, BINDING_SCENE_MATERIAL]) + } + /// Whether the world's depth before translucent geometry is kept + /// (`opaque_depth`, which the G-buffer is also built from). + pub fn needs_opaque_depth(&self) -> bool { + self.needs_gbuffer() || self.reads(&[BINDING_OPAQUE_DEPTH]) + } + /// The shadow map's resolution and distance in blocks. + pub fn shadow_config(&self) -> (u32, f32) { let res = self .options .iter() @@ -1065,7 +1070,7 @@ impl ShaderPack { .find(|o| o.key == "shadow_distance" || o.key == "shadowDistance") .map(|o| (o.value as f32).clamp(16.0, 512.0)) .unwrap_or(128.0); - (res, dist, 0.0) + (res, dist) } /// The pipeline-overridable constants every stage gets: the option values. pub fn constants(&self) -> Vec<(&str, f64)> { @@ -1139,8 +1144,15 @@ fn option( /// naga parses and validates the stage (prelude included) and checks its /// fragment entry point; errors point into the pack's own file. -fn validate(source: &str, file: &str, entry: &str) -> Result<(), String> { - let prelude_lines = PRELUDE.lines().count() as u32 + 1; +/// Parse and validate a stage: the prelude's bindings (group 0) its entry +/// point uses, or the error at the stage's own line. +fn validate( + source: &str, + prelude_lines: usize, + file: &str, + entry: &str, +) -> Result, String> { + let prelude_lines = prelude_lines as u32 + 1; let at = |location: Option| match location { Some(l) if l.line_number > prelude_lines => { format!( @@ -1153,20 +1165,28 @@ fn validate(source: &str, file: &str, entry: &str) -> Result<(), String> { }; let module = naga::front::wgsl::parse_str(source) .map_err(|e| format!("{}: {}", at(e.location(source)), e.message()))?; - naga::valid::Validator::new( + let info = naga::valid::Validator::new( naga::valid::ValidationFlags::all(), naga::valid::Capabilities::default(), ) .validate(&module) .map_err(|e| format!("{}: {}", at(e.location(source)), e.as_inner()))?; - if !module + let Some(index) = module .entry_points .iter() - .any(|e| e.name == entry && e.stage == naga::ShaderStage::Fragment) - { + .position(|e| e.name == entry && e.stage == naga::ShaderStage::Fragment) + else { return Err(format!("{file}: no fragment entry point `{entry}`")); - } - Ok(()) + }; + let uses = info.get_entry_point(index); + Ok(module + .global_variables + .iter() + .filter(|(handle, _)| !uses[*handle].is_empty()) + .filter_map(|(_, var)| var.binding.as_ref()) + .filter(|binding| binding.group == 0) + .map(|binding| binding.binding) + .collect()) } /// The option values saved for a pack (`shaderpacks/.txt`, `key=value`). @@ -1312,6 +1332,20 @@ override mode: i32 = 1; MANIFEST.replace("\"composite\"", "\"shadow\""), "stage kind `shadow`", ), + ( + MANIFEST.replace( + "kind = \"composite\"", + "kind = \"composite\"\nformat = \"rgba16float\"", + ), + "`format` needs api 2", + ), + ( + MANIFEST.replace("api = 1", "api = 2").replace( + "kind = \"composite\"", + "kind = \"composite\"\nformat = \"rgba32float\"", + ), + "stage format `rgba32float`", + ), ( MANIFEST.replace("grade.wgsl", "../grade.wgsl"), "outside the pack", @@ -1334,12 +1368,27 @@ override mode: i32 = 1; #[test] fn api_2_stages_and_pack_config_work() { - let manifest_v2 = MANIFEST - .replace("api = 1", "api = 2") - .replace("\"composite\"", "\"deferred\""); + let manifest_v2 = MANIFEST.replace("api = 1", "api = 2").replace( + "kind = \"composite\"", + "kind = \"composite\"\nformat = \"rgba16float\"", + ); let dir = pack(&[("pack.toml", &manifest_v2), ("shaders/grade.wgsl", GRADE)]); let loaded = ShaderPack::load(&dir, &BTreeMap::new()).unwrap(); - assert_eq!(loaded.stages[0].kind, StageKind::Deferred); + assert_eq!(loaded.stages[0].format.as_deref(), Some("rgba16float")); + assert!( + !loaded.needs_shadow() && !loaded.needs_gbuffer() && !loaded.needs_opaque_depth(), + "reading none of them costs no pass" + ); + let opaque = GRADE.replace("depth_at(in.uv)", "opaque_depth_at(in.uv)"); + let reads = pack(&[("pack.toml", &manifest_v2), ("shaders/grade.wgsl", &opaque)]); + let reads = ShaderPack::load(&reads, &BTreeMap::new()).unwrap(); + assert!(reads.needs_opaque_depth() && !reads.needs_gbuffer()); + let api_1 = pack(&[("pack.toml", MANIFEST), ("shaders/grade.wgsl", &opaque)]); + let error = ShaderPack::load(&api_1, &BTreeMap::new()).err().unwrap(); + assert!( + error.contains("opaque_depth_at"), + "api 1 stages don't see api 2's names: {error}" + ); let parent = dir.parent().unwrap(); let id = dir.file_name().unwrap().to_str().unwrap(); let mut cfg = PackConfig::load(parent, id).unwrap(); diff --git a/crates/horizon-client/src/shader_pack_prelude.wgsl b/crates/horizon-client/src/shader_pack_prelude.wgsl index ebe3ad4cf..7b16690f9 100644 --- a/crates/horizon-client/src/shader_pack_prelude.wgsl +++ b/crates/horizon-client/src/shader_pack_prelude.wgsl @@ -1,7 +1,6 @@ -// Horizon shader pack prelude, api 2 (docs/shader-packs.md): placed before -// every stage's source. Bindings, the Frame and FrameExt uniforms, the -// full-screen vertex shader, G-buffer/shadow accessors and PBR/post helpers -// that hide the renderer's reversed depth. +// Horizon shader pack prelude, api 1 (docs/shader-packs.md): placed before +// every stage's source. Bindings, the Frame uniform, the full-screen vertex +// shader and helpers that hide the renderer's reversed depth. struct Frame { view: mat4x4, projection: mat4x4, @@ -20,36 +19,12 @@ struct Frame { view_params: vec4, dimension: vec4, } - -struct FrameExt { - previous_view: mat4x4, - previous_projection: mat4x4, - shadow_view: mat4x4, - shadow_projection: mat4x4, - shadow_inverse_view: mat4x4, - shadow_inverse_projection: mat4x4, - // xyz: previous camera world position, w: frame delta time (seconds) - previous_camera: vec4, - // x: shadow map resolution, y: shadow distance (blocks), z: sun_path_rotation (rad), w: shadow strength - shadow_params: vec4, - // x: eye block light (0..240), y: eye sky light (0..240), z: smoothed wetness (0..1), w: center linear depth - environment: vec4, -} - @group(0) @binding(0) var scene_color: texture_2d; @group(0) @binding(1) var scene_depth: texture_depth_2d; @group(0) @binding(2) var previous: texture_2d; @group(0) @binding(3) var linear_sampler: sampler; @group(0) @binding(4) var nearest_sampler: sampler; @group(0) @binding(5) var frame: Frame; -@group(0) @binding(6) var frame_ext: FrameExt; -@group(0) @binding(7) var scene_normal: texture_2d; -@group(0) @binding(8) var scene_material: texture_2d; -@group(0) @binding(9) var opaque_depth: texture_depth_2d; -@group(0) @binding(10) var shadow_depth: texture_depth_2d; -@group(0) @binding(11) var shadow_sampler: sampler_comparison; -@group(0) @binding(12) var noise_texture: texture_2d; -@group(0) @binding(13) var repeat_sampler: sampler; struct StageIn { @builtin(position) position: vec4, @@ -67,10 +42,6 @@ struct StageIn { fn depth_at(uv: vec2) -> f32 { return textureSampleLevel(scene_depth, nearest_sampler, uv, 0); } -// The opaque world's depth at `uv` (before translucent water and stained glass). -fn opaque_depth_at(uv: vec2) -> f32 { - return textureSampleLevel(opaque_depth, nearest_sampler, uv, 0); -} fn is_sky(depth: f32) -> bool { return depth <= 0.0; } @@ -89,70 +60,6 @@ fn view_position(uv: vec2, depth: f32) -> vec3 { fn world_offset(uv: vec2, depth: f32) -> vec3 { return (frame.inverse_view * vec4(view_position(uv, depth), 1.0)).xyz; } -// World-space surface normal at `uv` from the G-buffer (or reconstructed from depth). -fn world_normal_at(uv: vec2) -> vec3 { - let encoded = textureSampleLevel(scene_normal, nearest_sampler, uv, 0.0); - if encoded.w > 0.001 { - return normalize(encoded.xyz * 2.0 - 1.0); - } - let step_uv = frame.resolution.zw; - let d0 = depth_at(uv); - let p0 = world_offset(uv, d0); - let px = world_offset(uv + vec2(step_uv.x, 0.0), depth_at(uv + vec2(step_uv.x, 0.0))) - p0; - let py = world_offset(uv + vec2(0.0, step_uv.y), depth_at(uv + vec2(0.0, step_uv.y))) - p0; - let n = cross(py, px); - let len = length(n); - if len > 1e-6 { - return n / len; - } - return vec3(0.0, 1.0, 0.0); -} -// G-buffer material data at `uv`: r = block light (0..1), g = sky light (0..1), -// b = water/translucent mask (0..1), a = roughness (0..1). -fn material_at(uv: vec2) -> vec4 { - return textureSampleLevel(scene_material, nearest_sampler, uv, 0.0); -} -// Reproject a camera-relative world position into previous-frame UV and clip depth. -fn reproject_uv(world_rel: vec3) -> vec3 { - let camera_delta = frame.camera_position.xyz - frame_ext.previous_camera.xyz; - let prev_rel = world_rel + camera_delta; - let clip = frame_ext.previous_projection * (frame_ext.previous_view * vec4(prev_rel, 1.0)); - if clip.w <= 1e-5 { - return vec3(-1.0); - } - let ndc = clip.xyz / clip.w; - return vec3(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5, ndc.z); -} -// Sample the directional sun/moon shadow map with 5-tap PCF and normal offset bias. -// Returns 1.0 in full light and 0.0 in full shadow. -fn sample_shadow(world_rel: vec3, world_normal: vec3) -> f32 { - if frame_ext.shadow_params.w <= 0.001 { - return 1.0; - } - let dist = length(world_rel); - let max_dist = max(frame_ext.shadow_params.y, 16.0); - if dist >= max_dist { - return 1.0; - } - let light_dir = normalize(select(frame.moon.xyz, frame.sun.xyz, frame.sun.y >= -0.05)); - let ndotl = max(dot(world_normal, light_dir), 0.0); - let bias_pos = world_rel + world_normal * (0.06 + 0.12 * (1.0 - ndotl)); - let light_clip = frame_ext.shadow_projection * (frame_ext.shadow_view * vec4(bias_pos, 1.0)); - let ndc = light_clip.xyz / max(light_clip.w, 1e-5); - let shadow_uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); - if any(shadow_uv < vec2(0.002)) || any(shadow_uv > vec2(0.998)) || ndc.z <= 0.0 || ndc.z >= 1.0 { - return 1.0; - } - let texel = 1.0 / max(frame_ext.shadow_params.x, 512.0); - let ref_z = clamp(ndc.z + 0.0008, 0.0, 1.0); - var sum = textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv, ref_z); - sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv + vec2(texel, 0.0), ref_z); - sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv - vec2(texel, 0.0), ref_z); - sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv + vec2(0.0, texel), ref_z); - sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv - vec2(0.0, texel), ref_z); - let fade = smoothstep(max_dist, max_dist * 0.82, dist); - return mix(1.0, sum * 0.2, fade * frame_ext.shadow_params.w); -} fn luminance(c: vec3) -> f32 { return dot(c, vec3(0.2126, 0.7152, 0.0722)); } @@ -162,12 +69,3 @@ fn srgb_to_linear(c: vec3) -> vec3 { fn linear_to_srgb(c: vec3) -> vec3 { return select(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, c <= vec3(0.0031308)); } -// ACES fitted filmic tonemapping curve (linear HDR -> linear 0..1). -fn aces_tonemap(x: vec3) -> vec3 { - let a = 2.51; - let b = 0.03; - let c = 2.43; - let d = 0.59; - let e = 0.14; - return clamp((x * (a * x + b)) / (x * (c * x + d) + e), vec3(0.0), vec3(1.0)); -} diff --git a/crates/horizon-client/src/shader_pack_prelude_api2.wgsl b/crates/horizon-client/src/shader_pack_prelude_api2.wgsl new file mode 100644 index 000000000..80e9a205e --- /dev/null +++ b/crates/horizon-client/src/shader_pack_prelude_api2.wgsl @@ -0,0 +1,108 @@ +// Horizon shader pack prelude, api 2 additions (docs/shader-packs.md): placed +// after the api 1 prelude before the stages of an `api = 2` pack, so api 1 +// packs keep every name they may have declared themselves. +struct FrameExt { + previous_view: mat4x4, + previous_projection: mat4x4, + shadow_view: mat4x4, + shadow_projection: mat4x4, + shadow_inverse_view: mat4x4, + shadow_inverse_projection: mat4x4, + // xyz: previous camera world position, w: frame delta time (seconds) + previous_camera: vec4, + // x: shadow map resolution, y: shadow distance (blocks), z: 0, + // w: 1 while the shadow map is drawn this frame, else 0 + shadow_params: vec4, + // x: eye block light (0..240), y: eye sky light (0..240), z: smoothed + // rain (0..1), w: 0 + environment: vec4, +} + +@group(0) @binding(6) var frame_ext: FrameExt; +@group(0) @binding(7) var scene_normal: texture_2d; +@group(0) @binding(8) var scene_material: texture_2d; +@group(0) @binding(9) var opaque_depth: texture_depth_2d; +@group(0) @binding(10) var shadow_depth: texture_depth_2d; +@group(0) @binding(11) var shadow_sampler: sampler_comparison; +@group(0) @binding(12) var noise_texture: texture_2d; +@group(0) @binding(13) var repeat_sampler: sampler; + +// The opaque world's depth at `uv` (before translucent water and stained glass). +fn opaque_depth_at(uv: vec2) -> f32 { + return textureSampleLevel(opaque_depth, nearest_sampler, uv, 0); +} + +// World-space surface normal at `uv` from the G-buffer (or reconstructed from depth). +fn world_normal_at(uv: vec2) -> vec3 { + let encoded = textureSampleLevel(scene_normal, nearest_sampler, uv, 0.0); + if encoded.w > 0.001 { + return normalize(encoded.xyz * 2.0 - 1.0); + } + let step_uv = frame.resolution.zw; + let d0 = depth_at(uv); + let p0 = world_offset(uv, d0); + let px = world_offset(uv + vec2(step_uv.x, 0.0), depth_at(uv + vec2(step_uv.x, 0.0))) - p0; + let py = world_offset(uv + vec2(0.0, step_uv.y), depth_at(uv + vec2(0.0, step_uv.y))) - p0; + let n = cross(py, px); + let len = length(n); + if len > 1e-6 { + return n / len; + } + return vec3(0.0, 1.0, 0.0); +} +// G-buffer material data at `uv`: r = block light (0..1), g = sky light (0..1), +// b = water/translucent mask (0..1), a = roughness (0..1). +fn material_at(uv: vec2) -> vec4 { + return textureSampleLevel(scene_material, nearest_sampler, uv, 0.0); +} +// Reproject a camera-relative world position into previous-frame UV and clip depth. +fn reproject_uv(world_rel: vec3) -> vec3 { + let camera_delta = frame.camera_position.xyz - frame_ext.previous_camera.xyz; + let prev_rel = world_rel + camera_delta; + let clip = frame_ext.previous_projection * (frame_ext.previous_view * vec4(prev_rel, 1.0)); + if clip.w <= 1e-5 { + return vec3(-1.0); + } + let ndc = clip.xyz / clip.w; + return vec3(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5, ndc.z); +} +// Sample the directional sun/moon shadow map with 5-tap PCF and normal offset bias. +// Returns 1.0 in full light and 0.0 in full shadow. +fn sample_shadow(world_rel: vec3, world_normal: vec3) -> f32 { + if frame_ext.shadow_params.w <= 0.001 { + return 1.0; + } + let dist = length(world_rel); + let max_dist = max(frame_ext.shadow_params.y, 16.0); + if dist >= max_dist { + return 1.0; + } + let light_dir = normalize(select(frame.moon.xyz, frame.sun.xyz, frame.sun.y >= -0.05)); + let ndotl = max(dot(world_normal, light_dir), 0.0); + let bias_pos = world_rel + world_normal * (0.06 + 0.12 * (1.0 - ndotl)); + let light_clip = frame_ext.shadow_projection * (frame_ext.shadow_view * vec4(bias_pos, 1.0)); + let ndc = light_clip.xyz / max(light_clip.w, 1e-5); + let shadow_uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + if any(shadow_uv < vec2(0.002)) || any(shadow_uv > vec2(0.998)) || ndc.z <= 0.0 || ndc.z >= 1.0 { + return 1.0; + } + let texel = 1.0 / max(frame_ext.shadow_params.x, 512.0); + let ref_z = clamp(ndc.z + 0.0008, 0.0, 1.0); + var sum = textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv, ref_z); + sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv + vec2(texel, 0.0), ref_z); + sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv - vec2(texel, 0.0), ref_z); + sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv + vec2(0.0, texel), ref_z); + sum += textureSampleCompareLevel(shadow_depth, shadow_sampler, shadow_uv - vec2(0.0, texel), ref_z); + let fade = smoothstep(max_dist, max_dist * 0.82, dist); + return mix(1.0, sum * 0.2, fade * frame_ext.shadow_params.w); +} + +// ACES fitted filmic tonemapping curve (linear HDR -> linear 0..1). +fn aces_tonemap(x: vec3) -> vec3 { + let a = 2.51; + let b = 0.03; + let c = 2.43; + let d = 0.59; + let e = 0.14; + return clamp((x * (a * x + b)) / (x * (c * x + d) + e), vec3(0.0), vec3(1.0)); +} diff --git a/crates/horizon-shaderpack/src/options.rs b/crates/horizon-shaderpack/src/options.rs index d25a3d776..3158b12cf 100644 --- a/crates/horizon-shaderpack/src/options.rs +++ b/crates/horizon-shaderpack/src/options.rs @@ -489,11 +489,14 @@ impl OptionValues { out.bools.insert(name.clone(), value); } } + // A saved value the option doesn't list (an old or hand-edited + // file) is dropped, as OptiFine's `ShaderOption.setValue` refuses it. for (name, o) in &options.strings { - if let Some(v) = saved.get(name) { - if *v != o.default { - out.strings.insert(name.clone(), v.clone()); - } + if let Some(v) = saved.get(name) + && *v != o.default + && o.allowed.contains(v) + { + out.strings.insert(name.clone(), v.clone()); } } out @@ -623,6 +626,13 @@ mod tests { !values.bools.contains_key("shadowHardwareFiltering"), "not a boolean: ignored" ); + let stale = [("QUALITY", "abc"), ("sunPathRotation", "")] + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .into(); + assert!( + OptionValues::new(&set, &stale).strings.is_empty(), + "values the options don't list: ignored" + ); let edited: Vec = lines .iter() .enumerate() diff --git a/crates/horizon-shaderpack/src/pipeline.rs b/crates/horizon-shaderpack/src/pipeline.rs index db656e3ae..89898eb07 100644 --- a/crates/horizon-shaderpack/src/pipeline.rs +++ b/crates/horizon-shaderpack/src/pipeline.rs @@ -323,8 +323,6 @@ pub struct Passes { /// next frame starts unflipped. pub flipped_at_end: BTreeSet, pub directives: Directives, - /// Whether the folder uses shadow mapping (`shadow` program or `shadowtex*`). - pub shadow_enabled: bool, } /// The `const` directives of a program folder that aren't about targets @@ -341,24 +339,6 @@ pub struct Directives { pub wetness_half_life: f32, /// `drynessHalflife`, tenths of a second: `wetness` smoothing when dry. pub dryness_half_life: f32, - /// `centerDepthHalflife`, tenths of a second: `centerDepthSmooth`. - pub center_depth_half_life: f32, - /// `shadowMapResolution` (or `SHADOW_RES`), in pixels per side. - pub shadow_map_resolution: u32, - /// `shadowDistance`, in blocks. - pub shadow_distance: f32, - /// `shadowDistanceRenderMul` (-1 when unset). - pub shadow_distance_render_mul: f32, - /// `ambientOcclusionLevel` (0.0..=1.0). - pub ambient_occlusion_level: f32, - /// `noiseTextureResolution`, in pixels per side. - pub noise_texture_resolution: u32, - /// `shadowHardwareFiltering` / `shadowHardwareFiltering0..1`. - pub shadow_hardware_filtering: [bool; 2], - /// `shadowtex0Nearest` / `shadowtex1Nearest`. - pub shadow_nearest: [bool; 2], - /// `generateShadowMipmap` / `shadowtex0Mipmap` / `shadowtex1Mipmap`. - pub shadow_mipmap: [bool; 2], } impl Default for Directives { @@ -368,15 +348,6 @@ impl Default for Directives { eye_brightness_half_life: 10.0, wetness_half_life: 600.0, dryness_half_life: 200.0, - center_depth_half_life: 1.0, - shadow_map_resolution: 2048, - shadow_distance: 128.0, - shadow_distance_render_mul: -1.0, - ambient_occlusion_level: 1.0, - noise_texture_resolution: 256, - shadow_hardware_filtering: [false; 2], - shadow_nearest: [false; 2], - shadow_mipmap: [false; 2], } } } @@ -387,66 +358,13 @@ impl Directives { let mut out = Self::default(); for fragment in fragments { for c in const_directives(fragment) { - let raw = c.value.trim_end_matches(['f', 'F']); - let fval = raw.parse::(); - let ival = raw.parse::(); - let bval = raw.parse::(); - match (c.ty, c.key.as_str()) { - ("float", "sunPathRotation") if fval.is_ok() => { - out.sun_path_rotation = fval.unwrap(); - } - ("float", "eyeBrightnessHalflife") if fval.is_ok() => { - out.eye_brightness_half_life = fval.unwrap(); - } - ("float", "wetnessHalflife") if fval.is_ok() => { - out.wetness_half_life = fval.unwrap(); - } - ("float", "drynessHalflife") if fval.is_ok() => { - out.dryness_half_life = fval.unwrap(); - } - ("float", "centerDepthHalflife") if fval.is_ok() => { - out.center_depth_half_life = fval.unwrap(); - } - ("float", "shadowDistance") if fval.is_ok() => { - out.shadow_distance = fval.unwrap().clamp(8.0, 1024.0); - } - ("float", "shadowDistanceRenderMul") if fval.is_ok() => { - out.shadow_distance_render_mul = fval.unwrap(); - } - ("float", "ambientOcclusionLevel") if fval.is_ok() => { - out.ambient_occlusion_level = fval.unwrap().clamp(0.0, 1.0); - } - ("int", "shadowMapResolution") if ival.is_ok() => { - out.shadow_map_resolution = ival.unwrap().clamp(64, 8192); - } - ("int", "noiseTextureResolution") if ival.is_ok() => { - out.noise_texture_resolution = ival.unwrap().clamp(16, 2048); - } - ("bool", "shadowHardwareFiltering") if bval.is_ok() => { - out.shadow_hardware_filtering = [bval.unwrap(); 2]; - } - ("bool", "shadowHardwareFiltering0") if bval.is_ok() => { - out.shadow_hardware_filtering[0] = bval.unwrap(); - } - ("bool", "shadowHardwareFiltering1") if bval.is_ok() => { - out.shadow_hardware_filtering[1] = bval.unwrap(); - } - ("bool", "shadowtexNearest" | "shadowtex0Nearest" | "shadow0MinMagNearest") - if bval.is_ok() => - { - out.shadow_nearest[0] = bval.unwrap(); - } - ("bool", "shadowtex1Nearest" | "shadow1MinMagNearest") if bval.is_ok() => { - out.shadow_nearest[1] = bval.unwrap(); - } - ("bool", "generateShadowMipmap" | "shadowtexMipmap" | "shadowtex0Mipmap") - if bval.is_ok() => - { - out.shadow_mipmap[0] = bval.unwrap(); - } - ("bool", "shadowtex1Mipmap") if bval.is_ok() => { - out.shadow_mipmap[1] = bval.unwrap(); - } + // Java's `Float.parseFloat` takes a trailing `f`. + let value = c.value.trim_end_matches(['f', 'F']).parse::(); + match (c.ty, c.key.as_str(), value) { + ("float", "sunPathRotation", Ok(v)) => out.sun_path_rotation = v, + ("float", "eyeBrightnessHalflife", Ok(v)) => out.eye_brightness_half_life = v, + ("float", "wetnessHalflife", Ok(v)) => out.wetness_half_life = v, + ("float", "drynessHalflife", Ok(v)) => out.dryness_half_life = v, _ => {} } } @@ -568,19 +486,9 @@ impl JavaPack { for name in &groups[0..2].concat() { fragments.insert(name.clone(), fragment(name)?); } - let shadow_enabled = ["shadow", "shadow_solid", "shadow_cutout"] - .iter() - .any(|s| exists(s)) - || sources.iter().any(|s| { - s.contains("shadowtex0") - || s.contains("shadowtex1") - || s.contains("watershadow") - || s.contains("shadow2D") - }); let mut out = Passes { targets: target_settings(sources.iter().map(String::as_str), properties), directives: Directives::read(sources.iter().map(String::as_str)), - shadow_enabled, ..Passes::default() }; @@ -858,14 +766,14 @@ mod tests { assert_eq!(Directives::read([]), Directives::default()); assert_eq!(Directives::default().eye_brightness_half_life, 10.0); let d = Directives::read([ - "const float sunPathRotation = 30.0;\nconst float eyeBrightnessHalflife = 4.0f;\nconst int shadowMapResolution = 4096;\nconst float shadowDistance = 192.0;", + "const float sunPathRotation = 30.0;\nconst float eyeBrightnessHalflife = 4.0f;\nconst float wetnessHalflife = 300.0;", "const float sunPathRotation = -40.0; // Complementary Unbound", "const int sunPathRotation = 5;", ]); assert_eq!(d.sun_path_rotation, -40.0); assert_eq!(d.eye_brightness_half_life, 4.0); - assert_eq!(d.shadow_map_resolution, 4096); - assert_eq!(d.shadow_distance, 192.0); + assert_eq!(d.wetness_half_life, 300.0); + assert_eq!(d.dryness_half_life, 200.0, "the default"); } #[test] diff --git a/crates/horizon-shaderpack/src/translate.rs b/crates/horizon-shaderpack/src/translate.rs index 623ad760d..27fafe34b 100644 --- a/crates/horizon-shaderpack/src/translate.rs +++ b/crates/horizon-shaderpack/src/translate.rs @@ -806,20 +806,11 @@ impl<'a> Legaliser<'a> { fn unit(&mut self, unit: &mut ast::TranslationUnit) -> Result<(), String> { // Functions, their sampler parameters, and struct definitions first. for ed in &unit.0 { - if let ast::ExternalDeclarationData::Declaration(d) = &ed.content { - match &d.content { - ast::DeclarationData::InitDeclaratorList(list) => { - if let ast::TypeSpecifierNonArrayData::Struct(s) = - &list.head.ty.ty.ty.content - { - self.record_struct(s); - } - } - ast::DeclarationData::TypeOnly(q) => { - let _ = q; - } - _ => {} - } + if let ast::ExternalDeclarationData::Declaration(d) = &ed.content + && let ast::DeclarationData::InitDeclaratorList(list) = &d.content + && let ast::TypeSpecifierNonArrayData::Struct(s) = &list.head.ty.ty.ty.content + { + self.record_struct(s); } let proto = match &ed.content { ast::ExternalDeclarationData::FunctionDefinition(f) => &f.prototype, diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 0ba8981fb..6718be0f7 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -13,16 +13,18 @@ Both are off by default. With no pack selected the renderer draws exactly what i | Part | State | | --- | --- | | Renderer layout (below) | today's code | -| Horizon shader packs: `composite`, `deferred`, `gbuffer`, `shadow`, `final` stages (API 2), uniforms, custom textures, hot reload | done (`examples/shaderpacks/horizon-ultra` + `horizon-sample`) | -| Shader Packs UI: import (`.zip`/folder dialog + drag-and-drop), profiles, sub-screens, sliders, toggles, reset to defaults | done (Horizon & Classic Video/Graphics settings) | -| Real-time shadow map pass (`"Horizon shadow"`, `shadowtex0/1`, `shadowModelView`, `shadowProjection`) & pre-translucent depth (`depthtex1/2`) | done | -| G-buffer normal & material pass (`"Horizon gbuffer"`, `scene_normal`, `scene_material`, `colortex1..3` initialization) | done | -| Java shader packs: preprocessor (`crates/horizon-shaderpack`: includes, options, Iris's macros, JCPP's `#if` and `#define` rules, `.lang` files) | done: ten packs tested (Compatibility, below) | -| Java shader packs: GLSL → WGSL (`horizon_shaderpack::translate`: syntax-tree legaliser, naga, 2D array & struct varyings, vertex `textureLod`, `mat2(vec4)`, `1 << 31` shifts) | done | -| Java shader packs: `shaders.properties` (`horizon_shaderpack::properties`: screens, sliders, profiles, `program.*.enabled`, image formats, blend modes, custom textures) | done, wired to UI and GPU passes | -| Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips, blend state) | done | -| Java shader packs: full-screen passes drawn (`java_pack.rs`, `gfx/java_stages.rs`: `begin`, `prepare`, `deferred*`, `composite*`, `final` over Horizon's world) | done: with shadow maps, `depthtex1/2`, custom PNG textures, GL blend modes, `wetness`, `centerDepthSmooth` | -| Java shader packs: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light | done | +| Horizon shader packs: `composite` stage, uniforms, hot reload, Shader Packs page | done (the page: list, pick, open the folder, drop a pack on it) | +| Horizon shader packs, api 2: stage `format`s, `[profiles]`, option descriptions, a `noise` texture, the opaque depth, a G-buffer reconstructed from depth, a sun/moon shadow map (Stages, below) | first slice: `examples/shaderpacks/horizon-ultra` | +| Horizon shader packs: `deferred`, `gbuffer`, `shadow` stages (the pack's own code in the world pass) | planned | +| Shader Pack Settings page: a pack's options, sub-screens, sliders, profiles and Reset, Horizon and Java packs alike; applied once on Done, as Iris does | done | +| Java shader packs: preprocessing + GLSL parse coverage | spike done: 450 of 470 programs reach valid WGSL (below) | +| Java shader packs: preprocessor (`crates/horizon-shaderpack`: includes, options, Iris's macros, JCPP's `#if` and `#define` rules, `.lang` files) | done: every program of the three test packs preprocesses; ten packs tested (Compatibility, below) | +| Java shader packs: GLSL → WGSL (`horizon_shaderpack::translate`: syntax-tree legaliser, naga; struct and nested-array varyings, vertex `texture`, `mat2(vec4)`, `1 << 31`) | done: the 464 programs the three test packs enable by default translate (below) | +| Java shader packs: `shaders.properties` (`horizon_shaderpack::properties`: screens, sliders, profiles, `program.*.enabled`, image formats, blend modes, `texture.*`) | done: read like Iris for the three test packs | +| Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips, `blend.*`) | done: planned for the three test packs | +| Java shader packs: full-screen passes drawn (`java_pack.rs`, `gfx/java_stages.rs`: `begin`, `prepare`, `deferred*`, `composite*`, `final` over Horizon's world) | first slice: BSL and Complementary run (below); `depthtex1`/`depthtex2` before translucent geometry, `blend.*`, PNG `texture..*` and `texture.noise` | +| Java shader packs: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light, `wetness` | done for the full-screen passes (below) | +| Java shader packs: `gbuffers_*`, `shadow`, `.dat` and resource-location textures, images, compute | planned | ## How the renderer draws a frame today @@ -63,7 +65,14 @@ The lightmap, fog and sky colours are computed on the CPU (`environment.rs`, `fo Horizon Settings... → Shader Packs...**, and the Shader Pack row of the graphics settings lead to it. It shows the folder's full path and an *Open Folder* button (the folder is made if it is missing), then one switch per pack: turning one on picks it, turning it off is the vanilla picture. With no pack, it says so under the path. The list is read again every - second while the page is open, so a pack dropped into the folder shows up. + second while the page is open, so a pack dropped into the folder shows up. A `.zip` or pack folder dropped on the + window while the page shows is copied into the folder and picked (Iris's `ShaderPackScreen.onFilesDrop`); one of + that name already there is left alone. +- With a pack on that has options, **Shader Pack Settings...** opens them: Horizon packs' `[options]` and + `[profiles]`, Java packs' `#define`/`const` options laid out by `shaders.properties` (`screen`, `screen.`, + `sliders`, `profile.*`) and named by `lang/en_us.lang` (`option.*`, `value.*`, `screen.*`, `profile.*`, as Iris; + without one, the option's own name). The values are saved and the pack built again once, when the page closes + (Iris applies on Done), not on every click or slider step. A saved value an option doesn't list is ignored. - The choice is kept in `horizon-graphics.txt` (`shaderPack:`, empty = off). A pack's option values are kept in `shaderpacks/.txt`, as Iris does. - A pack that fails to load or compile leaves the vanilla picture (or the last pack that worked) on and says why on @@ -79,7 +88,7 @@ my-pack/ composite.wgsl bloom.wgsl textures/ - noise.png # planned + noise.png # api 2: [textures] noise LICENSE ``` @@ -112,6 +121,24 @@ step = 0.05 [options.vignette] label = "Vignette" default = true +description = "Darkens the corners." # optional: the button's tooltip +``` + +Api 2 (`api = 2`) adds: + +```toml +[[stage]] +kind = "composite" +shader = "shaders/lighting.wgsl" +format = "rgba16float" # this stage's target: rgba8unorm, rgba16float or rgb10a2unorm; the last stage + # always writes the screen's format, so earlier ones can keep HDR colour + +[profiles.low] # the Profile button cycles these; "Custom" when the values match none +vignette = false +saturation = 1.0 + +[textures] +noise = "textures/noise.png" # replaces the prelude's noise_texture (256x256 random RGB without it) ``` Options become WGSL [pipeline-overridable constants](https://www.w3.org/TR/WGSL/#override-decls): the shader @@ -176,6 +203,29 @@ Prelude helpers: `linear_depth(depth) -> f32` (blocks from the eye), `view_posit The uniform layout only grows: a new field goes at the end and the `api` number goes up; a pack that declares an older `api` still loads. +An `api = 2` pack's stages get a second prelude after the first (`shader_pack_prelude_api2.wgsl`; api 1 packs don't, +so names they declare themselves can't clash): + +| Binding | WGSL | What | +| --- | --- | --- | +| 6 | `frame_ext: FrameExt` (uniform) | last frame's view and projection and camera, the shadow map's matrices, resolution and distance, eye light, smoothed rain | +| 7, 8 | `scene_normal`, `scene_material: texture_2d` | the G-buffer (below) | +| 9 | `opaque_depth: texture_depth_2d` | the world's depth before translucent geometry (water, glass, ice) | +| 10, 11 | `shadow_depth: texture_depth_2d`, `shadow_sampler: sampler_comparison` | the sun's (the moon's at night) shadow map | +| 12, 13 | `noise_texture: texture_2d`, `repeat_sampler: sampler` | `[textures] noise`, linear, repeat | + +Helpers: `opaque_depth_at(uv)`, `world_normal_at(uv)`, `material_at(uv)` (block light, sky light, translucent mask, +roughness), `reproject_uv(world_offset)` (last frame's uv and depth), `sample_shadow(world_offset, normal)` (5-tap +PCF, 1 lit .. 0 shadowed), `aces_tonemap(rgb)`. + +What each costs, only while a stage reads it (naga reports the bindings each entry point uses): the opaque depth, a +depth copy between the opaque and translucent halves of the world pass; the G-buffer, one full-screen pass after +the world; the shadow map, a depth pass of the terrain and entities from the light. Limits of this first slice: the +G-buffer is reconstructed from depth and colour (normals from neighbouring depths, block light estimated from +brightness, sky light the camera's), not written by the world's shaders; the shadow map holds the sections the +camera draws, so casters outside the view throw no shadow, and none of the terrain where Metal draws sections as one +list (`gfx/flat.rs`, more than 4096 of them). The `deferred`, `gbuffer` and `shadow` stages above replace these. + ### How it renders With a pack on, the world pass draws into the world target of `gfx/world_post.rs` (it exists already for resolution diff --git a/examples/shaderpacks/horizon-ultra/pack.toml b/examples/shaderpacks/horizon-ultra/pack.toml index 446115073..9a59eec90 100644 --- a/examples/shaderpacks/horizon-ultra/pack.toml +++ b/examples/shaderpacks/horizon-ultra/pack.toml @@ -1,15 +1,15 @@ # Horizon Ultra: multi-pass API 2 WGSL shader pack with PCF directional shadows, -# G-buffer GTAO, water SSR & absorption, volumetric godrays, HDR bloom and ACES tonemapping. +# screen-space AO, water SSR & absorption, screen-space godrays, HDR bloom and ACES tonemapping. [pack] name = "Horizon Ultra" -description = "PCF sun/moon shadows, GTAO, water reflections, volumetric godrays, bloom and ACES filmic tonemapping." +description = "PCF sun/moon shadows, ambient occlusion, water reflections, godrays, bloom and ACES filmic tonemapping." authors = ["Horizon contributors"] version = "2.0.0" license = "MIT" api = 2 [[stage]] -kind = "deferred" +kind = "composite" shader = "shaders/deferred_lighting.wgsl" format = "rgba16float" @@ -23,10 +23,9 @@ kind = "composite" shader = "shaders/bloom_godrays.wgsl" scale = 0.5 format = "rgba16float" -mipmap = true [[stage]] -kind = "final" +kind = "composite" shader = "shaders/final_tonemap.wgsl" [profiles.low] @@ -82,8 +81,8 @@ max = 1.0 step = 0.05 [options.ao_strength] -label = "Ambient Occlusion (GTAO)" -description = "Screen-space horizon ambient occlusion in corners and crevices." +label = "Ambient Occlusion" +description = "Screen-space ambient occlusion in corners and crevices." default = 0.75 min = 0.0 max = 1.5 @@ -95,7 +94,7 @@ description = "Screen-space sky and terrain reflections on water and translucent default = true [options.godrays] -label = "Volumetric Godrays" +label = "Godrays" description = "Atmospheric light shafts cast through trees and terrain towards the sun." default = true diff --git a/examples/shaderpacks/horizon-ultra/shaders/bloom_godrays.wgsl b/examples/shaderpacks/horizon-ultra/shaders/bloom_godrays.wgsl index 534e9d983..d175eab6c 100644 --- a/examples/shaderpacks/horizon-ultra/shaders/bloom_godrays.wgsl +++ b/examples/shaderpacks/horizon-ultra/shaders/bloom_godrays.wgsl @@ -1,5 +1,5 @@ // Stage 3 (Composite, half-resolution): HDR bloom extraction + 9-tap tent filter -// and radial volumetric light shafts (godrays) towards the sun/moon. +// and radial light shafts (screen-space godrays) towards the sun/moon. override godrays: bool = true; override bloom_strength: f32 = 0.35; @@ -30,7 +30,7 @@ override bloom_strength: f32 = 0.35; } } - // Radial volumetric godrays cast from the sun's screen projection. + // Radial godrays from the sun's screen projection. var shafts = vec3(0.0); if godrays && frame.camera_state.x == 0.0 && frame.dimension.y > 0.5 { let sun_clip = frame.projection * (frame.view * vec4(frame.sun.xyz * 128.0, 1.0)); diff --git a/examples/shaderpacks/horizon-ultra/shaders/deferred_lighting.wgsl b/examples/shaderpacks/horizon-ultra/shaders/deferred_lighting.wgsl index 3930a5c21..e44773f37 100644 --- a/examples/shaderpacks/horizon-ultra/shaders/deferred_lighting.wgsl +++ b/examples/shaderpacks/horizon-ultra/shaders/deferred_lighting.wgsl @@ -1,10 +1,10 @@ -// Stage 1 (Deferred): G-buffer normal reconstruction, multi-tap GTAO ambient +// Stage 1: G-buffer normals, 8-tap screen-space ambient // occlusion, directional sun/moon PCF shadow mapping, and rain puddle wetness. override shadows: bool = true; override shadow_strength: f32 = 0.85; override ao_strength: f32 = 0.75; -fn compute_gtao(uv: vec2, depth: f32, view_pos: vec3) -> f32 { +fn compute_ao(uv: vec2, depth: f32, view_pos: vec3) -> f32 { if ao_strength <= 0.001 { return 1.0; } @@ -60,7 +60,7 @@ fn compute_gtao(uv: vec2, depth: f32, view_pos: vec3) -> f32 { let mat = material_at(in.uv); // Ambient occlusion from depth discontinuity neighborhood. - let ao = compute_gtao(in.uv, depth, view_pos); + let ao = compute_ao(in.uv, depth, view_pos); // Directional sun/moon shadow factor. var shadow = 1.0;