Skip to main content

alpha2_render/
graph.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::sync::atomic::{AtomicU32, Ordering};
4
5use crate::graph_cache::{
6    composite_cache_key, effect_cache_key_with_resources, named_inputs_key, sum_cache_key,
7    transient_source_key, vector_cache_key,
8};
9use crate::{
10    BlendMode, Color, EffectId, EffectParams, EffectResources, EffectRuntime, LayerTransform,
11    RenderError, RenderSize, SourceView,
12};
13
14/// Stable handle to a node within one render graph.
15#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
16pub struct RenderNodeId {
17    pub(crate) graph: u32,
18    pub(crate) index: usize,
19}
20
21impl RenderNodeId {
22    /// Returns the node's insertion-order index.
23    #[must_use]
24    pub const fn index(self) -> usize {
25        self.index
26    }
27}
28
29/// Public category of a render graph node.
30#[derive(Copy, Clone, Debug, Eq, PartialEq)]
31pub enum RenderNodeKind {
32    /// Externally owned input texture.
33    Source,
34    /// Registered effect with one source and any declared named inputs.
35    Effect,
36    /// Registered two-input transition.
37    Transition,
38    /// Registered zero-input generator.
39    Generator,
40    /// Ordered layer composition.
41    Composite,
42    /// One source added up over several placements.
43    Sum,
44    /// A vector scene: fills drawn from tile coverage.
45    Vector,
46}
47
48/// Named images an effect node samples besides its source, sorted by name, one node per name.
49#[derive(Clone, Debug, Default, Eq, PartialEq)]
50pub struct EffectInputs<'a> {
51    values: Vec<(Cow<'a, str>, RenderNodeId)>,
52}
53
54impl<'a> EffectInputs<'a> {
55    /// Creates an empty set, without allocating.
56    #[must_use]
57    pub const fn new() -> Self {
58        Self { values: Vec::new() }
59    }
60
61    /// Adds or replaces one named input.
62    #[must_use]
63    pub fn with(mut self, name: impl Into<Cow<'a, str>>, node: RenderNodeId) -> Self {
64        self.insert(name, node);
65        self
66    }
67
68    /// Adds or replaces one named input in place.
69    pub fn insert(&mut self, name: impl Into<Cow<'a, str>>, node: RenderNodeId) {
70        let name = name.into();
71        match self
72            .values
73            .binary_search_by(|(held, _)| held.as_ref().cmp(name.as_ref()))
74        {
75            Ok(index) => self.values[index].1 = node,
76            Err(index) => self.values.insert(index, (name, node)),
77        }
78    }
79
80    /// Whether no input is named.
81    #[must_use]
82    pub fn is_empty(&self) -> bool {
83        self.values.is_empty()
84    }
85
86    /// The number of named inputs.
87    #[must_use]
88    pub fn len(&self) -> usize {
89        self.values.len()
90    }
91
92    /// Every input by name, in name order.
93    pub(crate) fn iter(&self) -> impl Iterator<Item = (&str, RenderNodeId)> {
94        self.values
95            .iter()
96            .map(|(name, node)| (name.as_ref(), *node))
97    }
98}
99
100/// One owned layer reference in a graph composition node.
101#[derive(Copy, Clone, Debug)]
102pub struct GraphLayer {
103    /// Node whose result is sampled as this layer.
104    pub source: RenderNodeId,
105    /// Layer transform and opacity.
106    pub visual: LayerTransform,
107    /// Artistic blend operation.
108    pub blend_mode: BlendMode,
109}
110
111/// An insertion-ordered, acyclic render program.
112#[derive(Debug)]
113pub struct RenderGraph<'a> {
114    pub(crate) id: u32,
115    pub(crate) size: RenderSize,
116    pub(crate) nodes: Vec<RenderNode<'a>>,
117    pub(crate) cache_keys: Vec<RenderCacheKey>,
118    /// Whether each node's key is complete (no unkeyed source beneath it).
119    pub(crate) stable: Vec<bool>,
120    /// Each node's cache intent; `None` when not a candidate.
121    pub(crate) intents: Vec<Option<crate::CacheIntent>>,
122    pub(crate) output: Option<RenderNodeId>,
123    /// Blend space for this graph's composites; `None` uses the renderer's.
124    pub(crate) blend_space: Option<crate::BlendSpace>,
125}
126
127static NEXT_GRAPH_ID: AtomicU32 = AtomicU32::new(1);
128
129#[derive(Debug)]
130pub(crate) enum RenderNode<'a> {
131    Source(SourceView<'a>),
132    Effect {
133        effect: EffectId,
134        source: RenderNodeId,
135        inputs: EffectInputs<'a>,
136        params: EffectParams<'a>,
137        resources: EffectResources,
138        runtime: EffectRuntime,
139    },
140    Transition {
141        effect: EffectId,
142        from: RenderNodeId,
143        to: RenderNodeId,
144        params: EffectParams<'a>,
145        resources: EffectResources,
146        runtime: EffectRuntime,
147    },
148    Generator {
149        effect: EffectId,
150        params: EffectParams<'a>,
151        resources: EffectResources,
152        runtime: EffectRuntime,
153    },
154    Composite {
155        layers: Vec<GraphLayer>,
156        background: Option<Color>,
157    },
158    Sum {
159        source: RenderNodeId,
160        placements: Vec<LayerTransform>,
161    },
162    Vector {
163        scene: std::sync::Arc<alpha2_geometry::VectorScene>,
164    },
165}
166
167/// Deterministic 128-bit key for a source or rendered graph result.
168#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
169pub struct RenderCacheKey(pub(crate) u128);
170
171impl RenderCacheKey {
172    /// Creates a stable source key supplied by a decode or asset cache.
173    #[must_use]
174    pub const fn source(value: u64) -> Self {
175        Self(value as u128)
176    }
177
178    /// Creates a key from all 128 bits. Keys not derived from a decoded source set high bits, so
179    /// they never equal a [`Self::source`] key.
180    #[must_use]
181    pub const fn from_value(value: u128) -> Self {
182        Self(value)
183    }
184
185    /// Returns the stable 128-bit representation.
186    #[must_use]
187    pub const fn value(self) -> u128 {
188        self.0
189    }
190}
191
192/// Structural or execution failure in a render graph.
193#[derive(Copy, Clone, Debug, Eq, PartialEq)]
194#[non_exhaustive]
195pub enum GraphError {
196    /// A node references an ID not already present in the graph.
197    InvalidDependency,
198    /// No final output node was selected.
199    MissingOutput,
200    /// An external source cannot be returned as an owned render result.
201    SourceOutput,
202    /// A registered shader kind does not match its graph node.
203    EffectKindMismatch,
204    /// A sum has more than [`crate::MAX_SUM_PLACEMENTS`] placements.
205    TooManyPlacements,
206    /// A rendering operation failed.
207    Render(RenderError),
208}
209
210impl fmt::Display for GraphError {
211    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
212        match self {
213            Self::InvalidDependency => {
214                formatter.write_str("render graph dependency must name an earlier node")
215            }
216            Self::MissingOutput => formatter.write_str("render graph has no selected output"),
217            Self::SourceOutput => {
218                formatter.write_str("render graph output must be a rendered node")
219            }
220            Self::EffectKindMismatch => {
221                formatter.write_str("registered effect kind does not match its graph node")
222            }
223            Self::TooManyPlacements => {
224                formatter.write_str("render graph sum has too many placements")
225            }
226            Self::Render(error) => write!(formatter, "render graph execution failed: {error}"),
227        }
228    }
229}
230
231impl std::error::Error for GraphError {
232    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
233        match self {
234            Self::Render(error) => Some(error),
235            _ => None,
236        }
237    }
238}
239
240impl From<RenderError> for GraphError {
241    fn from(error: RenderError) -> Self {
242        Self::Render(error)
243    }
244}
245
246impl GraphError {
247    /// Converts to [`RenderError`], reporting structural faults as [`RenderError::InvalidGraph`].
248    #[must_use]
249    pub const fn into_render_error(self) -> RenderError {
250        match self {
251            Self::Render(error) => error,
252            Self::InvalidDependency
253            | Self::MissingOutput
254            | Self::SourceOutput
255            | Self::EffectKindMismatch
256            | Self::TooManyPlacements => RenderError::InvalidGraph,
257        }
258    }
259}
260
261impl<'a> RenderGraph<'a> {
262    /// Creates an empty graph whose rendered nodes share one output size.
263    #[must_use]
264    pub fn new(size: RenderSize) -> Self {
265        Self {
266            id: NEXT_GRAPH_ID.fetch_add(1, Ordering::Relaxed),
267            size,
268            nodes: Vec::new(),
269            cache_keys: Vec::new(),
270            stable: Vec::new(),
271            intents: Vec::new(),
272            output: None,
273            blend_space: None,
274        }
275    }
276
277    /// The size every rendered node of this graph has.
278    #[must_use]
279    pub const fn size(&self) -> RenderSize {
280        self.size
281    }
282
283    /// Blends this graph's composites in `space` instead of the renderer default, so preview and
284    /// export match.
285    pub fn set_blend_space(&mut self, space: crate::BlendSpace) {
286        self.blend_space = Some(space);
287    }
288
289    /// Adds an externally owned source texture.
290    pub fn add_source(&mut self, texture: SourceView<'a>) -> RenderNodeId {
291        let key = transient_source_key(self.id, self.nodes.len());
292        self.push(RenderNode::Source(texture), key, false)
293    }
294
295    /// Adds an external texture with a stable cache key.
296    ///
297    /// The key must cover everything the pixels depend on (content, frame, decode and conversion);
298    /// results drawn from it can then be cached.
299    pub fn add_source_with_key(
300        &mut self,
301        texture: SourceView<'a>,
302        key: RenderCacheKey,
303    ) -> RenderNodeId {
304        self.push(RenderNode::Source(texture), key, true)
305    }
306
307    /// Adds a registered one-input effect node.
308    ///
309    /// # Errors
310    /// Returns [`GraphError::InvalidDependency`] unless `source` is earlier.
311    pub fn add_effect(
312        &mut self,
313        effect: EffectId,
314        source: RenderNodeId,
315        params: EffectParams<'a>,
316        runtime: EffectRuntime,
317    ) -> Result<RenderNodeId, GraphError> {
318        self.add_effect_with_resources(effect, source, params, EffectResources::new(), runtime)
319    }
320
321    /// Adds a registered one-input effect node with external resources.
322    ///
323    /// Built-in Gaussian blur and glow expand into internal passes; the last is returned.
324    ///
325    /// # Errors
326    /// [`GraphError::InvalidDependency`] unless `source` is earlier; for an expanded built-in, also
327    /// [`RenderError::InvalidEffectParams`] for unknown or out-of-range parameters.
328    pub fn add_effect_with_resources(
329        &mut self,
330        effect: EffectId,
331        source: RenderNodeId,
332        params: EffectParams<'a>,
333        resources: EffectResources,
334        runtime: EffectRuntime,
335    ) -> Result<RenderNodeId, GraphError> {
336        self.add_effect_with_inputs(
337            effect,
338            source,
339            EffectInputs::new(),
340            params,
341            resources,
342            runtime,
343        )
344    }
345
346    /// Adds a registered effect node that also samples `inputs` by their declared names.
347    ///
348    /// # Errors
349    /// [`GraphError::InvalidDependency`] unless `source` and every input are earlier,
350    /// [`RenderError::InvalidEffectParams`] for named inputs on an expanded built-in, and otherwise
351    /// the errors of [`Self::add_effect_with_resources`].
352    pub fn add_effect_with_inputs(
353        &mut self,
354        effect: EffectId,
355        source: RenderNodeId,
356        inputs: EffectInputs<'a>,
357        params: EffectParams<'a>,
358        resources: EffectResources,
359        runtime: EffectRuntime,
360    ) -> Result<RenderNodeId, GraphError> {
361        self.validate_dependency(source)?;
362        for (_, input) in inputs.iter() {
363            self.validate_dependency(input)?;
364        }
365        // Expanded built-ins take no resources or inputs; check before expanding so no node is
366        // left.
367        if !inputs.is_empty() && crate::gaussian_blur::expanded_passes(effect.as_str()).is_some() {
368            return Err(RenderError::InvalidEffectParams.into());
369        }
370        if let Some(expanded) = self.add_expanded_effect(&effect, source, &params, runtime) {
371            if resources.iter().next().is_some() {
372                return Err(RenderError::InvalidEffectParams.into());
373            }
374            return expanded;
375        }
376        let source_key = self.cache_keys[source.index];
377        let input_keys: &[RenderCacheKey] = if inputs.is_empty() {
378            &[source_key]
379        } else {
380            &[source_key, named_inputs_key(&inputs, &self.cache_keys)]
381        };
382        let key = effect_cache_key_with_resources(
383            b"effect", self.size, &effect, input_keys, &params, &resources, runtime,
384        );
385        let stable =
386            self.stable[source.index] && inputs.iter().all(|(_, input)| self.stable[input.index]);
387        Ok(self.push(
388            RenderNode::Effect {
389                effect,
390                source,
391                inputs,
392                params,
393                resources,
394                runtime,
395            },
396            key,
397            stable,
398        ))
399    }
400
401    /// Adds a registered generator node drawn from its parameters at the graph's size.
402    pub fn add_generator(
403        &mut self,
404        effect: EffectId,
405        params: EffectParams<'a>,
406        runtime: EffectRuntime,
407    ) -> RenderNodeId {
408        self.add_generator_with_resources(effect, params, EffectResources::new(), runtime)
409    }
410
411    /// Adds a registered generator node that samples external resources by declared name.
412    pub fn add_generator_with_resources(
413        &mut self,
414        effect: EffectId,
415        params: EffectParams<'a>,
416        resources: EffectResources,
417        runtime: EffectRuntime,
418    ) -> RenderNodeId {
419        let key = effect_cache_key_with_resources(
420            b"generator",
421            self.size,
422            &effect,
423            &[],
424            &params,
425            &resources,
426            runtime,
427        );
428        self.push(
429            RenderNode::Generator {
430                effect,
431                params,
432                resources,
433                runtime,
434            },
435            key,
436            true,
437        )
438    }
439
440    /// Adds a vector scene drawn from tile coverage over transparency
441    /// (see [`alpha2_geometry::VectorScene`]).
442    ///
443    /// Keyed by the scene, so an unchanged scene is a cache hit. Scene coordinates are this graph's
444    /// pixels.
445    pub fn add_vector(
446        &mut self,
447        scene: std::sync::Arc<alpha2_geometry::VectorScene>,
448    ) -> RenderNodeId {
449        let key = vector_cache_key(self.size, scene.key);
450        self.push(RenderNode::Vector { scene }, key, true)
451    }
452
453    /// Adds a registered two-input transition node.
454    ///
455    /// # Errors
456    /// Returns [`GraphError::InvalidDependency`] unless both inputs are earlier.
457    pub fn add_transition(
458        &mut self,
459        effect: EffectId,
460        from: RenderNodeId,
461        to: RenderNodeId,
462        params: EffectParams<'a>,
463        runtime: EffectRuntime,
464    ) -> Result<RenderNodeId, GraphError> {
465        self.add_transition_with_resources(
466            effect,
467            from,
468            to,
469            params,
470            EffectResources::new(),
471            runtime,
472        )
473    }
474
475    /// Adds a registered two-input transition node with external resources.
476    ///
477    /// # Errors
478    /// Returns [`GraphError::InvalidDependency`] unless both inputs are earlier.
479    pub fn add_transition_with_resources(
480        &mut self,
481        effect: EffectId,
482        from: RenderNodeId,
483        to: RenderNodeId,
484        params: EffectParams<'a>,
485        resources: EffectResources,
486        runtime: EffectRuntime,
487    ) -> Result<RenderNodeId, GraphError> {
488        self.validate_dependency(from)?;
489        self.validate_dependency(to)?;
490        let key = effect_cache_key_with_resources(
491            b"transition",
492            self.size,
493            &effect,
494            &[self.cache_keys[from.index], self.cache_keys[to.index]],
495            &params,
496            &resources,
497            runtime,
498        );
499        let stable = self.stable[from.index] && self.stable[to.index];
500        Ok(self.push(
501            RenderNode::Transition {
502                effect,
503                from,
504                to,
505                params,
506                resources,
507                runtime,
508            },
509            key,
510            stable,
511        ))
512    }
513
514    /// Adds an ordered layer-composition node over a transparent target.
515    ///
516    /// # Errors
517    /// Returns [`GraphError::InvalidDependency`] for a missing layer source.
518    pub fn add_composite(&mut self, layers: Vec<GraphLayer>) -> Result<RenderNodeId, GraphError> {
519        self.push_composite(layers, None)
520    }
521
522    /// Adds an ordered layer-composition node over a solid background.
523    ///
524    /// `background` acts as the bottom layer and is a premultiplied sRGB storage value, like
525    /// [`crate::Renderer::render_solid`]'s color.
526    ///
527    /// # Errors
528    /// [`GraphError::InvalidDependency`] for a missing layer source, or
529    /// [`RenderError::InvalidColor`] for an out-of-range or non-premultiplied background.
530    pub fn add_composite_over(
531        &mut self,
532        layers: Vec<GraphLayer>,
533        background: Color,
534    ) -> Result<RenderNodeId, GraphError> {
535        if !background.is_valid() {
536            return Err(GraphError::Render(RenderError::InvalidColor));
537        }
538        self.push_composite(layers, Some(background))
539    }
540
541    fn push_composite(
542        &mut self,
543        layers: Vec<GraphLayer>,
544        background: Option<Color>,
545    ) -> Result<RenderNodeId, GraphError> {
546        for layer in &layers {
547            self.validate_dependency(layer.source)?;
548        }
549        let key = composite_cache_key(self.size, &layers, background, &self.cache_keys);
550        let stable = layers.iter().all(|layer| self.stable[layer.source.index]);
551        Ok(self.push(RenderNode::Composite { layers, background }, key, stable))
552    }
553
554    /// Adds `source` summed over `placements`, each at its opacity, over a transparent target.
555    ///
556    /// Premultiplied color and alpha are added in the graph's blend space and clamped to 1, as
557    /// [`BlendMode::PlusLighter`] adds them, and the total is stored once. Placements with zero
558    /// opacity or zero scale add nothing; without placements the result is transparent.
559    ///
560    /// # Errors
561    /// [`GraphError::InvalidDependency`] unless `source` is earlier, or
562    /// [`GraphError::TooManyPlacements`] for more than [`crate::MAX_SUM_PLACEMENTS`].
563    pub fn add_sum(
564        &mut self,
565        source: RenderNodeId,
566        placements: Vec<LayerTransform>,
567    ) -> Result<RenderNodeId, GraphError> {
568        self.validate_dependency(source)?;
569        if placements.len() > crate::MAX_SUM_PLACEMENTS {
570            return Err(GraphError::TooManyPlacements);
571        }
572        let key = sum_cache_key(self.size, self.cache_keys[source.index], &placements);
573        let stable = self.stable[source.index];
574        Ok(self.push(RenderNode::Sum { source, placements }, key, stable))
575    }
576
577    /// Selects the graph result.
578    ///
579    /// # Errors
580    /// Returns [`GraphError::InvalidDependency`] for an unknown node.
581    pub fn set_output(&mut self, output: RenderNodeId) -> Result<(), GraphError> {
582        self.validate_dependency(output)?;
583        self.output = Some(output);
584        Ok(())
585    }
586
587    /// The selected graph result, if one was selected.
588    #[must_use]
589    pub const fn output(&self) -> Option<RenderNodeId> {
590        self.output
591    }
592
593    /// Returns the number of nodes in insertion order.
594    #[must_use]
595    pub fn node_count(&self) -> usize {
596        self.nodes.len()
597    }
598
599    /// Returns the public category of a node.
600    #[must_use]
601    pub fn node_kind(&self, id: RenderNodeId) -> Option<RenderNodeKind> {
602        if id.graph == self.id {
603            self.nodes.get(id.index).map(RenderNode::kind)
604        } else {
605            None
606        }
607    }
608
609    /// Makes `node` a cache candidate under `intent`, used when its key is complete.
610    /// [`crate::CacheIntent::Bypass`] excludes the node, its inputs and its dependents.
611    ///
612    /// # Errors
613    /// Returns [`GraphError::InvalidDependency`] for an unknown node.
614    pub fn set_cache_intent(
615        &mut self,
616        node: RenderNodeId,
617        intent: crate::CacheIntent,
618    ) -> Result<(), GraphError> {
619        self.validate_dependency(node)?;
620        self.intents[node.index] = Some(intent);
621        Ok(())
622    }
623
624    /// Whether `node`'s result can be cached, and if not, why.
625    ///
626    /// # Errors
627    /// Returns [`GraphError::InvalidDependency`] for an unknown node.
628    pub fn cache_eligibility(
629        &self,
630        node: RenderNodeId,
631    ) -> Result<crate::CacheEligibility, GraphError> {
632        self.validate_dependency(node)?;
633        Ok(self.eligibility()[node.index])
634    }
635
636    /// Every node's eligibility. A bypass spreads down to inputs and up to dependents; a transient
637    /// source only up.
638    pub(crate) fn eligibility(&self) -> Vec<crate::CacheEligibility> {
639        let count = self.nodes.len();
640        let mut bypassed: Vec<bool> = self
641            .intents
642            .iter()
643            .map(|intent| *intent == Some(crate::CacheIntent::Bypass))
644            .collect();
645        // Up: nodes are in dependency order, so inputs come first.
646        for index in 0..count {
647            if self.nodes[index]
648                .dependencies()
649                .any(|input| bypassed[input.index])
650            {
651                bypassed[index] = true;
652            }
653        }
654        // Down: from each explicitly bypassed node to its inputs.
655        let mut down: Vec<bool> = self
656            .intents
657            .iter()
658            .map(|intent| *intent == Some(crate::CacheIntent::Bypass))
659            .collect();
660        for index in (0..count).rev() {
661            if down[index] {
662                for input in self.nodes[index].dependencies() {
663                    down[input.index] = true;
664                }
665            }
666        }
667        (0..count)
668            .map(|index| {
669                if bypassed[index] || down[index] {
670                    crate::CacheEligibility::Bypassed
671                } else if self.stable[index] {
672                    crate::CacheEligibility::Eligible
673                } else {
674                    crate::CacheEligibility::TransientSource
675                }
676            })
677            .collect()
678    }
679
680    fn push(
681        &mut self,
682        node: RenderNode<'a>,
683        cache_key: RenderCacheKey,
684        stable: bool,
685    ) -> RenderNodeId {
686        let id = RenderNodeId {
687            graph: self.id,
688            index: self.nodes.len(),
689        };
690        self.nodes.push(node);
691        self.cache_keys.push(cache_key);
692        self.stable.push(stable);
693        self.intents.push(None);
694        id
695    }
696
697    fn validate_dependency(&self, dependency: RenderNodeId) -> Result<(), GraphError> {
698        if dependency.graph == self.id && dependency.index < self.nodes.len() {
699            Ok(())
700        } else {
701            Err(GraphError::InvalidDependency)
702        }
703    }
704}
705
706impl RenderNodeKind {
707    /// Label for pass timing ([`crate::PassTiming::label`]).
708    pub(crate) const fn pass_label(self) -> &'static str {
709        match self {
710            Self::Source => "source",
711            Self::Effect => "effect",
712            Self::Transition => "transition",
713            Self::Generator => "generator",
714            Self::Composite => "composite",
715            Self::Sum => "sum",
716            Self::Vector => "vector",
717        }
718    }
719}
720
721impl RenderNode<'_> {
722    pub(crate) const fn kind(&self) -> RenderNodeKind {
723        match self {
724            Self::Source(_) => RenderNodeKind::Source,
725            Self::Effect { .. } => RenderNodeKind::Effect,
726            Self::Transition { .. } => RenderNodeKind::Transition,
727            Self::Generator { .. } => RenderNodeKind::Generator,
728            Self::Composite { .. } => RenderNodeKind::Composite,
729            Self::Sum { .. } => RenderNodeKind::Sum,
730            Self::Vector { .. } => RenderNodeKind::Vector,
731        }
732    }
733
734    pub(crate) fn dependencies(&self) -> impl Iterator<Item = RenderNodeId> + '_ {
735        let (leading, inputs, layers): (_, &[(Cow<'_, str>, RenderNodeId)], &[GraphLayer]) =
736            match self {
737                Self::Source(_) | Self::Generator { .. } | Self::Vector { .. } => {
738                    ([None, None], &[], &[])
739                }
740                Self::Effect { source, inputs, .. } => {
741                    ([Some(*source), None], inputs.values.as_slice(), &[])
742                }
743                Self::Transition { from, to, .. } => ([Some(*from), Some(*to)], &[], &[]),
744                Self::Sum { source, .. } => ([Some(*source), None], &[], &[]),
745                Self::Composite { layers, .. } => ([None, None], &[], layers.as_slice()),
746            };
747        leading
748            .into_iter()
749            .flatten()
750            .chain(inputs.iter().map(|(_, input)| *input))
751            .chain(layers.iter().map(|layer| layer.source))
752    }
753}
754
755#[cfg(test)]
756mod tests {
757    use super::*;
758
759    #[test]
760    fn every_node_and_setting_refuses_a_node_of_another_graph_or_one_not_yet_added() {
761        // Node ids carry their graph; every method must refuse another graph's node with the same
762        // index.
763        let size = RenderSize::new(16, 9).expect("non-zero size");
764        let effect = EffectId::new("test.effect".into(), 1);
765        let mut other = RenderGraph::new(size);
766        let foreign = other.add_generator(
767            effect.clone(),
768            EffectParams::new(),
769            EffectRuntime::default(),
770        );
771        let mut graph = RenderGraph::new(size);
772        let own = graph.add_generator(
773            effect.clone(),
774            EffectParams::new(),
775            EffectRuntime::default(),
776        );
777        // The same index as a node of this graph, but another graph's.
778        assert_eq!(foreign.index, own.index);
779        let unknown = RenderNodeId {
780            graph: graph.id,
781            index: 1,
782        };
783        let layer = |source| GraphLayer {
784            source,
785            visual: crate::LayerTransform {
786                position: [0.5, 0.5],
787                anchor: [0.5, 0.5],
788                scale: [1.0, 1.0],
789                rotation_degrees: 0.0,
790                opacity: 1.0,
791            },
792            blend_mode: crate::BlendMode::Normal,
793        };
794        for bad in [foreign, unknown] {
795            let invalid = Err(GraphError::InvalidDependency);
796            assert_eq!(
797                graph.add_effect(
798                    effect.clone(),
799                    bad,
800                    EffectParams::new(),
801                    EffectRuntime::default()
802                ),
803                invalid
804            );
805            assert_eq!(
806                graph.add_transition(
807                    effect.clone(),
808                    own,
809                    bad,
810                    EffectParams::new(),
811                    EffectRuntime::default()
812                ),
813                invalid
814            );
815            assert_eq!(
816                graph.add_transition(
817                    effect.clone(),
818                    bad,
819                    own,
820                    EffectParams::new(),
821                    EffectRuntime::default()
822                ),
823                invalid
824            );
825            assert_eq!(graph.add_composite(vec![layer(own), layer(bad)]), invalid);
826            assert_eq!(graph.add_sum(bad, vec![layer(own).visual]), invalid);
827            assert_eq!(
828                graph.add_composite_over(vec![layer(bad)], Color::BLACK),
829                invalid
830            );
831            assert_eq!(graph.set_output(bad), Err(GraphError::InvalidDependency));
832            assert_eq!(
833                graph.set_cache_intent(bad, crate::CacheIntent::Pin),
834                Err(GraphError::InvalidDependency)
835            );
836            assert_eq!(
837                graph.cache_eligibility(bad),
838                Err(GraphError::InvalidDependency)
839            );
840            assert_eq!(graph.node_kind(bad), None);
841        }
842        assert_eq!(graph.node_count(), 1);
843        assert_eq!(graph.node_kind(own), Some(RenderNodeKind::Generator));
844        // An out-of-range background is refused before its layers are looked at.
845        assert_eq!(
846            graph.add_composite_over(vec![layer(foreign)], Color::rgba(1.5, 0.0, 0.0, 1.0)),
847            Err(GraphError::Render(RenderError::InvalidColor))
848        );
849        assert_eq!(graph.node_count(), 1);
850    }
851
852    fn generator(graph: &mut RenderGraph<'_>, id: &'static str) -> RenderNodeId {
853        graph.add_generator(
854            EffectId::from_static(id, 1),
855            EffectParams::new(),
856            EffectRuntime::default(),
857        )
858    }
859
860    fn effect_with_inputs(
861        graph: &mut RenderGraph<'static>,
862        source: RenderNodeId,
863        inputs: EffectInputs<'static>,
864    ) -> Result<RenderNodeId, GraphError> {
865        graph.add_effect_with_inputs(
866            EffectId::from_static("test.multi-input", 1),
867            source,
868            inputs,
869            EffectParams::new(),
870            EffectResources::new(),
871            EffectRuntime::default(),
872        )
873    }
874
875    #[test]
876    fn named_inputs_are_dependencies() {
877        // A node read only as a named input is drawn before the effect.
878        let size = RenderSize::new(16, 9).expect("non-zero size");
879        let mut graph = RenderGraph::new(size);
880        let source = generator(&mut graph, "test.source");
881        let map = generator(&mut graph, "test.map");
882        let unused = generator(&mut graph, "test.unused");
883        let effect = effect_with_inputs(&mut graph, source, EffectInputs::new().with("map", map))
884            .expect("earlier nodes");
885        graph.set_output(effect).expect("known output");
886        let plan = graph.compile().expect("compiles");
887        assert_eq!(plan.execution_order(), [source, map, effect]);
888        assert_eq!(plan.last_use(map), Some(2));
889        assert_eq!(plan.last_use(unused), None);
890        let later = RenderNodeId {
891            graph: graph.id,
892            index: graph.node_count(),
893        };
894        assert_eq!(
895            effect_with_inputs(&mut graph, source, EffectInputs::new().with("map", later)),
896            Err(GraphError::InvalidDependency)
897        );
898    }
899
900    #[test]
901    fn named_inputs_on_a_built_in_drawn_as_passes_are_refused() {
902        let size = RenderSize::new(16, 9).expect("non-zero size");
903        let mut graph = RenderGraph::new(size);
904        let source = generator(&mut graph, "test.source");
905        let map = generator(&mut graph, "test.map");
906        let count = graph.node_count();
907        for id in [crate::builtins::GAUSSIAN_BLUR_ID, crate::builtins::GLOW_ID] {
908            assert_eq!(
909                graph.add_effect_with_inputs(
910                    EffectId::from_static(id, 1),
911                    source,
912                    EffectInputs::new().with("map", map),
913                    EffectParams::new(),
914                    EffectResources::new(),
915                    EffectRuntime::default(),
916                ),
917                Err(GraphError::Render(RenderError::InvalidEffectParams)),
918                "{id}"
919            );
920        }
921        assert_eq!(graph.node_count(), count, "no pass is left behind");
922    }
923
924    #[test]
925    fn a_named_input_is_part_of_the_cache_key() {
926        let size = RenderSize::new(16, 9).expect("non-zero size");
927        let key = |build: &dyn Fn(&mut RenderGraph<'static>, [RenderNodeId; 3]) -> RenderNodeId| {
928            let mut graph = RenderGraph::new(size);
929            let nodes = [
930                generator(&mut graph, "test.source"),
931                generator(&mut graph, "test.map"),
932                generator(&mut graph, "test.other-map"),
933            ];
934            let node = build(&mut graph, nodes);
935            graph.cache_keys[node.index]
936        };
937        let named = |name: &'static str, input: usize| {
938            key(&move |graph, nodes| {
939                effect_with_inputs(
940                    graph,
941                    nodes[0],
942                    EffectInputs::new().with(name, nodes[input]),
943                )
944                .expect("earlier nodes")
945            })
946        };
947        assert_eq!(named("map", 1), named("map", 1));
948        assert_ne!(named("map", 1), named("map", 2));
949        assert_ne!(named("map", 1), named("mask", 1));
950        let none = key(&|graph, nodes| {
951            effect_with_inputs(graph, nodes[0], EffectInputs::new()).expect("earlier node")
952        });
953        assert_ne!(named("map", 1), none);
954        let plain = key(&|graph, nodes| {
955            graph
956                .add_effect_with_resources(
957                    EffectId::from_static("test.multi-input", 1),
958                    nodes[0],
959                    EffectParams::new(),
960                    EffectResources::new(),
961                    EffectRuntime::default(),
962                )
963                .expect("earlier node")
964        });
965        assert_eq!(none, plain);
966    }
967
968    fn placement(shift: f32) -> crate::LayerTransform {
969        crate::LayerTransform {
970            position: [0.5 + shift, 0.5],
971            anchor: [0.5, 0.5],
972            scale: [1.0, 1.0],
973            rotation_degrees: 0.0,
974            opacity: 0.25,
975        }
976    }
977
978    #[test]
979    fn a_sum_depends_on_its_source_and_takes_at_most_the_placements_one_pass_holds() {
980        let size = RenderSize::new(16, 9).expect("non-zero size");
981        let mut graph = RenderGraph::new(size);
982        let source = generator(&mut graph, "test.source");
983        let unused = generator(&mut graph, "test.unused");
984        assert_eq!(
985            graph.add_sum(source, vec![placement(0.0); crate::MAX_SUM_PLACEMENTS + 1]),
986            Err(GraphError::TooManyPlacements)
987        );
988        assert_eq!(
989            GraphError::TooManyPlacements.into_render_error(),
990            RenderError::InvalidGraph
991        );
992        assert_eq!(graph.node_count(), 2);
993        let sum = graph
994            .add_sum(source, vec![placement(0.0); crate::MAX_SUM_PLACEMENTS])
995            .expect("as many as a pass holds");
996        assert_eq!(graph.node_kind(sum), Some(RenderNodeKind::Sum));
997        graph.set_output(sum).expect("known output");
998        let plan = graph.compile().expect("compiles");
999        assert_eq!(plan.execution_order(), [source, sum]);
1000        assert_eq!(plan.last_use(source), Some(1));
1001        assert_eq!(plan.last_use(unused), None);
1002        assert_eq!(
1003            graph.cache_eligibility(sum),
1004            Ok(crate::CacheEligibility::Eligible)
1005        );
1006    }
1007
1008    #[test]
1009    fn a_sum_is_keyed_apart_from_a_composite_and_by_every_placement() {
1010        let size = RenderSize::new(16, 9).expect("non-zero size");
1011        let key = |build: &dyn Fn(&mut RenderGraph<'static>, [RenderNodeId; 2]) -> RenderNodeId| {
1012            let mut graph = RenderGraph::new(size);
1013            let nodes = [
1014                generator(&mut graph, "test.source"),
1015                generator(&mut graph, "test.other-source"),
1016            ];
1017            let node = build(&mut graph, nodes);
1018            graph.cache_keys[node.index]
1019        };
1020        let sum = |source: usize, placements: Vec<crate::LayerTransform>| {
1021            key(&move |graph, nodes| {
1022                graph
1023                    .add_sum(nodes[source], placements.clone())
1024                    .expect("earlier node")
1025            })
1026        };
1027        let placements = vec![placement(0.0), placement(0.1), placement(0.2)];
1028        let base = sum(0, placements.clone());
1029        assert_eq!(base, sum(0, placements.clone()));
1030        assert_ne!(base, sum(1, placements.clone()));
1031        assert_ne!(base, sum(0, placements[..2].to_vec()));
1032        let mut reordered = placements.clone();
1033        reordered.swap(0, 2);
1034        assert_ne!(base, sum(0, reordered));
1035        let edits: [fn(&mut crate::LayerTransform); 8] = [
1036            |placement| placement.position[0] += 0.01,
1037            |placement| placement.position[1] += 0.01,
1038            |placement| placement.anchor[0] += 0.01,
1039            |placement| placement.anchor[1] += 0.01,
1040            |placement| placement.scale[0] += 0.01,
1041            |placement| placement.scale[1] += 0.01,
1042            |placement| placement.rotation_degrees += 1.0,
1043            |placement| placement.opacity += 0.01,
1044        ];
1045        for index in 0..placements.len() {
1046            for (field, edit) in edits.iter().enumerate() {
1047                let mut changed = placements.clone();
1048                edit(&mut changed[index]);
1049                assert_ne!(base, sum(0, changed), "placement {index}, field {field}");
1050            }
1051        }
1052        let as_layers = |blend_mode: crate::BlendMode| {
1053            let placements = placements.clone();
1054            key(&move |graph, nodes| {
1055                graph
1056                    .add_composite(
1057                        placements
1058                            .iter()
1059                            .map(|visual| GraphLayer {
1060                                source: nodes[0],
1061                                visual: *visual,
1062                                blend_mode,
1063                            })
1064                            .collect(),
1065                    )
1066                    .expect("earlier node")
1067            })
1068        };
1069        assert_ne!(base, as_layers(crate::BlendMode::PlusLighter));
1070        assert_ne!(base, as_layers(crate::BlendMode::Normal));
1071        let one = sum(0, placements[..1].to_vec());
1072        let one_layer = key(&|graph, nodes| {
1073            graph
1074                .add_composite(vec![GraphLayer {
1075                    source: nodes[0],
1076                    visual: placement(0.0),
1077                    blend_mode: crate::BlendMode::Normal,
1078                }])
1079                .expect("earlier node")
1080        });
1081        assert_ne!(one, one_layer);
1082    }
1083
1084    #[test]
1085    fn a_graph_compiles_only_once_an_output_is_chosen() {
1086        let size = RenderSize::new(16, 9).expect("non-zero size");
1087        let mut graph = RenderGraph::new(size);
1088        let output = graph.add_composite(Vec::new()).expect("empty clear node");
1089        assert_eq!(graph.compile().err(), Some(GraphError::MissingOutput));
1090        assert_eq!(
1091            GraphError::MissingOutput.into_render_error(),
1092            RenderError::InvalidGraph
1093        );
1094        graph.set_output(output).expect("known output");
1095        assert_eq!(
1096            graph.compile().expect("compiles").execution_order(),
1097            [output]
1098        );
1099    }
1100}