Skip to main content

alpha2_model/
effect_spec.rs

1//! The built-in effects and transitions every engine registers, as data.
2
3use std::collections::{BTreeMap, HashMap};
4use std::sync::OnceLock;
5
6use serde::Deserialize;
7
8use crate::{Animated, ClipEffect, EffectValue, NodeId};
9
10/// Id prefix of built-in effects and transitions. A document id under it must name a built-in, so
11/// host effects use ids outside it.
12pub const BUILTIN_EFFECT_PREFIX: &str = "alpha2.";
13
14/// The catalog the renderer's built-ins serialize to, written by `emit-effect-catalog`.
15const CATALOG_JSON: &str = include_str!("builtin-effects.json");
16
17/// What an effect definition draws.
18#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
19#[serde(rename_all = "snake_case")]
20pub enum EffectKind {
21    /// An image effect with one source and any declared named inputs.
22    Effect,
23    /// A two-input transition at an explicit progress.
24    Transition,
25}
26
27/// The type of a parameter's values: the [`EffectValue`] variant it takes.
28#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
29#[serde(rename_all = "snake_case")]
30pub enum EffectParamType {
31    /// [`EffectValue::Float`].
32    Float,
33    /// [`EffectValue::Vec2`].
34    Vec2,
35    /// [`EffectValue::Vec4`].
36    Vec4,
37    /// [`EffectValue::Color`].
38    Color,
39    /// [`EffectValue::Enum`].
40    Enum,
41    /// [`EffectValue::Bool`].
42    Bool,
43}
44
45/// How a parameter's value reads in an editor.
46#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
47#[serde(rename_all = "snake_case")]
48pub enum EffectParamUnit {
49    /// A plain or normalized number: a fraction, count, rate, seed or size.
50    Normalized,
51    /// An angle in degrees.
52    Degrees,
53    /// A color.
54    Color,
55    /// One of the named choices.
56    Enum,
57    /// A toggle.
58    Bool,
59}
60
61/// One declared parameter of a built-in definition.
62#[derive(Clone, Debug, PartialEq)]
63#[non_exhaustive]
64pub struct EffectParamSpec {
65    /// The name a [`ClipEffect`] sets it by.
66    pub name: String,
67    /// A human-readable label.
68    pub label: String,
69    /// The type of its values.
70    pub param_type: EffectParamType,
71    /// The value used when a document leaves it out.
72    pub default: EffectValue,
73    /// Inclusive minimum of each scalar component.
74    pub min: Option<f32>,
75    /// Inclusive maximum of each scalar component.
76    pub max: Option<f32>,
77    /// A suggested editing increment.
78    pub step: Option<f32>,
79    /// How its value reads.
80    pub unit: EffectParamUnit,
81    /// The choices of an [`EffectParamType::Enum`]; an enum value is an index into them.
82    pub enum_values: Vec<String>,
83}
84
85impl EffectParamSpec {
86    /// Whether `value` has this parameter's type and lies in its range, as the renderer
87    /// requires of an authored value.
88    #[must_use]
89    pub fn accepts(&self, value: &EffectValue) -> bool {
90        let scalar = |value: f32| {
91            value.is_finite()
92                && self.min.is_none_or(|minimum| value >= minimum)
93                && self.max.is_none_or(|maximum| value <= maximum)
94        };
95        match (self.param_type, value) {
96            (EffectParamType::Float, EffectValue::Float(value)) => scalar(*value),
97            (EffectParamType::Vec2, EffectValue::Vec2(values)) => {
98                values.iter().all(|value| scalar(*value))
99            }
100            (EffectParamType::Vec4, EffectValue::Vec4(values)) => {
101                values.iter().all(|value| scalar(*value))
102            }
103            (EffectParamType::Color, EffectValue::Color(values)) => values
104                .iter()
105                .all(|value| value.is_finite() && (0.0..=1.0).contains(value)),
106            (EffectParamType::Enum, EffectValue::Enum(index)) => {
107                usize::try_from(*index).is_ok_and(|index| index < self.enum_values.len())
108            }
109            (EffectParamType::Bool, EffectValue::Bool(_)) => true,
110            _ => false,
111        }
112    }
113
114    /// The range of each scalar component, as [`Self::accepts`] checks it.
115    #[must_use]
116    pub const fn domain(&self) -> crate::Domain {
117        crate::Domain::new(
118            match self.min {
119                Some(min) => min,
120                None => f32::NEG_INFINITY,
121            },
122            match self.max {
123                Some(max) => max,
124                None => f32::INFINITY,
125            },
126        )
127    }
128
129    /// Whether the parameter can follow a data set, which only Float and Vec2 ones can.
130    #[must_use]
131    pub const fn takes_data(&self) -> bool {
132        matches!(
133            self.param_type,
134            EffectParamType::Float | EffectParamType::Vec2
135        )
136    }
137
138    /// Whether every authored value of `animation` is accepted, or for a data binding whether the
139    /// type takes data. Only keyframe values count, since interpolated overshoot is clamped.
140    #[must_use]
141    pub fn accepts_animation(&self, animation: &Animated<EffectValue>) -> bool {
142        match animation {
143            Animated::Constant { value } => self.accepts(value),
144            Animated::Keyframes { keyframes } => keyframes
145                .iter()
146                .all(|keyframe| self.accepts(&keyframe.value)),
147            Animated::Data(_) => self.takes_data(),
148        }
149    }
150}
151
152/// A built-in effect or transition definition, without its shader.
153#[derive(Clone, Debug, PartialEq)]
154#[non_exhaustive]
155pub struct EffectSpec {
156    /// The id documents name it by.
157    pub id: String,
158    /// The version documents must name.
159    pub version: u32,
160    /// What it draws.
161    pub kind: EffectKind,
162    /// A human-readable label.
163    pub label: String,
164    /// The catalog group it is listed under.
165    pub group: String,
166    /// The named images it samples besides its input.
167    pub inputs: Vec<String>,
168    /// Its parameters, in declaration order.
169    pub params: Vec<EffectParamSpec>,
170    /// The external resources it reads, by slot name.
171    pub resources: Vec<String>,
172    /// Whether this transition of two pictures under one coverage (a matte or mask) equals that
173    /// coverage over their transition, for every parameter value.
174    pub coverage_commutes: bool,
175}
176
177impl EffectSpec {
178    /// The parameter named `name`.
179    #[must_use]
180    pub fn param(&self, name: &str) -> Option<&EffectParamSpec> {
181        self.params.iter().find(|param| param.name == name)
182    }
183}
184
185/// Every built-in definition: effects, then transitions, in catalog order.
186#[must_use]
187pub fn builtin_effects() -> &'static [EffectSpec] {
188    &catalog().0
189}
190
191/// The built-in definition with `id`.
192#[must_use]
193pub fn builtin_effect(id: &str) -> Option<&'static EffectSpec> {
194    let (specs, index) = catalog();
195    index.get(id).map(|position| &specs[*position])
196}
197
198/// The catalog JSON the built-ins were read from, as `schema/effects.v1.json` publishes it.
199#[must_use]
200pub const fn builtin_effects_json() -> &'static str {
201    CATALOG_JSON
202}
203
204fn catalog() -> &'static (Vec<EffectSpec>, HashMap<String, usize>) {
205    static CATALOG: OnceLock<(Vec<EffectSpec>, HashMap<String, usize>)> = OnceLock::new();
206    CATALOG.get_or_init(|| {
207        let wire: CatalogWire =
208            serde_json::from_str(CATALOG_JSON).expect("the built-in effect catalog parses");
209        let specs = wire
210            .effects
211            .into_iter()
212            .chain(wire.transitions)
213            .map(EffectSpec::from)
214            .collect::<Vec<_>>();
215        let index = specs
216            .iter()
217            .enumerate()
218            .map(|(position, spec)| (spec.id.clone(), position))
219            .collect();
220        (specs, index)
221    })
222}
223
224/// Why a [`ClipEffect`] naming a built-in does not match it.
225#[derive(Clone, Debug, Eq, PartialEq)]
226#[non_exhaustive]
227pub enum EffectProblem {
228    /// The id is under [`BUILTIN_EFFECT_PREFIX`] but names no built-in.
229    UnknownBuiltin,
230    /// The version is not the built-in's.
231    Version {
232        /// The built-in's version.
233        expected: u32,
234    },
235    /// A transition where an effect belongs, or an effect where a transition belongs.
236    Kind,
237    /// A parameter the definition does not declare.
238    UnknownParam(String),
239    /// A parameter value of the wrong type or outside the declared range.
240    InvalidParam(String),
241    /// Named inputs other than exactly the declared ones.
242    Inputs,
243    /// Resources other than exactly the declared ones.
244    Resources,
245}
246
247/// Checks `effect` against its built-in definition, used as `kind`, as project validation does
248/// for a timeline transition or a node without named inputs. Ids outside
249/// [`BUILTIN_EFFECT_PREFIX`] belong to the host and pass.
250///
251/// # Errors
252/// What is wrong with the effect.
253pub fn check_builtin_effect(effect: &ClipEffect, kind: EffectKind) -> Result<(), EffectProblem> {
254    check_builtin(effect, kind, None)
255}
256
257/// Checks `effect` against its built-in definition, used as `kind`; `inputs` are an effect
258/// node's named inputs. Ids outside [`BUILTIN_EFFECT_PREFIX`] belong to the host and pass.
259pub(crate) fn check_builtin(
260    effect: &ClipEffect,
261    kind: EffectKind,
262    inputs: Option<&BTreeMap<String, Option<NodeId>>>,
263) -> Result<(), EffectProblem> {
264    if !effect.id.starts_with(BUILTIN_EFFECT_PREFIX) {
265        return Ok(());
266    }
267    let spec = builtin_effect(&effect.id).ok_or(EffectProblem::UnknownBuiltin)?;
268    if effect.version != spec.version {
269        return Err(EffectProblem::Version {
270            expected: spec.version,
271        });
272    }
273    if spec.kind != kind {
274        return Err(EffectProblem::Kind);
275    }
276    for (name, value) in &effect.params {
277        let param = spec
278            .param(name)
279            .ok_or_else(|| EffectProblem::UnknownParam(name.clone()))?;
280        if !param.accepts_animation(value) {
281            return Err(EffectProblem::InvalidParam(name.clone()));
282        }
283    }
284    let declared = |names: &[String], used: &mut dyn Iterator<Item = &String>| {
285        let used = used.collect::<Vec<_>>();
286        used.len() == names.len() && used.iter().all(|name| names.contains(name))
287    };
288    if !declared(
289        &spec.inputs,
290        &mut inputs.into_iter().flat_map(BTreeMap::keys),
291    ) {
292        return Err(EffectProblem::Inputs);
293    }
294    if !declared(&spec.resources, &mut effect.resources.keys()) {
295        return Err(EffectProblem::Resources);
296    }
297    Ok(())
298}
299
300#[derive(Deserialize)]
301struct CatalogWire {
302    effects: Vec<SpecWire>,
303    transitions: Vec<SpecWire>,
304}
305
306#[derive(Deserialize)]
307struct SpecWire {
308    id: String,
309    version: u32,
310    kind: EffectKind,
311    label: String,
312    group: String,
313    inputs: Vec<NamedWire>,
314    params: Vec<ParamWire>,
315    resources: Vec<NamedWire>,
316    #[serde(default)]
317    coverage_commutes: bool,
318}
319
320#[derive(Deserialize)]
321struct NamedWire {
322    name: String,
323}
324
325#[derive(Deserialize)]
326#[serde(rename_all = "camelCase")]
327struct ParamWire {
328    name: String,
329    label: String,
330    #[serde(rename = "type")]
331    param_type: EffectParamType,
332    default: serde_json::Value,
333    min: Option<f32>,
334    max: Option<f32>,
335    step: Option<f32>,
336    unit: EffectParamUnit,
337    enum_values: Vec<String>,
338}
339
340impl From<SpecWire> for EffectSpec {
341    fn from(wire: SpecWire) -> Self {
342        Self {
343            id: wire.id,
344            version: wire.version,
345            kind: wire.kind,
346            label: wire.label,
347            group: wire.group,
348            inputs: wire.inputs.into_iter().map(|input| input.name).collect(),
349            params: wire.params.into_iter().map(EffectParamSpec::from).collect(),
350            resources: wire
351                .resources
352                .into_iter()
353                .map(|resource| resource.name)
354                .collect(),
355            coverage_commutes: wire.coverage_commutes,
356        }
357    }
358}
359
360impl From<ParamWire> for EffectParamSpec {
361    fn from(wire: ParamWire) -> Self {
362        let default = default_value(wire.param_type, &wire.default)
363            .unwrap_or_else(|| panic!("parameter {} has a default of its type", wire.name));
364        Self {
365            name: wire.name,
366            label: wire.label,
367            param_type: wire.param_type,
368            default,
369            min: wire.min,
370            max: wire.max,
371            step: wire.step,
372            unit: wire.unit,
373            enum_values: wire.enum_values,
374        }
375    }
376}
377
378#[allow(clippy::cast_possible_truncation)]
379fn default_value(param_type: EffectParamType, value: &serde_json::Value) -> Option<EffectValue> {
380    // The catalog widens each `f32` to `f64`; narrowing restores it exactly.
381    let numbers = |count: usize| {
382        let values = value.as_array()?;
383        (values.len() == count)
384            .then(|| {
385                values
386                    .iter()
387                    .map(|value| value.as_f64().map(|value| value as f32))
388            })?
389            .collect::<Option<Vec<f32>>>()
390    };
391    Some(match param_type {
392        EffectParamType::Float => EffectValue::Float(value.as_f64()? as f32),
393        EffectParamType::Vec2 => EffectValue::Vec2(numbers(2)?.try_into().ok()?),
394        EffectParamType::Vec4 => EffectValue::Vec4(numbers(4)?.try_into().ok()?),
395        EffectParamType::Color => EffectValue::Color(numbers(4)?.try_into().ok()?),
396        EffectParamType::Enum => EffectValue::Enum(u32::try_from(value.as_u64()?).ok()?),
397        EffectParamType::Bool => EffectValue::Bool(value.as_bool()?),
398    })
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404
405    #[test]
406    fn every_builtin_parses_with_defaults_it_accepts() {
407        let specs = builtin_effects();
408        assert!(specs.iter().any(|spec| spec.kind == EffectKind::Effect));
409        assert!(specs.iter().any(|spec| spec.kind == EffectKind::Transition));
410        for spec in specs {
411            assert!(spec.id.starts_with(BUILTIN_EFFECT_PREFIX), "{}", spec.id);
412            assert_eq!(builtin_effect(&spec.id), Some(spec));
413            for param in &spec.params {
414                assert!(param.accepts(&param.default), "{} {}", spec.id, param.name);
415            }
416        }
417    }
418}