wgpu_types/surface.rs
1//! Surface presentation configuration: present modes, alpha compositing, and
2//! color-space types (HDR and wide-gamut output).
3//!
4//! This module is re-exported flatly from `wgpu-types`; the user-facing color
5//! space and HDR primer lives in the `wgpu` crate's top-level docs.
6
7use alloc::{vec, vec::Vec};
8
9use macro_rules_attribute::derive;
10
11use crate::{link_to_wgpu_docs, link_to_wgpu_item, ConstDefault, TextureFormat, TextureUsages};
12
13#[cfg(any(feature = "serde", test))]
14use serde::{Deserialize, Serialize};
15
16/// Timing and queueing with which frames are actually displayed to the user.
17///
18/// Use this as part of a [`SurfaceConfiguration`] to control the behavior of
19/// [`SurfaceTexture::present()`].
20///
21/// Some modes are only supported by some backends.
22/// You can use one of the `Auto*` modes, [`Fifo`](Self::Fifo),
23/// or choose one of the supported modes from [`SurfaceCapabilities::present_modes`].
24///
25#[doc = link_to_wgpu_docs!(["presented"]: "struct.SurfaceTexture.html#method.present")]
26#[doc = link_to_wgpu_docs!(["`SurfaceTexture::present()`"]: "struct.SurfaceTexture.html#method.present")]
27#[repr(C)]
28#[derive(Copy, Clone, Debug, ConstDefault!, PartialEq, Eq, Hash)]
29#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
30pub enum PresentMode {
31 /// Chooses the first supported mode out of:
32 ///
33 /// 1. [`FifoRelaxed`](Self::FifoRelaxed)
34 /// 2. [`Fifo`](Self::Fifo)
35 ///
36 /// Because of the fallback behavior, this is supported everywhere.
37 AutoVsync = 0,
38
39 /// Chooses the first supported mode out of:
40 ///
41 /// 1. [`Immediate`](Self::Immediate)
42 /// 2. [`Mailbox`](Self::Mailbox)
43 /// 3. [`Fifo`](Self::Fifo)
44 ///
45 /// Because of the fallback behavior, this is supported everywhere.
46 AutoNoVsync = 1,
47
48 /// Presentation frames are kept in a First-In-First-Out queue approximately 3 frames
49 /// long. Every vertical blanking period, the presentation engine will pop a frame
50 /// off the queue to display. If there is no frame to display, it will present the same
51 /// frame again until the next vblank.
52 ///
53 /// When a present command is executed on the GPU, the presented image is added on the queue.
54 ///
55 /// Calls to [`Surface::get_current_texture()`] will block until there is a spot in the queue.
56 ///
57 /// * **Tearing:** No tearing will be observed.
58 /// * **Supported on**: All platforms.
59 /// * **Also known as**: "Vsync On"
60 ///
61 /// This is the [default](Self::default) value for `PresentMode`.
62 /// If you don't know what mode to choose, choose this mode.
63 ///
64 #[doc = link_to_wgpu_docs!(["`Surface::get_current_texture()`"]: "struct.Surface.html#method.get_current_texture")]
65 #[custom(default)]
66 Fifo = 2,
67
68 /// Presentation frames are kept in a First-In-First-Out queue approximately 3 frames
69 /// long. Every vertical blanking period, the presentation engine will pop a frame
70 /// off the queue to display. If there is no frame to display, it will present the
71 /// same frame until there is a frame in the queue. The moment there is a frame in the
72 /// queue, it will immediately pop the frame off the queue.
73 ///
74 /// When a present command is executed on the GPU, the presented image is added on the queue.
75 ///
76 /// Calls to [`Surface::get_current_texture()`] will block until there is a spot in the queue.
77 ///
78 /// * **Tearing**:
79 /// Tearing will be observed if frames last more than one vblank as the front buffer.
80 /// * **Supported on**: AMD on Vulkan.
81 /// * **Also known as**: "Adaptive Vsync"
82 ///
83 #[doc = link_to_wgpu_docs!(["`Surface::get_current_texture()`"]: "struct.Surface.html#method.get_current_texture")]
84 FifoRelaxed = 3,
85
86 /// Presentation frames are not queued at all. The moment a present command
87 /// is executed on the GPU, the presented image is swapped onto the front buffer
88 /// immediately.
89 ///
90 /// * **Tearing**: Tearing can be observed.
91 /// * **Supported on**: Most platforms except older DX12 and Wayland.
92 /// * **Also known as**: "Vsync Off"
93 Immediate = 4,
94
95 /// Presentation frames are kept in a single-frame queue. Every vertical blanking period,
96 /// the presentation engine will pop a frame from the queue. If there is no frame to display,
97 /// it will present the same frame again until the next vblank.
98 ///
99 /// When a present command is executed on the GPU, the frame will be put into the queue.
100 /// If there was already a frame in the queue, the new frame will _replace_ the old frame
101 /// on the queue.
102 ///
103 /// * **Tearing**: No tearing will be observed.
104 /// * **Supported on**: DX12 on Windows 10, NVidia on Vulkan and Wayland on Vulkan.
105 /// * **Also known as**: "Fast Vsync"
106 Mailbox = 5,
107}
108
109/// Specifies how the alpha channel of the textures should be handled during
110/// compositing.
111#[repr(C)]
112#[derive(Debug, ConstDefault!, Clone, Copy, PartialEq, Eq, Hash)]
113#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
114#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
115pub enum CompositeAlphaMode {
116 /// Chooses either `Opaque` or `Inherit` automatically, depending on the
117 /// `alpha_mode` that the current surface can support.
118 #[custom(default)]
119 Auto = 0,
120 /// The alpha channel, if it exists, of the textures is ignored in the
121 /// compositing process. Instead, the textures is treated as if it has a
122 /// constant alpha of 1.0.
123 Opaque = 1,
124 /// The alpha channel, if it exists, of the textures is respected in the
125 /// compositing process. The non-alpha channels of the textures are
126 /// expected to already be multiplied by the alpha channel by the
127 /// application.
128 PreMultiplied = 2,
129 /// The alpha channel, if it exists, of the textures is respected in the
130 /// compositing process. The non-alpha channels of the textures are not
131 /// expected to already be multiplied by the alpha channel by the
132 /// application; instead, the compositor will multiply the non-alpha
133 /// channels of the texture by the alpha channel during compositing.
134 PostMultiplied = 3,
135 /// The alpha channel, if it exists, of the textures is unknown for processing
136 /// during compositing. Instead, the application is responsible for setting
137 /// the composite alpha blending mode using native WSI command. If not set,
138 /// then a platform-specific default will be used.
139 Inherit = 4,
140}
141
142/// The color space in which the presentation engine interprets the values
143/// written to a surface texture.
144///
145/// A color space defines the *primaries*, *white point*, and *transfer
146/// function* of the output signal (see the Terminology section below),
147/// following the same convention as [CSS predefined color spaces] and
148/// [`VkColorSpaceKHR`].
149/// It does **not** change the texel format of the surface; it changes how the
150/// compositor / display pipeline interprets those texels.
151///
152/// Support is queried via [`SurfaceCapabilities`], which reports a set of
153/// [`SurfaceColorSpaces`] for every supported texture format. Selecting a
154/// color space other than [`Srgb`](Self::Srgb) is how an application opts a
155/// surface into high-dynamic-range (HDR) or wide-color-gamut output on
156/// platforms that support it.
157///
158/// New to HDR? The `wgpu` crate's top-level docs include a [color space and HDR
159/// primer] covering the concepts and the steps to get HDR output on screen.
160///
161/// # Terminology
162///
163/// The named color spaces are described by four properties. For
164/// [`PassThrough`](Self::PassThrough), the application determines these properties.
165///
166/// * **Primaries** (the *gamut*): the chromaticities of the red, green, and
167/// blue that color values address, and so the range of colors that can be
168/// expressed. [BT.709] (the sRGB / HDTV primaries) is the standard-gamut set;
169/// [Display P3] and [BT.2020] are progressively wider.
170/// * **White point**: the chromaticity produced by equal red, green, and blue.
171/// The named color spaces here use [D65], the standard daylight white.
172/// * **Transfer function** (the *OETF*): how stored values map to light, such
173/// as the [sRGB] transfer function, a linear transfer, or an HDR transfer
174/// function like [PQ] or [HLG]. Your shader applies this encoding transfer
175/// function; the display applies the inverse (the *EOTF*). Except for writes
176/// to an `*Srgb` texture format (where the hardware applies the sRGB encoding
177/// for you), wgpu does **not** encode for you: the values your shader writes
178/// to the surface texture must already be in whatever encoding the chosen
179/// color space expects (linear for a linear transfer). The [HDR surface
180/// example] shows encoders for the named color spaces.
181/// * **Dynamic range**: standard dynamic range (SDR), where `1.0` is reference
182/// (SDR) white and values outside 0.0..=1.0 are clamped, or high dynamic
183/// range (HDR), where `(1.0, 1.0, 1.0)` is SDR reference white and values
184/// above `1.0` drive brighter-than-SDR output on HDR displays.
185///
186#[doc = include_str!("color_gamuts.svg")]
187///
188/// *The primaries of each color space form a triangle on the CIE 1931
189/// chromaticity diagram; colors inside it are expressible, colors outside are
190/// not. [`Srgb`](Self::Srgb) uses the [BT.709] gamut;
191/// [`DisplayP3`](Self::DisplayP3) and [`Bt2100Pq`](Self::Bt2100Pq)'s [BT.2020]
192/// are progressively wider. All share the [D65] white point.*
193///
194#[doc = include_str!("sdr_hdr_range.svg")]
195///
196/// *`0.0` is black and `1.0` is SDR reference white. [`Srgb`](Self::Srgb) and
197/// [`DisplayP3`](Self::DisplayP3) clamp above `1.0`; the extended-range and HDR
198/// color spaces drive values above `1.0` as brighter-than-SDR output, up to the
199/// display's headroom (query it via [`DisplayHdrInfo::tone_map_headroom`]).*
200///
201/// # Extended-range variants: linear vs encoded
202///
203/// The extended-range color spaces come in two forms that share a range but
204/// differ in transfer: [`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear) carries
205/// a **linear** signal, while [`ExtendedSrgb`](Self::ExtendedSrgb) and
206/// [`ExtendedDisplayP3`](Self::ExtendedDisplayP3) carry the **sRGB-encoded**
207/// (gamma) signal: the sRGB transfer function is applied as usual and then
208/// continued to values above `1.0` (brighter than SDR white) and below `0.0`
209/// (colors outside the base gamut). Pick by whether the values your shader
210/// writes to the surface texture are linear or encoded; confusing the two is the
211/// most common HDR setup mistake.
212///
213/// # Web (WebGPU) backend
214///
215/// Browsers do not expose these named color spaces directly. A WebGPU canvas is
216/// configured with a [`colorSpace`] (only `"srgb"` or `"display-p3"`) plus a
217/// separate [`toneMapping`] mode (`"standard"` or `"extended"`), so on the web
218/// wgpu offers only the combinations that pair can produce: [`Srgb`](Self::Srgb)
219/// and [`DisplayP3`](Self::DisplayP3) with standard tone mapping, plus their
220/// extended-range HDR forms [`ExtendedSrgb`](Self::ExtendedSrgb) and
221/// [`ExtendedDisplayP3`](Self::ExtendedDisplayP3) with extended tone mapping.
222/// There is no linear-transfer canvas color space, so
223/// [`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear) (scRGB) is native-only, and
224/// [`Bt2100Pq`](Self::Bt2100Pq) and [`Bt2100Hlg`](Self::Bt2100Hlg) are
225/// unavailable (browsers expose no PQ or HLG canvas signaling).
226///
227/// [CSS predefined color spaces]: https://www.w3.org/TR/css-color-4/#predefined
228/// [`VkColorSpaceKHR`]: https://registry.khronos.org/vulkan/specs/latest/man/html/VkColorSpaceKHR.html
229///
230/// [BT.709]: https://www.itu.int/rec/R-REC-BT.709
231/// [BT.2020]: https://www.itu.int/rec/R-REC-BT.2020
232/// [Display P3]: https://en.wikipedia.org/wiki/DCI-P3#Display_P3
233/// [D65]: https://en.wikipedia.org/wiki/Standard_illuminant#D65_values
234/// [sRGB]: https://registry.color.org/rgb-registry/srgb
235/// [PQ]: https://en.wikipedia.org/wiki/Perceptual_quantizer
236/// [HLG]: https://www.itu.int/rec/R-REC-BT.2100
237/// [HDR surface example]: https://github.com/gfx-rs/wgpu/tree/trunk/examples/standalone/03_hdr_surface
238///
239/// [`colorSpace`]: https://www.w3.org/TR/webgpu/#dom-gpucanvasconfiguration-colorspace
240/// [`toneMapping`]: https://www.w3.org/TR/webgpu/#gpucanvastonemappingmode
241#[doc = link_to_wgpu_docs!(["color space and HDR primer"]: "index.html#surface-color-spaces-and-hdr-output")]
242#[repr(C)]
243#[derive(Copy, Clone, Debug, ConstDefault!, PartialEq, Eq, Hash)]
244#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
245pub enum SurfaceColorSpace {
246 /// Let the backend choose a color space, reproducing wgpu's historical
247 /// behavior:
248 ///
249 /// * [`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear) if the format is
250 /// [`TextureFormat::Rgba16Float`] and the surface supports it for that
251 /// format,
252 /// * otherwise [`Srgb`](Self::Srgb), if the surface supports it for the
253 /// format.
254 ///
255 /// Apart from the linear [`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear)
256 /// above (which fp16 surfaces have historically used and which needs no
257 /// extra encoding), `Auto` never resolves to a wide-gamut or HDR color
258 /// space, since those would change how the application must encode its
259 /// output. If a format is only available in such color spaces (which some
260 /// drivers report when the OS is in HDR mode), configuring it with `Auto`
261 /// fails validation; such formats are listed in
262 /// [`SurfaceCapabilities::format_capabilities`] but excluded from
263 /// [`SurfaceCapabilities::formats`].
264 ///
265 /// On the browser WebGPU backend, `Auto` always keeps the canvas
266 /// defaults (sRGB with standard tone mapping), even for
267 /// [`TextureFormat::Rgba16Float`]; request
268 /// [`ExtendedSrgb`](Self::ExtendedSrgb) explicitly for HDR canvas output
269 /// ([`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear) is native-only).
270 #[custom(default)]
271 Auto = 0,
272
273 /// The sRGB color space: BT.709 primaries, D65 white point, sRGB transfer
274 /// function, standard dynamic range.
275 ///
276 /// Values outside of 0.0..=1.0 (after format encoding) are clamped by
277 /// the display pipeline.
278 ///
279 /// This is what every backend produces today for non-`Rgba16Float`
280 /// formats and is supported everywhere.
281 ///
282 /// Note that the transfer function is applied by the *format*, not this
283 /// color space choice: an `*Srgb` format applies sRGB encoding on write,
284 /// while writes to a non-`*Srgb` format are interpreted as already
285 /// sRGB-encoded.
286 Srgb = 1,
287
288 /// Extended linear sRGB, also known as [scRGB] (the **linear** encoding of
289 /// IEC 61966-2-2): BT.709 primaries, D65 white point, **linear** transfer
290 /// function, extended dynamic range. Typically used with
291 /// [`TextureFormat::Rgba16Float`].
292 ///
293 /// The linear counterpart to the sRGB-encoded
294 /// [`ExtendedSrgb`](Self::ExtendedSrgb) (IEC 61966-2-2 defines both); pick
295 /// this one if the values your shader writes to the surface texture are
296 /// **linear**.
297 ///
298 /// This corresponds to Vulkan's `VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT`,
299 /// Metal's extended dynamic range (EDR), and DXGI's
300 /// `DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709`.
301 ///
302 /// * **Supported on**: native only (Vulkan, Metal, DX12). Not available on
303 /// the browser WebGPU backend, which cannot express a linear-transfer
304 /// canvas color space; use [`ExtendedSrgb`](Self::ExtendedSrgb) for HDR
305 /// canvas output on the web.
306 /// * **Also known as**: scRGB.
307 ///
308 /// [scRGB]: https://en.wikipedia.org/wiki/ScRGB
309 ExtendedSrgbLinear = 2,
310
311 /// The [Display P3] color space: P3 primaries, D65 white point, sRGB
312 /// transfer function, standard dynamic range.
313 ///
314 /// A wide-gamut SDR color space covering roughly 25% more area than sRGB in
315 /// the CIE chromaticity diagram. It uses the wide P3 primaries of theatrical
316 /// DCI-P3, but with the D65 white point and the sRGB transfer function (not
317 /// DCI's white point and 2.6 gamma).
318 ///
319 /// Like [`Srgb`](Self::Srgb), this is standard dynamic range (values outside
320 /// 0.0..=1.0 are clamped). For wide-gamut HDR that keeps the P3 primaries
321 /// but extends the range, use [`ExtendedDisplayP3`](Self::ExtendedDisplayP3).
322 ///
323 /// * **Supported on**: Vulkan (where the driver exposes it), Metal, and the
324 /// browser WebGPU backend (canvas color space `"display-p3"`). Not
325 /// reported on DX12.
326 ///
327 /// [Display P3]: https://en.wikipedia.org/wiki/DCI-P3#Display_P3
328 DisplayP3 = 3,
329
330 /// BT.2100 perceptual quantization (HDR10): BT.2020/2100 primaries, D65 white
331 /// point, SMPTE ST 2084 perceptual quantizer ([PQ]) transfer function, high
332 /// dynamic range.
333 ///
334 /// Texel values are interpreted as a PQ-encoded signal whose encoded range,
335 /// `0.0..=1.0`, maps to absolute luminance from 0 to 10,000 nits. The values
336 /// your shader writes to the surface texture must already be in the BT.2020
337 /// gamut and PQ-encoded into that `0.0..=1.0` range; the [HDR surface example]
338 /// shows how. The format is non-sRGB, typically
339 /// [`TextureFormat::Rgb10a2Unorm`].
340 ///
341 /// Commonly known as **HDR10** — though that term additionally implies static
342 /// ST 2086 / MaxCLL mastering metadata, which wgpu does not set; this
343 /// configures only the PQ color space.
344 ///
345 /// * **Supported on**: Vulkan (where the driver exposes it), DX12 (on
346 /// `Rgb10a2Unorm`), and Metal. Unavailable on the browser WebGPU backend
347 /// (no PQ canvas signaling).
348 ///
349 /// [PQ]: https://en.wikipedia.org/wiki/Perceptual_quantizer
350 /// [HDR surface example]: https://github.com/gfx-rs/wgpu/tree/trunk/examples/standalone/03_hdr_surface
351 Bt2100Pq = 4,
352
353 /// BT.2100 hybrid log-gamma: BT.2020/2100 primaries, D65 white point, [HLG]
354 /// (ARIB STD-B67) transfer function, high dynamic range.
355 ///
356 /// A relative-luminance HDR signal, primarily used for broadcast content. The
357 /// values your shader writes to the surface texture must already be in the
358 /// BT.2020 gamut and HLG-encoded into `0.0..=1.0`; the [HDR surface example]
359 /// shows how. The format is non-sRGB, typically
360 /// [`TextureFormat::Rgb10a2Unorm`].
361 ///
362 /// Unlike [`Bt2100Pq`](Self::Bt2100Pq)'s PQ, the HLG signal is *relative*:
363 /// `1.0` maps to the display's nominal peak luminance rather than a fixed
364 /// absolute level. BT.2100 defines its reference OOTF at a nominal peak of
365 /// 1000 cd/m² (system gamma 1.2); the [HDR surface example] normalizes its
366 /// absolute-nit test pattern onto that 1000-nit nominal peak.
367 ///
368 /// * **Supported on**: Vulkan (where the driver exposes it) and Metal.
369 /// Unavailable on DX12 and the browser WebGPU backend (no HLG canvas
370 /// signaling).
371 ///
372 /// [HLG]: https://www.itu.int/rec/R-REC-BT.2100
373 /// [HDR surface example]: https://github.com/gfx-rs/wgpu/tree/trunk/examples/standalone/03_hdr_surface
374 Bt2100Hlg = 5,
375
376 /// Extended-range sRGB (encoded): BT.709 primaries, D65 white point, the
377 /// **nonlinear sRGB transfer function extended beyond 0.0..=1.0**,
378 /// extended dynamic range.
379 ///
380 /// The sRGB-encoded sibling of
381 /// [`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear): the signal is
382 /// sRGB-*encoded* (gamma), not linear. Typically used with
383 /// [`TextureFormat::Rgba16Float`].
384 ///
385 /// If the values your shader writes to the surface texture are **linear**,
386 /// you want [`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear) (scRGB) instead;
387 /// confusing the two is the most common HDR setup mistake. See the [HDR
388 /// surface example] for the encoder.
389 ///
390 /// This is the "encoded extended range" sRGB used by browser WebGPU (canvas
391 /// color space `"srgb"` with `"extended"` tone mapping). It corresponds to
392 /// Vulkan's `VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT` and Metal's
393 /// `kCGColorSpaceExtendedSRGB`.
394 ///
395 /// * **Supported on**: Vulkan (where the driver exposes it), Metal, and the
396 /// browser WebGPU backend. Not available on DX12, which has no
397 /// encoded-extended-sRGB swapchain color space.
398 ///
399 /// [HDR surface example]: https://github.com/gfx-rs/wgpu/tree/trunk/examples/standalone/03_hdr_surface
400 ExtendedSrgb = 6,
401
402 /// Extended-range Display-P3 (encoded): P3 primaries, D65 white point, the
403 /// **nonlinear sRGB transfer function extended beyond 0.0..=1.0**,
404 /// extended dynamic range.
405 ///
406 /// The wide-gamut (P3) analogue of [`ExtendedSrgb`](Self::ExtendedSrgb), and
407 /// the HDR counterpart to the SDR-only [`DisplayP3`](Self::DisplayP3): it
408 /// keeps the P3 primaries but extends the encoded range for HDR. Like
409 /// [`ExtendedSrgb`](Self::ExtendedSrgb) the signal is sRGB-*encoded* (gamma),
410 /// not linear. Typically used with [`TextureFormat::Rgba16Float`].
411 ///
412 /// * **Supported on**: Metal and the browser WebGPU backend (canvas color
413 /// space `"display-p3"` with `"extended"` tone mapping; Metal's
414 /// `kCGColorSpaceExtendedDisplayP3`). Not available on Vulkan or DX12,
415 /// neither of which has an encoded-extended-Display-P3 swapchain color
416 /// space.
417 ExtendedDisplayP3 = 7,
418
419 /// Presentation without a predefined color space.
420 ///
421 /// The application must ensure that the surface's stored color values match
422 /// the encoding and color space expected by the window system. Rendering to
423 /// an `*Srgb` texture view still applies hardware sRGB encoding.
424 /// [`Auto`](Self::Auto) never selects this color space.
425 ///
426 /// This maps to [`VK_COLOR_SPACE_PASS_THROUGH_EXT`] on Vulkan and a `nil`
427 /// [`CAMetalLayer.colorspace`] on Metal.
428 ///
429 /// On Metal, this disables color matching and extended dynamic range content.
430 ///
431 /// On Vulkan with Wayland, this lets the application manage surface color,
432 /// if supported by the compositor. Configure `PassThrough` before creating
433 /// an application-owned `wp_color_management_surface_v1`, and destroy that
434 /// object before configuring another color space. Otherwise, it can conflict
435 /// with Vulkan's own color-management object and cause a fatal
436 /// `surface_exists` protocol error.
437 ///
438 /// * **Supported on**: Vulkan (where the driver exposes it), Metal.
439 ///
440 /// [`VK_COLOR_SPACE_PASS_THROUGH_EXT`]: https://registry.khronos.org/vulkan/specs/latest/man/html/VkColorSpaceKHR.html
441 /// [`CAMetalLayer.colorspace`]: https://developer.apple.com/documentation/quartzcore/cametallayer/colorspace
442 PassThrough = 8,
443}
444
445impl SurfaceColorSpace {
446 /// Returns the [`SurfaceColorSpaces`] flag set holding just this color space,
447 /// or `None` for [`Auto`](Self::Auto) (which maps to no specific flag).
448 #[must_use]
449 pub const fn to_color_spaces(self) -> Option<SurfaceColorSpaces> {
450 match self {
451 Self::Auto => None,
452 Self::PassThrough => Some(SurfaceColorSpaces::PASS_THROUGH),
453 Self::Srgb => Some(SurfaceColorSpaces::SRGB),
454 Self::ExtendedSrgbLinear => Some(SurfaceColorSpaces::EXTENDED_SRGB_LINEAR),
455 Self::DisplayP3 => Some(SurfaceColorSpaces::DISPLAY_P3),
456 Self::Bt2100Pq => Some(SurfaceColorSpaces::BT2100_PQ),
457 Self::Bt2100Hlg => Some(SurfaceColorSpaces::BT2100_HLG),
458 Self::ExtendedSrgb => Some(SurfaceColorSpaces::EXTENDED_SRGB),
459 Self::ExtendedDisplayP3 => Some(SurfaceColorSpaces::EXTENDED_DISPLAY_P3),
460 }
461 }
462
463 /// Whether this is a high-dynamic-range color space: one that drives values
464 /// above SDR white (`1.0`) as brighter-than-white output.
465 ///
466 /// `true` for the extended-range and PQ/HLG spaces; `false` for the SDR ones
467 /// ([`Srgb`](Self::Srgb) and the wide-gamut-but-SDR
468 /// [`DisplayP3`](Self::DisplayP3)). [`Auto`](Self::Auto) is `false`: it defers
469 /// to the backend and is the SDR-safe default, so check the resolved color
470 /// space if you need certainty.
471 ///
472 /// [`PassThrough`](Self::PassThrough) returns `false` because its dynamic
473 /// range is defined by the application and unknown to wgpu.
474 ///
475 /// Use this to branch after picking a color space from
476 /// [`SurfaceCapabilities`]: an HDR result is the one whose highlights you
477 /// scale by [`DisplayHdrInfo::tone_map_headroom`].
478 #[must_use]
479 pub const fn is_hdr(self) -> bool {
480 match self {
481 Self::ExtendedSrgbLinear
482 | Self::ExtendedSrgb
483 | Self::ExtendedDisplayP3
484 | Self::Bt2100Pq
485 | Self::Bt2100Hlg => true,
486 Self::Auto | Self::Srgb | Self::DisplayP3 | Self::PassThrough => false,
487 }
488 }
489}
490
491bitflags::bitflags! {
492 /// A set of [`SurfaceColorSpace`]s supported by a surface for a particular
493 /// texture format.
494 ///
495 /// Reported per format in [`SurfaceCapabilities::formats`] via
496 /// [`SurfaceFormatCapabilities`].
497 #[repr(transparent)]
498 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
499 #[cfg_attr(feature = "serde", serde(transparent))]
500 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
501 pub struct SurfaceColorSpaces: u32 {
502 /// [`SurfaceColorSpace::Srgb`] is supported.
503 const SRGB = 1 << 0;
504 /// [`SurfaceColorSpace::ExtendedSrgbLinear`] is supported.
505 const EXTENDED_SRGB_LINEAR = 1 << 1;
506 /// [`SurfaceColorSpace::DisplayP3`] is supported.
507 const DISPLAY_P3 = 1 << 2;
508 /// [`SurfaceColorSpace::Bt2100Pq`] is supported.
509 const BT2100_PQ = 1 << 3;
510 /// [`SurfaceColorSpace::Bt2100Hlg`] is supported.
511 const BT2100_HLG = 1 << 4;
512 /// [`SurfaceColorSpace::ExtendedSrgb`] is supported.
513 const EXTENDED_SRGB = 1 << 5;
514 /// [`SurfaceColorSpace::ExtendedDisplayP3`] is supported.
515 const EXTENDED_DISPLAY_P3 = 1 << 6;
516 /// [`SurfaceColorSpace::PassThrough`] is supported.
517 const PASS_THROUGH = 1 << 7;
518 }
519}
520
521/// A texture format supported by a surface, together with the color spaces
522/// in which the surface can present it.
523#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
524#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
525pub struct SurfaceFormatCapabilities {
526 /// The texture format.
527 pub format: TextureFormat,
528 /// The set of color spaces the surface supports for this format.
529 ///
530 /// This reports which color spaces the surface can be *configured* with; it
531 /// does not reflect whether the display is currently in HDR mode. For the
532 /// display's live HDR state, see [`DisplayHdrInfo`].
533 ///
534 /// Guaranteed to be non-empty.
535 pub color_spaces: SurfaceColorSpaces,
536}
537
538/// Defines the capabilities of a given surface and adapter.
539#[derive(Debug)]
540pub struct SurfaceCapabilities {
541 /// List of supported formats to use with the given adapter. The first format in the vector is preferred.
542 ///
543 /// Only contains formats that can be configured with the default
544 /// [`SurfaceColorSpace::Auto`]; formats available exclusively in
545 /// explicit-opt-in (wide-gamut / HDR) color spaces appear only in
546 /// [`format_capabilities`](Self::format_capabilities).
547 ///
548 /// Returns an empty vector if the surface is incompatible with the adapter.
549 pub formats: Vec<TextureFormat>,
550 /// List of supported formats together with the color spaces supported for
551 /// each format, in the same preference order as
552 /// [`formats`](Self::formats), of which it is a superset.
553 ///
554 /// Returns an empty vector if the surface is incompatible with the adapter.
555 pub format_capabilities: Vec<SurfaceFormatCapabilities>,
556 /// List of supported presentation modes to use with the given adapter.
557 ///
558 /// Returns an empty vector if the surface is incompatible with the adapter.
559 pub present_modes: Vec<PresentMode>,
560 /// List of supported alpha modes to use with the given adapter.
561 ///
562 /// Will return at least one element, [`CompositeAlphaMode::Opaque`] or [`CompositeAlphaMode::Inherit`].
563 pub alpha_modes: Vec<CompositeAlphaMode>,
564 /// Bitflag of supported texture usages for the surface to use with the given adapter.
565 ///
566 /// The usage [`TextureUsages::RENDER_ATTACHMENT`] is guaranteed.
567 pub usages: TextureUsages,
568}
569
570impl SurfaceCapabilities {
571 /// Returns the set of color spaces supported for the given format, or an
572 /// empty set if the format is not supported.
573 ///
574 /// This is a convenience lookup over
575 /// [`format_capabilities`](Self::format_capabilities): an empty result
576 /// means `format` is absent from that list.
577 #[must_use]
578 pub fn color_spaces(&self, format: TextureFormat) -> SurfaceColorSpaces {
579 self.format_capabilities
580 .iter()
581 .filter(|fc| fc.format == format)
582 .fold(SurfaceColorSpaces::empty(), |acc, fc| acc | fc.color_spaces)
583 }
584}
585
586impl Default for SurfaceCapabilities {
587 fn default() -> Self {
588 Self {
589 formats: Vec::new(),
590 format_capabilities: Vec::new(),
591 present_modes: Vec::new(),
592 alpha_modes: vec![CompositeAlphaMode::Opaque],
593 usages: TextureUsages::RENDER_ATTACHMENT,
594 }
595 }
596}
597
598/// HDR and luminance characteristics of the display backing a [`Surface`], as
599/// reported by the platform at query time.
600///
601/// This describes the display; it does not configure it. Set the output color
602/// space through [`SurfaceConfiguration::color_space`]; wgpu does not write HDR
603/// metadata (`vkSetHdrMetadataEXT` / DXGI `SetHDRMetaData`).
604///
605/// Use it for tone mapping, not to decide whether to enable HDR - that is a
606/// capability question for [`SurfaceCapabilities`], and holds even when the panel
607/// has no headroom right now. The live highlight multiplier is
608/// [`tone_map_headroom`](Self::tone_map_headroom).
609///
610/// The values change as the display does, so re-query after the surface moves or
611/// resizes or the display configuration changes.
612///
613/// Every field is [`Option`] and no platform reports them all; `None` means
614/// unknown, never zero and never SDR (Windows reports nits, macOS only a headroom
615/// multiplier). The numbers are advisory hints, not contracts: OS/EDID figures run
616/// optimistic and report the panel's claim, not what survives the compositor.
617///
618#[doc = link_to_wgpu_item!(struct Surface)]
619#[derive(Clone, Debug, ConstDefault!, PartialEq)]
620#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
621pub struct DisplayHdrInfo {
622 /// Absolute-nit luminance levels. `Some` only on platforms that report
623 /// absolute nits (Windows, via DXGI). `None` on Apple EDR, the web, Vulkan
624 /// on non-Windows, and GLES.
625 pub luminance: Option<DisplayLuminance>,
626
627 /// Relative EDR-headroom multipliers. `Some` only on Apple. `None`
628 /// elsewhere.
629 pub headroom: Option<DisplayHeadroom>,
630
631 /// Chromaticity of the display's primaries and white point (CIE 1931 xy).
632 /// `Some` only on Windows (via DXGI). `None` on Apple (which exposes no
633 /// primaries), the web (boolean-only), Vulkan on non-Windows, and GLES.
634 /// Advisory (often EDID-sourced).
635 pub chromaticity: Option<DisplayChromaticity>,
636
637 /// Coarse, boolean dynamic-range + gamut bucket. The only luminance-adjacent
638 /// data the web exposes (CSS `dynamic-range` / `color-gamut`), and a useful
639 /// cross-check elsewhere. `None` only when nothing at all is known.
640 pub coarse: Option<DisplayCoarseRange>,
641
642 /// Output signal bit depth, e.g. `8` / `10` / `12` (DXGI `BitsPerColor`).
643 /// Advisory and often unreliable (may report `8` on a 10-bit panel). `None`
644 /// if unreported.
645 pub bits_per_color: Option<u8>,
646}
647
648/// Absolute luminance levels in nits (cd/m²). Populated only on Windows (via
649/// DXGI); `None` on every other platform.
650///
651/// Advisory: OS/EDID figures run optimistic. A `0.0` from the OS stays
652/// `Some(0.0)`; absence is `None`. These are achromatic (luminance = CIE Y), not a
653/// per-color ceiling: a display can't reach [`max_nits`](Self::max_nits) at a
654/// saturated chromaticity. Pair them with [`DisplayChromaticity`] for gamut mapping.
655#[derive(Clone, Copy, Debug, ConstDefault!, PartialEq)]
656#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
657pub struct DisplayLuminance {
658 /// Peak luminance of a small patch, nits. DXGI `MaxLuminance`.
659 pub max_nits: Option<f32>,
660 /// Sustained full-white-frame luminance, nits: the ceiling for a fully-lit
661 /// frame, which power/thermal limits can hold below the small-patch peak
662 /// [`max_nits`](Self::max_nits). May equal `max_nits` if the OS reports no
663 /// distinct limit. Prefer it over `max_nits` for large bright regions; don't
664 /// derive it from `max_nits`. DXGI `MaxFullFrameLuminance`.
665 pub max_full_frame_nits: Option<f32>,
666 /// Minimum (black) luminance, nits. DXGI `MinLuminance`.
667 pub min_nits: Option<f32>,
668 /// Luminance the OS maps SDR reference white to, nits; moves with the
669 /// brightness slider. Converts between absolute nits and relative EDR headroom
670 /// (`max_nits / sdr_white_nits`). Read via the `DISPLAYCONFIG_SDR_WHITE_LEVEL`
671 /// query, separate from the other nits, so `None` only if that query fails.
672 pub sdr_white_nits: Option<f32>,
673}
674
675/// Relative EDR headroom (Apple): unitless multipliers over current SDR white,
676/// where `1.0` means no headroom. Moves with brightness, ambient light, battery,
677/// and which display the window is on. Apple exposes no absolute-nit equivalent,
678/// so this is separate from [`DisplayLuminance`] and can't be converted to nits.
679///
680/// Populated only on macOS; `None` on iOS, tvOS, and visionOS.
681#[derive(Clone, Copy, Debug, ConstDefault!, PartialEq)]
682#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
683pub struct DisplayHeadroom {
684 /// Headroom available *right now* (`maximumExtendedDynamicRangeColorComponentValue`
685 /// / iOS `UIScreen.currentEDRHeadroom`). `1.0` means no headroom at this
686 /// instant, even on an HDR-capable panel.
687 pub current: Option<f32>,
688 /// Headroom the display could reach under ideal conditions
689 /// (`maximumPotentialExtendedDynamicRangeColorComponentValue` /
690 /// `UIScreen.potentialEDRHeadroom`).
691 pub potential: Option<f32>,
692 /// Headroom for reference-white content
693 /// (`maximumReferenceExtendedDynamicRangeColorComponentValue`). `None` if
694 /// unreported.
695 pub reference: Option<f32>,
696}
697
698/// CIE 1931 xy chromaticity of a display's primaries and white point. Each
699/// coordinate is `[x, y]`; a coordinate the platform omits is `None`.
700#[derive(Clone, Copy, Debug, ConstDefault!, PartialEq)]
701#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
702pub struct DisplayChromaticity {
703 /// xy of the red primary.
704 pub red: Option<[f32; 2]>,
705 /// xy of the green primary.
706 pub green: Option<[f32; 2]>,
707 /// xy of the blue primary.
708 pub blue: Option<[f32; 2]>,
709 /// xy of the white point.
710 pub white: Option<[f32; 2]>,
711}
712
713/// Coarse, boolean dynamic-range and gamut signal.
714///
715/// This is the only luminance-adjacent data the web exposes, and a useful
716/// cross-check on other platforms.
717#[derive(Clone, Copy, Debug, ConstDefault!, PartialEq, Eq)]
718#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
719pub struct DisplayCoarseRange {
720 /// CSS `@media (dynamic-range: high)`: the display *can* present HDR-range
721 /// content. Best-effort and platform-defined — "capable", not "an HDR mode is
722 /// active". It feeds [`tone_map_headroom`](DisplayHdrInfo::tone_map_headroom):
723 /// `Some(false)` marks a definitively-SDR display, collapsing the headroom to
724 /// `1.0`.
725 pub high_dynamic_range: Option<bool>,
726 /// Best gamut bucket the display covers (CSS `color-gamut`).
727 pub gamut: Option<DisplayGamut>,
728}
729
730/// Coarse gamut classification, mirroring CSS `color-gamut`.
731///
732/// These variants are **not** ordered by containment; do not rely on their
733/// declaration order to compare gamut sizes.
734#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
735#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
736#[non_exhaustive]
737pub enum DisplayGamut {
738 /// Approximately sRGB / Rec.709.
739 Srgb,
740 /// Approximately Display-P3.
741 DisplayP3,
742 /// Approximately Rec.2020.
743 Rec2020,
744}
745
746impl DisplayHdrInfo {
747 /// Best-effort tone-map headroom: the linear multiplier of SDR white the
748 /// display can drive before clipping. This is the single value most
749 /// tone-mappers want, with the subjective parts left to the application.
750 ///
751 /// Resolution order, first match wins:
752 /// 1. Apple EDR: [`DisplayHeadroom::current`] (already a multiplier).
753 /// 2. `Some(1.0)` when [`DisplayCoarseRange::high_dynamic_range`] is
754 /// `Some(false)` — a definitively-SDR display (Windows and the web both set
755 /// this flag for an SDR output). Its panel peak may sit above its SDR white,
756 /// but that ratio isn't headroom you can drive, so it isn't reported as
757 /// such.
758 /// 3. Absolute nits: `max_nits / sdr_white_nits`, when both are known and
759 /// `sdr_white_nits > 0.0`.
760 /// 4. Otherwise `None`: the available figures don't pin a multiplier (e.g.
761 /// `max_nits` known but `sdr_white_nits` unknown).
762 ///
763 /// Use `unwrap_or(1.0)` on the result for the SDR fallback. Never returns a
764 /// non-finite value.
765 #[must_use]
766 pub fn tone_map_headroom(&self) -> Option<f32> {
767 // Apple EDR reports a multiplier directly.
768 if let Some(h) = self
769 .headroom
770 .and_then(|h| h.current)
771 .filter(|h| h.is_finite())
772 {
773 return Some(h);
774 }
775 // A definitively-SDR display still reports a physical peak against a
776 // default SDR white; checked before the nit ratio so that unusable ratio
777 // can't surface as phantom headroom.
778 if self.coarse.and_then(|c| c.high_dynamic_range) == Some(false) {
779 return Some(1.0);
780 }
781 // Otherwise derive the multiplier from absolute nits, when both the peak
782 // and the SDR white level are known.
783 if let Some((max, sdr)) = self
784 .luminance
785 .and_then(|l| l.max_nits.zip(l.sdr_white_nits))
786 .filter(|&(max, sdr)| sdr > 0.0 && max.is_finite() && sdr.is_finite())
787 {
788 return Some(max / sdr);
789 }
790 None
791 }
792}
793
794/// Configures a [`Surface`] for presentation.
795///
796#[doc = link_to_wgpu_item!(struct Surface)]
797#[repr(C)]
798#[derive(Clone, Debug, PartialEq, Eq, Hash)]
799#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
800pub struct SurfaceConfiguration<V> {
801 /// The usage of the swap chain. The only usage guaranteed to be supported is [`TextureUsages::RENDER_ATTACHMENT`].
802 pub usage: TextureUsages,
803 /// The texture format of the swap chain. The only formats that are guaranteed are
804 /// [`TextureFormat::Bgra8Unorm`] and [`TextureFormat::Bgra8UnormSrgb`]. Unlike
805 /// WebGPU canvases, `wgpu` supports sRGB surface formats.
806 pub format: TextureFormat,
807 /// The color space in which the presentation engine interprets the values
808 /// written to the swap chain.
809 ///
810 /// The supported color spaces for each format are listed in
811 /// [`SurfaceCapabilities::format_capabilities`].
812 /// [`SurfaceColorSpace::Auto`] (the default) is supported for every
813 /// format in [`SurfaceCapabilities::formats`]; any other value must be
814 /// present in the format's
815 /// [`color_spaces`](SurfaceFormatCapabilities::color_spaces) set.
816 pub color_space: SurfaceColorSpace,
817 /// Width of the swap chain. Must be the same size as the surface, and nonzero.
818 ///
819 /// If this is not the same size as the underlying surface (e.g. if it is
820 /// set once, and the window is later resized), the behaviour is defined
821 /// but platform-specific, and may change in the future (currently macOS
822 /// scales the surface, other platforms may do something else).
823 pub width: u32,
824 /// Height of the swap chain. Must be the same size as the surface, and nonzero.
825 ///
826 /// If this is not the same size as the underlying surface (e.g. if it is
827 /// set once, and the window is later resized), the behaviour is defined
828 /// but platform-specific, and may change in the future (currently macOS
829 /// scales the surface, other platforms may do something else).
830 pub height: u32,
831 /// Presentation mode of the swap chain. Fifo is the only mode guaranteed to be supported.
832 /// `FifoRelaxed`, `Immediate`, and `Mailbox` will crash if unsupported, while `AutoVsync` and
833 /// `AutoNoVsync` will gracefully do a designed sets of fallbacks if their primary modes are
834 /// unsupported.
835 pub present_mode: PresentMode,
836 /// Desired maximum number of monitor refreshes between a [`Surface::get_current_texture`] call and the
837 /// texture being presented to the screen. This is sometimes called "Frames in Flight".
838 ///
839 /// Defaults to `2` when created via [`Surface::get_default_config`] as this is a reasonable default.
840 ///
841 /// This is ultimately a hint to the backend implementation and will always be clamped
842 /// to the supported range.
843 ///
844 /// Typical values are `1` to `3`, but higher values are valid, though likely to be clamped.
845 /// * Choose `1` to minimize latency above all else. This only gives a single monitor refresh for all of
846 /// the CPU and GPU work to complete. ⚠️ As a result of these short swapchains, the CPU and GPU
847 /// cannot run in parallel, prioritizing latency over throughput. For applications like GUIs doing
848 /// a small amount of GPU work each frame that need low latency, this is a reasonable choice.
849 /// * Choose `2` for a balance between latency and throughput. The CPU and GPU both can each use
850 /// a full monitor refresh to do their computations. This is a reasonable default for most applications.
851 /// * Choose `3` or higher to maximize throughput, sacrificing latency when the CPU and GPU
852 /// are using less than a full monitor refresh each. For applications that use CPU-side pipelining
853 /// of frames this may be a reasonable choice. ⚠️ On 60hz displays the latency can be very noticeable.
854 ///
855 /// This maps to the backend in the following ways:
856 /// - Vulkan: Number of frames in the swapchain is `desired_maximum_frame_latency + 1`,
857 /// clamped to the supported range.
858 /// - DX12: Calls [`IDXGISwapChain2::SetMaximumFrameLatency(desired_maximum_frame_latency)`][SMFL].
859 /// - Metal: Sets the `maximumDrawableCount` of the underlying `CAMetalLayer` to
860 /// `desired_maximum_frame_latency + 1`, clamped to the supported range.
861 /// - OpenGL: Ignored
862 ///
863 /// It also has various subtle interactions with various present modes and APIs.
864 /// - DX12 + Mailbox: Limits framerate to `desired_maximum_frame_latency * Monitor Hz` fps.
865 /// - Vulkan/Metal + Mailbox: If this is set to `2`, limits framerate to `2 * Monitor Hz` fps. `3` or higher is unlimited.
866 ///
867 #[doc = link_to_wgpu_docs!(["`Surface::get_current_texture`"]: "struct.Surface.html#method.get_current_texture")]
868 #[doc = link_to_wgpu_docs!(["`Surface::get_default_config`"]: "struct.Surface.html#method.get_default_config")]
869 /// [SMFL]: https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_3/nf-dxgi1_3-idxgiswapchain2-setmaximumframelatency
870 pub desired_maximum_frame_latency: u32,
871 /// Specifies how the alpha channel of the textures should be handled during compositing.
872 pub alpha_mode: CompositeAlphaMode,
873 /// Specifies what view formats will be allowed when calling `Texture::create_view` on
874 /// the texture returned by `Surface::get_current_texture`.
875 ///
876 /// Views with the same format as the texture are always allowed. Views with a different
877 /// format than the texture require [`crate::DownlevelFlags::SURFACE_VIEW_FORMATS`].
878 /// Note that `wgpu` treats adapters as [WebGPU-compliant][`crate::DownlevelFlags::compliant`]
879 /// even if they lack [`crate::DownlevelFlags::SURFACE_VIEW_FORMATS`].
880 ///
881 /// Currently, a view format may only differ from the surface in srgb-ness (ex: `Rgba8Unorm`
882 /// texture + `Rgba8UnormSrgb` view).
883 ///
884 /// Unlike WebGPU canvases, `wgpu` supports sRGB surface formats.
885 pub view_formats: V,
886}
887
888impl<V: Clone> SurfaceConfiguration<V> {
889 /// Map `view_formats` of the texture descriptor into another.
890 pub fn map_view_formats<'a, M>(
891 &'a self,
892 fun: impl FnOnce(&'a V) -> M,
893 ) -> SurfaceConfiguration<M> {
894 SurfaceConfiguration {
895 usage: self.usage,
896 format: self.format,
897 color_space: self.color_space,
898 width: self.width,
899 height: self.height,
900 present_mode: self.present_mode,
901 desired_maximum_frame_latency: self.desired_maximum_frame_latency,
902 alpha_mode: self.alpha_mode,
903 view_formats: fun(&self.view_formats),
904 }
905 }
906}
907
908/// Status of the received surface image.
909#[repr(C)]
910#[derive(Debug)]
911pub enum SurfaceStatus {
912 /// No issues.
913 Good,
914 /// The swap chain is operational, but it does no longer perfectly
915 /// match the surface. A re-configuration is needed.
916 Suboptimal,
917 /// Unable to get the next frame, timed out.
918 ///
919 /// Try reconfiguring your surface.
920 Timeout,
921 /// The window is occluded (e.g. minimized or behind another window).
922 ///
923 /// Try again once the window is no longer occluded.
924 Occluded,
925 /// The surface under the swap chain has changed.
926 ///
927 /// Try reconfiguring your surface.
928 Outdated,
929 /// The surface under the swap chain is lost.
930 Lost,
931 /// `Surface::get_current_texture` has hit a validation error which was caught
932 /// by a error scope.
933 Validation,
934}
935
936/// Nanosecond timestamp used by the presentation engine.
937///
938/// The specific clock depends on the window system integration (WSI) API used.
939///
940/// <table>
941/// <tr>
942/// <td>WSI</td>
943/// <td>Clock</td>
944/// </tr>
945/// <tr>
946/// <td>IDXGISwapchain</td>
947/// <td><a href="https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter">QueryPerformanceCounter</a></td>
948/// </tr>
949/// <tr>
950/// <td>IPresentationManager</td>
951/// <td><a href="https://docs.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryinterrupttimeprecise">QueryInterruptTimePrecise</a></td>
952/// </tr>
953/// <tr>
954/// <td>CAMetalLayer</td>
955/// <td><a href="https://developer.apple.com/documentation/kernel/1462446-mach_absolute_time">mach_absolute_time</a></td>
956/// </tr>
957/// <tr>
958/// <td>VK_GOOGLE_display_timing</td>
959/// <td><a href="https://linux.die.net/man/3/clock_gettime">clock_gettime(CLOCK_MONOTONIC)</a></td>
960/// </tr>
961/// </table>
962#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
963pub struct PresentationTimestamp(
964 /// Timestamp in nanoseconds.
965 pub u128,
966);
967
968impl PresentationTimestamp {
969 /// A timestamp that is invalid due to the platform not having a timestamp system.
970 pub const INVALID_TIMESTAMP: Self = Self(u128::MAX);
971
972 /// Returns true if this timestamp is the invalid timestamp.
973 #[must_use]
974 pub fn is_invalid(self) -> bool {
975 self == Self::INVALID_TIMESTAMP
976 }
977}
978
979#[cfg(test)]
980mod display_hdr_info_tests {
981 use super::*;
982
983 #[test]
984 fn default_is_unknown() {
985 // Nothing known, so no headroom is derived — it never guesses SDR vs HDR.
986 assert_eq!(DisplayHdrInfo::default().tone_map_headroom(), None);
987 }
988
989 #[test]
990 fn apple_headroom_is_used_directly() {
991 // Apple reports a live multiplier; it's returned as-is.
992 let info = DisplayHdrInfo {
993 headroom: Some(DisplayHeadroom {
994 current: Some(3.0),
995 potential: Some(5.0),
996 reference: None,
997 }),
998 ..Default::default()
999 };
1000 assert_eq!(info.tone_map_headroom(), Some(3.0));
1001 }
1002
1003 #[test]
1004 fn apple_uses_current_not_potential() {
1005 // A capable panel with no headroom right now (current 1.0, potential 16.0
1006 // — e.g. macOS at full brightness). The live value wins; the potential
1007 // ceiling is never tone-mapped against.
1008 let info = DisplayHdrInfo {
1009 headroom: Some(DisplayHeadroom {
1010 current: Some(1.0),
1011 potential: Some(16.0),
1012 reference: None,
1013 }),
1014 ..Default::default()
1015 };
1016 assert_eq!(info.tone_map_headroom(), Some(1.0));
1017 }
1018
1019 #[test]
1020 fn windows_nits_derive_headroom_only_with_sdr_white() {
1021 // Both nits present and sdr_white > 0, so it returns the ratio.
1022 let info = DisplayHdrInfo {
1023 luminance: Some(DisplayLuminance {
1024 max_nits: Some(800.0),
1025 sdr_white_nits: Some(200.0),
1026 ..Default::default()
1027 }),
1028 ..Default::default()
1029 };
1030 assert_eq!(info.tone_map_headroom(), Some(4.0));
1031
1032 // max_nits known but sdr_white unknown, so it won't guess across frames.
1033 let info = DisplayHdrInfo {
1034 luminance: Some(DisplayLuminance {
1035 max_nits: Some(800.0),
1036 sdr_white_nits: None,
1037 ..Default::default()
1038 }),
1039 ..Default::default()
1040 };
1041 assert_eq!(info.tone_map_headroom(), None);
1042 }
1043
1044 #[test]
1045 fn sdr_display_collapses_to_unity() {
1046 // A definitively-SDR display (`dynamic-range: standard`) has no usable
1047 // headroom, even with no luminance figures at all.
1048 let info = DisplayHdrInfo {
1049 coarse: Some(DisplayCoarseRange {
1050 high_dynamic_range: Some(false),
1051 gamut: Some(DisplayGamut::Srgb),
1052 }),
1053 ..Default::default()
1054 };
1055 assert_eq!(info.tone_map_headroom(), Some(1.0));
1056 }
1057
1058 #[test]
1059 fn sdr_display_overrides_panel_nits() {
1060 // An SDR-mode output still reports its EDID peak (270 nits) against a
1061 // default 80-nit SDR white. That 270/80 ratio is unusable, so the SDR flag
1062 // wins and the headroom collapses to 1.0 rather than 3.375.
1063 let info = DisplayHdrInfo {
1064 luminance: Some(DisplayLuminance {
1065 max_nits: Some(270.0),
1066 sdr_white_nits: Some(80.0),
1067 ..Default::default()
1068 }),
1069 coarse: Some(DisplayCoarseRange {
1070 high_dynamic_range: Some(false),
1071 gamut: Some(DisplayGamut::DisplayP3),
1072 }),
1073 ..Default::default()
1074 };
1075 assert_eq!(info.tone_map_headroom(), Some(1.0));
1076 }
1077
1078 #[test]
1079 fn coarse_hdr_capable_alone_derives_nothing() {
1080 // `dynamic-range: high` (the web's only signal) means the display is
1081 // HDR-capable, not that headroom is available — and it carries no
1082 // luminance to derive one from, so the headroom stays unknown.
1083 let info = DisplayHdrInfo {
1084 coarse: Some(DisplayCoarseRange {
1085 high_dynamic_range: Some(true),
1086 gamut: Some(DisplayGamut::Rec2020),
1087 }),
1088 ..Default::default()
1089 };
1090 assert_eq!(info.tone_map_headroom(), None);
1091 }
1092
1093 #[test]
1094 fn non_finite_current_falls_through_to_nits() {
1095 // A non-finite EDR read is skipped, not leaked; the nit ratio answers.
1096 let info = DisplayHdrInfo {
1097 headroom: Some(DisplayHeadroom {
1098 current: Some(f32::INFINITY),
1099 ..Default::default()
1100 }),
1101 luminance: Some(DisplayLuminance {
1102 max_nits: Some(1000.0),
1103 sdr_white_nits: Some(100.0),
1104 ..Default::default()
1105 }),
1106 ..Default::default()
1107 };
1108 assert_eq!(info.tone_map_headroom(), Some(10.0));
1109 }
1110}