Shader packs, clean room 15: globals initialized at run time, switch options
naga keeps only constant initializers of globals, so every initialized global that is not `const` (and every conditional one) gets its value from a function of ours that main calls first, one per declarator, converting as GLSL's initialization does (`vec2 v = atlasSize`). `vec3 a = x, b = y;` no longer loses `b`. Program-enable expressions (3.3) now see the pack's switch options that are on by default (8.1): `#define NAME` with nothing after it, tested with `#ifdef`/`#ifndef` anywhere in the pack (OQ-13 working answer). BSL's `deferred` (ambient occlusion) and its TAA ran with options off before. Clean-room: implemented from cleanroom/shader-packs-spec.md revision 1, sections 3.3, 8.1; no other loader's code read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -17,6 +17,7 @@ mod config;
|
||||
mod discover;
|
||||
mod lang;
|
||||
mod macros;
|
||||
mod options;
|
||||
mod pack;
|
||||
mod post;
|
||||
mod preprocess;
|
||||
@@ -28,6 +29,7 @@ pub use config::{BUFFERS, Buffer, Config, Format, Kind, buffer_index, draw_buffe
|
||||
pub use discover::{Found, discover};
|
||||
pub use lang::Lang;
|
||||
pub use macros::{MC_VERSION, Macros, RENDER_STAGES};
|
||||
pub use options::switches_on;
|
||||
pub use pack::{Pack, PackError};
|
||||
pub use post::{Group, Post, PostProgram, dimension_folder, load_post};
|
||||
pub use preprocess::{Diagnostic, Origin, Preprocessed, preprocess};
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
//! 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.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::Pack;
|
||||
|
||||
const SOURCES: [&str; 8] = ["vsh", "fsh", "gsh", "csh", "tcs", "tes", "glsl", "inc"];
|
||||
|
||||
/// The switch options that are on by default.
|
||||
pub fn switches_on(pack: &Pack) -> BTreeSet<String> {
|
||||
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;
|
||||
};
|
||||
for line in text.lines() {
|
||||
let line = line.trim();
|
||||
let (commented, rest) = match line.strip_prefix("//") {
|
||||
Some(rest) => (true, rest.trim_start()),
|
||||
None => (false, line),
|
||||
};
|
||||
let Some((directive, rest)) = rest
|
||||
.strip_prefix('#')
|
||||
.map(str::trim_start)
|
||||
.and_then(|r| r.split_once(|c: char| c.is_whitespace()))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let mut words = rest.split_whitespace();
|
||||
let Some(name) = words.next() else { continue };
|
||||
match directive {
|
||||
"ifdef" | "ifndef" if !commented => _ = tested.insert(name.to_owned()),
|
||||
"define" if words.next().is_none_or(|w| w.starts_with("//")) => {
|
||||
let set = if commented { &mut off } else { &mut on };
|
||||
set.insert(name.to_owned());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Defined both ways is ambiguous (8.1): it keeps its default only where it is on everywhere.
|
||||
on.retain(|name| tested.contains(name) && !off.contains(name));
|
||||
on
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::pack::tests::zip;
|
||||
|
||||
#[test]
|
||||
fn switches_need_a_test_and_no_value() {
|
||||
let pack = Pack::from_zip_bytes(
|
||||
"P.zip",
|
||||
zip(&[
|
||||
(
|
||||
"shaders/lib/settings.glsl",
|
||||
" #define AO // ambient occlusion\n//#define BLOOM\n#define LEVEL 2 //[1 2]\n\
|
||||
#define SPLIT\n#define UNTESTED\n",
|
||||
),
|
||||
(
|
||||
"shaders/world0/deferred.fsh",
|
||||
"#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/shaders.properties", "#define NOT_SOURCE\n#ifdef NOT_SOURCE\n"),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(switches_on(&pack), BTreeSet::from(["AO".to_owned()]));
|
||||
}
|
||||
}
|
||||
@@ -167,6 +167,39 @@ impl Pack {
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
/// Every file of the pack, by its path inside `shaders`, sorted.
|
||||
pub fn all_files(&self) -> Vec<String> {
|
||||
let mut names = match &self.files {
|
||||
Files::Folder(root) => {
|
||||
let mut names = Vec::new();
|
||||
let mut dirs = vec![String::new()];
|
||||
while let Some(dir) = dirs.pop() {
|
||||
for e in fs::read_dir(root.join(&dir))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
{
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
let path = if dir.is_empty() {
|
||||
name
|
||||
} else {
|
||||
format!("{dir}/{name}")
|
||||
};
|
||||
match e.file_type() {
|
||||
Ok(t) if t.is_dir() => dirs.push(path),
|
||||
Ok(t) if t.is_file() => names.push(path),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
Files::Zip { entries, .. } => entries.keys().cloned().collect(),
|
||||
};
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
}
|
||||
|
||||
/// `a/./b/../c` → `a/c`; `None` for a path that climbs out of `shaders`.
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
//! - A program that fails to translate is reported and treated as missing (2.5).
|
||||
//! - Terrain draws with the first program of its fallback chain that loads (2.3).
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::config::{self, Config};
|
||||
use crate::{GbuffersInputs, Macros, Pack, Preprocessed, Program, Properties, Target};
|
||||
use crate::{eval_condition, preprocess, translate_composite, translate_gbuffers};
|
||||
@@ -99,6 +101,7 @@ pub fn load_post(
|
||||
folder,
|
||||
properties,
|
||||
macros,
|
||||
switches: crate::switches_on(pack),
|
||||
post: &mut post,
|
||||
};
|
||||
for (group, base) in GROUPS {
|
||||
@@ -135,6 +138,7 @@ struct Loader<'a> {
|
||||
folder: &'a str,
|
||||
properties: &'a Properties,
|
||||
macros: &'a Macros,
|
||||
switches: BTreeSet<String>,
|
||||
post: &'a mut Post,
|
||||
}
|
||||
|
||||
@@ -156,7 +160,13 @@ impl Loader<'_> {
|
||||
if !self.pack.exists(&fsh) || !self.pack.exists(&vsh) {
|
||||
return None;
|
||||
}
|
||||
if !enabled(self.properties, self.folder, &name, self.macros) {
|
||||
if !enabled(
|
||||
self.properties,
|
||||
self.folder,
|
||||
&name,
|
||||
self.macros,
|
||||
&self.switches,
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
if self.pack.exists(&path("gsh")) {
|
||||
@@ -215,8 +225,14 @@ fn diagnostics(pp: &Preprocessed) -> Vec<String> {
|
||||
}
|
||||
|
||||
/// `program.<name>.enabled` (or `program.<folder>/<name>.enabled`): a boolean expression over
|
||||
/// switch options (3.3). An option is on when its macro is defined.
|
||||
fn enabled(properties: &Properties, folder: &str, name: &str, macros: &Macros) -> bool {
|
||||
/// switch options (3.3): those on by default (8.1) and the defined macros.
|
||||
fn enabled(
|
||||
properties: &Properties,
|
||||
folder: &str,
|
||||
name: &str,
|
||||
macros: &Macros,
|
||||
switches: &BTreeSet<String>,
|
||||
) -> bool {
|
||||
let keys = [
|
||||
format!("program.{folder}/{name}.enabled"),
|
||||
format!("program.{name}.enabled"),
|
||||
@@ -230,6 +246,7 @@ fn enabled(properties: &Properties, folder: &str, name: &str, macros: &Macros) -
|
||||
match token {
|
||||
"true" => condition.push('1'),
|
||||
"false" => condition.push('0'),
|
||||
t if switches.contains(t) => condition.push('1'),
|
||||
t if t.starts_with(|c: char| c.is_alphabetic() || c == '_') => {
|
||||
condition.push_str(&format!("defined({t})"));
|
||||
}
|
||||
|
||||
@@ -472,6 +472,21 @@ mod tests {
|
||||
assert_eq!(i.outputs, [0, 1]);
|
||||
}
|
||||
|
||||
/// naga drops non-constant global initializers: they run in our `main`, one per declarator,
|
||||
/// converting as GLSL's initialization does.
|
||||
#[test]
|
||||
fn global_initializers_read_uniforms() {
|
||||
let fsh = "#version 120\nuniform float rainStrength;\nuniform ivec2 atlasSize;\n\
|
||||
vec2 size = atlasSize;\nvec3 a = vec3(rainStrength), b = a * 2.0, c;\n\
|
||||
const float k = rainStrength > 0.5 ? 1.0 : 0.0;\nfloat w[] = float[](rainStrength, 1.0);\n\
|
||||
void main() { c = b; gl_FragColor = vec4(a + c, size.x * k + w[0]); }\n";
|
||||
let p = program(
|
||||
&[("composite.vsh", VSH_120), ("composite.fsh", fsh)],
|
||||
Target::Window,
|
||||
);
|
||||
assert!(p.is_ok(), "{:?}", p.err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_programs_translate() {
|
||||
let vsh = "#version 330 core\nin vec3 vaPosition;\nin vec2 vaUV0;\nuniform mat4 modelViewMatrix, projectionMatrix;\n\
|
||||
|
||||
@@ -338,41 +338,115 @@ impl<'p> Stage<'p> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A global `T name = a ? b : c;`: naga can't evaluate a conditional at global scope, so
|
||||
/// the initializer becomes a function of ours on the same line (`T name; T hz_init_name() {
|
||||
/// return a ? b : c; }`), called by our `main` before the pack's.
|
||||
/// A global `T name = a ? b : c;` or, without `const`, any initialized global: naga only
|
||||
/// evaluates constant initializers at global scope (a conditional is not one; GL drivers
|
||||
/// also take uniforms and other globals there), so each initializer becomes a function of
|
||||
/// ours on the same line (`T a; T hz_init_a() { return T(...); } T b; ...`), called by our
|
||||
/// `main` before the pack's, in file order. The return converts as GLSL's initialization
|
||||
/// does (`vec2 v = ivec2(...)`).
|
||||
pub(super) fn initializer(&mut self, words: &[usize], to: usize) {
|
||||
let text = |i: usize| self.tokens[i];
|
||||
let Some(eq) = words.iter().position(|&i| text(i) == "=") else {
|
||||
return;
|
||||
};
|
||||
if !words[eq..].iter().any(|&i| text(i) == "?")
|
||||
|| words[..eq].iter().any(|&i| text(i) == ",")
|
||||
{
|
||||
// Declarators, split at top-level commas: (first word, `=` if any, end).
|
||||
let mut declarators = Vec::new();
|
||||
let (mut begin, mut nesting, mut assign) = (0, 0i32, None);
|
||||
for (n, &i) in words.iter().enumerate() {
|
||||
match text(i) {
|
||||
"(" | "[" | "{" => nesting += 1,
|
||||
")" | "]" | "}" => nesting -= 1,
|
||||
"=" if nesting == 0 && assign.is_none() => assign = Some(n),
|
||||
"," if nesting == 0 => {
|
||||
declarators.push((begin, assign.take(), n));
|
||||
begin = n + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
declarators.push((begin, assign, words.len()));
|
||||
let constant = words[..eq].iter().any(|&i| text(i) == "const");
|
||||
let conditional =
|
||||
|d: &(usize, Option<usize>, usize)| words[d.0..d.2].iter().any(|&i| text(i) == "?");
|
||||
if constant && !declarators.iter().any(conditional) {
|
||||
return;
|
||||
}
|
||||
let Some(name_at) = words[..eq].iter().rposition(|&i| is_ident(text(i))) else {
|
||||
// The first declarator's name ends the type.
|
||||
let first_end = declarators[0].1.unwrap_or(declarators[0].2);
|
||||
let Some(name_at) = words[..first_end].iter().rposition(|&i| is_ident(text(i))) else {
|
||||
return;
|
||||
};
|
||||
let name = text(words[name_at]).to_owned();
|
||||
let array: String = words[name_at + 1..eq].iter().map(|&i| text(i)).collect();
|
||||
let ty: Vec<&str> = words[..name_at]
|
||||
.iter()
|
||||
.map(|&i| text(i))
|
||||
.filter(|&t| t != "const")
|
||||
.collect();
|
||||
let Some(ty) = ty.last() else { return };
|
||||
// The type, with a `vec3[]`'s count written in.
|
||||
let mut ty = String::new();
|
||||
for &i in &words[..name_at] {
|
||||
match text(i) {
|
||||
"const" => {}
|
||||
"]" if ty.ends_with('[') => match self.array_length(i) {
|
||||
Some(n) => write!(ty, "{n}]").unwrap(),
|
||||
None => return,
|
||||
},
|
||||
t if ty.is_empty() || t == "[" => ty.push_str(t),
|
||||
// Qualifiers before the type (`highp`...): the type is the last word.
|
||||
t => ty = t.to_owned(),
|
||||
}
|
||||
}
|
||||
if ty.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut replaced = Vec::new();
|
||||
let mut names = Vec::new();
|
||||
for (n, &(begin, assign, end)) in declarators.iter().enumerate() {
|
||||
let name_at = if n == 0 { name_at } else { begin };
|
||||
let name = text(words[name_at]).to_owned();
|
||||
if !is_ident(&name) {
|
||||
return;
|
||||
}
|
||||
let stop = assign.unwrap_or(end);
|
||||
let mut array: String = words[name_at + 1..stop].iter().map(|&i| text(i)).collect();
|
||||
if array == "[]" {
|
||||
// `T x[] = T[](a, b)`: the count is written in, as the rewrite does for the name.
|
||||
match assign.and_then(|a| self.array_length(words[a - 1])) {
|
||||
Some(n) => array = format!("[{n}]"),
|
||||
None => return,
|
||||
}
|
||||
}
|
||||
let next = if n + 1 < declarators.len() {
|
||||
format!(" {ty}")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let end_token = words.get(end).copied().unwrap_or(to);
|
||||
match assign {
|
||||
Some(a) => {
|
||||
// Scalars, vectors and matrices convert; arrays and structs must match.
|
||||
let scalar = array.is_empty()
|
||||
&& !ty.contains('[')
|
||||
&& (matches!(ty.as_str(), "float" | "int" | "uint" | "bool")
|
||||
|| ty.contains("vec")
|
||||
|| ty.starts_with("mat"));
|
||||
let (open, close) = if scalar {
|
||||
(format!("{ty}("), ")")
|
||||
} else {
|
||||
(String::new(), "")
|
||||
};
|
||||
replaced.push((
|
||||
words[a],
|
||||
format!("; {ty}{array} hz_init_{name}() {{ return {open}"),
|
||||
));
|
||||
replaced.push((end_token, format!("{close}; }}{next}")));
|
||||
names.push(name);
|
||||
}
|
||||
None if n + 1 < declarators.len() => replaced.push((end_token, format!(";{next}"))),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
for &i in &words[..name_at] {
|
||||
if text(i) == "const" {
|
||||
self.removed.push(i..i + 1);
|
||||
}
|
||||
}
|
||||
self.replaced.insert(
|
||||
words[eq],
|
||||
format!("; {ty}{array} hz_init_{name}() {{ return"),
|
||||
);
|
||||
self.replaced.insert(to, "; }".into());
|
||||
self.inits.push(name);
|
||||
self.replaced.extend(replaced);
|
||||
self.inits.extend(names);
|
||||
}
|
||||
|
||||
/// A function definition or prototype: remember which parameters are samplers.
|
||||
|
||||
Reference in New Issue
Block a user