-
Notifications
You must be signed in to change notification settings - Fork 938
/
render.rs
2866 lines (2609 loc) · 112 KB
/
render.rs
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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::resource::Resource;
use crate::snatch::SnatchGuard;
use crate::{
api_log,
binding_model::BindError,
command::{
self,
bind::Binder,
end_occlusion_query, end_pipeline_statistics_query,
memory_init::{fixup_discarded_surfaces, SurfacesInDiscardState},
BasePass, BasePassRef, BindGroupStateChange, CommandBuffer, CommandEncoderError,
CommandEncoderStatus, DrawError, ExecutionError, MapPassErr, PassErrorScope, QueryUseError,
RenderCommand, RenderCommandError, StateChange,
},
device::{
AttachmentData, Device, DeviceError, MissingDownlevelFlags, MissingFeatures,
RenderPassCompatibilityCheckType, RenderPassCompatibilityError, RenderPassContext,
},
error::{ErrorFormatter, PrettyError},
global::Global,
hal_api::HalApi,
hal_label, id,
init_tracker::{MemoryInitKind, TextureInitRange, TextureInitTrackerAction},
pipeline::{self, PipelineFlags},
resource::{Buffer, QuerySet, Texture, TextureView, TextureViewNotRenderableReason},
storage::Storage,
track::{TextureSelector, Tracker, UsageConflict, UsageScope},
validation::{
check_buffer_usage, check_texture_usage, MissingBufferUsageError, MissingTextureUsageError,
},
Label,
};
use arrayvec::ArrayVec;
use hal::CommandEncoder as _;
use thiserror::Error;
use wgt::{
BufferAddress, BufferSize, BufferUsages, Color, IndexFormat, TextureUsages,
TextureViewDimension, VertexStepMode,
};
#[cfg(feature = "serde")]
use serde::Deserialize;
#[cfg(feature = "serde")]
use serde::Serialize;
use std::sync::Arc;
use std::{borrow::Cow, fmt, iter, marker::PhantomData, mem, num::NonZeroU32, ops::Range, str};
use super::{
memory_init::TextureSurfaceDiscard, CommandBufferTextureMemoryActions, CommandEncoder,
QueryResetMap,
};
/// Operation to perform to the output attachment at the start of a renderpass.
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum LoadOp {
/// Clear the output attachment with the clear color. Clearing is faster than loading.
Clear = 0,
/// Do not clear output attachment.
Load = 1,
}
/// Operation to perform to the output attachment at the end of a renderpass.
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum StoreOp {
/// Discards the content of the render target.
///
/// If you don't care about the contents of the target, this can be faster.
Discard = 0,
/// Store the result of the renderpass.
Store = 1,
}
/// Describes an individual channel within a render pass, such as color, depth, or stencil.
#[repr(C)]
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PassChannel<V> {
/// Operation to perform to the output attachment at the start of a
/// renderpass.
///
/// This must be clear if it is the first renderpass rendering to a swap
/// chain image.
pub load_op: LoadOp,
/// Operation to perform to the output attachment at the end of a renderpass.
pub store_op: StoreOp,
/// If load_op is [`LoadOp::Clear`], the attachment will be cleared to this
/// color.
pub clear_value: V,
/// If true, the relevant channel is not changed by a renderpass, and the
/// corresponding attachment can be used inside the pass by other read-only
/// usages.
pub read_only: bool,
}
impl<V> PassChannel<V> {
fn hal_ops(&self) -> hal::AttachmentOps {
let mut ops = hal::AttachmentOps::empty();
match self.load_op {
LoadOp::Load => ops |= hal::AttachmentOps::LOAD,
LoadOp::Clear => (),
};
match self.store_op {
StoreOp::Store => ops |= hal::AttachmentOps::STORE,
StoreOp::Discard => (),
};
ops
}
}
/// Describes a color attachment to a render pass.
#[repr(C)]
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct RenderPassColorAttachment {
/// The view to use as an attachment.
pub view: id::TextureViewId,
/// The view that will receive the resolved output if multisampling is used.
pub resolve_target: Option<id::TextureViewId>,
/// What operations will be performed on this color attachment.
pub channel: PassChannel<Color>,
}
/// Describes a depth/stencil attachment to a render pass.
#[repr(C)]
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct RenderPassDepthStencilAttachment {
/// The view to use as an attachment.
pub view: id::TextureViewId,
/// What operations will be performed on the depth part of the attachment.
pub depth: PassChannel<f32>,
/// What operations will be performed on the stencil part of the attachment.
pub stencil: PassChannel<u32>,
}
impl RenderPassDepthStencilAttachment {
/// Validate the given aspects' read-only flags against their load
/// and store ops.
///
/// When an aspect is read-only, its load and store ops must be
/// `LoadOp::Load` and `StoreOp::Store`.
///
/// On success, return a pair `(depth, stencil)` indicating
/// whether the depth and stencil passes are read-only.
fn depth_stencil_read_only(
&self,
aspects: hal::FormatAspects,
) -> Result<(bool, bool), RenderPassErrorInner> {
let mut depth_read_only = true;
let mut stencil_read_only = true;
if aspects.contains(hal::FormatAspects::DEPTH) {
if self.depth.read_only
&& (self.depth.load_op, self.depth.store_op) != (LoadOp::Load, StoreOp::Store)
{
return Err(RenderPassErrorInner::InvalidDepthOps);
}
depth_read_only = self.depth.read_only;
}
if aspects.contains(hal::FormatAspects::STENCIL) {
if self.stencil.read_only
&& (self.stencil.load_op, self.stencil.store_op) != (LoadOp::Load, StoreOp::Store)
{
return Err(RenderPassErrorInner::InvalidStencilOps);
}
stencil_read_only = self.stencil.read_only;
}
Ok((depth_read_only, stencil_read_only))
}
}
/// Location to write a timestamp to (beginning or end of the pass).
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum RenderPassTimestampLocation {
Beginning = 0,
End = 1,
}
/// Describes the writing of timestamp values in a render pass.
#[repr(C)]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct RenderPassTimestampWrites {
/// The query set to write the timestamp to.
pub query_set: id::QuerySetId,
/// The index of the query set at which a start timestamp of this pass is written, if any.
pub beginning_of_pass_write_index: Option<u32>,
/// The index of the query set at which an end timestamp of this pass is written, if any.
pub end_of_pass_write_index: Option<u32>,
}
/// Describes the attachments of a render pass.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RenderPassDescriptor<'a> {
pub label: Label<'a>,
/// The color attachments of the render pass.
pub color_attachments: Cow<'a, [Option<RenderPassColorAttachment>]>,
/// The depth and stencil attachment of the render pass, if any.
pub depth_stencil_attachment: Option<&'a RenderPassDepthStencilAttachment>,
/// Defines where and when timestamp values will be written for this pass.
pub timestamp_writes: Option<&'a RenderPassTimestampWrites>,
/// Defines where the occlusion query results will be stored for this pass.
pub occlusion_query_set: Option<id::QuerySetId>,
}
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct RenderPass {
base: BasePass<RenderCommand>,
parent_id: id::CommandEncoderId,
color_targets: ArrayVec<Option<RenderPassColorAttachment>, { hal::MAX_COLOR_ATTACHMENTS }>,
depth_stencil_target: Option<RenderPassDepthStencilAttachment>,
timestamp_writes: Option<RenderPassTimestampWrites>,
occlusion_query_set_id: Option<id::QuerySetId>,
// Resource binding dedupe state.
#[cfg_attr(feature = "serde", serde(skip))]
current_bind_groups: BindGroupStateChange,
#[cfg_attr(feature = "serde", serde(skip))]
current_pipeline: StateChange<id::RenderPipelineId>,
}
impl RenderPass {
pub fn new(parent_id: id::CommandEncoderId, desc: &RenderPassDescriptor) -> Self {
Self {
base: BasePass::new(&desc.label),
parent_id,
color_targets: desc.color_attachments.iter().cloned().collect(),
depth_stencil_target: desc.depth_stencil_attachment.cloned(),
timestamp_writes: desc.timestamp_writes.cloned(),
occlusion_query_set_id: desc.occlusion_query_set,
current_bind_groups: BindGroupStateChange::new(),
current_pipeline: StateChange::new(),
}
}
pub fn parent_id(&self) -> id::CommandEncoderId {
self.parent_id
}
#[cfg(feature = "trace")]
pub fn into_command(self) -> crate::device::trace::Command {
crate::device::trace::Command::RunRenderPass {
base: self.base,
target_colors: self.color_targets.into_iter().collect(),
target_depth_stencil: self.depth_stencil_target,
timestamp_writes: self.timestamp_writes,
occlusion_query_set_id: self.occlusion_query_set_id,
}
}
pub fn set_index_buffer(
&mut self,
buffer_id: id::BufferId,
index_format: IndexFormat,
offset: BufferAddress,
size: Option<BufferSize>,
) {
self.base.commands.push(RenderCommand::SetIndexBuffer {
buffer_id,
index_format,
offset,
size,
});
}
}
impl fmt::Debug for RenderPass {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RenderPass")
.field("encoder_id", &self.parent_id)
.field("color_targets", &self.color_targets)
.field("depth_stencil_target", &self.depth_stencil_target)
.field("command count", &self.base.commands.len())
.field("dynamic offset count", &self.base.dynamic_offsets.len())
.field(
"push constant u32 count",
&self.base.push_constant_data.len(),
)
.finish()
}
}
#[derive(Debug, PartialEq)]
enum OptionalState {
Unused,
Required,
Set,
}
impl OptionalState {
fn require(&mut self, require: bool) {
if require && *self == Self::Unused {
*self = Self::Required;
}
}
}
#[derive(Debug, Default)]
struct IndexState {
bound_buffer_view: Option<(id::BufferId, Range<BufferAddress>)>,
format: Option<IndexFormat>,
pipeline_format: Option<IndexFormat>,
limit: u64,
}
impl IndexState {
fn update_limit(&mut self) {
self.limit = match self.bound_buffer_view {
Some((_, ref range)) => {
let format = self
.format
.expect("IndexState::update_limit must be called after a index buffer is set");
let shift = match format {
IndexFormat::Uint16 => 1,
IndexFormat::Uint32 => 2,
};
(range.end - range.start) >> shift
}
None => 0,
}
}
fn reset(&mut self) {
self.bound_buffer_view = None;
self.limit = 0;
}
}
#[derive(Clone, Copy, Debug)]
struct VertexBufferState {
total_size: BufferAddress,
step: pipeline::VertexStep,
bound: bool,
}
impl VertexBufferState {
const EMPTY: Self = Self {
total_size: 0,
step: pipeline::VertexStep {
stride: 0,
last_stride: 0,
mode: VertexStepMode::Vertex,
},
bound: false,
};
}
#[derive(Debug, Default)]
struct VertexState {
inputs: ArrayVec<VertexBufferState, { hal::MAX_VERTEX_BUFFERS }>,
/// Length of the shortest vertex rate vertex buffer
vertex_limit: u64,
/// Buffer slot which the shortest vertex rate vertex buffer is bound to
vertex_limit_slot: u32,
/// Length of the shortest instance rate vertex buffer
instance_limit: u64,
/// Buffer slot which the shortest instance rate vertex buffer is bound to
instance_limit_slot: u32,
/// Total amount of buffers required by the pipeline.
buffers_required: u32,
}
impl VertexState {
fn update_limits(&mut self) {
// Implements the validation from https://gpuweb.github.io/gpuweb/#dom-gpurendercommandsmixin-draw
// Except that the formula is shuffled to extract the number of vertices in order
// to carry the bulk of the computation when changing states intead of when producing
// draws. Draw calls tend to happen at a higher frequency. Here we determine vertex
// limits that can be cheaply checked for each draw call.
self.vertex_limit = u32::MAX as u64;
self.instance_limit = u32::MAX as u64;
for (idx, vbs) in self.inputs.iter().enumerate() {
if !vbs.bound {
continue;
}
let limit = if vbs.total_size < vbs.step.last_stride {
// The buffer cannot fit the last vertex.
0
} else {
if vbs.step.stride == 0 {
// We already checked that the last stride fits, the same
// vertex will be repeated so this slot can accomodate any number of
// vertices.
continue;
}
// The general case.
(vbs.total_size - vbs.step.last_stride) / vbs.step.stride + 1
};
match vbs.step.mode {
VertexStepMode::Vertex => {
if limit < self.vertex_limit {
self.vertex_limit = limit;
self.vertex_limit_slot = idx as _;
}
}
VertexStepMode::Instance => {
if limit < self.instance_limit {
self.instance_limit = limit;
self.instance_limit_slot = idx as _;
}
}
}
}
}
fn reset(&mut self) {
self.inputs.clear();
self.vertex_limit = 0;
self.instance_limit = 0;
}
}
#[derive(Debug)]
struct State<A: HalApi> {
pipeline_flags: PipelineFlags,
binder: Binder<A>,
blend_constant: OptionalState,
stencil_reference: u32,
pipeline: Option<id::RenderPipelineId>,
index: IndexState,
vertex: VertexState,
debug_scope_depth: u32,
}
impl<A: HalApi> State<A> {
fn is_ready(&self, indexed: bool) -> Result<(), DrawError> {
// Determine how many vertex buffers have already been bound
let vertex_buffer_count = self.vertex.inputs.iter().take_while(|v| v.bound).count() as u32;
// Compare with the needed quantity
if vertex_buffer_count < self.vertex.buffers_required {
return Err(DrawError::MissingVertexBuffer {
index: vertex_buffer_count,
});
}
let bind_mask = self.binder.invalid_mask();
if bind_mask != 0 {
//let (expected, provided) = self.binder.entries[index as usize].info();
return Err(DrawError::IncompatibleBindGroup {
index: bind_mask.trailing_zeros(),
diff: self.binder.bgl_diff(),
});
}
if self.pipeline.is_none() {
return Err(DrawError::MissingPipeline);
}
if self.blend_constant == OptionalState::Required {
return Err(DrawError::MissingBlendConstant);
}
if indexed {
// Pipeline expects an index buffer
if let Some(pipeline_index_format) = self.index.pipeline_format {
// We have a buffer bound
let buffer_index_format = self.index.format.ok_or(DrawError::MissingIndexBuffer)?;
// The buffers are different formats
if pipeline_index_format != buffer_index_format {
return Err(DrawError::UnmatchedIndexFormats {
pipeline: pipeline_index_format,
buffer: buffer_index_format,
});
}
}
}
self.binder.check_late_buffer_bindings()?;
Ok(())
}
/// Reset the `RenderBundle`-related states.
fn reset_bundle(&mut self) {
self.binder.reset();
self.pipeline = None;
self.index.reset();
self.vertex.reset();
}
}
/// Describes an attachment location in words.
///
/// Can be used as "the {loc} has..." or "{loc} has..."
#[derive(Debug, Copy, Clone)]
pub enum AttachmentErrorLocation {
Color { index: usize, resolve: bool },
Depth,
}
impl fmt::Display for AttachmentErrorLocation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
AttachmentErrorLocation::Color {
index,
resolve: false,
} => write!(f, "color attachment at index {index}'s texture view"),
AttachmentErrorLocation::Color {
index,
resolve: true,
} => write!(
f,
"color attachment at index {index}'s resolve texture view"
),
AttachmentErrorLocation::Depth => write!(f, "depth attachment's texture view"),
}
}
}
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum ColorAttachmentError {
#[error("Attachment format {0:?} is not a color format")]
InvalidFormat(wgt::TextureFormat),
#[error("The number of color attachments {given} exceeds the limit {limit}")]
TooMany { given: usize, limit: usize },
}
/// Error encountered when performing a render pass.
#[derive(Clone, Debug, Error)]
pub enum RenderPassErrorInner {
#[error(transparent)]
Device(DeviceError),
#[error(transparent)]
ColorAttachment(#[from] ColorAttachmentError),
#[error(transparent)]
Encoder(#[from] CommandEncoderError),
#[error("Attachment texture view {0:?} is invalid")]
InvalidAttachment(id::TextureViewId),
#[error("Attachment texture view {0:?} is invalid")]
InvalidResolveTarget(id::TextureViewId),
#[error("The format of the depth-stencil attachment ({0:?}) is not a depth-stencil format")]
InvalidDepthStencilAttachmentFormat(wgt::TextureFormat),
#[error("The format of the {location} ({format:?}) is not resolvable")]
UnsupportedResolveTargetFormat {
location: AttachmentErrorLocation,
format: wgt::TextureFormat,
},
#[error("No color attachments or depth attachments were provided, at least one attachment of any kind must be provided")]
MissingAttachments,
#[error("The {location} is not renderable:")]
TextureViewIsNotRenderable {
location: AttachmentErrorLocation,
#[source]
reason: TextureViewNotRenderableReason,
},
#[error("Attachments have differing sizes: the {expected_location} has extent {expected_extent:?} but is followed by the {actual_location} which has {actual_extent:?}")]
AttachmentsDimensionMismatch {
expected_location: AttachmentErrorLocation,
expected_extent: wgt::Extent3d,
actual_location: AttachmentErrorLocation,
actual_extent: wgt::Extent3d,
},
#[error("Attachments have differing sample counts: the {expected_location} has count {expected_samples:?} but is followed by the {actual_location} which has count {actual_samples:?}")]
AttachmentSampleCountMismatch {
expected_location: AttachmentErrorLocation,
expected_samples: u32,
actual_location: AttachmentErrorLocation,
actual_samples: u32,
},
#[error("The resolve source, {location}, must be multi-sampled (has {src} samples) while the resolve destination must not be multisampled (has {dst} samples)")]
InvalidResolveSampleCounts {
location: AttachmentErrorLocation,
src: u32,
dst: u32,
},
#[error(
"Resource source, {location}, format ({src:?}) must match the resolve destination format ({dst:?})"
)]
MismatchedResolveTextureFormat {
location: AttachmentErrorLocation,
src: wgt::TextureFormat,
dst: wgt::TextureFormat,
},
#[error("Surface texture is dropped before the render pass is finished")]
SurfaceTextureDropped,
#[error("Not enough memory left for render pass")]
OutOfMemory,
#[error("The bind group at index {0:?} is invalid")]
InvalidBindGroup(usize),
#[error("Unable to clear non-present/read-only depth")]
InvalidDepthOps,
#[error("Unable to clear non-present/read-only stencil")]
InvalidStencilOps,
#[error("Setting `values_offset` to be `None` is only for internal use in render bundles")]
InvalidValuesOffset,
#[error(transparent)]
MissingFeatures(#[from] MissingFeatures),
#[error(transparent)]
MissingDownlevelFlags(#[from] MissingDownlevelFlags),
#[error("Indirect draw uses bytes {offset}..{end_offset} {} which overruns indirect buffer of size {buffer_size}",
count.map_or_else(String::new, |v| format!("(using count {v})")))]
IndirectBufferOverrun {
count: Option<NonZeroU32>,
offset: u64,
end_offset: u64,
buffer_size: u64,
},
#[error("Indirect draw uses bytes {begin_count_offset}..{end_count_offset} which overruns indirect buffer of size {count_buffer_size}")]
IndirectCountBufferOverrun {
begin_count_offset: u64,
end_count_offset: u64,
count_buffer_size: u64,
},
#[error("Cannot pop debug group, because number of pushed debug groups is zero")]
InvalidPopDebugGroup,
#[error(transparent)]
ResourceUsageConflict(#[from] UsageConflict),
#[error("Render bundle has incompatible targets, {0}")]
IncompatibleBundleTargets(#[from] RenderPassCompatibilityError),
#[error(
"Render bundle has incompatible read-only flags: \
bundle has flags depth = {bundle_depth} and stencil = {bundle_stencil}, \
while the pass has flags depth = {pass_depth} and stencil = {pass_stencil}. \
Read-only renderpasses are only compatible with read-only bundles for that aspect."
)]
IncompatibleBundleReadOnlyDepthStencil {
pass_depth: bool,
pass_stencil: bool,
bundle_depth: bool,
bundle_stencil: bool,
},
#[error(transparent)]
RenderCommand(#[from] RenderCommandError),
#[error(transparent)]
Draw(#[from] DrawError),
#[error(transparent)]
Bind(#[from] BindError),
#[error(transparent)]
QueryUse(#[from] QueryUseError),
#[error("Multiview layer count must match")]
MultiViewMismatch,
#[error(
"Multiview pass texture views with more than one array layer must have D2Array dimension"
)]
MultiViewDimensionMismatch,
#[error("QuerySet {0:?} is invalid")]
InvalidQuerySet(id::QuerySetId),
#[error("missing occlusion query set")]
MissingOcclusionQuerySet,
}
impl PrettyError for RenderPassErrorInner {
fn fmt_pretty(&self, fmt: &mut ErrorFormatter) {
fmt.error(self);
if let Self::InvalidAttachment(id) = *self {
fmt.texture_view_label_with_key(&id, "attachment");
};
if let Self::Draw(DrawError::IncompatibleBindGroup { diff, .. }) = self {
for d in diff {
fmt.note(&d);
}
};
}
}
impl From<MissingBufferUsageError> for RenderPassErrorInner {
fn from(error: MissingBufferUsageError) -> Self {
Self::RenderCommand(error.into())
}
}
impl From<MissingTextureUsageError> for RenderPassErrorInner {
fn from(error: MissingTextureUsageError) -> Self {
Self::RenderCommand(error.into())
}
}
impl From<DeviceError> for RenderPassErrorInner {
fn from(error: DeviceError) -> Self {
Self::Device(error)
}
}
/// Error encountered when performing a render pass.
#[derive(Clone, Debug, Error)]
#[error("{scope}")]
pub struct RenderPassError {
pub scope: PassErrorScope,
#[source]
inner: RenderPassErrorInner,
}
impl PrettyError for RenderPassError {
fn fmt_pretty(&self, fmt: &mut ErrorFormatter) {
// This error is wrapper for the inner error,
// but the scope has useful labels
fmt.error(self);
self.scope.fmt_pretty(fmt);
}
}
impl<T, E> MapPassErr<T, RenderPassError> for Result<T, E>
where
E: Into<RenderPassErrorInner>,
{
fn map_pass_err(self, scope: PassErrorScope) -> Result<T, RenderPassError> {
self.map_err(|inner| RenderPassError {
scope,
inner: inner.into(),
})
}
}
struct RenderAttachment<'a, A: HalApi> {
texture: Arc<Texture<A>>,
selector: &'a TextureSelector,
usage: hal::TextureUses,
}
impl<A: HalApi> TextureView<A> {
fn to_render_attachment(&self, usage: hal::TextureUses) -> RenderAttachment<A> {
RenderAttachment {
texture: self.parent.clone(),
selector: &self.selector,
usage,
}
}
}
const MAX_TOTAL_ATTACHMENTS: usize = hal::MAX_COLOR_ATTACHMENTS + hal::MAX_COLOR_ATTACHMENTS + 1;
type AttachmentDataVec<T> = ArrayVec<T, MAX_TOTAL_ATTACHMENTS>;
struct RenderPassInfo<'a, A: HalApi> {
context: RenderPassContext,
usage_scope: UsageScope<A>,
/// All render attachments, including depth/stencil
render_attachments: AttachmentDataVec<RenderAttachment<'a, A>>,
is_depth_read_only: bool,
is_stencil_read_only: bool,
extent: wgt::Extent3d,
_phantom: PhantomData<A>,
pending_discard_init_fixups: SurfacesInDiscardState<A>,
divergent_discarded_depth_stencil_aspect: Option<(wgt::TextureAspect, &'a TextureView<A>)>,
multiview: Option<NonZeroU32>,
}
impl<'a, A: HalApi> RenderPassInfo<'a, A> {
fn add_pass_texture_init_actions<V>(
channel: &PassChannel<V>,
texture_memory_actions: &mut CommandBufferTextureMemoryActions<A>,
view: &TextureView<A>,
pending_discard_init_fixups: &mut SurfacesInDiscardState<A>,
) {
if channel.load_op == LoadOp::Load {
pending_discard_init_fixups.extend(texture_memory_actions.register_init_action(
&TextureInitTrackerAction {
texture: view.parent.clone(),
range: TextureInitRange::from(view.selector.clone()),
// Note that this is needed even if the target is discarded,
kind: MemoryInitKind::NeedsInitializedMemory,
},
));
} else if channel.store_op == StoreOp::Store {
// Clear + Store
texture_memory_actions.register_implicit_init(
&view.parent,
TextureInitRange::from(view.selector.clone()),
);
}
if channel.store_op == StoreOp::Discard {
// the discard happens at the *end* of a pass, but recording the
// discard right away be alright since the texture can't be used
// during the pass anyways
texture_memory_actions.discard(TextureSurfaceDiscard {
texture: view.parent.clone(),
mip_level: view.selector.mips.start,
layer: view.selector.layers.start,
});
}
}
fn start(
device: &Device<A>,
label: Option<&str>,
color_attachments: &[Option<RenderPassColorAttachment>],
depth_stencil_attachment: Option<&RenderPassDepthStencilAttachment>,
timestamp_writes: Option<&RenderPassTimestampWrites>,
occlusion_query_set: Option<id::QuerySetId>,
encoder: &mut CommandEncoder<A>,
trackers: &mut Tracker<A>,
texture_memory_actions: &mut CommandBufferTextureMemoryActions<A>,
pending_query_resets: &mut QueryResetMap<A>,
view_guard: &'a Storage<TextureView<A>>,
buffer_guard: &'a Storage<Buffer<A>>,
texture_guard: &'a Storage<Texture<A>>,
query_set_guard: &'a Storage<QuerySet<A>>,
snatch_guard: &SnatchGuard<'a>,
) -> Result<Self, RenderPassErrorInner> {
profiling::scope!("RenderPassInfo::start");
// We default to false intentionally, even if depth-stencil isn't used at all.
// This allows us to use the primary raw pipeline in `RenderPipeline`,
// instead of the special read-only one, which would be `None`.
let mut is_depth_read_only = false;
let mut is_stencil_read_only = false;
let mut render_attachments = AttachmentDataVec::<RenderAttachment<A>>::new();
let mut discarded_surfaces = AttachmentDataVec::new();
let mut pending_discard_init_fixups = SurfacesInDiscardState::new();
let mut divergent_discarded_depth_stencil_aspect = None;
let mut attachment_location = AttachmentErrorLocation::Color {
index: usize::MAX,
resolve: false,
};
let mut extent = None;
let mut sample_count = 0;
let mut detected_multiview: Option<Option<NonZeroU32>> = None;
let mut check_multiview = |view: &TextureView<A>| {
// Get the multiview configuration for this texture view
let layers = view.selector.layers.end - view.selector.layers.start;
let this_multiview = if layers >= 2 {
// Trivially proven by the if above
Some(unsafe { NonZeroU32::new_unchecked(layers) })
} else {
None
};
// Make sure that if this view is a multiview, it is set to be an array
if this_multiview.is_some() && view.desc.dimension != TextureViewDimension::D2Array {
return Err(RenderPassErrorInner::MultiViewDimensionMismatch);
}
// Validate matching first, or store the first one
if let Some(multiview) = detected_multiview {
if multiview != this_multiview {
return Err(RenderPassErrorInner::MultiViewMismatch);
}
} else {
// Multiview is only supported if the feature is enabled
if this_multiview.is_some() {
device.require_features(wgt::Features::MULTIVIEW)?;
}
detected_multiview = Some(this_multiview);
}
Ok(())
};
let mut add_view = |view: &TextureView<A>, location| {
let render_extent = view.render_extent.map_err(|reason| {
RenderPassErrorInner::TextureViewIsNotRenderable { location, reason }
})?;
if let Some(ex) = extent {
if ex != render_extent {
return Err(RenderPassErrorInner::AttachmentsDimensionMismatch {
expected_location: attachment_location,
expected_extent: ex,
actual_location: location,
actual_extent: render_extent,
});
}
} else {
extent = Some(render_extent);
}
if sample_count == 0 {
sample_count = view.samples;
} else if sample_count != view.samples {
return Err(RenderPassErrorInner::AttachmentSampleCountMismatch {
expected_location: attachment_location,
expected_samples: sample_count,
actual_location: location,
actual_samples: view.samples,
});
}
attachment_location = location;
Ok(())
};
let mut colors =
ArrayVec::<Option<hal::ColorAttachment<A>>, { hal::MAX_COLOR_ATTACHMENTS }>::new();
let mut depth_stencil = None;
if let Some(at) = depth_stencil_attachment {
let view: &TextureView<A> = trackers
.views
.add_single(view_guard, at.view)
.ok_or(RenderPassErrorInner::InvalidAttachment(at.view))?;
check_multiview(view)?;
add_view(view, AttachmentErrorLocation::Depth)?;
let ds_aspects = view.desc.aspects();
if ds_aspects.contains(hal::FormatAspects::COLOR) {
return Err(RenderPassErrorInner::InvalidDepthStencilAttachmentFormat(
view.desc.format,
));
}
if !ds_aspects.contains(hal::FormatAspects::STENCIL)
|| (at.stencil.load_op == at.depth.load_op
&& at.stencil.store_op == at.depth.store_op)
{
Self::add_pass_texture_init_actions(
&at.depth,
texture_memory_actions,
view,
&mut pending_discard_init_fixups,
);
} else if !ds_aspects.contains(hal::FormatAspects::DEPTH) {
Self::add_pass_texture_init_actions(
&at.stencil,
texture_memory_actions,
view,
&mut pending_discard_init_fixups,
);
} else {
// This is the only place (anywhere in wgpu) where Stencil &
// Depth init state can diverge.
//
// To safe us the overhead of tracking init state of texture
// aspects everywhere, we're going to cheat a little bit in
// order to keep the init state of both Stencil and Depth
// aspects in sync. The expectation is that we hit this path
// extremely rarely!
//
// Diverging LoadOp, i.e. Load + Clear:
//
// Record MemoryInitKind::NeedsInitializedMemory for the entire
// surface, a bit wasteful on unit but no negative effect!
//
// Rationale: If the loaded channel is uninitialized it needs
// clearing, the cleared channel doesn't care. (If everything is
// already initialized nothing special happens)
//
// (possible minor optimization: Clear caused by
// NeedsInitializedMemory should know that it doesn't need to
// clear the aspect that was set to C)
let need_init_beforehand =
at.depth.load_op == LoadOp::Load || at.stencil.load_op == LoadOp::Load;
if need_init_beforehand {
pending_discard_init_fixups.extend(
texture_memory_actions.register_init_action(&TextureInitTrackerAction {
texture: view.parent.clone(),
range: TextureInitRange::from(view.selector.clone()),
kind: MemoryInitKind::NeedsInitializedMemory,
}),
);
}
// Diverging Store, i.e. Discard + Store:
//
// Immediately zero out channel that is set to discard after
// we're done with the render pass. This allows us to set the
// entire surface to MemoryInitKind::ImplicitlyInitialized (if
// it isn't already set to NeedsInitializedMemory).
//
// (possible optimization: Delay and potentially drop this zeroing)
if at.depth.store_op != at.stencil.store_op {
if !need_init_beforehand {
texture_memory_actions.register_implicit_init(
&view.parent,
TextureInitRange::from(view.selector.clone()),
);
}
divergent_discarded_depth_stencil_aspect = Some((
if at.depth.store_op == StoreOp::Discard {
wgt::TextureAspect::DepthOnly
} else {
wgt::TextureAspect::StencilOnly
},
view,
));
} else if at.depth.store_op == StoreOp::Discard {
// Both are discarded using the regular path.
discarded_surfaces.push(TextureSurfaceDiscard {
texture: view.parent.clone(),
mip_level: view.selector.mips.start,
layer: view.selector.layers.start,
});
}
}
(is_depth_read_only, is_stencil_read_only) = at.depth_stencil_read_only(ds_aspects)?;
let usage = if is_depth_read_only
&& is_stencil_read_only
&& device
.downlevel
.flags
.contains(wgt::DownlevelFlags::READ_ONLY_DEPTH_STENCIL)