From 7b35ca27998f246649869056389e57fb429f19aa Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 06:35:43 +0100 Subject: [PATCH] Shader packs, clean room 28: Sildurs Vibrant renders Three things kept Sildurs Vibrant black or wrong: - Matrix and array varyings (`varying mat3 tbnMatrix;`): wgpu's stage interfaces take only scalars and vectors, so the translator now carries each column or element as its own varying and copies them out of and into a private global around the pack's `main`. - Switch options defined in an included file whose name is not a shader extension (`#include "shaders.settings"`) were not read, so every `program..enabled` that tested them was false and the composites were skipped (OQ-13). - `fogStart`/`fogEnd` mixed the start of one of vanilla's two fogs with the end of the other, so on clear days fog began at the camera and Sildurs' water turned white. They now come as the pair of the fog that is complete nearer (OQ-36). Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/gfx/pack_uniforms.rs | 16 ++- crates/horizon-shaders/src/options.rs | 45 +++++-- crates/horizon-shaders/src/translate/mod.rs | 116 +++++++++++++++++- 3 files changed, 155 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/gfx/pack_uniforms.rs b/crates/horizon-client/src/gfx/pack_uniforms.rs index ad53b509a..21cfc2b14 100644 --- a/crates/horizon-client/src/gfx/pack_uniforms.rs +++ b/crates/horizon-client/src/gfx/pack_uniforms.rs @@ -233,12 +233,18 @@ impl FrameUniforms { for (smoothed, target) in self.eye_smooth.iter_mut().zip(eye) { *smoothed = smooth(*smoothed, target, 10.0 / 20.0, dt); } + // Vanilla fades by the stronger of two linear fogs; a pack gets one: the pair (start + // and end together) of the one that is complete nearer (OQ-36). Mixing the nearer start + // of one with the nearer end of the other made fog begin at the camera on clear days. let (fog_color, fog_start, fog_end) = match &frame.fog { - Some(f) => ( - [f.color[0], f.color[1], f.color[2]], - f.environmental_start.min(f.render_distance_start), - f.environmental_end.min(f.render_distance_end), - ), + Some(f) => { + let (start, end) = if f.environmental_end < f.render_distance_end { + (f.environmental_start, f.environmental_end) + } else { + (f.render_distance_start, f.render_distance_end) + }; + ([f.color[0], f.color[1], f.color[2]], start, end) + } None => (frame.sky.fog_color, frame.distance * 0.9, frame.distance), }; // The shadow camera (OQ-6, impl-plan.md): orthographic, `shadowDistance` (160) blocks diff --git a/crates/horizon-shaders/src/options.rs b/crates/horizon-shaders/src/options.rs index 687fd40e0..752dc12a0 100644 --- a/crates/horizon-shaders/src/options.rs +++ b/crates/horizon-shaders/src/options.rs @@ -1,8 +1,9 @@ //! Switch options (spec 8.1), as far as program-enable expressions (3.3) need them: which are on //! by default. A switch is `#define NAME` (on) or `//#define NAME` (off) with nothing after the //! name but a comment, in any stage or included file of the pack. Packs keep their options in -//! included `.glsl` files and test them elsewhere (OQ-13), so the test the spec asks for -//! (`#ifdef NAME` / `#ifndef NAME`) may be in any file of the pack. +//! included `.glsl` files (or files of any name a source includes) and test them elsewhere +//! (OQ-13), so the test the spec asks for (`#ifdef NAME` / `#ifndef NAME`) may be in any file +//! of the pack. use std::collections::BTreeSet; @@ -13,14 +14,27 @@ const SOURCES: [&str; 8] = ["vsh", "fsh", "gsh", "csh", "tcs", "tes", "glsl", "i /// The switch options that are on by default. pub fn switches_on(pack: &Pack) -> BTreeSet { let (mut on, mut off, mut tested) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new()); - for path in pack.all_files() { - let ext = path.rsplit_once('.').map_or("", |(_, e)| e); - if !SOURCES.contains(&ext) { - continue; - } - let Some(text) = pack.read_text(&path) else { - continue; - }; + let files = pack.all_files(); + let source = |path: &str| SOURCES.contains(&path.rsplit_once('.').map_or("", |(_, e)| e)); + let texts: Vec<(&String, String)> = files + .iter() + .filter(|p| source(p)) + .filter_map(|p| Some((p, pack.read_text(p)?))) + .collect(); + // Files of other names count when a source includes them (`#include "shaders.settings"`). + let included: BTreeSet<&str> = texts + .iter() + .flat_map(|(_, t)| t.lines()) + .filter_map(|l| l.trim().strip_prefix("#include")) + .map(|r| r.trim().trim_matches(|c| c == '"' || c == '<' || c == '>')) + .map(|r| r.rsplit('/').next().unwrap_or(r)) + .collect(); + let extra: Vec<(&String, String)> = files + .iter() + .filter(|p| !source(p) && included.contains(p.rsplit('/').next().unwrap_or(p))) + .filter_map(|p| Some((p, pack.read_text(p)?))) + .collect(); + for (_, text) in texts.iter().chain(&extra) { for line in text.lines() { let line = line.trim(); let (commented, rest) = match line.strip_prefix("//") { @@ -71,10 +85,19 @@ mod tests { "#ifdef AO\n#endif\n#ifndef BLOOM\n#endif\n#ifdef SPLIT\n#endif\n#ifdef LEVEL\n#endif\n", ), ("shaders/world-1/deferred.fsh", "//#define SPLIT\n"), + ( + "shaders/final.fsh", + "#include \"shaders.settings\"\n#ifdef GODRAYS\n#endif\n", + ), + ("shaders/shaders.settings", " #define GODRAYS //Toggle\n"), + ("shaders/notes.settings", "#define NOT_INCLUDED\n#ifdef NOT_INCLUDED\n"), ("shaders/shaders.properties", "#define NOT_SOURCE\n#ifdef NOT_SOURCE\n"), ]), ) .unwrap(); - assert_eq!(switches_on(&pack), BTreeSet::from(["AO".to_owned()])); + assert_eq!( + switches_on(&pack), + BTreeSet::from(["AO".to_owned(), "GODRAYS".to_owned()]) + ); } } diff --git a/crates/horizon-shaders/src/translate/mod.rs b/crates/horizon-shaders/src/translate/mod.rs index 35475ddab..96872da1d 100644 --- a/crates/horizon-shaders/src/translate/mod.rs +++ b/crates/horizon-shaders/src/translate/mod.rs @@ -204,13 +204,30 @@ fn translate( }) .collect(); - // Varyings by name: the vertex outputs, then fragment inputs the vertex stage lacks. + // Varyings by name: the vertex outputs, then fragment inputs the vertex stage lacks. A + // matrix or array travels as one varying per column or element (`varying_parts`). let mut locations: BTreeMap = BTreeMap::new(); + let mut split: BTreeMap)> = BTreeMap::new(); for var in v.outs.iter().chain(&f.ins) { - let next = locations.len() as u32; - locations - .entry(var.name.clone()) - .or_insert((next, var.decl.clone())); + if locations.contains_key(&var.name) || split.contains_key(&var.name) { + continue; + } + match varying_parts(&var.decl) { + Some((global, parts)) => { + let mut copies = Vec::new(); + for (k, (decl, access)) in parts.into_iter().enumerate() { + let part = format!("hz_v_{}_{k}", var.name); + let next = locations.len() as u32; + locations.insert(part.clone(), (next, decl)); + copies.push((part, access)); + } + split.insert(var.name.clone(), (global, copies)); + } + None => { + let next = locations.len() as u32; + locations.insert(var.name.clone(), (next, var.decl.clone())); + } + } } let header = |stage: &Stage| { @@ -255,6 +272,9 @@ fn translate( ) .unwrap(); } + for (name, (global, _)) in &split { + writeln!(h, "{}", global.replace("@", name)).unwrap(); + } if let (Some(inputs), ShaderStage::Vertex) = (gbuffers, stage.kind) { h.push_str(&inputs.declarations); h.push('\n'); @@ -292,9 +312,15 @@ fn translate( for name in &v.inits { writeln!(vertex_main, " {name} = hz_init_{name}();").unwrap(); } + vertex_main.push_str(" hz_main();\n"); + for (name, (_, copies)) in &split { + for (part, access) in copies { + writeln!(vertex_main, " {part} = {name}{access};").unwrap(); + } + } write!( vertex_main, - " hz_main();\n gl_Position = vec4(gl_Position.x, {flip}gl_Position.y, (gl_Position.z + gl_Position.w) * 0.5, gl_Position.w);\n{}}}\n", + " gl_Position = vec4(gl_Position.x, {flip}gl_Position.y, (gl_Position.z + gl_Position.w) * 0.5, gl_Position.w);\n{}}}\n", gbuffers.map_or("", |g| &g.after) ) .unwrap(); @@ -309,6 +335,11 @@ fn translate( Target::Buffers => " hz_FragCoord = gl_FragCoord;\n", }); } + for (name, (_, copies)) in &split { + for (part, access) in copies { + writeln!(fragment_main, " {name}{access} = {part};").unwrap(); + } + } for name in &f.inits { writeln!(fragment_main, " {name} = hz_init_{name}();").unwrap(); } @@ -363,6 +394,52 @@ fn translate( }) } +/// A matrix or array varying (`flat mat3 @[2];`): wgpu's stage interfaces take only scalars +/// and vectors (WGSL), so it becomes a private global (`mat3 @[2];`) and one varying per +/// column or element, each with the qualifiers and how to reach it (`[1][2]`). `None` for +/// scalars and vectors, and for sizes that are not plain numbers. +fn varying_parts(decl: &str) -> Option<(String, Vec<(String, String)>)> { + let (before, after) = decl.split_once('@')?; + let mut words: Vec<&str> = before.split_whitespace().collect(); + let ty = words.pop()?; + let qualifiers: String = words.iter().map(|w| format!("{w} ")).collect(); + let array = after.trim().trim_end_matches(';').trim(); + let mut sizes = Vec::new(); + let mut rest = array; + while let Some(r) = rest.strip_prefix('[') { + let (n, r) = r.split_once(']')?; + sizes.push(n.trim().parse::().ok()?); + rest = r.trim_start(); + } + if !rest.is_empty() { + return None; + } + // matC or matCxR: C columns of R rows. + let column = ty.strip_prefix("mat").and_then(|d| { + let (c, r) = d.split_once('x').unwrap_or((d, d)); + Some((c.parse::().ok()?, r.parse::().ok()?)) + }); + if sizes.is_empty() && column.is_none() { + return None; + } + let part_ty = column.map_or(ty.to_owned(), |(_, r)| format!("vec{r}")); + if let Some((c, _)) = column { + sizes.push(c); + } + let count: usize = sizes.iter().product(); + let parts = (0..count) + .map(|mut k| { + let mut access = String::new(); + for &size in sizes.iter().rev() { + access.insert_str(0, &format!("[{}]", k % size)); + k /= size; + } + (format!("{qualifiers}{part_ty} @;"), access) + }) + .collect(); + Some((format!("{ty} @{array};"), parts)) +} + /// `sampler2DShadow` → (`texture2D`, `samplerShadow`); `isampler3D` → (`itexture3D`, `sampler`). pub(super) fn split_sampler(ty: &str) -> (String, &'static str) { let shadow = ty.ends_with("Shadow"); @@ -643,6 +720,33 @@ mod tests { ); } + #[test] + fn matrix_and_array_varyings_travel_in_parts() { + let vsh = "#version 120\nvarying mat3 tbn;\nflat varying ivec2 ids[2];\nvarying mat2x3 m[2];\n\ + void main() {\n gl_Position = ftransform();\n tbn = mat3(2.0);\n \ + ids[1] = ivec2(3);\n m[1][0] = vec3(4.0);\n}\n"; + let fsh = "#version 120\nvarying mat3 tbn;\nflat varying ivec2 ids[2];\nvarying mat2x3 m[2];\n\ + void main() { gl_FragColor = vec4(tbn[2] + m[1][0], float(ids[1].x)); }\n"; + let p = program( + &[("composite.vsh", vsh), ("composite.fsh", fsh)], + Target::Buffers, + ) + .unwrap_or_else(|e| panic!("{e:?}")); + let inputs = p.fragment.entry_points[0].function.arguments.len(); + // 3 columns + 2 elements + 2 x 2 columns, and the fragment position. + assert!(inputs >= 9, "{inputs} inputs"); + assert_eq!( + varying_parts("flat ivec2 @[2];").unwrap().1, + [ + ("flat ivec2 @;".to_owned(), "[0]".to_owned()), + ("flat ivec2 @;".to_owned(), "[1]".to_owned()) + ] + ); + assert_eq!(varying_parts("mat2x3 @[2];").unwrap().1[3].1, "[1][1]"); + assert!(varying_parts("vec4 @;").is_none()); + assert!(varying_parts("vec4 @[N];").is_none()); + } + #[test] fn locals_may_hide_a_sampler() { let fsh = "#version 120\nuniform sampler2D specular;\nstruct M { float specular; };\n\