use crate::settings::FogQuality;
use crate::view::bindings::FogVolume;
use crate::view::frame::FrameContext;
use volumes::Volumes;
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::ENVIRONMENT,
&crate::shading::PBR,
&crate::shading::RECT_LIGHT,
&crate::shading::FOG,
],
};
pub(crate) const INJECT_ENTRY: &str = "inject";
pub(crate) const FILTER_FROXELS_ENTRY: &str = "filter_froxels";
pub(crate) const INTEGRATE_ENTRY: &str = "integrate";
const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
const INJECT_GROUP: u32 = 4;
const FILTER_GROUP: u32 = 8;
const FILTER_RUN: u32 = 8;
const INTEGRATE_GROUP: u32 = 8;
const TEMPORAL_FRAMES: u32 = 16;
const TEMPORAL_REPROJECT_AMOUNT: f32 = 0.9;
const MAX_ANISOTROPY: f32 = 0.9;
#[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,
padding: [u32; 2],
}
#[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,
]
)]
}
#[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),
)]
}
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]
}
pub(crate) struct VolumetricFog {
inject: wgpu::ComputePipeline,
filter: [wgpu::ComputePipeline; 2],
integrate: wgpu::ComputePipeline,
inject_layout: wgpu::BindGroupLayout,
filter_layout: wgpu::BindGroupLayout,
integrate_layout: wgpu::BindGroupLayout,
uniform: wgpu::Buffer,
reached: volume_froxels::ReachedFroxels,
sampler: wgpu::Sampler,
volumes: Volumes,
}
impl VolumetricFog {
pub fn new(device: &wgpu::Device, lit: &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 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)],
});
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,
&[],
);
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, &integrate_layout, &uniform, [1; 3]);
Self {
inject,
filter,
integrate,
inject_layout,
filter_layout,
integrate_layout,
uniform,
reached: volume_froxels::ReachedFroxels::new(device),
sampler,
volumes,
}
}
pub fn prepare(
&mut self,
device: &wgpu::Device,
quality: Option<FogQuality>,
render: [u32; 2],
) {
let Some(quality) = quality else {
return;
};
let size = froxels(quality, render, device.limits().max_texture_dimension_3d);
if self.volumes.size != size {
self.volumes = Volumes::new(
device,
&self.filter_layout,
&self.integrate_layout,
&self.uniform,
size,
);
}
}
pub fn volume(&self) -> FogVolume<'_> {
FogVolume {
view: &self.volumes.integrated,
sampler: &self.sampler,
}
}
#[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,
]
}
pub fn encode(&mut self, ctx: &mut FrameContext<'_>) {
let history = ctx.history;
let volumes = &mut self.volumes;
let Some((index, reprojects)) = volumes.holds.frame(&history, ctx.effective.fog.is_some())
else {
return;
};
let fog = ctx.input.fog;
let camera = ctx.input.camera;
let projection = camera.projection;
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: [
projection.x_axis.x,
projection.y_axis.y,
projection.z_axis.x,
projection.z_axis.y,
],
size: volumes.size,
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 reprojects {
TEMPORAL_REPROJECT_AMOUNT
} else {
0.
},
ambient: fog.ambient.max(0.),
volume_count: 0,
padding: [0; 2],
};
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;
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(&self.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);
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")),
});
let groups = |side: u32, along: bool| {
side.div_ceil(FILTER_GROUP * if along { FILTER_RUN } else { 1 })
};
for (axis, (pipeline, group)) in
self.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);
}
volumes.holds.filtered(index, history.frames);
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(&self.integrate);
pass.set_bind_group(1, &volumes.integrate[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;