Skip to main content

valo_dl/
effect.rs

1//! Runtime effects: WGSL functions the renderer splices into its own pipelines.
2//!
3//! Every effect defines `fn shade(position: vec2f) -> vec4f`. As a paint shader it colours the
4//! shapes it fills; as a filter it may also read `source`, the content it filters or the
5//! backdrop behind it. `position` is in the draw's local coordinates, and the colour returned is
6//! premultiplied, as images and `source` sample and as Skia's, Impeller's and Metal's shaders
7//! return it. The renderer writes the `@fragment` entry around the function, so coverage,
8//! clipping, the paint's alpha and blending stay its own and an effect cannot break them.
9//!
10//! An effect's own bindings follow the renderer's groups. Its images are `texture_2d<f32>` /
11//! `sampler` pairs in `@group(1)`, at bindings 0 and 1, 2 and 3, and so on; its uniforms are one
12//! struct at `@group(2) @binding(0)`, at most [`MAX_UNIFORM_BYTES`]. A filter's `source` and
13//! `source_sampler` are `@group(3)`, read through `uv_of(position)`, the source's uv at a local
14//! position, and `source_levels()`, how many levels its pyramid has; `filter_bounds()` is the
15//! area the filter shades, `(x, y, width, height)` in local coordinates. `@group(0)` is the
16//! renderer's own. Pipeline-overridable
17//! constants (`override`) choose variants, compiled one pipeline per set of values; each needs a
18//! default, so a draw names only the ones it changes.
19//!
20//! Creating an effect parses and validates its WGSL with naga, together with the declarations
21//! the renderer adds for its kind, and needs no GPU device.
22
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::sync::Arc;
25
26use naga::{AddressSpace, ImageClass, ImageDimension, ScalarKind, TypeInner, VectorSize};
27
28/// The group of an effect's images.
29pub const IMAGE_GROUP: u32 = 1;
30/// The group of an effect's uniform struct.
31pub const UNIFORM_GROUP: u32 = 2;
32/// The group of a filter's `source` and `source_sampler`.
33pub const SOURCE_GROUP: u32 = 3;
34/// The largest uniform struct an effect may declare.
35pub const MAX_UNIFORM_BYTES: u32 = 1024;
36
37/// What the renderer declares for every filter. The helpers' bodies here stand in for the
38/// renderer's, which read its own draw record; their names and signatures are the contract.
39const FILTER_CONTRACT: &str = "
40@group(3) @binding(0) var source: texture_2d<f32>;
41@group(3) @binding(1) var source_sampler: sampler;
42var<private> valo_contract_source: vec4<f32>;
43
44fn uv_of(position: vec2<f32>) -> vec2<f32> {
45    return (position - valo_contract_source.xy) / valo_contract_source.zw;
46}
47
48fn source_levels() -> f32 {
49    return 1.0;
50}
51
52fn filter_bounds() -> vec4<f32> {
53    return valo_contract_source;
54}
55";
56
57/// What a filter asks the renderer to prepare as its `source`.
58#[derive(Clone, Copy, Debug, PartialEq)]
59#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
60pub struct FilterInputs {
61    /// How far outside the drawn area the filter reads, in local units: the source covers the
62    /// drawn area grown by this much on every side.
63    pub margin: f32,
64    /// Whether the source carries a blur pyramid: level 0 is the source, each level after it
65    /// half the size and blurred, read with `textureSampleLevel`.
66    pub source_mips: bool,
67    /// The resolution of the source relative to the target; 0.5 captures at half resolution.
68    pub source_scale: f32,
69}
70
71impl Default for FilterInputs {
72    fn default() -> FilterInputs {
73        FilterInputs {
74            margin: 0.0,
75            source_mips: false,
76            source_scale: 1.0,
77        }
78    }
79}
80
81/// Whether an effect fills shapes or filters an input.
82#[derive(Clone, Copy, Debug, PartialEq)]
83#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
84pub enum EffectKind {
85    /// A paint shader, colouring the shapes it fills.
86    Shader,
87    /// A filter, which may also read `source`.
88    Filter(FilterInputs),
89}
90
91/// The type of a uniform field, as WGSL lays it out.
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
94pub enum UniformType {
95    F32,
96    I32,
97    U32,
98    Vec2F,
99    Vec3F,
100    Vec4F,
101    Vec2I,
102    Vec2U,
103    Mat2x2F,
104    Mat3x3F,
105    Mat4x4F,
106    /// Anything else (a nested struct, an array as an array's element), written as raw bytes.
107    Other {
108        size: u32,
109    },
110}
111
112/// One field of an effect's uniform struct.
113#[derive(Clone, Debug, PartialEq)]
114#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
115pub struct UniformField {
116    pub name: String,
117    pub offset: u32,
118    /// The field's type; for an array, the type of each element.
119    pub ty: UniformType,
120    /// How the elements of an array field are laid out; `None` for a field that is not an
121    /// array.
122    pub array: Option<UniformArray>,
123}
124
125/// `UniformArray` is the layout of an array field's elements, Impeller's `array_elements` with
126/// the stride its `padding_layout` spells out.
127///
128/// WGSL places uniform array elements 16 bytes apart at least, so an array of `f32` or `vec2f`
129/// is not allowed in a uniform struct and a tightly packed float array, as Flutter's shaders
130/// declare one, becomes an array of `vec4f`, four floats an element. A host that writes floats
131/// by index repacks them through this layout.
132#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
134pub struct UniformArray {
135    /// How many elements the array holds.
136    pub count: u32,
137    /// The bytes from the start of one element to the start of the next.
138    pub stride: u32,
139}
140
141/// An effect's uniform struct: the bytes a draw supplies for it.
142#[derive(Clone, Debug, Default, PartialEq)]
143#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
144pub struct UniformLayout {
145    /// The struct's size in bytes; 0 when the effect has no uniforms.
146    pub size: u32,
147    pub fields: Vec<UniformField>,
148}
149
150impl UniformLayout {
151    /// The field named `name`.
152    pub fn field(&self, name: &str) -> Option<&UniformField> {
153        self.fields.iter().find(|field| field.name == name)
154    }
155}
156
157/// Why WGSL could not become an effect.
158#[derive(Clone, Debug, PartialEq, Eq)]
159pub enum EffectError {
160    /// The WGSL does not parse; the message points into the source.
161    Parse(String),
162    /// The WGSL parses but naga rejects it.
163    Invalid(String),
164    /// The WGSL is valid but breaks the effect contract described in this module.
165    Contract(String),
166}
167
168impl std::fmt::Display for EffectError {
169    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170        match self {
171            EffectError::Parse(message) => write!(f, "effect does not parse: {message}"),
172            EffectError::Invalid(message) => write!(f, "effect is invalid: {message}"),
173            EffectError::Contract(message) => write!(f, "effect breaks the contract: {message}"),
174        }
175    }
176}
177
178impl std::error::Error for EffectError {}
179
180/// A WGSL function the renderer runs as a paint shader or a filter.
181///
182/// Immutable once created; draws share it through `Arc` and supply uniforms and images per draw
183/// in a [`RuntimeShader`].
184#[derive(Debug)]
185#[cfg_attr(feature = "serde", derive(serde::Serialize))]
186pub struct RuntimeEffect {
187    /// Identity for the renderer's pipeline caches; unique per created effect.
188    id: u64,
189    kind: EffectKind,
190    source: Arc<str>,
191    uniforms: UniformLayout,
192    /// The names of the effect's textures, by slot.
193    image_names: Vec<String>,
194    constants: Vec<String>,
195}
196
197impl RuntimeEffect {
198    /// A paint shader from WGSL defining `fn shade(position: vec2f) -> vec4f`.
199    pub fn shader(wgsl: &str) -> Result<Arc<RuntimeEffect>, EffectError> {
200        RuntimeEffect::new(EffectKind::Shader, wgsl)
201    }
202
203    /// A filter from WGSL defining `fn shade(position: vec2f) -> vec4f`, which may read
204    /// `source`.
205    pub fn filter(wgsl: &str, inputs: FilterInputs) -> Result<Arc<RuntimeEffect>, EffectError> {
206        // Written so NaN fails too.
207        let scale_in_range = inputs.source_scale > 0.0 && inputs.source_scale <= 1.0;
208        if !scale_in_range {
209            return Err(EffectError::Contract(format!(
210                "source_scale must be in (0, 1], not {}",
211                inputs.source_scale
212            )));
213        }
214        let margin_in_range = inputs.margin >= 0.0;
215        if !margin_in_range {
216            return Err(EffectError::Contract(format!(
217                "margin must not be negative, not {}",
218                inputs.margin
219            )));
220        }
221        RuntimeEffect::new(EffectKind::Filter(inputs), wgsl)
222    }
223
224    /// What the renderer declares for every effect of `kind`, for validation.
225    fn contract(kind: EffectKind) -> &'static str {
226        match kind {
227            EffectKind::Shader => "",
228            EffectKind::Filter(_) => FILTER_CONTRACT,
229        }
230    }
231
232    pub fn id(&self) -> u64 {
233        self.id
234    }
235
236    pub fn kind(&self) -> EffectKind {
237        self.kind
238    }
239
240    /// What a filter asks of its source; `None` for a paint shader.
241    pub fn filter_inputs(&self) -> Option<FilterInputs> {
242        match self.kind {
243            EffectKind::Shader => None,
244            EffectKind::Filter(inputs) => Some(inputs),
245        }
246    }
247
248    /// The effect author's WGSL, without the contract.
249    pub fn source(&self) -> &str {
250        &self.source
251    }
252
253    pub fn uniforms(&self) -> &UniformLayout {
254        &self.uniforms
255    }
256
257    /// How many images the effect samples.
258    pub fn images(&self) -> u32 {
259        self.image_names.len() as u32
260    }
261
262    /// The names of the effect's textures, by slot: the image at slot `n` is bound at
263    /// `@binding(2n)`.
264    pub fn image_names(&self) -> &[String] {
265        &self.image_names
266    }
267
268    /// The names of the effect's `override` constants.
269    pub fn constants(&self) -> &[String] {
270        &self.constants
271    }
272
273    fn new(kind: EffectKind, wgsl: &str) -> Result<Arc<RuntimeEffect>, EffectError> {
274        // The author's source comes first so naga's line numbers are theirs.
275        let composed = format!("{wgsl}\n{}", RuntimeEffect::contract(kind));
276        let module = naga::front::wgsl::parse_str(&composed)
277            .map_err(|error| EffectError::Parse(error.emit_to_string(&composed)))?;
278        naga::valid::Validator::new(
279            naga::valid::ValidationFlags::all(),
280            naga::valid::Capabilities::default(),
281        )
282        .validate(&module)
283        .map_err(|error| EffectError::Invalid(error.emit_to_string(&composed)))?;
284        if !module.entry_points.is_empty() {
285            return Err(EffectError::Contract(
286                "an effect defines no entry points; valo writes the @fragment entry".to_owned(),
287            ));
288        }
289        check_function(&module)?;
290        let (uniforms, image_names) = read_bindings(&module, kind)?;
291        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
292        Ok(Arc::new(RuntimeEffect {
293            id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
294            kind,
295            source: Arc::from(wgsl),
296            uniforms,
297            image_names,
298            constants: read_constants(&module)?,
299        }))
300    }
301}
302
303/// The function every effect defines.
304const FUNCTION: &str = "shade";
305
306/// The effect's `shade` function exists with its signature.
307fn check_function(module: &naga::Module) -> Result<(), EffectError> {
308    let name = FUNCTION;
309    let signature = format!("fn {name}(position: vec2<f32>) -> vec4<f32>");
310    let Some((_, function)) = module
311        .functions
312        .iter()
313        .find(|(_, function)| function.name.as_deref() == Some(name))
314    else {
315        return Err(EffectError::Contract(format!("missing `{signature}`")));
316    };
317    let takes_position = function.arguments.len() == 1
318        && is_float_vector(module, function.arguments[0].ty, VectorSize::Bi);
319    let returns_colour = function
320        .result
321        .as_ref()
322        .is_some_and(|result| is_float_vector(module, result.ty, VectorSize::Quad));
323    if !(takes_position && returns_colour) {
324        return Err(EffectError::Contract(format!(
325            "`{name}` must be `{signature}`"
326        )));
327    }
328    Ok(())
329}
330
331fn is_float_vector(module: &naga::Module, ty: naga::Handle<naga::Type>, size: VectorSize) -> bool {
332    matches!(
333        module.types[ty].inner,
334        TypeInner::Vector { size: vector_size, scalar }
335            if vector_size == size && scalar.kind == ScalarKind::Float && scalar.width == 4
336    )
337}
338
339/// The effect's uniform layout and image count, after checking every binding it declares sits
340/// where the contract puts it.
341fn read_bindings(
342    module: &naga::Module,
343    kind: EffectKind,
344) -> Result<(UniformLayout, Vec<String>), EffectError> {
345    let contract = naga::front::wgsl::parse_str(RuntimeEffect::contract(kind))
346        .expect("valo's contract parses");
347    let contract_names: Vec<&str> = contract
348        .global_variables
349        .iter()
350        .filter_map(|(_, global)| global.name.as_deref())
351        .collect();
352    let mut uniforms = UniformLayout::default();
353    let mut textures = Vec::new();
354    let mut samplers = Vec::new();
355    for (_, global) in module.global_variables.iter() {
356        let name = global.name.as_deref().unwrap_or("<unnamed>");
357        if contract_names.contains(&name) {
358            continue;
359        }
360        let Some(binding) = &global.binding else {
361            continue;
362        };
363        let inner = &module.types[global.ty].inner;
364        match (binding.group, binding.binding) {
365            (UNIFORM_GROUP, 0) => uniforms = read_uniforms(module, name, inner, global.space)?,
366            (IMAGE_GROUP, index) => match inner {
367                TypeInner::Image {
368                    dim: ImageDimension::D2,
369                    arrayed: false,
370                    class:
371                        ImageClass::Sampled {
372                            kind: ScalarKind::Float,
373                            multi: false,
374                        },
375                } if index % 2 == 0 => textures.push((index, name.to_owned())),
376                TypeInner::Sampler { comparison: false } if index % 2 == 1 => samplers.push(index),
377                _ => {
378                    return Err(EffectError::Contract(format!(
379                        "`{name}` at @group({IMAGE_GROUP}) @binding({index}): images are \
380                         texture_2d<f32> at even bindings, each followed by its sampler"
381                    )));
382                }
383            },
384            (group, index) => {
385                return Err(EffectError::Contract(format!(
386                    "`{name}` at @group({group}) @binding({index}): an effect's images are in \
387                     @group({IMAGE_GROUP}) and its uniforms at @group({UNIFORM_GROUP}) @binding(0)"
388                )));
389            }
390        }
391    }
392    textures.sort_unstable();
393    samplers.sort_unstable();
394    let paired = samplers.len() == textures.len()
395        && textures.iter().enumerate().all(|(slot, (binding, _))| {
396            *binding == 2 * slot as u32 && samplers[slot] == binding + 1
397        });
398    if !paired {
399        return Err(EffectError::Contract(format!(
400            "images must be texture_2d<f32> / sampler pairs in @group({IMAGE_GROUP}), at bindings \
401             0 and 1, 2 and 3, …"
402        )));
403    }
404    Ok((
405        uniforms,
406        textures.into_iter().map(|(_, name)| name).collect(),
407    ))
408}
409
410fn read_uniforms(
411    module: &naga::Module,
412    name: &str,
413    inner: &TypeInner,
414    space: AddressSpace,
415) -> Result<UniformLayout, EffectError> {
416    let (TypeInner::Struct { members, span }, AddressSpace::Uniform) = (inner, space) else {
417        return Err(EffectError::Contract(format!(
418            "@group({UNIFORM_GROUP}) @binding(0) is the effect's uniform struct; `{name}` is not one"
419        )));
420    };
421    if *span > MAX_UNIFORM_BYTES {
422        return Err(EffectError::Contract(format!(
423            "the uniform struct is {span} bytes; an effect's uniforms fit in {MAX_UNIFORM_BYTES}"
424        )));
425    }
426    Ok(UniformLayout {
427        size: *span,
428        fields: members
429            .iter()
430            .map(|member| uniform_field(module, member))
431            .collect(),
432    })
433}
434
435/// `uniform_field` is one member of the uniform struct: an array's element type and layout, or
436/// any other member's type.
437fn uniform_field(module: &naga::Module, member: &naga::StructMember) -> UniformField {
438    let (ty, array) = match module.types[member.ty].inner {
439        TypeInner::Array {
440            base,
441            size: naga::ArraySize::Constant(count),
442            stride,
443        } => (
444            uniform_type(module, base),
445            Some(UniformArray {
446                count: count.get(),
447                stride,
448            }),
449        ),
450        _ => (uniform_type(module, member.ty), None),
451    };
452    UniformField {
453        name: member.name.clone().unwrap_or_default(),
454        offset: member.offset,
455        ty,
456        array,
457    }
458}
459
460fn uniform_type(module: &naga::Module, ty: naga::Handle<naga::Type>) -> UniformType {
461    let inner = &module.types[ty].inner;
462    match *inner {
463        TypeInner::Scalar(scalar) if scalar.width == 4 => match scalar.kind {
464            ScalarKind::Float => UniformType::F32,
465            ScalarKind::Sint => UniformType::I32,
466            ScalarKind::Uint => UniformType::U32,
467            _ => UniformType::Other {
468                size: inner.size(module.to_ctx()),
469            },
470        },
471        TypeInner::Vector { size, scalar } if scalar.width == 4 => match (size, scalar.kind) {
472            (VectorSize::Bi, ScalarKind::Float) => UniformType::Vec2F,
473            (VectorSize::Tri, ScalarKind::Float) => UniformType::Vec3F,
474            (VectorSize::Quad, ScalarKind::Float) => UniformType::Vec4F,
475            (VectorSize::Bi, ScalarKind::Sint) => UniformType::Vec2I,
476            (VectorSize::Bi, ScalarKind::Uint) => UniformType::Vec2U,
477            _ => UniformType::Other {
478                size: inner.size(module.to_ctx()),
479            },
480        },
481        TypeInner::Matrix {
482            columns,
483            rows,
484            scalar,
485        } if scalar.kind == ScalarKind::Float && scalar.width == 4 && columns == rows => {
486            match columns {
487                VectorSize::Bi => UniformType::Mat2x2F,
488                VectorSize::Tri => UniformType::Mat3x3F,
489                VectorSize::Quad => UniformType::Mat4x4F,
490            }
491        }
492        _ => UniformType::Other {
493            size: inner.size(module.to_ctx()),
494        },
495    }
496}
497
498/// The names of the effect's `override` constants, each keyed by its name and given a default.
499fn read_constants(module: &naga::Module) -> Result<Vec<String>, EffectError> {
500    module
501        .overrides
502        .iter()
503        .map(|(_, constant)| {
504            let name = constant.name.clone().unwrap_or_default();
505            if constant.id.is_some() {
506                return Err(EffectError::Contract(format!(
507                    "override `{name}` has an @id; valo sets overrides by name"
508                )));
509            }
510            if constant.init.is_none() {
511                return Err(EffectError::Contract(format!(
512                    "override `{name}` needs a default"
513                )));
514            }
515            Ok(name)
516        })
517        .collect()
518}
519
520/// An image an effect samples, and how.
521#[derive(Clone, Debug, PartialEq)]
522#[cfg_attr(feature = "serde", derive(serde::Serialize))]
523pub struct EffectImage {
524    /// The image sampled; `None` only in the first slot of a paint shader's effect used as an
525    /// image filter, where the renderer binds the filter's input, as Flutter leaves the first
526    /// sampler of `ImageFilter.shader` for the engine to set.
527    pub image: Option<crate::Image>,
528    /// How the image is sampled; for the filter's input, Flutter's `filterQuality`.
529    pub sampling: crate::Sampling,
530}
531
532/// A [`RuntimeEffect`] with one draw's uniforms and images.
533#[derive(Clone, Debug)]
534#[cfg_attr(feature = "serde", derive(serde::Serialize))]
535pub struct RuntimeShader {
536    pub effect: Arc<RuntimeEffect>,
537    /// The uniform struct's bytes, exactly [`UniformLayout::size`] long.
538    pub uniforms: Arc<[u8]>,
539    /// One image, with how it is sampled, per image pair the effect declares.
540    pub images: Vec<EffectImage>,
541    /// Values for the effect's `override` constants, by name; unset ones keep their default.
542    pub constants: Vec<(String, f64)>,
543    /// How far past its area this draw's filter reads, in place of the effect's
544    /// [`FilterInputs::margin`]: for a filter whose reach follows its uniforms.
545    pub margin: Option<f32>,
546}
547
548impl RuntimeShader {
549    /// Pairs `effect` with a draw's inputs, checking they fit what it declares.
550    pub fn new(
551        effect: Arc<RuntimeEffect>,
552        uniforms: impl Into<Arc<[u8]>>,
553        images: Vec<EffectImage>,
554    ) -> Result<RuntimeShader, EffectError> {
555        let uniforms = uniforms.into();
556        if uniforms.len() != effect.uniforms.size as usize {
557            return Err(EffectError::Contract(format!(
558                "the effect's uniforms are {} bytes, not {}",
559                effect.uniforms.size,
560                uniforms.len()
561            )));
562        }
563        if images.len() != effect.image_names.len() {
564            return Err(EffectError::Contract(format!(
565                "the effect samples {} images, not {}",
566                effect.image_names.len(),
567                images.len()
568            )));
569        }
570        Ok(RuntimeShader {
571            effect,
572            uniforms,
573            images,
574            constants: Vec::new(),
575            margin: None,
576        })
577    }
578
579    /// `check_images_set` refuses a draw that leaves an image unset: one with no filter input
580    /// to fill it.
581    pub(crate) fn check_images_set(&self) -> Result<(), EffectError> {
582        match self.images.iter().position(|input| input.image.is_none()) {
583            Some(slot) => Err(EffectError::Contract(format!(
584                "image {slot} is unset; only a filter's input, the first image of a paint \
585                 shader's effect used as an image filter, is left to the renderer"
586            ))),
587            None => Ok(()),
588        }
589    }
590
591    /// `check_filter_input` refuses a paint shader's effect that cannot be a filter by
592    /// Flutter's convention, checking what dart:ui's `ImageFilter.shader` checks: the first
593    /// uniform is a `vec2f`, the input's size, and the first image is left unset for the input.
594    pub(crate) fn check_filter_input(&self) -> Result<(), EffectError> {
595        let size_first = self.effect.uniforms.fields.first().is_some_and(|field| {
596            field.offset == 0 && field.ty == UniformType::Vec2F && field.array.is_none()
597        });
598        if !size_first {
599            return Err(EffectError::Contract(
600                "a paint shader used as a filter has a vec2<f32> first in its uniforms, which \
601                 the renderer sets to its input's size"
602                    .to_owned(),
603            ));
604        }
605        let Some((input, others)) = self.images.split_first() else {
606            return Err(EffectError::Contract(
607                "a paint shader used as a filter samples at least one image, its input".to_owned(),
608            ));
609        };
610        if input.image.is_some() {
611            return Err(EffectError::Contract(
612                "a paint shader used as a filter leaves its first image unset, for its input"
613                    .to_owned(),
614            ));
615        }
616        if others.iter().any(|other| other.image.is_none()) {
617            return Err(EffectError::Contract(
618                "only a filter's first image, its input, is left unset".to_owned(),
619            ));
620        }
621        Ok(())
622    }
623
624    /// Sets how far past its area this draw's filter reads, in local units, in place of the
625    /// effect's [`FilterInputs::margin`].
626    pub fn margin(mut self, margin: f32) -> Result<RuntimeShader, EffectError> {
627        if self.effect.filter_inputs().is_none() {
628            return Err(EffectError::Contract(
629                "only a filter reads past its area".to_owned(),
630            ));
631        }
632        // Written so NaN fails too.
633        let margin_in_range = margin >= 0.0;
634        if !margin_in_range {
635            return Err(EffectError::Contract(format!(
636                "margin must not be negative, not {margin}"
637            )));
638        }
639        self.margin = Some(margin);
640        Ok(self)
641    }
642
643    /// How far past its area this draw's filter reads: its own margin, or its effect's.
644    pub fn read_margin(&self) -> f32 {
645        self.margin.unwrap_or_else(|| {
646            self.effect
647                .filter_inputs()
648                .map_or(0.0, |inputs| inputs.margin)
649        })
650    }
651
652    /// Sets the `override` constant `name` for this draw, choosing a pipeline variant.
653    pub fn constant(mut self, name: &str, value: f64) -> Result<RuntimeShader, EffectError> {
654        if !self
655            .effect
656            .constants
657            .iter()
658            .any(|constant| constant == name)
659        {
660            return Err(EffectError::Contract(format!(
661                "the effect declares no override `{name}`"
662            )));
663        }
664        self.constants.retain(|(existing, _)| existing != name);
665        self.constants.push((name.to_owned(), value));
666        Ok(self)
667    }
668}
669
670impl PartialEq for RuntimeShader {
671    fn eq(&self, other: &RuntimeShader) -> bool {
672        Arc::ptr_eq(&self.effect, &other.effect)
673            && self.uniforms == other.uniforms
674            && self.images == other.images
675            && self.constants == other.constants
676            && self.margin == other.margin
677    }
678}
679
680#[cfg(test)]
681mod tests {
682    use super::*;
683
684    const WAVE: &str = "
685struct Uniforms {
686    time: f32,
687    tint: vec4<f32>,
688    centre: vec3<f32>,
689}
690@group(2) @binding(0) var<uniform> u: Uniforms;
691
692fn shade(position: vec2<f32>) -> vec4<f32> {
693    return u.tint * (0.5 + 0.5 * sin(position.x * 0.1 + u.time));
694}
695";
696
697    #[test]
698    fn a_shader_reads_its_uniform_layout() {
699        let effect = RuntimeEffect::shader(WAVE).expect("valid shader");
700        let uniforms = effect.uniforms();
701        assert_eq!(uniforms.size, 48);
702        let fields: Vec<_> = uniforms
703            .fields
704            .iter()
705            .map(|field| (field.name.as_str(), field.offset, field.ty))
706            .collect();
707        assert_eq!(
708            fields,
709            vec![
710                ("time", 0, UniformType::F32),
711                ("tint", 16, UniformType::Vec4F),
712                ("centre", 32, UniformType::Vec3F),
713            ]
714        );
715        assert_eq!(effect.images(), 0);
716        assert!(uniforms.fields.iter().all(|field| field.array.is_none()));
717    }
718
719    /// An array field reports its elements' type and layout, as Impeller's reflection does,
720    /// so a host can write floats packed tightly by index into WGSL's 16-byte elements.
721    #[test]
722    fn an_array_reports_its_elements() {
723        let effect = RuntimeEffect::shader(
724            "
725struct Uniforms {
726    size: vec2<f32>,
727    shapes: array<vec4<f32>, 28>,
728    corners: array<vec3<f32>, 2>,
729    rows: array<array<vec4<f32>, 2>, 3>,
730}
731@group(2) @binding(0) var<uniform> u: Uniforms;
732
733fn shade(position: vec2<f32>) -> vec4<f32> {
734    return u.shapes[0] + vec4<f32>(u.corners[1], u.size.x) + u.rows[2][1];
735}
736",
737        )
738        .expect("valid shader");
739        let fields: Vec<_> = effect
740            .uniforms()
741            .fields
742            .iter()
743            .map(|field| (field.name.as_str(), field.offset, field.ty, field.array))
744            .collect();
745        let array = |count, stride| Some(UniformArray { count, stride });
746        assert_eq!(
747            fields,
748            vec![
749                ("size", 0, UniformType::Vec2F, None),
750                ("shapes", 16, UniformType::Vec4F, array(28, 16)),
751                ("corners", 464, UniformType::Vec3F, array(2, 16)),
752                ("rows", 496, UniformType::Other { size: 32 }, array(3, 32)),
753            ]
754        );
755        assert_eq!(effect.uniforms().size, 592);
756    }
757
758    #[test]
759    fn a_filter_may_use_the_contract() {
760        let effect = RuntimeEffect::filter(
761            "
762@group(1) @binding(0) var noise: texture_2d<f32>;
763@group(1) @binding(1) var noise_sampler: sampler;
764
765fn shade(position: vec2<f32>) -> vec4<f32> {
766    let lod = source_levels() - 1.0;
767    let grain = textureSampleLevel(noise, noise_sampler, position / 64.0, 0.0);
768    return textureSampleLevel(source, source_sampler, uv_of(position), lod) * grain;
769}
770",
771            FilterInputs {
772                margin: 12.0,
773                source_mips: true,
774                source_scale: 0.5,
775            },
776        )
777        .expect("valid filter");
778        assert_eq!(effect.images(), 1);
779        assert_eq!(effect.image_names(), ["noise"]);
780        let shader = RuntimeShader::new(effect.clone(), Vec::new(), vec![]);
781        assert!(shader.is_err(), "the noise image is missing");
782        assert_eq!(effect.uniforms().size, 0);
783    }
784
785    #[test]
786    fn override_constants_choose_variants() {
787        let effect = RuntimeEffect::shader(
788            "
789override highlights: bool = true;
790override quality: f32 = 1.0;
791fn shade(position: vec2<f32>) -> vec4<f32> {
792    if highlights { return vec4<f32>(quality); }
793    return vec4<f32>(0.0);
794}
795",
796        )
797        .expect("valid shader");
798        assert_eq!(effect.constants(), ["highlights", "quality"]);
799        let shader = RuntimeShader::new(effect, Vec::new(), Vec::new())
800            .unwrap()
801            .constant("quality", 2.0)
802            .unwrap();
803        assert_eq!(shader.constants, vec![("quality".to_owned(), 2.0)]);
804        assert!(shader.constant("missing", 1.0).is_err());
805        let without_default = RuntimeEffect::shader(
806            "override quality: f32;
807             fn shade(position: vec2<f32>) -> vec4<f32> { return vec4<f32>(quality); }",
808        );
809        assert!(contract_error(without_default).contains("needs a default"));
810    }
811
812    /// A draw may read further than its effect says, as a filter whose reach follows its
813    /// uniforms does; a paint shader reads nothing past its area.
814    #[test]
815    fn a_draw_may_set_its_own_margin() {
816        let filter = RuntimeEffect::filter(
817            "fn shade(position: vec2<f32>) -> vec4<f32> {
818                 return textureSampleLevel(source, source_sampler, uv_of(position), 0.0);
819             }",
820            FilterInputs {
821                margin: 4.0,
822                ..FilterInputs::default()
823            },
824        )
825        .unwrap();
826        let shader = RuntimeShader::new(filter, Vec::new(), Vec::new()).unwrap();
827        assert_eq!(shader.read_margin(), 4.0);
828        let wider = shader.clone().margin(20.0).unwrap();
829        assert_eq!(wider.read_margin(), 20.0);
830        assert_ne!(wider, shader);
831        assert!(shader.margin(f32::NAN).is_err());
832        let paint = RuntimeEffect::shader(
833            "fn shade(position: vec2<f32>) -> vec4<f32> { return vec4<f32>(1.0); }",
834        )
835        .unwrap();
836        let paint = RuntimeShader::new(paint, Vec::new(), Vec::new()).unwrap();
837        assert!(paint.margin(1.0).is_err());
838    }
839
840    fn contract_error(result: Result<Arc<RuntimeEffect>, EffectError>) -> String {
841        match result {
842            Err(EffectError::Contract(message)) => message,
843            other => panic!("expected a contract error, got {other:?}"),
844        }
845    }
846
847    #[test]
848    fn the_function_must_exist_with_its_signature() {
849        let missing = RuntimeEffect::shader(
850            "fn paint(position: vec2<f32>) -> vec4<f32> { return vec4<f32>(1.0); }",
851        );
852        assert!(contract_error(missing).contains("missing `fn shade"));
853        let wrong = RuntimeEffect::shader(
854            "fn shade(position: vec2<f32>) -> vec3<f32> { return vec3<f32>(1.0); }",
855        );
856        assert!(contract_error(wrong).contains("must be"));
857        let shader_reading_source = RuntimeEffect::shader(
858            "fn shade(position: vec2<f32>) -> vec4<f32> { return textureLoad(source, vec2<i32>(0), 0); }",
859        );
860        assert!(
861            matches!(shader_reading_source, Err(EffectError::Parse(_))),
862            "only filters have a source"
863        );
864    }
865
866    #[test]
867    fn bindings_must_sit_where_the_contract_puts_them() {
868        let renderer_group = RuntimeEffect::shader(
869            "@group(0) @binding(5) var<uniform> x: vec4<f32>;
870             fn shade(position: vec2<f32>) -> vec4<f32> { return x; }",
871        );
872        assert!(contract_error(renderer_group).contains("@group(0)"));
873        let lone_texture = RuntimeEffect::shader(
874            "@group(1) @binding(0) var t: texture_2d<f32>;
875             fn shade(position: vec2<f32>) -> vec4<f32> { return textureLoad(t, vec2<i32>(0), 0); }",
876        );
877        assert!(contract_error(lone_texture).contains("pairs"));
878        let entry_point = RuntimeEffect::shader(
879            "fn shade(position: vec2<f32>) -> vec4<f32> { return vec4<f32>(1.0); }
880             @fragment fn main() -> @location(0) vec4<f32> { return shade(vec2<f32>(0.0)); }",
881        );
882        assert!(contract_error(entry_point).contains("entry points"));
883    }
884
885    #[test]
886    fn uniforms_have_a_size_limit() {
887        let oversized = RuntimeEffect::shader(
888            "struct Big { values: array<vec4<f32>, 65> }
889             @group(2) @binding(0) var<uniform> big: Big;
890             fn shade(position: vec2<f32>) -> vec4<f32> { return big.values[0]; }",
891        );
892        assert!(contract_error(oversized).contains("1024"));
893    }
894
895    #[test]
896    fn a_parse_error_points_into_the_authors_source() {
897        let Err(EffectError::Parse(message)) =
898            RuntimeEffect::shader("fn shade(position: vec2<f32>) -> vec4<f32> { return oops; }")
899        else {
900            panic!("expected a parse error");
901        };
902        assert!(message.contains("oops"), "{message}");
903        assert!(message.contains(":1:"), "{message}");
904    }
905
906    /// A paint shader's effect is a filter by Flutter's convention: dart:ui's checks, its first
907    /// uniform the input's size and its first image left for the input, and nothing else unset.
908    #[test]
909    fn a_paint_shader_is_a_filter_by_flutters_convention() {
910        let effect = RuntimeEffect::shader(
911            "struct U { size: vec2<f32>, amount: f32 }
912             @group(2) @binding(0) var<uniform> u: U;
913             @group(1) @binding(0) var input: texture_2d<f32>;
914             @group(1) @binding(1) var input_sampler: sampler;
915             fn shade(position: vec2<f32>) -> vec4<f32> {
916                 return textureSampleLevel(input, input_sampler, position / u.size, 0.0) * u.amount;
917             }",
918        )
919        .unwrap();
920        let shader = |image: Option<crate::Image>| {
921            RuntimeShader::new(
922                effect.clone(),
923                vec![0; 16],
924                vec![EffectImage {
925                    image,
926                    sampling: crate::Sampling::default(),
927                }],
928            )
929            .unwrap()
930        };
931        assert!(crate::ImageFilter::runtime(shader(None)).is_ok());
932        assert!(
933            crate::Shader::runtime(shader(None)).is_err(),
934            "a paint shader samples only images it is given"
935        );
936
937        let size_last = RuntimeEffect::shader(
938            "struct U { amount: f32, size: vec2<f32> }
939             @group(2) @binding(0) var<uniform> u: U;
940             @group(1) @binding(0) var input: texture_2d<f32>;
941             @group(1) @binding(1) var input_sampler: sampler;
942             fn shade(position: vec2<f32>) -> vec4<f32> {
943                 return textureSampleLevel(input, input_sampler, position / u.size, 0.0) * u.amount;
944             }",
945        )
946        .unwrap();
947        let unset = vec![EffectImage {
948            image: None,
949            sampling: crate::Sampling::default(),
950        }];
951        let size_last = RuntimeShader::new(size_last, vec![0; 16], unset.clone()).unwrap();
952        assert!(crate::ImageFilter::runtime(size_last).is_err());
953
954        let no_image = RuntimeEffect::shader(
955            "struct U { size: vec2<f32> }
956             @group(2) @binding(0) var<uniform> u: U;
957             fn shade(position: vec2<f32>) -> vec4<f32> { return vec4<f32>(position / u.size, 0.0, 1.0); }",
958        )
959        .unwrap();
960        let no_image = RuntimeShader::new(no_image, vec![0; 8], Vec::new()).unwrap();
961        assert!(crate::ImageFilter::runtime(no_image).is_err());
962
963        let valo_filter = RuntimeEffect::filter(
964            "@group(1) @binding(0) var t: texture_2d<f32>;
965             @group(1) @binding(1) var s: sampler;
966             fn shade(position: vec2<f32>) -> vec4<f32> { return textureSampleLevel(t, s, position, 0.0); }",
967            FilterInputs::default(),
968        )
969        .unwrap();
970        let valo_filter = RuntimeShader::new(valo_filter, Vec::new(), unset).unwrap();
971        assert!(
972            crate::ImageFilter::runtime(valo_filter).is_err(),
973            "a filter's effect reads its input as `source`"
974        );
975    }
976
977    #[test]
978    fn draw_inputs_must_fit_the_effect() {
979        let effect = RuntimeEffect::shader(WAVE).unwrap();
980        assert!(RuntimeShader::new(effect.clone(), vec![0; 48], Vec::new()).is_ok());
981        assert!(RuntimeShader::new(effect, vec![0; 16], Vec::new()).is_err());
982        assert!(RuntimeEffect::filter(
983            WAVE,
984            FilterInputs {
985                source_scale: 0.0,
986                ..FilterInputs::default()
987            }
988        )
989        .is_err());
990    }
991}