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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
//! Rendering operations and command submission.
//!
//!

pub mod node;
pub mod pass_ref;

mod binding;
mod edge;
mod info;
mod resolver;
mod swapchain;

pub use self::{
    binding::{Bind, Unbind},
    resolver::Resolver,
};

use {
    self::{
        binding::Binding,
        edge::Edge,
        info::Information,
        node::Node,
        node::{
            AccelerationStructureLeaseNode, AccelerationStructureNode,
            AnyAccelerationStructureNode, AnyBufferNode, AnyImageNode, BufferLeaseNode, BufferNode,
            ImageLeaseNode, ImageNode, SwapchainImageNode,
        },
        pass_ref::{AttachmentIndex, Bindings, Descriptor, PassRef, SubresourceAccess, ViewType},
    },
    crate::driver::{
        buffer::Buffer,
        buffer_copy_subresources, buffer_image_copy_subresource,
        compute::ComputePipeline,
        device::Device,
        format_aspect_mask,
        graphic::{DepthStencilMode, GraphicPipeline},
        image::{ImageType, ImageViewInfo, SampleCount},
        is_write_access,
        ray_trace::RayTracePipeline,
        render_pass::ResolveMode,
        shader::PipelineDescriptorInfo,
        DescriptorBindingMap,
    },
    ash::vk,
    std::{
        cmp::Ord,
        collections::{BTreeMap, HashMap},
        fmt::{Debug, Formatter},
        ops::Range,
        sync::Arc,
    },
    vk_sync::AccessType,
};

type ExecFn = Box<dyn FnOnce(&Device, vk::CommandBuffer, Bindings<'_>) + Send>;
type NodeIndex = usize;

#[derive(Clone, Copy, Debug)]
struct Area {
    height: u32,
    width: u32,
    x: i32,
    y: i32,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Attachment {
    array_layer_count: u32,
    aspect_mask: vk::ImageAspectFlags,
    base_array_layer: u32,
    base_mip_level: u32,
    format: vk::Format,
    mip_level_count: u32,
    sample_count: SampleCount,
    target: NodeIndex,
}

impl Attachment {
    fn new(image_view_info: ImageViewInfo, sample_count: SampleCount, target: NodeIndex) -> Self {
        Self {
            array_layer_count: image_view_info
                .array_layer_count
                .unwrap_or(vk::REMAINING_ARRAY_LAYERS),
            aspect_mask: image_view_info.aspect_mask,
            base_array_layer: image_view_info.base_array_layer,
            base_mip_level: image_view_info.base_mip_level,
            format: image_view_info.fmt,
            mip_level_count: image_view_info
                .mip_level_count
                .unwrap_or(vk::REMAINING_MIP_LEVELS),
            sample_count,
            target,
        }
    }

    fn are_compatible(lhs: Option<Self>, rhs: Option<Self>) -> bool {
        // Two attachment references are compatible if they have matching format and sample
        // count, or are both VK_ATTACHMENT_UNUSED or the pointer that would contain the
        // reference is NULL.
        if lhs.is_none() || rhs.is_none() {
            return true;
        }

        Self::are_identical(lhs.unwrap(), rhs.unwrap())
    }

    pub fn are_identical(lhs: Self, rhs: Self) -> bool {
        lhs.array_layer_count == rhs.array_layer_count
            && lhs.base_array_layer == rhs.base_array_layer
            && lhs.base_mip_level == rhs.base_mip_level
            && lhs.format == rhs.format
            && lhs.mip_level_count == rhs.mip_level_count
            && lhs.sample_count == rhs.sample_count
            && lhs.target == rhs.target
    }
}

/// Specifies a color attachment clear value which can be used to initliaze an image.
#[derive(Clone, Copy, Debug)]
pub struct ClearColorValue(pub [f32; 4]);

impl From<[f32; 4]> for ClearColorValue {
    fn from(color: [f32; 4]) -> Self {
        Self(color)
    }
}

impl From<[u8; 4]> for ClearColorValue {
    fn from(color: [u8; 4]) -> Self {
        Self([
            color[0] as f32 / u8::MAX as f32,
            color[1] as f32 / u8::MAX as f32,
            color[2] as f32 / u8::MAX as f32,
            color[3] as f32 / u8::MAX as f32,
        ])
    }
}

#[derive(Default)]
struct Execution {
    accesses: HashMap<NodeIndex, [SubresourceAccess; 2]>,
    bindings: BTreeMap<Descriptor, (NodeIndex, Option<ViewType>)>,

    correlated_view_mask: u32,
    depth_stencil: Option<DepthStencilMode>,
    view_mask: u32,

    color_attachments: HashMap<AttachmentIndex, Attachment>,
    color_clears: HashMap<AttachmentIndex, (Attachment, ClearColorValue)>,
    color_loads: HashMap<AttachmentIndex, Attachment>,
    color_resolves: HashMap<AttachmentIndex, (Attachment, AttachmentIndex)>,
    color_stores: HashMap<AttachmentIndex, Attachment>,
    depth_stencil_attachment: Option<Attachment>,
    depth_stencil_clear: Option<(Attachment, vk::ClearDepthStencilValue)>,
    depth_stencil_load: Option<Attachment>,
    depth_stencil_resolve: Option<(
        Attachment,
        AttachmentIndex,
        Option<ResolveMode>,
        Option<ResolveMode>,
    )>,
    depth_stencil_store: Option<Attachment>,

    func: Option<ExecutionFunction>,
    pipeline: Option<ExecutionPipeline>,
}

impl Debug for Execution {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        // The only field missing is func which cannot easily be implemented because it is a
        // FnOnce.
        f.debug_struct("Execution")
            .field("accesses", &self.accesses)
            .field("bindings", &self.bindings)
            .field("depth_stencil", &self.depth_stencil)
            .field("color_attachments", &self.color_attachments)
            .field("color_clears", &self.color_clears)
            .field("color_loads", &self.color_loads)
            .field("color_resolves", &self.color_resolves)
            .field("color_stores", &self.color_stores)
            .field("depth_stencil_attachment", &self.depth_stencil_attachment)
            .field("depth_stencil_clear", &self.depth_stencil_clear)
            .field("depth_stencil_load", &self.depth_stencil_load)
            .field("depth_stencil_resolve", &self.depth_stencil_resolve)
            .field("depth_stencil_store", &self.depth_stencil_store)
            .field("pipeline", &self.pipeline)
            .finish()
    }
}

struct ExecutionFunction(ExecFn);

#[derive(Debug)]
enum ExecutionPipeline {
    Compute(Arc<ComputePipeline>),
    Graphic(Arc<GraphicPipeline>),
    RayTrace(Arc<RayTracePipeline>),
}

impl ExecutionPipeline {
    fn bind_point(&self) -> vk::PipelineBindPoint {
        match self {
            ExecutionPipeline::Compute(_) => vk::PipelineBindPoint::COMPUTE,
            ExecutionPipeline::Graphic(_) => vk::PipelineBindPoint::GRAPHICS,
            ExecutionPipeline::RayTrace(_) => vk::PipelineBindPoint::RAY_TRACING_KHR,
        }
    }

    fn descriptor_bindings(&self) -> &DescriptorBindingMap {
        match self {
            ExecutionPipeline::Compute(pipeline) => &pipeline.descriptor_bindings,
            ExecutionPipeline::Graphic(pipeline) => &pipeline.descriptor_bindings,
            ExecutionPipeline::RayTrace(pipeline) => &pipeline.descriptor_bindings,
        }
    }

    fn descriptor_info(&self) -> &PipelineDescriptorInfo {
        match self {
            ExecutionPipeline::Compute(pipeline) => &pipeline.descriptor_info,
            ExecutionPipeline::Graphic(pipeline) => &pipeline.descriptor_info,
            ExecutionPipeline::RayTrace(pipeline) => &pipeline.descriptor_info,
        }
    }

    fn layout(&self) -> vk::PipelineLayout {
        match self {
            ExecutionPipeline::Compute(pipeline) => pipeline.layout,
            ExecutionPipeline::Graphic(pipeline) => pipeline.layout,
            ExecutionPipeline::RayTrace(pipeline) => pipeline.layout,
        }
    }

    fn stage(&self) -> vk::PipelineStageFlags {
        match self {
            ExecutionPipeline::Compute(_) => vk::PipelineStageFlags::COMPUTE_SHADER,
            ExecutionPipeline::Graphic(_) => vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
            ExecutionPipeline::RayTrace(_) => vk::PipelineStageFlags::RAY_TRACING_SHADER_KHR,
        }
    }
}

impl Clone for ExecutionPipeline {
    fn clone(&self) -> Self {
        match self {
            Self::Compute(pipeline) => Self::Compute(Arc::clone(pipeline)),
            Self::Graphic(pipeline) => Self::Graphic(Arc::clone(pipeline)),
            Self::RayTrace(pipeline) => Self::RayTrace(Arc::clone(pipeline)),
        }
    }
}

#[derive(Debug)]
struct Pass {
    execs: Vec<Execution>,
    name: String,
    render_area: Option<Area>,
}

impl Pass {
    fn descriptor_pools_sizes(
        &self,
    ) -> impl Iterator<Item = &HashMap<u32, HashMap<vk::DescriptorType, u32>>> {
        self.execs
            .iter()
            .flat_map(|exec| exec.pipeline.as_ref())
            .map(|pipeline| &pipeline.descriptor_info().pool_sizes)
    }
}

/// A composable graph of render pass operations.
///
/// `RenderGraph` instances are are intended for one-time use.
///
/// The design of this code originated with a combination of
/// [`PassBuilder`](https://github.com/EmbarkStudios/kajiya/blob/main/crates/lib/kajiya-rg/src/pass_builder.rs)
/// and
/// [`render_graph.cpp`](https://github.com/Themaister/Granite/blob/master/renderer/render_graph.cpp).
#[derive(Debug)]
pub struct RenderGraph {
    bindings: Vec<Binding>,
    passes: Vec<Pass>,

    /// Set to true (when in debug mode) in order to get a breakpoint hit where you want.
    #[cfg(debug_assertions)]
    pub debug: bool,
}

impl RenderGraph {
    /// Constructs a new `RenderGraph`.
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        let bindings = vec![];
        let passes = vec![];

        #[cfg(debug_assertions)]
        let debug = false;

        Self {
            bindings,
            passes,
            #[cfg(debug_assertions)]
            debug,
        }
    }

    /// Begins a new pass.
    pub fn begin_pass(&mut self, name: impl AsRef<str>) -> PassRef<'_> {
        PassRef::new(self, name.as_ref().to_string())
    }

    /// Binds a Vulkan acceleration structure, buffer, or image to this graph.
    ///
    /// Bound nodes may be used in passes for pipeline and shader operations.
    pub fn bind_node<'a, B>(&'a mut self, binding: B) -> <B as Edge<Self>>::Result
    where
        B: Edge<Self>,
        B: Bind<&'a mut Self, <B as Edge<Self>>::Result>,
    {
        binding.bind(self)
    }

    /// Copy an image, potentially performing format conversion.
    pub fn blit_image(
        &mut self,
        src_node: impl Into<AnyImageNode>,
        dst_node: impl Into<AnyImageNode>,
        filter: vk::Filter,
    ) -> &mut Self {
        let src_node = src_node.into();
        let dst_node = dst_node.into();

        let src_info = self.node_info(src_node);
        let dst_info = self.node_info(dst_node);

        self.blit_image_region(
            src_node,
            dst_node,
            filter,
            vk::ImageBlit {
                src_subresource: vk::ImageSubresourceLayers {
                    aspect_mask: format_aspect_mask(src_info.fmt),
                    mip_level: 0,
                    base_array_layer: 0,
                    layer_count: 1,
                },
                src_offsets: [
                    vk::Offset3D {
                        x: src_info.width as _,
                        y: src_info.height as _,
                        z: src_info.depth as _,
                    },
                    vk::Offset3D { x: 0, y: 0, z: 0 },
                ],
                dst_subresource: vk::ImageSubresourceLayers {
                    aspect_mask: format_aspect_mask(dst_info.fmt),
                    mip_level: 0,
                    base_array_layer: 0,
                    layer_count: 1,
                },
                dst_offsets: [
                    vk::Offset3D {
                        x: dst_info.width as _,
                        y: dst_info.height as _,
                        z: dst_info.depth as _,
                    },
                    vk::Offset3D { x: 0, y: 0, z: 0 },
                ],
            },
        )
    }

    /// Copy a region of an image, potentially performing format conversion.
    pub fn blit_image_region(
        &mut self,
        src_node: impl Into<AnyImageNode>,
        dst_node: impl Into<AnyImageNode>,
        filter: vk::Filter,
        region: vk::ImageBlit,
    ) -> &mut Self {
        self.blit_image_regions(src_node, dst_node, filter, vec![region])
    }

    /// Copy regions of an image, potentially performing format conversion.
    #[profiling::function]
    pub fn blit_image_regions(
        &mut self,
        src_node: impl Into<AnyImageNode>,
        dst_node: impl Into<AnyImageNode>,
        filter: vk::Filter,
        regions: impl AsRef<[vk::ImageBlit]> + 'static + Send,
    ) -> &mut Self {
        let src_node = src_node.into();
        let dst_node = dst_node.into();
        let src_access_range = self.node_info(src_node).default_view_info();
        let dst_access_range = self.node_info(dst_node).default_view_info();

        self.begin_pass("blit image")
            .access_node_subrange(src_node, AccessType::TransferRead, src_access_range)
            .access_node_subrange(dst_node, AccessType::TransferWrite, dst_access_range)
            .record_cmd_buf(move |device, cmd_buf, bindings| unsafe {
                device.cmd_blit_image(
                    cmd_buf,
                    *bindings[src_node],
                    vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
                    *bindings[dst_node],
                    vk::ImageLayout::TRANSFER_DST_OPTIMAL,
                    regions.as_ref(),
                    filter,
                );
            })
            .submit_pass()
    }

    /// Clear a color image.
    pub fn clear_color_image(&mut self, image_node: impl Into<AnyImageNode>) -> &mut Self {
        self.clear_color_image_value(image_node, [0, 0, 0, 0])
    }

    /// Clear a color image.
    #[profiling::function]
    pub fn clear_color_image_value(
        &mut self,
        image_node: impl Into<AnyImageNode>,
        color_value: impl Into<ClearColorValue>,
    ) -> &mut Self {
        let color_value = color_value.into();
        let image_node = image_node.into();
        let image_info = self.node_info(image_node);
        let image_access_range = image_info.default_view_info();

        self.begin_pass("clear color")
            .access_node_subrange(image_node, AccessType::TransferWrite, image_access_range)
            .record_cmd_buf(move |device, cmd_buf, bindings| unsafe {
                device.cmd_clear_color_image(
                    cmd_buf,
                    *bindings[image_node],
                    vk::ImageLayout::TRANSFER_DST_OPTIMAL,
                    &vk::ClearColorValue {
                        float32: color_value.0,
                    },
                    &[vk::ImageSubresourceRange {
                        aspect_mask: vk::ImageAspectFlags::COLOR,
                        level_count: image_info.mip_level_count,
                        layer_count: image_info.array_elements,
                        ..Default::default()
                    }],
                );
            })
            .submit_pass()
    }

    /// Clears a depth/stencil image.
    pub fn clear_depth_stencil_image(&mut self, image_node: impl Into<AnyImageNode>) -> &mut Self {
        self.clear_depth_stencil_image_value(image_node, 1.0, 0)
    }

    /// Clears a depth/stencil image.
    #[profiling::function]
    pub fn clear_depth_stencil_image_value(
        &mut self,
        image_node: impl Into<AnyImageNode>,
        depth: f32,
        stencil: u32,
    ) -> &mut Self {
        let image_node = image_node.into();
        let image_info = self.node_info(image_node);
        let image_access_range = image_info.default_view_info();

        self.begin_pass("clear depth/stencil")
            .access_node_subrange(image_node, AccessType::TransferWrite, image_access_range)
            .record_cmd_buf(move |device, cmd_buf, bindings| unsafe {
                device.cmd_clear_depth_stencil_image(
                    cmd_buf,
                    *bindings[image_node],
                    vk::ImageLayout::TRANSFER_DST_OPTIMAL,
                    &vk::ClearDepthStencilValue { depth, stencil },
                    &[vk::ImageSubresourceRange {
                        aspect_mask: format_aspect_mask(image_info.fmt),
                        level_count: image_info.mip_level_count,
                        layer_count: image_info.array_elements,
                        ..Default::default()
                    }],
                );
            })
            .submit_pass()
    }

    /// Copy data between buffers
    pub fn copy_buffer(
        &mut self,
        src_node: impl Into<AnyBufferNode>,
        dst_node: impl Into<AnyBufferNode>,
    ) -> &mut Self {
        let src_node = src_node.into();
        let dst_node = dst_node.into();
        let src_info = self.node_info(src_node);
        let dst_info = self.node_info(dst_node);

        self.copy_buffer_region(
            src_node,
            dst_node,
            vk::BufferCopy {
                src_offset: 0,
                dst_offset: 0,
                size: src_info.size.min(dst_info.size),
            },
        )
    }

    /// Copy data between buffer regions.
    pub fn copy_buffer_region(
        &mut self,
        src_node: impl Into<AnyBufferNode>,
        dst_node: impl Into<AnyBufferNode>,
        region: vk::BufferCopy,
    ) -> &mut Self {
        self.copy_buffer_regions(src_node, dst_node, vec![region])
    }

    /// Copy data between buffer regions.
    #[profiling::function]
    pub fn copy_buffer_regions(
        &mut self,
        src_node: impl Into<AnyBufferNode>,
        dst_node: impl Into<AnyBufferNode>,
        regions: impl AsRef<[vk::BufferCopy]> + 'static + Send,
    ) -> &mut Self {
        let src_node = src_node.into();
        let dst_node = dst_node.into();
        let (src_access_range, dst_access_range) = buffer_copy_subresources(regions.as_ref());

        self.begin_pass("copy buffer")
            .access_node_subrange(src_node, AccessType::TransferRead, src_access_range)
            .access_node_subrange(dst_node, AccessType::TransferWrite, dst_access_range)
            .record_cmd_buf(move |device, cmd_buf, bindings| unsafe {
                device.cmd_copy_buffer(
                    cmd_buf,
                    *bindings[src_node],
                    *bindings[dst_node],
                    regions.as_ref(),
                );
            })
            .submit_pass()
    }

    /// Copy data from a buffer into an image.
    pub fn copy_buffer_to_image(
        &mut self,
        src_node: impl Into<AnyBufferNode>,
        dst_node: impl Into<AnyImageNode>,
    ) -> &mut Self {
        let dst_node = dst_node.into();
        let dst_info = self.node_info(dst_node);

        self.copy_buffer_to_image_region(
            src_node,
            dst_node,
            vk::BufferImageCopy {
                buffer_offset: 0,
                buffer_row_length: dst_info.width,
                buffer_image_height: dst_info.height,
                image_subresource: vk::ImageSubresourceLayers {
                    aspect_mask: format_aspect_mask(dst_info.fmt),
                    mip_level: 0,
                    base_array_layer: 0,
                    layer_count: 1,
                },
                image_offset: Default::default(),
                image_extent: vk::Extent3D {
                    depth: dst_info.depth,
                    height: dst_info.height,
                    width: dst_info.width,
                },
            },
        )
    }

    /// Copy data from a buffer into an image.
    pub fn copy_buffer_to_image_region(
        &mut self,
        src_node: impl Into<AnyBufferNode>,
        dst_node: impl Into<AnyImageNode>,
        region: vk::BufferImageCopy,
    ) -> &mut Self {
        self.copy_buffer_to_image_regions(src_node, dst_node, vec![region])
    }

    /// Copy data from a buffer into an image.
    #[profiling::function]
    pub fn copy_buffer_to_image_regions(
        &mut self,
        src_node: impl Into<AnyBufferNode>,
        dst_node: impl Into<AnyImageNode>,
        regions: impl AsRef<[vk::BufferImageCopy]> + 'static + Send,
    ) -> &mut Self {
        let src_node = src_node.into();
        let dst_node = dst_node.into();
        let dst_access_range = self.node_info(dst_node).default_view_info();
        let src_access_range = buffer_image_copy_subresource(regions.as_ref());

        self.begin_pass("copy buffer to image")
            .access_node_subrange(src_node, AccessType::TransferRead, src_access_range)
            .access_node_subrange(dst_node, AccessType::TransferWrite, dst_access_range)
            .record_cmd_buf(move |device, cmd_buf, bindings| unsafe {
                device.cmd_copy_buffer_to_image(
                    cmd_buf,
                    *bindings[src_node],
                    *bindings[dst_node],
                    vk::ImageLayout::TRANSFER_DST_OPTIMAL,
                    regions.as_ref(),
                );
            })
            .submit_pass()
    }

    /// Copy data between images.
    pub fn copy_image(
        &mut self,
        src_node: impl Into<AnyImageNode>,
        dst_node: impl Into<AnyImageNode>,
    ) -> &mut Self {
        let src_node = src_node.into();
        let dst_node = dst_node.into();

        let src_info = self.node_info(src_node);
        let dst_info = self.node_info(dst_node);

        self.copy_image_region(
            src_node,
            dst_node,
            vk::ImageCopy {
                src_subresource: vk::ImageSubresourceLayers {
                    aspect_mask: format_aspect_mask(src_info.fmt),
                    mip_level: 0,
                    base_array_layer: 0,
                    layer_count: if matches!(src_info.ty, ImageType::Cube | ImageType::CubeArray) {
                        6
                    } else {
                        1
                    },
                },
                src_offset: vk::Offset3D { x: 0, y: 0, z: 0 },
                dst_subresource: vk::ImageSubresourceLayers {
                    aspect_mask: format_aspect_mask(dst_info.fmt),
                    mip_level: 0,
                    base_array_layer: 0,
                    layer_count: if matches!(dst_info.ty, ImageType::Cube | ImageType::CubeArray) {
                        6
                    } else {
                        1
                    },
                },
                dst_offset: vk::Offset3D { x: 0, y: 0, z: 0 },
                extent: vk::Extent3D {
                    depth: src_info.depth.clamp(1, dst_info.depth),
                    height: src_info.height.clamp(1, dst_info.height),
                    width: src_info.width.min(dst_info.width),
                },
            },
        )
    }

    /// Copy data between images.
    pub fn copy_image_region(
        &mut self,
        src_node: impl Into<AnyImageNode>,
        dst_node: impl Into<AnyImageNode>,
        region: vk::ImageCopy,
    ) -> &mut Self {
        self.copy_image_regions(src_node, dst_node, vec![region])
    }

    /// Copy data between images.
    #[profiling::function]
    pub fn copy_image_regions(
        &mut self,
        src_node: impl Into<AnyImageNode>,
        dst_node: impl Into<AnyImageNode>,
        regions: impl AsRef<[vk::ImageCopy]> + 'static + Send,
    ) -> &mut Self {
        let src_node = src_node.into();
        let dst_node = dst_node.into();
        let src_access_range = self.node_info(src_node).default_view_info();
        let dst_access_range = self.node_info(dst_node).default_view_info();

        self.begin_pass("copy image")
            .access_node_subrange(src_node, AccessType::TransferRead, src_access_range)
            .access_node_subrange(dst_node, AccessType::TransferWrite, dst_access_range)
            .record_cmd_buf(move |device, cmd_buf, bindings| unsafe {
                device.cmd_copy_image(
                    cmd_buf,
                    *bindings[src_node],
                    vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
                    *bindings[dst_node],
                    vk::ImageLayout::TRANSFER_DST_OPTIMAL,
                    regions.as_ref(),
                );
            })
            .submit_pass()
    }

    /// Copy image data into a buffer.
    pub fn copy_image_to_buffer(
        &mut self,
        src_node: impl Into<AnyImageNode>,
        dst_node: impl Into<AnyBufferNode>,
    ) -> &mut Self {
        let src_node = src_node.into();
        let dst_node = dst_node.into();

        let src_info = self.node_info(src_node);

        self.copy_image_to_buffer_region(
            src_node,
            dst_node,
            vk::BufferImageCopy {
                buffer_offset: 0,
                buffer_row_length: src_info.width,
                buffer_image_height: src_info.height,
                image_subresource: vk::ImageSubresourceLayers {
                    aspect_mask: format_aspect_mask(src_info.fmt),
                    mip_level: 0,
                    base_array_layer: 0,
                    layer_count: 1,
                },
                image_offset: Default::default(),
                image_extent: vk::Extent3D {
                    depth: src_info.depth,
                    height: src_info.height,
                    width: src_info.width,
                },
            },
        )
    }

    /// Copy image data into a buffer.
    pub fn copy_image_to_buffer_region(
        &mut self,
        src_node: impl Into<AnyImageNode>,
        dst_node: impl Into<AnyBufferNode>,
        region: vk::BufferImageCopy,
    ) -> &mut Self {
        self.copy_image_to_buffer_regions(src_node, dst_node, vec![region])
    }

    /// Copy image data into a buffer.
    #[profiling::function]
    pub fn copy_image_to_buffer_regions(
        &mut self,
        src_node: impl Into<AnyImageNode>,
        dst_node: impl Into<AnyBufferNode>,
        regions: impl AsRef<[vk::BufferImageCopy]> + 'static + Send,
    ) -> &mut Self {
        let src_node = src_node.into();
        let dst_node = dst_node.into();
        let src_subresource = self.node_info(src_node).default_view_info();
        let dst_subresource = buffer_image_copy_subresource(regions.as_ref());

        self.begin_pass("copy image to buffer")
            .access_node_subrange(src_node, AccessType::TransferRead, src_subresource)
            .access_node_subrange(dst_node, AccessType::TransferWrite, dst_subresource)
            .record_cmd_buf(move |device, cmd_buf, bindings| unsafe {
                device.cmd_copy_image_to_buffer(
                    cmd_buf,
                    *bindings[src_node],
                    vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
                    *bindings[dst_node],
                    regions.as_ref(),
                );
            })
            .submit_pass()
    }

    /// Fill a region of a buffer with a fixed value.
    pub fn fill_buffer(&mut self, buffer_node: impl Into<AnyBufferNode>, data: u32) -> &mut Self {
        let buffer_node = buffer_node.into();

        let buffer_info = self.node_info(buffer_node);

        self.fill_buffer_region(buffer_node, data, 0..buffer_info.size)
    }

    /// Fill a region of a buffer with a fixed value.
    #[profiling::function]
    pub fn fill_buffer_region(
        &mut self,
        buffer_node: impl Into<AnyBufferNode>,
        data: u32,
        region: Range<vk::DeviceSize>,
    ) -> &mut Self {
        let buffer_node = buffer_node.into();
        let buffer_info = self.node_info(buffer_node);
        let buffer_access_range = 0..buffer_info.size;

        self.begin_pass("fill buffer")
            .access_node_subrange(buffer_node, AccessType::TransferWrite, buffer_access_range)
            .record_cmd_buf(move |device, cmd_buf, bindings| unsafe {
                device.cmd_fill_buffer(
                    cmd_buf,
                    *bindings[buffer_node],
                    region.start,
                    region.end - region.start,
                    data,
                );
            })
            .submit_pass()
    }

    #[profiling::function]
    pub(super) fn last_write(&self, node: impl Node) -> Option<AccessType> {
        let node_idx = node.index();

        self.passes
            .iter()
            .rev()
            .flat_map(|pass| pass.execs.iter().rev())
            .find_map(|exec| {
                exec.accesses.get(&node_idx).and_then(|[_early, late]| {
                    if is_write_access(late.access) {
                        Some(late.access)
                    } else {
                        None
                    }
                })
            })
    }

    /// Returns the index of the first pass which accesses a given node
    #[profiling::function]
    fn first_node_access_pass_index(&self, node: impl Node) -> Option<usize> {
        let node_idx = node.index();

        for (pass_idx, pass) in self.passes.iter().enumerate() {
            for exec in pass.execs.iter() {
                if exec.accesses.contains_key(&node_idx) {
                    return Some(pass_idx);
                }
            }
        }

        None
    }

    /// Returns the device address of a buffer node.
    ///
    /// # Panics
    ///
    /// Panics if the buffer is not currently bound or was not created with the
    /// `SHADER_DEVICE_ADDRESS` usage flag.
    pub fn node_device_address(&self, node: impl Into<AnyBufferNode>) -> vk::DeviceAddress {
        let node: AnyBufferNode = node.into();
        let buffer = self.bindings[node.index()].as_driver_buffer().unwrap();

        Buffer::device_address(buffer)
    }

    /// Returns information used to crate a node.
    pub fn node_info<N>(&self, node: N) -> <N as Information>::Info
    where
        N: Information,
    {
        node.get(self)
    }

    /// Finalizes the graph and provides an object with functions for submitting the resulting
    /// commands.
    #[profiling::function]
    pub fn resolve(mut self) -> Resolver {
        // The final execution of each pass has no function
        for pass in &mut self.passes {
            pass.execs.pop();
        }

        Resolver::new(self)
    }

    /// Removes a node from this graph.
    ///
    /// Future access to `node` on this graph will return invalid results.
    pub fn unbind_node<N>(&mut self, node: N) -> <N as Edge<Self>>::Result
    where
        N: Edge<Self>,
        N: Unbind<Self, <N as Edge<Self>>::Result>,
    {
        node.unbind(self)
    }

    /// Note: `data` must not exceed 65536 bytes.
    pub fn update_buffer(
        &mut self,
        buffer_node: impl Into<AnyBufferNode>,
        data: impl AsRef<[u8]> + 'static + Send,
    ) -> &mut Self {
        self.update_buffer_offset(buffer_node, 0, data)
    }

    /// Note: `data` must not exceed 65536 bytes.
    #[profiling::function]
    pub fn update_buffer_offset(
        &mut self,
        buffer_node: impl Into<AnyBufferNode>,
        offset: vk::DeviceSize,
        data: impl AsRef<[u8]> + 'static + Send,
    ) -> &mut Self {
        let buffer_node = buffer_node.into();
        let buffer_info = self.node_info(buffer_node);
        let buffer_access_range = 0..buffer_info.size;

        self.begin_pass("update buffer")
            .access_node_subrange(buffer_node, AccessType::TransferWrite, buffer_access_range)
            .record_cmd_buf(move |device, cmd_buf, bindings| unsafe {
                device.cmd_update_buffer(cmd_buf, *bindings[buffer_node], offset, data.as_ref());
            })
            .submit_pass()
    }
}