1use core::marker::PhantomData;
2
3use crate::{
4 AccessId, AccessMode, AccessRole, AttachmentStoreOp, Buffer, BufferRange,
5 BufferTextureCopyLocation, ColorAttachmentOps, DepthAttachmentOps, Frame, FrameGraphError,
6 NodeKind, PassId, ResourceId, TextureCopyLocation, TextureSubresourceRange, TextureTarget,
7 WriteContents,
8 execution::{
9 CopyOperation, RenderColorAttachment, RenderDepthAttachment, TextureCopyLocationRecord,
10 },
11 model::{AccessRecord, NodeRecord, NormalizedRange},
12 types::AttachmentLoadOp,
13};
14
15mod sealed {
16 pub trait Sealed {}
17}
18
19pub trait AccessMarker: sealed::Sealed + Copy {}
21
22pub trait BufferAccessMarker: AccessMarker {}
24
25pub trait TextureAccessMarker: AccessMarker {}
27
28macro_rules! define_marker {
29 ($($name:ident),+ $(,)?) => {$ (
30 #[doc = concat!("Type marker for the `", stringify!($name), "` access role.")]
31 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32 pub struct $name;
33 impl sealed::Sealed for $name {}
34 impl AccessMarker for $name {}
35 )+ };
36}
37
38define_marker!(
39 SampledTexture,
40 StorageTextureRead,
41 StorageTextureWrite,
42 ColorAttachment,
43 DepthAttachment,
44 TextureCopySrc,
45 TextureCopyDst,
46 UniformBuffer,
47 StorageBufferRead,
48 StorageBufferWrite,
49 VertexBuffer,
50 IndexBuffer,
51 IndirectBuffer,
52 BufferCopySrc,
53 BufferCopyDst,
54);
55
56macro_rules! impl_buffer_marker {
57 ($($name:ty),+ $(,)?) => {$ (
58 impl BufferAccessMarker for $name {}
59 )+ };
60}
61
62macro_rules! impl_texture_marker {
63 ($($name:ty),+ $(,)?) => {$ (
64 impl TextureAccessMarker for $name {}
65 )+ };
66}
67
68impl_buffer_marker!(
69 UniformBuffer,
70 StorageBufferRead,
71 StorageBufferWrite,
72 VertexBuffer,
73 IndexBuffer,
74 IndirectBuffer,
75 BufferCopySrc,
76 BufferCopyDst,
77);
78
79impl_texture_marker!(
80 SampledTexture,
81 StorageTextureRead,
82 StorageTextureWrite,
83 ColorAttachment,
84 DepthAttachment,
85 TextureCopySrc,
86 TextureCopyDst,
87);
88
89#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
94#[must_use = "the access is recorded even when the token is ignored; keep the token for execution"]
95pub struct AccessToken<'frame, Role: AccessMarker> {
96 pub(crate) owner: u64,
97 pub(crate) recording: u64,
98 pass: PassId,
99 access: AccessId,
100 resource: ResourceId,
101 marker: PhantomData<fn(&'frame mut Role) -> &'frame mut Role>,
102}
103
104impl<Role: AccessMarker> AccessToken<'_, Role> {
105 pub const fn pass_id(self) -> PassId {
107 self.pass
108 }
109
110 pub const fn access_id(self) -> AccessId {
112 self.access
113 }
114
115 pub const fn resource_id(self) -> ResourceId {
117 self.resource
118 }
119}
120
121pub struct PassBuilder<'a, 'frame> {
129 frame: &'a mut Frame<'frame>,
130 node: Option<NodeRecord>,
131 color_attachments: Vec<RenderColorAttachment>,
132 depth_attachments: Vec<RenderDepthAttachment>,
133 copy_operations: Vec<CopyOperation>,
134 closed: bool,
135}
136
137impl<'a, 'frame> PassBuilder<'a, 'frame> {
138 pub(crate) fn new(
139 frame: &'a mut Frame<'frame>,
140 id: PassId,
141 kind: NodeKind,
142 label: String,
143 side_effect: bool,
144 ) -> Self {
145 let debug_group = frame.current_debug_group();
146 Self {
147 frame,
148 node: Some(NodeRecord {
149 id,
150 kind,
151 label,
152 side_effect,
153 accesses: Vec::new(),
154 debug_group,
155 }),
156 color_attachments: Vec::new(),
157 depth_attachments: Vec::new(),
158 copy_operations: Vec::new(),
159 closed: false,
160 }
161 }
162
163 pub fn id(&self) -> PassId {
165 self.node.as_ref().expect("open pass").id
166 }
167
168 pub fn set_side_effect(&mut self, side_effect: bool) -> &mut Self {
173 self.node.as_mut().expect("open pass").side_effect = side_effect;
174 self
175 }
176
177 pub fn sampled_texture(
179 &mut self,
180 target: impl Into<TextureTarget<'frame>>,
181 ) -> Result<AccessToken<'frame, SampledTexture>, FrameGraphError> {
182 self.texture_access(
183 target.into(),
184 AccessRole::SampledTexture,
185 AccessMode::Read,
186 true,
187 false,
188 )
189 }
190
191 pub fn storage_texture_read(
193 &mut self,
194 target: impl Into<TextureTarget<'frame>>,
195 ) -> Result<AccessToken<'frame, StorageTextureRead>, FrameGraphError> {
196 self.texture_access(
197 target.into(),
198 AccessRole::StorageTextureRead,
199 AccessMode::Read,
200 true,
201 false,
202 )
203 }
204
205 pub fn storage_texture_write(
210 &mut self,
211 target: impl Into<TextureTarget<'frame>>,
212 contents: WriteContents,
213 ) -> Result<AccessToken<'frame, StorageTextureWrite>, FrameGraphError> {
214 self.texture_access(
215 target.into(),
216 AccessRole::StorageTextureWrite,
217 AccessMode::Write,
218 contents == WriteContents::Preserve,
219 true,
220 )
221 }
222
223 pub fn color_attachment(
228 &mut self,
229 target: impl Into<TextureTarget<'frame>>,
230 ops: ColorAttachmentOps,
231 ) -> Result<AccessToken<'frame, ColorAttachment>, FrameGraphError> {
232 let (load, store) = ops.semantic();
233 let token = self.attachment_access(
234 target.into(),
235 AccessRole::ColorAttachment,
236 load,
237 store,
238 ops.depth_slice,
239 )?;
240 self.color_attachments.push(RenderColorAttachment {
241 access: token.access,
242 resolve_access: None,
243 ops,
244 });
245 Ok(token)
246 }
247
248 pub fn color_attachment_with_resolve(
253 &mut self,
254 source: impl Into<TextureTarget<'frame>>,
255 resolve_target: impl Into<TextureTarget<'frame>>,
256 ops: ColorAttachmentOps,
257 ) -> Result<AccessToken<'frame, ColorAttachment>, FrameGraphError> {
258 let (load, store) = ops.semantic();
259 let checkpoint = self.access_checkpoint();
260 let source = self.attachment_access(
261 source.into(),
262 AccessRole::ColorAttachment,
263 load,
264 store,
265 ops.depth_slice,
266 )?;
267 let resolve = self
268 .attachment_access::<ColorAttachment>(
269 resolve_target.into(),
270 AccessRole::ColorAttachment,
271 AttachmentLoadOp::Clear,
272 AttachmentStoreOp::Store,
273 None,
274 )
275 .inspect_err(|_| {
276 self.rollback_accesses(checkpoint);
277 })?;
278 self.color_attachments.push(RenderColorAttachment {
279 access: source.access,
280 resolve_access: Some(resolve.access),
281 ops,
282 });
283 Ok(source)
284 }
285
286 pub fn depth_attachment(
288 &mut self,
289 target: impl Into<TextureTarget<'frame>>,
290 ops: DepthAttachmentOps,
291 ) -> Result<AccessToken<'frame, DepthAttachment>, FrameGraphError> {
292 let (load, store) = ops.semantic();
293 let token = self.attachment_access(
294 target.into(),
295 AccessRole::DepthAttachment,
296 load,
297 store,
298 None,
299 )?;
300 self.depth_attachments.push(RenderDepthAttachment {
301 access: token.access,
302 ops: Some(ops),
303 read_only: false,
304 });
305 Ok(token)
306 }
307
308 pub fn depth_attachment_read_only(
310 &mut self,
311 target: impl Into<TextureTarget<'frame>>,
312 ) -> Result<AccessToken<'frame, DepthAttachment>, FrameGraphError> {
313 let (resource, range, view) =
314 self.normalize_attachment_target(target.into(), AccessRole::DepthAttachment, None)?;
315 let token = self.add_access(
316 resource,
317 AccessRole::DepthAttachment,
318 AccessMode::Read,
319 true,
320 false,
321 range,
322 view,
323 )?;
324 self.depth_attachments.push(RenderDepthAttachment {
325 access: token.access,
326 ops: None,
327 read_only: true,
328 });
329 Ok(token)
330 }
331
332 pub fn texture_copy_src(
334 &mut self,
335 target: impl Into<TextureTarget<'frame>>,
336 ) -> Result<AccessToken<'frame, TextureCopySrc>, FrameGraphError> {
337 self.texture_access(
338 target.into(),
339 AccessRole::TextureCopySrc,
340 AccessMode::Read,
341 true,
342 false,
343 )
344 }
345
346 pub fn texture_copy_dst(
348 &mut self,
349 target: impl Into<TextureTarget<'frame>>,
350 contents: WriteContents,
351 ) -> Result<AccessToken<'frame, TextureCopyDst>, FrameGraphError> {
352 self.texture_access(
353 target.into(),
354 AccessRole::TextureCopyDst,
355 AccessMode::Write,
356 contents == WriteContents::Preserve,
357 true,
358 )
359 }
360
361 pub fn uniform_buffer(
363 &mut self,
364 buffer: Buffer<'frame>,
365 range: BufferRange,
366 ) -> Result<AccessToken<'frame, UniformBuffer>, FrameGraphError> {
367 self.buffer_access(
368 buffer,
369 range,
370 AccessRole::UniformBuffer,
371 AccessMode::Read,
372 true,
373 false,
374 )
375 }
376
377 pub fn storage_buffer_read(
379 &mut self,
380 buffer: Buffer<'frame>,
381 range: BufferRange,
382 ) -> Result<AccessToken<'frame, StorageBufferRead>, FrameGraphError> {
383 self.buffer_access(
384 buffer,
385 range,
386 AccessRole::StorageBufferRead,
387 AccessMode::Read,
388 true,
389 false,
390 )
391 }
392
393 pub fn storage_buffer_write(
395 &mut self,
396 buffer: Buffer<'frame>,
397 range: BufferRange,
398 contents: WriteContents,
399 ) -> Result<AccessToken<'frame, StorageBufferWrite>, FrameGraphError> {
400 self.buffer_access(
401 buffer,
402 range,
403 AccessRole::StorageBufferWrite,
404 AccessMode::Write,
405 contents == WriteContents::Preserve,
406 true,
407 )
408 }
409
410 pub fn vertex_buffer(
412 &mut self,
413 buffer: Buffer<'frame>,
414 range: BufferRange,
415 ) -> Result<AccessToken<'frame, VertexBuffer>, FrameGraphError> {
416 self.buffer_access(
417 buffer,
418 range,
419 AccessRole::VertexBuffer,
420 AccessMode::Read,
421 true,
422 false,
423 )
424 }
425
426 pub fn index_buffer(
428 &mut self,
429 buffer: Buffer<'frame>,
430 range: BufferRange,
431 ) -> Result<AccessToken<'frame, IndexBuffer>, FrameGraphError> {
432 self.buffer_access(
433 buffer,
434 range,
435 AccessRole::IndexBuffer,
436 AccessMode::Read,
437 true,
438 false,
439 )
440 }
441
442 pub fn indirect_buffer(
444 &mut self,
445 buffer: Buffer<'frame>,
446 range: BufferRange,
447 ) -> Result<AccessToken<'frame, IndirectBuffer>, FrameGraphError> {
448 self.buffer_access(
449 buffer,
450 range,
451 AccessRole::IndirectBuffer,
452 AccessMode::Read,
453 true,
454 false,
455 )
456 }
457
458 pub fn buffer_copy_src(
460 &mut self,
461 buffer: Buffer<'frame>,
462 range: BufferRange,
463 ) -> Result<AccessToken<'frame, BufferCopySrc>, FrameGraphError> {
464 self.buffer_access(
465 buffer,
466 range,
467 AccessRole::BufferCopySrc,
468 AccessMode::Read,
469 true,
470 false,
471 )
472 }
473
474 pub fn buffer_copy_dst(
476 &mut self,
477 buffer: Buffer<'frame>,
478 range: BufferRange,
479 contents: WriteContents,
480 ) -> Result<AccessToken<'frame, BufferCopyDst>, FrameGraphError> {
481 self.buffer_access(
482 buffer,
483 range,
484 AccessRole::BufferCopyDst,
485 AccessMode::Write,
486 contents == WriteContents::Preserve,
487 true,
488 )
489 }
490
491 pub fn copy_buffer_to_buffer(
498 &mut self,
499 source: Buffer<'frame>,
500 source_offset: u64,
501 destination: Buffer<'frame>,
502 destination_offset: u64,
503 size: u64,
504 ) -> Result<&mut Self, FrameGraphError> {
505 self.require_kind(NodeKind::Copy, "buffer-to-buffer copy")?;
506 let source_range = BufferRange::new(source_offset, size);
507 let destination_range = BufferRange::new(destination_offset, size);
508 let checkpoint = self.access_checkpoint();
509 let _ = self.buffer_copy_src(source, source_range)?;
510 let _ = self
511 .buffer_copy_dst(destination, destination_range, WriteContents::Overwrite)
512 .inspect_err(|_| {
513 self.rollback_accesses(checkpoint);
514 })?;
515 if size == 0 {
516 self.set_access_graph_effect(checkpoint.0, false);
517 }
518 self.copy_operations.push(CopyOperation::BufferToBuffer {
519 source: source.id,
520 source_offset,
521 destination: destination.id,
522 destination_offset,
523 size,
524 });
525 Ok(self)
526 }
527
528 pub fn copy_buffer_to_texture(
538 &mut self,
539 source: BufferTextureCopyLocation<'frame>,
540 destination: TextureCopyLocation<'frame>,
541 copy_size: wgpu::Extent3d,
542 ) -> Result<&mut Self, FrameGraphError> {
543 self.require_kind(NodeKind::Copy, "buffer-to-texture copy")?;
544 let destination =
545 validate_texture_copy_location(self.frame, self.id(), destination, copy_size)?;
546 let buffer = validate_buffer_texture_copy(
547 self.frame,
548 self.id(),
549 source,
550 destination.record.resource,
551 destination.format,
552 destination.byte_aspect,
553 copy_size,
554 )?;
555 let checkpoint = self.access_checkpoint();
556 let _ = self.add_access::<BufferCopySrc>(
557 buffer.resource,
558 AccessRole::BufferCopySrc,
559 AccessMode::Read,
560 true,
561 false,
562 NormalizedRange::Buffer(buffer.range.clone()),
563 None,
564 )?;
565 let _ = self
566 .add_access::<TextureCopyDst>(
567 destination.record.resource,
568 AccessRole::TextureCopyDst,
569 AccessMode::Write,
570 !destination.full_subresources,
571 true,
572 NormalizedRange::Texture(destination.range),
573 None,
574 )
575 .inspect_err(|_| {
576 self.rollback_accesses(checkpoint);
577 })?;
578 if texture_copy_is_empty(copy_size) {
579 self.set_access_graph_effect(checkpoint.0, false);
580 }
581 self.copy_operations.push(CopyOperation::BufferToTexture {
582 source: buffer.resource,
583 source_layout: source.layout,
584 destination: destination.record,
585 copy_size,
586 });
587 Ok(self)
588 }
589
590 pub fn copy_texture_to_buffer(
597 &mut self,
598 source: TextureCopyLocation<'frame>,
599 destination: BufferTextureCopyLocation<'frame>,
600 copy_size: wgpu::Extent3d,
601 ) -> Result<&mut Self, FrameGraphError> {
602 self.require_kind(NodeKind::Copy, "texture-to-buffer copy")?;
603 let source = validate_texture_copy_location(self.frame, self.id(), source, copy_size)?;
604 let buffer = validate_buffer_texture_copy(
605 self.frame,
606 self.id(),
607 destination,
608 source.record.resource,
609 source.format,
610 source.byte_aspect,
611 copy_size,
612 )?;
613 let checkpoint = self.access_checkpoint();
614 let _ = self.add_access::<TextureCopySrc>(
615 source.record.resource,
616 AccessRole::TextureCopySrc,
617 AccessMode::Read,
618 true,
619 false,
620 NormalizedRange::Texture(source.range),
621 None,
622 )?;
623 let _ = self
624 .add_access::<BufferCopyDst>(
625 buffer.resource,
626 AccessRole::BufferCopyDst,
627 AccessMode::Write,
628 !buffer.tightly_packed,
629 true,
630 NormalizedRange::Buffer(buffer.range.clone()),
631 None,
632 )
633 .inspect_err(|_| {
634 self.rollback_accesses(checkpoint);
635 })?;
636 if texture_copy_is_empty(copy_size) {
637 self.set_access_graph_effect(checkpoint.0, false);
638 }
639 self.copy_operations.push(CopyOperation::TextureToBuffer {
640 source: source.record,
641 destination: buffer.resource,
642 destination_layout: destination.layout,
643 copy_size,
644 });
645 Ok(self)
646 }
647
648 pub fn copy_texture_to_texture(
655 &mut self,
656 source: TextureCopyLocation<'frame>,
657 destination: TextureCopyLocation<'frame>,
658 copy_size: wgpu::Extent3d,
659 ) -> Result<&mut Self, FrameGraphError> {
660 self.require_kind(NodeKind::Copy, "texture-to-texture copy")?;
661 let source = validate_texture_copy_location(self.frame, self.id(), source, copy_size)?;
662 let destination =
663 validate_texture_copy_location(self.frame, self.id(), destination, copy_size)?;
664 let checkpoint = self.access_checkpoint();
665 let _ = self.add_access::<TextureCopySrc>(
666 source.record.resource,
667 AccessRole::TextureCopySrc,
668 AccessMode::Read,
669 true,
670 false,
671 NormalizedRange::Texture(source.range),
672 None,
673 )?;
674 let _ = self
675 .add_access::<TextureCopyDst>(
676 destination.record.resource,
677 AccessRole::TextureCopyDst,
678 AccessMode::Write,
679 !destination.full_subresources,
680 true,
681 NormalizedRange::Texture(destination.range),
682 None,
683 )
684 .inspect_err(|_| {
685 self.rollback_accesses(checkpoint);
686 })?;
687 if texture_copy_is_empty(copy_size) {
688 self.set_access_graph_effect(checkpoint.0, false);
689 }
690 self.copy_operations.push(CopyOperation::TextureToTexture {
691 source: source.record,
692 destination: destination.record,
693 copy_size,
694 });
695 Ok(self)
696 }
697
698 pub fn finish(mut self) -> Result<PassId, FrameGraphError> {
704 self.finish_node()
705 }
706
707 pub fn finish_render<F>(mut self, callback: F) -> Result<PassId, FrameGraphError>
714 where
715 F: for<'execute> FnOnce(crate::RenderPassContext<'execute>) -> Result<(), FrameGraphError>
716 + 'frame,
717 {
718 if let Err(error) = self.require_kind(NodeKind::Render, "render executor") {
719 return Err(self.fail_finish(error));
720 }
721 if self.color_attachments.is_empty() && self.depth_attachments.is_empty() {
722 let error =
723 self.invalid_operation(None, "render nodes require at least one attachment");
724 return Err(self.fail_finish(error));
725 }
726 if self.depth_attachments.len() > 1 {
727 let error = self.invalid_operation(None, "render nodes support one depth attachment");
728 return Err(self.fail_finish(error));
729 }
730 let id = self.finish_node()?;
731 self.frame.executors.insert(
732 id,
733 crate::execution::NodeExecutor::Render {
734 color_attachments: core::mem::take(&mut self.color_attachments),
735 depth_attachment: self.depth_attachments.pop(),
736 callback: Box::new(callback),
737 },
738 );
739 Ok(id)
740 }
741
742 pub fn finish_compute<F>(mut self, callback: F) -> Result<PassId, FrameGraphError>
744 where
745 F: for<'execute> FnOnce(crate::ComputePassContext<'execute>) -> Result<(), FrameGraphError>
746 + 'frame,
747 {
748 if let Err(error) = self.require_kind(NodeKind::Compute, "compute executor") {
749 return Err(self.fail_finish(error));
750 }
751 let id = self.finish_node()?;
752 self.frame.executors.insert(
753 id,
754 crate::execution::NodeExecutor::Compute(Box::new(callback)),
755 );
756 Ok(id)
757 }
758
759 pub fn finish_command<F>(mut self, callback: F) -> Result<PassId, FrameGraphError>
763 where
764 F: for<'execute> FnOnce(crate::CommandContext<'execute>) -> Result<(), FrameGraphError>
765 + 'frame,
766 {
767 let node = self.node.as_ref().expect("open pass");
768 if node.kind != NodeKind::Command {
769 let error = FrameGraphError::InvalidNodeExecutor {
770 pass: node.id,
771 expected: "command",
772 actual: node.kind,
773 };
774 return Err(self.fail_finish(error));
775 }
776 let id = self.finish_node()?;
777 self.frame.executors.insert(
778 id,
779 crate::execution::NodeExecutor::Command(Box::new(callback)),
780 );
781 Ok(id)
782 }
783
784 pub fn finish_external<F>(mut self, callback: F) -> Result<PassId, FrameGraphError>
789 where
790 F: for<'execute> FnOnce(
791 crate::ExternalSubmissionContext<'execute>,
792 ) -> Result<(), FrameGraphError>
793 + 'frame,
794 {
795 let node = self.node.as_ref().expect("open pass");
796 if node.kind != NodeKind::ExternalSubmission {
797 let error = FrameGraphError::InvalidNodeExecutor {
798 pass: node.id,
799 expected: "external-submission",
800 actual: node.kind,
801 };
802 return Err(self.fail_finish(error));
803 }
804 let id = self.finish_node()?;
805 self.frame.executors.insert(
806 id,
807 crate::execution::NodeExecutor::External(Box::new(callback)),
808 );
809 Ok(id)
810 }
811
812 fn finish_node(&mut self) -> Result<PassId, FrameGraphError> {
813 let open = self.node.as_ref().expect("open pass");
814 if open.kind == NodeKind::Render
815 && let Err(error) = validate_render_attachments(
816 self.frame,
817 open.id,
818 &self.color_attachments,
819 self.depth_attachments.first().copied(),
820 open,
821 )
822 {
823 return Err(self.fail_finish(error));
824 }
825 if open.kind == NodeKind::Copy && !self.copy_operations.is_empty() {
826 self.frame.executors.insert(
827 open.id,
828 crate::execution::NodeExecutor::Copy(core::mem::take(&mut self.copy_operations)),
829 );
830 }
831 let node = self.node.take().expect("open pass");
832 let id = node.id;
833 self.frame.nodes.push(node);
834 self.closed = true;
835 Ok(id)
836 }
837
838 fn access_checkpoint(&self) -> (usize, u32) {
839 (
840 self.node.as_ref().expect("open pass").accesses.len(),
841 self.frame.next_access,
842 )
843 }
844
845 fn rollback_accesses(&mut self, checkpoint: (usize, u32)) {
846 self.node
847 .as_mut()
848 .expect("open pass")
849 .accesses
850 .truncate(checkpoint.0);
851 self.frame.next_access = checkpoint.1;
852 }
853
854 fn fail_finish(&mut self, error: FrameGraphError) -> FrameGraphError {
855 if self.frame.recording_error.is_none() {
856 self.frame.recording_error = Some(error.clone());
857 }
858 self.closed = true;
859 error
860 }
861
862 pub(crate) fn abort_with_error(&mut self, error: FrameGraphError) -> FrameGraphError {
863 self.fail_finish(error)
864 }
865
866 fn attachment_access<Role: AccessMarker>(
867 &mut self,
868 target: TextureTarget<'frame>,
869 role: AccessRole,
870 load: AttachmentLoadOp,
871 store: AttachmentStoreOp,
872 depth_slice: Option<u32>,
873 ) -> Result<AccessToken<'frame, Role>, FrameGraphError> {
874 let (resource, range, view) =
875 self.normalize_attachment_target(target, role, depth_slice)?;
876 self.add_access(
877 resource,
878 role,
879 AccessMode::Write,
880 load == AttachmentLoadOp::Load,
881 store == AttachmentStoreOp::Store,
882 range,
883 view,
884 )
885 }
886
887 fn normalize_attachment_target(
888 &mut self,
889 target: TextureTarget<'frame>,
890 role: AccessRole,
891 depth_slice: Option<u32>,
892 ) -> Result<(ResourceId, NormalizedRange, Option<crate::ViewId>), FrameGraphError> {
893 let direct_texture = matches!(target, TextureTarget::Texture(_));
894 let view = match target {
895 TextureTarget::Texture(_) => None,
896 TextureTarget::View(view) => Some(view.id),
897 };
898 let (resource, mut range) = self.frame.texture_target_range(target, false)?;
899 validate_texture_role(self.frame, resource, view, role)?;
900 let desc = self.frame.resource(resource)?.texture().expect("texture");
901 let regions = match &mut range {
902 NormalizedRange::Texture(regions) => regions,
903 NormalizedRange::Buffer(_) => unreachable!(),
904 };
905 if regions.is_empty() {
906 return Err(FrameGraphError::InvalidTextureView {
907 resource,
908 message: "attachment has no selected subresource".into(),
909 });
910 }
911 if !direct_texture && regions.len() != 1 {
912 return Err(FrameGraphError::InvalidTextureView {
913 resource,
914 message: "attachments require a single-mip view".into(),
915 });
916 }
917 regions.truncate(1);
918 let region = &mut regions[0];
919 if desc.dimension == wgpu::TextureDimension::D3 {
920 let slice = depth_slice.ok_or_else(|| FrameGraphError::InvalidTextureView {
921 resource,
922 message: "3D color attachments require depth_slice".into(),
923 })?;
924 if slice < region.base_slice || slice >= region.base_slice + region.slice_count {
925 return Err(FrameGraphError::InvalidTextureView {
926 resource,
927 message: format!("depth slice {slice} is outside the selected view"),
928 });
929 }
930 region.base_slice = slice;
931 region.slice_count = 1;
932 } else {
933 if depth_slice.is_some() {
934 return Err(FrameGraphError::InvalidTextureView {
935 resource,
936 message: "depth_slice is only valid for 3D color attachments".into(),
937 });
938 }
939 if !direct_texture && region.slice_count != 1 {
940 return Err(FrameGraphError::InvalidTextureView {
941 resource,
942 message: "attachments require a single array layer".into(),
943 });
944 }
945 region.slice_count = 1;
946 }
947 Ok((resource, range, view))
948 }
949
950 fn require_kind(
951 &self,
952 expected: NodeKind,
953 operation: &'static str,
954 ) -> Result<(), FrameGraphError> {
955 let node = self.node.as_ref().expect("open pass");
956 if node.kind == expected {
957 Ok(())
958 } else {
959 Err(FrameGraphError::InvalidNodeOperation {
960 pass: node.id,
961 resource: None,
962 message: format!(
963 "{operation} requires a {expected:?} node, found {:?}",
964 node.kind
965 ),
966 })
967 }
968 }
969
970 fn invalid_operation(
971 &self,
972 resource: Option<ResourceId>,
973 message: impl Into<String>,
974 ) -> FrameGraphError {
975 FrameGraphError::InvalidNodeOperation {
976 pass: self.id(),
977 resource,
978 message: message.into(),
979 }
980 }
981
982 fn texture_access<Role: AccessMarker>(
983 &mut self,
984 target: TextureTarget<'frame>,
985 role: AccessRole,
986 mode: AccessMode,
987 consumes_previous: bool,
988 produces_value: bool,
989 ) -> Result<AccessToken<'frame, Role>, FrameGraphError> {
990 let direct_texture = matches!(target, TextureTarget::Texture(_));
991 let view = match target {
992 TextureTarget::Texture(_) => None,
993 TextureTarget::View(view) => Some(view.id),
994 };
995 let (resource, mut range) = self.frame.texture_target_range(target, false)?;
996 validate_texture_role(self.frame, resource, view, role)?;
997 if matches!(
998 role,
999 AccessRole::StorageTextureRead | AccessRole::StorageTextureWrite
1000 ) {
1001 let regions = match &mut range {
1002 NormalizedRange::Texture(regions) => regions,
1003 NormalizedRange::Buffer(_) => unreachable!(),
1004 };
1005 if !direct_texture && regions.len() != 1 {
1006 return Err(FrameGraphError::InvalidTextureView {
1007 resource,
1008 message: "storage texture access requires a single-mip view".into(),
1009 });
1010 }
1011 regions.truncate(1);
1012 }
1013 self.add_access(
1014 resource,
1015 role,
1016 mode,
1017 consumes_previous,
1018 produces_value,
1019 range,
1020 view,
1021 )
1022 }
1023
1024 fn buffer_access<Role: AccessMarker>(
1025 &mut self,
1026 buffer: Buffer<'frame>,
1027 range: BufferRange,
1028 role: AccessRole,
1029 mode: AccessMode,
1030 consumes_previous: bool,
1031 produces_value: bool,
1032 ) -> Result<AccessToken<'frame, Role>, FrameGraphError> {
1033 self.frame.validate_handle(buffer.owner, buffer.recording)?;
1034 let desc =
1035 self.frame
1036 .resource(buffer.id)?
1037 .buffer()
1038 .ok_or_else(|| FrameGraphError::Internal {
1039 message: "buffer handle resolved to a texture".into(),
1040 })?;
1041 let range = NormalizedRange::Buffer(range.resolve(buffer.id, desc.size)?);
1042 self.add_access(
1043 buffer.id,
1044 role,
1045 mode,
1046 consumes_previous,
1047 produces_value,
1048 range,
1049 None,
1050 )
1051 }
1052
1053 #[expect(
1054 clippy::too_many_arguments,
1055 reason = "stores the normalized access record"
1056 )]
1057 fn add_access<Role: AccessMarker>(
1058 &mut self,
1059 resource: ResourceId,
1060 role: AccessRole,
1061 mode: AccessMode,
1062 consumes_previous: bool,
1063 produces_value: bool,
1064 range: NormalizedRange,
1065 view: Option<crate::ViewId>,
1066 ) -> Result<AccessToken<'frame, Role>, FrameGraphError> {
1067 let node = self.node.as_mut().expect("open pass");
1068 for existing in &node.accesses {
1069 if existing.resource == resource
1070 && existing.range.overlaps(&range)
1071 && (existing.mode == AccessMode::Write || mode == AccessMode::Write)
1072 {
1073 return Err(FrameGraphError::ConflictingAccesses {
1074 pass: node.id,
1075 resource,
1076 message:
1077 "overlapping reads and writes must be represented as one preserving access"
1078 .into(),
1079 });
1080 }
1081 }
1082 let id = AccessId::new(self.frame.next_access);
1083 self.frame.next_access = self.frame.next_access.checked_add(1).ok_or_else(|| {
1084 FrameGraphError::InvalidResourceDescriptor {
1085 message: "too many accesses in one frame".into(),
1086 }
1087 })?;
1088 node.accesses.push(AccessRecord {
1089 id,
1090 pass: node.id,
1091 resource,
1092 role,
1093 mode,
1094 graph_effect: true,
1095 consumes_previous,
1096 produces_value,
1097 range,
1098 view,
1099 value: None,
1100 });
1101 Ok(AccessToken {
1102 owner: self.frame.owner,
1103 recording: self.frame.recording,
1104 pass: node.id,
1105 access: id,
1106 resource,
1107 marker: PhantomData,
1108 })
1109 }
1110
1111 fn set_access_graph_effect(&mut self, start: usize, graph_effect: bool) {
1112 for access in &mut self.node.as_mut().expect("open pass").accesses[start..] {
1113 access.graph_effect = graph_effect;
1114 if !graph_effect {
1115 access.consumes_previous = false;
1116 access.produces_value = false;
1117 }
1118 }
1119 }
1120}
1121
1122impl Drop for PassBuilder<'_, '_> {
1123 fn drop(&mut self) {
1124 if self.closed {
1125 return;
1126 }
1127 if let Some(node) = self.node.as_ref()
1128 && self.frame.recording_error.is_none()
1129 {
1130 self.frame.recording_error = Some(FrameGraphError::UnclosedPass {
1131 pass: node.id,
1132 label: node.label.clone(),
1133 });
1134 }
1135 }
1136}
1137
1138fn validate_texture_role(
1139 frame: &Frame<'_>,
1140 resource: ResourceId,
1141 view: Option<crate::ViewId>,
1142 role: AccessRole,
1143) -> Result<(), FrameGraphError> {
1144 let desc = frame
1145 .resource(resource)?
1146 .texture()
1147 .ok_or_else(|| FrameGraphError::Internal {
1148 message: "texture access resolved to a buffer".into(),
1149 })?;
1150 let format = view
1151 .and_then(|id| frame.views.get(id.get() as usize))
1152 .and_then(|view| view.descriptor.format)
1153 .unwrap_or(desc.format);
1154 let depth = format.has_depth_aspect();
1155 match role {
1156 AccessRole::ColorAttachment if depth => Err(FrameGraphError::InvalidTextureView {
1157 resource,
1158 message: "depth formats cannot be color attachments".into(),
1159 }),
1160 AccessRole::DepthAttachment if !depth => Err(FrameGraphError::InvalidTextureView {
1161 resource,
1162 message: "color formats cannot be depth attachments".into(),
1163 }),
1164 _ => Ok(()),
1165 }
1166}
1167
1168#[derive(Clone, Debug)]
1169struct ValidatedTextureCopy {
1170 record: TextureCopyLocationRecord,
1171 range: Vec<TextureSubresourceRange>,
1172 format: wgpu::TextureFormat,
1173 byte_aspect: wgpu::TextureAspect,
1174 full_subresources: bool,
1175}
1176
1177#[derive(Clone, Debug)]
1178struct ValidatedBufferTextureCopy {
1179 resource: ResourceId,
1180 range: core::ops::Range<u64>,
1181 tightly_packed: bool,
1182}
1183
1184fn validate_texture_copy_location(
1185 frame: &Frame<'_>,
1186 pass: PassId,
1187 location: TextureCopyLocation<'_>,
1188 copy_size: wgpu::Extent3d,
1189) -> Result<ValidatedTextureCopy, FrameGraphError> {
1190 frame.validate_handle(location.texture.owner, location.texture.recording)?;
1191 let resource = location.texture.id;
1192 let desc = frame
1193 .resource(resource)?
1194 .texture()
1195 .ok_or_else(|| FrameGraphError::Internal {
1196 message: "texture copy location resolved to a buffer".into(),
1197 })?;
1198 let invalid = |message: String| FrameGraphError::InvalidNodeOperation {
1199 pass,
1200 resource: Some(resource),
1201 message,
1202 };
1203 if location.mip_level >= desc.mip_level_count {
1204 return Err(invalid(format!(
1205 "mip {} is outside {} mip levels",
1206 location.mip_level, desc.mip_level_count
1207 )));
1208 }
1209 let aspect = if desc.format.has_depth_aspect() {
1210 wgpu::TextureAspect::DepthOnly
1211 } else {
1212 wgpu::TextureAspect::All
1213 };
1214 let mip = location.mip_level;
1215 let mip_width = (desc.size.width >> mip).max(1);
1216 let mip_height = match desc.dimension {
1217 wgpu::TextureDimension::D1 => 1,
1218 _ => (desc.size.height >> mip).max(1),
1219 };
1220 let (block_width, block_height) = desc.format.block_dimensions();
1221 let physical_width =
1222 u64::from(mip_width).div_ceil(u64::from(block_width)) * u64::from(block_width);
1223 let physical_height =
1224 u64::from(mip_height).div_ceil(u64::from(block_height)) * u64::from(block_height);
1225 let mip_slices = crate::graph::slices_at_mip(desc, mip);
1226 let end_x = location
1227 .origin
1228 .x
1229 .checked_add(copy_size.width)
1230 .ok_or_else(|| invalid("texture copy x range overflows".into()))?;
1231 let end_y = location
1232 .origin
1233 .y
1234 .checked_add(copy_size.height)
1235 .ok_or_else(|| invalid("texture copy y range overflows".into()))?;
1236 let end_z = location
1237 .origin
1238 .z
1239 .checked_add(copy_size.depth_or_array_layers)
1240 .ok_or_else(|| invalid("texture copy z range overflows".into()))?;
1241 if u64::from(end_x) > physical_width || u64::from(end_y) > physical_height || end_z > mip_slices
1242 {
1243 return Err(invalid(format!(
1244 "copy region {:?}+{:?} exceeds mip extent {}x{}x{}",
1245 location.origin, copy_size, mip_width, mip_height, mip_slices
1246 )));
1247 }
1248 Ok(ValidatedTextureCopy {
1249 record: TextureCopyLocationRecord {
1250 resource,
1251 mip_level: mip,
1252 origin: location.origin,
1253 aspect: location.aspect,
1254 },
1255 range: vec![TextureSubresourceRange {
1256 base_mip_level: mip,
1257 mip_level_count: 1,
1258 base_slice: location.origin.z,
1259 slice_count: if texture_copy_is_empty(copy_size) {
1260 0
1261 } else {
1262 copy_size.depth_or_array_layers
1263 },
1264 aspect,
1265 }],
1266 format: desc.format,
1267 byte_aspect: aspect,
1268 full_subresources: location.origin.x == 0
1269 && location.origin.y == 0
1270 && u64::from(copy_size.width) == physical_width
1271 && u64::from(copy_size.height) == physical_height,
1272 })
1273}
1274
1275fn texture_copy_is_empty(copy_size: wgpu::Extent3d) -> bool {
1276 copy_size.width == 0 || copy_size.height == 0 || copy_size.depth_or_array_layers == 0
1277}
1278
1279fn validate_buffer_texture_copy(
1280 frame: &Frame<'_>,
1281 pass: PassId,
1282 location: BufferTextureCopyLocation<'_>,
1283 texture_resource: ResourceId,
1284 format: wgpu::TextureFormat,
1285 aspect: wgpu::TextureAspect,
1286 copy_size: wgpu::Extent3d,
1287) -> Result<ValidatedBufferTextureCopy, FrameGraphError> {
1288 frame.validate_handle(location.buffer.owner, location.buffer.recording)?;
1289 let resource = location.buffer.id;
1290 let desc = frame
1291 .resource(resource)?
1292 .buffer()
1293 .ok_or_else(|| FrameGraphError::Internal {
1294 message: "buffer texture copy location resolved to a texture".into(),
1295 })?;
1296 let invalid = |message: String| FrameGraphError::InvalidNodeOperation {
1297 pass,
1298 resource: Some(resource),
1299 message,
1300 };
1301 if texture_copy_is_empty(copy_size) && format.block_copy_size(Some(aspect)).is_none() {
1302 if location.layout.offset > desc.size {
1303 return Err(invalid(format!(
1304 "copy offset {} exceeds buffer size {}",
1305 location.layout.offset, desc.size
1306 )));
1307 }
1308 return Ok(ValidatedBufferTextureCopy {
1309 resource,
1310 range: location.layout.offset..location.layout.offset,
1311 tightly_packed: true,
1312 });
1313 }
1314 let bytes_per_block = u64::from(format.block_copy_size(Some(aspect)).ok_or_else(|| {
1315 FrameGraphError::InvalidNodeOperation {
1316 pass,
1317 resource: Some(texture_resource),
1318 message: format!(
1319 "texture format {format:?} has no buffer-texture copy footprint for dependency planning"
1320 ),
1321 }
1322 })?);
1323 let (block_width, block_height) = format.block_dimensions();
1324 let width_blocks = copy_size.width.div_ceil(block_width);
1325 let height_blocks = copy_size.height.div_ceil(block_height);
1326 let bytes_in_last_row = u64::from(width_blocks) * bytes_per_block;
1327 let row_stride = u64::from(location.layout.bytes_per_row.unwrap_or(0)).max(bytes_in_last_row);
1328 let image_rows = u64::from(
1329 location
1330 .layout
1331 .rows_per_image
1332 .unwrap_or(0)
1333 .max(height_blocks),
1334 );
1335 let bytes_in_copy = if copy_size.depth_or_array_layers == 0 {
1336 0
1337 } else if copy_size.depth_or_array_layers == 1 {
1338 if height_blocks == 0 {
1339 0
1340 } else {
1341 row_stride
1342 .checked_mul(u64::from(height_blocks - 1))
1343 .and_then(|rows| rows.checked_add(bytes_in_last_row))
1344 .ok_or_else(|| invalid("buffer texture copy range overflows".into()))?
1345 }
1346 } else {
1347 let image_stride = row_stride
1348 .checked_mul(image_rows)
1349 .ok_or_else(|| invalid("buffer texture copy range overflows".into()))?;
1350 image_stride
1351 .checked_mul(u64::from(copy_size.depth_or_array_layers - 1))
1352 .and_then(|images| {
1353 if height_blocks == 0 {
1354 Some(images)
1355 } else {
1356 row_stride
1357 .checked_mul(u64::from(height_blocks - 1))
1358 .and_then(|rows| images.checked_add(rows))
1359 .and_then(|bytes| bytes.checked_add(bytes_in_last_row))
1360 }
1361 })
1362 .ok_or_else(|| invalid("buffer texture copy range overflows".into()))?
1363 };
1364 let validation_end = location
1365 .layout
1366 .offset
1367 .checked_add(bytes_in_copy)
1368 .ok_or_else(|| invalid("buffer texture copy range overflows".into()))?;
1369 if validation_end > desc.size {
1370 return Err(invalid(format!(
1371 "copy range {}..{} exceeds buffer size {}",
1372 location.layout.offset, validation_end, desc.size
1373 )));
1374 }
1375 let end = if texture_copy_is_empty(copy_size) {
1376 location.layout.offset
1377 } else {
1378 validation_end
1379 };
1380 Ok(ValidatedBufferTextureCopy {
1381 resource,
1382 range: location.layout.offset..end,
1383 tightly_packed: (height_blocks <= 1 || row_stride == bytes_in_last_row)
1384 && (copy_size.depth_or_array_layers <= 1
1385 || (row_stride == bytes_in_last_row && image_rows == u64::from(height_blocks))),
1386 })
1387}
1388
1389fn validate_render_attachments(
1390 _frame: &Frame<'_>,
1391 pass: PassId,
1392 _colors: &[RenderColorAttachment],
1393 depth: Option<RenderDepthAttachment>,
1394 _node: &NodeRecord,
1395) -> Result<(), FrameGraphError> {
1396 let invalid = |resource, message: String| FrameGraphError::InvalidNodeOperation {
1397 pass,
1398 resource,
1399 message,
1400 };
1401 if let Some(depth) = depth
1402 && depth.ops.is_none()
1403 && !depth.read_only
1404 {
1405 return Err(invalid(
1406 None,
1407 "writable depth attachments require load/store operations".into(),
1408 ));
1409 }
1410 Ok(())
1411}
1412
1413#[cfg(test)]
1414mod completion_tests {
1415 use super::*;
1416
1417 #[test]
1418 fn failed_render_finish_installs_no_executor() {
1419 let mut graph = crate::FrameGraph::new();
1420 let mut frame = graph.begin_frame();
1421 let error = frame
1422 .render_pass("empty")
1423 .finish_render(|_| Ok(()))
1424 .unwrap_err();
1425 assert!(matches!(
1426 error,
1427 FrameGraphError::InvalidNodeOperation { .. }
1428 ));
1429 assert!(frame.executors.is_empty());
1430 assert!(frame.nodes.is_empty());
1431 assert_eq!(frame.recording_error, Some(error));
1432 }
1433}