1use std::collections::{BTreeMap, HashMap};
4use std::sync::OnceLock;
5
6use serde::Deserialize;
7
8use crate::{Animated, ClipEffect, EffectValue, NodeId};
9
10pub const BUILTIN_EFFECT_PREFIX: &str = "alpha2.";
13
14const CATALOG_JSON: &str = include_str!("builtin-effects.json");
16
17#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
19#[serde(rename_all = "snake_case")]
20pub enum EffectKind {
21 Effect,
23 Transition,
25 Generator,
27}
28
29#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
31#[serde(rename_all = "snake_case")]
32pub enum EffectParamType {
33 Float,
35 Vec2,
37 Vec4,
39 Color,
41 Enum,
43 Bool,
45}
46
47#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
49#[serde(rename_all = "snake_case")]
50pub enum EffectParamUnit {
51 Normalized,
53 Degrees,
55 Color,
57 Enum,
59 Bool,
61}
62
63#[derive(Clone, Debug, PartialEq)]
65#[non_exhaustive]
66pub struct EffectParamSpec {
67 pub name: String,
69 pub label: String,
71 pub param_type: EffectParamType,
73 pub default: EffectValue,
75 pub min: Option<f32>,
77 pub max: Option<f32>,
79 pub step: Option<f32>,
81 pub unit: EffectParamUnit,
83 pub enum_values: Vec<String>,
85}
86
87impl EffectParamSpec {
88 #[must_use]
91 pub fn accepts(&self, value: &EffectValue) -> bool {
92 let scalar = |value: f32| {
93 value.is_finite()
94 && self.min.is_none_or(|minimum| value >= minimum)
95 && self.max.is_none_or(|maximum| value <= maximum)
96 };
97 match (self.param_type, value) {
98 (EffectParamType::Float, EffectValue::Float(value)) => scalar(*value),
99 (EffectParamType::Vec2, EffectValue::Vec2(values)) => {
100 values.iter().all(|value| scalar(*value))
101 }
102 (EffectParamType::Vec4, EffectValue::Vec4(values)) => {
103 values.iter().all(|value| scalar(*value))
104 }
105 (EffectParamType::Color, EffectValue::Color(values)) => values
106 .iter()
107 .all(|value| value.is_finite() && (0.0..=1.0).contains(value)),
108 (EffectParamType::Enum, EffectValue::Enum(index)) => {
109 usize::try_from(*index).is_ok_and(|index| index < self.enum_values.len())
110 }
111 (EffectParamType::Bool, EffectValue::Bool(_)) => true,
112 _ => false,
113 }
114 }
115
116 #[must_use]
118 pub const fn domain(&self) -> crate::Domain {
119 crate::Domain::new(
120 match self.min {
121 Some(min) => min,
122 None => f32::NEG_INFINITY,
123 },
124 match self.max {
125 Some(max) => max,
126 None => f32::INFINITY,
127 },
128 )
129 }
130
131 #[must_use]
133 pub const fn takes_data(&self) -> bool {
134 matches!(
135 self.param_type,
136 EffectParamType::Float | EffectParamType::Vec2
137 )
138 }
139
140 #[must_use]
144 pub fn accepts_animation(&self, animation: &Animated<EffectValue>) -> bool {
145 match animation {
146 Animated::Constant { value } => self.accepts(value),
147 Animated::Keyframes { keyframes, .. } => keyframes
148 .iter()
149 .all(|keyframe| self.accepts(&keyframe.value)),
150 Animated::Split { channels } => {
151 let components = match self.param_type {
152 EffectParamType::Vec2 => 2,
153 EffectParamType::Vec4 => 4,
154 _ => return false,
155 };
156 let domain = self.domain();
157 channels.len() == components
158 && channels.iter().all(|channel| match channel {
159 Animated::Constant { value } => domain.contains(*value),
160 Animated::Keyframes { keyframes, .. } => keyframes
161 .iter()
162 .all(|keyframe| domain.contains(keyframe.value)),
163 Animated::Data(_) => true,
164 Animated::Split { .. } => false,
165 })
166 }
167 Animated::Data(_) => self.takes_data(),
168 }
169 }
170}
171
172#[derive(Clone, Debug, PartialEq)]
174#[non_exhaustive]
175pub struct EffectSpec {
176 pub id: String,
178 pub version: u32,
180 pub kind: EffectKind,
182 pub label: String,
184 pub group: String,
186 pub inputs: Vec<String>,
188 pub params: Vec<EffectParamSpec>,
190 pub resources: Vec<String>,
192 pub coverage_commutes: bool,
195}
196
197impl EffectSpec {
198 #[must_use]
200 pub fn param(&self, name: &str) -> Option<&EffectParamSpec> {
201 self.params.iter().find(|param| param.name == name)
202 }
203}
204
205#[must_use]
207pub fn builtin_effects() -> &'static [EffectSpec] {
208 &catalog().0
209}
210
211#[must_use]
213pub fn builtin_effect(id: &str) -> Option<&'static EffectSpec> {
214 let (specs, index) = catalog();
215 index.get(id).map(|position| &specs[*position])
216}
217
218#[must_use]
220pub const fn builtin_effects_json() -> &'static str {
221 CATALOG_JSON
222}
223
224fn catalog() -> &'static (Vec<EffectSpec>, HashMap<String, usize>) {
225 static CATALOG: OnceLock<(Vec<EffectSpec>, HashMap<String, usize>)> = OnceLock::new();
226 CATALOG.get_or_init(|| {
227 let wire: CatalogWire =
228 serde_json::from_str(CATALOG_JSON).expect("the built-in effect catalog parses");
229 let specs = wire
230 .effects
231 .into_iter()
232 .chain(wire.transitions)
233 .chain(wire.generators)
234 .map(EffectSpec::from)
235 .collect::<Vec<_>>();
236 let index = specs
237 .iter()
238 .enumerate()
239 .map(|(position, spec)| (spec.id.clone(), position))
240 .collect();
241 (specs, index)
242 })
243}
244
245#[derive(Clone, Debug, Eq, PartialEq)]
247#[non_exhaustive]
248pub enum EffectProblem {
249 UnknownBuiltin,
251 Version {
253 expected: u32,
255 },
256 Kind,
258 UnknownParam(String),
260 InvalidParam(String),
262 Inputs,
264 Resources,
266}
267
268pub fn check_builtin_effect(effect: &ClipEffect, kind: EffectKind) -> Result<(), EffectProblem> {
275 check_builtin(effect, kind, None)
276}
277
278pub(crate) fn check_builtin(
281 effect: &ClipEffect,
282 kind: EffectKind,
283 inputs: Option<&BTreeMap<String, Option<NodeId>>>,
284) -> Result<(), EffectProblem> {
285 if !effect.id.starts_with(BUILTIN_EFFECT_PREFIX) {
286 return Ok(());
287 }
288 let spec = builtin_effect(&effect.id).ok_or(EffectProblem::UnknownBuiltin)?;
289 if effect.version != spec.version {
290 return Err(EffectProblem::Version {
291 expected: spec.version,
292 });
293 }
294 if spec.kind != kind {
295 return Err(EffectProblem::Kind);
296 }
297 for (name, value) in &effect.params {
298 let param = spec
299 .param(name)
300 .ok_or_else(|| EffectProblem::UnknownParam(name.clone()))?;
301 if !param.accepts_animation(value) {
302 return Err(EffectProblem::InvalidParam(name.clone()));
303 }
304 }
305 let declared = |names: &[String], used: &mut dyn Iterator<Item = &String>| {
306 let used = used.collect::<Vec<_>>();
307 used.len() == names.len() && used.iter().all(|name| names.contains(name))
308 };
309 if !declared(
310 &spec.inputs,
311 &mut inputs.into_iter().flat_map(BTreeMap::keys),
312 ) {
313 return Err(EffectProblem::Inputs);
314 }
315 if !declared(&spec.resources, &mut effect.resources.keys()) {
316 return Err(EffectProblem::Resources);
317 }
318 Ok(())
319}
320
321#[derive(Deserialize)]
322struct CatalogWire {
323 effects: Vec<SpecWire>,
324 transitions: Vec<SpecWire>,
325 generators: Vec<SpecWire>,
326}
327
328#[derive(Deserialize)]
329struct SpecWire {
330 id: String,
331 version: u32,
332 kind: EffectKind,
333 label: String,
334 group: String,
335 inputs: Vec<NamedWire>,
336 params: Vec<ParamWire>,
337 resources: Vec<NamedWire>,
338 #[serde(default)]
339 coverage_commutes: bool,
340}
341
342#[derive(Deserialize)]
343struct NamedWire {
344 name: String,
345}
346
347#[derive(Deserialize)]
348#[serde(rename_all = "camelCase")]
349struct ParamWire {
350 name: String,
351 label: String,
352 #[serde(rename = "type")]
353 param_type: EffectParamType,
354 default: serde_json::Value,
355 min: Option<f32>,
356 max: Option<f32>,
357 step: Option<f32>,
358 unit: EffectParamUnit,
359 enum_values: Vec<String>,
360}
361
362impl From<SpecWire> for EffectSpec {
363 fn from(wire: SpecWire) -> Self {
364 Self {
365 id: wire.id,
366 version: wire.version,
367 kind: wire.kind,
368 label: wire.label,
369 group: wire.group,
370 inputs: wire.inputs.into_iter().map(|input| input.name).collect(),
371 params: wire.params.into_iter().map(EffectParamSpec::from).collect(),
372 resources: wire
373 .resources
374 .into_iter()
375 .map(|resource| resource.name)
376 .collect(),
377 coverage_commutes: wire.coverage_commutes,
378 }
379 }
380}
381
382impl From<ParamWire> for EffectParamSpec {
383 fn from(wire: ParamWire) -> Self {
384 let default = default_value(wire.param_type, &wire.default)
385 .unwrap_or_else(|| panic!("parameter {} has a default of its type", wire.name));
386 Self {
387 name: wire.name,
388 label: wire.label,
389 param_type: wire.param_type,
390 default,
391 min: wire.min,
392 max: wire.max,
393 step: wire.step,
394 unit: wire.unit,
395 enum_values: wire.enum_values,
396 }
397 }
398}
399
400#[allow(clippy::cast_possible_truncation)]
401fn default_value(param_type: EffectParamType, value: &serde_json::Value) -> Option<EffectValue> {
402 let numbers = |count: usize| {
404 let values = value.as_array()?;
405 (values.len() == count)
406 .then(|| {
407 values
408 .iter()
409 .map(|value| value.as_f64().map(|value| value as f32))
410 })?
411 .collect::<Option<Vec<f32>>>()
412 };
413 Some(match param_type {
414 EffectParamType::Float => EffectValue::Float(value.as_f64()? as f32),
415 EffectParamType::Vec2 => EffectValue::Vec2(numbers(2)?.try_into().ok()?),
416 EffectParamType::Vec4 => EffectValue::Vec4(numbers(4)?.try_into().ok()?),
417 EffectParamType::Color => EffectValue::Color(numbers(4)?.try_into().ok()?),
418 EffectParamType::Enum => EffectValue::Enum(u32::try_from(value.as_u64()?).ok()?),
419 EffectParamType::Bool => EffectValue::Bool(value.as_bool()?),
420 })
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426
427 #[test]
428 fn every_builtin_parses_with_defaults_it_accepts() {
429 let specs = builtin_effects();
430 assert!(specs.iter().any(|spec| spec.kind == EffectKind::Effect));
431 assert!(specs.iter().any(|spec| spec.kind == EffectKind::Transition));
432 for spec in specs {
433 assert!(spec.id.starts_with(BUILTIN_EFFECT_PREFIX), "{}", spec.id);
434 assert_eq!(builtin_effect(&spec.id), Some(spec));
435 for param in &spec.params {
436 assert!(param.accepts(¶m.default), "{} {}", spec.id, param.name);
437 }
438 }
439 }
440}