crcbl-hal 0.4.0

Crucible graphics HAL: backend seam traits and POD descriptors
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
//! Surfaces, swapchains, and the acquire/present pair.
//!
//! # The acquire shape, and why it is this one
//!
//! Stage 10 listed "swapchain acquire is implicit/async" as
//! a constraint the HAL must already satisfy: *"HAL surface API shaped so
//! 'acquire' can be trivial (WebGPU `getCurrentTexture`)"*. The two APIs to
//! reconcile:
//!
//! | | Vulkan | WebGPU |
//! | --- | --- | --- |
//! | Call | `vkAcquireNextImageKHR(sc, timeout, sem, fence, &idx)` | `ctx.getCurrentTexture()` |
//! | Returns | an image index | a texture |
//! | Sync | caller supplies a semaphore to be signalled | none; implicit |
//! | Present | `vkQueuePresentKHR` waits on a semaphore | implicit at rAF end |
//!
//! A literal port of the Vulkan signature — `acquire_next_image(&self, swapchain,
//! semaphore)` — forces the caller to create and rotate binary semaphores it
//! has no use for on a device with no semaphores at all, and forces the wgpu
//! backend to invent and signal fake ones.
//!
//! **The fix: the swapchain owns its synchronisation.** [`Device::acquire_next_frame`](crate::Device::acquire_next_frame)
//! returns an [`AcquiredFrame`] carrying the image *and* an
//! `Option<SemaphoreHandle>` pair, which the backend supplies from its own
//! per-image ring:
//!
//! * `crcbl-vk` returns `Some(..)` for both. The renderer splices
//!   `acquire_semaphore` into its submit's waits and `present_semaphore` into
//!   its signals.
//! * `crcbl-webgpu` returns `None` for both. The same renderer code splices
//!   nothing.
//!
//! The renderer is written once, with no per-backend branch, and the WebGPU
//! implementation is three lines. This is also why [`AcquiredFrame`] hands back
//! an [`ImageHandle`] rather than an index the caller must map: WebGPU has no
//! stable image index to give, only a texture per frame.
//!
//! # The swapchain owns the views too
//!
//! [`AcquiredFrame::view`] is there for the same reason as the two semaphores,
//! and it was added for the same reason: P1.1 found that *every* caller had to
//! build the identical per-image view cache, because
//! [`CommandEncoder::begin_render_pass`](crate::CommandEncoder::begin_render_pass)
//! needs an [`ImageViewHandle`] and acquire yielded only an [`ImageHandle`].
//! That is duplicated bookkeeping in every consumer *and* an index-keyed
//! invalidation rule every backend has to document — to save one field.
//!
//! The swapchain owns its images, so it is the natural owner of their views.
//! A backend creates one view per ring image at configure time, reissues them
//! on [`reconfigure`](crate::Device::reconfigure_swapchain), and destroys them
//! with the swapchain. The view covers the whole image with the swapchain's own
//! format, which is what a colour attachment wants; a caller that needs a
//! different view of a swapchain image — an sRGB reinterpretation, say — still
//! makes its own with [`Device::create_image_view`](crate::Device::create_image_view).
//!
//! # Reconfigure, don't recreate
//!
//! [`Device::reconfigure_swapchain`](crate::Device::reconfigure_swapchain) mirrors WebGPU's `configure()` and covers
//! resize, present-mode change and format change with one call. Vulkan
//! implements it by recreating; wgpu implements it by reconfiguring. Callers
//! never destroy and recreate a swapchain to resize, so the handle stays stable
//! across a resize storm and nothing above has to re-fetch it.
//!
//! # The extent: one request, one answer — implementation obligations
//!
//! Two things claim to know how big a swapchain should be, and they disagree in
//! practice:
//!
//! * the **shell**'s `WindowState::size()`, delivered as a
//!   `ShellEvent::Resized` when the window system configures the window; and
//! * [`SurfaceCaps::current_extent`], queried here.
//!
//! Vulkan makes the disagreement structural rather than hypothetical.
//! `VkSurfaceCapabilitiesKHR::currentExtent` is a real size on X11 (the server
//! knows), and is deliberately `0xFFFFFFFF, 0xFFFFFFFF` on Wayland, which means
//! "you choose — the compositor is not going to tell you". WebGPU has no such
//! query at all. A seam that left this unstated would get one answer from
//! `crcbl-vk` and a different one from `crcbl-webgpu`, and the bug would look
//! like a window that renders at the wrong size on exactly one backend.
//!
//! ## What P1.1 changed, and why
//!
//! These obligations originally said the shell's size was simply what the
//! swapchain *is* configured at, and that a backend "must not fail a create or
//! reconfigure merely because the two differ". Driving them against real
//! Vulkan proved that unimplementable on X11: `imageExtent` must lie within
//! `minImageExtent..=maxImageExtent`, and an X server reports
//! `minImageExtent == maxImageExtent == currentExtent`. So when a resize event
//! is one frame behind — which is the *normal* state during a resize —
//! **there is no legal swapchain at the shell's size at all**. A backend can
//! only clamp, and the old rule left it no way to say so, which meant a caller
//! could render a frame at a size the swapchain did not have.
//!
//! The rule below is the one that survives contact: the shell's size is the
//! **request**, and the extent that came back is on [`AcquiredFrame`].
//!
//! ## The obligations
//!
//! 1. **The shell's size is the request, and the only thing a backend may
//!    start from.** [`SwapchainDesc::extent`] is what the caller asks for. A
//!    backend **must not** substitute [`SurfaceCaps::current_extent`] for it,
//!    and **must not** fail a create or reconfigure merely because the two
//!    differ.
//! 2. **A backend clamps into the platform's permitted range, and reports what
//!    it configured.** Where the window system pins that range — X11 pins it to
//!    `currentExtent` exactly — clamping is forced, not chosen. The configured
//!    size is then reported on every [`AcquiredFrame::extent`], and a backend
//!    that had to clamp **should** say so once in a log line, because it means
//!    the shell and the window system are out of step.
//! 3. **A caller renders at [`AcquiredFrame::extent`], not at the size it asked
//!    for.** That is the render area, the viewport and the scissor. Using the
//!    requested size instead is the bug this field exists to prevent, and it
//!    only appears while a window is being dragged. The two are equal on every
//!    platform that does not pin a range, so this costs nothing to obey.
//! 4. **`current_extent` is a cross-check, and it is optional.** Report it when
//!    the platform supplies a real one; report `None` when it does not.
//!    `0xFFFFFFFF` is **not** a value to pass through — it is the platform
//!    saying "no opinion", so a Vulkan backend maps it to `None` and never lets
//!    that sentinel escape into the seam. Nothing above the seam needs to read
//!    it; obligation 3 already gives a caller the number it acts on.
//! 5. **A zero or absent extent is the caller's problem, not a fallback.** An
//!    unconfigured or minimized window has no size, a zero-extent swapchain is
//!    forbidden in Vulkan, and the answer is to *not create one yet* — never to
//!    guess from `current_extent`.
//!
//! The corollary for [`SurfaceTarget`](crcbl_core::SurfaceTarget): no variant
//! carries a size, including
//! [`Offscreen`](crcbl_core::SurfaceTarget::Offscreen), which used to and no
//! longer does. A target names handles; handles survive a resize; the extent
//! travels in the descriptor. That is what makes "re-query the target after a
//! mode change" a complete rule rather than one with an exception in it.
//!
//! # Offscreen is a swapchain too
//!
//! [`SurfaceTarget::Offscreen`](crcbl_core::SurfaceTarget::Offscreen) produces a
//! surface whose "swapchain" is a ring of plain images. `crcbl screenshot` and
//! the P1 golden-image e2e therefore run through the *same* acquire/present
//! path as a real window, instead of a second, less-exercised one.

use std::time::Duration;

use crcbl_core::Handle;

use crate::{Format, ImageHandle, ImageViewHandle, SemaphoreHandle};

/// Marker type for surface handles. Uninhabited.
#[derive(Debug)]
pub enum Surface {}
/// Marker type for swapchain handles. Uninhabited.
#[derive(Debug)]
pub enum Swapchain {}

/// A presentation surface, created from a
/// [`SurfaceTarget`](crcbl_core::SurfaceTarget).
pub type SurfaceHandle = Handle<Surface>;
/// A swapchain configured on a [`Surface`].
pub type SwapchainHandle = Handle<Swapchain>;

/// How presented images are paced.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PresentMode {
    /// Wait for vblank, queue depth 1. Always supported; the only mode WebGPU
    /// has.
    #[default]
    Fifo,
    /// Wait for vblank, but tear rather than stall if a frame is late.
    FifoRelaxed,
    /// Replace the queued image with the newest one. Low latency, no tearing,
    /// uncapped GPU work. Preferred by `crcbl-vk` where available.
    Mailbox,
    /// Present immediately; tears. For latency measurement and uncapped
    /// benchmarking.
    Immediate,
}

/// What the display is **actually** doing with the frames we present.
///
/// [`PresentMode`] is a request — it picks a queueing discipline and says
/// nothing about the panel behind it. This is the observation, read back with
/// [`Device::display_timing`](crate::Device::display_timing) on a device that
/// advertises [`Features::PRESENT_TIMING`](crate::Features::PRESENT_TIMING).
///
/// The four arms are the four states a presentation engine can be in, not three
/// with a fallback: a refresh cycle can be fixed, free-running, quantised, or
/// simply unreported, and collapsing the third into the first is the specific
/// lie this type exists to prevent.
///
/// **Live, never cached.** See
/// [`Device::display_timing`](crate::Device::display_timing) — the answer
/// changes underneath a running swapchain.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum DisplayTiming {
    /// The presentation engine did not say.
    ///
    /// Covers a device without the capability, a swapchain nothing has been
    /// presented to yet, and — the case worth naming — **a cycle duration that
    /// was reported while its dynamics were not**. That last one is deliberately
    /// not [`Fixed`](Self::Fixed): the platform told us how long the current
    /// cycle is and refused to say whether it will stay that length, and
    /// "how long is a cycle" without "will it change" is not an answer to the
    /// question this type asks. The duration is discarded rather than dressed
    /// up as a promise.
    #[default]
    Unknown,
    /// Fixed refresh: every cycle is `cycle` long, and will stay that way until
    /// this query answers differently.
    Fixed {
        /// The refresh cycle, e.g. 16.67 ms on a 60 Hz panel.
        cycle: Duration,
    },
    /// Adaptive sync, free-running: the cycle has no fixed length, and
    /// `shortest` is the shortest one the presentation engine will produce.
    ///
    /// The ceiling of the panel's VRR range, in other words — present faster
    /// than this and the extra frames cannot be shown.
    Variable {
        /// The shortest cycle the engine will produce; the reciprocal of the
        /// panel's maximum rate.
        shortest: Duration,
    },
    /// The cycle can change, but only in whole multiples of `step`.
    ///
    /// A panel that can drop from 120 Hz to 60 Hz to 40 Hz but nothing between
    /// them: `cycle` is what it is right now, and the next one will be some
    /// other multiple of `step`. Adaptive, so a caller pacing on a fixed
    /// interval is wrong — but bounded, so it is not [`Variable`](Self::Variable)
    /// either.
    Stepped {
        /// The cycle currently in force. Always a whole multiple of `step`.
        cycle: Duration,
        /// The quantum the cycle moves in.
        step: Duration,
    },
}

/// Reads a presentation engine's two refresh figures as a [`DisplayTiming`].
///
/// Both arguments are nanosecond counts in the encoding
/// `VK_EXT_present_timing` defines for `VkSwapchainTimingPropertiesEXT`, which
/// is the only platform that reports this today. Free-standing, and with no
/// backend type in its signature, because the mapping is where every subtle
/// mistake in this seam lives and it is the one part of it that a machine with
/// no display can check.
///
/// The encoding, from the extension proposal:
///
/// * `refresh_duration_ns` of zero — the engine cannot report the cycle length.
/// * `refresh_interval_ns` of zero — the engine cannot report the cycle's
///   dynamics.
/// * `refresh_interval_ns` of [`u64::MAX`] — VRR, and `refresh_duration_ns` is
///   the *minimum* cycle rather than the current one.
/// * the two equal — fixed refresh.
/// * otherwise — the cycle varies in quanta of `refresh_interval_ns`, and
///   `refresh_duration_ns` is a whole multiple of it.
///
/// # Contradictory input
///
/// A driver that reports an interval which does not divide the duration has
/// broken the last of those rules, and the pair cannot be believed:
/// [`DisplayTiming::Stepped`] would hand a caller a `cycle`/`step` whose
/// quotient is not a whole number, and every other arm would be inventing a
/// claim the driver did not make. So the answer is
/// [`DisplayTiming::Unknown`] — the conservative arm, because it is the only
/// one that promises nothing.
#[must_use]
pub fn display_timing_from_refresh_nanos(
    refresh_duration_ns: u64,
    refresh_interval_ns: u64,
) -> DisplayTiming {
    // Nothing below can say anything without a cycle length, including the VRR
    // arm — "the shortest cycle is zero" is not a weaker claim than `Unknown`,
    // it is a false one.
    if refresh_duration_ns == 0 {
        return DisplayTiming::Unknown;
    }
    match refresh_interval_ns {
        0 => DisplayTiming::Unknown,
        // Checked before the equality below, because the two collide when a
        // driver reports `u64::MAX` for both: the sentinel is an explicit
        // spelling of "VRR" and the equality is an inference, so the sentinel
        // wins.
        u64::MAX => DisplayTiming::Variable {
            shortest: Duration::from_nanos(refresh_duration_ns),
        },
        interval if interval == refresh_duration_ns => DisplayTiming::Fixed {
            cycle: Duration::from_nanos(refresh_duration_ns),
        },
        interval if refresh_duration_ns.is_multiple_of(interval) => DisplayTiming::Stepped {
            cycle: Duration::from_nanos(refresh_duration_ns),
            step: Duration::from_nanos(interval),
        },
        _ => DisplayTiming::Unknown,
    }
}

/// How the surface's alpha channel composites with the desktop.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CompositeAlpha {
    /// Alpha ignored; the surface is opaque. The engine's default.
    #[default]
    Opaque,
    /// Alpha is premultiplied into the colour channels.
    PreMultiplied,
    /// Alpha is separate from the colour channels.
    PostMultiplied,
    /// Let the window system decide.
    Inherit,
}

/// What a surface supports on a given adapter.
///
/// Queried with [`Instance::surface_caps`](crate::Instance::surface_caps)
/// *before* a device exists, because present-queue selection on Vulkan needs
/// the answer at device-creation time.
///
/// # Decision: WSI vocabulary is correct here
///
/// P0's seam review flagged [`min_image_count`](Self::min_image_count) /
/// [`max_image_count`](Self::max_image_count) as Vulkan-shaped, since WebGPU
/// has no notion of a swapchain image count. Recorded so it is not
/// re-litigated: *surface capabilities are inherently a WSI concept* — this
/// whole struct describes what a window system will accept — so WSI vocabulary
/// is the right vocabulary in it. A WebGPU backend reports the range its
/// platform actually offers (`2..=2` for a WebGPU canvas, which has one
/// implicit ring) and the caller's clamp code is unchanged. The alternative,
/// removing the fields, would take a real knob away from the three backends
/// that have one.
#[derive(Clone, Debug, PartialEq)]
pub struct SurfaceCaps {
    /// Formats the surface can be configured with, best first.
    ///
    /// **At least one must be sRGB.** That is an obligation on every backend,
    /// not a hope: every pass above the seam writes display-referred values and
    /// leaves the encode to the hardware, so a swapchain configured with a
    /// linear format presents a transfer function too dark — and nothing in the
    /// frame's path notices, because a linear target is a perfectly valid one to
    /// render into. The failure is a picture a human calls wrong and no return
    /// value calls anything.
    ///
    /// A backend whose window system will only *configure* a linear format
    /// still offers the sRGB counterpart here and reaches it through whatever
    /// reinterpretation its API has — a D3D12 flip-model back buffer is linear
    /// with an sRGB render-target view over it, and a WebGPU canvas is linear
    /// with the counterpart in `GPUCanvasConfiguration.viewFormats`. This list
    /// is what the engine picks from, so this list is where the sRGB one has to
    /// be. `crates/crcbl/tests/hal_seam_e2e.rs`'s
    /// `a_surface_offers_an_srgb_format_and_preferred_format_picks_it` holds
    /// every backend to it.
    pub formats: Vec<Format>,
    /// Present modes available. Always contains [`PresentMode::Fifo`].
    pub present_modes: Vec<PresentMode>,
    /// Composite-alpha modes available.
    pub composite_alpha: Vec<CompositeAlpha>,
    /// Fewest images the surface will accept.
    pub min_image_count: u32,
    /// Most images the surface will accept.
    pub max_image_count: u32,
    /// Current size in pixels, if the window system reports one.
    ///
    /// **A cross-check, never the source of truth** — see the [module
    /// docs](self#the-extent-one-request-one-answer--implementation-obligations).
    /// The shell's `WindowState::size()` is what a swapchain is configured at;
    /// this is what the *surface* believes, which on Wayland is nothing at all
    /// (`None`, never the `0xFFFFFFFF` sentinel) and on X11 can be a frame
    /// behind a resize.
    pub current_extent: Option<(u32, u32)>,
}

/// Configuration for a swapchain.
///
/// Passed to both [`Device::create_swapchain`](crate::Device::create_swapchain)
/// and [`Device::reconfigure_swapchain`](crate::Device::reconfigure_swapchain) —
/// one struct, so a resize cannot accidentally change something it did not mean
/// to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SwapchainDesc<'a> {
    /// Debug name; see [`BufferDesc::label`](crate::BufferDesc::label).
    pub label: Option<&'a str>,
    /// Surface to present to.
    pub surface: SurfaceHandle,
    /// Image format. Must be one of [`SurfaceCaps::formats`].
    ///
    /// The engine presents an **sRGB** swapchain and renders to an
    /// [`Rgba16Float`](Format::Rgba16Float) offscreen target that a tonemap pass
    /// resolves into it — HDR from P1, per `docs/plan/ROADMAP.md`. The swapchain
    /// format is therefore a display format, never a shading one.
    pub format: Format,
    /// Size in pixels, **from the shell** — the *request*.
    ///
    /// A backend starts here and never substitutes
    /// [`SurfaceCaps::current_extent`] for it (obligation 1), but it may have
    /// to clamp into a range the window system pins, in which case the size it
    /// actually configured comes back on [`AcquiredFrame::extent`] (obligations
    /// 2 and 3). **Render at that, not at this.** See the [module
    /// docs](self#the-extent-one-request-one-answer--implementation-obligations)
    /// for why the rule is stated rather than left to each backend, and note
    /// that a zero extent is a caller bug — an unconfigured or minimized window
    /// means "do not create a swapchain yet", not "pick something".
    ///
    /// In borderless mode this is the *native* surface size; render scale is a
    /// renderer feature applied to an offscreen target (topic 15), not a
    /// smaller swapchain.
    pub extent: (u32, u32),
    /// Requested image count. The backend clamps to
    /// [`SurfaceCaps::min_image_count`]/[`max`](SurfaceCaps::max_image_count).
    pub image_count: u32,
    /// Requested pacing. The backend falls back to [`PresentMode::Fifo`] if
    /// unavailable, which is always supported.
    pub present_mode: PresentMode,
    /// Desktop compositing mode.
    pub composite_alpha: CompositeAlpha,
}

/// A swapchain image ready to be rendered into.
///
/// See the module docs for why the semaphores are optional and owned by the
/// swapchain rather than supplied by the caller.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AcquiredFrame {
    /// Image to render into. Valid until the matching
    /// [`present`](crate::Device::present).
    ///
    /// Its state on acquire is *undefined*: the first barrier touching it must
    /// use [`ResourceState::Undefined`](crate::ResourceState::Undefined) as the
    /// source, which discards any previous contents. Loading a swapchain image
    /// is never correct.
    pub image: ImageHandle,
    /// A whole-image view of [`image`](Self::image), in the swapchain's format
    /// — what a [`ColorAttachment`](crate::ColorAttachment) needs.
    ///
    /// **Owned by the swapchain**, like the semaphores: do not destroy it, and
    /// do not hold it across a
    /// [`reconfigure`](crate::Device::reconfigure_swapchain), which reissues
    /// every one. See the [module docs](self#the-swapchain-owns-the-views-too)
    /// for why this is here rather than left to each caller.
    pub view: ImageViewHandle,
    /// The size this swapchain was actually configured at, in pixels.
    ///
    /// **Obligation 3**: this is the render area, the viewport and the scissor
    /// — not [`SwapchainDesc::extent`], which is only what was *asked for*.
    /// The two differ exactly when the window system pinned a range the
    /// request fell outside of, which on X11 is any frame where a resize event
    /// has not caught up yet. See the [module
    /// docs](self#the-extent-one-request-one-answer--implementation-obligations).
    pub extent: (u32, u32),
    /// Index within the swapchain's image ring. For debug output and for
    /// indexing per-image caches; do not use it to guess how many images exist.
    pub index: u32,
    /// Wait on this before the first submission that writes the image, if
    /// present. `None` on backends with an implicit acquire.
    pub acquire_semaphore: Option<SemaphoreHandle>,
    /// Signal this from the last submission that writes the image, and pass it
    /// to [`present`](crate::Device::present), if present. `None` on backends
    /// with an implicit present.
    pub present_semaphore: Option<SemaphoreHandle>,
    /// The swapchain still works but no longer matches the surface exactly —
    /// usually a resize that arrived mid-frame. Render this frame, then
    /// reconfigure. Ignoring it is legal and merely looks slightly wrong for one
    /// frame; treating it as fatal is a bug.
    ///
    /// **This is the only place the seam carries "suboptimal".** A present can
    /// discover it too — `vkQueuePresentKHR` returns `VK_SUBOPTIMAL_KHR` — and
    /// [`Device::present`](crate::Device::present) has nowhere to put it, since
    /// it is not an error. That is deliberate rather than an oversight: a
    /// backend remembers it and folds it into the *next* acquire, which is
    /// where the caller already handles it, and which costs one `bool` instead
    /// of a second reporting channel every consumer would have to branch on.
    pub suboptimal: bool,
}

/// Parameters for a present.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PresentInfo<'a> {
    /// Swapchain to present.
    pub swapchain: SwapchainHandle,
    /// Waited on before the image is handed to the compositor. Normally exactly
    /// the [`AcquiredFrame::present_semaphore`], or empty when that was `None`.
    pub waits: &'a [SemaphoreHandle],
    /// A number for this present, so it can be waited for afterwards with
    /// [`Device::wait_until_presented`](crate::Device::wait_until_presented).
    ///
    /// **Must strictly increase** across the presents of one swapchain, and
    /// starts over when the swapchain is
    /// [reconfigured](crate::Device::reconfigure_swapchain) — a backend is
    /// free to key state off the number, so a repeated or a going-backwards
    /// one is a caller bug. The engine uses its submission counter, which is
    /// monotonic already.
    ///
    /// `None` numbers nothing and is always legal: a caller that will never
    /// wait pays nothing for the seam existing, and a backend with no way to
    /// number a present ignores this field. It is an `Option` rather than a
    /// reserved `0` because a sentinel is a value someone eventually passes by
    /// accident.
    pub present_id: Option<u64>,
}

impl SurfaceCaps {
    /// Picks a swapchain format: the first sRGB format the surface offers, or
    /// the first format at all.
    ///
    /// sRGB by preference because the tonemap pass writes display-referred
    /// values and hardware sRGB encode is free. Returns `None` only if the
    /// surface offers nothing, which means the backend should have failed
    /// earlier.
    #[must_use]
    pub fn preferred_format(&self) -> Option<Format> {
        self.formats
            .iter()
            .copied()
            .find(|format| format.is_srgb())
            .or_else(|| self.formats.first().copied())
    }

    /// Whether `mode` is available.
    #[must_use]
    pub fn supports_present_mode(&self, mode: PresentMode) -> bool {
        self.present_modes.contains(&mode)
    }

    /// Picks the first available mode from `preferences`, falling back to
    /// [`PresentMode::Fifo`].
    ///
    /// The `[Mailbox, Fifo]` preference from
    /// stage 2 §2.2, expressed once here instead of
    /// re-derived in every backend.
    #[must_use]
    pub fn choose_present_mode(&self, preferences: &[PresentMode]) -> PresentMode {
        preferences
            .iter()
            .copied()
            .find(|mode| self.supports_present_mode(*mode))
            .unwrap_or(PresentMode::Fifo)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn caps() -> SurfaceCaps {
        SurfaceCaps {
            formats: vec![Format::Bgra8Unorm, Format::Bgra8UnormSrgb],
            present_modes: vec![PresentMode::Fifo, PresentMode::Mailbox],
            composite_alpha: vec![CompositeAlpha::Opaque],
            min_image_count: 2,
            max_image_count: 4,
            current_extent: Some((1920, 1080)),
        }
    }

    #[test]
    fn preferred_format_prefers_srgb_even_when_listed_second() {
        assert_eq!(caps().preferred_format(), Some(Format::Bgra8UnormSrgb));
    }

    #[test]
    fn preferred_format_falls_back_to_the_first_listed() {
        let linear_only = SurfaceCaps {
            formats: vec![Format::Rgba16Float, Format::Bgra8Unorm],
            ..caps()
        };
        assert_eq!(linear_only.preferred_format(), Some(Format::Rgba16Float));

        let empty = SurfaceCaps {
            formats: vec![],
            ..caps()
        };
        assert_eq!(empty.preferred_format(), None);
    }

    #[test]
    fn present_mode_choice_follows_the_plans_preference_order() {
        let caps = caps();
        assert_eq!(
            caps.choose_present_mode(&[PresentMode::Mailbox, PresentMode::Fifo]),
            PresentMode::Mailbox
        );
        // Immediate is absent here, so the next preference wins.
        assert_eq!(
            caps.choose_present_mode(&[PresentMode::Immediate, PresentMode::Fifo]),
            PresentMode::Fifo
        );
        // Nothing available at all still yields Fifo, which every surface has.
        assert_eq!(
            caps.choose_present_mode(&[PresentMode::Immediate]),
            PresentMode::Fifo
        );
    }

    /// The portable shape from the module docs, asserted against the backend that
    /// models it rather than against a hand-built literal: an implicit acquire
    /// returns `None` for both semaphores, so the renderer's splice becomes an
    /// empty slice rather than a branch. The image, the view and the extent are
    /// **not** optional — every backend has all three, which is the whole
    /// reason they sit beside the semaphores rather than being left to the
    /// caller — and here they are checked by *using* them.
    ///
    /// The timeline-semaphore half of the same contract, and the ring's rotation and
    /// reconfigure behaviour, are the null backend's own
    /// `swapchain_acquire_matches_each_presets_sync_model`.
    #[test]
    fn an_implicit_acquire_frame_carries_no_semaphores() {
        use crate::null::NullInstance;
        use crate::{
            AdapterId, ClearValue, ColorAttachment, CommandEncoderDesc, DeviceDesc, Features,
            Instance, LoadOp, QueueKind, Rect2d, RenderPassDesc, StoreOp, SubmitInfo,
            SurfaceTarget,
        };

        const EXTENT: (u32, u32) = (1280, 720);

        let instance = NullInstance::portable();
        // SAFETY: `Offscreen` names no platform object at all, so there is
        // nothing that has to outlive the surface.
        let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }
            .expect("an offscreen surface always works");
        let device = instance
            .create_device(&DeviceDesc {
                required_features: Features::COMPUTE,
                ..DeviceDesc::for_adapter(AdapterId(0))
            })
            .expect("the portable preset has compute");
        let surface_caps = instance
            .surface_caps(surface, AdapterId(0))
            .expect("surface caps");
        let format = surface_caps
            .preferred_format()
            .expect("a format is offered");
        let swapchain = device
            .create_swapchain(&SwapchainDesc {
                label: Some("implicit acquire"),
                surface,
                format,
                extent: EXTENT,
                image_count: surface_caps.min_image_count,
                present_mode: surface_caps.choose_present_mode(&[PresentMode::Fifo]),
                composite_alpha: CompositeAlpha::Opaque,
            })
            .expect("a swapchain");

        let frame = device.acquire_next_frame(swapchain).expect("acquire");
        assert!(
            frame.acquire_semaphore.is_none(),
            "a backend with an implicit acquire has nothing to wait on"
        );
        assert!(
            frame.present_semaphore.is_none(),
            "and nothing to signal into the present"
        );
        // Obligation 3: this is the number a caller renders at.
        assert_eq!(frame.extent, EXTENT);

        // The view is a live object beside the optional semaphores, not a
        // placeholder — so hand it to the thing it exists for. The null backend
        // records a validation error for a dead attachment view rather than
        // failing the call, which is what `assert_valid` below reads.
        let queue = device.queue(QueueKind::Graphics).expect("a graphics queue");
        let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
            label: Some("implicit acquire"),
            queue,
        });
        encoder.begin_render_pass(&RenderPassDesc {
            label: Some("clear"),
            color_attachments: &[ColorAttachment {
                view: frame.view,
                resolve: None,
                load: LoadOp::Clear,
                store: StoreOp::Store,
                clear: ClearValue::default(),
            }],
            depth_stencil_attachment: None,
            render_area: Rect2d::from_size(frame.extent.0, frame.extent.1),
            timestamp_writes: None,
        });
        encoder.end_render_pass();
        let commands = encoder.finish().expect("recording succeeded");
        instance.recorder().assert_valid();
        device
            .submit(queue, &SubmitInfo::new(&[commands]))
            .expect("submit");

        // The renderer's splice: `None` collects to an empty slice, so the
        // present is the same code as a semaphore-carrying device's with nothing in
        // it.
        let waits: Vec<SemaphoreHandle> = frame.present_semaphore.into_iter().collect();
        assert!(waits.is_empty(), "the splice is an empty slice");
        device
            .present(
                queue,
                &PresentInfo {
                    swapchain,
                    waits: &waits,
                    present_id: None,
                },
            )
            .expect("presenting with no waits is the implicit-acquire path, not an error");

        device.destroy_command_buffer(commands);
        device.destroy_swapchain(swapchain);
        instance.destroy_surface(surface);
    }

    #[test]
    fn default_present_mode_is_the_universally_supported_one() {
        assert_eq!(PresentMode::default(), PresentMode::Fifo);
        assert!(caps().supports_present_mode(PresentMode::Fifo));
        assert_eq!(CompositeAlpha::default(), CompositeAlpha::Opaque);
    }

    /// 60 Hz, to the nanosecond a presentation engine would actually report.
    const CYCLE_60HZ_NS: u64 = 16_666_667;
    /// 120 Hz — half of [`CYCLE_60HZ_NS`] rounded the way a driver would, so
    /// the two do *not* divide evenly. Used for the contradictory-input case.
    const CYCLE_120HZ_NS: u64 = 8_333_333;

    /// A device that says nothing says [`DisplayTiming::Unknown`], and so does
    /// the seam's own default — the arm every backend without the capability
    /// answers with.
    #[test]
    fn nothing_reported_is_unknown() {
        assert_eq!(DisplayTiming::default(), DisplayTiming::Unknown);
        assert_eq!(
            display_timing_from_refresh_nanos(0, 0),
            DisplayTiming::Unknown
        );
    }

    /// A live interval with no duration behind it: the dynamics are known and
    /// the cycle is not, which is not enough for any arm that carries a
    /// `Duration`. Every interval encoding must land on `Unknown`, including
    /// the VRR sentinel — `Variable { shortest: 0 }` would be a false claim,
    /// not a weak one.
    #[test]
    fn a_zero_duration_is_unknown_whatever_the_interval_says() {
        for interval in [1, CYCLE_60HZ_NS, u64::MAX] {
            assert_eq!(
                display_timing_from_refresh_nanos(0, interval),
                DisplayTiming::Unknown,
                "interval {interval}"
            );
        }
    }

    /// The case the doc comment calls out: the duration was known, the
    /// dynamics were not, and the duration is **discarded** rather than
    /// promoted to `Fixed`.
    #[test]
    fn a_known_duration_with_unknown_dynamics_discards_the_duration() {
        assert_eq!(
            display_timing_from_refresh_nanos(CYCLE_60HZ_NS, 0),
            DisplayTiming::Unknown
        );
    }

    /// `UINT64_MAX` is the proposal's spelling of "VRR", and the duration
    /// beside it is the *minimum* cycle.
    #[test]
    fn the_max_interval_sentinel_is_free_running_adaptive_sync() {
        assert_eq!(
            display_timing_from_refresh_nanos(CYCLE_120HZ_NS, u64::MAX),
            DisplayTiming::Variable {
                shortest: Duration::from_nanos(CYCLE_120HZ_NS)
            }
        );
    }

    /// Two ways to read `duration == interval == u64::MAX`, and the sentinel
    /// wins: it is an explicit statement, where the equality is an inference.
    #[test]
    fn the_sentinel_outranks_the_equality_when_both_match() {
        assert_eq!(
            display_timing_from_refresh_nanos(u64::MAX, u64::MAX),
            DisplayTiming::Variable {
                shortest: Duration::from_nanos(u64::MAX)
            }
        );
    }

    /// Equal figures are fixed refresh — the only arm a frame loop may pace a
    /// fixed interval against.
    #[test]
    fn equal_figures_are_fixed_refresh() {
        assert_eq!(
            display_timing_from_refresh_nanos(CYCLE_60HZ_NS, CYCLE_60HZ_NS),
            DisplayTiming::Fixed {
                cycle: Duration::from_nanos(CYCLE_60HZ_NS)
            }
        );
        // Nanosecond counts far larger than any real panel still map, and map
        // to the same arm: `Duration::from_nanos` takes the whole `u64` range,
        // so there is no overflow to guard and no clamp to get wrong.
        let huge = u64::MAX - 1;
        assert_eq!(
            display_timing_from_refresh_nanos(huge, huge),
            DisplayTiming::Fixed {
                cycle: Duration::from_nanos(huge)
            }
        );
    }

    /// A genuine multiple: the cycle is 40 Hz right now and moves in 120 Hz
    /// quanta. Adaptive, so not `Fixed`; bounded, so not `Variable`.
    #[test]
    fn a_multiple_of_the_interval_is_a_stepped_cycle() {
        let step = 8_333_333;
        let cycle = step * 3;
        assert_eq!(
            display_timing_from_refresh_nanos(cycle, step),
            DisplayTiming::Stepped {
                cycle: Duration::from_nanos(cycle),
                step: Duration::from_nanos(step),
            }
        );
        // The smallest multiple that is not the equal case, so the boundary
        // between `Fixed` and `Stepped` is pinned rather than assumed.
        assert_eq!(
            display_timing_from_refresh_nanos(2, 1),
            DisplayTiming::Stepped {
                cycle: Duration::from_nanos(2),
                step: Duration::from_nanos(1),
            }
        );
    }

    /// A driver contradicting the proposal — an interval that does not divide
    /// the duration — is not believed. `Unknown` is the conservative arm: it is
    /// the only one that promises nothing, and in particular it is not `Fixed`,
    /// which is the answer this whole type exists to stop us guessing.
    #[test]
    fn an_interval_that_does_not_divide_the_duration_is_not_believed() {
        // 16_666_667 is not a multiple of 8_333_333 — one nanosecond out, which
        // is exactly the shape a rounding bug in a driver takes.
        assert_eq!(
            display_timing_from_refresh_nanos(CYCLE_60HZ_NS, CYCLE_120HZ_NS),
            DisplayTiming::Unknown
        );
        // An interval *longer* than the duration breaks the same rule.
        assert_eq!(
            display_timing_from_refresh_nanos(CYCLE_120HZ_NS, CYCLE_60HZ_NS),
            DisplayTiming::Unknown
        );
    }

    /// Every arm is reachable, and no two inputs above collide onto one. Driven
    /// as a table so a fifth arm added without a mapping shows up as a hole
    /// here rather than as a silent `Unknown` in the field.
    #[test]
    fn every_arm_is_reachable_from_some_input() {
        let step = 8_333_333;
        let observed = [
            display_timing_from_refresh_nanos(0, 0),
            display_timing_from_refresh_nanos(CYCLE_60HZ_NS, CYCLE_60HZ_NS),
            display_timing_from_refresh_nanos(CYCLE_120HZ_NS, u64::MAX),
            display_timing_from_refresh_nanos(step * 3, step),
        ];
        assert!(matches!(observed[0], DisplayTiming::Unknown));
        assert!(matches!(observed[1], DisplayTiming::Fixed { .. }));
        assert!(matches!(observed[2], DisplayTiming::Variable { .. }));
        assert!(matches!(observed[3], DisplayTiming::Stepped { .. }));
    }
}