-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathgpu.rs
More file actions
1734 lines (1599 loc) · 69.5 KB
/
Copy pathgpu.rs
File metadata and controls
1734 lines (1599 loc) · 69.5 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
//! Clustering of lights and other clusterable objects on GPU.
//!
//! GPU light clustering uses the hardware rasterizer for compute purposes as a
//! way to automatically distribute workloads within 2D axis-aligned bounding
//! boxes without actually rendering any pixels. The algorithm is as follows,
//! with each step corresponding to a raster or compute command
//!
//! 1. *Z slicing*: We have a 3D cluster froxel grid of size W×H×D and seek to
//! rasterize D axis-aligned quads, each of size W×H, representing the range of
//! each clusterable object. In this compute phase, we generate D indirect
//! instances for each clusterable object for the subsequent indirect draws.
//!
//! 2. *Count rasterization*: We use instanced indirect drawing to rasterize
//! each quad generated in step 1 to a viewport of size W×H, with color
//! writes disabled. Each rasterized fragment represents a cluster-object
//! pair. In the fragment shader, we check to see if the object
//! intersects the cluster, and, if it does, we atomically bump a counter
//! corresponding to the number of objects of the given type intersecting
//! the cluster in question. We don't record the ID of the object in this
//! phase; we simply count the number of objects.
//!
//! 3. *Local allocation*: Now that we know the number of objects of each
//! type in each cluster, we can proceed to allocate space in the
//! clustered object buffer for each clustered object list. To do this,
//! we need to perform a [*prefix sum*] operation so that each list is
//! tightly packed with the others. For example, if adjacent clusters
//! have 2, 5, and 3 objects, they'll be allocated at offsets 0, 2, and 7
//! respectively. This *local* step uses a [Hillis-Steele scan] in shared
//! memory to compute the prefix sum of each chunk of 256 clusters. We
//! can't go beyond 256 clusters in this local step because 256 is the
//! maximum workgroup size in `wgpu`.
//!
//! 4. *Global allocation*: To deal with the fact that we can't calculate
//! prefix sums beyond 256 clusters in step 3, we employ this second step
//! that does a sequential loop over every 256-cluster chunk, propagating
//! the prefix sum. At the end of this step, every list of clustered
//! objects is allocated.
//!
//! 5. *Populate rasterization*: Finally, we issue an instanced indirect
//! draw command using the same parameters as step (2). We test each
//! cluster-object pair for intersection, and, if the test passes, we
//! record the ID of each clustered object into the correct space in the
//! list, using an scratch pad buffer of atomics to store the position of
//! the next object in each list.
//!
//! [*prefix sum*]: https://en.wikipedia.org/wiki/Prefix_sum
//!
//! [Hillis-Steele scan]: https://en.wikipedia.org/wiki/Prefix_sum#Algorithm_1:_Shorter_span,_more_parallel
use alloc::sync::Arc;
use std::sync::Mutex;
use bevy_app::{App, Plugin};
use bevy_asset::{embedded_asset, load_embedded_asset, AssetServer, Handle};
use bevy_camera::Camera;
use bevy_color::Color;
use bevy_core_pipeline::{prepass::node::early_prepass, Core3d, Core3dSystems};
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
component::Component,
entity::Entity,
query::With,
resource::Resource,
schedule::IntoScheduleConfigs as _,
system::{Commands, Query, Res, ResMut},
world::{FromWorld, World},
};
use bevy_light::{
cluster::{Clusters, GlobalClusterGpuSettings, GlobalClusterSettings},
EnvironmentMapLight, IrradianceVolume,
};
use bevy_material::descriptor::{
BindGroupLayoutDescriptor, CachedComputePipelineId, CachedRenderPipelineId,
ComputePipelineDescriptor, FragmentState, RenderPipelineDescriptor, VertexState,
};
use bevy_math::{vec2, Vec2};
use bevy_mesh::{VertexBufferLayout, VertexFormat};
use bevy_render::{
diagnostic::RecordDiagnostics as _,
extract_resource::{ExtractResource, ExtractResourcePlugin},
render_resource::{
binding_types,
encase::internal::{CreateFrom as _, Reader},
BindGroup, BindGroupEntry, BindGroupLayoutEntries, Buffer, BufferBindingType,
BufferDescriptor, BufferInitDescriptor, BufferUsages, ColorTargetState, ColorWrites,
CommandEncoder, ComputePassDescriptor, ComputePipeline, Extent3d, IndexFormat, LoadOp,
MapMode, Operations, PipelineCache, RenderPassColorAttachment, RenderPassDescriptor,
RenderPipeline, ShaderStages, ShaderType, SpecializedComputePipeline,
SpecializedComputePipelines, SpecializedRenderPipeline, SpecializedRenderPipelines,
StorageBuffer, StoreOp, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages,
UninitBufferVec, VertexAttribute, VertexStepMode,
},
renderer::{RenderContext, RenderDevice, RenderQueue, ViewQuery},
sync_world::{MainEntity, MainEntityHashMap, MainEntityHashSet, RenderEntity},
texture::{CachedTexture, TextureCache},
view::{ExtractedView, ViewUniform, ViewUniformOffset, ViewUniforms},
GpuResourceAppExt, MainWorld, Render, RenderApp, RenderSystems,
};
use bevy_shader::{load_shader_library, Shader, ShaderDefVal};
use bevy_utils::default;
use bytemuck::{Pod, Zeroable};
use tracing::{error, trace, warn};
use crate::{
cluster::{
GpuClusterOffsetAndCounts, GpuClusterOffsetsAndCountsStorage,
GpuClusterableObjectIndexListsStorage, ViewClusterBuffers,
},
decal::clustered::{DecalsBuffer, RenderClusteredDecal, RenderClusteredDecals},
gpu_clustering_is_enabled, ExtractedClusterConfig, GlobalClusterableObjectMeta,
GpuClusteredLight, GpuLights, LightMeta, LightProbesBuffer, LightProbesUniform,
RenderViewLightProbes, ViewClusterBindings, ViewLightProbesUniformOffset,
ViewLightsUniformOffset,
};
/// The workgroup size of the `cluster_allocate.wgsl` shader.
const ALLOCATION_WORKGROUP_SIZE: u32 = 256;
/// The workgroup size of the `cluster_z_slice.wgsl` shader.
const Z_SLICING_WORKGROUP_SIZE: u32 = 64;
/// A plugin that enables GPU clustering of lights and other objects.
pub struct GpuClusteringPlugin;
impl Plugin for GpuClusteringPlugin {
fn build(&self, app: &mut App) {
load_shader_library!(app, "cluster.wgsl");
embedded_asset!(app, "cluster_z_slice.wgsl");
embedded_asset!(app, "cluster_raster.wgsl");
embedded_asset!(app, "cluster_allocate.wgsl");
app.add_plugins(ExtractResourcePlugin::<
GlobalClusterSettings,
GpuClusteringPlugin,
>::default());
}
fn finish(&self, app: &mut App) {
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
// Bail out if we have no storage buffers. This is the case when we have
// `WGPU_SETTINGS_PRIO="webgl2"`.
let render_device = render_app.world().resource::<RenderDevice>();
if render_device.limits().max_storage_buffers_per_shader_stage == 0 {
return;
}
render_app
.init_gpu_resource::<SpecializedRenderPipelines<ClusteringRasterPipeline>>()
.init_gpu_resource::<SpecializedComputePipelines<ClusteringZSlicingPipeline>>()
.init_gpu_resource::<SpecializedComputePipelines<ClusteringAllocationPipeline>>()
.init_gpu_resource::<RenderViewClusteringReadbackData>()
.init_gpu_resource::<GpuClusteringMeshBuffers>()
.init_gpu_resource::<ClusteringRasterPipeline>()
.init_gpu_resource::<ClusteringZSlicingPipeline>()
.init_gpu_resource::<ClusteringAllocationPipeline>()
.add_systems(
Render,
(prepare_clustering_pipelines, prepare_cluster_dummy_textures)
.in_set(RenderSystems::Prepare)
.run_if(gpu_clustering_is_enabled),
)
.add_systems(
Render,
(
prepare_clusters_for_gpu_clustering,
upload_view_gpu_clustering_buffers,
)
.chain()
.in_set(RenderSystems::PrepareResources)
.run_if(gpu_clustering_is_enabled),
)
.add_systems(
Render,
prepare_clustering_bind_groups
.in_set(RenderSystems::PrepareBindGroups)
.run_if(gpu_clustering_is_enabled),
)
.add_systems(
Core3d,
cluster_on_gpu
.before(early_prepass)
.in_set(Core3dSystems::Prepass)
.run_if(gpu_clustering_is_enabled),
);
}
}
/// The texture that we bind when performing the raster passes.
///
/// We don't actually write to this texture; it exists only so that we can set a
/// viewport.
#[derive(Component, Deref, DerefMut)]
pub struct ViewClusteringDummyTexture(CachedTexture);
/// The bind groups for each pass of GPU clustering.
#[derive(Component)]
pub struct ViewClusteringBindGroups {
/// The bind group for the Z-slicing compute pass.
clustering_bind_group_z_slicing_pass: BindGroup,
/// The bind group for the count rasterization pass.
clustering_bind_group_count_pass: BindGroup,
/// The bind group for both local and global allocation passes.
clustering_bind_group_allocate_pass: BindGroup,
/// The bind group for the populate rasterization pass.
clustering_bind_group_populate_pass: BindGroup,
}
/// The GPU representation of a single Z-slice of a clusterable object.
///
/// A Z-slice is an axis-aligned bounding box representing the potential
/// bounding box of a clusterable object in a single Z slice of the froxel grid.
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, ShaderType, Pod, Zeroable)]
#[repr(C)]
pub struct ClusterableObjectZSlice {
/// The index of the object to be clustered.
pub object_index: u32,
/// The type of the object to be clustered.
///
/// This is one of the `CLUSTERABLE_OBJECT_TYPE_` constants in
/// `cluster.wgsl`.
pub object_type: u32,
/// The Z coordinate of the froxels that this slice covers.
pub z_slice: u32,
}
/// Metadata stored on GPU that's global to all clusters for a view.
#[derive(Clone, Copy, Default, ShaderType, Pod, Zeroable)]
#[repr(C)]
pub struct ClusterMetadata {
/// The indirect draw parameters for the raster passes.
indirect_draw_params: ClusterRasterIndirectDrawParams,
/// The total number of clustered lights, set by the CPU.
clustered_light_count: u32,
/// The total number of reflection probes, set by the CPU.
reflection_probe_count: u32,
/// The total number of irradiance volumes, set by the CPU.
irradiance_volume_count: u32,
/// The total number of clustered decals, set by the CPU.
decal_count: u32,
/// The current maximum size of the Z-slice list.
z_slice_list_capacity: u32,
/// The current size of the clustered object index list.
///
/// This is set to 0 by the CPU, and the GPU updates it with the computed
/// value.
index_list_capacity: u32,
/// The farthest depth that any clustered object AABB has extended to this
/// frame.
///
/// This is set to 0 by the CPU, and the GPU updates it with the computed
/// value.
///
/// This is a float encoded by `f32_bits_to_sortable_u32`. Decode with `sortable_u32_to_f32_bits`.
farthest_z: u32,
}
/// Indirect draw parameters for the raster dispatch phase, built partially by
/// the CPU and partially by the GPU.
///
/// These must conform to the format that `wgpu` demands, so this structure
/// layout must not be modified.
#[derive(Clone, Copy, Default, ShaderType, Pod, Zeroable)]
#[repr(C)]
pub struct ClusterRasterIndirectDrawParams {
index_count: u32,
/// Represents the total number of Z slices.
///
/// This field is the one that the GPU modifies.
instance_count: u32,
first_index: u32,
base_vertex: u32,
first_instance: u32,
}
/// A component, stored on [`ExtractedView`], that stores buffers needed to
/// perform GPU clustering for that view.
#[derive(Component)]
pub struct ViewGpuClusteringBuffers {
/// The buffer that holds the Z slices for each clusterable object.
///
/// The `cluster_z_slice.wgsl` shader fills this buffer out, and the raster
/// passes read it.
pub z_slices_buffer: UninitBufferVec<ClusterableObjectZSlice>,
/// The buffer that holds the scratchpad offsets and counts for each
/// clusterable object.
///
/// The populate pass uses this to coordinate where to write indices for
/// each clusterable object. The allocation pass zeroes it out.
scratchpad_offsets_and_counts_buffer: UninitBufferVec<GpuClusterOffsetAndCounts>,
/// The buffer that stores the [`ClusterMetadata`].
///
/// Since this buffer is small, [`StorageBuffer`] is fine to use.
cluster_metadata_buffer: StorageBuffer<ClusterMetadata>,
}
impl ViewGpuClusteringBuffers {
/// Creates a new, empty set of [`ViewGpuClusteringBuffers`] for a single
/// view.
pub(crate) fn new() -> ViewGpuClusteringBuffers {
let mut cluster_metadata_buffer = StorageBuffer::from(ClusterMetadata::default());
cluster_metadata_buffer.add_usages(BufferUsages::COPY_SRC | BufferUsages::INDIRECT);
cluster_metadata_buffer.set_label(Some("clustering Z slicing metadata buffer"));
ViewGpuClusteringBuffers {
cluster_metadata_buffer,
z_slices_buffer: UninitBufferVec::new(BufferUsages::STORAGE | BufferUsages::COPY_DST),
scratchpad_offsets_and_counts_buffer: UninitBufferVec::new(
BufferUsages::STORAGE | BufferUsages::COPY_DST,
),
}
}
}
/// Stores data associated with reading back clustering statistics from GPU to
/// CPU for all views.
#[derive(Resource, Default)]
pub(crate) struct RenderViewClusteringReadbackData {
/// The data for each view.
///
/// This is locked behind a mutex so that the buffer readback callbacks,
/// which execute concurrently, can access it alongside the render world.
views: MainEntityHashMap<Arc<Mutex<ViewClusteringReadbackData>>>,
}
/// Data associated with reading back clustering statistics for a single view.
struct ViewClusteringReadbackData {
/// The current capacity of the Z slice list.
///
/// This starts out at the default size as specified by the allocation and
/// can grow based on the results of GPU readback.
z_slice_list_capacity: usize,
/// The current capacity of the clustered object index list.
///
/// This starts out at the default size as specified by the allocation and
/// can grow based on the results of GPU readback.
max_index_list_capacity: usize,
/// Buffers corresponding to GPU readback operations in progress.
metadata_staging_pending_buffers: Vec<Buffer>,
/// Buffers corresponding to GPU readback operations that are finished.
///
/// These buffers are ready for reuse.
metadata_staging_free_buffers: Vec<Buffer>,
/// Statistics about GPU clustering that the GPU calculated last frame.
last_frame_statistics: Option<ViewClusteringLastFrameStatistics>,
}
/// Statistics about GPU clustering that the GPU calculated last frame.
struct ViewClusteringLastFrameStatistics {
/// The actual used size of the index list.
///
/// If this is greater than the capacity of the index list, the CPU will
/// resize the index list buffer.
index_list_size: u32,
/// The maximum depth of all axis-aligned bounding boxes corresponding to
/// clusterable objects in view.
farthest_z: f32,
}
impl ViewClusteringReadbackData {
/// Creates a new [`ViewClusteringReadbackData`] for a view.
///
/// The [`Self::z_slice_list_capacity`] and
/// [`Self::max_index_list_capacity`] are calculated based on the initial
/// capacities that the application set in the [`GlobalClusterGpuSettings`].
fn new(settings: &GlobalClusterGpuSettings) -> ViewClusteringReadbackData {
ViewClusteringReadbackData {
z_slice_list_capacity: settings.initial_z_slice_list_capacity,
max_index_list_capacity: settings.initial_index_list_capacity,
metadata_staging_pending_buffers: vec![],
metadata_staging_free_buffers: vec![],
last_frame_statistics: None,
}
}
fn get_or_create_staging_buffer(&mut self, render_device: &RenderDevice) -> Buffer {
let staging_buffer = self.metadata_staging_free_buffers.pop().unwrap_or_else(|| {
render_device.create_buffer(&BufferDescriptor {
label: Some("clustering metadata staging buffer"),
size: ClusterMetadata::min_size().into(),
usage: BufferUsages::COPY_DST | BufferUsages::MAP_READ,
mapped_at_creation: false,
})
});
self.metadata_staging_pending_buffers
.push(staging_buffer.clone());
staging_buffer
}
/// Updates this [`ViewClusteringReadbackData`] with new information from
/// the given metadata read back from the GPU.
fn update_from_metadata(&mut self, gpu_clustering_metadata: &ClusterMetadata) {
// Schedule a resize of the Z slice list if the GPU overflowed.
if self.z_slice_list_capacity
< gpu_clustering_metadata.indirect_draw_params.instance_count as usize
{
let new_capacity = gpu_clustering_metadata
.indirect_draw_params
.instance_count
.next_power_of_two();
warn!(
"Resizing the view clustering Z slice list from a capacity of {0} elements to \
a capacity of {1} elements. The scene lighting may have been corrupted for a \
few frames. To avoid this, set the `gpu_clustering.z_slice_list_capacity` field \
on the `GlobalClusterSettings` resource to at least {1}.",
self.z_slice_list_capacity, new_capacity
);
self.z_slice_list_capacity = new_capacity as usize;
}
// Schedule a resize of the index slice list if the GPU overflowed.
if self.max_index_list_capacity < gpu_clustering_metadata.index_list_capacity as usize {
let new_capacity = gpu_clustering_metadata
.index_list_capacity
.next_power_of_two();
warn!(
"Resizing the view clustering index list from a capacity of {0} elements to a \
capacity of {1} elements. The scene lighting may have been corrupted for a \
few frames. To avoid this, set the `gpu_clustering.index_list_capacity` field on \
the `GlobalClusterSettings` resource to at least {1}.",
self.max_index_list_capacity, new_capacity
);
self.max_index_list_capacity = new_capacity as usize;
}
// Record the statistics we just received.
self.last_frame_statistics = Some(ViewClusteringLastFrameStatistics {
index_list_size: gpu_clustering_metadata.index_list_capacity,
farthest_z: f32::from_bits(sortable_u32_to_f32_bits(
gpu_clustering_metadata.farthest_z,
)),
});
}
}
/// Decodes a u32 produced by `f32_bits_to_sortable_u32` (in
/// `cluster_z_slice.wgsl`) back into f32 bits.
///
/// The encode flips the sign bit for positive floats and all bits for
/// negative floats, so the decode must inspect the *encoded* sign bit
/// (which is inverted relative to the original) and apply the
/// complementary mask.
fn sortable_u32_to_f32_bits(bits: u32) -> u32 {
let mask = (!((bits as i32) >> 31)) as u32 | 0x80000000;
bits ^ mask
}
/// Global data relating to the `cluster_raster.wgsl` shader.
#[derive(Resource)]
pub struct ClusteringRasterPipeline {
/// The bind group layout for group 0 for the count (first) pass.
pub bind_group_layout_count_pass: BindGroupLayoutDescriptor,
/// The bind group layout for group 0 for the populate (second) pass.
pub bind_group_layout_populate_pass: BindGroupLayoutDescriptor,
/// A handle to the shader itself.
pub shader: Handle<Shader>,
}
/// Global data relating to the `cluster_z_slice.wgsl` shader.
#[derive(Resource)]
pub struct ClusteringZSlicingPipeline {
/// The bind group layout for group 0.
pub bind_group_layout: BindGroupLayoutDescriptor,
/// A handle to the shader itself.
pub shader: Handle<Shader>,
}
/// Global data relating to the `cluster_allocate.wgsl` shader.
#[derive(Resource)]
pub struct ClusteringAllocationPipeline {
/// The bind group layout of group 0 for both shader invocations.
pub bind_group_layout: BindGroupLayoutDescriptor,
/// A handle to the `cluster_allocate.wgsl` shader itself.
pub shader: Handle<Shader>,
}
/// The pipeline key that identifies specializations of the
/// `cluster_raster.wgsl` shader.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClusteringRasterPipelineKey {
/// True if this is the populate (second) pass; false if it's the count
/// (first) one.
populate_pass: bool,
}
/// The pipeline key that identifies specializations of the
/// `cluster_allocate.wgsl` shader.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClusteringAllocationPipelineKey {
/// True if this is the global (second) pass; false if it's the local
/// (first) one.
global_pass: bool,
}
impl FromWorld for ClusteringRasterPipeline {
fn from_world(world: &mut World) -> Self {
let asset_server = world.resource::<AssetServer>();
let mut bind_group_layout_entries_count_pass = vec![
// @group(0) @binding(0) var<storage> z_slices:
// array<ClusterableObjectZSlice>;
binding_types::storage_buffer_read_only::<ClusterableObjectZSlice>(false)
.build(0, ShaderStages::VERTEX_FRAGMENT),
// @group(0) @binding(1) var<storage, read_write> index_lists:
// ClusterableObjectIndexLists;
binding_types::storage_buffer::<GpuClusterableObjectIndexListsStorage>(false)
.build(1, ShaderStages::FRAGMENT),
// @group(0) @binding(2) var<storage> clustered_lights:
// ClusteredLights;
binding_types::storage_buffer_read_only::<GpuClusteredLight>(false)
.build(2, ShaderStages::VERTEX_FRAGMENT),
// @group(0) @binding(3) var<uniform> light_probes: LightProbes;
binding_types::uniform_buffer::<LightProbesUniform>(true)
.build(3, ShaderStages::VERTEX_FRAGMENT),
// @group(0) @binding(4) var<storage> clustered_decals:
// ClusteredDecals;
binding_types::storage_buffer_read_only::<RenderClusteredDecal>(false)
.build(4, ShaderStages::VERTEX_FRAGMENT),
// @group(0) @binding(5) var<uniform> lights: Lights;
binding_types::uniform_buffer::<GpuLights>(true)
.build(5, ShaderStages::VERTEX_FRAGMENT),
// @group(0) @binding(6) var<uniform> view: View;
binding_types::uniform_buffer::<ViewUniform>(true)
.build(6, ShaderStages::VERTEX_FRAGMENT),
];
let mut bind_group_layout_entries_populate_pass =
bind_group_layout_entries_count_pass.clone();
// @group(0) @binding(7) var<storage, read_write> offsets_and_counts:
// ClusterOffsetsAndCountsAtomic;
bind_group_layout_entries_count_pass.push(
binding_types::storage_buffer::<GpuClusterOffsetsAndCountsStorage>(false)
.build(7, ShaderStages::FRAGMENT),
);
// @group(0) @binding(7) var<storage> offsets_and_counts:
// ClusterOffsetsAndCounts;
bind_group_layout_entries_populate_pass.push(
binding_types::storage_buffer_read_only::<GpuClusterOffsetsAndCountsStorage>(false)
.build(7, ShaderStages::FRAGMENT),
);
// @group(0) @binding(8) var<storage, read_write>
// scratchpad_offsets_and_counts: ClusterOffsetsAndCountsAtomic;
bind_group_layout_entries_populate_pass.push(
binding_types::storage_buffer::<GpuClusterOffsetsAndCountsStorage>(false)
.build(8, ShaderStages::FRAGMENT),
);
let bind_group_layout_count_pass = BindGroupLayoutDescriptor::new(
"clustering count pass bind group layout",
&bind_group_layout_entries_count_pass,
);
let bind_group_layout_populate_pass = BindGroupLayoutDescriptor::new(
"clustering populate pass bind group layout",
&bind_group_layout_entries_populate_pass,
);
let shader = load_embedded_asset!(asset_server, "cluster_raster.wgsl");
ClusteringRasterPipeline {
bind_group_layout_count_pass,
bind_group_layout_populate_pass,
shader,
}
}
}
impl SpecializedRenderPipeline for ClusteringRasterPipeline {
type Key = ClusteringRasterPipelineKey;
fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {
let mut fragment_shader_defs = vec![];
if key.populate_pass {
fragment_shader_defs.push(ShaderDefVal::from("POPULATE_PASS"));
} else {
fragment_shader_defs.push(ShaderDefVal::from("COUNT_PASS"));
}
let mut vertex_shader_defs = fragment_shader_defs.clone();
vertex_shader_defs.push(ShaderDefVal::from("VERTEX_SHADER"));
RenderPipelineDescriptor {
label: if key.populate_pass {
Some("clustering populate pipeline".into())
} else {
Some("clustering count pipeline".into())
},
layout: vec![if key.populate_pass {
self.bind_group_layout_populate_pass.clone()
} else {
self.bind_group_layout_count_pass.clone()
}],
immediate_size: 0,
vertex: VertexState {
shader: self.shader.clone(),
shader_defs: vertex_shader_defs,
entry_point: Some("vertex_main".into()),
buffers: vec![VertexBufferLayout {
array_stride: size_of::<Vec2>() as u64,
step_mode: VertexStepMode::Vertex,
attributes: vec![VertexAttribute {
format: VertexFormat::Float32x2,
offset: 0,
shader_location: 0,
}],
}],
},
fragment: Some(FragmentState {
shader: self.shader.clone(),
shader_defs: fragment_shader_defs,
entry_point: Some("fragment_main".into()),
targets: vec![Some(ColorTargetState {
format: TextureFormat::R8Unorm,
blend: None,
// Disable writing.
write_mask: ColorWrites::empty(),
})],
}),
..default()
}
}
}
impl FromWorld for ClusteringZSlicingPipeline {
fn from_world(world: &mut World) -> Self {
let asset_server = world.resource::<AssetServer>();
let bind_group_layout = BindGroupLayoutDescriptor::new(
"clustering Z slicing pass bind group layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::COMPUTE,
(
// @group(0) @binding(0) var<storage, read_write>
// cluster_metadata: ClusterMetadata;
binding_types::storage_buffer::<ClusterMetadata>(false),
// @group(0) @binding(1) var<storage, read_write> z_slices:
// array<ClusterableObjectZSlice>;
binding_types::storage_buffer::<ClusterableObjectZSlice>(false),
// @group(0) @binding(2) var<storage> clustered_lights:
// ClusteredLights;
binding_types::storage_buffer_read_only::<GpuClusteredLight>(false),
// @group(0) @binding(3) var<uniform> light_probes:
// LightProbes;
binding_types::uniform_buffer::<LightProbesUniform>(true),
// @group(0) @binding(4) var<storage> clustered_decals:
// ClusteredDecals;
binding_types::storage_buffer_read_only::<RenderClusteredDecal>(false),
// @group(0) @binding(5) var<uniform> lights: Lights;
binding_types::uniform_buffer::<GpuLights>(true),
// @group(0) @binding(6) var<uniform> view: View;
binding_types::uniform_buffer::<ViewUniform>(true),
),
),
);
let shader = load_embedded_asset!(asset_server, "cluster_z_slice.wgsl");
ClusteringZSlicingPipeline {
bind_group_layout,
shader,
}
}
}
impl SpecializedComputePipeline for ClusteringZSlicingPipeline {
type Key = ();
fn specialize(&self, _: Self::Key) -> ComputePipelineDescriptor {
ComputePipelineDescriptor {
label: Some("clustering Z slicing pipeline".into()),
layout: vec![self.bind_group_layout.clone()],
shader: self.shader.clone(),
shader_defs: vec![],
entry_point: Some("z_slice_main".into()),
zero_initialize_workgroup_memory: true,
..default()
}
}
}
impl FromWorld for ClusteringAllocationPipeline {
fn from_world(world: &mut World) -> Self {
let asset_server = world.resource::<AssetServer>();
let bind_group_layout = BindGroupLayoutDescriptor::new(
"clustering allocation pass bind group layout",
&BindGroupLayoutEntries::sequential(
ShaderStages::COMPUTE,
(
// @group(0) @binding(0) var<storage, read_write>
// offsets_and_counts: ClusterOffsetsAndCounts;
binding_types::storage_buffer::<GpuClusterOffsetsAndCountsStorage>(false),
// @group(0) @binding(1) var<uniform> lights: Lights;
binding_types::uniform_buffer::<GpuLights>(true),
// @group(0) @binding(2) var<storage, read_write>
// clustering_metadata: ClusterMetadata;
binding_types::storage_buffer::<ClusterMetadata>(false),
// @group(0) @binding(3) var<storage, read_write>
// scratchpad_offsets_and_counts: ClusterOffsetsAndCounts;
binding_types::storage_buffer::<GpuClusterOffsetsAndCountsStorage>(false),
),
),
);
let shader = load_embedded_asset!(asset_server, "cluster_allocate.wgsl");
ClusteringAllocationPipeline {
bind_group_layout,
shader,
}
}
}
impl SpecializedComputePipeline for ClusteringAllocationPipeline {
type Key = ClusteringAllocationPipelineKey;
fn specialize(&self, key: Self::Key) -> ComputePipelineDescriptor {
ComputePipelineDescriptor {
label: if key.global_pass {
Some("clustering allocation global pass pipeline".into())
} else {
Some("clustering allocation local pass pipeline".into())
},
layout: vec![self.bind_group_layout.clone()],
shader: self.shader.clone(),
shader_defs: vec![],
entry_point: if key.global_pass {
Some("allocate_global_main".into())
} else {
Some("allocate_local_main".into())
},
zero_initialize_workgroup_memory: true,
..default()
}
}
}
/// The vertices of the quad that we rasterize to represent a clusterable object
/// Z slice.
static GPU_CLUSTERING_VERTICES: [Vec2; 4] = [
vec2(0.0, 0.0),
vec2(1.0, 0.0),
vec2(0.0, 1.0),
vec2(1.0, 1.0),
];
/// The indices of the quad that we rasterize to represent a clusterable object
/// Z slice.
static GPU_CLUSTERING_INDICES: [u32; 6] = [0, 1, 2, 1, 3, 2];
/// The buffers that store the vertices and indices for the quad that we
/// rasterize to represent each clusterable object Z slice.
#[derive(Resource)]
struct GpuClusteringMeshBuffers {
/// The vertex buffer containing the 4 vertices of a quad.
vertex_buffer: Buffer,
/// The index buffer containing the 6 indices of a quad.
index_buffer: Buffer,
}
impl FromWorld for GpuClusteringMeshBuffers {
fn from_world(world: &mut World) -> Self {
let render_device = world.resource::<RenderDevice>();
GpuClusteringMeshBuffers {
vertex_buffer: render_device.create_buffer_with_data(&BufferInitDescriptor {
label: Some("GPU clustering vertex buffer"),
contents: bytemuck::bytes_of(&GPU_CLUSTERING_VERTICES),
usage: BufferUsages::COPY_DST | BufferUsages::VERTEX,
}),
index_buffer: render_device.create_buffer_with_data(&BufferInitDescriptor {
label: Some("GPU clustering index buffer"),
contents: bytemuck::bytes_of(&GPU_CLUSTERING_INDICES),
usage: BufferUsages::COPY_DST | BufferUsages::INDEX,
}),
}
}
}
/// The IDs of each pipeline used for GPU clustering for a single view.
#[derive(Component)]
pub struct ViewGpuClusteringPipelineIds {
/// The compute pipeline for the Z slicing compute pass (pass 1).
clustering_z_slicing_pipeline_id: CachedComputePipelineId,
/// The compute pipeline for the count raster pass (pass 2).
clustering_count_pipeline_id: CachedRenderPipelineId,
/// The compute pipeline for the local allocation compute pass (pass 3).
clustering_allocation_local_pipeline_id: CachedComputePipelineId,
/// The compute pipeline for the global allocation compute pass (pass 4).
clustering_allocation_global_pipeline_id: CachedComputePipelineId,
/// The compute pipeline for the populate raster pass (pass 5).
clustering_populate_pipeline_id: CachedRenderPipelineId,
}
/// The render command building system that performs GPU clustering on each
/// view.
fn cluster_on_gpu(
view_query: ViewQuery<(
&MainEntity,
Option<&ViewGpuClusteringBuffers>,
Option<&ViewGpuClusteringPipelineIds>,
Option<&ViewClusteringDummyTexture>,
Option<&ViewClusteringBindGroups>,
Option<&ViewLightProbesUniformOffset>,
Option<&ViewLightsUniformOffset>,
Option<&ViewUniformOffset>,
Option<&ExtractedClusterConfig>,
)>,
pipeline_cache: Res<PipelineCache>,
clustering_mesh_buffers: Res<GpuClusteringMeshBuffers>,
render_view_clustering_readback_data: Res<RenderViewClusteringReadbackData>,
mut render_context: RenderContext,
) {
let (
view_main_entity,
Some(view_gpu_clustering_buffers),
Some(view_gpu_clustering_pipeline_ids),
Some(view_clustering_dummy_texture),
Some(view_clustering_bind_groups),
Some(view_light_probes_uniform_offset),
Some(view_lights_uniform_offset),
Some(view_uniform_offset),
Some(extracted_cluster_config),
) = view_query.into_inner()
else {
trace!("Failed to match view query; not clustering");
return;
};
let Some(view_clustering_readback_data) = render_view_clustering_readback_data
.views
.get(view_main_entity)
else {
return;
};
let (
Some(clustering_z_slicing_compute_pipeline),
Some(clustering_count_render_pipeline),
Some(clustering_allocate_local_compute_pipeline),
Some(clustering_allocate_global_compute_pipeline),
Some(clustering_populate_render_pipeline),
) = (
pipeline_cache.get_compute_pipeline(
view_gpu_clustering_pipeline_ids.clustering_z_slicing_pipeline_id,
),
pipeline_cache
.get_render_pipeline(view_gpu_clustering_pipeline_ids.clustering_count_pipeline_id),
pipeline_cache.get_compute_pipeline(
view_gpu_clustering_pipeline_ids.clustering_allocation_local_pipeline_id,
),
pipeline_cache.get_compute_pipeline(
view_gpu_clustering_pipeline_ids.clustering_allocation_global_pipeline_id,
),
pipeline_cache
.get_render_pipeline(view_gpu_clustering_pipeline_ids.clustering_populate_pipeline_id),
)
else {
trace!("One or more clustering pipelines not found; not clustering");
return;
};
let diagnostics = render_context.diagnostic_recorder();
let diagnostics = diagnostics.as_deref();
let time_span = diagnostics.time_span(render_context.command_encoder(), "clustering");
// Fetch a staging buffer for us to perform readback with.
let Ok(staging_buffer) = view_clustering_readback_data
.lock()
.map(|mut data| data.get_or_create_staging_buffer(render_context.render_device()))
else {
error!("Failed to fetch staging buffer; not clustering.");
return;
};
let command_encoder = render_context.command_encoder();
command_encoder.push_debug_group("clustering");
// Pass 1: Z slicing.
run_clustering_z_slicing_pass(
command_encoder,
clustering_z_slicing_compute_pipeline,
&view_clustering_bind_groups.clustering_bind_group_z_slicing_pass,
&view_gpu_clustering_buffers.cluster_metadata_buffer,
view_light_probes_uniform_offset,
view_lights_uniform_offset,
view_uniform_offset,
);
// Pass 2: Count raster.
run_clustering_rasterization_pass(
command_encoder,
clustering_count_render_pipeline,
&view_clustering_bind_groups.clustering_bind_group_count_pass,
view_gpu_clustering_buffers,
view_light_probes_uniform_offset,
view_lights_uniform_offset,
view_uniform_offset,
view_clustering_dummy_texture,
extracted_cluster_config,
&clustering_mesh_buffers,
false,
);
// Pass 3: local allocation.
run_clustering_allocation_pass(
command_encoder,
clustering_allocate_local_compute_pipeline,
view_clustering_bind_groups,
view_lights_uniform_offset,
extracted_cluster_config,
false,
);
// Pass 4: global allocation.
run_clustering_allocation_pass(
command_encoder,
clustering_allocate_global_compute_pipeline,
view_clustering_bind_groups,
view_lights_uniform_offset,
extracted_cluster_config,
true,
);
// Pass 5: populate raster.
run_clustering_rasterization_pass(
command_encoder,
clustering_populate_render_pipeline,
&view_clustering_bind_groups.clustering_bind_group_populate_pass,
view_gpu_clustering_buffers,
view_light_probes_uniform_offset,
view_lights_uniform_offset,
view_uniform_offset,
view_clustering_dummy_texture,
extracted_cluster_config,
&clustering_mesh_buffers,
true,
);
// Schedule a readback of the readback data.
schedule_readback_staging(
command_encoder,
view_gpu_clustering_buffers,
&staging_buffer,
);
schedule_readback_buffer_map(
command_encoder,
view_clustering_readback_data.clone(),
&staging_buffer,
);
command_encoder.pop_debug_group();
time_span.end(render_context.command_encoder());
/// Runs the Z slicing pass (step 1).
fn run_clustering_z_slicing_pass(
command_encoder: &mut CommandEncoder,
clustering_z_slicing_pipeline: &ComputePipeline,
clustering_z_slicing_bind_group: &BindGroup,
clustering_cluster_metadata_buffer: &StorageBuffer<ClusterMetadata>,
view_light_probes_uniform_offset: &ViewLightProbesUniformOffset,
view_lights_uniform_offset: &ViewLightsUniformOffset,
view_uniform_offset: &ViewUniformOffset,
) {
let mut compute_pass = command_encoder.begin_compute_pass(&ComputePassDescriptor {
label: Some("clustering Z slicing pass"),
..default()
});
compute_pass.set_pipeline(clustering_z_slicing_pipeline);
compute_pass.set_bind_group(
0,
Some(&**clustering_z_slicing_bind_group),
&[
**view_light_probes_uniform_offset,
view_lights_uniform_offset.offset,
view_uniform_offset.offset,
],
);
let clustering_cluster_metadata = clustering_cluster_metadata_buffer.get();
let clusterable_object_count = clustering_cluster_metadata.clustered_light_count
+ clustering_cluster_metadata.reflection_probe_count
+ clustering_cluster_metadata.irradiance_volume_count
+ clustering_cluster_metadata.decal_count;
let workgroup_count = clusterable_object_count.div_ceil(Z_SLICING_WORKGROUP_SIZE);
compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
}
/// Runs either the count or populate rasterization pass (steps 2 and 5
/// respectively) for a single view.
///
/// The `populate_pass` parameter specifies whether this is a count pass