forked from IceSentry/bevy
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgpu_preprocessing.rs
More file actions
2140 lines (1957 loc) · 82.8 KB
/
gpu_preprocessing.rs
File metadata and controls
2140 lines (1957 loc) · 82.8 KB
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
//! Batching functionality when GPU preprocessing is in use.
use core::{any::TypeId, marker::PhantomData, mem};
use bevy_app::{App, Plugin};
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
prelude::Entity,
query::{Has, With},
resource::Resource,
schedule::IntoScheduleConfigs as _,
system::{Query, Res, ResMut, StaticSystemParam},
world::{FromWorld, World},
};
use bevy_encase_derive::ShaderType;
use bevy_math::UVec4;
use bevy_platform::collections::{hash_map::Entry, HashMap, HashSet};
use bevy_utils::{default, TypeIdMap};
use bytemuck::{Pod, Zeroable};
use encase::{internal::WriteInto, ShaderSize};
use indexmap::IndexMap;
use nonmax::NonMaxU32;
use tracing::{error, info};
use wgpu::{BindingResource, BufferUsages, DownlevelFlags, Features};
use crate::{
experimental::occlusion_culling::OcclusionCulling,
render_phase::{
BinnedPhaseItem, BinnedRenderPhaseBatch, BinnedRenderPhaseBatchSet,
BinnedRenderPhaseBatchSets, CachedRenderPipelinePhaseItem, PhaseItem,
PhaseItemBatchSetKey as _, PhaseItemExtraIndex, RenderBin, SortedPhaseItem,
SortedRenderPhase, UnbatchableBinnedEntityIndices, ViewBinnedRenderPhases,
ViewSortedRenderPhases,
},
render_resource::{Buffer, GpuArrayBufferable, RawBufferVec, UninitBufferVec},
renderer::{RenderAdapter, RenderAdapterInfo, RenderDevice, RenderQueue, WgpuWrapper},
sync_world::MainEntity,
view::{ExtractedView, NoIndirectDrawing, RetainedViewEntity},
Render, RenderApp, RenderDebugFlags, RenderSystems,
};
use super::{BatchMeta, GetBatchData, GetFullBatchData};
#[derive(Default)]
pub struct BatchingPlugin {
/// Debugging flags that can optionally be set when constructing the renderer.
pub debug_flags: RenderDebugFlags,
}
impl Plugin for BatchingPlugin {
fn build(&self, app: &mut App) {
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app
.insert_resource(IndirectParametersBuffers::new(
self.debug_flags
.contains(RenderDebugFlags::ALLOW_COPIES_FROM_INDIRECT_PARAMETERS),
))
.add_systems(
Render,
write_indirect_parameters_buffers.in_set(RenderSystems::PrepareResourcesFlush),
)
.add_systems(
Render,
clear_indirect_parameters_buffers.in_set(RenderSystems::ManageViews),
);
}
fn finish(&self, app: &mut App) {
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app.init_resource::<GpuPreprocessingSupport>();
}
}
/// Records whether GPU preprocessing and/or GPU culling are supported on the
/// device.
///
/// No GPU preprocessing is supported on WebGL because of the lack of compute
/// shader support. GPU preprocessing is supported on DirectX 12, but due to [a
/// `wgpu` limitation] GPU culling is not.
///
/// [a `wgpu` limitation]: https://github.com/gfx-rs/wgpu/issues/2471
#[derive(Clone, Copy, PartialEq, Resource)]
pub struct GpuPreprocessingSupport {
/// The maximum amount of GPU preprocessing available on this platform.
pub max_supported_mode: GpuPreprocessingMode,
}
impl GpuPreprocessingSupport {
/// Returns true if this GPU preprocessing support level isn't `None`.
#[inline]
pub fn is_available(&self) -> bool {
self.max_supported_mode != GpuPreprocessingMode::None
}
/// Returns the given GPU preprocessing mode, capped to the current
/// preprocessing mode.
pub fn min(&self, mode: GpuPreprocessingMode) -> GpuPreprocessingMode {
match (self.max_supported_mode, mode) {
(GpuPreprocessingMode::None, _) | (_, GpuPreprocessingMode::None) => {
GpuPreprocessingMode::None
}
(mode, GpuPreprocessingMode::Culling) | (GpuPreprocessingMode::Culling, mode) => mode,
(GpuPreprocessingMode::PreprocessingOnly, GpuPreprocessingMode::PreprocessingOnly) => {
GpuPreprocessingMode::PreprocessingOnly
}
}
}
/// Returns true if GPU culling is supported on this platform.
pub fn is_culling_supported(&self) -> bool {
self.max_supported_mode == GpuPreprocessingMode::Culling
}
}
/// The amount of GPU preprocessing (compute and indirect draw) that we do.
#[derive(Clone, Copy, PartialEq)]
pub enum GpuPreprocessingMode {
/// No GPU preprocessing is in use at all.
///
/// This is used when GPU compute isn't available.
None,
/// GPU preprocessing is in use, but GPU culling isn't.
///
/// This is used when the [`NoIndirectDrawing`] component is present on the
/// camera.
PreprocessingOnly,
/// Both GPU preprocessing and GPU culling are in use.
///
/// This is used by default.
Culling,
}
/// The GPU buffers holding the data needed to render batches.
///
/// For example, in the 3D PBR pipeline this holds `MeshUniform`s, which are the
/// `BD` type parameter in that mode.
///
/// We have a separate *buffer data input* type (`BDI`) here, which a compute
/// shader is expected to expand to the full buffer data (`BD`) type. GPU
/// uniform building is generally faster and uses less system RAM to VRAM bus
/// bandwidth, but only implemented for some pipelines (for example, not in the
/// 2D pipeline at present) and only when compute shader is available.
#[derive(Resource)]
pub struct BatchedInstanceBuffers<BD, BDI>
where
BD: GpuArrayBufferable + Sync + Send + 'static,
BDI: Pod + Default,
{
/// The uniform data inputs for the current frame.
///
/// These are uploaded during the extraction phase.
pub current_input_buffer: InstanceInputUniformBuffer<BDI>,
/// The uniform data inputs for the previous frame.
///
/// The indices don't generally line up between `current_input_buffer`
/// and `previous_input_buffer`, because, among other reasons, entities
/// can spawn or despawn between frames. Instead, each current buffer
/// data input uniform is expected to contain the index of the
/// corresponding buffer data input uniform in this list.
pub previous_input_buffer: InstanceInputUniformBuffer<BDI>,
/// The data needed to render buffers for each phase.
///
/// The keys of this map are the type IDs of each phase: e.g. `Opaque3d`,
/// `AlphaMask3d`, etc.
pub phase_instance_buffers: TypeIdMap<UntypedPhaseBatchedInstanceBuffers<BD>>,
}
impl<BD, BDI> Default for BatchedInstanceBuffers<BD, BDI>
where
BD: GpuArrayBufferable + Sync + Send + 'static,
BDI: Pod + Sync + Send + Default + 'static,
{
fn default() -> Self {
BatchedInstanceBuffers {
current_input_buffer: InstanceInputUniformBuffer::new(),
previous_input_buffer: InstanceInputUniformBuffer::new(),
phase_instance_buffers: HashMap::default(),
}
}
}
/// The GPU buffers holding the data needed to render batches for a single
/// phase.
///
/// These are split out per phase so that we can run the phases in parallel.
/// This is the version of the structure that has a type parameter, which
/// enables Bevy's scheduler to run the batching operations for the different
/// phases in parallel.
///
/// See the documentation for [`BatchedInstanceBuffers`] for more information.
#[derive(Resource)]
pub struct PhaseBatchedInstanceBuffers<PI, BD>
where
PI: PhaseItem,
BD: GpuArrayBufferable + Sync + Send + 'static,
{
/// The buffers for this phase.
pub buffers: UntypedPhaseBatchedInstanceBuffers<BD>,
phantom: PhantomData<PI>,
}
impl<PI, BD> Default for PhaseBatchedInstanceBuffers<PI, BD>
where
PI: PhaseItem,
BD: GpuArrayBufferable + Sync + Send + 'static,
{
fn default() -> Self {
PhaseBatchedInstanceBuffers {
buffers: UntypedPhaseBatchedInstanceBuffers::default(),
phantom: PhantomData,
}
}
}
/// The GPU buffers holding the data needed to render batches for a single
/// phase, without a type parameter for that phase.
///
/// Since this structure doesn't have a type parameter, it can be placed in
/// [`BatchedInstanceBuffers::phase_instance_buffers`].
pub struct UntypedPhaseBatchedInstanceBuffers<BD>
where
BD: GpuArrayBufferable + Sync + Send + 'static,
{
/// A storage area for the buffer data that the GPU compute shader is
/// expected to write to.
///
/// There will be one entry for each index.
pub data_buffer: UninitBufferVec<BD>,
/// The index of the buffer data in the current input buffer that
/// corresponds to each instance.
///
/// This is keyed off each view. Each view has a separate buffer.
pub work_item_buffers: HashMap<RetainedViewEntity, PreprocessWorkItemBuffers>,
/// A buffer that holds the number of indexed meshes that weren't visible in
/// the previous frame, when GPU occlusion culling is in use.
///
/// There's one set of [`LatePreprocessWorkItemIndirectParameters`] per
/// view. Bevy uses this value to determine how many threads to dispatch to
/// check meshes that weren't visible next frame to see if they became newly
/// visible this frame.
pub late_indexed_indirect_parameters_buffer:
RawBufferVec<LatePreprocessWorkItemIndirectParameters>,
/// A buffer that holds the number of non-indexed meshes that weren't
/// visible in the previous frame, when GPU occlusion culling is in use.
///
/// There's one set of [`LatePreprocessWorkItemIndirectParameters`] per
/// view. Bevy uses this value to determine how many threads to dispatch to
/// check meshes that weren't visible next frame to see if they became newly
/// visible this frame.
pub late_non_indexed_indirect_parameters_buffer:
RawBufferVec<LatePreprocessWorkItemIndirectParameters>,
}
/// Holds the GPU buffer of instance input data, which is the data about each
/// mesh instance that the CPU provides.
///
/// `BDI` is the *buffer data input* type, which the GPU mesh preprocessing
/// shader is expected to expand to the full *buffer data* type.
pub struct InstanceInputUniformBuffer<BDI>
where
BDI: Pod + Default,
{
/// The buffer containing the data that will be uploaded to the GPU.
buffer: RawBufferVec<BDI>,
/// Indices of slots that are free within the buffer.
///
/// When adding data, we preferentially overwrite these slots first before
/// growing the buffer itself.
free_uniform_indices: Vec<u32>,
}
impl<BDI> InstanceInputUniformBuffer<BDI>
where
BDI: Pod + Default,
{
/// Creates a new, empty buffer.
pub fn new() -> InstanceInputUniformBuffer<BDI> {
InstanceInputUniformBuffer {
buffer: RawBufferVec::new(BufferUsages::STORAGE),
free_uniform_indices: vec![],
}
}
/// Clears the buffer and entity list out.
pub fn clear(&mut self) {
self.buffer.clear();
self.free_uniform_indices.clear();
}
/// Returns the [`RawBufferVec`] corresponding to this input uniform buffer.
#[inline]
pub fn buffer(&self) -> &RawBufferVec<BDI> {
&self.buffer
}
/// Adds a new piece of buffered data to the uniform buffer and returns its
/// index.
pub fn add(&mut self, element: BDI) -> u32 {
match self.free_uniform_indices.pop() {
Some(uniform_index) => {
self.buffer.values_mut()[uniform_index as usize] = element;
uniform_index
}
None => self.buffer.push(element) as u32,
}
}
/// Removes a piece of buffered data from the uniform buffer.
///
/// This simply marks the data as free.
pub fn remove(&mut self, uniform_index: u32) {
self.free_uniform_indices.push(uniform_index);
}
/// Returns the piece of buffered data at the given index.
///
/// Returns [`None`] if the index is out of bounds or the data is removed.
pub fn get(&self, uniform_index: u32) -> Option<BDI> {
if (uniform_index as usize) >= self.buffer.len()
|| self.free_uniform_indices.contains(&uniform_index)
{
None
} else {
Some(self.get_unchecked(uniform_index))
}
}
/// Returns the piece of buffered data at the given index.
/// Can return data that has previously been removed.
///
/// # Panics
/// if `uniform_index` is not in bounds of [`Self::buffer`].
pub fn get_unchecked(&self, uniform_index: u32) -> BDI {
self.buffer.values()[uniform_index as usize]
}
/// Stores a piece of buffered data at the given index.
///
/// # Panics
/// if `uniform_index` is not in bounds of [`Self::buffer`].
pub fn set(&mut self, uniform_index: u32, element: BDI) {
self.buffer.values_mut()[uniform_index as usize] = element;
}
// Ensures that the buffers are nonempty, which the GPU requires before an
// upload can take place.
pub fn ensure_nonempty(&mut self) {
if self.buffer.is_empty() {
self.buffer.push(default());
}
}
/// Returns the number of instances in this buffer.
pub fn len(&self) -> usize {
self.buffer.len()
}
/// Returns true if this buffer has no instances or false if it contains any
/// instances.
pub fn is_empty(&self) -> bool {
self.buffer.is_empty()
}
/// Consumes this [`InstanceInputUniformBuffer`] and returns the raw buffer
/// ready to be uploaded to the GPU.
pub fn into_buffer(self) -> RawBufferVec<BDI> {
self.buffer
}
}
impl<BDI> Default for InstanceInputUniformBuffer<BDI>
where
BDI: Pod + Default,
{
fn default() -> Self {
Self::new()
}
}
/// The buffer of GPU preprocessing work items for a single view.
#[cfg_attr(
not(target_arch = "wasm32"),
expect(
clippy::large_enum_variant,
reason = "See https://github.com/bevyengine/bevy/issues/19220"
)
)]
pub enum PreprocessWorkItemBuffers {
/// The work items we use if we aren't using indirect drawing.
///
/// Because we don't have to separate indexed from non-indexed meshes in
/// direct mode, we only have a single buffer here.
Direct(RawBufferVec<PreprocessWorkItem>),
/// The buffer of work items we use if we are using indirect drawing.
///
/// We need to separate out indexed meshes from non-indexed meshes in this
/// case because the indirect parameters for these two types of meshes have
/// different sizes.
Indirect {
/// The buffer of work items corresponding to indexed meshes.
indexed: RawBufferVec<PreprocessWorkItem>,
/// The buffer of work items corresponding to non-indexed meshes.
non_indexed: RawBufferVec<PreprocessWorkItem>,
/// The work item buffers we use when GPU occlusion culling is in use.
gpu_occlusion_culling: Option<GpuOcclusionCullingWorkItemBuffers>,
},
}
/// The work item buffers we use when GPU occlusion culling is in use.
pub struct GpuOcclusionCullingWorkItemBuffers {
/// The buffer of work items corresponding to indexed meshes.
pub late_indexed: UninitBufferVec<PreprocessWorkItem>,
/// The buffer of work items corresponding to non-indexed meshes.
pub late_non_indexed: UninitBufferVec<PreprocessWorkItem>,
/// The offset into the
/// [`UntypedPhaseBatchedInstanceBuffers::late_indexed_indirect_parameters_buffer`]
/// where this view's indirect dispatch counts for indexed meshes live.
pub late_indirect_parameters_indexed_offset: u32,
/// The offset into the
/// [`UntypedPhaseBatchedInstanceBuffers::late_non_indexed_indirect_parameters_buffer`]
/// where this view's indirect dispatch counts for non-indexed meshes live.
pub late_indirect_parameters_non_indexed_offset: u32,
}
/// A GPU-side data structure that stores the number of workgroups to dispatch
/// for the second phase of GPU occlusion culling.
///
/// The late mesh preprocessing phase checks meshes that weren't visible frame
/// to determine if they're potentially visible this frame.
#[derive(Clone, Copy, ShaderType, Pod, Zeroable)]
#[repr(C)]
pub struct LatePreprocessWorkItemIndirectParameters {
/// The number of workgroups to dispatch.
///
/// This will be equal to `work_item_count / 64`, rounded *up*.
dispatch_x: u32,
/// The number of workgroups along the abstract Y axis to dispatch: always
/// 1.
dispatch_y: u32,
/// The number of workgroups along the abstract Z axis to dispatch: always
/// 1.
dispatch_z: u32,
/// The actual number of work items.
///
/// The GPU indirect dispatch doesn't read this, but it's used internally to
/// determine the actual number of work items that exist in the late
/// preprocessing work item buffer.
work_item_count: u32,
/// Padding to 64-byte boundaries for some hardware.
pad: UVec4,
}
impl Default for LatePreprocessWorkItemIndirectParameters {
fn default() -> LatePreprocessWorkItemIndirectParameters {
LatePreprocessWorkItemIndirectParameters {
dispatch_x: 0,
dispatch_y: 1,
dispatch_z: 1,
work_item_count: 0,
pad: default(),
}
}
}
/// Returns the set of work item buffers for the given view, first creating it
/// if necessary.
///
/// Bevy uses work item buffers to tell the mesh preprocessing compute shader
/// which meshes are to be drawn.
///
/// You may need to call this function if you're implementing your own custom
/// render phases. See the `specialized_mesh_pipeline` example.
pub fn get_or_create_work_item_buffer<'a, I>(
work_item_buffers: &'a mut HashMap<RetainedViewEntity, PreprocessWorkItemBuffers>,
view: RetainedViewEntity,
no_indirect_drawing: bool,
enable_gpu_occlusion_culling: bool,
) -> &'a mut PreprocessWorkItemBuffers
where
I: 'static,
{
let preprocess_work_item_buffers = match work_item_buffers.entry(view) {
Entry::Occupied(occupied_entry) => occupied_entry.into_mut(),
Entry::Vacant(vacant_entry) => {
if no_indirect_drawing {
vacant_entry.insert(PreprocessWorkItemBuffers::Direct(RawBufferVec::new(
BufferUsages::STORAGE,
)))
} else {
vacant_entry.insert(PreprocessWorkItemBuffers::Indirect {
indexed: RawBufferVec::new(BufferUsages::STORAGE),
non_indexed: RawBufferVec::new(BufferUsages::STORAGE),
// We fill this in below if `enable_gpu_occlusion_culling`
// is set.
gpu_occlusion_culling: None,
})
}
}
};
// Initialize the GPU occlusion culling buffers if necessary.
if let PreprocessWorkItemBuffers::Indirect {
ref mut gpu_occlusion_culling,
..
} = *preprocess_work_item_buffers
{
match (
enable_gpu_occlusion_culling,
gpu_occlusion_culling.is_some(),
) {
(false, false) | (true, true) => {}
(false, true) => {
*gpu_occlusion_culling = None;
}
(true, false) => {
*gpu_occlusion_culling = Some(GpuOcclusionCullingWorkItemBuffers {
late_indexed: UninitBufferVec::new(BufferUsages::STORAGE),
late_non_indexed: UninitBufferVec::new(BufferUsages::STORAGE),
late_indirect_parameters_indexed_offset: 0,
late_indirect_parameters_non_indexed_offset: 0,
});
}
}
}
preprocess_work_item_buffers
}
/// Initializes work item buffers for a phase in preparation for a new frame.
pub fn init_work_item_buffers(
work_item_buffers: &mut PreprocessWorkItemBuffers,
late_indexed_indirect_parameters_buffer: &'_ mut RawBufferVec<
LatePreprocessWorkItemIndirectParameters,
>,
late_non_indexed_indirect_parameters_buffer: &'_ mut RawBufferVec<
LatePreprocessWorkItemIndirectParameters,
>,
) {
// Add the offsets for indirect parameters that the late phase of mesh
// preprocessing writes to.
if let PreprocessWorkItemBuffers::Indirect {
gpu_occlusion_culling:
Some(GpuOcclusionCullingWorkItemBuffers {
ref mut late_indirect_parameters_indexed_offset,
ref mut late_indirect_parameters_non_indexed_offset,
..
}),
..
} = *work_item_buffers
{
*late_indirect_parameters_indexed_offset = late_indexed_indirect_parameters_buffer
.push(LatePreprocessWorkItemIndirectParameters::default())
as u32;
*late_indirect_parameters_non_indexed_offset = late_non_indexed_indirect_parameters_buffer
.push(LatePreprocessWorkItemIndirectParameters::default())
as u32;
}
}
impl PreprocessWorkItemBuffers {
/// Adds a new work item to the appropriate buffer.
///
/// `indexed` specifies whether the work item corresponds to an indexed
/// mesh.
pub fn push(&mut self, indexed: bool, preprocess_work_item: PreprocessWorkItem) {
match *self {
PreprocessWorkItemBuffers::Direct(ref mut buffer) => {
buffer.push(preprocess_work_item);
}
PreprocessWorkItemBuffers::Indirect {
indexed: ref mut indexed_buffer,
non_indexed: ref mut non_indexed_buffer,
ref mut gpu_occlusion_culling,
} => {
if indexed {
indexed_buffer.push(preprocess_work_item);
} else {
non_indexed_buffer.push(preprocess_work_item);
}
if let Some(ref mut gpu_occlusion_culling) = *gpu_occlusion_culling {
if indexed {
gpu_occlusion_culling.late_indexed.add();
} else {
gpu_occlusion_culling.late_non_indexed.add();
}
}
}
}
}
/// Clears out the GPU work item buffers in preparation for a new frame.
pub fn clear(&mut self) {
match *self {
PreprocessWorkItemBuffers::Direct(ref mut buffer) => {
buffer.clear();
}
PreprocessWorkItemBuffers::Indirect {
indexed: ref mut indexed_buffer,
non_indexed: ref mut non_indexed_buffer,
ref mut gpu_occlusion_culling,
} => {
indexed_buffer.clear();
non_indexed_buffer.clear();
if let Some(ref mut gpu_occlusion_culling) = *gpu_occlusion_culling {
gpu_occlusion_culling.late_indexed.clear();
gpu_occlusion_culling.late_non_indexed.clear();
gpu_occlusion_culling.late_indirect_parameters_indexed_offset = 0;
gpu_occlusion_culling.late_indirect_parameters_non_indexed_offset = 0;
}
}
}
}
}
/// One invocation of the preprocessing shader: i.e. one mesh instance in a
/// view.
#[derive(Clone, Copy, Default, Pod, Zeroable, ShaderType)]
#[repr(C)]
pub struct PreprocessWorkItem {
/// The index of the batch input data in the input buffer that the shader
/// reads from.
pub input_index: u32,
/// In direct mode, the index of the mesh uniform; in indirect mode, the
/// index of the [`IndirectParametersGpuMetadata`].
///
/// In indirect mode, this is the index of the
/// [`IndirectParametersGpuMetadata`] in the
/// `IndirectParametersBuffers::indexed_metadata` or
/// `IndirectParametersBuffers::non_indexed_metadata`.
pub output_or_indirect_parameters_index: u32,
}
/// The `wgpu` indirect parameters structure that specifies a GPU draw command.
///
/// This is the variant for indexed meshes. We generate the instances of this
/// structure in the `build_indirect_params.wgsl` compute shader.
#[derive(Clone, Copy, Debug, Pod, Zeroable, ShaderType)]
#[repr(C)]
pub struct IndirectParametersIndexed {
/// The number of indices that this mesh has.
pub index_count: u32,
/// The number of instances we are to draw.
pub instance_count: u32,
/// The offset of the first index for this mesh in the index buffer slab.
pub first_index: u32,
/// The offset of the first vertex for this mesh in the vertex buffer slab.
pub base_vertex: u32,
/// The index of the first mesh instance in the `MeshUniform` buffer.
pub first_instance: u32,
}
/// The `wgpu` indirect parameters structure that specifies a GPU draw command.
///
/// This is the variant for non-indexed meshes. We generate the instances of
/// this structure in the `build_indirect_params.wgsl` compute shader.
#[derive(Clone, Copy, Debug, Pod, Zeroable, ShaderType)]
#[repr(C)]
pub struct IndirectParametersNonIndexed {
/// The number of vertices that this mesh has.
pub vertex_count: u32,
/// The number of instances we are to draw.
pub instance_count: u32,
/// The offset of the first vertex for this mesh in the vertex buffer slab.
pub base_vertex: u32,
/// The index of the first mesh instance in the `Mesh` buffer.
pub first_instance: u32,
}
/// A structure, initialized on CPU and read on GPU, that contains metadata
/// about each batch.
///
/// Each batch will have one instance of this structure.
#[derive(Clone, Copy, Default, Pod, Zeroable, ShaderType)]
#[repr(C)]
pub struct IndirectParametersCpuMetadata {
/// The index of the first instance of this mesh in the array of
/// `MeshUniform`s.
///
/// Note that this is the *first* output index in this batch. Since each
/// instance of this structure refers to arbitrarily many instances, the
/// `MeshUniform`s corresponding to this batch span the indices
/// `base_output_index..(base_output_index + instance_count)`.
pub base_output_index: u32,
/// The index of the batch set that this batch belongs to in the
/// [`IndirectBatchSet`] buffer.
///
/// A *batch set* is a set of meshes that may be multi-drawn together.
/// Multiple batches (and therefore multiple instances of
/// [`IndirectParametersGpuMetadata`] structures) can be part of the same
/// batch set.
pub batch_set_index: u32,
}
/// A structure, written and read GPU, that records how many instances of each
/// mesh are actually to be drawn.
///
/// The GPU mesh preprocessing shader increments the
/// [`Self::early_instance_count`] and [`Self::late_instance_count`] as it
/// determines that meshes are visible. The indirect parameter building shader
/// reads this metadata in order to construct the indirect draw parameters.
///
/// Each batch will have one instance of this structure.
#[derive(Clone, Copy, Default, Pod, Zeroable, ShaderType)]
#[repr(C)]
pub struct IndirectParametersGpuMetadata {
/// The index of the first mesh in this batch in the array of
/// `MeshInputUniform`s.
pub mesh_index: u32,
/// The number of instances that were judged visible last frame.
///
/// The CPU sets this value to 0, and the GPU mesh preprocessing shader
/// increments it as it culls mesh instances.
pub early_instance_count: u32,
/// The number of instances that have been judged potentially visible this
/// frame that weren't in the last frame's potentially visible set.
///
/// The CPU sets this value to 0, and the GPU mesh preprocessing shader
/// increments it as it culls mesh instances.
pub late_instance_count: u32,
}
/// A structure, shared between CPU and GPU, that holds the number of on-GPU
/// indirect draw commands for each *batch set*.
///
/// A *batch set* is a set of meshes that may be multi-drawn together.
///
/// If the current hardware and driver support `multi_draw_indirect_count`, the
/// indirect parameters building shader increments
/// [`Self::indirect_parameters_count`] as it generates indirect parameters. The
/// `multi_draw_indirect_count` command reads
/// [`Self::indirect_parameters_count`] in order to determine how many commands
/// belong to each batch set.
#[derive(Clone, Copy, Default, Pod, Zeroable, ShaderType)]
#[repr(C)]
pub struct IndirectBatchSet {
/// The number of indirect parameter commands (i.e. batches) in this batch
/// set.
///
/// The CPU sets this value to 0 before uploading this structure to GPU. The
/// indirect parameters building shader increments this value as it creates
/// indirect parameters. Then the `multi_draw_indirect_count` command reads
/// this value in order to determine how many indirect draw commands to
/// process.
pub indirect_parameters_count: u32,
/// The offset within the `IndirectParametersBuffers::indexed_data` or
/// `IndirectParametersBuffers::non_indexed_data` of the first indirect draw
/// command for this batch set.
///
/// The CPU fills out this value.
pub indirect_parameters_base: u32,
}
/// The buffers containing all the information that indirect draw commands
/// (`multi_draw_indirect`, `multi_draw_indirect_count`) use to draw the scene.
///
/// In addition to the indirect draw buffers themselves, this structure contains
/// the buffers that store [`IndirectParametersGpuMetadata`], which are the
/// structures that culling writes to so that the indirect parameter building
/// pass can determine how many meshes are actually to be drawn.
///
/// These buffers will remain empty if indirect drawing isn't in use.
#[derive(Resource, Deref, DerefMut)]
pub struct IndirectParametersBuffers {
/// A mapping from a phase type ID to the indirect parameters buffers for
/// that phase.
///
/// Examples of phase type IDs are `Opaque3d` and `AlphaMask3d`.
#[deref]
pub buffers: TypeIdMap<UntypedPhaseIndirectParametersBuffers>,
/// If true, this sets the `COPY_SRC` flag on indirect draw parameters so
/// that they can be read back to CPU.
///
/// This is a debugging feature that may reduce performance. It primarily
/// exists for the `occlusion_culling` example.
pub allow_copies_from_indirect_parameter_buffers: bool,
}
impl IndirectParametersBuffers {
/// Initializes a new [`IndirectParametersBuffers`] resource.
pub fn new(allow_copies_from_indirect_parameter_buffers: bool) -> IndirectParametersBuffers {
IndirectParametersBuffers {
buffers: TypeIdMap::default(),
allow_copies_from_indirect_parameter_buffers,
}
}
}
/// The buffers containing all the information that indirect draw commands use
/// to draw the scene, for a single phase.
///
/// This is the version of the structure that has a type parameter, so that the
/// batching for different phases can run in parallel.
///
/// See the [`IndirectParametersBuffers`] documentation for more information.
#[derive(Resource)]
pub struct PhaseIndirectParametersBuffers<PI>
where
PI: PhaseItem,
{
/// The indirect draw buffers for the phase.
pub buffers: UntypedPhaseIndirectParametersBuffers,
phantom: PhantomData<PI>,
}
impl<PI> PhaseIndirectParametersBuffers<PI>
where
PI: PhaseItem,
{
pub fn new(allow_copies_from_indirect_parameter_buffers: bool) -> Self {
PhaseIndirectParametersBuffers {
buffers: UntypedPhaseIndirectParametersBuffers::new(
allow_copies_from_indirect_parameter_buffers,
),
phantom: PhantomData,
}
}
}
/// The buffers containing all the information that indirect draw commands use
/// to draw the scene, for a single phase.
///
/// This is the version of the structure that doesn't have a type parameter, so
/// that it can be inserted into [`IndirectParametersBuffers::buffers`]
///
/// See the [`IndirectParametersBuffers`] documentation for more information.
pub struct UntypedPhaseIndirectParametersBuffers {
/// Information that indirect draw commands use to draw indexed meshes in
/// the scene.
pub indexed: MeshClassIndirectParametersBuffers<IndirectParametersIndexed>,
/// Information that indirect draw commands use to draw non-indexed meshes
/// in the scene.
pub non_indexed: MeshClassIndirectParametersBuffers<IndirectParametersNonIndexed>,
}
impl UntypedPhaseIndirectParametersBuffers {
/// Creates the indirect parameters buffers.
pub fn new(
allow_copies_from_indirect_parameter_buffers: bool,
) -> UntypedPhaseIndirectParametersBuffers {
let mut indirect_parameter_buffer_usages = BufferUsages::STORAGE | BufferUsages::INDIRECT;
if allow_copies_from_indirect_parameter_buffers {
indirect_parameter_buffer_usages |= BufferUsages::COPY_SRC;
}
UntypedPhaseIndirectParametersBuffers {
non_indexed: MeshClassIndirectParametersBuffers::new(
allow_copies_from_indirect_parameter_buffers,
),
indexed: MeshClassIndirectParametersBuffers::new(
allow_copies_from_indirect_parameter_buffers,
),
}
}
/// Reserves space for `count` new batches.
///
/// The `indexed` parameter specifies whether the meshes that these batches
/// correspond to are indexed or not.
pub fn allocate(&mut self, indexed: bool, count: u32) -> u32 {
if indexed {
self.indexed.allocate(count)
} else {
self.non_indexed.allocate(count)
}
}
/// Returns the number of batches currently allocated.
///
/// The `indexed` parameter specifies whether the meshes that these batches
/// correspond to are indexed or not.
fn batch_count(&self, indexed: bool) -> usize {
if indexed {
self.indexed.batch_count()
} else {
self.non_indexed.batch_count()
}
}
/// Returns the number of batch sets currently allocated.
///
/// The `indexed` parameter specifies whether the meshes that these batch
/// sets correspond to are indexed or not.
pub fn batch_set_count(&self, indexed: bool) -> usize {
if indexed {
self.indexed.batch_sets.len()
} else {
self.non_indexed.batch_sets.len()
}
}
/// Adds a new batch set to `Self::indexed_batch_sets` or
/// `Self::non_indexed_batch_sets` as appropriate.
///
/// `indexed` specifies whether the meshes that these batch sets correspond
/// to are indexed or not. `indirect_parameters_base` specifies the offset
/// within `Self::indexed_data` or `Self::non_indexed_data` of the first
/// batch in this batch set.
#[inline]
pub fn add_batch_set(&mut self, indexed: bool, indirect_parameters_base: u32) {
if indexed {
self.indexed.batch_sets.push(IndirectBatchSet {
indirect_parameters_base,
indirect_parameters_count: 0,
});
} else {
self.non_indexed.batch_sets.push(IndirectBatchSet {
indirect_parameters_base,
indirect_parameters_count: 0,
});
}
}
/// Returns the index that a newly-added batch set will have.
///
/// The `indexed` parameter specifies whether the meshes in such a batch set
/// are indexed or not.
pub fn get_next_batch_set_index(&self, indexed: bool) -> Option<NonMaxU32> {
NonMaxU32::new(self.batch_set_count(indexed) as u32)
}
/// Clears out the buffers in preparation for a new frame.
pub fn clear(&mut self) {
self.indexed.clear();
self.non_indexed.clear();
}
}
/// The buffers containing all the information that indirect draw commands use
/// to draw the scene, for a single mesh class (indexed or non-indexed), for a
/// single phase.
pub struct MeshClassIndirectParametersBuffers<IP>
where
IP: Clone + ShaderSize + WriteInto,
{
/// The GPU buffer that stores the indirect draw parameters for the meshes.
///
/// The indirect parameters building shader writes to this buffer, while the
/// `multi_draw_indirect` or `multi_draw_indirect_count` commands read from
/// it to perform the draws.
data: UninitBufferVec<IP>,
/// The GPU buffer that holds the data used to construct indirect draw
/// parameters for meshes.
///
/// The GPU mesh preprocessing shader writes to this buffer, and the
/// indirect parameters building shader reads this buffer to construct the
/// indirect draw parameters.
cpu_metadata: RawBufferVec<IndirectParametersCpuMetadata>,
/// The GPU buffer that holds data built by the GPU used to construct
/// indirect draw parameters for meshes.
///
/// The GPU mesh preprocessing shader writes to this buffer, and the
/// indirect parameters building shader reads this buffer to construct the
/// indirect draw parameters.
gpu_metadata: UninitBufferVec<IndirectParametersGpuMetadata>,
/// The GPU buffer that holds the number of indirect draw commands for each
/// phase of each view, for meshes.
///
/// The indirect parameters building shader writes to this buffer, and the
/// `multi_draw_indirect_count` command reads from it in order to know how
/// many indirect draw commands to process.
batch_sets: RawBufferVec<IndirectBatchSet>,
}
impl<IP> MeshClassIndirectParametersBuffers<IP>
where
IP: Clone + ShaderSize + WriteInto,
{
fn new(
allow_copies_from_indirect_parameter_buffers: bool,
) -> MeshClassIndirectParametersBuffers<IP> {
let mut indirect_parameter_buffer_usages = BufferUsages::STORAGE | BufferUsages::INDIRECT;
if allow_copies_from_indirect_parameter_buffers {
indirect_parameter_buffer_usages |= BufferUsages::COPY_SRC;
}