Skip to main content

nsh_core/
shader.rs

1//! Shaders: GPU programs apps write in WGSL, which a view draws its box with.
2//!
3//! An app writes one function, `fn shade(uv: vec2f) -> vec4f`, giving the
4//! color of the point `uv` of the view's box (0..1 from its top left
5//! corner, CSS's direction) as straight sRGB with alpha, the way CSS colors
6//! are: no linearization, the alpha not premultiplied. Besides its own
7//! functions and constants it reads the view's built-ins through `nsh`
8//! (`nsh.size`, the box in points; `nsh.time`, seconds since the shader
9//! appeared; `nsh.scale`, pixels per point) and, when it declares
10//! `struct Uniforms { … }`, its values through `uniforms`, which the app
11//! sets by name ([`ShaderLayer::new`]). The core wraps the function into a
12//! module of its own ([`Shader::compile`]): the two entry points the
13//! renderers draw a quad with (`nsh_vertex`, `nsh_fragment`, which
14//! premultiplies), the built-ins at `@group(0) @binding(0)` and the
15//! uniforms at `@binding(1)`.
16//!
17//! What a shader may do is checked here, in Rust, before any platform sees
18//! it: the source is at most [`MAX_SOURCE_BYTES`], it declares no entry
19//! points, bindings or resources of its own (only `var<private>` globals),
20//! its uniforms are numbers, vectors of `f32` and arrays of `vec4f`
21//! ([`UniformType`]) in at most [`MAX_UNIFORM_BYTES`], and the whole module
22//! validates (naga, the WGSL front end wgpu and browsers' WebGPU share).
23//! The platforms draw it at most once per display frame and only while the
24//! view is in sight, and only while something it reads changes: a shader
25//! reading `nsh.time` is [`Shader::animated`] and draws every frame unless
26//! paused, others draw when their size or uniforms change.
27//!
28//! The native backends render the module with wgpu (`nsh_engine::shader`), the web
29//! backend with WebGL 2 from the GLSL ES this module translates it into
30//! ([`Shader::glsl_es`], feature `glsl`).
31//!
32//! Animated values among the uniforms ([`UniformValue::Animated`]) become
33//! the layer's value slots ([`ShaderLayer::slots`]), bound to the view as
34//! [`crate::animation::AnimationProp::CanvasArg`]s: the platform writes
35//! their values into the uniforms ([`ShaderLayer::write_slot`]) and draws
36//! again on its own, without JS.
37//!
38//! # Pictures, effects and transitions
39//!
40//! Besides drawing a view's box under its children ([`ShaderRole::Fill`]),
41//! a shader can draw what other views draw: `sample_content(uv)` (the
42//! children of an effect, [`ShaderRole::Effect`], or the whole surface,
43//! [`ShaderRole::Screen`]), `sample_backdrop(uv)` (what is behind the view)
44//! and `sample_from(uv)` / `sample_to(uv)` (a transition's two sides,
45//! [`ShaderRole::Transition`] and [`ShaderRole::ScreenTransition`], and a
46//! page's or dialog's). Each returns straight sRGB with alpha, like
47//! `shade`, at the point `uv` of the box; outside its picture it is
48//! transparent. `nsh.progress` is an effect's `progress` or how far a
49//! transition is (0 to 1); `nsh.overflow` is how far beyond the box the
50//! shader draws and its pictures reach, in points (`maxSampleOffset`): the
51//! frame then covers `uv` from `-overflow / size` to `1 + overflow / size`.
52//! The platforms take the pictures ([`Shader::inputs`] says which) and the
53//! renderers bind them at `@binding(2)` (a sampler) and `@binding(3)` to
54//! `@binding(6)`; [`crossfade`] is the transitions' default.
55
56use std::{
57    fmt,
58    hash::{Hash, Hasher},
59    sync::Arc,
60};
61
62#[cfg(feature = "shader")]
63use naga::{
64    AddressSpace, ArraySize, Expression, Handle, Module, ScalarKind, TypeInner, VectorSize,
65    valid::{Capabilities, ModuleInfo, ValidationFlags, Validator},
66};
67
68use crate::{
69    Color,
70    animation::{AnimationValue, NodeId},
71    geometry::{Percentage, Points, Size},
72};
73
74/// The longest source a shader may have, in bytes.
75pub const MAX_SOURCE_BYTES: usize = 64 * 1024;
76
77/// The most bytes `struct Uniforms` may take.
78pub const MAX_UNIFORM_BYTES: u32 = 4096;
79
80#[cfg(feature = "shader")]
81/// The function an app's source defines.
82const SHADE: &str = "shade";
83
84#[cfg(feature = "shader")]
85/// What the core adds to the app's source: the built-ins and the entry
86/// points (WGSL declarations may come in any order, so the app's source
87/// goes first and its lines keep their numbers).
88const BUILTINS: &str = r#"
89// 32 bytes, as `builtins` writes them: wgpu's GL backend refuses a uniform
90// struct whose size is no multiple of 16 where the device lacks
91// `BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED`, so `overflow` pads it.
92struct Nsh {
93    size: vec2f,
94    time: f32,
95    scale: f32,
96    progress: f32,
97    @size(12) overflow: f32,
98}
99
100@group(0) @binding(0) var<uniform> nsh: Nsh;
101
102@group(0) @binding(2) var nsh_sampler: sampler;
103@group(0) @binding(3) var nsh_content: texture_2d<f32>;
104@group(0) @binding(4) var nsh_backdrop: texture_2d<f32>;
105@group(0) @binding(5) var nsh_from: texture_2d<f32>;
106@group(0) @binding(6) var nsh_to: texture_2d<f32>;
107
108// A point of the box in the pictures, which cover it and `overflow` points
109// beyond each side.
110fn nsh_picture(uv: vec2f) -> vec2f {
111    return (uv * nsh.size + nsh.overflow) / max(nsh.size + 2.0 * nsh.overflow, vec2f(1e-6));
112}
113
114// A premultiplied texel as straight color; transparent outside the picture.
115fn nsh_straight(c: vec4f, p: vec2f) -> vec4f {
116    if (any(p < vec2f(0.0)) || any(p > vec2f(1.0)) || c.a <= 0.0) {
117        return vec4f(0.0);
118    }
119    return vec4f(c.rgb / c.a, c.a);
120}
121
122fn sample_content(uv: vec2f) -> vec4f {
123    let p = nsh_picture(uv);
124    return nsh_straight(textureSampleLevel(nsh_content, nsh_sampler, p, 0.0), p);
125}
126
127fn sample_backdrop(uv: vec2f) -> vec4f {
128    let p = nsh_picture(uv);
129    return nsh_straight(textureSampleLevel(nsh_backdrop, nsh_sampler, p, 0.0), p);
130}
131
132fn sample_from(uv: vec2f) -> vec4f {
133    let p = nsh_picture(uv);
134    return nsh_straight(textureSampleLevel(nsh_from, nsh_sampler, p, 0.0), p);
135}
136
137fn sample_to(uv: vec2f) -> vec4f {
138    let p = nsh_picture(uv);
139    return nsh_straight(textureSampleLevel(nsh_to, nsh_sampler, p, 0.0), p);
140}
141"#;
142
143#[cfg(feature = "shader")]
144const UNIFORMS: &str = "\n@group(0) @binding(1) var<uniform> uniforms: Uniforms;\n";
145
146#[cfg(feature = "shader")]
147const ENTRY_POINTS: &str = r#"
148struct NshVarying {
149    @builtin(position) position: vec4f,
150    @location(0) uv: vec2f,
151}
152
153@vertex
154fn nsh_vertex(@builtin(vertex_index) index: u32) -> NshVarying {
155    // One triangle covering the target: uv 0..1 over the box, y down, and
156    // past it by `overflow` points on each side.
157    let corner = vec2f(f32((index << 1u) & 2u), f32(index & 2u));
158    let grow = nsh.overflow / max(nsh.size, vec2f(1e-6));
159    var out: NshVarying;
160    out.position = vec4f(corner.x * 2.0 - 1.0, 1.0 - corner.y * 2.0, 0.0, 1.0);
161    out.uv = corner * (1.0 + 2.0 * grow) - grow;
162    return out;
163}
164
165@fragment
166fn nsh_fragment(in: NshVarying) -> @location(0) vec4f {
167    let color = clamp(shade(in.uv), vec4f(0.0), vec4f(1.0));
168    return vec4f(color.rgb * color.a, color.a);
169}
170"#;
171
172#[cfg(feature = "shader")]
173/// The index of `time` in `struct Nsh`.
174const TIME_MEMBER: u32 = 1;
175
176/// The words of the built-ins (`struct Nsh`): the box's size in points,
177/// the seconds since the shader appeared, the pixels per point, the
178/// progress (0 to 1) and the overflow in points, as the renderers upload
179/// them to `@binding(0)` (32 bytes).
180pub fn builtins(
181    size: Size<Points>,
182    time: f32,
183    scale: f32,
184    progress: Percentage,
185    overflow: Points,
186) -> [u32; 8] {
187    [
188        size.width.0.to_bits(),
189        size.height.0.to_bits(),
190        time.to_bits(),
191        scale.to_bits(),
192        progress.0.to_bits(),
193        overflow.0.to_bits(),
194        0,
195        0,
196    ]
197}
198
199/// The pictures a shader can read.
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
201#[non_exhaustive]
202pub enum ShaderInput {
203    /// `sample_content`: an effect's children, a screen effect's surface.
204    Content,
205    /// `sample_backdrop`: what is behind the view.
206    Backdrop,
207    /// `sample_from`: a transition's side it leaves.
208    From,
209    /// `sample_to`: a transition's side it comes to.
210    To,
211}
212
213impl ShaderInput {
214    /// Every input, in their bindings' order (`@binding(3)` to `@binding(6)`).
215    pub const ALL: [ShaderInput; 4] = [
216        ShaderInput::Content,
217        ShaderInput::Backdrop,
218        ShaderInput::From,
219        ShaderInput::To,
220    ];
221
222    /// Its index (0 to 3; the binding is 3 more).
223    pub fn index(self) -> usize {
224        self as usize
225    }
226
227    /// The function the app calls to read it.
228    pub fn function(self) -> &'static str {
229        match self {
230            ShaderInput::Content => "sample_content",
231            ShaderInput::Backdrop => "sample_backdrop",
232            ShaderInput::From => "sample_from",
233            ShaderInput::To => "sample_to",
234        }
235    }
236
237    /// The texture's global in the module.
238    pub fn texture(self) -> &'static str {
239        match self {
240            ShaderInput::Content => "nsh_content",
241            ShaderInput::Backdrop => "nsh_backdrop",
242            ShaderInput::From => "nsh_from",
243            ShaderInput::To => "nsh_to",
244        }
245    }
246}
247
248/// The set of [`ShaderInput`]s a shader reads.
249#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
250pub struct ShaderInputs(u8);
251
252impl ShaderInputs {
253    /// Whether it reads `input`.
254    pub fn contains(self, input: ShaderInput) -> bool {
255        self.0 & (1 << input.index()) != 0
256    }
257
258    /// Whether it reads none.
259    pub fn is_empty(self) -> bool {
260        self.0 == 0
261    }
262
263    /// It with `input`.
264    pub fn with(self, input: ShaderInput) -> Self {
265        ShaderInputs(self.0 | 1 << input.index())
266    }
267
268    /// The inputs it reads.
269    pub fn iter(self) -> impl Iterator<Item = ShaderInput> {
270        ShaderInput::ALL
271            .into_iter()
272            .filter(move |i| self.contains(*i))
273    }
274}
275
276/// What a layer draws, which decides where the platform shows it and which
277/// pictures it takes.
278#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
279#[non_exhaustive]
280pub enum ShaderRole {
281    /// A shader view: the box under its children (upstream's `Shader`).
282    #[default]
283    Fill,
284    /// An effect: its children draw through it, their picture is the
285    /// content; the result shows where they are.
286    Effect,
287    /// A transition: while one runs (`MountItem::ShaderTransition`), its
288    /// children change through it, their picture before as `from`, their
289    /// drawing now as `to`; otherwise they show as they are.
290    Transition,
291    /// A screen effect: the whole surface draws through it, its picture the
292    /// content.
293    Screen,
294    /// A screen transition: the whole surface changes through it.
295    ScreenTransition,
296}
297
298/// `progress`: `nsh.progress` as a number, or moved natively by an
299/// animated value.
300#[derive(Debug, Clone, Copy, PartialEq)]
301pub enum ShaderProgress {
302    /// A fraction (0 to 1, by convention; a spring may overshoot it).
303    Number(Percentage),
304    /// The animated value of this node.
305    Animated(NodeId),
306}
307
308impl Default for ShaderProgress {
309    fn default() -> Self {
310        ShaderProgress::Number(Percentage(0.0))
311    }
312}
313
314/// A transition's `value`: when it changes, the transition runs.
315#[derive(Debug, Clone, PartialEq, Eq, Hash)]
316pub enum TransitionKey {
317    /// A string.
318    String(Arc<str>),
319    /// A number (its bits; made by [`TransitionKey::number`]).
320    Number(u64),
321    /// A boolean.
322    Bool(bool),
323}
324
325impl From<&str> for TransitionKey {
326    fn from(s: &str) -> Self {
327        TransitionKey::String(s.into())
328    }
329}
330
331impl TransitionKey {
332    /// A number as a key: equal numbers are equal keys, as JS compares
333    /// them (`0` and `-0` are one key; every NaN is one key).
334    pub fn number(n: f64) -> Self {
335        let n = if n == 0.0 {
336            0.0
337        } else if n.is_nan() {
338            f64::NAN
339        } else {
340            n
341        };
342        TransitionKey::Number(n.to_bits())
343    }
344}
345
346impl From<f64> for TransitionKey {
347    fn from(n: f64) -> Self {
348        TransitionKey::number(n)
349    }
350}
351
352impl From<bool> for TransitionKey {
353    fn from(b: bool) -> Self {
354        TransitionKey::Bool(b)
355    }
356}
357
358/// A page's or a dialog's `transitionShader`: the program it comes and
359/// goes through, its uniforms and how long that takes.
360#[derive(Debug, Clone, Default, PartialEq)]
361#[non_exhaustive]
362pub struct NavShaderSpec {
363    /// The WGSL defining `shade`, which reads the lower side as
364    /// `sample_from` and the upper as `sample_to`.
365    pub source: Arc<str>,
366    /// Its uniforms.
367    pub uniforms: ShaderUniforms,
368    /// How long it runs in milliseconds; 350 when absent, about as long as
369    /// the platforms' own push (an element's `ShaderTransition` takes 300).
370    pub duration: Option<f32>,
371}
372
373/// A page's or a dialog's transition program, built in Rust
374/// (`Screen::transition_shader`,
375/// `Modal::transition_shader`;
376/// TS: `transitionShader`): a compiled [`Shader`] defining `shade`, which
377/// reads the lower side as `sample_from` and the upper as `sample_to`.
378#[derive(Debug, Clone, Default, PartialEq)]
379pub struct TransitionShader(NavShaderSpec);
380
381impl TransitionShader {
382    /// Runs `shader`, with no uniforms, for 350 ms.
383    pub fn new(shader: Shader) -> Self {
384        Self(NavShaderSpec {
385            source: shader.source().into(),
386            uniforms: ShaderUniforms::default(),
387            duration: None,
388        })
389    }
390
391    /// Sets the member `name` of the shader's `struct Uniforms` to `value`:
392    /// a number, a color or a list (a vector, an array of `vec4f`).
393    pub fn uniform(mut self, name: &str, value: impl Into<UniformValue>) -> Self {
394        let value = value.into();
395        match self.0.uniforms.0.iter_mut().find(|(n, _)| &**n == name) {
396            Some(entry) => entry.1 = value,
397            None => self.0.uniforms.0.push((name.into(), value)),
398        }
399        self
400    }
401
402    /// How long it runs (350 ms by default).
403    pub fn duration(mut self, duration: std::time::Duration) -> Self {
404        self.0.duration = Some(duration.as_secs_f32() * 1000.0);
405        self
406    }
407}
408
409impl From<TransitionShader> for NavShaderSpec {
410    fn from(shader: TransitionShader) -> Self {
411        shader.0
412    }
413}
414
415/// The word a progress slot writes ([`ShaderLayer::slots`]): not one of the
416/// uniforms, the built-in `nsh.progress`.
417pub const PROGRESS_WORD: u32 = u32::MAX;
418
419/// The name of [`note_use`], which `nsh-cli` looks for in a web runtime's
420/// symbol table to know the app shows a shader (it then keeps the
421/// `nsh_feature_shader` gate). A test below fails when the two stop matching.
422pub const USE_MARKER: &str = "note_use";
423
424/// Called by everything an app makes a shader view or a shader transition
425/// with. It is never inlined and its own address escapes, so every such
426/// call keeps a reference to this one function.
427#[inline(never)]
428pub(crate) fn note_use() {
429    std::hint::black_box(note_use as fn());
430}
431
432/// The transitions' default program: a cross-fade from `sample_from` to
433/// `sample_to` over `nsh.progress`. `None` only in a web runtime linked
434/// without shaders ([`set_compile`]), which has no transition to run it
435/// on: compiled with this module's compiler, so the cross-fade does not
436/// link naga into every web runtime.
437pub fn crossfade() -> Option<Shader> {
438    static CROSSFADE: std::sync::OnceLock<Option<Shader>> = std::sync::OnceLock::new();
439    CROSSFADE
440        .get_or_init(|| {
441            compile_source(
442                "fn shade(uv: vec2f) -> vec4f {\n    return mix(sample_from(uv), sample_to(uv), nsh.progress);\n}\n",
443            )
444            .map_err(|e| log::warn!(target: "js", "the cross-fade: {e}"))
445            .ok()
446        })
447        .clone()
448}
449
450/// Why a shader did not compile: what is wrong and where in the app's
451/// source (1-based; 0 when the error is not at a place in it).
452#[derive(Debug, Clone, Default, PartialEq, Eq)]
453#[non_exhaustive]
454pub struct ShaderError {
455    /// What is wrong.
456    pub message: String,
457    /// The line, from 1 (0: none).
458    pub line: u32,
459    /// The column in bytes, from 1 (0: none).
460    pub column: u32,
461}
462
463impl ShaderError {
464    fn new(message: impl Into<String>) -> Self {
465        ShaderError {
466            message: message.into(),
467            line: 0,
468            column: 0,
469        }
470    }
471
472    #[cfg(feature = "shader")]
473    fn at(message: impl Into<String>, source: &str, offset: Option<usize>) -> Self {
474        let mut error = ShaderError::new(message);
475        if let Some(offset) = offset.filter(|&o| o <= source.len()) {
476            let prefix = &source[..offset];
477            error.line = prefix.matches('\n').count() as u32 + 1;
478            error.column = (offset - prefix.rfind('\n').map_or(0, |p| p + 1)) as u32 + 1;
479        }
480        error
481    }
482}
483
484impl fmt::Display for ShaderError {
485    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486        if self.line > 0 {
487            write!(f, "{}:{}: {}", self.line, self.column, self.message)
488        } else {
489            f.write_str(&self.message)
490        }
491    }
492}
493
494impl std::error::Error for ShaderError {}
495
496/// The type of a member of `struct Uniforms`.
497#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
498pub enum UniformType {
499    /// `f32`.
500    #[default]
501    F32,
502    /// `i32`.
503    I32,
504    /// `u32`.
505    U32,
506    /// `vec2f`.
507    Vec2,
508    /// `vec3f`: three numbers, or a color's red, green and blue.
509    Vec3,
510    /// `vec4f`: four numbers, or a color with its alpha.
511    Vec4,
512    /// `array<vec4f, N>`: up to `N` vectors or colors (a palette, the stops
513    /// of a gradient); those not given are zero.
514    Vec4Array(u32),
515}
516
517impl UniformType {
518    /// Its WGSL spelling.
519    pub fn wgsl(self) -> String {
520        match self {
521            UniformType::F32 => "f32".into(),
522            UniformType::I32 => "i32".into(),
523            UniformType::U32 => "u32".into(),
524            UniformType::Vec2 => "vec2f".into(),
525            UniformType::Vec3 => "vec3f".into(),
526            UniformType::Vec4 => "vec4f".into(),
527            UniformType::Vec4Array(n) => format!("array<vec4f, {n}>"),
528        }
529    }
530}
531
532/// A member of `struct Uniforms`: its name, type and place in the buffer.
533#[derive(Debug, Clone, Default, PartialEq, Eq)]
534#[non_exhaustive]
535pub struct UniformField {
536    /// Its name, which the app sets it by.
537    pub name: Arc<str>,
538    /// Its type.
539    pub ty: UniformType,
540    /// Its offset in bytes (a multiple of 4).
541    pub offset: u32,
542}
543
544/// The WGSL modules the GLSL ES 3.00 a WebGL 2 context compiles
545/// ([`Shader::glsl_es`]).
546#[cfg(feature = "glsl")]
547#[derive(Debug, Clone, Default, PartialEq, Eq)]
548#[non_exhaustive]
549pub struct GlslProgram {
550    /// The vertex shader.
551    pub vertex: String,
552    /// The fragment shader.
553    pub fragment: String,
554    /// The name of the uniform block of the built-ins in `fragment`, when
555    /// it reads them (bind it to 0).
556    pub builtins_block: Option<String>,
557    /// The name of the uniform block of `struct Uniforms`, when it reads it
558    /// (bind it to 1).
559    pub uniforms_block: Option<String>,
560    /// The sampler uniforms of the pictures it reads, by input.
561    pub pictures: Vec<(String, ShaderInput)>,
562}
563
564/// A compiled shader: the app's source checked and wrapped into a module
565/// every renderer draws (cheap to clone; equal when their sources are).
566#[derive(Clone)]
567pub struct Shader(Arc<Program>);
568
569// Made only by the compiler (feature `shader`).
570#[cfg_attr(not(feature = "shader"), allow(dead_code))]
571struct Program {
572    source: Arc<str>,
573    hash: u64,
574    wgsl: String,
575    // The GLSL writer's input.
576    #[cfg(feature = "shader")]
577    #[cfg_attr(not(feature = "glsl"), allow(dead_code))]
578    module: Module,
579    #[cfg(feature = "shader")]
580    #[cfg_attr(not(feature = "glsl"), allow(dead_code))]
581    info: ModuleInfo,
582    uniforms: Vec<UniformField>,
583    uniform_size: u32,
584    animated: bool,
585    inputs: ShaderInputs,
586    #[cfg(feature = "glsl")]
587    glsl: std::sync::OnceLock<Result<GlslProgram, ShaderError>>,
588}
589
590impl fmt::Debug for Shader {
591    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592        f.debug_struct("Shader")
593            .field("hash", &format_args!("{:016x}", self.0.hash))
594            .field("uniforms", &self.0.uniforms)
595            .field("animated", &self.0.animated)
596            .finish()
597    }
598}
599
600impl PartialEq for Shader {
601    fn eq(&self, other: &Shader) -> bool {
602        Arc::ptr_eq(&self.0, &other.0)
603            || (self.0.hash == other.0.hash && self.0.source == other.0.source)
604    }
605}
606
607impl Eq for Shader {}
608
609/// The hash of a shader's source (what [`Shader::hash`] gives, and what
610/// caches of compiled shaders are keyed by).
611pub fn source_hash(source: &str) -> u64 {
612    let mut hasher = rustc_hash::FxHasher::default();
613    source.hash(&mut hasher);
614    hasher.finish()
615}
616
617/// What compiles the apps' shader sources in this module ([`Shader::compile`],
618/// which links naga).
619pub type Compile = fn(&str) -> Result<Shader, ShaderError>;
620
621#[cfg(target_arch = "wasm32")]
622thread_local! {
623    /// The compiler a web runtime linked: one built for an app that uses no
624    /// shader leaves it out, naga with it ([`set_compile`]).
625    static COMPILE: std::cell::Cell<Option<Compile>> = const { std::cell::Cell::new(None) };
626}
627
628/// Sets the compiler of this WebAssembly module's shader sources: the web
629/// runtime's gate for shaders sets it, so naga is linked only into the
630/// runtimes of apps that use shaders. The native backends always have
631/// [`Shader::compile`].
632#[cfg(target_arch = "wasm32")]
633pub fn set_compile(compile: Compile) {
634    COMPILE.with(|c| c.set(Some(compile)));
635}
636
637/// Compiles `source` with this module's compiler, if it has one.
638pub(crate) fn compile_source(source: &str) -> Result<Shader, ShaderError> {
639    #[cfg(target_arch = "wasm32")]
640    {
641        match COMPILE.with(|c| c.get()) {
642            Some(compile) => compile(source),
643            None => Err(ShaderError::new(
644                "this web runtime has no shader compiler (it was linked for an app that \
645                 imports no `Shader`)",
646            )),
647        }
648    }
649    #[cfg(not(target_arch = "wasm32"))]
650    Shader::compile(source)
651}
652
653impl Shader {
654    /// Refuses `source`: this build has no shader compiler (feature `shader`).
655    #[cfg(not(feature = "shader"))]
656    pub fn compile(_source: &str) -> Result<Shader, ShaderError> {
657        Err(ShaderError::new(
658            "this build has no shader compiler (the NSH platform crate's feature `shader` is off)",
659        ))
660    }
661
662    /// Checks and compiles the app's WGSL `source`, which defines
663    /// `fn shade(uv: vec2f) -> vec4f` (module docs).
664    #[cfg(feature = "shader")]
665    pub fn compile(source: &str) -> Result<Shader, ShaderError> {
666        if source.len() > MAX_SOURCE_BYTES {
667            return Err(ShaderError::new(format!(
668                "a shader's source is at most {MAX_SOURCE_BYTES} bytes; this one has {}",
669                source.len()
670            )));
671        }
672        let has_uniforms = declares_uniforms(source);
673        let mut wgsl = String::with_capacity(
674            source.len() + BUILTINS.len() + UNIFORMS.len() + ENTRY_POINTS.len(),
675        );
676        wgsl.push_str(source);
677        wgsl.push_str(BUILTINS);
678        if has_uniforms {
679            wgsl.push_str(UNIFORMS);
680        }
681        // Checked without the entry points first: an error there is in the
682        // app's source, not in what calls `shade`.
683        let module = parse(&wgsl, source)?;
684        check(&module, source, has_uniforms)?;
685        wgsl.push_str(ENTRY_POINTS);
686        let module = parse(&wgsl, source)?;
687        let info = Validator::new(ValidationFlags::all(), Capabilities::empty())
688            .validate(&module)
689            .map_err(|e| {
690                // The innermost place: an expression inside the function.
691                let offset = e
692                    .spans()
693                    .filter_map(|(span, _)| span.to_range())
694                    .map(|r| r.start)
695                    .filter(|&s| s < source.len())
696                    .max();
697                ShaderError::at(error_chain(e.as_inner()), source, offset)
698            })?;
699        let (uniforms, uniform_size) = if has_uniforms {
700            reflect_uniforms(&module, source)?
701        } else {
702            (Vec::new(), 0)
703        };
704        let animated = reads_time(&module);
705        let inputs = reads_inputs(&module, &info);
706        Ok(Shader(Arc::new(Program {
707            source: source.into(),
708            hash: source_hash(source),
709            wgsl,
710            module,
711            info,
712            uniforms,
713            uniform_size,
714            animated,
715            inputs,
716            #[cfg(feature = "glsl")]
717            glsl: std::sync::OnceLock::new(),
718        })))
719    }
720
721    /// The app's source.
722    pub fn source(&self) -> &str {
723        &self.0.source
724    }
725
726    /// The hash of the app's source ([`source_hash`]).
727    pub fn hash(&self) -> u64 {
728        self.0.hash
729    }
730
731    /// The whole WGSL module: the app's source, the built-ins, the
732    /// uniforms' binding and the entry points `nsh_vertex` and
733    /// `nsh_fragment`.
734    pub fn wgsl(&self) -> &str {
735        &self.0.wgsl
736    }
737
738    /// The members of `struct Uniforms`, in order (empty without one).
739    pub fn uniforms(&self) -> &[UniformField] {
740        &self.0.uniforms
741    }
742
743    /// The size of `struct Uniforms` in bytes (a multiple of 16; 0 without
744    /// one).
745    pub fn uniform_size(&self) -> u32 {
746        self.0.uniform_size
747    }
748
749    /// Whether it reads `nsh.time`: it then draws every frame while it is
750    /// in sight and not paused.
751    pub fn animated(&self) -> bool {
752        self.0.animated
753    }
754
755    /// The pictures it reads (`sample_content`, …): the platform takes
756    /// them for it.
757    pub fn inputs(&self) -> ShaderInputs {
758        self.0.inputs
759    }
760
761    /// The program as GLSL ES 3.00 for WebGL 2 (translated once, on first
762    /// use).
763    #[cfg(feature = "glsl")]
764    pub fn glsl_es(&self) -> Result<&GlslProgram, ShaderError> {
765        self.0
766            .glsl
767            .get_or_init(|| glsl_es(&self.0.module, &self.0.info))
768            .as_ref()
769            .map_err(Clone::clone)
770    }
771}
772
773#[cfg(feature = "shader")]
774/// Whether `source` declares `struct Uniforms` (outside comments).
775fn declares_uniforms(source: &str) -> bool {
776    let mut rest = source;
777    let mut code = String::with_capacity(source.len());
778    // Comments out: `//` to the end of the line, `/* … */` (nested, as
779    // WGSL's are).
780    while !rest.is_empty() {
781        if let Some(r) = rest.strip_prefix("//") {
782            rest = r.find('\n').map_or("", |n| &r[n..]);
783        } else if rest.starts_with("/*") {
784            let mut depth = 0usize;
785            let mut i = 0;
786            let bytes = rest.as_bytes();
787            while i < bytes.len() {
788                if bytes[i..].starts_with(b"/*") {
789                    depth += 1;
790                    i += 2;
791                } else if bytes[i..].starts_with(b"*/") {
792                    depth -= 1;
793                    i += 2;
794                    if depth == 0 {
795                        break;
796                    }
797                } else {
798                    i += 1;
799                }
800            }
801            code.push(' ');
802            rest = &rest[i.min(rest.len())..];
803        } else {
804            let c = rest.chars().next().expect("not empty");
805            code.push(c);
806            rest = &rest[c.len_utf8()..];
807        }
808    }
809    let mut words = code
810        .split(|c: char| !(c.is_alphanumeric() || c == '_'))
811        .filter(|w| !w.is_empty());
812    while let Some(word) = words.next() {
813        if word == "struct" && words.next() == Some("Uniforms") {
814            return true;
815        }
816    }
817    false
818}
819
820#[cfg(feature = "shader")]
821/// An error and its causes, innermost last ("Function 'shade' is invalid:
822/// …").
823fn error_chain(error: &dyn std::error::Error) -> String {
824    let mut message = error.to_string();
825    let mut cause = error.source();
826    while let Some(e) = cause {
827        message.push_str(": ");
828        message.push_str(&e.to_string());
829        cause = e.source();
830    }
831    message
832}
833
834#[cfg(feature = "shader")]
835fn parse(wgsl: &str, source: &str) -> Result<Module, ShaderError> {
836    naga::front::wgsl::parse_str(wgsl).map_err(|e| {
837        let offset = e
838            .location(wgsl)
839            .map(|l| l.offset as usize)
840            .filter(|&o| o < source.len());
841        ShaderError::at(e.message().to_string(), source, offset)
842    })
843}
844
845#[cfg(feature = "shader")]
846/// What the app's module may hold: `shade` with its signature, no entry
847/// points, no resources of its own.
848fn check(module: &Module, source: &str, has_uniforms: bool) -> Result<(), ShaderError> {
849    let span_of = |span: naga::Span| span.to_range().map(|r| r.start);
850    if let Some(entry) = module.entry_points.first() {
851        let offset = source.find(&format!("fn {}", entry.name));
852        return Err(ShaderError::at(
853            format!(
854                "a shader declares no entry points (`{}`): NSH calls `fn {SHADE}(uv: vec2f) -> vec4f`",
855                entry.name
856            ),
857            source,
858            offset,
859        ));
860    }
861    for (handle, global) in module.global_variables.iter() {
862        let name = global.name.as_deref().unwrap_or("");
863        let ours = (matches!(name, "nsh" | "uniforms" | "nsh_sampler")
864            || ShaderInput::ALL.iter().any(|i| i.texture() == name))
865            && global.binding.is_some();
866        if ours || global.space == AddressSpace::Private {
867            continue;
868        }
869        return Err(ShaderError::at(
870            format!(
871                "`{name}`: a shader's globals are `var<private>`; its inputs are `nsh` and `uniforms`"
872            ),
873            source,
874            span_of(module.global_variables.get_span(handle)),
875        ));
876    }
877    let shade = module
878        .functions
879        .iter()
880        .find(|(_, f)| f.name.as_deref() == Some(SHADE));
881    let Some((handle, shade)) = shade else {
882        return Err(ShaderError::new(format!(
883            "a shader defines `fn {SHADE}(uv: vec2f) -> vec4f`, the color of each point of its box"
884        )));
885    };
886    let is_vec = |ty: Handle<naga::Type>, size: VectorSize| {
887        matches!(
888            module.types[ty].inner,
889            TypeInner::Vector { size: s, scalar } if s == size && scalar.kind == ScalarKind::Float && scalar.width == 4
890        )
891    };
892    let signature = shade.arguments.len() == 1
893        && is_vec(shade.arguments[0].ty, VectorSize::Bi)
894        && shade
895            .result
896            .as_ref()
897            .is_some_and(|r| is_vec(r.ty, VectorSize::Quad));
898    if !signature {
899        return Err(ShaderError::at(
900            format!("`{SHADE}` takes the point's `uv: vec2f` and returns its color, a `vec4f`"),
901            source,
902            span_of(module.functions.get_span(handle)),
903        ));
904    }
905    if has_uniforms {
906        let declared = module.types.iter().any(|(_, t)| {
907            t.name.as_deref() == Some("Uniforms") && matches!(t.inner, TypeInner::Struct { .. })
908        });
909        if !declared {
910            return Err(ShaderError::new("`Uniforms` is a struct"));
911        }
912    }
913    Ok(())
914}
915
916#[cfg(feature = "shader")]
917/// The members of `struct Uniforms` and its size.
918fn reflect_uniforms(
919    module: &Module,
920    source: &str,
921) -> Result<(Vec<UniformField>, u32), ShaderError> {
922    let Some((handle, ty)) = module
923        .types
924        .iter()
925        .find(|(_, t)| t.name.as_deref() == Some("Uniforms"))
926    else {
927        return Ok((Vec::new(), 0));
928    };
929    let TypeInner::Struct { members, span } = &ty.inner else {
930        return Err(ShaderError::new("`Uniforms` is a struct"));
931    };
932    let at = module.types.get_span(handle).to_range().map(|r| r.start);
933    if *span > MAX_UNIFORM_BYTES {
934        return Err(ShaderError::at(
935            format!("`Uniforms` takes {span} bytes; at most {MAX_UNIFORM_BYTES}"),
936            source,
937            at,
938        ));
939    }
940    let mut fields = Vec::with_capacity(members.len());
941    for member in members {
942        let name = member.name.clone().unwrap_or_default();
943        let ty = uniform_type(module, member.ty).ok_or_else(|| {
944            ShaderError::at(
945                format!(
946                    "uniform `{name}`: uniforms are `f32`, `i32`, `u32`, `vec2f`, `vec3f`, `vec4f` or `array<vec4f, N>`"
947                ),
948                source,
949                at,
950            )
951        })?;
952        fields.push(UniformField {
953            name: name.into(),
954            ty,
955            offset: member.offset,
956        });
957    }
958    Ok((fields, span.next_multiple_of(16)))
959}
960
961#[cfg(feature = "shader")]
962fn uniform_type(module: &Module, ty: Handle<naga::Type>) -> Option<UniformType> {
963    Some(match module.types[ty].inner {
964        TypeInner::Scalar(s) if s.width == 4 => match s.kind {
965            ScalarKind::Float => UniformType::F32,
966            ScalarKind::Sint => UniformType::I32,
967            ScalarKind::Uint => UniformType::U32,
968            _ => return None,
969        },
970        TypeInner::Vector { size, scalar }
971            if scalar.kind == ScalarKind::Float && scalar.width == 4 =>
972        {
973            match size {
974                VectorSize::Bi => UniformType::Vec2,
975                VectorSize::Tri => UniformType::Vec3,
976                VectorSize::Quad => UniformType::Vec4,
977            }
978        }
979        TypeInner::Array {
980            base,
981            size: ArraySize::Constant(n),
982            stride: 16,
983        } if uniform_type(module, base) == Some(UniformType::Vec4) => {
984            UniformType::Vec4Array(n.get())
985        }
986        _ => return None,
987    })
988}
989
990#[cfg(feature = "shader")]
991/// The pictures the fragment stage reads: the textures `nsh_fragment` uses,
992/// through `shade` and whatever it calls (naga's analysis follows calls).
993fn reads_inputs(module: &Module, info: &ModuleInfo) -> ShaderInputs {
994    let Some(entry) = module
995        .entry_points
996        .iter()
997        .position(|e| e.name == "nsh_fragment")
998    else {
999        return ShaderInputs::default();
1000    };
1001    let uses = info.get_entry_point(entry);
1002    module
1003        .global_variables
1004        .iter()
1005        .filter(|&(handle, _)| !uses[handle].is_empty())
1006        .filter_map(|(_, global)| {
1007            let name = global.name.as_deref()?;
1008            ShaderInput::ALL.into_iter().find(|i| i.texture() == name)
1009        })
1010        .fold(ShaderInputs::default(), ShaderInputs::with)
1011}
1012
1013#[cfg(feature = "shader")]
1014/// Whether any function reads `nsh.time`.
1015fn reads_time(module: &Module) -> bool {
1016    let Some(nsh) = module
1017        .global_variables
1018        .iter()
1019        .find(|(_, g)| g.name.as_deref() == Some("nsh"))
1020        .map(|(h, _)| h)
1021    else {
1022        return false;
1023    };
1024    let reads = |f: &naga::Function| {
1025        f.expressions.iter().any(|(_, e)| {
1026            matches!(*e, Expression::AccessIndex { base, index }
1027                if index == TIME_MEMBER && matches!(f.expressions[base], Expression::GlobalVariable(g) if g == nsh))
1028        })
1029    };
1030    module.functions.iter().any(|(_, f)| reads(f))
1031        || module.entry_points.iter().any(|e| reads(&e.function))
1032}
1033
1034#[cfg(feature = "glsl")]
1035fn glsl_es(module: &Module, info: &ModuleInfo) -> Result<GlslProgram, ShaderError> {
1036    use naga::back::glsl;
1037    let options = glsl::Options {
1038        version: glsl::Version::Embedded {
1039            version: 300,
1040            is_webgl: true,
1041        },
1042        // Drawn straight into the canvas the page shows: clip space keeps
1043        // WGSL's +y up, which is GL's too (no flip as for a texture).
1044        writer_flags: glsl::WriterFlags::empty(),
1045        ..Default::default()
1046    };
1047    // Out-of-range indices read in range, as wgpu's checks make them.
1048    let policies = naga::proc::BoundsCheckPolicies {
1049        index: naga::proc::BoundsCheckPolicy::Restrict,
1050        buffer: naga::proc::BoundsCheckPolicy::Restrict,
1051        image_load: naga::proc::BoundsCheckPolicy::Restrict,
1052        binding_array: naga::proc::BoundsCheckPolicy::Restrict,
1053    };
1054    let write = |stage: naga::ShaderStage, entry: &str| {
1055        let mut out = String::new();
1056        let pipeline = glsl::PipelineOptions {
1057            shader_stage: stage,
1058            entry_point: entry.into(),
1059            multiview: None,
1060        };
1061        let mut writer = glsl::Writer::new(&mut out, module, info, &options, &pipeline, policies)
1062            .map_err(|e| ShaderError::new(format!("GLSL ES: {e}")))?;
1063        let reflection = writer
1064            .write()
1065            .map_err(|e| ShaderError::new(format!("GLSL ES: {e}")))?;
1066        Ok::<_, ShaderError>((out, reflection))
1067    };
1068    let (vertex, _) = write(naga::ShaderStage::Vertex, "nsh_vertex")?;
1069    let (fragment, reflection) = write(naga::ShaderStage::Fragment, "nsh_fragment")?;
1070    let block = |name: &str| {
1071        reflection.uniforms.iter().find_map(|(handle, block)| {
1072            (module.global_variables[*handle].name.as_deref() == Some(name)).then(|| block.clone())
1073        })
1074    };
1075    let pictures = reflection
1076        .texture_mapping
1077        .iter()
1078        .filter_map(|(name, mapping)| {
1079            let global = module.global_variables[mapping.texture].name.as_deref()?;
1080            let input = ShaderInput::ALL
1081                .into_iter()
1082                .find(|i| i.texture() == global)?;
1083            Some((name.clone(), input))
1084        })
1085        .collect();
1086    Ok(GlslProgram {
1087        builtins_block: block("nsh"),
1088        uniforms_block: block("uniforms"),
1089        pictures,
1090        vertex,
1091        fragment,
1092    })
1093}
1094
1095/// A value an app gives a uniform.
1096#[derive(Debug, Clone, PartialEq)]
1097pub enum UniformValue {
1098    /// A number (`f32`, `i32` and `u32` uniforms; a component of a vector).
1099    Number(f32),
1100    /// A color: a `vec3f`'s red, green and blue, or a `vec4f` with its
1101    /// alpha, in 0..1 (sRGB, as CSS).
1102    Color(Color),
1103    /// An animated value: a number, or a color for a `vec3f` / `vec4f`.
1104    /// The platform writes it on every frame it changes.
1105    Animated(NodeId),
1106    /// The components of a vector, or the items of an array of `vec4f`.
1107    List(Vec<UniformValue>),
1108}
1109
1110impl From<f32> for UniformValue {
1111    fn from(n: f32) -> Self {
1112        UniformValue::Number(n)
1113    }
1114}
1115
1116impl From<i32> for UniformValue {
1117    fn from(n: i32) -> Self {
1118        UniformValue::Number(n as f32)
1119    }
1120}
1121
1122impl From<Color> for UniformValue {
1123    fn from(c: Color) -> Self {
1124        UniformValue::Color(c)
1125    }
1126}
1127
1128impl From<crate::color::Hsla> for UniformValue {
1129    fn from(c: crate::color::Hsla) -> Self {
1130        UniformValue::Color(c.into())
1131    }
1132}
1133
1134impl<const N: usize> From<[f32; N]> for UniformValue {
1135    fn from(v: [f32; N]) -> Self {
1136        UniformValue::List(v.iter().map(|&n| UniformValue::Number(n)).collect())
1137    }
1138}
1139
1140impl From<Vec<UniformValue>> for UniformValue {
1141    fn from(v: Vec<UniformValue>) -> Self {
1142        UniformValue::List(v)
1143    }
1144}
1145
1146/// The values of a shader's uniforms, by name (`uniforms`).
1147#[derive(Debug, Clone, Default, PartialEq)]
1148pub struct ShaderUniforms(pub Vec<(Arc<str>, UniformValue)>);
1149
1150/// How a value slot writes its animated value into the uniforms.
1151#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1152pub enum SlotKind {
1153    /// One `f32`.
1154    #[default]
1155    F32,
1156    /// One `i32` (the value rounded toward zero).
1157    I32,
1158    /// One `u32` (the value rounded toward zero, at least 0).
1159    U32,
1160    /// A color's red, green and blue.
1161    Rgb,
1162    /// A color's red, green, blue and alpha.
1163    Rgba,
1164}
1165
1166/// Where an animated uniform goes: the word it starts at and how it is
1167/// written.
1168#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1169#[non_exhaustive]
1170pub struct UniformSlot {
1171    /// The index of its first word (4 bytes) in [`ShaderLayer::uniforms`].
1172    pub word: u32,
1173    /// How its value is written.
1174    pub kind: SlotKind,
1175}
1176
1177/// A shader as a view shows it: the program, the words of its uniforms
1178/// as the app set them, and the slots of its animated values.
1179#[derive(Debug, Clone, PartialEq)]
1180#[non_exhaustive]
1181pub struct ShaderLayer {
1182    /// The program.
1183    pub shader: Shader,
1184    /// The uniform buffer, `shader.uniform_size() / 4` words (bit patterns
1185    /// of `f32`, `i32` and `u32`).
1186    pub uniforms: Arc<[u32]>,
1187    /// The animated values' slots: slot `n` is bound as
1188    /// [`crate::animation::AnimationProp::CanvasArg`]`(n)`.
1189    pub slots: Vec<UniformSlot>,
1190    /// The animation nodes of the slots, in the same order.
1191    pub nodes: Vec<NodeId>,
1192    /// Its clock stands still (`nsh.time` keeps its value).
1193    pub paused: bool,
1194    /// What it draws ([`ShaderRole`]).
1195    pub role: ShaderRole,
1196    /// How far beyond the box it draws and its pictures reach, in points
1197    /// (`nsh.overflow`, `maxSampleOffset`).
1198    pub overflow: Points,
1199    /// `nsh.progress`, unless an animated value moves it (a slot whose
1200    /// word is [`PROGRESS_WORD`]) or a transition runs it.
1201    pub progress: Percentage,
1202}
1203
1204impl ShaderLayer {
1205    /// The layer of `shader` with the uniforms `values` (by name; those not
1206    /// given are zero). What does not fit a uniform is left out, each with
1207    /// a warning in `warnings`.
1208    pub fn new(
1209        shader: Shader,
1210        values: &[(Arc<str>, UniformValue)],
1211        warnings: &mut Vec<String>,
1212    ) -> ShaderLayer {
1213        let mut words = vec![0u32; (shader.uniform_size() / 4) as usize];
1214        let mut slots = Vec::new();
1215        let mut nodes = Vec::new();
1216        for (name, value) in values {
1217            let Some(field) = shader.uniforms().iter().find(|f| f.name == *name) else {
1218                warnings.push(if shader.uniforms().is_empty() {
1219                    format!("uniform `{name}`: the shader declares no `struct Uniforms`")
1220                } else {
1221                    format!("uniform `{name}`: `struct Uniforms` has no such member")
1222                });
1223                continue;
1224            };
1225            let mut packer = Packer {
1226                words: &mut words,
1227                slots: &mut slots,
1228                nodes: &mut nodes,
1229            };
1230            if let Err(expected) = packer.pack(field.ty, field.offset / 4, value) {
1231                warnings.push(format!(
1232                    "uniform `{name}` is a `{}`: it takes {expected}",
1233                    field.ty.wgsl()
1234                ));
1235            }
1236        }
1237        ShaderLayer {
1238            shader,
1239            uniforms: words.into(),
1240            slots,
1241            nodes,
1242            paused: false,
1243            role: ShaderRole::Fill,
1244            overflow: Points::ZERO,
1245            progress: Percentage(0.0),
1246        }
1247    }
1248
1249    /// The same layer drawing as `role`.
1250    pub fn with_role(mut self, role: ShaderRole) -> Self {
1251        self.role = role;
1252        self
1253    }
1254
1255    /// The same layer drawing `overflow` points beyond the box.
1256    pub fn with_overflow(mut self, overflow: Points) -> Self {
1257        self.overflow = overflow.max(Points::ZERO);
1258        self
1259    }
1260
1261    /// The same layer with its clock stopped or running.
1262    pub fn with_paused(mut self, paused: bool) -> Self {
1263        self.paused = paused;
1264        self
1265    }
1266
1267    /// The same layer with `nsh.progress` at `progress`, or moved by the
1268    /// animated value of node `animated` (one more slot).
1269    pub fn with_progress(mut self, progress: Percentage, animated: Option<NodeId>) -> Self {
1270        self.progress = progress;
1271        if let Some(node) = animated {
1272            self.slots.push(UniformSlot {
1273                word: PROGRESS_WORD,
1274                kind: SlotKind::F32,
1275            });
1276            self.nodes.push(node);
1277        }
1278        self
1279    }
1280
1281    /// The slot that moves `nsh.progress`, if an animated value does.
1282    pub fn progress_slot(&self) -> Option<u16> {
1283        self.slots
1284            .iter()
1285            .position(|s| s.word == PROGRESS_WORD)
1286            .map(|i| i as u16)
1287    }
1288
1289    /// Writes slot `slot`'s animated `value` into `words` (a copy of
1290    /// [`Self::uniforms`] the platform keeps).
1291    pub fn write_slot(&self, words: &mut [u32], slot: u16, value: AnimationValue) {
1292        let Some(slot) = self.slots.get(slot as usize) else {
1293            return;
1294        };
1295        let at = slot.word as usize;
1296        let number = || value.number();
1297        match slot.kind {
1298            SlotKind::F32 => set(words, at, number().to_bits()),
1299            SlotKind::I32 => set(words, at, (number() as i32) as u32),
1300            SlotKind::U32 => set(words, at, number().max(0.0) as u32),
1301            SlotKind::Rgb | SlotKind::Rgba => {
1302                let color = match value {
1303                    AnimationValue::Color(c) => Color(c),
1304                    other => Color(other.number() as u32),
1305                };
1306                let n = if slot.kind == SlotKind::Rgb { 3 } else { 4 };
1307                for (i, c) in rgba(color).into_iter().take(n).enumerate() {
1308                    set(words, at + i, c.to_bits());
1309                }
1310            }
1311        }
1312    }
1313}
1314
1315fn set(words: &mut [u32], at: usize, word: u32) {
1316    if let Some(w) = words.get_mut(at) {
1317        *w = word;
1318    }
1319}
1320
1321/// A color's components in 0..1.
1322fn rgba(color: Color) -> [f32; 4] {
1323    let c = color.0;
1324    [c >> 24, c >> 16, c >> 8, c].map(|b| (b & 0xff) as f32 / 255.0)
1325}
1326
1327struct Packer<'a> {
1328    words: &'a mut [u32],
1329    slots: &'a mut Vec<UniformSlot>,
1330    nodes: &'a mut Vec<NodeId>,
1331}
1332
1333impl Packer<'_> {
1334    /// Writes `value` as a `ty` at word `at`; `Err` names what `ty` takes.
1335    fn pack(&mut self, ty: UniformType, at: u32, value: &UniformValue) -> Result<(), &'static str> {
1336        const SCALAR: &str = "a number or an animated value";
1337        match ty {
1338            UniformType::F32 | UniformType::I32 | UniformType::U32 => {
1339                let kind = match ty {
1340                    UniformType::F32 => SlotKind::F32,
1341                    UniformType::I32 => SlotKind::I32,
1342                    _ => SlotKind::U32,
1343                };
1344                match *value {
1345                    UniformValue::Number(n) => {
1346                        let word = match kind {
1347                            SlotKind::F32 => n.to_bits(),
1348                            SlotKind::I32 => (n as i32) as u32,
1349                            _ => n.max(0.0) as u32,
1350                        };
1351                        set(self.words, at as usize, word);
1352                    }
1353                    UniformValue::Animated(node) => self.slot(at, kind, node),
1354                    _ => return Err(SCALAR),
1355                }
1356            }
1357            UniformType::Vec2 | UniformType::Vec3 | UniformType::Vec4 => {
1358                let n = match ty {
1359                    UniformType::Vec2 => 2,
1360                    UniformType::Vec3 => 3,
1361                    _ => 4,
1362                };
1363                let expected = match ty {
1364                    UniformType::Vec2 => "2 numbers",
1365                    UniformType::Vec3 => "3 numbers or a color",
1366                    _ => "4 numbers or a color",
1367                };
1368                match value {
1369                    UniformValue::Color(c) if n >= 3 => {
1370                        for (i, c) in rgba(*c).into_iter().take(n).enumerate() {
1371                            set(self.words, at as usize + i, c.to_bits());
1372                        }
1373                    }
1374                    UniformValue::Animated(node) if n >= 3 => {
1375                        let kind = if n == 3 {
1376                            SlotKind::Rgb
1377                        } else {
1378                            SlotKind::Rgba
1379                        };
1380                        self.slot(at, kind, *node);
1381                    }
1382                    UniformValue::List(items) if items.len() == n => {
1383                        for (i, item) in items.iter().enumerate() {
1384                            match *item {
1385                                UniformValue::Number(v) => {
1386                                    set(self.words, at as usize + i, v.to_bits())
1387                                }
1388                                UniformValue::Animated(node) => {
1389                                    self.slot(at + i as u32, SlotKind::F32, node)
1390                                }
1391                                _ => return Err(expected),
1392                            }
1393                        }
1394                    }
1395                    _ => return Err(expected),
1396                }
1397            }
1398            UniformType::Vec4Array(len) => {
1399                let UniformValue::List(items) = value else {
1400                    return Err("a list of colors or of 4 numbers");
1401                };
1402                if items.len() > len as usize {
1403                    return Err("at most as many items as the array has");
1404                }
1405                for (i, item) in items.iter().enumerate() {
1406                    self.pack(UniformType::Vec4, at + 4 * i as u32, item)
1407                        .map_err(|_| "a list of colors or of 4 numbers")?;
1408                }
1409            }
1410        }
1411        Ok(())
1412    }
1413
1414    fn slot(&mut self, word: u32, kind: SlotKind, node: NodeId) {
1415        self.slots.push(UniformSlot { word, kind });
1416        self.nodes.push(node);
1417    }
1418}
1419
1420#[cfg(test)]
1421mod tests {
1422    use super::*;
1423
1424    #[test]
1425    fn use_marker_names_the_function_shader_views_call() {
1426        let name = std::any::type_name_of_val(&note_use);
1427        assert!(
1428            name.ends_with(&format!("::{USE_MARKER}")),
1429            "{name} is not {USE_MARKER}: update nsh-cli's shader detection"
1430        );
1431    }
1432
1433    const GRADIENT: &str = r#"
1434struct Uniforms {
1435    start: vec4f,
1436    end: vec3f,
1437    speed: f32,
1438    stops: array<vec4f, 4>,
1439    count: i32,
1440}
1441
1442fn shade(uv: vec2f) -> vec4f {
1443    let t = fract(uv.x + nsh.time * uniforms.speed);
1444    return mix(uniforms.start, vec4f(uniforms.end, 1.0), t) + uniforms.stops[uniforms.count];
1445}
1446"#;
1447
1448    #[test]
1449    fn compiles_and_reflects() {
1450        let shader = Shader::compile(GRADIENT).expect("compiles");
1451        assert!(shader.animated());
1452        let fields: Vec<_> = shader
1453            .uniforms()
1454            .iter()
1455            .map(|f| (&*f.name, f.ty, f.offset))
1456            .collect();
1457        assert_eq!(
1458            fields,
1459            [
1460                ("start", UniformType::Vec4, 0),
1461                ("end", UniformType::Vec3, 16),
1462                ("speed", UniformType::F32, 28),
1463                ("stops", UniformType::Vec4Array(4), 32),
1464                ("count", UniformType::I32, 96),
1465            ]
1466        );
1467        assert_eq!(shader.uniform_size(), 112);
1468        assert!(shader.wgsl().contains("fn nsh_fragment"));
1469        assert_eq!(shader, Shader::compile(GRADIENT).unwrap());
1470    }
1471
1472    #[test]
1473    fn still_shaders_do_not_animate() {
1474        let shader =
1475            Shader::compile("fn shade(uv: vec2f) -> vec4f { return vec4f(uv, nsh.size.x, 1.0); }")
1476                .unwrap();
1477        assert!(!shader.animated());
1478        assert!(shader.uniforms().is_empty());
1479        // Comments do not declare uniforms.
1480        let commented = "// struct Uniforms { a: f32 }\n/* struct Uniforms */ fn shade(uv: vec2f) -> vec4f { return vec4f(1.0); }";
1481        assert!(Shader::compile(commented).unwrap().uniforms().is_empty());
1482    }
1483
1484    #[test]
1485    fn the_built_ins_take_the_bytes_the_renderers_upload() {
1486        let shader = Shader::compile(GRADIENT).unwrap();
1487        let module = naga::front::wgsl::parse_str(shader.wgsl()).unwrap();
1488        let span = module
1489            .types
1490            .iter()
1491            .find_map(|(_, ty)| match ty.inner {
1492                TypeInner::Struct { span, .. } if ty.name.as_deref() == Some("Nsh") => Some(span),
1493                _ => None,
1494            })
1495            .expect("struct Nsh");
1496        let words = builtins(
1497            Size::default(),
1498            0.0,
1499            1.0,
1500            Percentage(0.0),
1501            Points::default(),
1502        );
1503        assert_eq!(span as usize, size_of_val(&words));
1504        // GLES without `BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED` takes no other.
1505        assert_eq!(span % 16, 0);
1506    }
1507
1508    #[test]
1509    fn an_app_binds_no_globals_of_its_own_under_nsh_names() {
1510        let error = Shader::compile(
1511            "@group(0) @binding(7) var nsh_extra: texture_2d<f32>;\n\
1512             fn shade(uv: vec2f) -> vec4f { return textureLoad(nsh_extra, vec2i(0), 0); }",
1513        )
1514        .unwrap_err();
1515        assert!(error.message.contains("nsh_extra"), "{error:?}");
1516        // The pictures' own globals are NSH's.
1517        assert!(
1518            Shader::compile(
1519                "fn shade(uv: vec2f) -> vec4f { return textureSampleLevel(nsh_content, nsh_sampler, uv, 0.0); }"
1520            )
1521            .is_ok()
1522        );
1523    }
1524
1525    #[test]
1526    fn equal_numbers_are_one_transition_key() {
1527        assert_eq!(TransitionKey::from(0.0), TransitionKey::from(-0.0));
1528        assert_eq!(
1529            TransitionKey::from(f64::NAN),
1530            TransitionKey::from(-f64::NAN)
1531        );
1532        assert_ne!(TransitionKey::from(1.0), TransitionKey::from(2.0));
1533    }
1534
1535    #[test]
1536    fn inputs_are_the_pictures_shade_reaches() {
1537        let inputs = |source: &str| Shader::compile(source).unwrap().inputs();
1538        assert!(inputs("fn shade(uv: vec2f) -> vec4f { return vec4f(1.0); }").is_empty());
1539        // Through a helper, whatever its name.
1540        let helper = inputs(
1541            "fn sample_custom(uv: vec2f) -> vec4f { return sample_content(uv) * 0.5; }\n\
1542             fn shade(uv: vec2f) -> vec4f { return sample_custom(uv) + sample_to(uv); }",
1543        );
1544        assert_eq!(
1545            helper.iter().collect::<Vec<_>>(),
1546            [ShaderInput::Content, ShaderInput::To]
1547        );
1548        // A helper `shade` never calls reads nothing.
1549        let unused = inputs(
1550            "fn unused(uv: vec2f) -> vec4f { return sample_backdrop(uv); }\n\
1551             fn shade(uv: vec2f) -> vec4f { return sample_from(uv); }",
1552        );
1553        assert_eq!(unused.iter().collect::<Vec<_>>(), [ShaderInput::From]);
1554    }
1555
1556    #[test]
1557    fn errors_point_into_the_source() {
1558        let error = Shader::compile("fn shade(uv: vec2f) -> vec4f {\n  return vec4f(uv, 0.0);\n}")
1559            .unwrap_err();
1560        assert_eq!(error.line, 2, "{error}");
1561        let missing =
1562            Shader::compile("fn paint(uv: vec2f) -> vec4f { return vec4f(1.0); }").unwrap_err();
1563        assert!(missing.message.contains("fn shade"), "{missing}");
1564        let signature =
1565            Shader::compile("fn shade(uv: vec2f) -> vec3f { return vec3f(1.0); }").unwrap_err();
1566        assert!(
1567            signature.message.contains("returns its color"),
1568            "{signature}"
1569        );
1570    }
1571
1572    #[test]
1573    fn refuses_resources_and_entry_points() {
1574        let storage = Shader::compile(
1575            "@group(1) @binding(0) var<storage> data: array<f32>;\nfn shade(uv: vec2f) -> vec4f { return vec4f(data[0]); }",
1576        )
1577        .unwrap_err();
1578        assert!(storage.message.contains("`data`"), "{storage}");
1579        assert_eq!(storage.line, 1);
1580        let entry = Shader::compile(
1581            "fn shade(uv: vec2f) -> vec4f { return vec4f(1.0); }\n@fragment fn main() -> @location(0) vec4f { return vec4f(1.0); }",
1582        )
1583        .unwrap_err();
1584        assert!(entry.message.contains("entry points"), "{entry}");
1585        let big = Shader::compile(&" ".repeat(MAX_SOURCE_BYTES + 1)).unwrap_err();
1586        assert!(big.message.contains("at most"));
1587        let mat = Shader::compile(
1588            "struct Uniforms { m: mat2x2f }\nfn shade(uv: vec2f) -> vec4f { return vec4f(uniforms.m[0], 0.0, 1.0); }",
1589        )
1590        .unwrap_err();
1591        assert!(mat.message.contains("uniform `m`"), "{mat}");
1592        // Private globals are the shader's own.
1593        Shader::compile(
1594            "var<private> seed: f32 = 0.5;\nfn shade(uv: vec2f) -> vec4f { return vec4f(seed); }",
1595        )
1596        .unwrap();
1597    }
1598
1599    #[test]
1600    fn packs_uniforms() {
1601        let shader = Shader::compile(GRADIENT).unwrap();
1602        let mut warnings = Vec::new();
1603        let layer = ShaderLayer::new(
1604            shader,
1605            &[
1606                ("start".into(), UniformValue::Color(Color(0xff000080))),
1607                ("end".into(), UniformValue::Animated(7)),
1608                ("speed".into(), UniformValue::Number(0.5)),
1609                (
1610                    "stops".into(),
1611                    UniformValue::List(vec![
1612                        [1.0, 2.0, 3.0, 4.0].into(),
1613                        UniformValue::Color(Color(0x00ff00ff)),
1614                    ]),
1615                ),
1616                ("count".into(), UniformValue::Number(1.0)),
1617                ("nope".into(), UniformValue::Number(1.0)),
1618                ("speed".into(), UniformValue::Color(Color(0))),
1619            ],
1620            &mut warnings,
1621        );
1622        assert_eq!(warnings.len(), 2, "{warnings:?}");
1623        let f = |w: usize| f32::from_bits(layer.uniforms[w]);
1624        assert_eq!([f(0), f(1), f(2)], [1.0, 0.0, 0.0]);
1625        assert!((f(3) - 128.0 / 255.0).abs() < 1e-6);
1626        assert_eq!(f(7), 0.5);
1627        assert_eq!([f(8), f(9), f(10), f(11)], [1.0, 2.0, 3.0, 4.0]);
1628        assert_eq!([f(12), f(13), f(14), f(15)], [0.0, 1.0, 0.0, 1.0]);
1629        assert_eq!(layer.uniforms[24], 1);
1630        assert_eq!(
1631            layer.slots,
1632            [UniformSlot {
1633                word: 4,
1634                kind: SlotKind::Rgb
1635            }]
1636        );
1637        assert_eq!(layer.nodes, [7]);
1638        let mut words = layer.uniforms.to_vec();
1639        layer.write_slot(&mut words, 0, AnimationValue::Color(0x0000ffff));
1640        assert_eq!([4, 5, 6].map(|w| f32::from_bits(words[w])), [0.0, 0.0, 1.0]);
1641    }
1642
1643    #[cfg(feature = "glsl")]
1644    #[test]
1645    fn translates_to_glsl_es() {
1646        let shader = Shader::compile(GRADIENT).unwrap();
1647        let glsl = shader.glsl_es().expect("translates");
1648        assert!(
1649            glsl.vertex.starts_with("#version 300 es"),
1650            "{}",
1651            glsl.vertex
1652        );
1653        assert!(glsl.fragment.contains("uniform"), "{}", glsl.fragment);
1654        assert!(glsl.builtins_block.is_some());
1655        assert!(glsl.uniforms_block.is_some());
1656    }
1657}