Skip to main content

wde_pbr/post_process/
pass_exposure.rs

1use wde_logger::prelude::*;
2
3use bevy::{
4    ecs::system::{
5        SystemParamItem,
6        lifetimeless::{SRes, SResMut}
7    },
8    prelude::*
9};
10use wde_renderer::{prelude::*, wgpu_utils::*};
11
12use super::data::PostProcessBuffers;
13use crate::prelude::*;
14
15/// Workgroup size of the histogram shader, in pixels per side.
16const HISTOGRAM_TILE: u32 = 16;
17
18/// Eye adaptation: bins the luminance of the [`RenderTexture`] into a histogram, then moves the adapted
19/// exposure towards the one bringing its average (within the metering percentiles) to middle grey.
20///
21/// The adapted exposure stays on the GPU and is applied by the composite pass. It has a render index of 92,
22/// and does nothing when [`ExposureSettings::eye_adaptation`] is disabled.
23pub struct RenderPassExposure;
24impl RenderPass for RenderPassExposure {
25    type Params = ();
26
27    fn describe(_: &SystemParamItem<Self::Params>) -> RenderPassDesc {
28        RenderPassDesc::default()
29    }
30
31    fn id() -> RenderPassId {
32        92
33    }
34    fn label() -> &'static str {
35        "exposure"
36    }
37
38    fn custom_render(world: &mut World, command_buffer: &mut CommandBuffer) -> Option<bool> {
39        if world.resource::<PostProcessUniform>().exposure[0] <= 0.0 {
40            return Some(true);
41        }
42        Some(
43            world.resource_scope(|world, mut bind_group: Mut<ExposureBindGroup>| {
44                bind_group.update(world) && render_exposure(world, &bind_group, command_buffer)
45            })
46        )
47    }
48}
49
50fn exposure_layout() -> BindGroupLayout {
51    BindGroupLayout::new("exposure", |builder| {
52        let storage = BufferBindingType::Storage { read_only: false };
53        builder
54            .add_texture_view_filterable(0, ShaderStages::COMPUTE, false, true)
55            .add_buffer(1, ShaderStages::COMPUTE, BufferBindingType::Uniform)
56            .add_buffer(2, ShaderStages::COMPUTE, storage)
57            .add_buffer(3, ShaderStages::COMPUTE, storage);
58    })
59}
60
61/// Bind group of the exposure shaders: the render texture, the parameters, the histogram and the exposure.
62#[derive(Resource, Default)]
63pub(crate) struct ExposureBindGroup {
64    texture: Option<AssetId<Texture>>,
65    size: (u32, u32),
66    bind_group: Option<BindGroup>
67}
68impl ExposureBindGroup {
69    /// Recreates the bind group if the render texture changed. Returns false if it is not ready.
70    fn update(&mut self, world: &World) -> bool {
71        let Some(texture) = world
72            .resource::<RenderAssets<GpuRenderData<RenderTexture>>>()
73            .iter()
74            .next()
75            .and_then(|(_, t)| t.get_texture(RenderTexture::BINDING))
76            .map(|t| t.id())
77        else {
78            return false;
79        };
80        if self.texture == Some(texture) && self.bind_group.is_some() {
81            return true;
82        }
83
84        let Some((_, data)) = world
85            .resource::<RenderAssets<GpuRenderData<PostProcessBuffers>>>()
86            .iter()
87            .next()
88        else {
89            return false;
90        };
91        let gpu_buffers = world.resource::<RenderAssets<GpuBuffer>>();
92        let buffer = |idx| data.get_buffer(idx).and_then(|b| gpu_buffers.get(&b));
93        let (Some(params), Some(histogram), Some(exposure)) = (
94            buffer(PostProcessBuffers::PARAMS_IDX),
95            buffer(PostProcessBuffers::HISTOGRAM_IDX),
96            buffer(PostProcessBuffers::EXPOSURE_IDX)
97        ) else {
98            return false;
99        };
100        let Some(gpu_texture) = world.resource::<RenderAssets<GpuTexture>>().get(texture) else {
101            return false;
102        };
103
104        let instance = world.resource::<RenderInstance>().0.read().unwrap();
105        let Ok(layout) = exposure_layout().build(&instance) else {
106            return false;
107        };
108        let Ok(bind_group) = BindGroupBuilder::build(
109            "exposure",
110            &instance,
111            &layout,
112            &vec![
113                BindGroupBuilder::texture_view(0, &gpu_texture.texture),
114                BindGroupBuilder::buffer(1, &params.buffer),
115                BindGroupBuilder::buffer(2, &histogram.buffer),
116                BindGroupBuilder::buffer(3, &exposure.buffer),
117            ]
118        ) else {
119            return false;
120        };
121        self.texture = Some(texture);
122        self.size = gpu_texture.texture.size;
123        self.bind_group = Some(bind_group);
124        true
125    }
126}
127
128fn render_exposure(
129    world: &World,
130    bind_group: &ExposureBindGroup,
131    command_buffer: &mut CommandBuffer
132) -> bool {
133    let pipeline_manager = world.resource::<PipelineManager>();
134    let pipeline =
135        |id: Option<CachedPipelineIndex>| match id.map(|id| pipeline_manager.get_pipeline(id)) {
136            Some(CachedPipelineStatus::OkCompute(p)) => Some(p),
137            _ => None
138        };
139    let (Some(histogram), Some(average), Some(bind_group_gpu)) = (
140        pipeline(
141            world
142                .resource::<RenderAssets<ExposureHistogramPipeline>>()
143                .iter()
144                .next()
145                .map(|(_, p)| p.0)
146        ),
147        pipeline(
148            world
149                .resource::<RenderAssets<ExposureAveragePipeline>>()
150                .iter()
151                .next()
152                .map(|(_, p)| p.0)
153        ),
154        bind_group.bind_group.as_ref()
155    ) else {
156        return false;
157    };
158
159    // Separate dispatches: the average reads the histogram written by every workgroup
160    let mut pass = command_buffer.create_compute_pass("exposure");
161    let (width, height) = bind_group.size;
162    for (pipeline, workgroups) in [
163        (
164            histogram,
165            (
166                width.div_ceil(HISTOGRAM_TILE),
167                height.div_ceil(HISTOGRAM_TILE)
168            )
169        ),
170        (average, (1, 1))
171    ] {
172        if pass.set_pipeline(pipeline).is_err() {
173            return false;
174        }
175        pass.set_bind_group(0, bind_group_gpu);
176        if let Err(e) = pass.dispatch(workgroups.0, workgroups.1, 1) {
177            trace!("Failed to dispatch the exposure compute: {:?}.", e);
178            return false;
179        }
180    }
181    true
182}
183
184macro_rules! exposure_pipeline {
185    ($name:ident, $label:literal, $shader:literal) => {
186        #[derive(TypePath, Default, Clone, Debug)]
187        pub(crate) struct $name(pub CachedPipelineIndex);
188        impl RenderAsset for $name {
189            type SourceAsset = RenderPipelineAsset<$name>;
190            type Params = (SRes<AssetServer>, SResMut<PipelineManager>);
191
192            fn prepare(
193                _id: AssetId<Self::SourceAsset>,
194                asset: Self::SourceAsset,
195                (assets_server, pipeline_manager): &mut SystemParamItem<Self::Params>
196            ) -> Result<Self, PrepareAssetError<Self::SourceAsset>> {
197                Ok($name(pipeline_manager.create_compute_pipeline(
198                    ComputePipelineDescriptor {
199                        label: $label,
200                        comp: Some(assets_server.load($shader)),
201                        bind_group_layouts: vec![Some(exposure_layout())],
202                        push_constants: vec![]
203                    },
204                    asset
205                )?))
206            }
207        }
208    };
209}
210exposure_pipeline!(
211    ExposureHistogramPipeline,
212    "exposure-histogram",
213    "core/render/post_process/exposure_histogram.comp.wgsl"
214);
215exposure_pipeline!(
216    ExposureAveragePipeline,
217    "exposure-average",
218    "core/render/post_process/exposure_average.comp.wgsl"
219);