From 4dff61b697f8f032f374a6b71bea80b1af23d866 Mon Sep 17 00:00:00 2001 From: kerneldroid <212222389+kerneldroid@users.noreply.github.com> Date: Fri, 23 Oct 2026 10:37:14 +0500 Subject: [PATCH] feat(shaders): complete wgpu Iris/Horizon API-2 shader pipeline, shadow & G-buffer passes, GLSL translator fixes, and settings/import UI --- crates/horizon-client/src/game.rs | 3 + crates/horizon-client/src/game/options.rs | 6 + crates/horizon-client/src/game/packs.rs | 54 ++ .../horizon-client/src/game/shader_packs.rs | 26 + .../horizon-client/src/game/startup_menu.rs | 27 + crates/horizon-client/src/gfx.rs | 214 ++++- crates/horizon-client/src/gfx/java_stages.rs | 308 +++++-- crates/horizon-client/src/gfx/pack_stages.rs | 254 +++++- crates/horizon-client/src/gfx/world_post.rs | 557 +++++++++++- crates/horizon-client/src/graphics_ui.rs | 13 +- crates/horizon-client/src/java_pack.rs | 27 +- crates/horizon-client/src/options_ui.rs | 311 ++++++- crates/horizon-client/src/shader_pack.rs | 825 +++++++++++++++++- .../src/shader_pack_prelude.wgsl | 108 ++- crates/horizon-shaderpack/src/lib.rs | 28 +- crates/horizon-shaderpack/src/pipeline.rs | 144 ++- crates/horizon-shaderpack/src/properties.rs | 87 +- crates/horizon-shaderpack/src/source.rs | 22 +- crates/horizon-shaderpack/src/translate.rs | 439 +++++++--- crates/horizon-shaderpack/tests/translate.rs | 41 +- docs/shader-packs.md | 20 +- examples/shaderpacks/horizon-ultra/LICENSE | 13 + examples/shaderpacks/horizon-ultra/pack.toml | 134 +++ .../horizon-ultra/shaders/bloom_godrays.wgsl | 61 ++ .../shaders/deferred_lighting.wgsl | 92 ++ .../horizon-ultra/shaders/final_tonemap.wgsl | 29 + .../shaders/water_reflections.wgsl | 58 ++ 27 files changed, 3614 insertions(+), 287 deletions(-) create mode 100644 examples/shaderpacks/horizon-ultra/LICENSE create mode 100644 examples/shaderpacks/horizon-ultra/pack.toml create mode 100644 examples/shaderpacks/horizon-ultra/shaders/bloom_godrays.wgsl create mode 100644 examples/shaderpacks/horizon-ultra/shaders/deferred_lighting.wgsl create mode 100644 examples/shaderpacks/horizon-ultra/shaders/final_tonemap.wgsl create mode 100644 examples/shaderpacks/horizon-ultra/shaders/water_reflections.wgsl diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0faca0ab4..95c8749f3 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10700,6 +10700,9 @@ impl ApplicationHandler for Game<'_> { WindowEvent::CloseRequested => { self.pending_save.as_mut().unwrap().quit = true; } + WindowEvent::DroppedFile(path) => { + self.import_shader_pack_path(&path); + } WindowEvent::Focused(focused) => { self.focused = focused; if !focused { diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index ea7a5f5c5..c715b4d1a 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -243,6 +243,12 @@ 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(); + } } } Ok(()) diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 94e61d948..13de550e1 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -34,6 +34,60 @@ 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 7d628ef44..d7ec206ec 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -101,6 +101,32 @@ 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); + 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}"))); + } + } + } + /// 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); + } + } fn shader_pack_error(&mut self, id: &str, error: &str) { log::warn!("Horizon: shader pack {id}: {error}"); // The Shader Packs page says why on the pack's row: the first line, diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index a5d076878..e01dd6dc6 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -387,6 +387,22 @@ 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(); + } // The startup menu runs before the game opens a control socket. Event::ButtonClick | Event::CopyAgentDetails => {} } @@ -452,6 +468,17 @@ 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(); + } + } WindowEvent::RedrawRequested => self.draw(), WindowEvent::ModifiersChanged(modifiers) => self.menu.modifiers = modifiers.state(), WindowEvent::Focused(false) => { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index c14a32e2c..0fd03e01b 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -332,6 +332,11 @@ pub struct Renderer { /// (`crosshair_globals`). crosshair_group: wgpu::BindGroup, crosshair_globals: wgpu::Buffer, + shadow_pipeline: wgpu::RenderPipeline, + shadow_entity_pipeline: wgpu::RenderPipeline, + shadow_globals: wgpu::Buffer, + shadow_group: wgpu::BindGroup, + shadow_entity_group: wgpu::BindGroup, entity_pipeline: wgpu::RenderPipeline, weather: weather::Weather, crumbling_pipeline: wgpu::RenderPipeline, @@ -1271,6 +1276,38 @@ impl Renderer { usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); + let shadow_globals = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Shader pack shadow globals"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Terrain shadow"), + layout: Some(&layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_terrain"), + compilation_options: Default::default(), + buffers: &terrain_buffers, + }, + primitive: wgpu::PrimitiveState { + topology: tri, + cull_mode: Some(wgpu::Face::Back), + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::GreaterEqual), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: None, + multiview_mask: None, + cache: None, + }); let prepared = prepared.unwrap_or_else(|| { PreparedTextures::new(sprite_pixels, sprite_size, layers, sprite_mips, forcefield) }); @@ -1384,6 +1421,16 @@ impl Renderer { &lightmap_view, &lightmap_sampler, ); + let shadow_group = terrain_group( + &device, + "Shader pack shadow terrain resources", + &bindings, + &shadow_globals, + &sprite_views, + &sprite_sampler, + &lightmap_view, + &lightmap_sampler, + ); let index_quads = 1 << 16; let indices = Self::quad_indices(&device, index_quads); let instance_capacity = 4096; @@ -1539,6 +1586,32 @@ impl Renderer { }, ], }); + let shadow_entity_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Shader pack shadow entity resources"), + layout: &entity_bindings, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: shadow_globals.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&atlas_view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&atlas_sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::TextureView(&lightmap_view), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Sampler(&lightmap_sampler), + }, + ], + }); let entity_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Entity layout"), bind_group_layouts: &[Some(&entity_bindings)], @@ -1649,6 +1722,32 @@ impl Renderer { wgpu::ColorWrites::ALL, ) }; + let shadow_entity_pipeline = + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Entity shadow"), + layout: Some(&entity_layout), + vertex: wgpu::VertexState { + module: &entity_shader, + entry_point: Some("vs_entity"), + compilation_options: Default::default(), + buffers: &entity_vertex, + }, + primitive: wgpu::PrimitiveState { + cull_mode: None, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(true), + depth_compare: Some(wgpu::CompareFunction::GreaterEqual), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: None, + multiview_mask: None, + cache: None, + }); // RenderPipelines.WATER_MASK: the boat's water patch writes depth only. let water_mask_pipeline = entity_pipeline_with( "Water mask", @@ -2157,6 +2256,11 @@ impl Renderer { debug_line_capacity: 4096, crosshair_group, crosshair_globals, + shadow_pipeline, + shadow_entity_pipeline, + shadow_globals, + shadow_group, + shadow_entity_group, entity_pipeline, weather, crumbling_pipeline, @@ -2661,7 +2765,12 @@ impl Renderer { &pack.id, java, )?), - None => Pack::Horizon(pack_stages::PackStages::new(&self.device, format, pack)?), + None => Pack::Horizon(pack_stages::PackStages::new( + &self.device, + &self.queue, + format, + pack, + )?), }), None => None, }; @@ -2703,6 +2812,16 @@ impl Renderer { &self.lightmap_view, &self.lightmap_sampler, ); + self.shadow_group = terrain_group( + &self.device, + "Shader pack shadow terrain resources", + &self.terrain_layout, + &self.shadow_globals, + &views, + &self.sprite_sampler, + &self.lightmap_view, + &self.lightmap_sampler, + ); } pub fn view_projection(&self, frame: &Frame) -> Mat4 { self.projection( @@ -3544,6 +3663,32 @@ 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 + }; + if let Some((shadow_res, shadow_dist)) = shadow_cfg { + self.world_post + .prepare_shadow(&self.device, shadow_res, shadow_dist, sun, -sun); + let shadow_globals = Globals { + view_proj: (self.world_post.shadow_proj * self.world_post.shadow_view) + .to_cols_array_2d(), + ..globals + }; + self.uploads.buffer( + &mut encoder, + &self.shadow_globals, + 0, + bytemuck::bytes_of(&shadow_globals), + ); + } else { + self.world_post.shadow_active = false; + } let scaled = self.world_post .prepare(&self.device, [self.config.width, self.config.height], pack); @@ -3552,6 +3697,36 @@ impl Renderer { None => (&view_target, &self.depth), }; let cull = self.cull.as_ref().filter(|_| culling && solid_draws > 0); + if shadow_cfg.is_some() { + let shadow_view = self.world_post.shadow_depth().clone(); + let mut shadow_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Horizon shadow"), + color_attachments: &[], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &shadow_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(0.0), + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + ..Default::default() + }); + if solid_draws > 0 && !flat_frame { + shadow_pass.set_bind_group(0, &self.shadow_group, &[]); + shadow_pass.set_pipeline(&self.shadow_pipeline); + shadow_pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + shadow_pass.set_vertex_buffer(1, self.instances.slice(..)); + self.draw_sections(&mut shadow_pass, &self.indirect, 0, 0, solid_draws); + } + if entity_quads > 0 { + shadow_pass.set_pipeline(&self.shadow_entity_pipeline); + shadow_pass.set_bind_group(0, &self.shadow_entity_group, &[]); + shadow_pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + shadow_pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); + shadow_pass.draw_indexed(0..entity_quads * 6, 0, 0..1); + } + } { let attachments = [Some(wgpu::RenderPassColorAttachment { view: world_view, @@ -3753,6 +3928,33 @@ impl Renderer { pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..)); pass.draw(0..4, debug_depth..debug_depth + debug_top); } + if pack { + drop(pass); + self.world_post.capture_opaque_depth(&mut encoder); + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: world_view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + })]; + pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Horizon world, translucent"), + color_attachments: &attachments, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: world_depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }), + stencil_ops: None, + }), + ..Default::default() + }); + pass.set_bind_group(0, &self.group, &[]); + } match self.flat.as_ref().filter(|_| flat_frame) { Some(flat) => { pass.set_pipeline(&flat.translucent); @@ -3824,6 +4026,15 @@ impl Renderer { ); } } + if pack && scaled.is_some() { + self.world_post.build_gbuffer( + &self.queue, + &mut encoder, + &pack_uniform, + frame.shader.eye_light, + frame.shader.rain, + ); + } if let (true, Some((color, depth)), Some(size), Some(stages)) = (pack, &scaled, self.world_post.size(), self.pack.as_mut()) { @@ -3837,6 +4048,7 @@ impl Renderer { size, &self.world_post, pack_uniform, + frame.shader.eye_light, ), Pack::Java(stages) => stages.run( &self.device, diff --git a/crates/horizon-client/src/gfx/java_stages.rs b/crates/horizon-client/src/gfx/java_stages.rs index e9f8ddbb1..8091b0703 100644 --- a/crates/horizon-client/src/gfx/java_stages.rs +++ b/crates/horizon-client/src/gfx/java_stages.rs @@ -1,17 +1,20 @@ //! 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) 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 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. +//! 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 +//! 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 glam::{Mat3, Mat4, Vec3, Vec4}; use horizon_shaderpack::pipeline::TargetSettings; use horizon_shaderpack::pipeline::{Directives, Program, target_index}; +use horizon_shaderpack::properties::Blend; use horizon_shaderpack::uniforms::{CustomUniforms, SmoothFloat, UniformState}; use std::collections::{BTreeMap, BTreeSet, HashMap}; @@ -35,6 +38,7 @@ const MAX_ATTRIBUTES: usize = 8; const BLIT: &str = r#" @group(0) @binding(0) var color: texture_2d; @group(0) @binding(1) var depth: texture_depth_2d; +@group(0) @binding(2) var opaque_depth: texture_depth_2d; @vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f { @@ -45,15 +49,20 @@ fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f { struct World { @location(0) color: vec4f, @location(1) depth: vec4f, + @location(2) opaque_depth: vec4f, } -// The world's colour and depth, upside down into GL's layout; Horizon's -// reversed depth (near 1) as GL's (near 0). +// The world's colour, depth and pre-translucent depth, upside down into GL's +// layout; Horizon's reversed depth (near 1) as GL's (near 0). @fragment fn world_in(@builtin(position) p: vec4f) -> World { let size = textureDimensions(depth); let xy = vec2u(u32(p.x), size.y - 1u - u32(p.y)); - return World(textureLoad(color, xy, 0), vec4f(1.0 - textureLoad(depth, xy, 0))); + return World( + textureLoad(color, xy, 0), + vec4f(1.0 - textureLoad(depth, xy, 0)), + vec4f(1.0 - textureLoad(opaque_depth, xy, 0)), + ); } // A target, upside down back into wgpu's layout. @@ -64,6 +73,42 @@ fn present(@builtin(position) p: vec4f) -> @location(0) vec4f { } "#; +/// Convert a GL `Blend` override from `shaders.properties` into a wgpu `BlendState`. +fn blend_state(blend: &Blend) -> Option { + let Blend::Factors(factors) = blend else { + return None; + }; + let map_factor = |name: &str| -> wgpu::BlendFactor { + use wgpu::BlendFactor as B; + match name { + "ZERO" => B::Zero, + "ONE" => B::One, + "SRC_COLOR" => B::Src, + "ONE_MINUS_SRC_COLOR" => B::OneMinusSrc, + "DST_COLOR" => B::Dst, + "ONE_MINUS_DST_COLOR" => B::OneMinusDst, + "SRC_ALPHA" => B::SrcAlpha, + "ONE_MINUS_SRC_ALPHA" => B::OneMinusSrcAlpha, + "DST_ALPHA" => B::DstAlpha, + "ONE_MINUS_DST_ALPHA" => B::OneMinusDstAlpha, + "SRC_ALPHA_SATURATE" => B::SrcAlphaSaturated, + _ => B::One, + } + }; + Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: map_factor(&factors[0]), + dst_factor: map_factor(&factors[1]), + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: map_factor(&factors[2]), + dst_factor: map_factor(&factors[3]), + operation: wgpu::BlendOperation::Add, + }, + }) +} + /// A wgpu format for each of Iris's (`InternalTextureFormat`), renderable /// everywhere: 8-bit unsigned normalized formats stay, signed normalized, /// 16-bit and packed float ones become half floats, integer ones 32-bit. @@ -123,11 +168,12 @@ struct Target { #[derive(Clone, Copy, Debug, PartialEq)] enum Source { Target(u32), - /// `depthtex0..2`: the world's depth. + /// `depthtex0` / `gdepthtex`: the world's depth (including translucent water). Depth, + /// `depthtex1` / `depthtex2`: the opaque world's depth (before translucent water). + OpaqueDepth, Noise, - /// `shadowtex*`: no shadow map yet, so a far depth (nothing in shadow); - /// also Distant Horizons' and Voxy's depth, as without those mods. + /// `shadowtex*`: directional sun/moon shadow map depth (or far depth for DH/Voxy). Shadow, /// Anything else (`shadowcolor*`, custom textures): white or black. Blank(bool), @@ -135,7 +181,8 @@ enum Source { fn source(name: &str) -> Source { match name { - "depthtex0" | "depthtex1" | "depthtex2" | "gdepthtex" => Source::Depth, + "depthtex0" | "gdepthtex" => Source::Depth, + "depthtex1" | "depthtex2" => Source::OpaqueDepth, "noisetex" => Source::Noise, "shadowtex0" | "shadowtex1" | "shadow" | "watershadow" => Source::Shadow, n if n.starts_with("dhDepthTex") || n.starts_with("vxDepthTex") => Source::Shadow, @@ -146,6 +193,7 @@ fn source(name: &str) -> Source { /// A sampler of a pass: its texture and sampler bindings. struct SamplerBinding { + name: String, source: Source, dimension: wgpu::TextureViewDimension, /// `isampler` (true) or `usampler` (false). @@ -183,6 +231,7 @@ struct Common { repeat: wgpu::Sampler, compare: wgpu::Sampler, noise: wgpu::TextureView, + custom_textures: BTreeMap, /// Full-screen triangle data per attribute kind (see `PassGpu::attributes`). vertices: [wgpu::Buffer; 4], world_layout: wgpu::BindGroupLayout, @@ -196,6 +245,7 @@ struct Bound { size: [u32; 2], targets: BTreeMap, depth: wgpu::TextureView, + opaque_depth: wgpu::TextureView, /// Per pass, then `final`. groups: Vec, world_in: (wgpu::RenderPipeline, wgpu::BindGroup), @@ -217,6 +267,7 @@ struct Folder { passes: Vec, final_pass: Option, directives: Directives, + shadow_enabled: bool, } pub struct JavaStages { @@ -234,9 +285,25 @@ pub struct JavaStages { uniform_state: UniformState, /// `eyeBrightnessSmooth`, block then sky. eye_smooth: [SmoothFloat; 2], + /// `wetness`, smoothed with `wetnessHalflife` / `drynessHalflife`. + 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, @@ -245,7 +312,7 @@ impl JavaStages { id: &str, pack: &JavaPasses, ) -> Result { - let common = Common::new(device, queue); + let common = Common::new(device, queue, &pack.custom_textures); let folder_for = [-1, 0, 1].map(|d| pack.folder_for(d)); let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); let folders = pack @@ -275,6 +342,7 @@ impl JavaStages { passes, final_pass, directives: plan.directives, + shadow_enabled: plan.shadow_enabled, }) }) .collect::, _>>()?; @@ -295,6 +363,8 @@ impl JavaStages { uniforms: pack.uniforms.clone(), uniform_state: UniformState::default(), eye_smooth: [SmoothFloat::default(); 2], + wetness_smooth: SmoothFloat::default(), + center_depth_smooth: SmoothFloat::default(), }) } @@ -335,10 +405,26 @@ 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); } + inputs.wetness = self.wetness_smooth.update( + frame.weather[0], + directives.wetness_half_life, + 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) @@ -496,10 +582,28 @@ impl JavaStages { size, ) .create_view(&Default::default()); + let opaque_depth = texture( + "Java shader pack opaque depth", + wgpu::TextureFormat::R32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + size, + ) + .create_view(&Default::default()); let mut blank = Vec::new(); let groups = all .clone() - .map(|pass| pass.bind(device, queue, &targets, &depth, &self.common, &mut blank)) + .map(|pass| { + pass.bind( + device, + queue, + &targets, + &depth, + &opaque_depth, + post, + &self.common, + &mut blank, + ) + }) .collect(); // The world goes into colortex0's side the gbuffers would write. @@ -509,7 +613,11 @@ impl JavaStages { &self.common, &self.common.world_layout, "world_in", - &[colortex0.format, wgpu::TextureFormat::R32Float], + &[ + colortex0.format, + wgpu::TextureFormat::R32Float, + wgpu::TextureFormat::R32Float, + ], ); let world_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("Java shader pack world"), @@ -523,6 +631,10 @@ impl JavaStages { binding: 1, resource: wgpu::BindingResource::TextureView(world_depth), }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(post.opaque_depth()), + }, ], }); @@ -571,6 +683,7 @@ impl JavaStages { size, targets, depth, + opaque_depth, groups, world_in: (world_pipeline, world_group), world_alt: plan.flipped_after_prepare.contains(&0), @@ -593,6 +706,7 @@ fn world_in(encoder: &mut wgpu::CommandEncoder, bound: &Bound) { let attachments = [ Some(color_attachment(side, None)), Some(color_attachment(&bound.depth, None)), + Some(color_attachment(&bound.opaque_depth, None)), ]; let mut render = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Java shader pack world"), @@ -666,7 +780,11 @@ fn blit_pipeline( } impl Common { - fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self { + fn new( + device: &wgpu::Device, + queue: &wgpu::Queue, + custom_map: &BTreeMap)>, + ) -> Self { let sampler = |filter, address, compare| { device.create_sampler(&wgpu::SamplerDescriptor { label: Some("Java shader pack"), @@ -714,6 +832,34 @@ impl Common { }, 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. @@ -754,12 +900,14 @@ impl Common { repeat: sampler(Linear, Repeat, None), compare: sampler(Linear, ClampToEdge, Some(wgpu::CompareFunction::LessEqual)), noise: noise.create_view(&Default::default()), + custom_textures, vertices, world_layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("Java shader pack world"), entries: &[ texture_entry(0, unfilterable), texture_entry(1, wgpu::TextureSampleType::Depth), + texture_entry(2, wgpu::TextureSampleType::Depth), ], }), present_layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { @@ -841,6 +989,7 @@ impl PassGpu { .cloned() .unwrap_or_else(|| format!("{sampler}_s")); samplers.push(SamplerBinding { + name: sampler.clone(), source: source(sampler), dimension, signed, @@ -885,7 +1034,7 @@ impl PassGpu { )), ) } - (false, Source::Depth | Source::Shadow) => ( + (false, Source::Depth | Source::OpaqueDepth | Source::Shadow) => ( wgpu::TextureSampleType::Float { filterable: false }, Some(false), ), @@ -979,10 +1128,11 @@ impl PassGpu { // Output location `l` writes target `draw_buffers[l]` (or the screen). let outputs = &program.fragment.interface.outputs; + let pass_blend = program.pass.blend.as_ref().and_then(blend_state); let target_states: Vec> = match screen { Some(format) => vec![Some(wgpu::ColorTargetState { format, - blend: None, + blend: pass_blend, write_mask: if outputs.contains_key(&0) { wgpu::ColorWrites::ALL } else { @@ -994,12 +1144,25 @@ impl PassGpu { .iter() .enumerate() .map(|(l, &i)| { + let format = formats + .get(i as usize) + .copied() + .unwrap_or(wgpu::TextureFormat::Rgba8Unorm); + // Only filterable float/unorm formats support blending. + let can_blend = matches!( + sample_type(format), + wgpu::TextureSampleType::Float { filterable: true } + ); + let buf_blend = program + .pass + .buffer_blends + .iter() + .find(|(idx, _)| *idx == i) + .map(|(_, b)| blend_state(b)) + .unwrap_or(pass_blend); Some(wgpu::ColorTargetState { - format: formats - .get(i as usize) - .copied() - .unwrap_or(wgpu::TextureFormat::Rgba8Unorm), - blend: None, + format, + blend: if can_blend { buf_blend } else { None }, write_mask: if outputs.contains_key(&(l as u32)) { wgpu::ColorWrites::ALL } else { @@ -1068,37 +1231,54 @@ impl PassGpu { } /// The pass's bind group over `targets`. + #[allow(clippy::too_many_arguments)] fn bind( &self, device: &wgpu::Device, queue: &wgpu::Queue, 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 = match (s.compare, s.source) { - (true, _) => blank_view(device, queue, blank, s, BlankKind::FarDepth), - (false, Source::Target(i)) if s.dimension == wgpu::TextureViewDimension::D2 => { - match targets.get(&i) { - Some(t) if self.reads_alt.contains(&i) => t.alt_view.clone(), - Some(t) => t.main_view.clone(), - None => blank_view(device, queue, blank, s, BlankKind::Color(false)), + let view = if let Some(custom) = common + .custom_textures + .get(&s.name) + .filter(|_| !s.compare && s.dimension == wgpu::TextureViewDimension::D2) + { + 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) { + Some(t) if self.reads_alt.contains(&i) => t.alt_view.clone(), + Some(t) => t.main_view.clone(), + None => blank_view(device, queue, blank, s, BlankKind::Color(false)), + } } + (false, Source::Depth) if s.dimension == wgpu::TextureViewDimension::D2 => { + depth.clone() + } + (false, Source::OpaqueDepth) + if s.dimension == wgpu::TextureViewDimension::D2 => + { + opaque_depth.clone() + } + (false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far), + (false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => { + common.noise.clone() + } + (false, Source::Blank(white)) => { + blank_view(device, queue, blank, s, BlankKind::Color(white)) + } + _ => blank_view(device, queue, blank, s, BlankKind::Color(false)), } - (false, Source::Depth) if s.dimension == wgpu::TextureViewDimension::D2 => { - depth.clone() - } - (false, Source::Shadow) => blank_view(device, queue, blank, s, BlankKind::Far), - (false, Source::Noise) if s.dimension == wgpu::TextureViewDimension::D2 => { - common.noise.clone() - } - (false, Source::Blank(white)) => { - blank_view(device, queue, blank, s, BlankKind::Color(white)) - } - _ => blank_view(device, queue, blank, s, BlankKind::Color(false)), }; let sampler = match (s.compare, s.source) { _ if s.shared.is_some() => match s.shared.as_deref() { @@ -1110,7 +1290,7 @@ impl PassGpu { (true, _) => &common.compare, _ if s.signed.is_some() => &common.nearest, (false, Source::Noise) => &common.repeat, - (false, Source::Depth | Source::Shadow) => &common.nearest, + (false, Source::Depth | Source::OpaqueDepth | Source::Shadow) => &common.nearest, (false, Source::Target(i)) => { match targets.get(&i).map(|t| sample_type(t.format)) { Some(wgpu::TextureSampleType::Float { filterable: true }) | None => { @@ -1432,6 +1612,8 @@ 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], @@ -1442,6 +1624,10 @@ struct Inputs { /// `eyeBrightness` and `eyeBrightnessSmooth`: block, sky light × 16. eye: [f32; 2], eye_smooth: [f32; 2], + wetness: f32, + center_depth_smooth: f32, + ambient_occlusion_level: f32, + shadow_map_resolution: f32, /// `CelestialUniforms`, in view space. sun_position: Vec3, moon_position: Vec3, @@ -1490,6 +1676,8 @@ 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), @@ -1499,6 +1687,10 @@ impl Inputs { frame: *frame, 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, @@ -1591,27 +1783,42 @@ impl Inputs { }), "upPosition" => vec3(self.up_position), "moonPhase" => vec![f.moon[3]], - "rainStrength" | "wetness" => vec![f.weather[0]], + "rainStrength" => vec![f.weather[0]], + "wetness" => vec![self.wetness], "thunderStrength" => vec![f.weather[1]], "fogColor" => f.fog_color[..3].to_vec(), "skyColor" => f.sky_color[..3].to_vec(), "isEyeInWater" => vec![f.camera_state[0]], "nightVision" => vec![f.camera_state[1]], - "darknessFactor" => vec![f.camera_state[2]], + "darknessFactor" | "darknessLightFactor" => vec![f.camera_state[2]], + "blindness" => vec![f.camera_state[3]], "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" - | "shadowModelViewInverse" - | "shadowProjection" - | "shadowProjectionInverse" => mat(Mat4::IDENTITY), + "shadowModelView" => mat(self.shadow_view), + "shadowModelViewInverse" => mat(self.shadow_view.inverse()), + "shadowProjection" => mat(self.shadow_projection), + "shadowProjectionInverse" => mat(self.shadow_projection.inverse()), _ => return None, }) } @@ -1651,6 +1858,7 @@ mod tests { assert_eq!(source("colortex4"), Source::Target(4)); assert_eq!(source("gaux1"), Source::Target(4)); assert_eq!(source("gdepthtex"), Source::Depth); + assert_eq!(source("depthtex1"), Source::OpaqueDepth); assert_eq!(source("shadowtex1"), Source::Shadow); assert_eq!(source("dhDepthTex0"), Source::Shadow); assert_eq!(source("shadowcolor0"), Source::Blank(true)); diff --git a/crates/horizon-client/src/gfx/pack_stages.rs b/crates/horizon-client/src/gfx/pack_stages.rs index 87d22d07d..08a6b9aea 100644 --- a/crates/horizon-client/src/gfx/pack_stages.rs +++ b/crates/horizon-client/src/gfx/pack_stages.rs @@ -1,9 +1,12 @@ -//! A Horizon shader pack on the GPU (docs/shader-packs.md): each `composite` -//! stage is one full-screen pass that reads the world's colour and depth and -//! the previous stage's output and writes its own target; the last target -//! goes to the screen through `world_post` (copy or FXAA) under the hand and -//! HUD. Only exists while a pack is selected. -use crate::shader_pack::{ShaderPack, VERTEX_ENTRY}; +//! A Horizon shader pack on the GPU (docs/shader-packs.md): each stage +//! (`shadow`, `gbuffer`, `deferred`, `composite`, `final`) is a full-screen +//! pass that reads the world's colour, depth, opaque depth, G-buffer normals +//! and materials, shadow map, noise texture and the previous stage's output, +//! and writes its own target; the last target goes to the screen through +//! `world_post` (copy or FXAA) under the hand and HUD. Only exists while a +//! pack is selected. +use crate::shader_pack::{ShaderPack, StageKind, VERTEX_ENTRY}; +use horizon_shaderpack::uniforms::SmoothFloat; /// The `Frame` uniform of the prelude (`shader_pack_prelude.wgsl`). #[repr(C)] @@ -27,10 +30,29 @@ pub struct FrameUniform { pub dimension: [f32; 4], } +/// The API 2 `FrameExt` uniform of the prelude (`shader_pack_prelude.wgsl`). +#[repr(C)] +#[derive(Clone, Copy, Default, bytemuck::Pod, bytemuck::Zeroable)] +pub struct FrameExtUniform { + pub previous_view: [[f32; 4]; 4], + pub previous_projection: [[f32; 4]; 4], + pub shadow_view: [[f32; 4]; 4], + pub shadow_projection: [[f32; 4]; 4], + pub shadow_inverse_view: [[f32; 4]; 4], + pub shadow_inverse_projection: [[f32; 4]; 4], + pub previous_camera: [f32; 4], + pub shadow_params: [f32; 4], + pub environment: [f32; 4], +} + +const NOISE_SIZE: u32 = 256; + struct Pass { pipeline: wgpu::RenderPipeline, scale: f32, + target_format: wgpu::TextureFormat, uniform: wgpu::Buffer, + uniform_ext: wgpu::Buffer, } /// A stage's output and the bindings that read the world into it. struct Target { @@ -41,24 +63,43 @@ struct Target { pub struct PackStages { pub id: String, + pub needs_shadow: bool, + pub shadow_res: u32, + pub shadow_dist: f32, layout: wgpu::BindGroupLayout, linear: wgpu::Sampler, nearest: wgpu::Sampler, + repeat: wgpu::Sampler, + shadow_sampler: wgpu::Sampler, + noise_view: wgpu::TextureView, passes: Vec, - format: wgpu::TextureFormat, /// Built for this world target size. targets: Vec, /// `world_post`'s bindings of the last stage's output. output: Option, world_size: [u32; 2], + shadow_size: u32, started: std::time::Instant, + last: Option, frames: u32, + previous: Option<([[f32; 4]; 4], [[f32; 4]; 4], [f32; 3])>, + wetness: SmoothFloat, +} + +fn stage_format(name: Option<&str>, default: wgpu::TextureFormat) -> wgpu::TextureFormat { + match name.map(str::to_lowercase).as_deref() { + Some("rgba16float" | "rgba16f") => wgpu::TextureFormat::Rgba16Float, + Some("rgba8unorm" | "rgba8" | "rgba") => wgpu::TextureFormat::Rgba8Unorm, + Some("rgb10a2unorm" | "rgb10_a2") => wgpu::TextureFormat::Rgb10a2Unorm, + _ => default, + } } impl PackStages { /// The pipelines of a loaded (already validated) pack, or wgpu's error. pub fn new( device: &wgpu::Device, + queue: &wgpu::Queue, format: wgpu::TextureFormat, pack: &ShaderPack, ) -> Result { @@ -79,6 +120,16 @@ impl PackStages { ty: wgpu::BindingType::Sampler(ty), count: None, }; + let uniform_entry = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }; let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("Shader pack stage"), entries: &[ @@ -87,16 +138,15 @@ impl PackStages { texture(2, float), sampler(3, wgpu::SamplerBindingType::Filtering), sampler(4, wgpu::SamplerBindingType::NonFiltering), - wgpu::BindGroupLayoutEntry { - binding: 5, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: None, - }, + uniform_entry(5), + uniform_entry(6), + texture(7, float), + texture(8, float), + texture(9, wgpu::TextureSampleType::Depth), + texture(10, wgpu::TextureSampleType::Depth), + sampler(11, wgpu::SamplerBindingType::Comparison), + texture(12, float), + sampler(13, wgpu::SamplerBindingType::Filtering), ], }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -106,10 +156,18 @@ impl PackStages { }); let constants = pack.constants(); let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let stage_count = pack.stages.len(); let passes = pack .stages .iter() - .map(|stage| { + .enumerate() + .map(|(idx, stage)| { + let is_last = idx + 1 == stage_count || stage.kind == StageKind::Final; + let target_format = if is_last { + format + } else { + stage_format(stage.format.as_deref(), format) + }; let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(&stage.file), source: wgpu::ShaderSource::Wgsl(stage.source.as_str().into()), @@ -140,7 +198,7 @@ impl PackStages { ..Default::default() }, targets: &[Some(wgpu::ColorTargetState { - format, + format: target_format, blend: None, write_mask: wgpu::ColorWrites::ALL, })], @@ -151,38 +209,110 @@ impl PackStages { Pass { pipeline, scale: stage.scale, + target_format, uniform: device.create_buffer(&wgpu::BufferDescriptor { label: Some("Shader pack frame"), size: std::mem::size_of::() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }), + uniform_ext: device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Shader pack frame ext"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }), } }) .collect(); if let Some(error) = pollster::block_on(scope.pop()) { return Err(error.to_string()); } - let sampler = |filter| { + let make_sampler = |filter, address, compare| { device.create_sampler(&wgpu::SamplerDescriptor { label: Some("Shader pack"), + address_mode_u: address, + address_mode_v: address, + address_mode_w: address, mag_filter: filter, min_filter: filter, + compare, ..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_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); Ok(Self { id: pack.id.clone(), + needs_shadow: pack.needs_shadow(), + shadow_res, + shadow_dist, layout, - linear: sampler(wgpu::FilterMode::Linear), - nearest: sampler(wgpu::FilterMode::Nearest), + linear: make_sampler( + wgpu::FilterMode::Linear, + wgpu::AddressMode::ClampToEdge, + None, + ), + nearest: make_sampler( + wgpu::FilterMode::Nearest, + wgpu::AddressMode::ClampToEdge, + None, + ), + repeat: make_sampler(wgpu::FilterMode::Linear, wgpu::AddressMode::Repeat, None), + shadow_sampler: make_sampler( + wgpu::FilterMode::Linear, + wgpu::AddressMode::ClampToEdge, + Some(wgpu::CompareFunction::GreaterEqual), + ), + noise_view: noise_tex.create_view(&Default::default()), passes, - format, targets: Vec::new(), output: None, world_size: [0, 0], + shadow_size: 0, started: std::time::Instant::now(), + last: None, frames: 0, + previous: None, + wetness: SmoothFloat::default(), }) } @@ -199,9 +329,14 @@ impl PackStages { size: [u32; 2], post: &super::world_post::Post, mut uniform: FrameUniform, + eye_light: [u8; 2], ) -> &wgpu::BindGroup { - if self.world_size != size || self.targets.len() != self.passes.len() { + if self.world_size != size + || self.shadow_size != post.shadow_resolution + || self.targets.len() != self.passes.len() + { self.world_size = size; + self.shadow_size = post.shadow_resolution; self.targets.clear(); for pass in &self.passes { let target_size = size.map(|v| ((v as f32 * pass.scale).round() as u32).max(1)); @@ -216,7 +351,7 @@ impl PackStages { mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, - format: self.format, + format: pass.target_format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], @@ -251,6 +386,38 @@ impl PackStages { binding: 5, resource: pass.uniform.as_entire_binding(), }, + wgpu::BindGroupEntry { + binding: 6, + resource: pass.uniform_ext.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 7, + resource: wgpu::BindingResource::TextureView(post.normal()), + }, + wgpu::BindGroupEntry { + binding: 8, + resource: wgpu::BindingResource::TextureView(post.material()), + }, + wgpu::BindGroupEntry { + binding: 9, + resource: wgpu::BindingResource::TextureView(post.opaque_depth()), + }, + wgpu::BindGroupEntry { + binding: 10, + resource: wgpu::BindingResource::TextureView(post.shadow_depth()), + }, + wgpu::BindGroupEntry { + binding: 11, + resource: wgpu::BindingResource::Sampler(&self.shadow_sampler), + }, + wgpu::BindGroupEntry { + binding: 12, + resource: wgpu::BindingResource::TextureView(&self.noise_view), + }, + wgpu::BindGroupEntry { + binding: 13, + resource: wgpu::BindingResource::Sampler(&self.repeat), + }, ], }); self.targets.push(Target { @@ -262,6 +429,42 @@ impl PackStages { let last = &self.targets.last().expect("a pack has a stage").view; self.output = Some(post.bind(device, last)); } + let now = std::time::Instant::now(); + let dt = self.last.map_or(0.0, |t| (now - t).as_secs_f32()); + self.last = Some(now); + let wet = self.wetness.update(uniform.weather[0], 60.0, 120.0, dt); + let cam = [ + uniform.camera_position[0], + uniform.camera_position[1], + uniform.camera_position[2], + ]; + let (prev_view, prev_proj, prev_cam) = + self.previous + .unwrap_or((uniform.view, uniform.projection, cam)); + self.previous = Some((uniform.view, uniform.projection, cam)); + let shadow_view = post.shadow_view; + let shadow_proj = post.shadow_proj; + let ext = FrameExtUniform { + previous_view: prev_view, + previous_projection: prev_proj, + shadow_view: shadow_view.to_cols_array_2d(), + shadow_projection: shadow_proj.to_cols_array_2d(), + shadow_inverse_view: shadow_view.inverse().to_cols_array_2d(), + shadow_inverse_projection: shadow_proj.inverse().to_cols_array_2d(), + previous_camera: [prev_cam[0], prev_cam[1], prev_cam[2], dt], + shadow_params: [ + post.shadow_resolution as f32, + post.shadow_distance, + 0.0, + if post.shadow_active { 1.0 } else { 0.0 }, + ], + environment: [ + f32::from(eye_light[0]) * 16.0, + f32::from(eye_light[1]) * 16.0, + wet, + uniform.view_params[2] * 0.5, + ], + }; uniform.time[0] = self.started.elapsed().as_secs_f32(); uniform.time[1] = self.frames as f32; self.frames = self.frames.wrapping_add(1); @@ -269,6 +472,7 @@ impl PackStages { let [w, h] = target.size.map(|v| v as f32); uniform.resolution = [w, h, 1.0 / w, 1.0 / h]; queue.write_buffer(&pass.uniform, 0, bytemuck::bytes_of(&uniform)); + queue.write_buffer(&pass.uniform_ext, 0, bytemuck::bytes_of(&ext)); let attachments = [Some(wgpu::RenderPassColorAttachment { view: &target.view, resolve_target: None, diff --git a/crates/horizon-client/src/gfx/world_post.rs b/crates/horizon-client/src/gfx/world_post.rs index 797ee03b7..69d95aae6 100644 --- a/crates/horizon-client/src/gfx/world_post.rs +++ b/crates/horizon-client/src/gfx/world_post.rs @@ -1,26 +1,148 @@ -//! Resolution scale and FXAA (Horizon settings): the world renders into its -//! own target at the scaled size, then one full-screen pass copies or -//! anti-aliases it onto the screen, under the hand and HUD. A shader pack -//! also needs the target (its stages read the world's colour and depth). +//! 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. +//! //! With none of them on, the world renders straight to the screen as before. +use super::pack_stages::FrameUniform; +use glam::{Mat4, Vec3, Vec4}; + +const GBUFFER_WGSL: &str = r#" +struct GbufferParams { + inverse_view: mat4x4, + inverse_projection: mat4x4, + resolution: vec4, + // x: eye block light (0..1), y: eye sky light (0..1), z: wetness (0..1), w: sun elevation + env: vec4, +} + +@group(0) @binding(0) var world_color: texture_2d; +@group(0) @binding(1) var world_depth: texture_depth_2d; +@group(0) @binding(2) var opaque_depth: texture_depth_2d; +@group(0) @binding(3) var nearest_sampler: sampler; +@group(0) @binding(4) var params: GbufferParams; + +struct VsOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +} + +@vertex +fn vs_gbuffer(@builtin(vertex_index) i: u32) -> VsOut { + let p = vec2(f32((i << 1u) & 2u), f32(i & 2u)); + var out: VsOut; + out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0); + out.uv = vec2(p.x, 1.0 - p.y); + return out; +} + +struct GbufferOut { + @location(0) normal: vec4, + @location(1) material: vec4, +} + +fn world_pos(uv: vec2, d: f32) -> vec3 { + let v = params.inverse_projection * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, d, 1.0); + let view = v.xyz / max(v.w, 1e-6); + return (params.inverse_view * vec4(view, 1.0)).xyz; +} + +@fragment +fn fs_gbuffer(in: VsOut) -> GbufferOut { + let d_all = textureSampleLevel(world_depth, nearest_sampler, in.uv, 0); + let d_opq = textureSampleLevel(opaque_depth, nearest_sampler, in.uv, 0); + let color = textureSampleLevel(world_color, nearest_sampler, in.uv, 0.0); + var out: GbufferOut; + if d_all <= 0.0 && d_opq <= 0.0 { + out.normal = vec4(0.5, 1.0, 0.5, 0.0); + out.material = vec4(0.0, params.env.y, 0.0, 1.0); + return out; + } + let d = select(d_all, d_opq, d_opq > 0.0); + let step_uv = params.resolution.zw; + let p0 = world_pos(in.uv, d); + let uv_r = clamp(in.uv + vec2(step_uv.x, 0.0), vec2(0.0), vec2(1.0)); + let uv_l = clamp(in.uv - vec2(step_uv.x, 0.0), vec2(0.0), vec2(1.0)); + let uv_d = clamp(in.uv + vec2(0.0, step_uv.y), vec2(0.0), vec2(1.0)); + let uv_u = clamp(in.uv - vec2(0.0, step_uv.y), vec2(0.0), vec2(1.0)); + let dr = textureSampleLevel(opaque_depth, nearest_sampler, uv_r, 0); + let dl = textureSampleLevel(opaque_depth, nearest_sampler, uv_l, 0); + let dd = textureSampleLevel(opaque_depth, nearest_sampler, uv_d, 0); + let du = textureSampleLevel(opaque_depth, nearest_sampler, uv_u, 0); + let dx = select(world_pos(uv_r, dr) - p0, p0 - world_pos(uv_l, dl), abs(dl - d) < abs(dr - d)); + let dy = select(world_pos(uv_d, dd) - p0, p0 - world_pos(uv_u, du), abs(du - d) < abs(dd - d)); + let raw_n = cross(dy, dx); + let n_len = length(raw_n); + let n = select(vec3(0.0, 1.0, 0.0), raw_n / max(n_len, 1e-6), n_len > 1e-6); + // Reversed depth: closer translucent geometry has larger depth than opaque geometry. + let is_translucent = select(0.0, 1.0, d_all > d_opq + 1e-5); + let luma = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722)); + let block_light = clamp(max(params.env.x, smoothstep(0.65, 0.98, luma)), 0.0, 1.0); + let roughness = select(clamp(0.85 - params.env.z * 0.45, 0.1, 1.0), 0.05, is_translucent > 0.5); + out.normal = vec4(n * 0.5 + 0.5, 1.0); + out.material = vec4(block_light, params.env.y, is_translucent, roughness); + return out; +} +"#; + +#[repr(C)] +#[derive(Clone, Copy, Default, bytemuck::Pod, bytemuck::Zeroable)] +struct GbufferUniform { + inverse_view: [[f32; 4]; 4], + inverse_projection: [[f32; 4]; 4], + resolution: [f32; 4], + env: [f32; 4], +} + struct WorldTarget { size: [u32; 2], color: wgpu::TextureView, + depth_tex: wgpu::Texture, depth: wgpu::TextureView, + opaque_depth_tex: wgpu::Texture, + opaque_depth: wgpu::TextureView, + normal: wgpu::TextureView, + material: wgpu::TextureView, + gbuffer_group: wgpu::BindGroup, group: wgpu::BindGroup, + opaque_captured: bool, +} + +struct ShadowTarget { + resolution: u32, + depth: wgpu::TextureView, } pub struct Post { layout: wgpu::BindGroupLayout, sampler: wgpu::Sampler, + nearest: wgpu::Sampler, copy: wgpu::RenderPipeline, fxaa: wgpu::RenderPipeline, + gbuffer_layout: wgpu::BindGroupLayout, + gbuffer_pipeline: wgpu::RenderPipeline, + gbuffer_uniform: wgpu::Buffer, format: wgpu::TextureFormat, /// World resolution relative to the window (0.5..=2.0). pub scale: f32, pub antialias: bool, target: Option, + shadow: Option, + fallback_shadow: wgpu::TextureView, + fallback_color: wgpu::TextureView, + pub shadow_view: Mat4, + pub shadow_proj: Mat4, + pub shadow_distance: f32, + pub shadow_resolution: u32, + pub shadow_active: bool, } impl Post { @@ -88,17 +210,169 @@ impl Post { min_filter: wgpu::FilterMode::Linear, ..Default::default() }); + let nearest = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Horizon post nearest"), + mag_filter: wgpu::FilterMode::Nearest, + min_filter: wgpu::FilterMode::Nearest, + ..Default::default() + }); + + let gbuffer_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Horizon gbuffer"), + source: wgpu::ShaderSource::Wgsl(GBUFFER_WGSL.into()), + }); + let gbuffer_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Horizon gbuffer layout"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Depth, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Depth, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::NonFiltering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 4, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + let gbuffer_pipe_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Horizon gbuffer"), + bind_group_layouts: &[Some(&gbuffer_layout)], + ..Default::default() + }); + let gbuffer_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Horizon gbuffer"), + layout: Some(&gbuffer_pipe_layout), + vertex: wgpu::VertexState { + module: &gbuffer_shader, + entry_point: Some("vs_gbuffer"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &gbuffer_shader, + entry_point: Some("fs_gbuffer"), + compilation_options: Default::default(), + targets: &[ + Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::Rgba8Unorm, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + }), + Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::Rgba8Unorm, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + }), + ], + }), + multiview_mask: None, + cache: None, + }); + let gbuffer_uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Horizon gbuffer uniform"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let fallback_shadow = device + .create_texture(&wgpu::TextureDescriptor { + label: Some("Horizon fallback shadow"), + size: wgpu::Extent3d { + width: 1, + height: 1, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Depth32Float, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + .create_view(&Default::default()); + let fallback_color = device + .create_texture(&wgpu::TextureDescriptor { + label: Some("Horizon fallback gbuffer"), + size: wgpu::Extent3d { + width: 1, + height: 1, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + .create_view(&Default::default()); Self { copy: pipeline("fs_copy"), fxaa: pipeline("fs_fxaa"), layout, sampler, + nearest, + gbuffer_layout, + gbuffer_pipeline, + gbuffer_uniform, format, scale: 1.0, antialias: false, target: None, + shadow: None, + fallback_shadow, + fallback_color, + shadow_view: Mat4::IDENTITY, + shadow_proj: Mat4::IDENTITY, + shadow_distance: 128.0, + shadow_resolution: 2048, + shadow_active: false, } } + /// The world's colour and depth targets this frame, or `None` to draw /// it straight to the screen. `pack`: a shader pack runs this frame. pub fn prepare( @@ -109,6 +383,7 @@ impl Post { ) -> Option<(wgpu::TextureView, wgpu::TextureView)> { if self.scale == 1.0 && !self.antialias && !pack { self.target = None; + self.shadow_active = false; return None; } let size = window.map(|v| ((v as f32 * self.scale).round() as u32).clamp(1, 8192)); @@ -118,46 +393,284 @@ impl Post { height: size[1], depth_or_array_layers: 1, }; - let texture = |label, format, usage| { - device - .create_texture(&wgpu::TextureDescriptor { - label: Some(label), - size: extent, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format, - usage, - view_formats: &[], - }) - .create_view(&Default::default()) + let make_tex = |label, format, usage| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: extent, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) }; - let color = texture( + let color = make_tex( "Scaled world", self.format, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, - ); - let depth = texture( + ) + .create_view(&Default::default()); + let depth_tex = make_tex( "Scaled world depth", wgpu::TextureFormat::Depth32Float, - wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_SRC, ); + let depth = depth_tex.create_view(&Default::default()); + let opaque_depth_tex = make_tex( + "Opaque world depth", + wgpu::TextureFormat::Depth32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_DST, + ); + let opaque_depth = opaque_depth_tex.create_view(&Default::default()); + let normal = make_tex( + "World G-buffer normal", + wgpu::TextureFormat::Rgba8Unorm, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + ) + .create_view(&Default::default()); + let material = make_tex( + "World G-buffer material", + wgpu::TextureFormat::Rgba8Unorm, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + ) + .create_view(&Default::default()); + let gbuffer_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Horizon gbuffer"), + layout: &self.gbuffer_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&color), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&depth), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::TextureView(&opaque_depth), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::Sampler(&self.nearest), + }, + wgpu::BindGroupEntry { + binding: 4, + resource: self.gbuffer_uniform.as_entire_binding(), + }, + ], + }); let group = self.bind(device, &color); self.target = Some(WorldTarget { size, color, + depth_tex, depth, + opaque_depth_tex, + opaque_depth, + normal, + material, + gbuffer_group, group, + opaque_captured: false, }); } + if let Some(t) = &mut self.target { + t.opaque_captured = false; + } self.target .as_ref() .map(|t| (t.color.clone(), t.depth.clone())) } + + /// Prepare the directional sun/moon shadow map target and compute its + /// camera-relative orthographic `shadow_view` and `shadow_proj` matrices. + pub fn prepare_shadow( + &mut self, + device: &wgpu::Device, + resolution: u32, + distance: f32, + sun_dir: Vec3, + moon_dir: Vec3, + ) -> &wgpu::TextureView { + let resolution = resolution.clamp(256, 4096); + let distance = distance.clamp(16.0, 512.0); + if self + .shadow + .as_ref() + .is_none_or(|s| s.resolution != resolution) + { + let depth = device + .create_texture(&wgpu::TextureDescriptor { + label: Some("Horizon shadow map"), + size: wgpu::Extent3d { + width: resolution, + height: resolution, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Depth32Float, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + .create_view(&Default::default()); + self.shadow = Some(ShadowTarget { resolution, depth }); + } + let light_dir = if sun_dir.y >= -0.05 { + sun_dir.normalize_or_zero() + } else { + moon_dir.normalize_or_zero() + }; + let dir = if light_dir.length_squared() > 1e-4 { + light_dir + } else { + Vec3::Y + }; + let up = if dir.y.abs() > 0.99 { Vec3::Z } else { Vec3::Y }; + self.shadow_view = Mat4::look_at_rh(dir * distance, Vec3::ZERO, up); + // Reversed-depth orthographic projection for the world's GreaterEqual + // pipelines (near maps to 1.0, far maps to 0.0), and standard 0..1 + // projection for shader sampling. + self.shadow_proj = Mat4::orthographic_rh( + -distance, + distance, + -distance, + distance, + distance * 2.5, + 0.05, + ); + self.shadow_distance = distance; + self.shadow_resolution = resolution; + self.shadow_active = true; + &self.shadow.as_ref().expect("created above").depth + } + + /// Snapshot `world_depth` into `opaque_depth` (`depthtex1`/`depthtex2`) + /// right before translucent water and weather draw. + pub fn capture_opaque_depth(&mut self, encoder: &mut wgpu::CommandEncoder) { + let Some(t) = &mut self.target else { return }; + encoder.copy_texture_to_texture( + t.depth_tex.as_image_copy(), + t.opaque_depth_tex.as_image_copy(), + t.depth_tex.size(), + ); + t.opaque_captured = true; + } + + /// Reconstruct the G-buffer `normal` and `material` textures after the + /// world pass finishes. + pub fn build_gbuffer( + &mut self, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + frame: &FrameUniform, + eye_light: [u8; 2], + wetness: f32, + ) { + let Some(t) = &mut self.target else { return }; + if !t.opaque_captured { + encoder.copy_texture_to_texture( + t.depth_tex.as_image_copy(), + t.opaque_depth_tex.as_image_copy(), + t.depth_tex.size(), + ); + t.opaque_captured = true; + } + let [w, h] = t.size.map(|v| v.max(1) as f32); + let uniform = GbufferUniform { + inverse_view: frame.inverse_view, + inverse_projection: frame.inverse_projection, + resolution: [w, h, 1.0 / w, 1.0 / h], + env: [ + f32::from(eye_light[0]) / 15.0, + f32::from(eye_light[1]) / 15.0, + wetness, + frame.sun[1], + ], + }; + queue.write_buffer(&self.gbuffer_uniform, 0, bytemuck::bytes_of(&uniform)); + let attachments = [ + Some(wgpu::RenderPassColorAttachment { + view: &t.normal, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + }), + Some(wgpu::RenderPassColorAttachment { + view: &t.material, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + }), + ]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Horizon gbuffer"), + color_attachments: &attachments, + ..Default::default() + }); + pass.set_pipeline(&self.gbuffer_pipeline); + pass.set_bind_group(0, &t.gbuffer_group, &[]); + pass.draw(0..3, 0..1); + } + /// The world target's size, once `prepare` made one. pub fn size(&self) -> Option<[u32; 2]> { self.target.as_ref().map(|t| t.size) } + + /// Pre-translucent depth view (`depthtex1`/`depthtex2` / `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`). + 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`). + 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`). + 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 { @@ -175,11 +688,13 @@ impl Post { ], }) } + /// Draw the scaled world onto `screen`. pub fn finish(&self, encoder: &mut wgpu::CommandEncoder, screen: &wgpu::TextureView) { let Some(target) = &self.target else { return }; self.finish_with(encoder, screen, &target.group); } + /// Draw what `group` binds (`bind`) onto `screen`. pub fn finish_with( &self, diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index 514e64a88..fe797af3e 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -112,13 +112,18 @@ pub fn rows(level: Level) -> Vec { "Waits for the display's refresh: no tearing, a little latency.", ); let gui = v(Opt::GuiScale, None, "Size of menus and the HUD."); + let shader_pack = h( + H::ShaderPack, + High, + "Redraws the world with a pack from the shaderpacks folder. Off is vanilla.", + ); let preset = h( H::Preset, None, "Sets the options below together. Changing one makes it Custom.", ); let mut rows = match level { - Level::Simple => vec![preset, render, lod, far, fov, fps, vsync, gui], + Level::Simple => vec![preset, render, lod, far, fov, fps, vsync, gui, shader_pack], Level::Advanced => vec![ Row::Header("Rendering"), render, @@ -246,11 +251,7 @@ pub fn rows(level: Level) -> Vec { None, "Lowers the frame rate when minimised, or idle too.", ), - h( - H::ShaderPack, - High, - "Redraws the world with a pack from the shaderpacks folder. Off is vanilla.", - ), + shader_pack, Row::Header("Preferences"), v(Opt::ViewBobbing, None, "Sways the view while walking."), v(Opt::ChunkFade, None, "Fades newly loaded chunks in."), diff --git a/crates/horizon-client/src/java_pack.rs b/crates/horizon-client/src/java_pack.rs index a5bc2904e..5a37aa223 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 -//! as Iris runs them over its own. Geometry programs (`gbuffers_*`, -//! `shadow`) don't run yet: the world is drawn by Horizon. +//! `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. use horizon_shaderpack::{ JavaPack, pipeline::{Directives, Program, TargetSettings}, @@ -30,8 +30,10 @@ pub struct JavaFolder { pub final_pass: Option, /// The targets whose alternate side holds the frame's last write. pub flipped_at_end: BTreeSet, - /// `sunPathRotation` and `eyeBrightnessHalflife`. + /// `sunPathRotation`, `eyeBrightnessHalflife`, shadow and wetness directives. pub directives: Directives, + /// Whether this dimension's passes read directional shadow maps. + pub shadow_enabled: bool, } /// A loaded Java pack. @@ -41,6 +43,8 @@ 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)>, } impl JavaPasses { @@ -131,11 +135,25 @@ pub fn load( final_pass, flipped_at_end: plan.flipped_at_end, directives: plan.directives, + shadow_enabled: plan.shadow_enabled, }); } if folders.is_empty() { return Err("no deferred, composite or final programs".into()); } + 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 uniforms = properties.custom_uniforms(); for problem in &uniforms.problems { log::warn!("Horizon: shader pack custom uniform {problem}"); @@ -144,6 +162,7 @@ pub fn load( folders, uniforms, sky: properties.sky(), + custom_textures, }) } diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 7937958ea..4ae78da40 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -864,6 +864,8 @@ pub enum Page { Mods, /// The shader packs in `shaderpacks/`: pick one, open the folder. ShaderPacks, + /// Interactive options and profiles for the active shader pack. + ShaderPackOptions, /// Horizon's graphics settings (`graphics_ui`). Graphics, GraphicsAdvanced, @@ -901,6 +903,13 @@ 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, + ShaderPackOption(usize), + ResetShaderPackOptions, } enum WKind { Button { @@ -913,6 +922,11 @@ enum WKind { value: f32, opt: Opt, }, + ShaderOptionSlider { + label: Text, + value: f32, + index: usize, + }, Text { text: Text, color: u32, @@ -954,6 +968,10 @@ 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. + ReloadShaderPack, } /// `SliderableValueSet.applyValueImmediately`: these apply 600 ms after /// the last change (`OptionInstanceSliderButton.delayedApplyAt`). @@ -1011,6 +1029,12 @@ pub struct OptionsUi { pub shader_pack_error: Option<(String, String)>, /// 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(crate) dragging_shader_option: Option, + /// Horizon shader option slider currently being dragged. + pub(crate) hdragging_shader_option: Option, } impl Default for OptionsUi { fn default() -> Self { @@ -1042,6 +1066,9 @@ impl Default for OptionsUi { shader_packs: Default::default(), shader_pack_error: None, agent_status: Vec::new(), + shader_pack_config: None, + dragging_shader_option: None, + hdragging_shader_option: None, } } } @@ -1172,7 +1199,7 @@ impl OptionsUi { } /// Pick shader pack `i` of the folder, or turn it off when it is the /// one running. - pub(crate) fn toggle_shader_pack(&self, s: &mut Settings, i: usize) { + pub(crate) fn toggle_shader_pack(&mut self, s: &mut Settings, i: usize) { let Some((id, Ok(_))) = self.shader_packs.packs.get(i) else { return; }; @@ -1182,6 +1209,39 @@ impl OptionsUi { } else { id.clone() }; + self.sync_shader_pack_config(s); + } + /// Ensure `shader_pack_config` matches `s.horizon.shader_pack`. + pub fn sync_shader_pack_config(&mut self, s: &Settings) { + let id = s.horizon.shader_pack.as_str(); + if id.is_empty() { + self.shader_pack_config = None; + return; + } + if self + .shader_pack_config + .as_ref() + .is_some_and(|cfg| cfg.id == id) + { + return; + } + let dir = 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(); + } + /// 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); + } } pub(crate) fn shader_pack_failed(&self, id: &str) -> bool { self.shader_pack_error @@ -1215,6 +1275,7 @@ impl OptionsUi { Page::Packs => "resourcePack.title", Page::Mods => "Mods", Page::ShaderPacks => "Shader Packs", + Page::ShaderPackOptions => "Shader Pack Settings", Page::Graphics | Page::GraphicsAdvanced => "options.videoTitle", Page::Controller => "Controller Settings", Page::PadBinds => "Controller Binds", @@ -1587,6 +1648,121 @@ impl OptionsUi { None, )); } + let has_settings = !s.horizon.shader_pack.is_empty() + && self.shader_pack_config.as_ref().is_some_and(|c| { + c.id == s.horizon.shader_pack + && (!c.options.is_empty() || !c.profiles.is_empty()) + }); + if has_settings { + rows.push(Row::Buttons( + button( + 0.0, + 0.0, + 150.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, + )); + } + rows + } + Page::ShaderPackOptions => { + let Some(cfg) = &self.shader_pack_config else { + return vec![Row::Header("No configurable options for this shader pack")]; + }; + let screen = cfg.current_screen(); + let mut rows = vec![Row::Note(format!("{} — {}", cfg.id, screen.label))]; + if cfg.active_screen.is_some() { + rows.push(Row::Buttons( + button( + 0.0, + 0.0, + 310.0, + Text::literal("Back to Main Screen"), + Act::ShaderPackBackScreen, + ), + None, + )); + } + let mut widgets = Vec::new(); + for item in &screen.items { + match item { + crate::shader_pack::ScreenItem::Empty => {} + crate::shader_pack::ScreenItem::Profile => { + let label = + Text::literal(format!("Profile: {}", cfg.active_profile_label())); + widgets.push(button(0.0, 0.0, 150.0, label, Act::ShaderPackProfile)); + } + crate::shader_pack::ScreenItem::Subscreen(sub, title) => { + let label = Text::literal(format!("{title}...")); + widgets.push(button( + 0.0, + 0.0, + 150.0, + label, + Act::ShaderPackSubscreen(sub.clone()), + )); + } + crate::shader_pack::ScreenItem::Option(idx) => { + if let Some(opt) = cfg.options.get(*idx) { + let label = Text::literal(format!( + "{}: {}", + opt.label, + opt.display_value() + )); + if let Some(value) = opt.slider_pos() { + widgets.push(Widget { + x: 0.0, + y: 0.0, + w: 150.0, + h: 20.0, + kind: WKind::ShaderOptionSlider { + label, + value, + index: *idx, + }, + list: false, + }); + } else { + widgets.push(button( + 0.0, + 0.0, + 150.0, + label, + Act::ShaderPackOption(*idx), + )); + } + } + } + } + } + let mut iter = widgets.into_iter(); + while let Some(mut first) = iter.next() { + if let Some(second) = iter.next() { + rows.push(Row::Buttons(first, Some(second))); + } else { + first.w = 310.0; + rows.push(Row::Buttons(first, None)); + } + } rows } _ => { @@ -1599,6 +1775,9 @@ impl OptionsUi { fn layout(&mut self, s: &Settings, w: f32, h: f32) -> (Vec, f32, f32, f32) { let mut out = Vec::new(); let page = self.page(); + if matches!(page, Page::ShaderPacks | Page::ShaderPackOptions) { + self.sync_shader_pack_config(s); + } let cx = (w / 2.0).floor(); if matches!(page, Page::Video | Page::Controls | Page::KeyBinds) { self.settings_search.x = cx - 100.0; @@ -2079,6 +2258,9 @@ impl OptionsUi { Page::ShaderPacks => { Some(("Open Shader Pack Folder", Act::OpenShaderPackFolder)) } + Page::ShaderPackOptions => { + Some(("Reset to Defaults", Act::ResetShaderPackOptions)) + } _ => None, }; if let Some((label, act)) = folder { @@ -2248,6 +2430,16 @@ impl OptionsUi { 170.0, )); } + if let WKind::Button { + act: Act::ShaderPackOption(i), + .. + } = &wd.kind + && let Some(cfg) = &self.shader_pack_config + && let Some(opt) = cfg.options.get(*i) + && !opt.description.is_empty() + { + tooltip = Some(atlas.font.split(&Text::literal(&opt.description), 170.0)); + } } match &wd.kind { WKind::Button { label, active, act } => { @@ -2288,6 +2480,31 @@ impl OptionsUi { true, ); } + WKind::ShaderOptionSlider { + label, + value, + index, + } => { + let dragging = self.dragging_shader_option == Some(*index); + if hover + && let Some(cfg) = &self.shader_pack_config + && let Some(opt) = cfg.options.get(*index) + && !opt.description.is_empty() + { + tooltip = Some(atlas.font.split(&Text::literal(&opt.description), 170.0)); + } + ui::slider( + batch, + atlas, + wd.x, + wd.y, + wd.w, + label, + *value, + hover || dragging, + true, + ); + } WKind::Text { text, color, @@ -2502,6 +2719,21 @@ impl OptionsUi { set_slider(opt, s, v); events.push(Event::Changed); } + if let Some(idx) = self.dragging_shader_option + && let Some(wd) = widgets.iter().find(|wd| { + matches!(&wd.kind, WKind::ShaderOptionSlider { index, .. } if *index == idx) + }) + { + 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(); + events.push(Event::Changed); + events.push(Event::ReloadShaderPack); + } return events; } // Controller Binds: a click cancels the wait. @@ -2589,6 +2821,45 @@ 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(); + events.push(Event::Changed); + events.push(Event::ReloadShaderPack); + } + Act::ShaderPackSubscreen(sub) => { + if let Some(cfg) = &mut self.shader_pack_config { + cfg.active_screen = Some(sub); + } + self.scroll = 0.0; + } + Act::ShaderPackBackScreen => { + if let Some(cfg) = &mut self.shader_pack_config { + cfg.active_screen = None; + } + 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(); + 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(); + events.push(Event::Changed); + events.push(Event::ReloadShaderPack); + } Act::None => {} } } @@ -2599,6 +2870,18 @@ impl OptionsUi { set_slider(opt, s, v); events.push(Event::Changed); } + 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(); + events.push(Event::Changed); + events.push(Event::ReloadShaderPack); + } WKind::LanguageRow { code, .. } => { if self.language_choice.as_deref() == Some(code.as_str()) { events.extend(self.back(s)); @@ -2627,7 +2910,9 @@ 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(); + let slider = self.dragging.take().is_some() + || self.dragging_shader_option.take().is_some() + || self.hdragging_shader_option.take().is_some(); let graphics_slider = self.graphics.release(); if slider || graphics_slider { vec![Event::ButtonClick] @@ -2683,6 +2968,14 @@ impl OptionsUi { /// Escape or Done: leave the current page, applying page results. pub fn back(&mut self, s: &mut Settings) -> Vec { let mut events = Vec::new(); + if self.page() == Page::ShaderPackOptions + && let Some(cfg) = &mut self.shader_pack_config + && cfg.active_screen.is_some() + { + cfg.active_screen = None; + self.scroll = 0.0; + return events; + } let page = self.stack.pop().unwrap_or(Page::Main); self.scroll = 0.0; self.scrollbar_drag_y = None; @@ -3123,6 +3416,20 @@ 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(); + assert_eq!( + ui.click( + &mut s, + &atlas, + import_btn.x + 1.0, + import_btn.y + 1.0, + size, + [480, 240], + false, + false, + ), + vec![Event::ButtonClick, Event::ImportShaderPack] + ); 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 f3cf46028..f5a15ca79 100644 --- a/crates/horizon-client/src/shader_pack.rs +++ b/crates/horizon-client/src/shader_pack.rs @@ -1,18 +1,20 @@ //! Horizon shader packs (docs/shader-packs.md): folders in `shaderpacks/` -//! holding a `pack.toml` and WGSL stages. Loading reads the manifest and the +//! holding a `pack.toml` and WGSL stages, plus Java (OptiFine/Iris) shader +//! packs in folders or `.zip` archives. Loading reads the manifest and the //! player's option values, puts the prelude before each stage's source and //! has naga parse and validate it, so a broken pack is reported (file, line, //! column) and never reaches the GPU. +use horizon_shaderpack::{JavaPack, preprocess::Environment, properties::MenuElement}; use serde::Deserialize; use std::{ - collections::BTreeMap, + collections::{BTreeMap, BTreeSet}, fs, path::{Path, PathBuf}, time::SystemTime, }; /// The stage and uniform contract this build provides. -pub const API: u32 = 1; +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"); @@ -29,6 +31,10 @@ struct Manifest { stage: Vec, #[serde(default)] options: BTreeMap, + #[serde(default)] + profiles: BTreeMap>, + #[serde(default)] + textures: BTreeMap, } #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] @@ -51,11 +57,16 @@ struct StageEntry { shader: String, entry: Option, scale: Option, + format: Option, + #[serde(default)] + mipmap: bool, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct OptionEntry { label: Option, + #[serde(default)] + description: String, default: toml::Value, min: Option, max: Option, @@ -63,11 +74,20 @@ struct OptionEntry { values: Option>, } -/// Where a stage runs. Api 1 has `composite` only. +/// Where a stage runs. Api 1 has `composite` only; Api 2 adds `shadow`, +/// `gbuffer`, `deferred` and `final`. #[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 { @@ -79,6 +99,10 @@ pub struct Stage { pub entry: String, /// Target size relative to the world's. pub scale: f32, + /// Optional target format name (`rgba16float`, `rgba8unorm`). + pub format: Option, + /// Whether the previous stage's output is mipmapped before this stage runs. + pub mipmap: bool, } #[derive(Clone, Copy, Debug, PartialEq)] pub enum OptionKind { @@ -91,16 +115,582 @@ pub enum OptionKind { max: f64, step: f64, }, + /// A Java `#define` / `const` string option cycling through `choices` + /// (or drawn as a slider when `slider` is true and choices are numeric). + Choice { + slider: bool, + }, } #[derive(Clone, Debug, PartialEq)] pub struct PackOption { - /// The WGSL `override` it sets. + /// The WGSL `override` or GLSL `#define`/`const` name it sets. pub key: String, pub label: String, + pub description: String, pub kind: OptionKind, pub values: Vec, pub default: f64, pub value: f64, + /// Allowed `(raw_value, display_label)` pairs for `OptionKind::Choice`. + pub choices: Vec<(String, String)>, + pub default_choice: String, + pub current_choice: String, +} + +impl PackOption { + /// Formatted current value for UI buttons and labels. + pub fn display_value(&self) -> String { + match self.kind { + OptionKind::Bool => { + if self.value != 0.0 { + "ON".into() + } else { + "OFF".into() + } + } + OptionKind::Int => format!("{}", self.value.round() as i64), + OptionKind::Float { step, .. } => { + if step >= 1.0 { + format!("{:.0}", self.value) + } else if step >= 0.1 { + format!("{:.1}", self.value) + } else { + format!("{:.2}", self.value) + } + } + OptionKind::Choice { .. } => self + .choices + .iter() + .find(|(raw, _)| *raw == self.current_choice) + .map(|(_, label)| label.clone()) + .unwrap_or_else(|| self.current_choice.clone()), + } + } + + /// Normalized `0.0..=1.0` slider position if this option is a slider. + pub fn slider_pos(&self) -> Option { + match self.kind { + OptionKind::Float { min, max, .. } if max > min => { + Some(((self.value - min) / (max - min)).clamp(0.0, 1.0) as f32) + } + OptionKind::Choice { slider: true } if self.choices.len() > 1 => { + let idx = self + .choices + .iter() + .position(|(raw, _)| *raw == self.current_choice) + .unwrap_or(0); + Some(idx as f32 / (self.choices.len() - 1) as f32) + } + _ => None, + } + } + + /// Update the option from a normalized `0.0..=1.0` slider drag. + pub fn set_slider_pos(&mut self, pos: f32) { + let pos = f64::from(pos.clamp(0.0, 1.0)); + match self.kind { + OptionKind::Float { min, max, step } => { + let mut v = min + pos * (max - min); + if step > 0.0 { + v = (v / step).round() * step; + } + self.value = v.clamp(min, max); + } + OptionKind::Choice { slider: true } if !self.choices.is_empty() => { + let idx = (pos * (self.choices.len() - 1) as f64).round() as usize; + if let Some((raw, _)) = self.choices.get(idx.min(self.choices.len() - 1)) { + self.current_choice = raw.clone(); + } + } + _ => {} + } + } + + /// Cycle or toggle the option (`reverse`: right-click steps backwards). + pub fn cycle(&mut self, reverse: bool) { + match self.kind { + OptionKind::Bool => { + self.value = if self.value == 0.0 { 1.0 } else { 0.0 }; + } + OptionKind::Int if !self.values.is_empty() => { + let cur = self.value.round() as i64; + let idx = self.values.iter().position(|&v| v == cur).unwrap_or(0); + let next = if reverse { + (idx + self.values.len() - 1) % self.values.len() + } else { + (idx + 1) % self.values.len() + }; + self.value = self.values[next] as f64; + } + OptionKind::Float { min, max, step } => { + let delta = if step > 0.0 { step } else { (max - min) * 0.05 }; + let next = if reverse { + self.value - delta + } else { + self.value + delta + }; + self.value = next.clamp(min, max); + } + OptionKind::Choice { .. } if !self.choices.is_empty() => { + let idx = self + .choices + .iter() + .position(|(raw, _)| *raw == self.current_choice) + .unwrap_or(0); + let next = if reverse { + (idx + self.choices.len() - 1) % self.choices.len() + } else { + (idx + 1) % self.choices.len() + }; + self.current_choice = self.choices[next].0.clone(); + } + _ => {} + } + } + + /// Serialized string value for `shaderpacks/.txt`, or `None` if at default. + pub fn saved_string(&self) -> Option { + match self.kind { + OptionKind::Bool => { + let b = self.value != 0.0; + let def = self.default != 0.0; + (b != def).then(|| b.to_string()) + } + OptionKind::Int => { + let i = self.value.round() as i64; + let def = self.default.round() as i64; + (i != def).then(|| i.to_string()) + } + OptionKind::Float { .. } => { + ((self.value - self.default).abs() > 1e-6).then(|| format!("{}", self.value)) + } + OptionKind::Choice { .. } => { + (self.current_choice != self.default_choice).then(|| self.current_choice.clone()) + } + } + } + + /// Reset to the pack's default value. + pub fn reset(&mut self) { + self.value = self.default; + self.current_choice = self.default_choice.clone(); + } +} + +/// A named preset profile in a Horizon or Java shader pack (`Low`, `High`, `Ultra`). +#[derive(Clone, Debug, PartialEq)] +pub struct PackProfile { + pub name: String, + pub label: String, + pub values: BTreeMap, +} + +/// An item on a shader pack option screen (`shaders.properties` `screen`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ScreenItem { + Empty, + Profile, + Subscreen(String, String), + Option(usize), +} + +/// A laid-out option screen (main screen or sub-screen). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PackScreen { + pub name: String, + pub label: String, + pub columns: u32, + pub items: Vec, +} + +/// Interactive configuration metadata and current values for a shader pack, +/// usable directly by the Options UI without a GPU device. +#[derive(Clone, Debug, Default)] +pub struct PackConfig { + pub id: String, + pub options: Vec, + pub profiles: Vec, + pub main_screen: PackScreen, + pub subscreens: Vec, + /// Active subscreen name (`None` = main screen). + pub active_screen: Option, +} + +impl PackConfig { + /// Load the configurable options, profiles, and screens for pack `id` in `dir`. + pub fn load(dir: &Path, id: &str) -> Result { + if id.is_empty() { + return Err("no shader pack selected".into()); + } + let path = dir.join(id); + let saved = load_values(dir, id); + if path.join("pack.toml").is_file() { + let manifest = manifest(&path)?; + let mut options = Vec::new(); + for (key, entry) in manifest.options { + options.push(option(key, entry, &saved)?); + } + let mut profiles = Vec::new(); + for (name, map) in manifest.profiles { + let mut values = BTreeMap::new(); + for (k, v) in map { + let s = match v { + toml::Value::Boolean(b) => b.to_string(), + toml::Value::Integer(i) => i.to_string(), + toml::Value::Float(f) => f.to_string(), + toml::Value::String(s) => s, + _ => continue, + }; + values.insert(k, s); + } + profiles.push(PackProfile { + label: humanize_identifier(&name), + name, + values, + }); + } + let mut items = Vec::new(); + if !profiles.is_empty() { + items.push(ScreenItem::Profile); + } + items.extend((0..options.len()).map(ScreenItem::Option)); + return Ok(Self { + id: id.to_owned(), + options, + profiles, + main_screen: PackScreen { + name: String::new(), + label: manifest.pack.name, + columns: 2, + items, + }, + subscreens: Vec::new(), + active_screen: None, + }); + } + if crate::java_pack::is_java_pack(&path) { + return Self::load_java(&path, id, &saved); + } + Err("not a valid shader pack".into()) + } + + fn load_java(path: &Path, id: &str, saved: &BTreeMap) -> Result { + let pack = JavaPack::open(path)?; + let values = pack.values(saved); + 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)) + }; + let option_desc = |name: &str, comment: Option<&str>| -> String { + lang.get(&format!("option.{name}.comment")) + .cloned() + .or_else(|| comment.map(str::to_owned)) + .unwrap_or_default() + }; + + let mut options = Vec::new(); + let mut by_name = BTreeMap::new(); + for (name, b) in &pack.options.bools { + let current = values.bools.get(name).copied().unwrap_or(b.default); + let idx = options.len(); + options.push(PackOption { + key: name.clone(), + label: option_label(name, b.comment.as_deref()), + description: option_desc(name, b.comment.as_deref()), + kind: OptionKind::Bool, + values: Vec::new(), + default: f64::from(u8::from(b.default)), + value: f64::from(u8::from(current)), + choices: Vec::new(), + default_choice: b.default.to_string(), + current_choice: current.to_string(), + }); + by_name.insert(name.clone(), idx); + } + for (name, s) in &pack.options.strings { + let current = values + .strings + .get(name) + .cloned() + .unwrap_or_else(|| s.default.clone()); + 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) + }) + .collect(); + let idx = options.len(); + options.push(PackOption { + key: name.clone(), + label: option_label(name, s.comment.as_deref()), + description: option_desc(name, s.comment.as_deref()), + kind: OptionKind::Choice { + slider: sliders.contains(name.as_str()), + }, + values: Vec::new(), + default: 0.0, + value: 0.0, + choices, + default_choice: s.default.clone(), + current_choice: current, + }); + by_name.insert(name.clone(), idx); + } + + let profiles: Vec = props + .profiles(&pack.options) + .unwrap_or_default() + .into_iter() + .map(|p| { + let label = lang + .get(&format!("profile.{}", p.name)) + .cloned() + .unwrap_or_else(|| humanize_identifier(&p.name)); + PackProfile { + name: p.name, + label, + values: p.values, + } + }) + .collect(); + + let referenced: BTreeSet = std::iter::once(None) + .chain(props.screens().into_iter().map(Some)) + .flat_map(|s| props.screen(s).unwrap_or_default()) + .filter_map(|e| match e { + MenuElement::Option(o) => Some(o), + _ => None, + }) + .collect(); + + let build_screen = |screen_name: Option<&str>| -> PackScreen { + let elements = props + .screen(screen_name) + .unwrap_or_else(|| vec![MenuElement::Rest]); + let mut items = Vec::new(); + if screen_name.is_none() + && !profiles.is_empty() + && !elements.contains(&MenuElement::Profile) + { + items.push(ScreenItem::Profile); + } + for el in elements { + match el { + MenuElement::Empty => items.push(ScreenItem::Empty), + MenuElement::Profile => { + if !profiles.is_empty() { + items.push(ScreenItem::Profile); + } + } + MenuElement::Screen(sub) => { + let label = lang + .get(&format!("screen.{sub}")) + .cloned() + .unwrap_or_else(|| humanize_identifier(&sub)); + items.push(ScreenItem::Subscreen(sub, label)); + } + MenuElement::Option(opt) => { + if let Some(&idx) = by_name.get(&opt) { + items.push(ScreenItem::Option(idx)); + } + } + MenuElement::Rest => { + for (idx, opt) in options.iter().enumerate() { + if !referenced.contains(&opt.key) { + items.push(ScreenItem::Option(idx)); + } + } + } + } + } + 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)), + None => id.to_owned(), + }; + PackScreen { + name: name_str, + label, + columns: props.columns(screen_name).unwrap_or(2), + items, + } + }; + + let main_screen = build_screen(None); + let subscreens = props + .screens() + .into_iter() + .map(|s| build_screen(Some(s))) + .collect(); + + Ok(Self { + id: id.to_owned(), + options, + profiles, + main_screen, + subscreens, + active_screen: None, + }) + } + + /// Currently active screen (main or a sub-screen). + pub fn current_screen(&self) -> &PackScreen { + if let Some(name) = &self.active_screen + && let Some(sub) = self.subscreens.iter().find(|s| s.name == *name) + { + return sub; + } + &self.main_screen + } + + /// Name of the profile matching current option values, or `"Custom"`. + pub fn active_profile_label(&self) -> String { + let map = self.to_map(); + for profile in &self.profiles { + let matches = profile.values.iter().all(|(k, v)| { + if let Some(cur) = map.get(k) { + return cur == v; + } + if let Some(opt) = self.options.iter().find(|o| o.key == *k) { + return match opt.kind { + OptionKind::Bool => (opt.default != 0.0).to_string() == *v, + OptionKind::Int => (opt.default.round() as i64).to_string() == *v, + OptionKind::Float { .. } => format!("{}", opt.default) == *v, + OptionKind::Choice { .. } => opt.default_choice == *v, + }; + } + true + }); + if matches { + return profile.label.clone(); + } + } + "Custom".into() + } + + /// Cycle to the next (or previous) profile and apply its option values. + pub fn cycle_profile(&mut self, reverse: bool) { + if self.profiles.is_empty() { + return; + } + let current = self.active_profile_label(); + let idx = self + .profiles + .iter() + .position(|p| p.label == current) + .map(|i| { + if reverse { + (i + self.profiles.len() - 1) % self.profiles.len() + } else { + (i + 1) % self.profiles.len() + } + }) + .unwrap_or(0); + let values = self.profiles[idx].values.clone(); + for opt in &mut self.options { + if let Some(v) = values.get(&opt.key) { + match opt.kind { + OptionKind::Bool => { + if let Ok(b) = v.parse::() { + opt.value = f64::from(u8::from(b)); + } + } + OptionKind::Int => { + if let Ok(i) = v.parse::() { + opt.value = i as f64; + } + } + OptionKind::Float { min, max, .. } => { + if let Ok(f) = v.parse::() { + opt.value = f.clamp(min, max); + } + } + OptionKind::Choice { .. } => { + opt.current_choice = v.clone(); + } + } + } + } + } + + /// Reset all options to their defaults. + pub fn reset_all(&mut self) { + for opt in &mut self.options { + opt.reset(); + } + } + + /// Export non-default option values as a `key=value` map. + pub fn to_map(&self) -> BTreeMap { + let mut out = BTreeMap::new(); + for opt in &self.options { + if let Some(val) = opt.saved_string() { + out.insert(opt.key.clone(), val); + } + } + out + } + + /// Save the current non-default option values to `shaderpacks/.txt`. + pub fn save(&self, dir: &Path) -> Result<(), String> { + save_values(dir, &self.id, &self.to_map()) + } +} + +fn humanize_identifier(raw: &str) -> String { + let mut words = Vec::new(); + let mut current = String::new(); + for ch in raw.chars() { + if ch == '_' || ch == '-' { + if !current.is_empty() { + words.push(std::mem::take(&mut current)); + } + } else if ch.is_uppercase() + && !current.is_empty() + && current.chars().last().is_some_and(char::is_lowercase) + { + words.push(std::mem::take(&mut current)); + current.push(ch); + } else { + current.push(ch); + } + } + if !current.is_empty() { + words.push(current); + } + words + .into_iter() + .map(|w| { + let lower = w.to_lowercase(); + let mut chars = lower.chars(); + match chars.next() { + Some(first) => format!("{}{}", first.to_uppercase(), chars.as_str()), + None => String::new(), + } + }) + .collect::>() + .join(" ") } pub struct ShaderPack { @@ -109,6 +699,8 @@ pub struct ShaderPack { pub info: Info, pub stages: Vec, pub options: Vec, + /// Optional custom noise/LUT texture bytes (RGBA8, width, height) from `[textures]`. + pub custom_noise: Option<(u32, u32, Vec)>, /// A Java (OptiFine/Iris) pack's translated passes, instead of `stages`. pub java: Option, dir: PathBuf, @@ -116,7 +708,7 @@ pub struct ShaderPack { } /// Every file's path, length and modification time: a changed stamp means -/// the pack was edited (hot reload). +/// the pack or its `.txt` option file was edited (hot reload). #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Stamp(Vec<(PathBuf, u64, Option)>); impl Stamp { @@ -127,6 +719,17 @@ impl Stamp { { files.push((dir.to_path_buf(), meta.len(), meta.modified().ok())); } + // Also watch the sibling `.txt` options file for live option reloads. + if let Some(name) = dir.file_name() + && let Some(parent) = dir.parent() + { + let txt = parent.join(format!("{}.txt", name.to_string_lossy())); + if let Ok(meta) = fs::metadata(&txt) + && meta.is_file() + { + files.push((txt, meta.len(), meta.modified().ok())); + } + } let mut stack = vec![dir.to_path_buf()]; while let Some(d) = stack.pop() { let Ok(entries) = fs::read_dir(&d) else { @@ -177,6 +780,62 @@ pub fn folder() -> PathBuf { std::env::current_dir().unwrap_or_default().join(DIR) } +/// Import a `.zip` archive or shader pack folder from `source` into +/// `target_dir` (`shaderpacks/`), validating that it holds `pack.toml` or +/// `shaders/`. Returns the imported pack's folder/zip name (`id`). +pub fn import_pack(source: &Path, target_dir: &Path) -> Result { + let source = source + .canonicalize() + .unwrap_or_else(|_| source.to_path_buf()); + if !source.exists() { + return Err(format!("{}: file or folder not found", source.display())); + } + let name = source + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .filter(|n| !n.is_empty()) + .ok_or_else(|| "invalid shader pack path".to_string())?; + let is_horizon = source.is_dir() && source.join("pack.toml").is_file(); + let is_java = crate::java_pack::is_java_pack(&source); + if !is_horizon && !is_java { + return Err(format!( + "{name}: not a shader pack (needs pack.toml or shaders/)" + )); + } + if is_java && source.is_file() { + // Verify the zip actually contains `shaders/` or `pack.toml` at its root. + JavaPack::open(&source)?; + } else if is_horizon { + manifest(&source)?; + } + fs::create_dir_all(target_dir).map_err(|e| format!("{}: {e}", target_dir.display()))?; + let dest = target_dir.join(&name); + if dest.canonicalize().ok() == source.canonicalize().ok() { + return Ok(name); + } + if source.is_file() { + fs::copy(&source, &dest).map_err(|e| format!("failed to copy {name}: {e}"))?; + } else { + copy_dir_recursive(&source, &dest)?; + } + Ok(name) +} + +fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), String> { + fs::create_dir_all(dst).map_err(|e| format!("{}: {e}", dst.display()))?; + let entries = fs::read_dir(src).map_err(|e| format!("{}: {e}", src.display()))?; + 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()))?; + } + } + Ok(()) +} + /// `shaderpacks/` and its packs as the Shader Packs page lists them, read /// again at most once a second while the page is open, so a pack dropped /// into the folder shows up. @@ -199,13 +858,17 @@ 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: its full-screen passes run.".into(), + description: "Iris/OptiFine pack: G-buffers, shadow map and post passes.".into(), authors: Vec::new(), version: String::new(), license: String::new(), @@ -216,7 +879,7 @@ fn java_info(name: String) -> Info { fn manifest(dir: &Path) -> Result { let text = fs::read_to_string(dir.join("pack.toml")).map_err(|e| format!("pack.toml: {e}"))?; let manifest: Manifest = toml::from_str(&text).map_err(|e| format!("pack.toml: {e}"))?; - if manifest.pack.api > API { + if manifest.pack.api == 0 || manifest.pack.api > API { return Err(format!( "pack.toml: needs shader pack api {}, this Horizon has {API}", manifest.pack.api @@ -225,12 +888,41 @@ fn manifest(dir: &Path) -> Result { Ok(manifest) } +pub(crate) fn decode_png_rgba(bytes: &[u8]) -> Result<(u32, u32, Vec), String> { + 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())?; + let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)]; + let info = reader.next_frame(&mut buf).map_err(|e| e.to_string())?; + buf.truncate(info.buffer_size()); + let (w, h) = (info.width.max(1), info.height.max(1)); + let rgba = match info.color_type { + png::ColorType::Rgba => buf, + png::ColorType::Rgb => buf + .as_chunks::<3>() + .0 + .iter() + .flat_map(|p| [p[0], p[1], p[2], 255]) + .collect(), + png::ColorType::GrayscaleAlpha => buf + .as_chunks::<2>() + .0 + .iter() + .flat_map(|p| [p[0], p[0], p[0], p[1]]) + .collect(), + 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)) +} + impl ShaderPack { /// Load and validate the pack in `dir` with the option values in /// `values` (missing ones take their default). pub fn load(dir: &Path, values: &BTreeMap) -> Result { let stamp = Stamp::of(dir); let manifest = manifest(dir)?; + let pack_api = manifest.pack.api; if manifest.stage.is_empty() || manifest.stage.len() > MAX_STAGES { return Err(format!("pack.toml: 1 to {MAX_STAGES} stages")); } @@ -244,11 +936,15 @@ impl ShaderPack { .collect::, _>>()?; let mut stages = Vec::new(); for entry in manifest.stage { - let kind = match entry.kind.as_str() { - "composite" => StageKind::Composite, - other => { + 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) => { return Err(format!( - "pack.toml: stage kind `{other}` isn't supported (api {API} has `composite`)" + "pack.toml: stage kind `{other}` isn't supported (api {pack_api} has `composite`)" )); } }; @@ -273,8 +969,22 @@ impl ShaderPack { source, entry: entry_point, scale, + format: entry.format, + mipmap: entry.mipmap, }); } + let mut custom_noise = None; + if let Some(rel) = manifest + .textures + .get("noise") + .or_else(|| manifest.textures.values().next()) + { + 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}"))?); + } Ok(Self { id: dir .file_name() @@ -283,6 +993,7 @@ impl ShaderPack { info: manifest.pack, stages, options, + custom_noise, java: None, dir: dir.to_path_buf(), stamp, @@ -305,16 +1016,57 @@ 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: Vec::new(), + options, + 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") + }) + } + /// 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, + ); + } + let res = self + .options + .iter() + .find(|o| o.key == "shadow_resolution" || o.key == "shadowMapResolution") + .map(|o| (o.value.round() as u32).clamp(256, 4096)) + .unwrap_or(2048); + let dist = self + .options + .iter() + .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) + } /// The pipeline-overridable constants every stage gets: the option values. pub fn constants(&self) -> Vec<(&str, f64)> { self.options @@ -368,15 +1120,20 @@ fn option( .ok() .filter(|f| f.is_finite()) .map(|f| f.clamp(min, max)), + OptionKind::Choice { .. } => None, }) .unwrap_or(default); Ok(PackOption { - label: entry.label.unwrap_or_else(|| key.clone()), + label: entry.label.unwrap_or_else(|| humanize_identifier(&key)), + description: entry.description, key, kind, values: values_list, default, value, + choices: Vec::new(), + default_choice: String::new(), + current_choice: String::new(), }) } @@ -422,6 +1179,25 @@ pub fn load_values(dir: &Path, id: &str) -> BTreeMap { .collect() } +/// Save option values for a pack (`shaderpacks/.txt`, `key=value`). +/// When `values` is empty, removes `.txt` if present. +pub fn save_values(dir: &Path, id: &str, values: &BTreeMap) -> Result<(), String> { + if id.is_empty() { + return Ok(()); + } + let path = dir.join(format!("{id}.txt")); + if values.is_empty() { + let _ = fs::remove_file(path); + return Ok(()); + } + fs::create_dir_all(dir).map_err(|e| e.to_string())?; + let mut text = String::new(); + for (k, v) in values { + text.push_str(&format!("{k}={v}\n")); + } + fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display())) +} + #[cfg(test)] mod tests { use super::*; @@ -529,8 +1305,8 @@ override mode: i32 = 1; fn manifests_are_checked() { for (manifest, expected) in [ ( - MANIFEST.replace("api = 1", "api = 2"), - "needs shader pack api 2", + MANIFEST.replace("api = 1", "api = 3"), + "needs shader pack api 3", ), ( MANIFEST.replace("\"composite\"", "\"shadow\""), @@ -556,6 +1332,23 @@ 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 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); + let parent = dir.parent().unwrap(); + let id = dir.file_name().unwrap().to_str().unwrap(); + let mut cfg = PackConfig::load(parent, id).unwrap(); + assert_eq!(cfg.options.len(), 3); + cfg.options[0].cycle(false); + cfg.save(parent).unwrap(); + assert!(loaded.changed(), "saving .txt updates the stamp"); + } + #[test] fn edits_change_the_stamp_and_the_list_shows_every_pack() { let root = scratch(); diff --git a/crates/horizon-client/src/shader_pack_prelude.wgsl b/crates/horizon-client/src/shader_pack_prelude.wgsl index 7b16690f9..ebe3ad4cf 100644 --- a/crates/horizon-client/src/shader_pack_prelude.wgsl +++ b/crates/horizon-client/src/shader_pack_prelude.wgsl @@ -1,6 +1,7 @@ -// 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. +// 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. struct Frame { view: mat4x4, projection: mat4x4, @@ -19,12 +20,36 @@ 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, @@ -42,6 +67,10 @@ 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; } @@ -60,6 +89,70 @@ 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)); } @@ -69,3 +162,12 @@ 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-shaderpack/src/lib.rs b/crates/horizon-shaderpack/src/lib.rs index 71b6abbd3..fa454a134 100644 --- a/crates/horizon-shaderpack/src/lib.rs +++ b/crates/horizon-shaderpack/src/lib.rs @@ -17,7 +17,7 @@ pub mod uniforms; use include::{IncludeGraph, Inlined}; use options::{Annotated, OptionSet, OptionValues}; use preprocess::{Environment, Preprocessed}; -use properties::ShaderProperties; +use properties::{Properties, ShaderProperties}; use source::PackFiles; use std::{ collections::{BTreeMap, BTreeSet}, @@ -154,6 +154,32 @@ impl JavaPack { None => Ok(ShaderProperties::default()), } } + + /// The pack's language translations (`shaders/lang/.lang` or + /// `en_US.lang`), mapping keys such as `option.SHADOW_QUALITY`, + /// `value.SHADOW_QUALITY.2`, `screen.LIGHTING`, and `profile.HIGH` to their + /// display labels. + pub fn translations(&self, lang_code: &str) -> BTreeMap { + let mut out = BTreeMap::new(); + let lower = lang_code.to_lowercase(); + let upper = match lower.split_once('_') { + Some((l, r)) => format!("{l}_{}", r.to_uppercase()), + None => lower.clone(), + }; + let mut candidates = vec!["lang/en_US.lang".to_owned(), "lang/en_us.lang".to_owned()]; + if lower != "en_us" { + candidates.push(format!("lang/{lower}.lang")); + candidates.push(format!("lang/{upper}.lang")); + } + for path in candidates { + if let Some(text) = self.files.read(&path) { + for (k, v) in Properties::parse(&text).iter() { + out.insert(k.to_owned(), v.to_owned()); + } + } + } + out + } } /// A program's name in `shaders.properties` (`world-1/composite1.fsh` is diff --git a/crates/horizon-shaderpack/src/pipeline.rs b/crates/horizon-shaderpack/src/pipeline.rs index 7ebb35442..db656e3ae 100644 --- a/crates/horizon-shaderpack/src/pipeline.rs +++ b/crates/horizon-shaderpack/src/pipeline.rs @@ -11,7 +11,7 @@ use crate::{ JavaPack, options::OptionValues, preprocess::Environment, - properties::{LEGACY_TARGETS, ShaderProperties}, + properties::{Blend, LEGACY_TARGETS, ShaderProperties}, translate::{Link, Translated}, }; use std::collections::{BTreeMap, BTreeSet}; @@ -297,6 +297,10 @@ pub struct Pass { pub mipmapped: BTreeSet, /// `scale.`: the fraction of the screen it draws. pub scale: f32, + /// `blend.` override for all outputs of this pass. + pub blend: Option, + /// `blend..` overrides per colour target index. + pub buffer_blends: Vec<(u32, Blend)>, } /// The full-screen passes of one program folder, in order, and the @@ -319,6 +323,8 @@ 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 @@ -331,6 +337,28 @@ pub struct Directives { pub sun_path_rotation: f32, /// `eyeBrightnessHalflife`, tenths of a second: `eyeBrightnessSmooth`. pub eye_brightness_half_life: f32, + /// `wetnessHalflife`, tenths of a second: `wetness` smoothing when raining. + 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 { @@ -338,6 +366,17 @@ impl Default for Directives { Self { sun_path_rotation: 0.0, 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], } } } @@ -348,11 +387,66 @@ impl Directives { let mut out = Self::default(); for fragment in fragments { for c in const_directives(fragment) { - // 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, + 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(); + } _ => {} } } @@ -474,21 +568,43 @@ 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() }; + let resolve_blends = |prog: &str| { + let blend = properties.blend(prog).and_then(Result::ok); + let buffer_blends: Vec<(u32, Blend)> = properties + .buffer_blends(prog) + .into_iter() + .filter_map(|(i, b)| Some((i, b.ok()?))) + .collect(); + (blend, buffer_blends) + }; + let flips = explicit_flips(properties); let run = |group: &[String], pre: &str, flipped: &mut BTreeSet| { *flipped = flips_pre(&flips, pre, flipped); let mut passes = Vec::new(); for name in group { let text = &fragments[name]; + let prog = path(name); + let (blend, buffer_blends) = resolve_blends(&prog); let pass = Pass { - program: path(name), - draw_buffers: draw_buffers(text).map_err(|e| format!("{}: {e}", path(name)))?, + program: prog.clone(), + draw_buffers: draw_buffers(text).map_err(|e| format!("{prog}: {e}"))?, reads_alt: flipped.clone(), mipmapped: mipmapped(text), scale: properties @@ -496,6 +612,8 @@ impl JavaPack { .get(&format!("scale.{name}")) .and_then(|v| v.split_whitespace().next()?.parse().ok()) .unwrap_or(1.0), + blend, + buffer_blends, }; *flipped = flip_set(&pass, &flips); passes.push(pass); @@ -511,12 +629,16 @@ impl JavaPack { out.composite = run(&groups[3], "composite_pre", &mut flipped)?; out.flipped_at_end = flipped; if exists("final") { + let prog = path("final"); + let (blend, buffer_blends) = resolve_blends(&prog); out.final_pass = Some(Pass { - program: path("final"), + program: prog, draw_buffers: None, reads_alt: out.flipped_at_end.clone(), mipmapped: mipmapped(&fragment("final")?), scale: 1.0, + blend, + buffer_blends, }); } Ok(out) @@ -736,12 +858,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;", + "const float sunPathRotation = 30.0;\nconst float eyeBrightnessHalflife = 4.0f;\nconst int shadowMapResolution = 4096;\nconst float shadowDistance = 192.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); } #[test] diff --git a/crates/horizon-shaderpack/src/properties.rs b/crates/horizon-shaderpack/src/properties.rs index 3c6ee251c..0e989341a 100644 --- a/crates/horizon-shaderpack/src/properties.rs +++ b/crates/horizon-shaderpack/src/properties.rs @@ -358,8 +358,21 @@ impl Default for SkyDirectives { } } +/// A custom texture bound by `texture.. = ` in +/// `shaders.properties`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CustomTexture { + /// Stage family (`composite`, `deferred`, `gbuffers`, `prepare`, `begin`), + /// or `None` when bound across all stages. + pub stage: Option, + /// Sampler uniform name (`noisetex`, `colortex4`, `customTex`, ...). + pub sampler: String, + /// Path relative to `shaders/` (`textures/noise.png`). + pub path: String, +} + /// A pack's `shaders.properties`. -#[derive(Debug, Default)] +#[derive(Debug, Default, Clone)] pub struct ShaderProperties { /// As written: screens, sliders, profiles, feature flags. pub original: Properties, @@ -535,6 +548,31 @@ impl ShaderProperties { .collect() } + /// `texture.. = ` and `texture. = `: + /// custom textures defined in `shaders.properties`. + pub fn custom_textures(&self) -> Vec { + let mut out = Vec::new(); + for (k, v) in self.preprocessed.iter() { + let Some(rest) = k.strip_prefix("texture.") else { + continue; + }; + let path = v.split_whitespace().next().unwrap_or("").trim(); + if path.is_empty() { + continue; + } + let (stage, sampler) = match rest.split_once('.') { + Some((stage, sampler)) => (Some(stage.to_owned()), sampler.to_owned()), + None => (None, rest.to_owned()), + }; + out.push(CustomTexture { + stage, + sampler, + path: path.to_owned(), + }); + } + out + } + /// `uniform.*` and `variable.*`: the pack's custom uniforms. pub fn custom_uniforms(&self) -> crate::uniforms::CustomUniforms { crate::uniforms::CustomUniforms::parse(self.preprocessed.iter()) @@ -564,23 +602,37 @@ impl ShaderProperties { pub fn blend(&self, program: &str) -> Option> { self.preprocessed .get(&format!("blend.{program}")) + .or_else(|| { + let short = program.rsplit('/').next()?; + self.preprocessed.get(&format!("blend.{short}")) + }) .map(parse_blend) } /// `blend..`: per colour target overrides, by target index. pub fn buffer_blends(&self, program: &str) -> Vec<(u32, Result)> { - let prefix = format!("blend.{program}."); - self.preprocessed - .iter() - .filter_map(|(k, v)| { - let buffer = k.strip_prefix(&prefix)?; - let index = match LEGACY_TARGETS.iter().position(|t| *t == buffer) { - Some(i) => i as u32, - None => buffer.strip_prefix("colortex")?.parse().ok()?, - }; - Some((index, parse_blend(v))) - }) - .collect() + let short = program.rsplit('/').next().unwrap_or(program); + let prefixes = [format!("blend.{program}."), format!("blend.{short}.")]; + let mut out = Vec::new(); + for (k, v) in self.preprocessed.iter() { + let Some(buffer) = prefixes.iter().find_map(|p| k.strip_prefix(p.as_str())) else { + continue; + }; + let Some(index) = LEGACY_TARGETS + .iter() + .position(|t| *t == buffer) + .map(|i| i as u32) + .or_else(|| buffer.strip_prefix("colortex")?.parse().ok()) + else { + continue; + }; + if let Some(existing) = out.iter_mut().find(|(i, _)| *i == index) { + existing.1 = parse_blend(v); + } else { + out.push((index, parse_blend(v))); + } + } + out } } @@ -796,6 +848,7 @@ blend.gbuffers_water.gaux2 = off blend.gbuffers_water.colortex9 = ONE ONE ONE ONE size.buffer.colortex4 = 0.50 QUALITY image.lightimg0 = lighttex0 rgba RGBA16F half_float false false 128 64 128 +texture.composite.colortex4 = textures/noise.png # a comment, not a directive iris.features.optional = CUSTOM_IMAGES SSBO "; @@ -823,6 +876,14 @@ iris.features.optional = CUSTOM_IMAGES SSBO p.image_formats(), [("lightimg0".to_owned(), "rgba16f".to_owned())].into() ); + assert_eq!( + p.custom_textures(), + [CustomTexture { + stage: Some("composite".into()), + sampler: "colortex4".into(), + path: "textures/noise.png".into(), + }] + ); assert_eq!(p.features(), (vec![], vec!["CUSTOM_IMAGES", "SSBO"])); // The preprocessed read: #if picked, values expanded, spelling kept. assert!(!p.program_enabled("composite1", &set, &values)); diff --git a/crates/horizon-shaderpack/src/source.rs b/crates/horizon-shaderpack/src/source.rs index 0501661ce..4e4bcd779 100644 --- a/crates/horizon-shaderpack/src/source.rs +++ b/crates/horizon-shaderpack/src/source.rs @@ -63,13 +63,27 @@ impl PackFiles { Ok(Self::Zip(files)) } + /// Raw bytes of a file relative to `shaders/` (leading `/` or `./` stripped), + /// or `None` when it doesn't exist. + pub fn read_bytes(&self, rel: &str) -> Option> { + let clean = rel + .trim() + .trim_start_matches("./") + .trim_start_matches('/') + .trim_start_matches("shaders/"); + if clean.is_empty() || clean.contains("..") { + return None; + } + match self { + Self::Folder(root) => fs::read(root.join(clean)).ok(), + Self::Zip(files) => files.get(clean).cloned(), + } + } + /// A text file, or `None` when it doesn't exist. Invalid UTF-8 is /// replaced, as packs are often saved in Latin-1. pub fn read(&self, rel: &str) -> Option { - let bytes = match self { - Self::Folder(root) => fs::read(root.join(rel)).ok()?, - Self::Zip(files) => files.get(rel)?.clone(), - }; + let bytes = self.read_bytes(rel)?; Some(String::from_utf8_lossy(&bytes).into_owned()) } diff --git a/crates/horizon-shaderpack/src/translate.rs b/crates/horizon-shaderpack/src/translate.rs index 8a32795af..623ad760d 100644 --- a/crates/horizon-shaderpack/src/translate.rs +++ b/crates/horizon-shaderpack/src/translate.rs @@ -5,8 +5,9 @@ //! patches do for the core profile, prints GLSL 450 and has naga turn that //! into a validated module and WGSL: //! -//! - `attribute`/`varying` become `in`/`out` with locations; matrix and array -//! varyings are split into vectors (WGSL can pass neither between stages); +//! - `attribute`/`varying` become `in`/`out` with locations; matrix, nested +//! array and struct varyings are split into vectors (WGSL can pass none of +//! them directly between stages); //! - loose uniforms go into one std140 block (`bool`s stored as `int`); //! - `sampler2D` & co. become a texture and a sampler binding, rebuilt as //! `sampler2D(t, s)` where used, also through function parameters, and not @@ -16,13 +17,16 @@ //! (`vaPosition`, `modelViewMatrix`, ...) are declared; //! - legacy texture calls are renamed, `shadow2D` returns a `vec4` again and a //! swizzled shadow lookup is widened first (naga has no scalar swizzle); +//! - vertex and compute `texture(s, uv)` calls without an explicit LOD become +//! `textureLod(s, uv, 0.0)` so naga doesn't reject implicit derivatives; //! - global initialisers run at the start of `main` (drivers accept //! non-constant ones), unsized global arrays are sized from them; //! - `isnan`, `isinf` and `modf` are helper functions (WGSL has none); //! - what naga refuses and drivers accept: `%` goes through overloads (naga -//! won't take `ivec2 % int`), `sqrt` of a negative constant isn't folded, -//! constants naga can't fold (`?:`, `mix`) become globals set in `main`, -//! and 16/8-bit types are their 32-bit ones. +//! won't take `ivec2 % int`), `mat2(vec4)` goes through `iris_mat2`, `1 << 31` +//! shifts as unsigned before casting back to `int`, `sqrt` of a negative +//! constant isn't folded, constants naga can't fold (`?:`, `mix`, `<<`) +//! become globals set in `main`, and 16/8-bit types are their 32-bit ones. //! //! The programs of one pass share a [`Link`], so their locations, bindings and //! uniform block agree. @@ -238,6 +242,18 @@ vec3 iris_modf(vec3 x, out vec3 i) { i = trunc(x); return x - i; } vec4 iris_modf(vec4 x, out vec4 i) { i = trunc(x); return x - i; } "; +/// Overloaded `mat2` constructor helper: drivers accept `mat2(vec4)` (Bloop), +/// which naga's GLSL front end refuses. +const MAT2_HELPERS: &str = "\ +mat2 iris_mat2(float x) { return mat2(x); } +mat2 iris_mat2(vec2 a, vec2 b) { return mat2(a, b); } +mat2 iris_mat2(float a, float b, float c, float d) { return mat2(a, b, c, d); } +mat2 iris_mat2(vec4 v) { return mat2(v.xy, v.zw); } +mat2 iris_mat2(mat2 m) { return m; } +mat2 iris_mat2(mat3 m) { return mat2(m); } +mat2 iris_mat2(mat4 m) { return mat2(m); } +"; + /// A fragment output narrower than four channels (`out vec3 color`, /// Steadfast's `final`): the four-channel type it is written through and the /// epilogue line that fills it, with alpha 1 and the rest 0. `None` when the @@ -376,69 +392,62 @@ pub fn translate( let wgsl = naga::back::wgsl::write_string(&module, &info, naga::back::wgsl::WriterFlags::empty()) .map_err(|e| e.to_string())?; - let interface = std::mem::take(&mut legaliser.interface); Ok(Translated { glsl, module, info, wgsl, - interface, + interface: legaliser.interface, }) } -/// The GLSL built-ins naga's constant evaluator folds (`MathFunction`s it -/// implements), besides type constructors. +/// Built-in functions naga folds in `const` initialisers. const FOLDABLE: &[&str] = &[ - "abs", - "acos", - "acosh", - "asin", - "asinh", - "atan", - "atanh", - "ceil", - "clamp", - "cos", - "cosh", - "cross", + "radians", "degrees", + "sin", + "cos", + "tan", + "asin", + "acos", + "atan", + "pow", + "exp", + "log", + "exp2", + "log2", + "sqrt", + "inversesqrt", + "abs", + "sign", + "floor", + "trunc", + "round", + "ceil", + "fract", + "mod", + "min", + "max", + "clamp", + "step", + "length", "distance", "dot", - "exp", - "exp2", - "floor", - "fma", - "fract", - "inversesqrt", - "length", - "log", - "log2", - "max", - "min", + "cross", "normalize", - "pow", - "radians", - "round", - "sign", - "sin", - "sinh", - "sqrt", - "step", - "tan", - "tanh", - "trunc", ]; -/// Whether a constant's initialisers need what naga can't fold and drivers -/// do: a `?:`, another built-in (Bliss's `mix`), or a constant that had to -/// become a global (`runtime`). +fn constructor(name: &str) -> bool { + ["bool", "int", "uint", "float", "double"].contains(&name) + || ["vec", "ivec", "uvec", "bvec", "dvec", "mat", "dmat"] + .iter() + .any(|p| name.starts_with(p)) +} + +/// Whether `list` has an initialiser naga's constant folder refuses (`?:`, +/// `mix`, `smoothstep`, `1 << 31`, or a reference to a constant already turned +/// into a global). fn needs_runtime(list: &ast::InitDeclaratorList, runtime: &HashSet) -> bool { - let constructor = |name: &str| { - let n = name.trim_start_matches(['i', 'u', 'b', 'd']); - matches!(name, "float" | "int" | "uint" | "bool" | "double") - || n.starts_with("vec") - || n.starts_with("mat") - }; let expr = |e: &ast::Expr| { fn walk(e: &ast::Expr, f: &dyn Fn(&ast::Expr) -> bool) -> bool { use ast::ExprData as E; @@ -454,6 +463,14 @@ fn needs_runtime(list: &ast::InitDeclaratorList, runtime: &HashSet) -> b } walk(e, &|e| match &e.content { ast::ExprData::Ternary(..) => true, + ast::ExprData::Binary(op, _, _) + if matches!( + op.content, + ast::BinaryOpData::LShift | ast::BinaryOpData::RShift + ) => + { + true + } ast::ExprData::Variable(v) => runtime.contains(v.as_str()), ast::ExprData::FunCall(f, _) => { callee(f).is_some_and(|c| !constructor(&c) && !FOLDABLE.contains(&c.as_str())) @@ -503,6 +520,9 @@ enum Local { Sampler(&'static str), } +/// A struct field `(type_name, field_name, array_suffix)`. +type StructField = (String, String, String); + struct Legaliser<'a> { stage: Stage, link: &'a mut Link, @@ -515,6 +535,8 @@ struct Legaliser<'a> { /// User functions → indices of their sampler parameters. sampler_params: HashMap>, functions: HashSet, + /// User structs → their fields `(ty, name, array)` (for struct varyings). + structs: HashMap>, scopes: Vec>, /// Declarations before the program (bindings, block, inputs, outputs). header: Vec, @@ -528,10 +550,11 @@ struct Legaliser<'a> { errors: Vec, /// Inside a constant initialiser: no helper calls there. constant: bool, - /// The program uses `%` ([`modulo_helpers`]) or `iris_sqrt`: their - /// helpers go in. + /// The program uses `%` ([`modulo_helpers`]), `iris_sqrt` or `iris_mat2`: + /// their helpers go in. modulo: bool, nan: bool, + mat2_ctor: bool, /// Constants turned into globals ([`needs_runtime`]). runtime_constants: HashSet, } @@ -634,6 +657,38 @@ fn array_text(a: &Option) -> String { .collect() } +/// Parse one or more `[N]` dimensions (`[9][9]` → `Some(vec![9, 9])`). +fn array_dims(array: &str) -> Option> { + if array.is_empty() { + return Some(Vec::new()); + } + let mut dims = Vec::new(); + let mut rest = array.trim(); + while !rest.is_empty() { + let inner = rest.strip_prefix('[')?; + let (num, tail) = inner.split_once(']')?; + dims.push(num.trim().parse::().ok()?); + rest = tail.trim(); + } + Some(dims) +} + +/// Expand multi-dimensional indices `dims` into `(key_suffix, expr_suffix)` +/// pairs (`[2, 2]` → `("#0#0", "[0][0]")`, `("#0#1", "[0][1]")`, ...). +fn expand_dims(dims: &[usize]) -> Vec<(String, String)> { + let mut out = vec![(String::new(), String::new())]; + for &n in dims { + let mut next = Vec::with_capacity(out.len() * n); + for (k, e) in &out { + for i in 0..n { + next.push((format!("{k}#{i}"), format!("{e}[{i}]"))); + } + } + out = next; + } + out +} + /// The element count of `T[](a, b, c)`. fn constructor_len(init: &Option) -> Option { match &init.as_ref()?.content { @@ -718,6 +773,7 @@ impl<'a> Legaliser<'a> { sampler_vars: HashSet::new(), sampler_params: HashMap::new(), functions: HashSet::new(), + structs: HashMap::new(), scopes: Vec::new(), header: Vec::new(), prologue: Vec::new(), @@ -728,14 +784,43 @@ impl<'a> Legaliser<'a> { constant: false, modulo: false, nan: false, + mat2_ctor: false, runtime_constants: HashSet::new(), } } + fn record_struct(&mut self, spec: &ast::StructSpecifier) { + let Some(name) = &spec.name else { return }; + let mut fields = Vec::new(); + for field in &spec.fields { + let base_ty = type_text(&field.ty); + let ty_arr = array_text(&field.ty.array_specifier); + for id in &field.identifiers { + let arr = format!("{ty_arr}{}", array_text(&id.array_spec)); + fields.push((base_ty.clone(), id.ident.as_str().to_owned(), arr)); + } + } + self.structs.insert(name.as_str().to_owned(), fields); + } + fn unit(&mut self, unit: &mut ast::TranslationUnit) -> Result<(), String> { - // Functions and their sampler parameters first: calls may precede - // definitions through prototypes. + // 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; + } + _ => {} + } + } let proto = match &ed.content { ast::ExternalDeclarationData::FunctionDefinition(f) => &f.prototype, ast::ExternalDeclarationData::Declaration(d) => match &d.content { @@ -812,6 +897,22 @@ impl<'a> Legaliser<'a> { } fn global_list(&mut self, list: &mut ast::InitDeclaratorList) -> Result { + // If a standalone `struct S { ... };` has no declarator names, keep it + // in the header so varyings of type `S` can declare `S varname;` there. + if list.head.name.is_none() + && list.tail.is_empty() + && matches!( + list.head.ty.ty.ty.content, + ast::TypeSpecifierNonArrayData::Struct(_) + ) + { + let mut text = String::new(); + let decl = ast::DeclarationData::InitDeclaratorList(list.clone()).into_node(); + show_declaration(&mut text, &decl, &mut FormattingState::default()) + .map_err(|e| e.to_string())?; + self.header.push(text.trim().to_owned()); + return Ok(false); + } let qualifier = list.head.ty.qualifier.clone(); let storage = storage(&qualifier); let has = |s: ast::StorageQualifierData| storage.contains(&s); @@ -939,32 +1040,34 @@ impl<'a> Legaliser<'a> { .find(|(k, _)| k == "location") .and_then(|(_, v)| v?.parse().ok()); for (i, (name, array)) in names.iter().enumerate() { - let full = format!("{ty}{ty_array}"); + let full_array = format!("{ty_array}{array}"); if input { let at = Link::location(&mut self.link.attributes, name); - self.header - .push(format!("layout(location = {at}) in {full} {name}{array};")); + self.header.push(format!( + "layout(location = {at}) in {ty} {name}{full_array};" + )); self.interface.attributes.insert(name.clone()); } else if !varying { let at = explicit .map(|l: u32| l + i as u32) .unwrap_or_else(|| self.next_output()); - if let (Some(widened), "") = (widen_output(&full, name), array.as_str()) { + if let (Some(widened), "") = (widen_output(&ty, name), full_array.as_str()) { // GL fills the missing channels of a narrow output; // wgpu wants every channel of the target written. let (wide, fill) = widened; - self.header.push(format!("{full} {name};")); + self.header.push(format!("{ty} {name};")); self.header.push(format!( "layout(location = {at}) out {wide} iris_out_{name};" )); self.epilogue.push(fill); } else { - self.header - .push(format!("layout(location = {at}) out {full} {name}{array};")); + self.header.push(format!( + "layout(location = {at}) out {ty} {name}{full_array};" + )); } self.interface.outputs.insert(at, name.clone()); } else { - self.varying(dir, &interp, &full, name, array); + self.varying(dir, &interp, &ty, name, &full_array); } } return Ok(false); @@ -1001,64 +1104,106 @@ impl<'a> Legaliser<'a> { .unwrap() } - /// One varying: matrices and arrays split into vectors that a private - /// global of the original type is packed from or into. - fn varying(&mut self, dir: &str, interp: &str, ty: &str, name: &str, array: &str) { + /// Emit scalar/vector/matrix varying leaves for an expression `expr_path` + /// with key `key_prefix`. + fn varying_leaf(&mut self, dir: &str, interp: &str, ty: &str, key: &str, expr_path: &str) { + if let Some(fields) = self.structs.get(ty).cloned() { + for (f_ty, f_name, f_arr) in fields { + let sub_key = format!("{key}#{f_name}"); + let sub_expr = format!("{expr_path}.{f_name}"); + self.varying_composite(dir, interp, &f_ty, &sub_key, &sub_expr, &f_arr); + } + return; + } + if let Some((cols, column)) = matrix_columns(ty) { + let flat = if is_integer(&column) && !interp.contains("flat") { + "flat " + } else { + "" + }; + let mut columns = Vec::new(); + for c in 0..cols { + let c_key = format!("{key}#{c}"); + let at = Link::location(&mut self.link.varyings, &c_key); + let part = c_key.replace('#', "_iris"); + self.header.push(format!( + "layout(location = {at}) {flat}{interp}{dir} {column} {part};" + )); + if dir == "out" { + self.epilogue.push(format!("{part} = {expr_path}[{c}];")); + } + columns.push(part); + } + if dir == "in" { + self.prologue + .push(format!("{expr_path} = {ty}({});", columns.join(", "))); + } + return; + } let flat = if is_integer(ty) && !interp.contains("flat") { "flat " } else { "" }; - let count: Option = array - .strip_prefix('[') - .and_then(|a| a.strip_suffix(']')) - .and_then(|n| n.parse().ok()); - let parts: Vec<(String, String, String)> = match (matrix_columns(ty), count) { - (Some((cols, column)), None) => (0..cols) - .map(|c| { - ( - format!("{name}#{c}"), - column.clone(), - format!("{name}[{c}]"), - ) - }) - .collect(), - (None, Some(n)) => (0..n) - .map(|e| (format!("{name}#{e}"), ty.to_owned(), format!("{name}[{e}]"))) - .collect(), - (None, None) => { - let at = Link::location(&mut self.link.varyings, name); - self.header.push(format!( - "layout(location = {at}) {flat}{interp}{dir} {ty} {name};" - )); - return; - } - (Some(_), Some(_)) => { - self.errors.push(format!( - "varying {name}: arrays of matrices are not supported" - )); - return; - } + let at = Link::location(&mut self.link.varyings, key); + let part = key.replace('#', "_iris"); + self.header.push(format!( + "layout(location = {at}) {flat}{interp}{dir} {ty} {part};" + )); + if dir == "out" { + self.epilogue.push(format!("{part} = {expr_path};")); + } else { + self.prologue.push(format!("{expr_path} = {part};")); + } + } + + fn varying_composite( + &mut self, + dir: &str, + interp: &str, + ty: &str, + key: &str, + expr_path: &str, + array: &str, + ) { + let Some(dims) = array_dims(array) else { + self.errors + .push(format!("varying {expr_path}: unsupported array `{array}`")); + return; }; - self.header.push(format!("{ty} {name}{array};")); - let mut columns = Vec::new(); - for (key, part_ty, element) in &parts { - let at = Link::location(&mut self.link.varyings, key); - let part = key.replace('#', "_iris"); - self.header.push(format!( - "layout(location = {at}) {flat}{interp}{dir} {part_ty} {part};" - )); - if dir == "out" { - self.epilogue.push(format!("{part} = {element};")); - } else if count.is_some() { - self.prologue.push(format!("{element} = {part};")); + if dims.is_empty() { + self.varying_leaf(dir, interp, ty, key, expr_path); + } else { + for (k_suf, e_suf) in expand_dims(&dims) { + self.varying_leaf( + dir, + interp, + ty, + &format!("{key}{k_suf}"), + &format!("{expr_path}{e_suf}"), + ); } - columns.push(part); } - if dir == "in" && count.is_none() { - self.prologue - .push(format!("{name} = {ty}({});", columns.join(", "))); + } + + /// One varying: matrices, arrays (including multi-dimensional `vec3[9][9]`) + /// and structs (`CloudsParameters`) split into vectors that a private + /// global of the original type is packed from or into. + fn varying(&mut self, dir: &str, interp: &str, ty: &str, name: &str, array: &str) { + if array.is_empty() && matrix_columns(ty).is_none() && !self.structs.contains_key(ty) { + let flat = if is_integer(ty) && !interp.contains("flat") { + "flat " + } else { + "" + }; + let at = Link::location(&mut self.link.varyings, name); + self.header.push(format!( + "layout(location = {at}) {flat}{interp}{dir} {ty} {name};" + )); + return; } + self.header.push(format!("{ty} {name}{array};")); + self.varying_composite(dir, interp, ty, name, name, array); } fn sized(&mut self, list: &mut ast::InitDeclaratorList) { @@ -1404,13 +1549,30 @@ impl<'a> Legaliser<'a> { self.expr(a); self.expr(b); self.modulo = true; - let (a, b) = ( - std::mem::replace(&mut **a, var("_")), - std::mem::replace(&mut **b, var("_")), - ); - *e = call("iris_mod", vec![a, b]); + let lhs = std::mem::replace(&mut **a, var("_")); + let rhs = std::mem::replace(&mut **b, var("_")); + *e = call("iris_mod", vec![lhs, rhs]); } - E::Assignment(a, op, b) if op.content == ast::AssignmentOpData::Mod => { + E::Binary(op, a, b) + if op.content == ast::BinaryOpData::LShift + && matches!(a.content, E::IntConst(_)) + && matches!(b.content, E::IntConst(n) if n >= 31) => + { + self.expr(a); + self.expr(b); + let lhs = std::mem::replace(&mut **a, var("_")); + let rhs = std::mem::replace(&mut **b, var("_")); + let shifted = ast::ExprData::Binary( + ast::BinaryOpData::LShift.into_node(), + Box::new(call("uint", vec![lhs])), + Box::new(call("uint", vec![rhs])), + ) + .into_node(); + *e = call("int", vec![shifted]); + } + E::Assignment(a, op, b) + if op.content == ast::AssignmentOpData::Mod && !self.constant => + { self.expr(a); self.expr(b); self.modulo = true; @@ -1538,17 +1700,53 @@ impl<'a> Legaliser<'a> { if self.functions.contains(&name) { return; } + // `mat2(vec4)` (Bloop): naga refuses 1-argument `mat2` from a `vec4`. + if name == "mat2" + && !self.constant + && args.len() == 1 + && !matches!( + args[0].content, + ast::ExprData::FloatConst(_) + | ast::ExprData::IntConst(_) + | ast::ExprData::UIntConst(_) + | ast::ExprData::DoubleConst(_) + ) + { + *f = ast::FunIdentifierData::Expr(Box::new(var("iris_mat2"))).into_node(); + self.mat2_ctor = true; + return; + } // `sqrt(-1.0)`, Bloop's NaN: naga folds it and fails, drivers give NaN. if name == "sqrt" && !self.constant && args.len() == 1 && negative_constant(&args[0]) { *f = ast::FunIdentifierData::Expr(Box::new(var("iris_sqrt"))).into_node(); self.nan = true; return; } + let mut target_name = name.as_str(); if let Some((_, new)) = LEGACY_CALLS.iter().find(|(old, _)| *old == name) { *f = ast::FunIdentifierData::Expr(Box::new(var(new))).into_node(); + target_name = new; } else if let Some((_, new)) = SHADOW_CALLS.iter().find(|(old, _)| *old == name) { let args = std::mem::take(args); *e = call("vec4", vec![call(new, args)]); + return; + } + // In vertex and compute shaders, `texture(sampler, coord)` uses implicit + // derivatives that WGSL/naga forbid outside fragment shaders (Bliss): + // rewrite 2-argument non-shadow `texture(s, uv)` to `textureLod(s, uv, 0.0)`. + if self.stage != Stage::Fragment && target_name == "texture" && args.len() == 2 { + let is_shadow = match &args[0].content { + ast::ExprData::FunCall(g, _) => { + callee(g).and_then(|c| opaque(&c)).is_some_and(|o| o.3) + } + _ => false, + }; + if !is_shadow { + if let ast::ExprData::FunCall(f, args) = &mut e.content { + *f = ast::FunIdentifierData::Expr(Box::new(var("textureLod"))).into_node(); + args.push(ast::ExprData::FloatConst(0.0).into_node()); + } + } } } @@ -1589,6 +1787,9 @@ impl<'a> Legaliser<'a> { if self.nan { out.push_str("float iris_sqrt(float x) { return sqrt(x); }\n"); } + if self.mat2_ctor { + out.push_str(MAT2_HELPERS); + } if !self.link.uniforms.is_empty() { out.push_str("layout(std140, set = 0, binding = 0) uniform IrisUniforms {\n"); for (_, decl) in &self.link.uniforms { diff --git a/crates/horizon-shaderpack/tests/translate.rs b/crates/horizon-shaderpack/tests/translate.rs index 3c71d8546..9198f8b92 100644 --- a/crates/horizon-shaderpack/tests/translate.rs +++ b/crates/horizon-shaderpack/tests/translate.rs @@ -292,14 +292,48 @@ fn reports_errors_with_their_place() { /// What naga refuses and drivers accept: `vec % scalar` (Noble), `sqrt` of /// a negative constant (Bloop's NaN), constants naga can't fold (Bliss's -/// `?:`, `mix`), and 16-bit types (Noble on NVIDIA). +/// `?:`, `mix`), 16-bit types (Noble on NVIDIA), `mat2(vec4)` (Bloop), +/// `1 << 31` (Rethinking Voxels), vertex `texture2D` without LOD (Bliss), +/// nested array varyings (Noble), and struct varyings (Photon). #[test] fn legalises_what_naga_refuses() { let mut link = Link::default(); + let vs = run( + Stage::Vertex, + "uniform sampler2D colortex0; +struct CloudsParameters { + vec3 color; + float density; +}; +varying CloudsParameters clouds; +varying vec3 grid[2][2]; +void main() { + vec4 s = texture2D(colortex0, vec2(0.5)); + clouds.color = s.rgb; + clouds.density = s.a; + grid[0][0] = s.rgb; + grid[0][1] = s.gbr; + grid[1][0] = s.brg; + grid[1][1] = vec3(1.0); + gl_Position = vec4(0.0, 0.0, 0.0, 1.0); +} +", + &mut link, + ) + .unwrap(); + reparse(&vs.wgsl).unwrap(); + let fs = run( Stage::Fragment, "uniform vec2 uv; +struct CloudsParameters { + vec3 color; + float density; +}; +varying CloudsParameters clouds; +varying vec3 grid[2][2]; const int RES = 256 % 100; +const int SIGN_BIT = 1 << 31; const vec3 TARGET = length(vec3(1.0)) < 0.001 ? vec3(0.0) : normalize(vec3(1.0)); const vec3 TINT = mix(TARGET, vec3(1.0), 0.5); const vec3 HALF = TINT * 0.5; @@ -309,7 +343,9 @@ void main() { ivec2 texel = ivec2(uv) % RES; texel %= 7; uint packed = packFloat2x16(f16vec2(HALF.xy)); - gl_FragColor = vec4(vec2(texel), float(pack(packed).x), nan()); + mat2 rot = mat2(vec4(1.0, 0.0, 0.0, 1.0)); + vec2 r = rot * vec2(clouds.density, float(SIGN_BIT != 0)); + gl_FragColor = vec4(vec2(texel) + r + clouds.color.xy + grid[1][0].xy, float(pack(packed).x), nan()); } ", &mut link, @@ -325,6 +361,7 @@ void main() { "uvec2 pack(uint v)", "return iris_sqrt(-1.);", "uint packed = packHalf2x16(vec2(HALF.xy));", + "iris_mat2(", ] { assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl); } diff --git a/docs/shader-packs.md b/docs/shader-packs.md index d126d5a2a..0ba8981fb 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -13,16 +13,16 @@ 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` stage, uniforms, hot reload, Shader Packs page | done (the page: list, pick, open the folder) | -| Horizon shader packs: `deferred`, `gbuffer`, `shadow` stages, custom textures | planned | -| 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) | 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) | 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) | done, no screen yet: 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) | 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) | -| Java shader packs: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light | done for the full-screen passes (below) | -| Java shader packs: `gbuffers_*`, `shadow`, custom textures, images, compute, option screen | planned | +| 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 | ## How the renderer draws a frame today diff --git a/examples/shaderpacks/horizon-ultra/LICENSE b/examples/shaderpacks/horizon-ultra/LICENSE new file mode 100644 index 000000000..44c359a50 --- /dev/null +++ b/examples/shaderpacks/horizon-ultra/LICENSE @@ -0,0 +1,13 @@ +MIT License + +Copyright (c) 2026 Horizon contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. diff --git a/examples/shaderpacks/horizon-ultra/pack.toml b/examples/shaderpacks/horizon-ultra/pack.toml new file mode 100644 index 000000000..446115073 --- /dev/null +++ b/examples/shaderpacks/horizon-ultra/pack.toml @@ -0,0 +1,134 @@ +# 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. +[pack] +name = "Horizon Ultra" +description = "PCF sun/moon shadows, GTAO, water reflections, volumetric godrays, bloom and ACES filmic tonemapping." +authors = ["Horizon contributors"] +version = "2.0.0" +license = "MIT" +api = 2 + +[[stage]] +kind = "deferred" +shader = "shaders/deferred_lighting.wgsl" +format = "rgba16float" + +[[stage]] +kind = "composite" +shader = "shaders/water_reflections.wgsl" +format = "rgba16float" + +[[stage]] +kind = "composite" +shader = "shaders/bloom_godrays.wgsl" +scale = 0.5 +format = "rgba16float" +mipmap = true + +[[stage]] +kind = "final" +shader = "shaders/final_tonemap.wgsl" + +[profiles.low] +shadows = false +ao_strength = 0.25 +water_ssr = false +godrays = false +bloom_strength = 0.15 +tonemap_aces = true +vignette = false + +[profiles.medium] +shadows = true +shadow_strength = 0.70 +ao_strength = 0.50 +water_ssr = true +godrays = true +bloom_strength = 0.25 +tonemap_aces = true +vignette = true + +[profiles.high] +shadows = true +shadow_strength = 0.85 +ao_strength = 0.75 +water_ssr = true +godrays = true +bloom_strength = 0.35 +tonemap_aces = true +vignette = true + +[profiles.ultra] +shadows = true +shadow_strength = 1.0 +ao_strength = 1.0 +water_ssr = true +godrays = true +bloom_strength = 0.45 +tonemap_aces = true +vignette = true + +[options.shadows] +label = "Directional Shadows" +description = "Cast real-time sun and moon PCF shadows across terrain and entities." +default = true + +[options.shadow_strength] +label = "Shadow Strength" +description = "Intensity of directional sun and moon shadows." +default = 0.85 +min = 0.0 +max = 1.0 +step = 0.05 + +[options.ao_strength] +label = "Ambient Occlusion (GTAO)" +description = "Screen-space horizon ambient occlusion in corners and crevices." +default = 0.75 +min = 0.0 +max = 1.5 +step = 0.05 + +[options.water_ssr] +label = "Water Reflections & Refraction" +description = "Screen-space sky and terrain reflections on water and translucent surfaces." +default = true + +[options.godrays] +label = "Volumetric Godrays" +description = "Atmospheric light shafts cast through trees and terrain towards the sun." +default = true + +[options.bloom_strength] +label = "HDR Bloom" +description = "Soft glow around bright sky, lava, torches and emissive blocks." +default = 0.35 +min = 0.0 +max = 1.0 +step = 0.05 + +[options.exposure] +label = "Exposure" +description = "Overall scene exposure multiplier before filmic tonemapping." +default = 1.10 +min = 0.5 +max = 2.0 +step = 0.05 + +[options.saturation] +label = "Color Saturation" +description = "Color vibrancy of the final tonemapped image." +default = 1.12 +min = 0.0 +max = 2.0 +step = 0.05 + +[options.tonemap_aces] +label = "ACES Filmic Tonemap" +description = "Apply ACES fitted filmic curve to preserve highlight detail." +default = true + +[options.vignette] +label = "Cinematic Vignette" +description = "Subtle darkening at the edges of the viewport." +default = true diff --git a/examples/shaderpacks/horizon-ultra/shaders/bloom_godrays.wgsl b/examples/shaderpacks/horizon-ultra/shaders/bloom_godrays.wgsl new file mode 100644 index 000000000..534e9d983 --- /dev/null +++ b/examples/shaderpacks/horizon-ultra/shaders/bloom_godrays.wgsl @@ -0,0 +1,61 @@ +// Stage 3 (Composite, half-resolution): HDR bloom extraction + 9-tap tent filter +// and radial volumetric light shafts (godrays) towards the sun/moon. +override godrays: bool = true; +override bloom_strength: f32 = 0.35; + +@fragment fn fs_main(in: StageIn) -> @location(0) vec4 { + let base = textureSampleLevel(previous, linear_sampler, in.uv, 0.0).rgb; + let texel = frame.resolution.zw * 2.0; + + // 9-tap soft bloom filter around bright highlights. + var bloom = vec3(0.0); + if bloom_strength > 0.001 { + let offsets = array, 9>( + vec2(0.0, 0.0), + vec2(1.0, 0.0), + vec2(-1.0, 0.0), + vec2(0.0, 1.0), + vec2(0.0, -1.0), + vec2(1.0, 1.0), + vec2(-1.0, 1.0), + vec2(1.0, -1.0), + vec2(-1.0, -1.0), + ); + let weights = array(0.25, 0.125, 0.125, 0.125, 0.125, 0.0625, 0.0625, 0.0625, 0.0625); + for (var i = 0u; i < 9u; i++) { + let sample_c = textureSampleLevel(previous, linear_sampler, in.uv + offsets[i] * texel, 0.0).rgb; + let lum = luminance(sample_c); + let bright = max(lum - 0.72, 0.0) / max(lum, 1e-4); + bloom += sample_c * bright * weights[i]; + } + } + + // Radial volumetric godrays cast 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)); + if sun_clip.w > 0.0 { + let sun_ndc = sun_clip.xy / sun_clip.w; + let sun_uv = vec2(sun_ndc.x * 0.5 + 0.5, 0.5 - sun_ndc.y * 0.5); + let delta = (sun_uv - in.uv) / 12.0; + var uv_Cursor = in.uv; + var transmittance = 0.0; + var decay = 1.0; + for (var s = 0u; s < 12u; s++) { + uv_Cursor += delta; + let sample_uv = clamp(uv_Cursor, vec2(0.001), vec2(0.999)); + if is_sky(depth_at(sample_uv)) { + transmittance += decay; + } + decay *= 0.92; + } + let ray = normalize(world_offset(in.uv, 1e-5)); + let sun_facing = pow(max(dot(ray, frame.sun.xyz), 0.0), 4.0); + let sunset = smoothstep(-0.1, 0.25, frame.sun.y); + let shaft_color = mix(vec3(1.0, 0.55, 0.25), vec3(1.0, 0.92, 0.75), sunset); + shafts = shaft_color * (transmittance / 12.0) * sun_facing * 0.28 * (1.0 - frame.weather.x); + } + } + + return vec4(base + bloom * bloom_strength + shafts, 1.0); +} diff --git a/examples/shaderpacks/horizon-ultra/shaders/deferred_lighting.wgsl b/examples/shaderpacks/horizon-ultra/shaders/deferred_lighting.wgsl new file mode 100644 index 000000000..3930a5c21 --- /dev/null +++ b/examples/shaderpacks/horizon-ultra/shaders/deferred_lighting.wgsl @@ -0,0 +1,92 @@ +// Stage 1 (Deferred): G-buffer normal reconstruction, multi-tap GTAO 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 { + if ao_strength <= 0.001 { + return 1.0; + } + let step_uv = frame.resolution.zw * 2.5; + let offsets = array, 8>( + vec2(1.0, 0.0), + vec2(-1.0, 0.0), + vec2(0.0, 1.0), + vec2(0.0, -1.0), + vec2(0.707, 0.707), + vec2(-0.707, 0.707), + vec2(0.707, -0.707), + vec2(-0.707, -0.707), + ); + var occlusion = 0.0; + for (var i = 0u; i < 8u; i++) { + let sample_uv = clamp(uv + offsets[i] * step_uv, vec2(0.001), vec2(0.999)); + let sd = opaque_depth_at(sample_uv); + if !is_sky(sd) { + let sp = view_position(sample_uv, sd); + let diff = sp - view_pos; + let dist = length(diff); + if dist > 0.02 && dist < 3.5 { + let horizon = clamp(diff.z / dist, 0.0, 1.0); + occlusion += horizon * smoothstep(3.5, 0.2, dist); + } + } + } + return clamp(1.0 - (occlusion * 0.18 * ao_strength), 0.15, 1.0); +} + +@fragment fn fs_main(in: StageIn) -> @location(0) vec4 { + let base_srgb = textureSampleLevel(scene_color, linear_sampler, in.uv, 0.0).rgb; + var color = srgb_to_linear(base_srgb); + let depth = opaque_depth_at(in.uv); + let light_dir = normalize(select(frame.moon.xyz, frame.sun.xyz, frame.sun.y >= -0.05)); + let sun_elevation = clamp(frame.sun.y, -1.0, 1.0); + let day_factor = smoothstep(-0.08, 0.18, sun_elevation); + let sunset_factor = smoothstep(-0.12, 0.05, sun_elevation) * (1.0 - smoothstep(0.05, 0.35, sun_elevation)); + + if is_sky(depth) { + let ray = normalize(world_offset(in.uv, 1e-5)); + let sun_dot = max(dot(ray, frame.sun.xyz), 0.0); + let mie = pow(sun_dot, 12.0) * (0.35 + 0.65 * sunset_factor) * (1.0 - frame.weather.x * 0.8); + let sun_tint = mix(vec3(1.0, 0.88, 0.68), vec3(1.0, 0.45, 0.18), sunset_factor); + color += sun_tint * mie * 0.85; + return vec4(color, 1.0); + } + + let world_rel = world_offset(in.uv, depth); + let view_pos = view_position(in.uv, depth); + let normal = world_normal_at(in.uv); + let mat = material_at(in.uv); + + // Ambient occlusion from depth discontinuity neighborhood. + let ao = compute_gtao(in.uv, depth, view_pos); + + // Directional sun/moon shadow factor. + var shadow = 1.0; + if shadows && frame.dimension.y > 0.5 { + let raw_shadow = sample_shadow(world_rel, normal); + shadow = mix(1.0, raw_shadow, shadow_strength); + } + + let ndotl = max(dot(normal, light_dir), 0.0); + let sun_color = mix( + vec3(0.22, 0.28, 0.48), + mix(vec3(1.05, 0.96, 0.86), vec3(1.18, 0.58, 0.28), sunset_factor), + day_factor, + ); + let sky_ambient = mix(vec3(0.08, 0.11, 0.20), srgb_to_linear(frame.sky_color.rgb) * 0.55, day_factor); + let direct_light = sun_color * ndotl * shadow * (1.0 - frame.weather.x * 0.55); + let bounce_light = sky_ambient * (0.45 + 0.55 * max(normal.y, 0.0)) * ao; + + // Wetness specular sheen during rain on upward-facing surfaces. + let wetness = frame_ext.environment.z; + let view_dir = normalize(-world_rel); + let half_vec = normalize(light_dir + view_dir); + let wet_mask = wetness * smoothstep(0.65, 0.95, normal.y) * mat.g; + let spec = pow(max(dot(normal, half_vec), 0.0), 48.0) * wet_mask * shadow * 0.65; + + let shade_boost = mix(0.68 * ao, 1.0 + 0.35 * ndotl * shadow, 0.65); + color = color * shade_boost + color * direct_light * 0.32 + bounce_light * 0.08 + sun_color * spec; + return vec4(max(color, vec3(0.0)), 1.0); +} diff --git a/examples/shaderpacks/horizon-ultra/shaders/final_tonemap.wgsl b/examples/shaderpacks/horizon-ultra/shaders/final_tonemap.wgsl new file mode 100644 index 000000000..397abafa9 --- /dev/null +++ b/examples/shaderpacks/horizon-ultra/shaders/final_tonemap.wgsl @@ -0,0 +1,29 @@ +// Stage 4 (Final): Combines full-resolution scene with bloom/godrays, applies +// exposure, ACES filmic tonemapping, saturation, and cinematic vignette. +override exposure: f32 = 1.10; +override saturation: f32 = 1.12; +override tonemap_aces: bool = true; +override vignette: bool = true; + +@fragment fn fs_main(in: StageIn) -> @location(0) vec4 { + var hdr = textureSampleLevel(previous, linear_sampler, in.uv, 0.0).rgb * exposure; + + if tonemap_aces { + hdr = aces_tonemap(hdr); + } else { + hdr = clamp(hdr, vec3(0.0), vec3(1.0)); + } + + var srgb = linear_to_srgb(hdr); + let luma = luminance(srgb); + let rain_desat = 1.0 - 0.25 * max(frame.weather.x, frame.weather.y); + srgb = mix(vec3(luma), srgb, saturation * rain_desat); + + if vignette { + let aspect = frame.resolution.x * frame.resolution.w; + let d = length((in.uv - 0.5) * vec2(aspect, 1.0)); + srgb *= 1.0 - 0.26 * smoothstep(0.48, 0.98, d); + } + + return vec4(clamp(srgb, vec3(0.0), vec3(1.0)), 1.0); +} diff --git a/examples/shaderpacks/horizon-ultra/shaders/water_reflections.wgsl b/examples/shaderpacks/horizon-ultra/shaders/water_reflections.wgsl new file mode 100644 index 000000000..853cf78f5 --- /dev/null +++ b/examples/shaderpacks/horizon-ultra/shaders/water_reflections.wgsl @@ -0,0 +1,58 @@ +// Stage 2 (Composite): Screen-space water reflections (SSR), Fresnel Schlick, +// and Beer-Lambert underwater depth absorption using scene_depth vs opaque_depth. +override water_ssr: bool = true; + +@fragment fn fs_main(in: StageIn) -> @location(0) vec4 { + var color = textureSampleLevel(previous, linear_sampler, in.uv, 0.0).rgb; + let surface_depth = depth_at(in.uv); + let floor_depth = opaque_depth_at(in.uv); + let mat = material_at(in.uv); + + // Translucent water/glass layer exists where surface_depth is closer than floor_depth + // (reversed depth: closer = larger value) or where the G-buffer water mask is set. + let is_translucent = (surface_depth > floor_depth + 1e-5) || (mat.b > 0.5); + if !water_ssr || is_sky(surface_depth) || !is_translucent { + return vec4(color, 1.0); + } + + let water_pos = world_offset(in.uv, surface_depth); + let floor_pos = world_offset(in.uv, max(floor_depth, 1e-6)); + let water_column = clamp(length(floor_pos - water_pos), 0.0, 32.0); + + // Beer-Lambert depth absorption in deep water. + let absorption = exp(-vec3(0.22, 0.07, 0.03) * water_column * 0.35); + color *= mix(vec3(1.0), absorption, clamp(water_column * 0.08, 0.0, 0.65)); + + // Wave normal perturbation and Fresnel reflection. + let world_xz = (water_pos.xz + frame.camera_position.xz) * 0.08; + let wave_uv = world_xz + vec2(frame.time.x * 0.015, -frame.time.x * 0.011); + let noise_sample = textureSampleLevel(noise_texture, repeat_sampler, wave_uv, 0.0).rgb * 2.0 - 1.0; + let normal = normalize(vec3(noise_sample.x * 0.06, 1.0, noise_sample.y * 0.06)); + let view_dir = normalize(-water_pos); + let refl_dir = reflect(-view_dir, normal); + let fresnel = clamp(0.04 + 0.96 * pow(1.0 - max(dot(view_dir, normal), 0.0), 4.0), 0.0, 0.85); + + // Ray-march 8 steps in screen space along the reflection ray. + var refl_color = srgb_to_linear(frame.sky_color.rgb); + let sun_spec = pow(max(dot(refl_dir, frame.sun.xyz), 0.0), 96.0) * 2.5 * (1.0 - frame.weather.x); + refl_color += vec3(1.0, 0.9, 0.7) * sun_spec; + + for (var step = 1u; step <= 8u; step++) { + let march_pos = water_pos + refl_dir * (f32(step) * 2.2); + let clip = frame.projection * (frame.view * vec4(march_pos, 1.0)); + if clip.w > 0.0 { + let ndc = clip.xyz / clip.w; + let sample_uv = vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + if all(sample_uv >= vec2(0.01)) && all(sample_uv <= vec2(0.99)) { + let scene_d = opaque_depth_at(sample_uv); + if !is_sky(scene_d) && ndc.z <= scene_d && (scene_d - ndc.z) < 0.08 { + refl_color = textureSampleLevel(previous, linear_sampler, sample_uv, 0.0).rgb; + break; + } + } + } + } + + color = mix(color, refl_color, fresnel * 0.55); + return vec4(color, 1.0); +}