Skip to main content

alpha2_shaders/
lib.rs

1//! Reusable shader assets for the alpha2 render pipeline.
2//!
3//! - `shaders/build/*.wesl` are complete modules, flattened to WGSL by `build.rs`.
4//! - `shaders/runtime/**/*.wgsl` are effect bodies, not valid on their own: `alpha2-render`
5//!   prepends a preamble generated from each effect's parameter schema at runtime.
6
7mod effects;
8mod transitions;
9
10pub use effects::*;
11pub use transitions::*;
12
13/// Embeds a WESL module compiled by `build.rs` into `OUT_DIR`.
14macro_rules! built_module {
15    ($entry:literal) => {
16        include_str!(concat!(env!("OUT_DIR"), "/", $entry, ".wgsl"))
17    };
18}
19
20/// Full-screen triangle drawing a rendered frame onto a browser canvas.
21pub const CANVAS_PRESENT_WGSL: &str = built_module!("canvas-present");
22/// Full-screen triangle copying a premultiplied-alpha texel.
23pub const FULLSCREEN_TEXTURE_QUAD_WGSL: &str = built_module!("fullscreen-quad");
24/// Transform and blend one premultiplied RGBA layer over a backdrop.
25pub const COMPOSITE_WGSL: &str = built_module!("composite");
26/// GPU quantization from float intermediates into an RGBA8 readback texture.
27pub const READBACK_PACK_WGSL: &str = built_module!("readback-pack");
28/// GPU contain/rotation/premultiplication for browser-imported RGBA frames.
29pub const RGBA_PRESENT_WGSL: &str = built_module!("rgba-present");
30/// GPU conversion from premultiplied RGB intermediates into planar YUV420.
31pub const RGB_TO_YUV420_WGSL: &str = built_module!("rgb-to-yuv420");
32/// Sample-for-sample copy of decoded 8-bit 4:2:0 planes into NV12 targets.
33pub const YUV_REPACK_WGSL: &str = built_module!("yuv-repack");
34/// Limited/full-range BT.601/709/2020-NCL YUV plane conversion into linear RGB.
35pub const YUV_TO_LINEAR_WGSL: &str = built_module!("yuv-to-linear");
36/// [`YUV_TO_LINEAR_WGSL`] for 16-bit planes uploaded as unsigned integers, filtered in-shader.
37pub const YUV16_TO_LINEAR_WGSL: &str = built_module!("yuv16-to-linear");
38
39#[cfg(test)]
40mod tests {
41    use std::path::{Path, PathBuf};
42
43    fn shader_files(directory: &Path, files: &mut Vec<PathBuf>) {
44        for entry in std::fs::read_dir(directory).expect("shader directory") {
45            let path = entry.expect("shader entry").path();
46            if path.is_dir() {
47                shader_files(&path, files);
48            } else if path
49                .extension()
50                .is_some_and(|extension| extension == "wgsl" || extension == "wesl")
51            {
52                files.push(path);
53            }
54        }
55    }
56
57    /// `text` without `//` comments or whitespace. The shaders use no `/* */` comments.
58    fn code(text: &str) -> String {
59        text.lines()
60            .map(|line| line.split("//").next().unwrap_or_default())
61            .flat_map(str::chars)
62            .filter(|character| !character.is_whitespace())
63            .collect()
64    }
65
66    #[test]
67    fn no_built_in_shader_hashes_through_sin() {
68        // `fract(sin(x) * 43758.5453)` is not a portable hash: large-argument `sin` has no
69        // required precision.
70        let mut files = Vec::new();
71        shader_files(
72            &Path::new(env!("CARGO_MANIFEST_DIR")).join("shaders"),
73            &mut files,
74        );
75        assert!(files.len() > 10, "found only {files:?}");
76        for file in files {
77            let text = std::fs::read_to_string(&file).expect("shader text");
78            assert!(!text.contains("/*"), "{}: block comment", file.display());
79            let code = code(&text);
80            assert!(
81                !code.contains("fract(sin("),
82                "{} hashes through fract(sin(...)); use an integer hash (PCG) instead",
83                file.display()
84            );
85        }
86    }
87
88    /// The first two arguments of every built-in `smoothstep` call in `text`, excluding helpers
89    /// whose names end in it.
90    fn smoothstep_edges(text: &str) -> Vec<(String, String)> {
91        let text = text
92            .lines()
93            .map(|line| line.split("//").next().unwrap_or_default())
94            .collect::<Vec<_>>()
95            .join("\n");
96        let mut found = Vec::new();
97        let mut search = 0;
98        while let Some(offset) = text[search..].find("smoothstep") {
99            let start = search + offset;
100            search = start + "smoothstep".len();
101            let before = text[..start].chars().next_back();
102            let rest = text[search..].trim_start();
103            if before.is_some_and(|character| character.is_ascii_alphanumeric() || character == '_')
104                || !rest.starts_with('(')
105            {
106                continue;
107            }
108            let (mut depth, mut arguments, mut argument) = (0_usize, Vec::new(), String::new());
109            for character in rest[1..].chars() {
110                match character {
111                    '(' | '[' => depth += 1,
112                    ')' | ']' if depth == 0 => break,
113                    ')' | ']' => depth -= 1,
114                    ',' if depth == 0 => {
115                        arguments.push(std::mem::take(&mut argument));
116                        continue;
117                    }
118                    _ if character.is_whitespace() => continue,
119                    _ => {}
120                }
121                argument.push(character);
122            }
123            // A trailing comma leaves nothing after it.
124            if !argument.is_empty() {
125                arguments.push(argument);
126            }
127            let [edge0, edge1, _] = <[String; 3]>::try_from(arguments).expect("three arguments");
128            found.push((edge0, edge1));
129        }
130        found
131    }
132
133    #[test]
134    fn built_in_shaders_call_smoothstep_only_with_ascending_edges() {
135        // MSL, GLSL and SPIR-V leave `smoothstep` undefined for `edge0 >= edge1`, so descending
136        // ramps use `builtin_smoothstep`. Each raw call below is ascending by its constants or
137        // its parameter's schema range.
138        let ascending = [
139            ("cross-warp.wgsl", "0.0", "1.0", "constants"),
140            ("ripple.wgsl", "0.2", "1.0", "constants"),
141            ("window-blinds.wgsl", "0.8", "1.0", "constants"),
142            (
143                "simple-zoom.wgsl",
144                "0.0",
145                "quickness",
146                "quickness is clamped to 0.2..1",
147            ),
148            (
149                "simple-zoom.wgsl",
150                "quickness-0.2",
151                "1.0",
152                "quickness is clamped to 0.2..1",
153            ),
154            (
155                "directional-warp.wgsl",
156                "-params.smoothness",
157                "0.0",
158                "smoothness >= 0.0001",
159            ),
160            (
161                "crop.wgsl",
162                "line-feather",
163                "line+feather",
164                "feather >= 0.0001, line in 0..1",
165            ),
166            (
167                "vignette.wgsl",
168                "params.radius-params.softness",
169                "params.radius+params.softness",
170                "softness >= 0.01, radius <= 1.5",
171            ),
172            // threshold <= sqrt(3) < 2, where f32 steps are f32::EPSILON, and softness >=
173            // f32::EPSILON, so the sum is strictly greater.
174            (
175                "chroma-key.wgsl",
176                "params.threshold",
177                "params.threshold+params.softness",
178                "softness >= f32::EPSILON, threshold <= sqrt(3)",
179            ),
180        ];
181        let mut files = Vec::new();
182        shader_files(
183            &Path::new(env!("CARGO_MANIFEST_DIR")).join("shaders"),
184            &mut files,
185        );
186        let mut used = vec![false; ascending.len()];
187        for file in files {
188            let name = file
189                .file_name()
190                .and_then(|name| name.to_str())
191                .expect("name");
192            let text = std::fs::read_to_string(&file).expect("shader text");
193            for (edge0, edge1) in smoothstep_edges(&text) {
194                let listed = ascending.iter().position(|&(listed, low, high, _)| {
195                    (listed, low, high) == (name, edge0.as_str(), edge1.as_str())
196                });
197                let Some(index) = listed else {
198                    panic!(
199                        "{}: smoothstep({edge0}, {edge1}, ...) is not known to be ascending; \
200                         call builtin_smoothstep instead",
201                        file.display()
202                    );
203                };
204                used[index] = true;
205            }
206        }
207        for (index, entry) in ascending.iter().enumerate() {
208            assert!(used[index], "no longer called: {entry:?}");
209        }
210    }
211}