Skip to main content

alpha2_render/
graph_plan.rs

1use crate::graph::{GraphError, RenderCacheKey, RenderGraph, RenderNode, RenderNodeId};
2
3/// Compiled execution and lifetime schedule for a render graph.
4#[derive(Clone, Debug)]
5pub struct RenderPlan {
6    pub(crate) graph: u32,
7    pub(crate) order: Vec<RenderNodeId>,
8    pub(crate) last_use: Vec<Option<usize>>,
9    pub(crate) output: RenderNodeId,
10    pub(crate) cache_key: RenderCacheKey,
11}
12
13impl RenderPlan {
14    /// Reachable nodes in deterministic insertion order.
15    #[must_use]
16    pub fn execution_order(&self) -> &[RenderNodeId] {
17        &self.order
18    }
19
20    /// Returns the execution position after which a node can be released.
21    #[must_use]
22    pub fn last_use(&self, node: RenderNodeId) -> Option<usize> {
23        (node.graph == self.graph)
24            .then(|| self.last_use.get(node.index).copied().flatten())
25            .flatten()
26    }
27
28    /// Returns the structural cache key of the selected output.
29    #[must_use]
30    pub const fn cache_key(&self) -> RenderCacheKey {
31        self.cache_key
32    }
33}
34
35impl RenderGraph<'_> {
36    /// Compiles reachable nodes and their final-use positions.
37    ///
38    /// # Errors
39    /// Returns [`GraphError::MissingOutput`] when no output was selected.
40    pub fn compile(&self) -> Result<RenderPlan, GraphError> {
41        let output = self.output.ok_or(GraphError::MissingOutput)?;
42        let mut reachable = vec![false; self.nodes.len()];
43        mark_reachable(output, &self.nodes, &mut reachable);
44        let order = reachable
45            .iter()
46            .enumerate()
47            .filter(|(_, is_reachable)| **is_reachable)
48            .map(|(index, _)| RenderNodeId {
49                graph: self.id,
50                index,
51            })
52            .collect::<Vec<_>>();
53        let mut last_use = vec![None; self.nodes.len()];
54        for (position, node) in order.iter().enumerate() {
55            for dependency in self.nodes[node.index].dependencies() {
56                last_use[dependency.index] = Some(position);
57            }
58        }
59        last_use[output.index] = Some(order.len());
60        Ok(RenderPlan {
61            graph: self.id,
62            order,
63            last_use,
64            output,
65            cache_key: self.cache_keys[output.index],
66        })
67    }
68}
69
70fn mark_reachable(node: RenderNodeId, nodes: &[RenderNode<'_>], reachable: &mut [bool]) {
71    let mut pending = vec![node];
72    while let Some(node) = pending.pop() {
73        if reachable[node.index] {
74            continue;
75        }
76        reachable[node.index] = true;
77        pending.extend(nodes[node.index].dependencies());
78    }
79}