sg_abi/display.rs
1//! Display ABI: present modes, frame pacing, fullscreen and HDR metadata.
2//!
3//! Host functions (module `sg`):
4//!
5//! | Function | Returns |
6//! |---|---|
7//! | `display_info(ptr, cap) -> i64` | JSON document (see [`DisplayInfo`]); its length, copied only if it fits |
8//! | `present_config(mode, latency) -> i32` | a [`status`] code; `mode` is a [`mode`] code or [`mode::KEEP`], `latency` is 1..=3 or 0 to keep |
9//! | `frame_cap(fps: f64) -> i32` | a [`status`] code; `0.0` removes the cap, otherwise [`FPS_CAP_MIN`]..=[`FPS_CAP_MAX`] |
10//! | `fullscreen(mode) -> i32` | a [`status`] code; `mode` is a [`fullscreen`] code |
11//! | `hdr_metadata(ptr, len) -> i32` | a [`status`] code; `len` must be [`HDR_METADATA_SIZE`] |
12//! | `frame_stats(ptr, cap) -> i64` | JSON document (see [`FrameStats`]) |
13//!
14//! Requests are validated by the host; out-of-range values return
15//! [`status::INVALID`], never trap. Only malformed calls (pointers outside
16//! guest memory, a wrong `hdr_metadata` length) trap. The user's launch
17//! settings take precedence over every game request ([`status::LOCKED`]).
18
19/// Return codes of the display functions.
20pub mod status {
21 /// Accepted and applied (or applied at the next frame).
22 pub const OK: i32 = 0;
23 /// Accepted and stored, but it has no effect on the current output
24 /// (e.g. HDR metadata while the swapchain is SDR, or the driver lacks
25 /// `VK_EXT_hdr_metadata`). It is applied if that changes.
26 pub const NOT_APPLIED: i32 = 1;
27 /// A value out of range, NaN, or an unknown code.
28 pub const INVALID: i32 = -1;
29 /// Valid, but the surface/platform cannot do it (e.g. Mailbox on X11).
30 pub const UNSUPPORTED: i32 = -2;
31 /// Refused by policy: fullscreen without a recent user gesture.
32 pub const DENIED: i32 = -3;
33 /// Too many requests; try again later.
34 pub const RATE_LIMITED: i32 = -4;
35 /// The user fixed this setting at launch.
36 pub const LOCKED: i32 = -5;
37}
38
39/// Present-mode codes (the `repr` of `wgpu::PresentMode`).
40pub mod mode {
41 pub const AUTO_VSYNC: u32 = 0;
42 pub const AUTO_NO_VSYNC: u32 = 1;
43 pub const FIFO: u32 = 2;
44 pub const FIFO_RELAXED: u32 = 3;
45 pub const IMMEDIATE: u32 = 4;
46 pub const MAILBOX: u32 = 5;
47 /// `present_config`: leave the mode unchanged.
48 pub const KEEP: u32 = 0xffff_ffff;
49}
50
51/// Fullscreen codes.
52pub mod fullscreen {
53 pub const WINDOWED: u32 = 0;
54 /// A borderless window covering the monitor (no mode change).
55 pub const BORDERLESS: u32 = 1;
56 /// Exclusive fullscreen at the monitor's current video mode (no mode change;
57 /// lets the compositor/X server flip or unredirect). Falls back to borderless
58 /// where the platform has no exclusive mode (Wayland).
59 pub const EXCLUSIVE: u32 = 2;
60}
61
62pub const FPS_CAP_MIN: f64 = 10.0;
63pub const FPS_CAP_MAX: f64 = 1000.0;
64pub const LATENCY_MIN: u32 = 1;
65pub const LATENCY_MAX: u32 = 3;
66
67/// Static HDR metadata (SMPTE ST 2086 mastering display + CTA-861.3 content
68/// light levels), as 12 little-endian `f32`s in this order.
69#[derive(Clone, Copy, Debug, PartialEq, Default)]
70pub struct HdrMetadata {
71 /// CIE 1931 xy chromaticities of the red, green and blue primaries and the white point.
72 pub red: [f32; 2],
73 pub green: [f32; 2],
74 pub blue: [f32; 2],
75 pub white: [f32; 2],
76 /// Mastering display luminance in nits: 0 < max ≤ 10000, 0 ≤ min < max.
77 pub max_luminance: f32,
78 pub min_luminance: f32,
79 /// Maximum content / frame-average light level in nits (0 = unknown), ≤ 10000, FALL ≤ CLL.
80 pub max_cll: f32,
81 pub max_fall: f32,
82}
83
84pub const HDR_METADATA_SIZE: usize = 48;
85
86impl HdrMetadata {
87 /// BT.2020 primaries, D65 white: the usual HDR10 mastering container.
88 pub fn bt2020(max_luminance: f32, min_luminance: f32, max_cll: f32, max_fall: f32) -> Self {
89 HdrMetadata {
90 red: [0.708, 0.292],
91 green: [0.170, 0.797],
92 blue: [0.131, 0.046],
93 white: [0.3127, 0.3290],
94 max_luminance,
95 min_luminance,
96 max_cll,
97 max_fall,
98 }
99 }
100
101 pub fn to_bytes(&self) -> [u8; HDR_METADATA_SIZE] {
102 let v = [
103 self.red[0], self.red[1], self.green[0], self.green[1], self.blue[0], self.blue[1], self.white[0], self.white[1],
104 self.max_luminance, self.min_luminance, self.max_cll, self.max_fall,
105 ];
106 let mut b = [0u8; HDR_METADATA_SIZE];
107 for (i, x) in v.iter().enumerate() {
108 b[i * 4..i * 4 + 4].copy_from_slice(&x.to_le_bytes());
109 }
110 b
111 }
112
113 pub fn from_bytes(b: &[u8]) -> Option<Self> {
114 if b.len() != HDR_METADATA_SIZE {
115 return None;
116 }
117 let f = |i: usize| f32::from_le_bytes([b[i * 4], b[i * 4 + 1], b[i * 4 + 2], b[i * 4 + 3]]);
118 Some(HdrMetadata {
119 red: [f(0), f(1)],
120 green: [f(2), f(3)],
121 blue: [f(4), f(5)],
122 white: [f(6), f(7)],
123 max_luminance: f(8),
124 min_luminance: f(9),
125 max_cll: f(10),
126 max_fall: f(11),
127 })
128 }
129
130 /// Why the metadata is invalid, or `None` if it is valid.
131 pub fn check(&self) -> Option<&'static str> {
132 let all = [
133 self.red[0], self.red[1], self.green[0], self.green[1], self.blue[0], self.blue[1], self.white[0], self.white[1],
134 self.max_luminance, self.min_luminance, self.max_cll, self.max_fall,
135 ];
136 if all.iter().any(|x| !x.is_finite()) {
137 return Some("non-finite value");
138 }
139 for xy in [self.red, self.green, self.blue, self.white] {
140 // The spectral locus lies inside x in [0, 0.74], y in [0, 0.84].
141 if !(0.0..=0.8).contains(&xy[0]) || !(0.0..=0.9).contains(&xy[1]) || xy[0] + xy[1] > 1.0 {
142 return Some("chromaticity outside the CIE xy diagram");
143 }
144 }
145 if !(self.max_luminance > 0.0 && self.max_luminance <= 10000.0) {
146 return Some("max luminance must be in (0, 10000] nits");
147 }
148 if !(self.min_luminance >= 0.0 && self.min_luminance < self.max_luminance) {
149 return Some("min luminance must be in [0, max)");
150 }
151 if !(0.0..=10000.0).contains(&self.max_cll) || !(0.0..=10000.0).contains(&self.max_fall) {
152 return Some("content light levels must be in [0, 10000] nits");
153 }
154 if self.max_cll > 0.0 && self.max_fall > self.max_cll {
155 return Some("MaxFALL above MaxCLL");
156 }
157 None
158 }
159}
160
161/// Field names of the `display_info` JSON document (for reference; the guest
162/// parses it with any JSON library):
163///
164/// ```json
165/// { "present_modes": ["fifo", "immediate"], "present_mode": "fifo", "frame_latency": 2,
166/// "fps_cap": 0, "refresh_hz": 59.94, "fullscreen": "windowed", "backend": "wgpu",
167/// "hdr": { "enabled": true, "metadata_supported": false,
168/// "formats": { "Rgba16Float": ["srgb", "extended_srgb_linear"] } },
169/// "locked": ["present_mode"] }
170/// ```
171pub struct DisplayInfo;
172
173/// Field names of the `frame_stats` JSON document: rolling statistics over the
174/// last 120 presented frames, in milliseconds.
175///
176/// ```json
177/// { "frames": 1234, "interval_ms": {"median": 16.7, "p99": 17.1, "sd": 0.2},
178/// "acquire_ms": {..}, "present_ms": {..}, "display_latency_ms": {..} | null,
179/// "queue_depth": 1.0 }
180/// ```
181pub struct FrameStats;