Skip to main content

crcbl_render/
exposure.rs

1//! Topic 43 §6's auto-exposure: the luminance
2//! histogram of the finished frame, the reduce that turns it into one number,
3//! and the buffer the tonemap reads that number out of.
4//!
5//! ```text
6//!  begin_frame ──▶ extent ──▶ params[frame]
7//!
8//!  add_passes ── compute "exposure-clear"     ──▶ histogram[frame]
9//!             ── compute "exposure-histogram" scene-color ──▶ histogram[frame]
10//!             ── compute "exposure-reduce"    histogram   ──▶ measured[frame]
11//!                                                  tonemap reads measured[frame]
12//! ```
13//!
14//! A module of its own on [`crate::volumetric`]'s terms exactly: three
15//! pipelines, two buffer rings and the pass group, none of it reachable from
16//! the passes that draw except through [`Exposure::add_passes`].
17//!
18//! # Nothing here is read back, and nothing here is a frame behind
19//!
20//! All three passes run inside the frame they measure — the histogram bins the
21//! scene colour the passes before it produced, and the tonemap that follows
22//! reads the exposure the reduce wrote. So the exposure a frame is drawn with
23//! is measured from that frame, with no readback to stall on.
24//!
25//! The one value that survives between frames is the adaptation's starting
26//! point: with an [`ExposureAdaptation`] set, the reduce steps from the
27//! previous frame's exposure — the `measured` ring's slot behind the one it
28//! writes — toward this frame's measurement, so a cut between two
29//! differently-lit shots rolls rather than landing in a single frame.
30//!
31//! # The switch is a lane of the tonemap's block
32//!
33//! `tonemap.slang` binds [`Exposure::measured`]'s buffer on every frame and
34//! reads it only when its block says to, so a frame that adds no passes here
35//! writes a zero into that lane and draws exactly the picture this engine drew
36//! before the pass existed. [`crate::forward`] is what writes both.
37
38use crcbl_hal::{
39    BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
40    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
41    BufferUsage, ComputePipelineHandle, Device, HalError, ImageViewHandle, ImageViewType,
42    MemoryLocation, PipelineLayoutDesc, PipelineLayoutHandle, QueueHandle, ResourceState,
43    SampleType, ShaderStages, check_portable_storage_buffers,
44};
45use crcbl_shaders::EXPOSURE;
46use crcbl_shaders::exposure::{
47    BIN_COUNT, BIN_STRIDE, ExposureParams, MEASURED_SIZE, PARAMS_SIZE, WORKGROUP_SIZE,
48};
49
50use std::cell::Cell;
51use std::rc::Rc;
52
53use crate::draw_gen::{
54    UINT_STRIDE, bound, compute_pipeline_entry, fill_at_start_up, storage, uniform,
55};
56use crate::graph::{ImageId, ImportedBuffer, RenderGraph};
57use crate::ssao::cached_group;
58
59/// How far one frame's exposure may travel toward the one its histogram asks
60/// for.
61///
62/// **Why a step and not the measurement itself.** A real eye takes seconds to
63/// adapt; an exposure that lands on its target in a single frame turns a camera
64/// cut, a muzzle flash or a door opening into a flicker. So a view hands this
65/// in every frame with its own delta, and
66/// [`ForwardRenderer::set_exposure_adaptation`](crate::ForwardRenderer::set_exposure_adaptation)
67/// is where it goes.
68///
69/// **The two rates differ because the eye's do.** Adapting *down* to a scene
70/// that just got bright is fast and adapting back up is slow, and a viewer
71/// notices immediately when they are swapped. They are named for what the
72/// exposure does, not for what the scene did: `brighten` is the exposure
73/// climbing, which is the picture getting brighter as the eye opens up in the
74/// dark.
75///
76/// Each is a fraction of the remaining distance per second, so `2.0` covers
77/// half the distance in a quarter of a second and anything at or above
78/// `1.0 / delta` arrives in one frame. It is the linear approximation of the
79/// exponential approach every engine writes as `1 - exp(-rate * delta)`, and it
80/// is linear on purpose: this workspace lets no transcendental reach a colour,
81/// and an exposure multiplies every texel of the frame.
82#[derive(Clone, Copy, Debug, PartialEq)]
83pub struct ExposureAdaptation {
84    /// Fraction of the remaining distance per second while the exposure climbs.
85    pub brighten: f32,
86    /// The same while it falls.
87    pub darken: f32,
88    /// How long this frame was, in seconds — the view's own delta.
89    pub delta: f32,
90}
91
92impl ExposureAdaptation {
93    /// The two blends the block carries: `rate * delta`, clamped into `[0, 1]`.
94    ///
95    /// Clamped here rather than only in the shader because a rate and a delta
96    /// are both a caller's numbers, and the product of two of those is where a
97    /// pause, a breakpoint or a first frame puts a blend of several hundred.
98    fn blends(self) -> (f32, f32) {
99        let blend = |rate: f32| (rate * self.delta).clamp(0.0, 1.0);
100        (blend(self.brighten), blend(self.darken))
101    }
102}
103
104/// The buffers one frame's measurement lives in.
105///
106/// **A window for a test, and this pass's only public surface**, on
107/// [`FroxelBuffers`](crate::FroxelBuffers)' terms: the histogram is checked
108/// against `crcbl_shaders::exposure` bin by bin, which is the one thing that
109/// can tell a wrong bin from a wrong dispatch extent — a frame-level check sees
110/// only the exposure the two of them compose to.
111#[derive(Clone, Copy, Debug)]
112pub struct ExposureBuffers {
113    /// `[bin]`: how many texels of the frame landed in each bin, as
114    /// `histogramMain` left it.
115    pub histogram: BufferHandle,
116    /// `[0]`: the exposure `reduceMain` measured, and the one the tonemap
117    /// applied.
118    pub measured: BufferHandle,
119}
120
121/// Everything the pass owns.
122///
123/// Built once by [`Exposure::new`] and released by [`Exposure::destroy`], which
124/// is the shape every other resource group in this crate has.
125#[derive(Debug)]
126pub(crate) struct Exposure {
127    layout: BindGroupLayoutHandle,
128    pipeline_layout: PipelineLayoutHandle,
129    /// Zeroes the bins. A pass of its own because the histogram accumulates
130    /// with an atomic add — `exposure.slang` says why that is the only clear a
131    /// storage buffer has here.
132    clear: ComputePipelineHandle,
133    histogram_pipeline: ComputePipelineHandle,
134    reduce: ComputePipelineHandle,
135    /// `[frame]`: the extent being binned, one block per frame in flight for
136    /// the frame uniforms' reason — the previous frame may still be reading
137    /// last frame's while this one is written.
138    params: Vec<BufferHandle>,
139    /// `[frame]`: the bins.
140    histograms: Vec<BufferHandle>,
141    /// `[frame]`: the one float the tonemap reads.
142    measured: Vec<BufferHandle>,
143    /// `[frame]`: the group all three dispatches bind, cached against the scene
144    /// view — which is a graph transient, so it cannot be built until the graph
145    /// has realised one.
146    groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
147}
148
149impl Exposure {
150    /// Passes [`Exposure::add_passes`] adds to a frame.
151    ///
152    /// Exact rather than a ceiling: the three run or none of them do.
153    pub(crate) const PASSES: u32 = 3;
154
155    /// Builds the three pipelines and the buffer rings.
156    ///
157    /// # Errors
158    ///
159    /// [`HalError`] from any seam call. **Nothing is released on the failing
160    /// path**, for the reason every other builder in this crate gives: the
161    /// caller holds a rollback, and this is stored in it whole.
162    pub(crate) fn new(
163        device: &dyn Device,
164        queue: QueueHandle,
165        frames: usize,
166    ) -> Result<Self, HalError> {
167        // **Two, not one.** A frame reads the slot behind it for the exposure
168        // to adapt away from, and with a single slot that is the one this
169        // frame's reduce also writes — which the graph refuses outright, since
170        // a pass cannot claim one resource as both written and read. Enforced
171        // here rather than branched around: [`crate::forward::FRAMES_IN_FLIGHT`]
172        // is two, so the one-slot path would be a branch nothing ever takes.
173        if frames < 2 {
174            return Err(HalError::InvalidDescriptor(format!(
175                "auto-exposure needs at least two frames in flight, so a frame can read \
176                 the exposure the frame before it measured; got {frames}"
177            )));
178        }
179        // `exposure.slang`'s declaration order, which is the only order Metal
180        // and D3D12 agree about — see `crcbl_shaders::declaration_order`.
181        let entries = [
182            uniform(0),
183            BindGroupLayoutEntry {
184                binding: 1,
185                visibility: ShaderStages::COMPUTE,
186                kind: BindingKind::SampledImage {
187                    view_type: ImageViewType::D2,
188                    // The `Rgba16Float` scene target: an ordinary colour image,
189                    // and the WGSL artifact declares `texture_2d<f32>` for it.
190                    sample_type: SampleType::Float,
191                },
192                count: 1,
193                flags: BindingFlags::empty(),
194            },
195            storage(2, false, UINT_STRIDE),
196            storage(3, false, size_of::<f32>() as u32),
197            // Read-only: the reduce reads the frame before's exposure and never
198            // writes through this binding, which is what lets it be a different
199            // slot of the same ring the entry above writes.
200            storage(4, true, size_of::<f32>() as u32),
201        ];
202        let desc = BindGroupLayoutDesc {
203            label: Some("exposure"),
204            entries: &entries,
205        };
206        check_portable_storage_buffers(Some("exposure"), &[&desc])?;
207        let layout = device.create_bind_group_layout(&desc)?;
208        let set_layouts = [layout];
209        let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
210            label: Some("exposure"),
211            bind_group_layouts: &set_layouts,
212            push_constants: None,
213        })?;
214        // Three entry points of one module, which is why this is
215        // `compute_pipeline_entry` rather than `compute_pipeline`: the three
216        // share the binning arithmetic and shaders here have no `#include`.
217        let clear = compute_pipeline_entry(
218            device,
219            "exposure clear",
220            &EXPOSURE,
221            "clearMain",
222            pipeline_layout,
223            WORKGROUP_SIZE,
224        )?;
225        let histogram_pipeline = compute_pipeline_entry(
226            device,
227            "exposure histogram",
228            &EXPOSURE,
229            "histogramMain",
230            pipeline_layout,
231            WORKGROUP_SIZE,
232        )?;
233        let reduce = compute_pipeline_entry(
234            device,
235            "exposure reduce",
236            &EXPOSURE,
237            "reduceMain",
238            pipeline_layout,
239            // One invocation for the whole reduce, on the shader's own terms:
240            // float addition is not associative, so a tree would sum the bins in
241            // an order a device schedules and the exposure would differ in its
242            // last place between backends.
243            1,
244        )?;
245
246        let mut params = Vec::with_capacity(frames);
247        let mut histograms = Vec::with_capacity(frames);
248        let mut measured = Vec::with_capacity(frames);
249        for frame in 0..frames {
250            params.push(device.create_buffer(&BufferDesc {
251                label: Some(&format!("exposure params {frame}")),
252                size: PARAMS_SIZE as u64,
253                usage: BufferUsage::UNIFORM,
254                memory: MemoryLocation::HostUpload,
255            })?);
256            histograms.push(device.create_buffer(&BufferDesc {
257                label: Some(&format!("exposure histogram {frame}")),
258                size: u64::from(BIN_COUNT) * BIN_STRIDE as u64,
259                // `TRANSFER_SRC` because a test reads the bins back and compares
260                // them against the host's own binning of the same frame — the
261                // pass has no other observable, since the exposure it produces
262                // is a single number two different mistakes can agree on.
263                usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
264                memory: MemoryLocation::DeviceLocal,
265            })?);
266            let slot = device.create_buffer(&BufferDesc {
267                label: Some(&format!("exposure measured {frame}")),
268                size: MEASURED_SIZE as u64,
269                // `STORAGE` in three stages: written by the reduce, read by the
270                // tonemap, and read again by the *next* frame's reduce as the
271                // exposure to adapt away from. `TRANSFER_DST` for the start-up
272                // fill below.
273                usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC | BufferUsage::TRANSFER_DST,
274                memory: MemoryLocation::DeviceLocal,
275            })?;
276            // **Every slot starts at the default exposure**, because the first
277            // frame's reduce reads one of them as the value to adapt from and a
278            // device-local allocation carries whatever was last in that memory.
279            // A garbage prior inside the legal range would be indistinguishable
280            // from a measurement, and would differ between runs.
281            fill_at_start_up(
282                device,
283                queue,
284                &format!("exposure measured {frame}"),
285                slot,
286                &crcbl_shaders::tonemap::DEFAULT_EXPOSURE.to_le_bytes(),
287                // What `add_passes` imports it in, and what the tonemap left it
288                // in on every frame after the first.
289                ResourceState::ShaderRead,
290            )?;
291            measured.push(slot);
292        }
293
294        Ok(Self {
295            layout,
296            pipeline_layout,
297            clear,
298            histogram_pipeline,
299            reduce,
300            params,
301            histograms,
302            measured,
303            groups: vec![None; frames],
304        })
305    }
306
307    /// Writes `frame`'s parameter block: the extent of the image to bin.
308    ///
309    /// # Errors
310    ///
311    /// [`HalError`] from the mapped write.
312    ///
313    /// # Panics
314    ///
315    /// If `frame` is not a slot this was built with.
316    pub(crate) fn begin_frame(
317        &self,
318        device: &dyn Device,
319        frame: usize,
320        extent: (u32, u32),
321        adaptation: Option<ExposureAdaptation>,
322    ) -> Result<(), HalError> {
323        // `None` is both blends at one, which is the whole distance in one
324        // frame — the picture this pass drew before adaptation existed, and the
325        // one `ExposureParams::default` carries for the same reason.
326        let (brighten_blend, darken_blend) =
327            adaptation.map_or((1.0, 1.0), ExposureAdaptation::blends);
328        device.write_buffer(
329            self.params[frame],
330            0,
331            &ExposureParams {
332                viewport_x: extent.0.max(1),
333                viewport_y: extent.1.max(1),
334                brighten_blend,
335                darken_blend,
336            }
337            .to_bytes(),
338        )
339    }
340
341    /// The slot holding what the frame before `frame` was exposed by.
342    ///
343    /// One step back around the same ring, which is the previous frame because
344    /// the frame index advances by one — and never `frame`'s own slot, which is
345    /// what [`Exposure::new`]'s two-slot floor is for.
346    ///
347    /// # Panics
348    ///
349    /// If `frame` is not a slot this was built with.
350    fn previous(&self, frame: usize) -> BufferHandle {
351        assert!(frame < self.measured.len(), "no such frame slot");
352        self.measured[(frame + self.measured.len() - 1) % self.measured.len()]
353    }
354
355    /// The buffer the tonemap binds: `frame`'s measured exposure.
356    ///
357    /// # Panics
358    ///
359    /// If `frame` is not a slot this was built with.
360    pub(crate) fn measured(&self, frame: usize) -> BufferHandle {
361        self.measured[frame]
362    }
363
364    /// `frame`'s bins and the exposure they were reduced to.
365    ///
366    /// # Panics
367    ///
368    /// If `frame` is not a slot this was built with.
369    pub(crate) fn buffers(&self, frame: usize) -> ExposureBuffers {
370        ExposureBuffers {
371            histogram: self.histograms[frame],
372            measured: self.measured[frame],
373        }
374    }
375
376    /// Adds the clear, the histogram and the reduce, in that order.
377    ///
378    /// `scene` is the image the tonemap is about to read, and binning anything
379    /// else would expose the frame for a picture nobody sees.
380    ///
381    /// # Panics
382    ///
383    /// If `frame` is not a slot this was built with.
384    pub(crate) fn add_passes<'a>(
385        &'a mut self,
386        graph: &mut RenderGraph<'a>,
387        frame: usize,
388        extent: (u32, u32),
389        scene: ImageId,
390    ) {
391        // Both arrive in the state the previous frame that used this slot left
392        // them in, which is the state declared as final: the tonemap read the
393        // measurement and nothing read the bins. Vacuous on the first frame, and
394        // the real prior use on every later one.
395        let bins = graph.import_buffer(
396            "exposure-histogram",
397            ImportedBuffer {
398                buffer: self.histograms[frame],
399                initial: ResourceState::ShaderRead,
400                final_state: ResourceState::ShaderRead,
401            },
402        );
403        let measured = graph.import_buffer(
404            "exposure-measured",
405            ImportedBuffer {
406                buffer: self.measured[frame],
407                initial: ResourceState::ShaderRead,
408                final_state: ResourceState::ShaderRead,
409            },
410        );
411        // The frame before's slot, always a different buffer from the one this
412        // frame writes — `Exposure::new` refuses a ring too short for that.
413        let previous_buffer = self.previous(frame);
414        let previous = graph.import_buffer(
415            "exposure-previous",
416            ImportedBuffer {
417                buffer: previous_buffer,
418                // What the frame that wrote it left it in, and what this frame
419                // leaves it in: nothing here writes through it.
420                initial: ResourceState::ShaderRead,
421                final_state: ResourceState::ShaderRead,
422            },
423        );
424        let params = self.params[frame];
425        let histogram_buffer = self.histograms[frame];
426        let measured_buffer = self.measured[frame];
427        let layout = self.layout;
428        let pipeline_layout = self.pipeline_layout;
429        let clear = self.clear;
430        let histogram = self.histogram_pipeline;
431        let reduce = self.reduce;
432        let cached = &mut self.groups[frame];
433
434        // One group for all three dispatches, built inside the first of them:
435        // it names the scene colour, which is a graph transient, so there is no
436        // view to name until the graph has realised one. Cached against that
437        // view, and therefore rebuilt only on a resize.
438        //
439        // A shared `Cell` carries it to the two passes after this one: the pass
440        // bodies run synchronously and in order on this thread, so the pass that
441        // builds the group has always run before the two that bind it. `Rc`
442        // rather than a borrow because each body is an owned closure the graph
443        // keeps, and a body that finds no group records no dispatch rather than
444        // binding a stale one.
445        let group: Rc<Cell<Option<BindGroupHandle>>> = Rc::new(Cell::new(None));
446        let build = Rc::clone(&group);
447        graph
448            .add_compute_pass("exposure-clear")
449            // `ShaderReadWrite` rather than a write-only state, on the light
450            // grid's terms: a storage-buffer descriptor permits reads whatever
451            // the shader does with it.
452            .use_buffer(bins, ResourceState::ShaderReadWrite)
453            .use_buffer(measured, ResourceState::ShaderReadWrite)
454            // The image the pass after this one bins. Declared here as well
455            // because the group naming it is built in this pass, and a view is
456            // only realised for a pass that declared the image.
457            .read_image(scene)
458            .execute(move |ctx| {
459                let view = ctx.image_view(scene);
460                let device = ctx.device();
461                let entries = [
462                    bound(0, params),
463                    // Overwritten by `cached_group` with the realised view;
464                    // written here so the list is a complete description of the
465                    // layout rather than one with a hole in it.
466                    BindGroupEntry {
467                        binding: 1,
468                        array_index: 0,
469                        resource: BindingResource::ImageView(view),
470                    },
471                    bound(2, histogram_buffer),
472                    bound(3, measured_buffer),
473                    bound(4, previous_buffer),
474                ];
475                let Some(built) =
476                    cached_group(cached, device, &[(1, view)], "exposure", layout, &entries)
477                else {
478                    return;
479                };
480                build.set(Some(built));
481                let encoder = ctx.encoder();
482                encoder.bind_compute_pipeline(clear);
483                encoder.bind_group(0, built, &[], pipeline_layout);
484                encoder.dispatch(BIN_COUNT.div_ceil(WORKGROUP_SIZE), 1, 1);
485            });
486
487        // One invocation per texel of the scene target, and never zero: the
488        // extent is floored at one texel, and Metal rejects an empty dispatch
489        // outright rather than treating it as a no-op.
490        let row_groups = extent.0.max(1).div_ceil(WORKGROUP_SIZE);
491        let rows = extent.1.max(1);
492        let bind = Rc::clone(&group);
493        graph
494            .add_compute_pass("exposure-histogram")
495            .use_buffer(bins, ResourceState::ShaderReadWrite)
496            .read_image(scene)
497            .execute(move |ctx| {
498                let Some(group) = bind.get() else {
499                    return;
500                };
501                let encoder = ctx.encoder();
502                encoder.bind_compute_pipeline(histogram);
503                encoder.bind_group(0, group, &[], pipeline_layout);
504                encoder.dispatch(row_groups, rows, 1);
505            });
506
507        let bind = group;
508        graph
509            .add_compute_pass("exposure-reduce")
510            // The histogram's own output, read here — the graph's barrier
511            // between the two comes from both declaring this one id.
512            .use_buffer(bins, ResourceState::ShaderReadWrite)
513            .use_buffer(measured, ResourceState::ShaderReadWrite)
514            // The frame before's exposure, read to adapt away from.
515            .use_buffer(previous, ResourceState::ShaderRead)
516            .execute(move |ctx| {
517                let Some(group) = bind.get() else {
518                    return;
519                };
520                let encoder = ctx.encoder();
521                encoder.bind_compute_pipeline(reduce);
522                encoder.bind_group(0, group, &[], pipeline_layout);
523                encoder.dispatch(1, 1, 1);
524            });
525    }
526
527    /// Releases every object this owns.
528    pub(crate) fn destroy(self, device: &dyn Device) {
529        for cached in self.groups.into_iter().flatten() {
530            device.destroy_bind_group(cached.1);
531        }
532        device.destroy_compute_pipeline(self.reduce);
533        device.destroy_compute_pipeline(self.histogram_pipeline);
534        device.destroy_compute_pipeline(self.clear);
535        device.destroy_pipeline_layout(self.pipeline_layout);
536        device.destroy_bind_group_layout(self.layout);
537        for buffer in self
538            .params
539            .into_iter()
540            .chain(self.histograms)
541            .chain(self.measured)
542        {
543            device.destroy_buffer(buffer);
544        }
545    }
546}
547
548// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
549#[cfg(all(test, not(target_arch = "wasm32")))]
550mod tests {
551    use super::*;
552    use crate::TransientPool;
553    use crcbl_hal::{
554        ClearValue, CommandEncoderDesc, DeviceDesc, Features, Instance, Limits, LoadOp, QueueKind,
555        StoreOp,
556        null::{Command, NullInstance},
557    };
558
559    #[test]
560    fn histogram_dispatch_stays_within_the_portable_budget() {
561        let backend = NullInstance::portable();
562        let recorder = backend.recorder();
563        let adapter = backend.adapters().remove(0);
564        let device = backend
565            .create_device(&DeviceDesc {
566                required_features: Features::COMPUTE,
567                ..DeviceDesc::for_adapter(adapter.id)
568            })
569            .expect("device");
570        let queue = device.queue(QueueKind::Graphics).expect("queue");
571        let limits = Limits::minimum();
572        for extent in [
573            (3840, 2160),
574            (0, 0),
575            (1, 1),
576            (63, 193),
577            (64, 193),
578            (65, 193),
579            (limits.max_image_2d, limits.max_image_2d),
580        ] {
581            let normalized = (extent.0.max(1), extent.1.max(1));
582            let mut exposure = Exposure::new(device.as_ref(), queue, 2).expect("exposure");
583            exposure
584                .begin_frame(device.as_ref(), 0, extent, None)
585                .expect("parameters");
586            let mut pool = TransientPool::new();
587            let mut graph = RenderGraph::new(queue);
588            let scene = graph.create_image("scene", crate::targets::scene_color(normalized));
589            graph
590                .add_render_pass("scene-clear")
591                .color(scene, LoadOp::Clear, StoreOp::Store, ClearValue::default())
592                .execute(|_| {});
593            exposure.add_passes(&mut graph, 0, extent, scene);
594            let compiled = graph.compile(&pool).expect("compiled");
595            recorder.clear();
596            let mut encoder =
597                device.create_command_encoder(&CommandEncoderDesc { label: None, queue });
598            compiled
599                .execute(device.as_ref(), &mut pool, encoder.as_mut(), None)
600                .expect("recorded");
601            let command_buffer = encoder.finish().expect("finished");
602            let dispatches: Vec<_> = recorder
603                .commands()
604                .into_iter()
605                .filter_map(|command| match command {
606                    Command::Dispatch { x, y, z } => Some([x, y, z]),
607                    _ => None,
608                })
609                .collect();
610            assert_eq!(dispatches.len(), Exposure::PASSES as usize, "{extent:?}");
611            for dispatch in &dispatches {
612                assert!(
613                    dispatch.iter().all(
614                        |&axis| axis > 0 && axis <= limits.max_compute_workgroups_per_dimension
615                    ),
616                    "{extent:?}: {dispatch:?} exceeds the portable dispatch budget"
617                );
618            }
619            assert_eq!(
620                dispatches[1],
621                [normalized.0.div_ceil(WORKGROUP_SIZE), normalized.1, 1],
622                "{extent:?}"
623            );
624            device.destroy_command_buffer(command_buffer);
625            exposure.destroy(device.as_ref());
626            pool.destroy(device.as_ref());
627            recorder.assert_valid();
628        }
629    }
630}