sgl-3d 0.9.2

Caller-driven 3D rendering for SGL games, native and in the browser (WebGPU)
Documentation
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
//! Volumetric fog: Godot's froxel volume (`fog.wgsl`), after Hillaire 2015.
//! A volume of froxels fills the camera's frustum out to the fog's length,
//! its depth slices spread toward the camera. Each frame bounds the froxels
//! each of the scene's fog volumes reaches, as Godot does (`volume_froxels`),
//! sums the frame's medium and the volumes reaching each froxel, lights it
//! with the directional lights through their cascades, the camera's clustered
//! point, spot and rectangle lights through their local-light shadows, and
//! the ambient light, blends it with where the froxel was in the last frame's
//! volume, filters each slice across x and then y with Godot's Gaussian,
//! then integrates each column front to back into the light scattered
//! toward the camera and the transmittance to every slice. Every draw that
//! fogs samples that volume where its point lies (`shading/fog.wgsl`), so
//! opaque surfaces, blended surfaces, effects and the sky (by
//! `Fog::sky_affect`) take one fog.
//!
//! Placement: after shadows and before opaque, as Godot updates its
//! volumetric fog before its opaque pass (`render_forward_clustered.cpp`
//! `_pre_opaque_render`): it needs the frame's shadow maps and clusters and
//! no depth.
//!
//! Reads: the camera's lit group 0 (its clusters, the scene's lights, the
//! frame's local-light atlas and cascades, its directional lights, hemisphere
//! fill and environment), the frame's `FrameInput::fog`, the scene's fog
//! volumes, the camera history, and its own last volume.
//! Writes: the froxels each fog volume reaches, its froxel volumes and the
//! integrated volume, which group 0 lends draws and source completion
//! samples.
//! Honours: the effective fog (`Settings::atmosphere`, `Settings::fog_quality`
//! and `FrameInput::atmosphere`); without it, it does not run and nothing
//! fogs. The filter runs with `Settings::fog_filter`.
//! Timing groups: `fog injection`, `fog filter`, `fog integration`.
use crate::settings::FogQuality;
use crate::view::bindings::FogVolume;
use crate::view::frame::FrameContext;
use volumes::Volumes;

/// The injection under the lit group 0, and the filter and integration,
/// which bind no group 0.
pub(crate) static VOLUMETRIC_FOG: crate::shading::Module = crate::shading::Module {
    name: "volumetric_fog",
    source: include_str!("fog.wgsl"),
    deps: &[
        &crate::shading::BIND_LIT,
        &crate::shading::LIGHTS,
        &crate::shading::DIRECTIONAL_SHADOW,
        &crate::shading::SHADOW_MASK_NONE,
        &crate::shading::CONTACT_SHADOW_NONE,
        &crate::shading::ENVIRONMENT,
        &crate::shading::PBR,
        &crate::shading::RECT_LIGHT,
        &crate::shading::FOG,
        &crate::shading::FINITE,
        &crate::shading::sky::SKY,
    ],
};
/// The entry points the fog's pipelines are created with.
pub(crate) const INJECT_ENTRY: &str = "inject";
pub(crate) const FILTER_FROXELS_ENTRY: &str = "filter_froxels";
pub(crate) const INTEGRATE_ENTRY: &str = "integrate";

/// What a froxel and its integration store: RGBA16F, which filters and
/// stores in compute everywhere.
const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
/// The injection's workgroup side, in froxels along each axis.
const INJECT_GROUP: u32 = 4;
/// The filter's workgroup side, in invocations along x and y of one slice.
const FILTER_GROUP: u32 = 8;
/// The froxels each filter invocation filters along its pass's axis.
const FILTER_RUN: u32 = 8;
/// The integration's workgroup side, in columns along x and y.
const INTEGRATE_GROUP: u32 = 8;
/// Godot's `VolumetricFog::MAX_TEMPORAL_FRAMES`: the frames its froxel jitter
/// cycles through.
const TEMPORAL_FRAMES: u32 = 16;
/// The share of the last frame's volume a froxel keeps where it reprojects:
/// Godot's default `volumetric_fog_temporal_reproject_amount` (b130438
/// `scene/resources/environment.h`).
const TEMPORAL_REPROJECT_AMOUNT: f32 = 0.9;
/// Godot's anisotropy range.
const MAX_ANISOTROPY: f32 = 0.9;

/// `FroxelVolume` in fog.wgsl.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct FroxelVolumeUniform {
    world_from_view: [[f32; 4]; 4],
    previous_clip_from_world: [[f32; 4]; 4],
    projection: [f32; 4],
    size: [u32; 3],
    frame: u32,
    albedo: [f32; 3],
    density: f32,
    render_size: [f32; 2],
    length: f32,
    detail_spread: f32,
    height: f32,
    height_falloff: f32,
    anisotropy: f32,
    temporal_blend: f32,
    ambient: f32,
    volume_count: u32,
    previous_length: f32,
    start: f32,
    volume_layout: crate::shading::fog::FogLayout,
    /// WGSL rounds `FroxelVolume` up to its 16-byte alignment.
    padding_layout: [u32; 3],
}

/// The layouts this stage mirrors.
#[cfg(test)]
pub(crate) fn mirrors() -> Vec<crate::shading::layout_tests::Mirror> {
    use crate::shading::layout_tests::mirror;
    vec![mirror!(
        "volumetric_fog",
        "FroxelVolume",
        FroxelVolumeUniform,
        [
            world_from_view,
            previous_clip_from_world,
            projection,
            size,
            frame,
            albedo,
            density,
            render_size,
            length,
            detail_spread,
            height,
            height_falloff,
            anisotropy,
            temporal_blend,
            ambient,
            volume_count,
            previous_length,
            start,
            volume_layout,
        ]
    )]
}

/// The constant this stage shares with its shader.
#[cfg(test)]
pub(crate) fn constants() -> [crate::shading::layout_tests::Constant; 1] {
    [crate::shading::layout_tests::Constant::new(
        "volumetric_fog",
        "FOG_MOST_VOLUMES",
        naga::Literal::U32(volume_froxels::MOST_VOLUMES as u32),
    )]
}

/// The froxels of `quality` for a frame of `render` pixels, each side no
/// more than `largest`, the device's 3D texture limit: Godot's volume size
/// as the geometric mean of the two sides, so its froxels are square and
/// it holds as many as Godot's, and its depth slices. Godot's own split
/// (`side × r`, `side / r` with `r = w / ((w + h) / 2)`) leaves its froxels
/// wider than tall and its height unbounded as the frame narrows.
pub(crate) fn froxels(quality: FogQuality, render: [u32; 2], largest: u32) -> [u32; 3] {
    let (side, depth) = quality.volume();
    let [width, height] = render.map(|v| v.max(1) as f32);
    let across = |aspect: f32| ((side as f32 * aspect.sqrt()) as u32).clamp(1, largest);
    [across(width / height), across(height / width), depth]
}

struct Pipelines {
    inject: wgpu::ComputePipeline,
    /// Along x, then y.
    filter: [wgpu::ComputePipeline; 2],
    integrate: wgpu::ComputePipeline,
}

pub(crate) struct VolumetricFog {
    pipelines: Option<Pipelines>,
    /// The aerial volume the integration binds while aerial perspective is
    /// not in effect, which it then does not sample.
    no_aerial: wgpu::TextureView,
    inject_layout: wgpu::BindGroupLayout,
    filter_layout: wgpu::BindGroupLayout,
    integrate_layout: wgpu::BindGroupLayout,
    uniform: wgpu::Buffer,
    reached: volume_froxels::ReachedFroxels,
    /// Linear and clamped: reprojection's and every draw's.
    sampler: wgpu::Sampler,
    volumes: Volumes,
}

impl Pipelines {
    fn new(
        device: &wgpu::Device,
        lit: &wgpu::BindGroupLayout,
        inject_layout: &wgpu::BindGroupLayout,
        filter_layout: &wgpu::BindGroupLayout,
        integrate_layout: &wgpu::BindGroupLayout,
    ) -> Self {
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("volumetric fog"),
            source: wgpu::ShaderSource::Wgsl(crate::shading::compose(&[&VOLUMETRIC_FOG]).into()),
        });
        let pipeline = |label,
                        layouts: &[Option<&wgpu::BindGroupLayout>],
                        entry,
                        constants: &[(&str, f64)]| {
            let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some(label),
                bind_group_layouts: layouts,
                immediate_size: 0,
            });
            device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
                label: Some(label),
                layout: Some(&layout),
                module: &shader,
                entry_point: Some(entry),
                compilation_options: wgpu::PipelineCompilationOptions {
                    constants,
                    ..Default::default()
                },
                cache: None,
            })
        };
        let inject = pipeline(
            "volumetric fog injection",
            &[Some(lit), Some(inject_layout)],
            INJECT_ENTRY,
            &[],
        );
        let filter = [0., 1.].map(|axis| {
            pipeline(
                "volumetric fog filter",
                &[None, Some(filter_layout)],
                FILTER_FROXELS_ENTRY,
                &[("filter_axis", axis)],
            )
        });
        let integrate = pipeline(
            "volumetric fog integration",
            &[None, Some(integrate_layout)],
            INTEGRATE_ENTRY,
            &[],
        );
        Self {
            inject,
            filter,
            integrate,
        }
    }
}

impl VolumetricFog {
    /// One froxel for group 0 until a frame uses fog.
    pub fn new(device: &wgpu::Device) -> Self {
        let uniform = wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: wgpu::ShaderStages::COMPUTE,
            ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        };
        let texture = |binding, filterable| wgpu::BindGroupLayoutEntry {
            binding,
            visibility: wgpu::ShaderStages::COMPUTE,
            ty: wgpu::BindingType::Texture {
                sample_type: wgpu::TextureSampleType::Float { filterable },
                view_dimension: wgpu::TextureViewDimension::D3,
                multisampled: false,
            },
            count: None,
        };
        let storage = |binding| wgpu::BindGroupLayoutEntry {
            binding,
            visibility: wgpu::ShaderStages::COMPUTE,
            ty: wgpu::BindingType::StorageTexture {
                access: wgpu::StorageTextureAccess::WriteOnly,
                format: FORMAT,
                view_dimension: wgpu::TextureViewDimension::D3,
            },
            count: None,
        };
        let read_only_storage = |binding| wgpu::BindGroupLayoutEntry {
            binding,
            visibility: wgpu::ShaderStages::COMPUTE,
            ty: wgpu::BindingType::Buffer {
                ty: wgpu::BufferBindingType::Storage { read_only: true },
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        };
        let inject_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("volumetric fog injection"),
            entries: &[
                uniform,
                texture(1, true),
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                storage(3),
                read_only_storage(6),
                read_only_storage(9),
            ],
        });
        let filter_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("volumetric fog filter"),
            entries: &[uniform, texture(7, false), storage(8)],
        });
        let integrate_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("volumetric fog integration"),
            entries: &[
                uniform,
                texture(4, false),
                storage(5),
                texture(10, true),
                wgpu::BindGroupLayoutEntry {
                    binding: 11,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });
        let uniform = crate::counters::buffer(
            device,
            &wgpu::BufferDescriptor {
                label: Some("volumetric fog froxels"),
                size: size_of::<FroxelVolumeUniform>() as u64,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            },
        );
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("volumetric fog"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });
        let volumes = Volumes::new(device, &filter_layout, &uniform, ([1; 3], [1; 3]));
        let no_aerial = device
            .create_texture(&wgpu::TextureDescriptor {
                label: Some("no aerial perspective"),
                size: wgpu::Extent3d {
                    width: 1,
                    height: 1,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D3,
                format: FORMAT,
                usage: wgpu::TextureUsages::TEXTURE_BINDING,
                view_formats: &[],
            })
            .create_view(&Default::default());
        Self {
            pipelines: None,
            no_aerial,
            inject_layout,
            filter_layout,
            integrate_layout,
            uniform,
            reached: volume_froxels::ReachedFroxels::new(device),
            sampler,
            volumes,
        }
    }

    /// Sizes the volumes for `quality`, the effective fog's, at the render
    /// size `render`, and the integrated volume for the frame's fog volume,
    /// with the aerial slices while aerial perspective is in effect
    /// (`aerial`): without the fog, no froxel volume, and an integrated one
    /// as wide as the aerial volume. A new froxel size starts the volumes'
    /// history over; a new integrated size alone (aerial perspective coming
    /// into or out of effect) keeps it. With neither, the froxels stay as
    /// they are, and the stage lets go of the aerial volume and of an
    /// integrated volume made for aerial perspective alone.
    pub fn prepare(
        &mut self,
        device: &wgpu::Device,
        (quality, aerial): (Option<FogQuality>, bool),
        render: [u32; 2],
    ) {
        let layout = crate::shading::fog::FogLayout::new(
            quality.map(|quality| (quality.volume().1, 1.)),
            aerial,
        );
        let (size, integrated_size) = match quality {
            Some(quality) => {
                let size = froxels(quality, render, device.limits().max_texture_dimension_3d);
                (size, [size[0], size[1], layout.slices()])
            }
            None if aerial => {
                let side = crate::shading::sky::AERIAL_SIDE;
                ([1; 3], [side, side, layout.slices()])
            }
            None => {
                let volumes = &mut self.volumes;
                volumes.integrate = None;
                if volumes.size == [1; 3] && volumes.integrated_size != [1; 3] {
                    *volumes =
                        Volumes::new(device, &self.filter_layout, &self.uniform, ([1; 3], [1; 3]));
                }
                return;
            }
        };
        if self.volumes.size != size {
            self.volumes = Volumes::new(
                device,
                &self.filter_layout,
                &self.uniform,
                (size, integrated_size),
            );
        } else if self.volumes.integrated_size != integrated_size {
            self.volumes.resize_integrated(
                device,
                &self.filter_layout,
                &self.uniform,
                integrated_size,
            );
        }
    }

    /// Whether the stage holds an aerial volume (bound to its integration)
    /// or an integrated volume made for aerial perspective alone.
    #[cfg(test)]
    pub fn holds_aerial(&self) -> bool {
        let volumes = &self.volumes;
        volumes
            .integrate
            .as_ref()
            .is_some_and(|(bound, _)| *bound != self.no_aerial)
            || (volumes.size == [1; 3] && volumes.integrated_size != [1; 3])
    }

    /// The integrated volume and its sampler, which group 0 binds.
    pub fn volume(&self) -> FogVolume<'_> {
        FogVolume {
            view: &self.volumes.integrated,
            sampler: &self.sampler,
        }
    }

    /// The froxels the last frame wrote, which its successor reprojects,
    /// the froxels its integration read and the integrated volume.
    #[cfg(all(test, not(target_arch = "wasm32")))]
    pub fn test_volumes(&self) -> [&wgpu::TextureView; 3] {
        let volumes = &self.volumes;
        let last = volumes.holds.last();
        [
            &volumes.scattering[last],
            &volumes.scattering[volumes.integrated_from],
            &volumes.integrated,
        ]
    }

    /// Lights and integrates the frame's volume while the frame has fog,
    /// and composes it over the sky stage's `aerial` volume into the
    /// frame's one fog volume while aerial perspective is in effect, the
    /// integration alone without the fog.
    pub fn encode(&mut self, ctx: &mut FrameContext<'_>, aerial: Option<&wgpu::TextureView>) {
        let history = ctx.history;
        let volumes = &mut self.volumes;
        let held = volumes
            .holds
            .frame(&history, ctx.effective.fog.map(|_| ctx.input.fog.length));
        let Some(layout) = ctx.effective.fog_layout(ctx.input) else {
            return;
        };
        let aerial = aerial.filter(|_| layout.aerial_slices > 0);
        let pipelines = self.pipelines.get_or_insert_with(|| {
            Pipelines::new(
                ctx.device,
                &ctx.bindings.lit.layout,
                &self.inject_layout,
                &self.filter_layout,
                &self.integrate_layout,
            )
        });
        let fog = ctx.input.fog;
        let camera = ctx.input.camera;
        let [width, height, _] = volumes.integrated_size;
        let mut uniform = FroxelVolumeUniform {
            world_from_view: camera.view.inverse().to_cols_array_2d(),
            previous_clip_from_world: history.previous.to_cols_array_2d(),
            projection: crate::shading::fog::froxel_projection(camera.projection),
            size: match held {
                Some(_) => volumes.size,
                None => [width, height, 0],
            },
            frame: history.frames % TEMPORAL_FRAMES,
            albedo: fog.albedo,
            density: fog.density.max(0.),
            render_size: ctx.sizes.render.map(|v| v as f32),
            length: fog.length,
            detail_spread: crate::shading::fog::DETAIL_SPREAD,
            height: fog.height,
            height_falloff: fog.height_falloff.max(0.),
            anisotropy: fog.anisotropy.clamp(-MAX_ANISOTROPY, MAX_ANISOTROPY),
            temporal_blend: if held.is_some_and(|(_, previous)| previous.is_some()) {
                TEMPORAL_REPROJECT_AMOUNT
            } else {
                0.
            },
            ambient: fog.ambient.max(0.),
            volume_count: 0,
            previous_length: held
                .and_then(|(_, previous)| previous)
                .unwrap_or(fog.length),
            start: fog.effective_start(),
            volume_layout: layout,
            padding_layout: [0; 3],
        };
        volumes.bind_aerial(
            ctx.device,
            &self.integrate_layout,
            &self.uniform,
            (aerial.unwrap_or(&self.no_aerial), &self.sampler),
        );
        let Some((index, _)) = held else {
            // Aerial perspective alone: no froxels to light or filter.
            crate::counters::write_buffer(
                ctx.queue,
                &self.uniform,
                0,
                bytemuck::bytes_of(&uniform),
            );
            let mut pass = ctx
                .encoder
                .begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("volumetric fog integration"),
                    timestamp_writes: ctx.timing.and_then(|t| t.compute_pass("fog integration")),
                });
            pass.set_pipeline(&pipelines.integrate);
            pass.set_bind_group(1, volumes.integrate_group(0), &[]);
            pass.dispatch_workgroups(
                width.div_ceil(INTEGRATE_GROUP),
                height.div_ceil(INTEGRATE_GROUP),
                1,
            );
            return;
        };
        uniform.volume_count = self.reached.write(
            ctx.device,
            ctx.queue,
            &ctx.scene.transient.fog_volume_corners,
            camera.view,
            &uniform,
        );
        let fog_volumes = &ctx.scene.transient.fog_volumes;
        let reached = &self.reached.buffer;
        if volumes
            .inject
            .as_ref()
            .is_none_or(|(scene, bound, _)| scene != fog_volumes || bound != reached)
        {
            let groups = [0, 1].map(|index| {
                let view = wgpu::BindingResource::TextureView;
                ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("volumetric fog injection"),
                    layout: &self.inject_layout,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: self.uniform.as_entire_binding(),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: view(&volumes.scattering[1 - index]),
                        },
                        wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::Sampler(&self.sampler),
                        },
                        wgpu::BindGroupEntry {
                            binding: 3,
                            resource: view(&volumes.scattering[index]),
                        },
                        wgpu::BindGroupEntry {
                            binding: 6,
                            resource: fog_volumes.as_entire_binding(),
                        },
                        wgpu::BindGroupEntry {
                            binding: 9,
                            resource: reached.as_entire_binding(),
                        },
                    ],
                })
            });
            volumes.inject = Some((fog_volumes.clone(), reached.clone(), groups));
        }
        let inject = &volumes.inject.as_ref().unwrap().2[index];
        crate::counters::write_buffer(ctx.queue, &self.uniform, 0, bytemuck::bytes_of(&uniform));
        let [x, y, z] = volumes.size;
        // Two passes, so the integration binds no group 0.
        let mut pass = ctx
            .encoder
            .begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("volumetric fog injection"),
                timestamp_writes: ctx.timing.and_then(|t| t.compute_pass("fog injection")),
            });
        pass.set_pipeline(&pipelines.inject);
        pass.set_bind_group(0, ctx.bindings.camera_lit(), &[]);
        pass.set_bind_group(1, inject, &[]);
        pass.dispatch_workgroups(
            x.div_ceil(INJECT_GROUP),
            y.div_ceil(INJECT_GROUP),
            z.div_ceil(INJECT_GROUP),
        );
        drop(pass);
        // Godot's filter, after the history is kept and before integration
        // (fog.cpp volumetric_fog_update).
        volumes.integrated_from = index;
        if ctx.effective.fog_filter {
            let mut pass = ctx
                .encoder
                .begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: Some("volumetric fog filter"),
                    timestamp_writes: ctx.timing.and_then(|t| t.compute_pass("fog filter")),
                });
            // A pass's invocations each filter a run along its axis.
            let groups = |side: u32, along: bool| {
                side.div_ceil(FILTER_GROUP * if along { FILTER_RUN } else { 1 })
            };
            for (axis, (pipeline, group)) in pipelines
                .filter
                .iter()
                .zip(&volumes.filter[index])
                .enumerate()
            {
                pass.set_pipeline(pipeline);
                pass.set_bind_group(1, group, &[]);
                pass.dispatch_workgroups(groups(x, axis == 0), groups(y, axis == 1), z);
            }
            // A submitted frame may be retried without finish_frame. The
            // other volume then holds this frame, not its predecessor.
            volumes.holds.filtered(index);
            volumes.integrated_from = 1 - index;
        }
        let mut pass = ctx
            .encoder
            .begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("volumetric fog integration"),
                timestamp_writes: ctx.timing.and_then(|t| t.compute_pass("fog integration")),
            });
        pass.set_pipeline(&pipelines.integrate);
        pass.set_bind_group(1, volumes.integrate_group(volumes.integrated_from), &[]);
        pass.dispatch_workgroups(x.div_ceil(INTEGRATE_GROUP), y.div_ceil(INTEGRATE_GROUP), 1);
    }
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests;
pub(crate) mod volume_froxels;
mod volumes;