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
//! GPU-driven culling compute dispatch.
//!
//! `CullResources` holds the two compute pipelines and supporting buffers for
//! the cull pass. Call `dispatch` once per frame after uploading instance AABBs
//! and batch metadata to run:
//!
//! 1. `cull_instances` — one thread per instance, tests AABB vs frustum,
//! claims a visibility slot via atomicAdd.
//! 2. `write_indirect_args` — one thread per batch, writes a DrawIndexedIndirect
//! entry and resets the counter for the next frame.
//!
//! The two dispatches run in separate wgpu compute passes so the automatic
//! storage-buffer barrier between passes guarantees pass 2 sees pass 1 writes.
use crate::resources::FrustumUniform;
/// Bind group layout entry count for the cull compute pass (group 0).
const CULL_BGL_ENTRY_COUNT: usize = 6;
/// GPU culling infrastructure: pipelines, BGL, and frustum uniform buffer.
pub(super) struct CullResources {
/// Compute pipeline for the `cull_instances` entry point (workgroup 64).
cull_instances_pipeline: wgpu::ComputePipeline,
/// Compute pipeline for the `write_indirect_args` entry point (workgroup 64).
write_indirect_args_pipeline: wgpu::ComputePipeline,
/// Bind group layout for both cull pipelines (6 bindings, all COMPUTE).
bgl: wgpu::BindGroupLayout,
/// 96-byte uniform buffer holding the 6-plane camera frustum for the main pass.
pub(super) frustum_buf: wgpu::Buffer,
/// Per-cascade frustum uniform buffers for shadow GPU culling.
pub(super) cascade_frustum_bufs: [wgpu::Buffer; 4],
}
impl CullResources {
/// Create the cull pipelines and frustum buffer.
///
/// Called lazily on the first frame where GPU culling is active.
pub(super) fn new(device: &wgpu::Device) -> Self {
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("cull_bgl"),
entries: &Self::bgl_entries(),
});
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("cull_shader"),
source: wgpu::ShaderSource::Wgsl(include_str!(concat!(env!("OUT_DIR"), "/cull.wgsl")).into()),
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("cull_pipeline_layout"),
bind_group_layouts: &[&bgl],
push_constant_ranges: &[],
});
let cull_instances_pipeline =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("cull_instances_pipeline"),
layout: Some(&layout),
module: &shader,
entry_point: Some("cull_instances"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
let write_indirect_args_pipeline =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("write_indirect_args_pipeline"),
layout: Some(&layout),
module: &shader,
entry_point: Some("write_indirect_args"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
let frustum_buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("cull_frustum_buf"),
size: std::mem::size_of::<FrustumUniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let cascade_frustum_bufs = std::array::from_fn(|i| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(&format!("cull_cascade_frustum_buf_{i}")),
size: std::mem::size_of::<FrustumUniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
});
Self {
cull_instances_pipeline,
write_indirect_args_pipeline,
bgl,
frustum_buf,
cascade_frustum_bufs,
}
}
/// Dispatch the two cull compute passes into `encoder`.
///
/// - `frustum`: frustum planes to upload this frame.
/// - `aabb_buf` / `meta_buf` / `counter_buf` / `vis_buf` / `indirect_buf`:
/// the GPU buffers allocated by `upload_aabb_and_batch_meta`.
/// - `instance_count`: total number of instances (drives pass-1 dispatch).
/// - `batch_count`: number of batches (drives pass-2 dispatch).
pub(super) fn dispatch(
&self,
encoder: &mut wgpu::CommandEncoder,
device: &wgpu::Device,
queue: &wgpu::Queue,
frustum: &FrustumUniform,
aabb_buf: &wgpu::Buffer,
meta_buf: &wgpu::Buffer,
counter_buf: &wgpu::Buffer,
vis_buf: &wgpu::Buffer,
indirect_buf: &wgpu::Buffer,
instance_count: u32,
batch_count: u32,
) {
// Upload frustum for this frame.
queue.write_buffer(
&self.frustum_buf,
0,
bytemuck::cast_slice(std::slice::from_ref(frustum)),
);
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("cull_bg"),
layout: &self.bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: self.frustum_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: aabb_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: meta_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: counter_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: vis_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 5,
resource: indirect_buf.as_entire_binding(),
},
],
});
// Pass 1: cull_instances — one thread per instance.
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("cull_instances_pass"),
timestamp_writes: None,
});
pass.set_pipeline(&self.cull_instances_pipeline);
pass.set_bind_group(0, &bind_group, &[]);
let groups = instance_count.div_ceil(64);
pass.dispatch_workgroups(groups, 1, 1);
}
// wgpu inserts an automatic storage-buffer barrier between compute passes,
// so pass 2 is guaranteed to see all writes from pass 1.
// Pass 2: write_indirect_args — one thread per batch.
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("write_indirect_args_pass"),
timestamp_writes: None,
});
pass.set_pipeline(&self.write_indirect_args_pipeline);
pass.set_bind_group(0, &bind_group, &[]);
let groups = batch_count.div_ceil(64);
pass.dispatch_workgroups(groups, 1, 1);
}
}
/// Dispatch shadow cascade cull passes into `encoder` for one cascade.
///
/// Reuses the same compute pipelines and BGL as the main pass. The bind group
/// binds `cascade_frustum_bufs[cascade_idx]` instead of the camera frustum, and
/// writes into `shadow_vis_buf` / `shadow_indirect_buf` instead of the main-pass
/// buffers. The shared `counter_buf` is zeroed by `write_indirect_args` at the
/// end of each cascade dispatch, so cascades can be chained in one encoder.
pub(super) fn dispatch_shadow(
&self,
encoder: &mut wgpu::CommandEncoder,
device: &wgpu::Device,
queue: &wgpu::Queue,
cascade_idx: usize,
frustum: &FrustumUniform,
aabb_buf: &wgpu::Buffer,
meta_buf: &wgpu::Buffer,
counter_buf: &wgpu::Buffer,
shadow_vis_buf: &wgpu::Buffer,
shadow_indirect_buf: &wgpu::Buffer,
instance_count: u32,
batch_count: u32,
) {
queue.write_buffer(
&self.cascade_frustum_bufs[cascade_idx],
0,
bytemuck::cast_slice(std::slice::from_ref(frustum)),
);
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some(&format!("shadow_cull_bg_{cascade_idx}")),
layout: &self.bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: self.cascade_frustum_bufs[cascade_idx].as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: aabb_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: meta_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: counter_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: shadow_vis_buf.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 5,
resource: shadow_indirect_buf.as_entire_binding(),
},
],
});
// Pass 1: cull_instances — one thread per instance.
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some(&format!("shadow_cull_instances_pass_{cascade_idx}")),
timestamp_writes: None,
});
pass.set_pipeline(&self.cull_instances_pipeline);
pass.set_bind_group(0, &bind_group, &[]);
pass.dispatch_workgroups(instance_count.div_ceil(64), 1, 1);
}
// wgpu inserts an automatic storage-buffer barrier between compute passes.
// Pass 2: write_indirect_args — one thread per batch.
// Also zeroes batch_counters ready for the next cascade or next frame.
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some(&format!("shadow_write_indirect_args_pass_{cascade_idx}")),
timestamp_writes: None,
});
pass.set_pipeline(&self.write_indirect_args_pipeline);
pass.set_bind_group(0, &bind_group, &[]);
pass.dispatch_workgroups(batch_count.div_ceil(64), 1, 1);
}
}
fn bgl_entries() -> [wgpu::BindGroupLayoutEntry; CULL_BGL_ENTRY_COUNT] {
let compute = wgpu::ShaderStages::COMPUTE;
[
// binding 0: frustum uniform
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: compute,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// binding 1: instance_aabbs (read-only storage)
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: compute,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// binding 2: batch_metas (read-only storage)
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: compute,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// binding 3: batch_counters (read-write storage, atomic)
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: compute,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// binding 4: visibility_indices (read-write storage)
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: compute,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// binding 5: indirect_args (read-write storage)
wgpu::BindGroupLayoutEntry {
binding: 5,
visibility: compute,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
]
}
}