1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
//! Simple frame graph implementation

use std::mem::{discriminant, Discriminant};
use std::ops::Range;
use std::vec::Drain;

use gfx_hal::command::CommandBuffer;
use gfx_hal::pool::CommandPoolCreateFlags;
use gfx_hal::pso::PipelineStage;
use gfx_hal::{Backend, Device, Graphics, Submission};

use bitvec::BitVec;
use failure::Fallible;
use fnv::FnvHashMap;
use smallvec::SmallVec;

use crate::encoder::Encoder;
use crate::factory::Factory;
use crate::node::{AnyNode, AnyNodePlan, Node, NodeId, NodePlan};

type NodeDeps = SmallVec<[NodeId; 8]>;

#[derive(derivative::Derivative)]
#[derivative(Default(bound = ""))]
/// Dynamic group of nodes of the same type
struct NodeGroup<B: Backend> {
    /// The range of nodes we can rebuild during node group updating
    #[derivative(Default(value = "0..0"))]
    visit_range: Range<usize>,

    nodes: Vec<AnyNode<B>>,
    plans: Vec<AnyNodePlan<B>>,

    // Every node is associated with a single semaphore, which will be signaled after node execution
    wait_semaphores: Vec<NodeDeps>,
    signal_semaphores: Vec<NodeId>,
}

impl<B: Backend> NodeGroup<B> {
    fn new() -> NodeGroup<B> {
        Default::default()
    }

    /// Called every frame to avoid memory leaks and reuse nodes instead of rebuilding them
    fn reset(&mut self, f: &mut Factory<B>) {
        if self.visit_range.start != self.visit_range.end {
            for node in self.nodes.drain(self.visit_range.start..) {
                node.destroy(f);
            }

            self.plans.truncate(self.visit_range.start);
        }

        self.visit_range = 0..self.plans.len()
    }

    /// Get next node id to rebuild
    fn next_plan(&mut self) -> Option<usize> {
        // TODO: choose the best node to rebuild, instead of the first one
        if self.visit_range.start < self.visit_range.end {
            self.visit_range.start += 1;
            Some(self.visit_range.start - 1)
        } else {
            self.visit_range.start += 1;
            None
        }
    }

    /// Add a new node to the group, rebuilding the existing one or instantiating a new one.
    fn add_node(&mut self, f: &mut Factory<B>, id: NodeId, deps: NodeDeps, plan: AnyNodePlan<B>) {
        if let Some(idx) = self.next_plan() {
            self.rebuild_node(f, idx, id, deps, plan);
        } else {
            self.push_node(f, id, deps, plan);
        };
    }

    fn rebuild_node(
        &mut self,
        f: &mut Factory<B>,
        idx: usize,
        id: NodeId,
        deps: NodeDeps,
        plan: AnyNodePlan<B>,
    ) {
        plan.rebuild(f, &mut self.nodes[idx]);
        self.wait_semaphores[idx] = deps;
        self.signal_semaphores[idx] = id;
    }

    fn push_node(&mut self, f: &mut Factory<B>, id: NodeId, deps: NodeDeps, plan: AnyNodePlan<B>) {
        self.nodes.push(plan.build(f));
        self.plans.push(plan);
        self.wait_semaphores.push(deps);
        self.signal_semaphores.push(id);
    }
}

/// Graph containing a "recipe" with dependencies for rendering the next frame
pub struct FrameGraph<B: Backend> {
    nodes: FnvHashMap<Discriminant<AnyNodePlan<B>>, NodeGroup<B>>,
    num_semaphores: usize,
    factory: Factory<B>,
    final_semaphores: Vec<NodeId>,
}

impl<B: Backend> FrameGraph<B> {
    /// Create a new frame graph encapsulating the specified `Factory`.
    pub fn new(factory: Factory<B>) -> FrameGraph<B> {
        FrameGraph {
            nodes: Default::default(),
            num_semaphores: 0,
            factory,
            final_semaphores: vec![],
        }
    }

    /// Create a new frame graph plan. Does the same thing as `FrameGraphPlan::new` does.
    pub fn plan() -> FrameGraphPlan<B> {
        Default::default()
    }

    fn update(
        &mut self,
        deps: Drain<NodeDeps>,
        plans: Drain<AnyNodePlan<B>>,
        final_nodes: &BitVec,
    ) {
        self.num_semaphores = plans.len();

        for (id, (deps, plan)) in deps.zip(plans).enumerate() {
            if final_nodes[id] {
                self.final_semaphores.push(NodeId(id as _));
            }

            self.nodes
                .entry(discriminant(&plan))
                .or_insert(NodeGroup::new())
                .add_node(&mut self.factory, NodeId(id as _), deps, plan);
        }

        for group in self.nodes.values_mut() {
            group.reset(&mut self.factory);
        }
    }

    /// Execute the frame graph.
    ///
    /// Records commands from every node and submit command buffers to the queue
    /// (currently only a single queue is used), putting semaphores where needed.
    ///
    /// The order of submitted command buffers is not defined, however this shouldn't matter
    /// when the nodes have correct dependencies.
    pub fn run(&mut self) -> Fallible<()> {
        let mut semaphores = Vec::with_capacity(self.num_semaphores);

        for _ in 0..self.num_semaphores {
            semaphores.push(self.factory.device.create_semaphore()?);
        }

        let mut cpool = unsafe {
            self.factory.device.create_command_pool_typed(
                &self.factory.queue_group,
                CommandPoolCreateFlags::empty(),
            )?
        };

        for group in self.nodes.values_mut() {
            for (id, node) in group.nodes.iter_mut().enumerate() {
                let mut cbuf = cpool.acquire_command_buffer();
                let encoder = Encoder { buf: &mut cbuf };

                node.run(&mut self.factory, encoder);

                let wait = group.wait_semaphores[id]
                    .iter()
                    .map(|&NodeId(v)| (&semaphores[v as usize], PipelineStage::BOTTOM_OF_PIPE));

                let signal = &semaphores[group.signal_semaphores[id].0 as usize];

                let submission = Submission {
                    command_buffers: &[cbuf],
                    wait_semaphores: wait,
                    signal_semaphores: Some(signal),
                };

                let queue = &mut self.factory.queue_group.queues[0];
                unsafe { queue.submit(submission, None) };
            }
        }

        let wait = self
            .final_semaphores
            .iter()
            .map(|&NodeId(v)| (&semaphores[v as usize], PipelineStage::BOTTOM_OF_PIPE));

        let submission = Submission {
            command_buffers: Option::<&CommandBuffer<B, Graphics>>::None,
            wait_semaphores: wait,
            signal_semaphores: Option::<&B::Semaphore>::None,
        };

        let fence = self.factory.device.create_fence(false)?;

        let queue = &mut self.factory.queue_group.queues[0];
        unsafe { queue.submit(submission, Some(&fence)) };

        unsafe { self.factory.device.wait_for_fence(&fence, std::u64::MAX) }?;

        unsafe { self.factory.device.destroy_fence(fence) };

        for semaphore in semaphores.drain(..) {
            unsafe { self.factory.device.destroy_semaphore(semaphore) };
        }

        unsafe { self.factory.device.destroy_command_pool(cpool.into_raw()) };

        Ok(())
    }
}

impl<B: Backend> Drop for FrameGraph<B> {
    fn drop(&mut self) {
        for (_, mut group) in self.nodes.drain() {
            for node in group.nodes.drain(..) {
                node.destroy(&mut self.factory);
            }
        }
    }
}

/// Plan for building or making changes to the frame graph.
#[derive(Clone, derivative::Derivative)]
#[derivative(Default(bound = ""))]
pub struct FrameGraphPlan<B: Backend> {
    plans: Vec<AnyNodePlan<B>>,
    deps: Vec<NodeDeps>,
    final_nodes: BitVec,
}

impl<B: Backend> FrameGraphPlan<B> {
    /// Create a new frame graph plan. Does the same thing as `FrameGraph::plan` does.
    pub fn new() -> FrameGraphPlan<B> {
        Default::default()
    }

    /// Add a new node to the plan with specified dependencies.
    ///
    /// Returns ID of the newly created node.
    pub fn add_node<P: Into<AnyNodePlan<B>>>(&mut self, deps: &[NodeId], plan: P) -> NodeId {
        for dep in deps {
            self.final_nodes.set(dep.0 as _, false);
        }

        self.final_nodes.push(true);
        self.plans.push(plan.into());
        self.deps.push(deps.into());
        NodeId((self.plans.len() - 1) as _)
    }

    /// Commit changes to the framegraph allocating or just updating resources for planned nodes.
    ///
    /// After that, plan is cleared and can (and should) be used again next frame to reduce
    /// memory allocation count. If you want to commit the same plan twice, you can `.clone()` it.
    pub fn commit(&mut self, fg: &mut FrameGraph<B>) {
        fg.update(self.deps.drain(..), self.plans.drain(..), &self.final_nodes);
        self.final_nodes.clear();
    }
}