bevy_render/renderer/
graph_runner.rs

1use bevy_ecs::{prelude::Entity, world::World};
2use bevy_platform::collections::HashMap;
3#[cfg(feature = "trace")]
4use tracing::info_span;
5
6use alloc::{borrow::Cow, collections::VecDeque};
7use smallvec::{smallvec, SmallVec};
8use thiserror::Error;
9
10use crate::{
11    diagnostic::internal::{DiagnosticsRecorder, RenderDiagnosticsMutex},
12    render_graph::{
13        Edge, InternedRenderLabel, InternedRenderSubGraph, NodeRunError, NodeState, RenderGraph,
14        RenderGraphContext, SlotLabel, SlotType, SlotValue,
15    },
16    renderer::{RenderContext, RenderDevice},
17};
18
19/// The [`RenderGraphRunner`] is responsible for executing a [`RenderGraph`].
20///
21/// It will run all nodes in the graph sequentially in the correct order (defined by the edges).
22/// Each [`Node`](crate::render_graph::Node) can run any arbitrary code, but will generally
23/// either send directly a [`CommandBuffer`] or a task that will asynchronously generate a [`CommandBuffer`]
24///
25/// After running the graph, the [`RenderGraphRunner`] will execute in parallel all the tasks to get
26/// an ordered list of [`CommandBuffer`]s to execute. These [`CommandBuffer`] will be submitted to the GPU
27/// sequentially in the order that the tasks were submitted. (which is the order of the [`RenderGraph`])
28///
29/// [`CommandBuffer`]: wgpu::CommandBuffer
30pub(crate) struct RenderGraphRunner;
31
32#[derive(Error, Debug)]
33pub enum RenderGraphRunnerError {
34    #[error(transparent)]
35    NodeRunError(#[from] NodeRunError),
36    #[error("node output slot not set (index {slot_index}, name {slot_name})")]
37    EmptyNodeOutputSlot {
38        type_name: &'static str,
39        slot_index: usize,
40        slot_name: Cow<'static, str>,
41    },
42    #[error("graph '{sub_graph:?}' could not be run because slot '{slot_name}' at index {slot_index} has no value")]
43    MissingInput {
44        slot_index: usize,
45        slot_name: Cow<'static, str>,
46        sub_graph: Option<InternedRenderSubGraph>,
47    },
48    #[error("attempted to use the wrong type for input slot")]
49    MismatchedInputSlotType {
50        slot_index: usize,
51        label: SlotLabel,
52        expected: SlotType,
53        actual: SlotType,
54    },
55    #[error(
56        "node (name: '{node_name:?}') has {slot_count} input slots, but was provided {value_count} values"
57    )]
58    MismatchedInputCount {
59        node_name: InternedRenderLabel,
60        slot_count: usize,
61        value_count: usize,
62    },
63}
64
65impl RenderGraphRunner {
66    pub fn run(
67        graph: &RenderGraph,
68        render_device: RenderDevice,
69        mut diagnostics_recorder: Option<DiagnosticsRecorder>,
70        queue: &wgpu::Queue,
71        #[cfg(not(all(target_arch = "wasm32", target_feature = "atomics")))]
72        adapter: &wgpu::Adapter,
73        world: &World,
74        finalizer: impl FnOnce(&mut wgpu::CommandEncoder),
75    ) -> Result<Option<DiagnosticsRecorder>, RenderGraphRunnerError> {
76        if let Some(recorder) = &mut diagnostics_recorder {
77            recorder.begin_frame();
78        }
79
80        let mut render_context = RenderContext::new(
81            render_device,
82            #[cfg(not(all(target_arch = "wasm32", target_feature = "atomics")))]
83            adapter.get_info(),
84            diagnostics_recorder,
85        );
86        Self::run_graph(graph, None, &mut render_context, world, &[], None)?;
87        finalizer(render_context.command_encoder());
88
89        let (render_device, mut diagnostics_recorder) = {
90            let (commands, render_device, diagnostics_recorder) = render_context.finish();
91
92            #[cfg(feature = "trace")]
93            let _span = info_span!("submit_graph_commands").entered();
94            queue.submit(commands);
95
96            (render_device, diagnostics_recorder)
97        };
98
99        if let Some(recorder) = &mut diagnostics_recorder {
100            let render_diagnostics_mutex = world.resource::<RenderDiagnosticsMutex>().0.clone();
101            recorder.finish_frame(&render_device, move |diagnostics| {
102                *render_diagnostics_mutex.lock().expect("lock poisoned") = Some(diagnostics);
103            });
104        }
105
106        Ok(diagnostics_recorder)
107    }
108
109    /// Runs the [`RenderGraph`] and all its sub-graphs sequentially, making sure that all nodes are
110    /// run in the correct order. (a node only runs when all its dependencies have finished running)
111    fn run_graph<'w>(
112        graph: &RenderGraph,
113        sub_graph: Option<InternedRenderSubGraph>,
114        render_context: &mut RenderContext<'w>,
115        world: &'w World,
116        inputs: &[SlotValue],
117        view_entity: Option<Entity>,
118    ) -> Result<(), RenderGraphRunnerError> {
119        let mut node_outputs: HashMap<InternedRenderLabel, SmallVec<[SlotValue; 4]>> =
120            HashMap::default();
121        #[cfg(feature = "trace")]
122        let span = if let Some(label) = &sub_graph {
123            info_span!("run_graph", name = format!("{label:?}"))
124        } else {
125            info_span!("run_graph", name = "main_graph")
126        };
127        #[cfg(feature = "trace")]
128        let _guard = span.enter();
129
130        // Queue up nodes without inputs, which can be run immediately
131        let mut node_queue: VecDeque<&NodeState> = graph
132            .iter_nodes()
133            .filter(|node| node.input_slots.is_empty())
134            .collect();
135
136        // pass inputs into the graph
137        if let Some(input_node) = graph.get_input_node() {
138            let mut input_values: SmallVec<[SlotValue; 4]> = SmallVec::new();
139            for (i, input_slot) in input_node.input_slots.iter().enumerate() {
140                if let Some(input_value) = inputs.get(i) {
141                    if input_slot.slot_type != input_value.slot_type() {
142                        return Err(RenderGraphRunnerError::MismatchedInputSlotType {
143                            slot_index: i,
144                            actual: input_value.slot_type(),
145                            expected: input_slot.slot_type,
146                            label: input_slot.name.clone().into(),
147                        });
148                    }
149                    input_values.push(input_value.clone());
150                } else {
151                    return Err(RenderGraphRunnerError::MissingInput {
152                        slot_index: i,
153                        slot_name: input_slot.name.clone(),
154                        sub_graph,
155                    });
156                }
157            }
158
159            node_outputs.insert(input_node.label, input_values);
160
161            for (_, node_state) in graph
162                .iter_node_outputs(input_node.label)
163                .expect("node exists")
164            {
165                node_queue.push_front(node_state);
166            }
167        }
168
169        'handle_node: while let Some(node_state) = node_queue.pop_back() {
170            // skip nodes that are already processed
171            if node_outputs.contains_key(&node_state.label) {
172                continue;
173            }
174
175            let mut slot_indices_and_inputs: SmallVec<[(usize, SlotValue); 4]> = SmallVec::new();
176            // check if all dependencies have finished running
177            for (edge, input_node) in graph
178                .iter_node_inputs(node_state.label)
179                .expect("node is in graph")
180            {
181                match edge {
182                    Edge::SlotEdge {
183                        output_index,
184                        input_index,
185                        ..
186                    } => {
187                        if let Some(outputs) = node_outputs.get(&input_node.label) {
188                            slot_indices_and_inputs
189                                .push((*input_index, outputs[*output_index].clone()));
190                        } else {
191                            node_queue.push_front(node_state);
192                            continue 'handle_node;
193                        }
194                    }
195                    Edge::NodeEdge { .. } => {
196                        if !node_outputs.contains_key(&input_node.label) {
197                            node_queue.push_front(node_state);
198                            continue 'handle_node;
199                        }
200                    }
201                }
202            }
203
204            // construct final sorted input list
205            slot_indices_and_inputs.sort_by_key(|(index, _)| *index);
206            let inputs: SmallVec<[SlotValue; 4]> = slot_indices_and_inputs
207                .into_iter()
208                .map(|(_, value)| value)
209                .collect();
210
211            if inputs.len() != node_state.input_slots.len() {
212                return Err(RenderGraphRunnerError::MismatchedInputCount {
213                    node_name: node_state.label,
214                    slot_count: node_state.input_slots.len(),
215                    value_count: inputs.len(),
216                });
217            }
218
219            let mut outputs: SmallVec<[Option<SlotValue>; 4]> =
220                smallvec![None; node_state.output_slots.len()];
221            {
222                let mut context = RenderGraphContext::new(graph, node_state, &inputs, &mut outputs);
223                if let Some(view_entity) = view_entity {
224                    context.set_view_entity(view_entity);
225                }
226
227                {
228                    #[cfg(feature = "trace")]
229                    let _span = info_span!("node", name = node_state.type_name).entered();
230
231                    node_state.node.run(&mut context, render_context, world)?;
232                }
233
234                for run_sub_graph in context.finish() {
235                    let sub_graph = graph
236                        .get_sub_graph(run_sub_graph.sub_graph)
237                        .expect("sub graph exists because it was validated when queued.");
238                    Self::run_graph(
239                        sub_graph,
240                        Some(run_sub_graph.sub_graph),
241                        render_context,
242                        world,
243                        &run_sub_graph.inputs,
244                        run_sub_graph.view_entity,
245                    )?;
246                }
247            }
248
249            let mut values: SmallVec<[SlotValue; 4]> = SmallVec::new();
250            for (i, output) in outputs.into_iter().enumerate() {
251                if let Some(value) = output {
252                    values.push(value);
253                } else {
254                    let empty_slot = node_state.output_slots.get_slot(i).unwrap();
255                    return Err(RenderGraphRunnerError::EmptyNodeOutputSlot {
256                        type_name: node_state.type_name,
257                        slot_index: i,
258                        slot_name: empty_slot.name.clone(),
259                    });
260                }
261            }
262            node_outputs.insert(node_state.label, values);
263
264            for (_, node_state) in graph
265                .iter_node_outputs(node_state.label)
266                .expect("node exists")
267            {
268                node_queue.push_front(node_state);
269            }
270        }
271
272        Ok(())
273    }
274}