-
Notifications
You must be signed in to change notification settings - Fork 843
/
render.rs
2085 lines (1910 loc) · 80 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::{
binding_model::BindError,
command::{
bind::Binder, end_pipeline_statistics_query, BasePass, BasePassRef, CommandBuffer,
CommandEncoderError, CommandEncoderStatus, DrawError, ExecutionError, MapPassErr,
PassErrorScope, QueryResetMap, QueryUseError, RenderCommand, RenderCommandError,
StateChange,
},
device::{
AttachmentData, MissingDownlevelFlags, MissingFeatures, RenderPassCompatibilityError,
RenderPassContext,
},
error::{ErrorFormatter, PrettyError},
hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token},
id,
init_tracker::MemoryInitKind,
pipeline::PipelineFlags,
resource::{Texture, TextureView},
track::{StatefulTrackerSubset, TextureSelector, UsageConflict},
validation::{
check_buffer_usage, check_texture_usage, MissingBufferUsageError, MissingTextureUsageError,
},
Label, Stored,
};
use arrayvec::ArrayVec;
use hal::CommandEncoder as _;
use thiserror::Error;
use wgt::{
BufferAddress, BufferSize, BufferUsages, Color, IndexFormat, TextureUsages, VertexStepMode,
};
#[cfg(any(feature = "serial-pass", feature = "replay"))]
use serde::Deserialize;
#[cfg(any(feature = "serial-pass", feature = "trace"))]
use serde::Serialize;
use crate::track::UseExtendError;
use std::{borrow::Cow, fmt, iter, marker::PhantomData, mem, num::NonZeroU32, ops::Range, str};
/// Operation to perform to the output attachment at the start of a renderpass.
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(any(feature = "serial-pass", feature = "trace"), derive(Serialize))]
#[cfg_attr(any(feature = "serial-pass", feature = "replay"), derive(Deserialize))]
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(any(feature = "serial-pass", feature = "trace"), derive(Serialize))]
#[cfg_attr(any(feature = "serial-pass", feature = "replay"), derive(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, PartialEq)]
#[cfg_attr(any(feature = "serial-pass", feature = "trace"), derive(Serialize))]
#[cfg_attr(any(feature = "serial-pass", feature = "replay"), derive(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 attachement 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(any(feature = "serial-pass", feature = "trace"), derive(Serialize))]
#[cfg_attr(any(feature = "serial-pass", feature = "replay"), derive(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(any(feature = "serial-pass", feature = "trace"), derive(Serialize))]
#[cfg_attr(any(feature = "serial-pass", feature = "replay"), derive(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 {
fn is_read_only(&self, aspects: hal::FormatAspects) -> Result<bool, RenderPassErrorInner> {
if aspects.contains(hal::FormatAspects::DEPTH) && !self.depth.read_only {
return Ok(false);
}
if (self.depth.load_op, self.depth.store_op) != (LoadOp::Load, StoreOp::Store) {
return Err(RenderPassErrorInner::InvalidDepthOps);
}
if aspects.contains(hal::FormatAspects::STENCIL) && !self.stencil.read_only {
return Ok(false);
}
if (self.stencil.load_op, self.stencil.store_op) != (LoadOp::Load, StoreOp::Store) {
return Err(RenderPassErrorInner::InvalidStencilOps);
}
Ok(true)
}
}
/// 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, [RenderPassColorAttachment]>,
/// The depth and stencil attachment of the render pass, if any.
pub depth_stencil_attachment: Option<&'a RenderPassDepthStencilAttachment>,
}
#[cfg_attr(feature = "serial-pass", derive(Deserialize, Serialize))]
pub struct RenderPass {
base: BasePass<RenderCommand>,
parent_id: id::CommandEncoderId,
color_targets: ArrayVec<RenderPassColorAttachment, { hal::MAX_COLOR_TARGETS }>,
depth_stencil_target: Option<RenderPassDepthStencilAttachment>,
}
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(),
}
}
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,
}
}
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 {
write!(
f,
"RenderPass {{ encoder_id: {:?}, color_targets: {:?}, depth_stencil_target: {:?}, data: {:?} commands, {:?} dynamic offsets, and {:?} push constant u32s }}",
self.parent_id,
self.color_targets,
self.depth_stencil_target,
self.base.commands.len(),
self.base.dynamic_offsets.len(),
self.base.push_constant_data.len(),
)
}
}
#[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::Valid<id::BufferId>, Range<BufferAddress>)>,
format: Option<IndexFormat>,
pipeline_format: Option<IndexFormat>,
limit: u32,
}
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) as u32
}
None => 0,
}
}
fn reset(&mut self) {
self.bound_buffer_view = None;
self.limit = 0;
}
}
#[derive(Clone, Copy, Debug)]
struct VertexBufferState {
total_size: BufferAddress,
stride: BufferAddress,
rate: VertexStepMode,
bound: bool,
}
impl VertexBufferState {
const EMPTY: Self = Self {
total_size: 0,
stride: 0,
rate: 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: u32,
/// 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: u32,
/// 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) {
self.vertex_limit = u32::MAX;
self.instance_limit = u32::MAX;
for (idx, vbs) in self.inputs.iter().enumerate() {
if vbs.stride == 0 || !vbs.bound {
continue;
}
let limit = (vbs.total_size / vbs.stride) as u32;
match vbs.rate {
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 {
pipeline_flags: PipelineFlags,
binder: Binder,
blend_constant: OptionalState,
stencil_reference: u32,
pipeline: StateChange<id::RenderPipelineId>,
index: IndexState,
vertex: VertexState,
debug_scope_depth: u32,
}
impl State {
fn is_ready(&self, indexed: bool) -> Result<(), DrawError> {
// Determine how many vertex buffers have already been bound
let bound_buffers = self.vertex.inputs.iter().take_while(|v| v.bound).count() as u32;
// Compare with the needed quantity
if bound_buffers < self.vertex.buffers_required {
return Err(DrawError::MissingVertexBuffer {
index: bound_buffers,
});
}
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(),
});
}
if self.pipeline.is_unset() {
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,
});
}
}
}
Ok(())
}
/// Reset the `RenderBundle`-related states.
fn reset_bundle(&mut self) {
self.binder.reset();
self.pipeline.reset();
self.index.reset();
self.vertex.reset();
}
}
/// Error encountered when performing a render pass.
#[derive(Clone, Debug, Error)]
pub enum RenderPassErrorInner {
#[error(transparent)]
Encoder(#[from] CommandEncoderError),
#[error("attachment texture view {0:?} is invalid")]
InvalidAttachment(id::TextureViewId),
#[error("attachment format {0:?} is not a color format")]
InvalidColorAttachmentFormat(wgt::TextureFormat),
#[error("attachment format {0:?} is not a depth-stencil format")]
InvalidDepthStencilAttachmentFormat(wgt::TextureFormat),
#[error("necessary attachments are missing")]
MissingAttachments,
#[error("attachments have differing sizes: {previous:?} is followed by {mismatch:?}")]
AttachmentsDimensionMismatch {
previous: (&'static str, wgt::Extent3d),
mismatch: (&'static str, wgt::Extent3d),
},
#[error("attachment's sample count {0} is invalid")]
InvalidSampleCount(u32),
#[error("attachment with resolve target must be multi-sampled")]
InvalidResolveSourceSampleCount,
#[error("resolve target must have a sample count of 1")]
InvalidResolveTargetSampleCount,
#[error("surface texture is dropped before the render pass is finished")]
SurfaceTextureDropped,
#[error("not enough memory left")]
OutOfMemory,
#[error("unable to clear non-present/read-only depth")]
InvalidDepthOps,
#[error("unable to clear non-present/read-only stencil")]
InvalidStencilOps,
#[error("all attachments must have the same sample count, found {actual} != {expected}")]
SampleCountMismatch { actual: u32, expected: u32 },
#[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 an incompatible read-only depth/stencil flag: bundle is {bundle}, while the pass is {pass}")]
IncompatibleBundleRods { pass: bool, bundle: bool },
#[error(transparent)]
RenderCommand(#[from] RenderCommandError),
#[error(transparent)]
Draw(#[from] DrawError),
#[error(transparent)]
Bind(#[from] BindError),
#[error(transparent)]
QueryUse(#[from] QueryUseError),
}
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");
};
}
}
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())
}
}
/// 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> {
texture_id: &'a Stored<id::TextureId>,
selector: &'a TextureSelector,
usage: hal::TextureUses,
}
impl<A: hal::Api> TextureView<A> {
fn to_render_attachment(&self, usage: hal::TextureUses) -> RenderAttachment {
RenderAttachment {
texture_id: &self.parent_id,
selector: &self.selector,
usage,
}
}
}
const MAX_TOTAL_ATTACHMENTS: usize = hal::MAX_COLOR_TARGETS + hal::MAX_COLOR_TARGETS + 1;
type AttachmentDataVec<T> = ArrayVec<T, MAX_TOTAL_ATTACHMENTS>;
struct RenderPassInfo<'a, A: hal::Api> {
context: RenderPassContext,
trackers: StatefulTrackerSubset,
render_attachments: AttachmentDataVec<RenderAttachment<'a>>,
is_ds_read_only: bool,
extent: wgt::Extent3d,
_phantom: PhantomData<A>,
}
impl<'a, A: HalApi> RenderPassInfo<'a, A> {
fn start(
label: Option<&str>,
color_attachments: &[RenderPassColorAttachment],
depth_stencil_attachment: Option<&RenderPassDepthStencilAttachment>,
cmd_buf: &mut CommandBuffer<A>,
view_guard: &'a Storage<TextureView<A>, id::TextureViewId>,
) -> Result<Self, RenderPassErrorInner> {
profiling::scope!("start", "RenderPassInfo");
// 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_ds_read_only = false;
let mut render_attachments = AttachmentDataVec::<RenderAttachment>::new();
let mut attachment_type_name = "";
let mut extent = None;
let mut sample_count = 0;
let mut add_view = |view: &TextureView<A>, type_name| {
if let Some(ex) = extent {
if ex != view.extent {
return Err(RenderPassErrorInner::AttachmentsDimensionMismatch {
previous: (attachment_type_name, ex),
mismatch: (type_name, view.extent),
});
}
} else {
extent = Some(view.extent);
}
if sample_count == 0 {
sample_count = view.samples;
} else if sample_count != view.samples {
return Err(RenderPassErrorInner::SampleCountMismatch {
actual: view.samples,
expected: sample_count,
});
}
attachment_type_name = type_name;
Ok(())
};
let mut colors = ArrayVec::<hal::ColorAttachment<A>, { hal::MAX_COLOR_TARGETS }>::new();
let mut depth_stencil = None;
if let Some(at) = depth_stencil_attachment {
let view = cmd_buf
.trackers
.views
.use_extend(&*view_guard, at.view, (), ())
.map_err(|_| RenderPassErrorInner::InvalidAttachment(at.view))?;
add_view(view, "depth")?;
let ds_aspects = view.desc.aspects();
if ds_aspects.contains(hal::FormatAspects::COLOR) {
return Err(RenderPassErrorInner::InvalidDepthStencilAttachmentFormat(
view.desc.format,
));
}
let usage = if at.is_read_only(ds_aspects)? {
is_ds_read_only = true;
hal::TextureUses::DEPTH_STENCIL_READ | hal::TextureUses::RESOURCE
} else {
hal::TextureUses::DEPTH_STENCIL_WRITE
};
render_attachments.push(view.to_render_attachment(usage));
depth_stencil = Some(hal::DepthStencilAttachment {
target: hal::Attachment {
view: &view.raw,
usage,
},
depth_ops: at.depth.hal_ops(),
stencil_ops: at.stencil.hal_ops(),
clear_value: (at.depth.clear_value, at.stencil.clear_value),
});
}
for at in color_attachments {
let color_view = cmd_buf
.trackers
.views
.use_extend(&*view_guard, at.view, (), ())
.map_err(|_| RenderPassErrorInner::InvalidAttachment(at.view))?;
add_view(color_view, "color")?;
if !color_view
.desc
.aspects()
.contains(hal::FormatAspects::COLOR)
{
return Err(RenderPassErrorInner::InvalidColorAttachmentFormat(
color_view.desc.format,
));
}
render_attachments
.push(color_view.to_render_attachment(hal::TextureUses::COLOR_TARGET));
let mut hal_resolve_target = None;
if let Some(resolve_target) = at.resolve_target {
let resolve_view = cmd_buf
.trackers
.views
.use_extend(&*view_guard, resolve_target, (), ())
.map_err(|_| RenderPassErrorInner::InvalidAttachment(resolve_target))?;
if color_view.extent != resolve_view.extent {
return Err(RenderPassErrorInner::AttachmentsDimensionMismatch {
previous: (attachment_type_name, extent.unwrap_or_default()),
mismatch: ("resolve", resolve_view.extent),
});
}
if color_view.samples == 1 {
return Err(RenderPassErrorInner::InvalidResolveSourceSampleCount);
}
if resolve_view.samples != 1 {
return Err(RenderPassErrorInner::InvalidResolveTargetSampleCount);
}
render_attachments
.push(resolve_view.to_render_attachment(hal::TextureUses::COLOR_TARGET));
hal_resolve_target = Some(hal::Attachment {
view: &resolve_view.raw,
usage: hal::TextureUses::COLOR_TARGET,
});
}
colors.push(hal::ColorAttachment {
target: hal::Attachment {
view: &color_view.raw,
usage: hal::TextureUses::COLOR_TARGET,
},
resolve_target: hal_resolve_target,
ops: at.channel.hal_ops(),
clear_value: at.channel.clear_value,
});
}
if sample_count != 1 && sample_count != 4 {
return Err(RenderPassErrorInner::InvalidSampleCount(sample_count));
}
let view_data = AttachmentData {
colors: color_attachments
.iter()
.map(|at| view_guard.get(at.view).unwrap())
.collect(),
resolves: color_attachments
.iter()
.filter_map(|at| at.resolve_target)
.map(|attachment| view_guard.get(attachment).unwrap())
.collect(),
depth_stencil: depth_stencil_attachment.map(|at| view_guard.get(at.view).unwrap()),
};
let extent = extent.ok_or(RenderPassErrorInner::MissingAttachments)?;
let context = RenderPassContext {
attachments: view_data.map(|view| view.desc.format),
sample_count,
};
let hal_desc = hal::RenderPassDescriptor {
label,
extent,
sample_count,
color_attachments: &colors,
depth_stencil_attachment: depth_stencil,
};
unsafe {
cmd_buf.encoder.raw.begin_render_pass(&hal_desc);
};
Ok(Self {
context,
trackers: StatefulTrackerSubset::new(A::VARIANT),
render_attachments,
is_ds_read_only,
extent,
_phantom: PhantomData,
})
}
fn finish(
mut self,
raw: &mut A::CommandEncoder,
texture_guard: &Storage<Texture<A>, id::TextureId>,
) -> Result<StatefulTrackerSubset, RenderPassErrorInner> {
profiling::scope!("finish", "RenderPassInfo");
unsafe {
raw.end_render_pass();
}
for ra in self.render_attachments {
if !texture_guard.contains(ra.texture_id.value.0) {
return Err(RenderPassErrorInner::SurfaceTextureDropped);
}
let texture = &texture_guard[ra.texture_id.value];
check_texture_usage(texture.desc.usage, TextureUsages::RENDER_ATTACHMENT)?;
// the tracker set of the pass is always in "extend" mode
self.trackers
.textures
.change_extend(
ra.texture_id.value,
&ra.texture_id.ref_count,
ra.selector.clone(),
ra.usage,
)
.map_err(UsageConflict::from)?;
}
Ok(self.trackers)
}
}
// Common routines between render/compute
impl<G: GlobalIdentityHandlerFactory> Global<G> {
pub fn command_encoder_run_render_pass<A: HalApi>(
&self,
encoder_id: id::CommandEncoderId,
pass: &RenderPass,
) -> Result<(), RenderPassError> {
self.command_encoder_run_render_pass_impl::<A>(
encoder_id,
pass.base.as_ref(),
&pass.color_targets,
pass.depth_stencil_target.as_ref(),
)
}
#[doc(hidden)]
pub fn command_encoder_run_render_pass_impl<A: HalApi>(
&self,
encoder_id: id::CommandEncoderId,
base: BasePassRef<RenderCommand>,
color_attachments: &[RenderPassColorAttachment],
depth_stencil_attachment: Option<&RenderPassDepthStencilAttachment>,
) -> Result<(), RenderPassError> {
profiling::scope!("run_render_pass", "CommandEncoder");
let scope = PassErrorScope::Pass(encoder_id);
let hub = A::hub(self);
let mut token = Token::root();
let (device_guard, mut token) = hub.devices.read(&mut token);
let (pass_raw, trackers, query_reset_state) = {
let (mut cmb_guard, mut token) = hub.command_buffers.write(&mut token);
let cmd_buf =
CommandBuffer::get_encoder_mut(&mut *cmb_guard, encoder_id).map_pass_err(scope)?;
// close everything while the new command encoder is filled
cmd_buf.encoder.close();
// will be reset to true if recording is done without errors
cmd_buf.status = CommandEncoderStatus::Error;
#[cfg(feature = "trace")]
if let Some(ref mut list) = cmd_buf.commands {
list.push(crate::device::trace::Command::RunRenderPass {
base: BasePass::from_ref(base),
target_colors: color_attachments.to_vec(),
target_depth_stencil: depth_stencil_attachment.cloned(),
});
}
let device = &device_guard[cmd_buf.device_id.value];
unsafe {
cmd_buf.encoder.raw.begin_encoding(base.label).unwrap() //TODO: handle this better
};
let (bundle_guard, mut token) = hub.render_bundles.read(&mut token);
let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token);
let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token);
let (pipeline_guard, mut token) = hub.render_pipelines.read(&mut token);
let (query_set_guard, mut token) = hub.query_sets.read(&mut token);
let (buffer_guard, mut token) = hub.buffers.read(&mut token);
let (texture_guard, mut token) = hub.textures.read(&mut token);
let (view_guard, _) = hub.texture_views.read(&mut token);
log::trace!(
"Encoding render pass begin in command buffer {:?}",
encoder_id
);
let mut info = RenderPassInfo::start(
base.label,
color_attachments,
depth_stencil_attachment,
cmd_buf,
&*view_guard,
)
.map_pass_err(scope)?;
let raw = &mut cmd_buf.encoder.raw;
let mut state = State {
pipeline_flags: PipelineFlags::empty(),
binder: Binder::new(),
blend_constant: OptionalState::Unused,
stencil_reference: 0,
pipeline: StateChange::new(),
index: IndexState::default(),
vertex: VertexState::default(),
debug_scope_depth: 0,
};
let mut temp_offsets = Vec::new();
let mut dynamic_offset_count = 0;
let mut string_offset = 0;
let mut active_query = None;
let mut query_reset_state = QueryResetMap::new();
for command in base.commands {
match *command {
RenderCommand::SetBindGroup {
index,
num_dynamic_offsets,
bind_group_id,
} => {
let scope = PassErrorScope::SetBindGroup(bind_group_id);
let max_bind_groups = device.limits.max_bind_groups;
if (index as u32) >= max_bind_groups {
return Err(RenderCommandError::BindGroupIndexOutOfRange {
index,
max: max_bind_groups,
})
.map_pass_err(scope);
}
temp_offsets.clear();
temp_offsets.extend_from_slice(
&base.dynamic_offsets[dynamic_offset_count
..dynamic_offset_count + (num_dynamic_offsets as usize)],
);
dynamic_offset_count += num_dynamic_offsets as usize;
let bind_group = cmd_buf
.trackers
.bind_groups
.use_extend(&*bind_group_guard, bind_group_id, (), ())
.map_err(|_| RenderCommandError::InvalidBindGroup(bind_group_id))
.map_pass_err(scope)?;
bind_group
.validate_dynamic_bindings(&temp_offsets, &cmd_buf.limits)
.map_pass_err(scope)?;
// merge the resource tracker in
info.trackers
.merge_extend(&bind_group.used)
.map_pass_err(scope)?;
//Note: stateless trackers are not merged: the lifetime reference
// is held to the bind group itself.
cmd_buf.buffer_memory_init_actions.extend(
bind_group.used_buffer_ranges.iter().filter_map(|action| {
match buffer_guard.get(action.id) {
Ok(buffer) => buffer.initialization_status.check_action(action),
Err(_) => None,
}
}),
);
let pipeline_layout_id = state.binder.pipeline_layout_id;
let entries = state.binder.assign_group(
index as usize,
id::Valid(bind_group_id),
bind_group,
&temp_offsets,
);
if !entries.is_empty() {
let pipeline_layout =
&pipeline_layout_guard[pipeline_layout_id.unwrap()].raw;
for (i, e) in entries.iter().enumerate() {
let raw_bg =
&bind_group_guard[e.group_id.as_ref().unwrap().value].raw;
unsafe {
raw.set_bind_group(
pipeline_layout,
index as u32 + i as u32,
raw_bg,
&e.dynamic_offsets,
);
}
}
}
}
RenderCommand::SetPipeline(pipeline_id) => {
let scope = PassErrorScope::SetPipelineRender(pipeline_id);
if state.pipeline.set_and_check_redundant(pipeline_id) {
continue;
}
let pipeline = cmd_buf
.trackers
.render_pipes
.use_extend(&*pipeline_guard, pipeline_id, (), ())
.map_err(|_| RenderCommandError::InvalidPipeline(pipeline_id))
.map_pass_err(scope)?;
info.context
.check_compatible(&pipeline.pass_context)
.map_err(RenderCommandError::IncompatiblePipelineTargets)
.map_pass_err(scope)?;
state.pipeline_flags = pipeline.flags;
if pipeline.flags.contains(PipelineFlags::WRITES_DEPTH_STENCIL)
&& info.is_ds_read_only
{
return Err(RenderCommandError::IncompatiblePipelineRods)
.map_pass_err(scope);
}
state
.blend_constant
.require(pipeline.flags.contains(PipelineFlags::BLEND_CONSTANT));
unsafe {
raw.set_render_pipeline(&pipeline.raw);
}
if pipeline.flags.contains(PipelineFlags::STENCIL_REFERENCE) {
unsafe {
raw.set_stencil_reference(state.stencil_reference);
}
}
// Rebind resource
if state.binder.pipeline_layout_id != Some(pipeline.layout_id.value) {
let pipeline_layout = &pipeline_layout_guard[pipeline.layout_id.value];
let (start_index, entries) = state.binder.change_pipeline_layout(
&*pipeline_layout_guard,
pipeline.layout_id.value,
);
if !entries.is_empty() {
for (i, e) in entries.iter().enumerate() {
let raw_bg =
&bind_group_guard[e.group_id.as_ref().unwrap().value].raw;
unsafe {
raw.set_bind_group(
&pipeline_layout.raw,
start_index as u32 + i as u32,
raw_bg,
&e.dynamic_offsets,
);
}
}
}
// Clear push constant ranges
let non_overlapping = super::bind::compute_nonoverlapping_ranges(
&pipeline_layout.push_constant_ranges,
);
for range in non_overlapping {
let offset = range.range.start;
let size_bytes = range.range.end - offset;