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}
26
27#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
29#[serde(rename_all = "snake_case")]
30pub enum EffectParamType {
31 Float,
33 Vec2,
35 Vec4,
37 Color,
39 Enum,
41 Bool,
43}
44
45#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq)]
47#[serde(rename_all = "snake_case")]
48pub enum EffectParamUnit {
49 Normalized,
51 Degrees,
53 Color,
55 Enum,
57 Bool,
59}
60
61#[derive(Clone, Debug, PartialEq)]
63#[non_exhaustive]
64pub struct EffectParamSpec {
65 pub name: String,
67 pub label: String,
69 pub param_type: EffectParamType,
71 pub default: EffectValue,
73 pub min: Option<f32>,
75 pub max: Option<f32>,
77 pub step: Option<f32>,
79 pub unit: EffectParamUnit,
81 pub enum_values: Vec<String>,
83}
84
85impl EffectParamSpec {
86 #[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 #[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 #[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 #[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#[derive(Clone, Debug, PartialEq)]
154#[non_exhaustive]
155pub struct EffectSpec {
156 pub id: String,
158 pub version: u32,
160 pub kind: EffectKind,
162 pub label: String,
164 pub group: String,
166 pub inputs: Vec<String>,
168 pub params: Vec<EffectParamSpec>,
170 pub resources: Vec<String>,
172 pub coverage_commutes: bool,
175}
176
177impl EffectSpec {
178 #[must_use]
180 pub fn param(&self, name: &str) -> Option<&EffectParamSpec> {
181 self.params.iter().find(|param| param.name == name)
182 }
183}
184
185#[must_use]
187pub fn builtin_effects() -> &'static [EffectSpec] {
188 &catalog().0
189}
190
191#[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#[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#[derive(Clone, Debug, Eq, PartialEq)]
226#[non_exhaustive]
227pub enum EffectProblem {
228 UnknownBuiltin,
230 Version {
232 expected: u32,
234 },
235 Kind,
237 UnknownParam(String),
239 InvalidParam(String),
241 Inputs,
243 Resources,
245}
246
247pub fn check_builtin_effect(effect: &ClipEffect, kind: EffectKind) -> Result<(), EffectProblem> {
254 check_builtin(effect, kind, None)
255}
256
257pub(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 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(¶m.default), "{} {}", spec.id, param.name);
415 }
416 }
417 }
418}