Skip to main content

alpha2_shaders/
lib.rs

1//! Reusable shader assets for the alpha2 render pipeline.
2//!
3//! Shader source lives under `shaders/`, never inline in Rust, and is split by
4//! how it reaches the GPU:
5//!
6//! - `shaders/build/*.wesl` are complete modules with their own entry points.
7//!   `build.rs` resolves their imports and flattens each one into WGSL at build
8//!   time, so they are embedded here already compiled.
9//! - `shaders/runtime/**/*.wgsl` are effect *bodies*, not modules. They are not
10//!   valid on their own: `alpha2-render` generates a per-effect preamble from
11//!   the effect's parameter schema and concatenates the body onto it, which is
12//!   why these cannot be resolved ahead of time.
13
14mod transitions;
15
16pub use transitions::{
17    ANGULAR, CIRCLE, CIRCLE_CROP, CIRCLE_OPEN, COLOR_PHASE, COLOUR_DISTANCE, CROSS_WARP,
18    DIRECTIONAL, DIRECTIONAL_WARP, DIRECTIONAL_WIPE, DREAMY, FADE, FADE_COLOR, FADE_GRAYSCALE,
19    HEART, MORPH, PINWHEEL, PIXELIZE, POLKA_DOTS_CURTAIN, RADIAL, RIPPLE, SIMPLE_ZOOM, SQUEEZE,
20    TRANSITION_HELPERS, WIND, WINDOW_BLINDS, WINDOW_SLICE, WIPE_DOWN, WIPE_LEFT, WIPE_RIGHT,
21    WIPE_UP,
22};
23
24/// Embeds a WESL module compiled by `build.rs` into `OUT_DIR`.
25macro_rules! built_module {
26    ($entry:literal) => {
27        include_str!(concat!(env!("OUT_DIR"), "/", $entry, ".wgsl"))
28    };
29}
30
31/// Full-screen triangle drawing a rendered frame onto a browser canvas.
32pub const CANVAS_PRESENT_WGSL: &str = built_module!("canvas-present");
33/// Full-screen triangle copying a premultiplied-alpha texel.
34pub const FULLSCREEN_TEXTURE_QUAD_WGSL: &str = built_module!("fullscreen-quad");
35/// Transform and blend one premultiplied RGBA layer over a backdrop.
36pub const COMPOSITE_WGSL: &str = built_module!("composite");
37/// GPU quantization from float intermediates into an RGBA8 readback texture.
38pub const READBACK_PACK_WGSL: &str = built_module!("readback-pack");
39/// GPU contain/rotation/premultiplication for browser-imported RGBA frames.
40pub const RGBA_PRESENT_WGSL: &str = built_module!("rgba-present");
41/// GPU conversion from premultiplied RGB intermediates into planar YUV420.
42pub const RGB_TO_YUV420_WGSL: &str = built_module!("rgb-to-yuv420");
43/// Sample-for-sample copy of decoded 8-bit 4:2:0 planes into NV12 targets.
44pub const YUV_REPACK_WGSL: &str = built_module!("yuv-repack");
45/// Limited/full-range BT.601/709/2020-NCL YUV plane conversion into linear RGB.
46pub const YUV_TO_LINEAR_WGSL: &str = built_module!("yuv-to-linear");
47/// [`YUV_TO_LINEAR_WGSL`] for 16-bit containers uploaded as unsigned
48/// integers, which it filters and normalizes itself.
49pub const YUV16_TO_LINEAR_WGSL: &str = built_module!("yuv16-to-linear");
50
51/// Author body for the built-in chroma-key effect.
52pub const CHROMA_KEY_BODY: &str = include_str!("../shaders/runtime/effects/chroma-key.wgsl");
53/// Author body for one axis pass of the built-in Gaussian blur cascade.
54pub const GAUSSIAN_BLUR: &str = include_str!("../shaders/runtime/effects/gaussian-blur.wgsl");
55/// Author body for the built-in resource-backed 3D LUT effect.
56pub const LUT_3D_BODY: &str = include_str!("../shaders/runtime/effects/lut-3d.wgsl");
57/// Body of a public effect the render graph expands into internal passes.
58pub const EXPANDED_EFFECT: &str = include_str!("../shaders/runtime/effects/expanded.wgsl");
59/// Built-in exposure, contrast, saturation, temperature, and tint body.
60pub const COLOR_CONTROLS: &str = include_str!("../shaders/runtime/effects/color-controls.wgsl");
61/// Built-in vignette body.
62pub const VIGNETTE: &str = include_str!("../shaders/runtime/effects/vignette.wgsl");
63/// Built-in sharpening body.
64pub const SHARPEN: &str = include_str!("../shaders/runtime/effects/sharpen.wgsl");
65/// Built-in pixelation body.
66pub const PIXELATE_EFFECT: &str = include_str!("../shaders/runtime/effects/pixelate.wgsl");
67/// Glow's first pass: the straight color above its threshold.
68pub const GLOW_THRESHOLD: &str = include_str!("../shaders/runtime/effects/glow-threshold.wgsl");
69/// Glow's last pass: the source with its blurred bloom added.
70pub const GLOW_COMBINE: &str = include_str!("../shaders/runtime/effects/glow-combine.wgsl");
71/// Built-in procedural film-grain body.
72pub const FILM_GRAIN: &str = include_str!("../shaders/runtime/effects/film-grain.wgsl");
73/// Built-in crop body.
74pub const CROP: &str = include_str!("../shaders/runtime/effects/crop.wgsl");
75/// Built-in mirror body.
76pub const MIRROR: &str = include_str!("../shaders/runtime/effects/mirror.wgsl");
77
78#[cfg(test)]
79mod tests {
80    use std::path::{Path, PathBuf};
81
82    fn shader_files(directory: &Path, files: &mut Vec<PathBuf>) {
83        for entry in std::fs::read_dir(directory).expect("shader directory") {
84            let path = entry.expect("shader entry").path();
85            if path.is_dir() {
86                shader_files(&path, files);
87            } else if path
88                .extension()
89                .is_some_and(|extension| extension == "wgsl" || extension == "wesl")
90            {
91                files.push(path);
92            }
93        }
94    }
95
96    /// `text` without `//` comments and with the whitespace gone, which is
97    /// all a search for a call needs. The shaders write no `/* */` comments.
98    fn code(text: &str) -> String {
99        text.lines()
100            .map(|line| line.split("//").next().unwrap_or_default())
101            .flat_map(str::chars)
102            .filter(|character| !character.is_whitespace())
103            .collect()
104    }
105
106    #[test]
107    fn no_built_in_shader_hashes_through_sin() {
108        // `fract(sin(x) * 43758.5453)` is not a hash on every GPU: large-argument `sin` has no
109        // required precision, so each driver's error gives a different value.
110        let mut files = Vec::new();
111        shader_files(
112            &Path::new(env!("CARGO_MANIFEST_DIR")).join("shaders"),
113            &mut files,
114        );
115        assert!(files.len() > 10, "found only {files:?}");
116        for file in files {
117            let text = std::fs::read_to_string(&file).expect("shader text");
118            assert!(!text.contains("/*"), "{}: block comment", file.display());
119            let code = code(&text);
120            assert!(
121                !code.contains("fract(sin("),
122                "{} hashes through fract(sin(...)); use an integer hash (PCG) instead",
123                file.display()
124            );
125        }
126    }
127
128    /// The first two arguments, without whitespace, of every call to the
129    /// built-in `smoothstep` in `text`, not counting the helpers whose names
130    /// end in it.
131    fn smoothstep_edges(text: &str) -> Vec<(String, String)> {
132        let text = text
133            .lines()
134            .map(|line| line.split("//").next().unwrap_or_default())
135            .collect::<Vec<_>>()
136            .join("\n");
137        let mut found = Vec::new();
138        let mut search = 0;
139        while let Some(offset) = text[search..].find("smoothstep") {
140            let start = search + offset;
141            search = start + "smoothstep".len();
142            let before = text[..start].chars().next_back();
143            let rest = text[search..].trim_start();
144            if before.is_some_and(|character| character.is_ascii_alphanumeric() || character == '_')
145                || !rest.starts_with('(')
146            {
147                continue;
148            }
149            let (mut depth, mut arguments, mut argument) = (0_usize, Vec::new(), String::new());
150            for character in rest[1..].chars() {
151                match character {
152                    '(' | '[' => depth += 1,
153                    ')' | ']' if depth == 0 => break,
154                    ')' | ']' => depth -= 1,
155                    ',' if depth == 0 => {
156                        arguments.push(std::mem::take(&mut argument));
157                        continue;
158                    }
159                    _ if character.is_whitespace() => continue,
160                    _ => {}
161                }
162                argument.push(character);
163            }
164            // A trailing comma leaves nothing after it.
165            if !argument.is_empty() {
166                arguments.push(argument);
167            }
168            let [edge0, edge1, _] = <[String; 3]>::try_from(arguments).expect("three arguments");
169            found.push((edge0, edge1));
170        }
171        found
172    }
173
174    #[test]
175    fn built_in_shaders_call_smoothstep_only_with_ascending_edges() {
176        // naga emits MSL/GLSL `smoothstep` and SPIR-V `SmoothStep`, which leave `edge0 >= edge1`
177        // undefined; descending ramps go through `builtin_smoothstep`. Each raw call below is
178        // ascending by its constants or its parameter's schema range.
179        let ascending = [
180            ("cross-warp.wgsl", "0.0", "1.0", "constants"),
181            ("ripple.wgsl", "0.2", "1.0", "constants"),
182            ("window-blinds.wgsl", "0.8", "1.0", "constants"),
183            (
184                "simple-zoom.wgsl",
185                "0.0",
186                "quickness",
187                "quickness is clamped to 0.2..1",
188            ),
189            (
190                "simple-zoom.wgsl",
191                "quickness-0.2",
192                "1.0",
193                "quickness is clamped to 0.2..1",
194            ),
195            (
196                "directional-warp.wgsl",
197                "-params.smoothness",
198                "0.0",
199                "smoothness >= 0.0001",
200            ),
201            (
202                "crop.wgsl",
203                "line-feather",
204                "line+feather",
205                "feather >= 0.0001, line in 0..1",
206            ),
207            (
208                "vignette.wgsl",
209                "params.radius-params.softness",
210                "params.radius+params.softness",
211                "softness >= 0.01, radius <= 1.5",
212            ),
213            // threshold <= sqrt(3) < 2, where f32 values are f32::EPSILON apart, and
214            // softness >= f32::EPSILON: the sum is at least the next value up.
215            (
216                "chroma-key.wgsl",
217                "params.threshold",
218                "params.threshold+params.softness",
219                "softness >= f32::EPSILON, threshold <= sqrt(3)",
220            ),
221        ];
222        let mut files = Vec::new();
223        shader_files(
224            &Path::new(env!("CARGO_MANIFEST_DIR")).join("shaders"),
225            &mut files,
226        );
227        let mut used = vec![false; ascending.len()];
228        for file in files {
229            let name = file
230                .file_name()
231                .and_then(|name| name.to_str())
232                .expect("name");
233            let text = std::fs::read_to_string(&file).expect("shader text");
234            for (edge0, edge1) in smoothstep_edges(&text) {
235                let listed = ascending.iter().position(|&(listed, low, high, _)| {
236                    (listed, low, high) == (name, edge0.as_str(), edge1.as_str())
237                });
238                let Some(index) = listed else {
239                    panic!(
240                        "{}: smoothstep({edge0}, {edge1}, ...) is not known to be ascending; \
241                         call builtin_smoothstep instead",
242                        file.display()
243                    );
244                };
245                used[index] = true;
246            }
247        }
248        for (index, entry) in ascending.iter().enumerate() {
249            assert!(used[index], "no longer called: {entry:?}");
250        }
251    }
252}