Skip to main content

sui_render_wgpu/
output.rs

1use crate::WgpuRenderer;
2use crate::diagnostics::RendererFrameStats;
3use crate::resources::OffscreenTarget;
4use bytemuck::Pod;
5use bytemuck::Zeroable;
6use sui_core::Color;
7use sui_core::Error;
8use sui_core::Result;
9use sui_core::WindowId;
10use sui_scene::SceneFrame;
11use sui_scene::TextSubpixelOrder;
12use web_time::Instant;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct RendererCapabilities {
16    pub supports_color_management: bool,
17    pub supports_offscreen_surfaces: bool,
18}
19
20impl Default for RendererCapabilities {
21    fn default() -> Self {
22        Self {
23            supports_color_management: true,
24            supports_offscreen_surfaces: true,
25        }
26    }
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
30pub enum DisplayColorPrimaries {
31    #[default]
32    Srgb,
33    DisplayP3,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37pub enum DynamicRangeMode {
38    #[default]
39    StandardDynamicRange,
40    HighDynamicRange,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
44pub enum DisplayTransferFunction {
45    #[default]
46    Srgb,
47    LinearExtended,
48    Pq,
49    Hlg,
50}
51
52#[derive(Debug, Clone, PartialEq)]
53pub struct DisplayCapabilities {
54    /// Whether the display shows colors beyond sRGB.
55    pub supports_wide_gamut: bool,
56    pub supports_hdr: bool,
57    /// The primaries to encode output for this display in. A display
58    /// presenting HDR as scRGB prefers sRGB primaries even when it shows
59    /// wider colors, which scRGB carries as values beyond sRGB's range; see
60    /// [`OutputStrategy::gamut`] for the colors an output shows.
61    pub preferred_primaries: DisplayColorPrimaries,
62    pub preferred_dynamic_range: DynamicRangeMode,
63    pub max_luminance_nits: Option<f32>,
64    pub sdr_white_nits: Option<f32>,
65    pub max_content_headroom: Option<f32>,
66    pub native_hdr_presentation_supported: bool,
67    /// The subpixel order the system antialiases text for on this display, or
68    /// `None` when it uses grayscale antialiasing or does not say. Windows that
69    /// follow the system's text smoothing render LCD text in this order.
70    pub text_subpixel_order: TextSubpixelOrder,
71    pub notes: String,
72}
73
74impl DisplayCapabilities {
75    /// An sRGB display that shows SDR only.
76    pub fn sdr() -> Self {
77        Self {
78            notes: "Simulated SDR display".to_string(),
79            ..Self::default()
80        }
81    }
82
83    /// A Display P3 display that shows SDR only.
84    pub fn wide_gamut() -> Self {
85        Self {
86            supports_wide_gamut: true,
87            preferred_primaries: DisplayColorPrimaries::DisplayP3,
88            notes: "Simulated wide-gamut SDR display".to_string(),
89            ..Self::default()
90        }
91    }
92
93    /// A wide-gamut display presenting HDR natively as scRGB, as Windows HDR
94    /// displays do, `peak_nits` bright with SDR white at `sdr_white_nits`.
95    pub fn hdr(peak_nits: f32, sdr_white_nits: f32) -> Self {
96        Self {
97            supports_wide_gamut: true,
98            supports_hdr: true,
99            preferred_primaries: DisplayColorPrimaries::Srgb,
100            preferred_dynamic_range: DynamicRangeMode::HighDynamicRange,
101            max_luminance_nits: Some(peak_nits),
102            sdr_white_nits: Some(sdr_white_nits),
103            max_content_headroom: None,
104            native_hdr_presentation_supported: true,
105            notes: "Simulated HDR display".to_string(),
106            ..Self::default()
107        }
108    }
109}
110
111/// Output settings for a window rendered without a surface: it renders as if
112/// presenting to a display with these capabilities, so diagnostics and
113/// final-output captures follow the same strategy a real surface would.
114#[derive(Debug, Clone, Default)]
115pub(crate) struct OffscreenOutput {
116    pub(crate) display_capabilities: DisplayCapabilities,
117    pub(crate) color_management: ColorManagementMode,
118}
119
120impl OffscreenOutput {
121    /// The formats surfaces commonly offer: 8-bit sRGB and 16-bit float.
122    const SURFACE_FORMATS: [wgpu::TextureFormat; 2] = [
123        wgpu::TextureFormat::Bgra8UnormSrgb,
124        wgpu::TextureFormat::Rgba16Float,
125    ];
126
127    pub(crate) fn output_strategy(&self) -> OutputStrategy {
128        select_output_strategy(
129            &Self::SURFACE_FORMATS,
130            self.display_capabilities.clone(),
131            self.color_management,
132        )
133    }
134}
135
136impl Default for DisplayCapabilities {
137    fn default() -> Self {
138        Self {
139            supports_wide_gamut: false,
140            supports_hdr: false,
141            preferred_primaries: DisplayColorPrimaries::Srgb,
142            preferred_dynamic_range: DynamicRangeMode::StandardDynamicRange,
143            max_luminance_nits: None,
144            sdr_white_nits: None,
145            max_content_headroom: None,
146            native_hdr_presentation_supported: false,
147            text_subpixel_order: TextSubpixelOrder::None,
148            notes: "Default SDR capability profile".to_string(),
149        }
150    }
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
154pub enum RequestedOutputColorPrimaries {
155    #[default]
156    Automatic,
157    Srgb,
158    DisplayP3,
159}
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
162pub enum RequestedDynamicRangeMode {
163    #[default]
164    Automatic,
165    StandardDynamicRange,
166    HighDynamicRange,
167}
168
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
170pub enum RequestedColorManagementMode {
171    #[default]
172    Automatic,
173    ForceSdr,
174    PreferWideGamut,
175    PreferHdr,
176}
177
178/// How extended-range colors fit an SDR output. Colors within SDR range
179/// pass through unchanged in every mode, so SDR content looks as authored.
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
181pub enum RequestedToneMappingMode {
182    /// `Clamp` on SDR outputs; native HDR outputs present extended range.
183    #[default]
184    Automatic,
185    /// Clip highlights while keeping their hue: the brightest channel lands
186    /// at SDR white and the others keep their ratio to it.
187    Clamp,
188    /// Clip highlights like `Clamp`, then turn the energy above SDR white
189    /// toward white along a Reinhard curve, so brighter highlights still read
190    /// brighter.
191    Reinhard,
192}
193
194/// Fit a linear color to the SDR range as `mode` does on an SDR output. The
195/// same function runs on the GPU; this is it for inspection and tests.
196pub fn fit_to_sdr(color: [f32; 3], mode: RequestedToneMappingMode) -> [f32; 3] {
197    SdrFit::for_tone_mapping(mode).apply(color)
198}
199
200/// How a pipeline fits colors to its target (see `shaders/sdr_fit.wgsl`).
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
202pub(crate) enum SdrFit {
203    /// Keep extended range: float targets and native HDR output.
204    None,
205    #[default]
206    Clip,
207    RollOff,
208}
209
210impl SdrFit {
211    pub(crate) const fn for_tone_mapping(mode: RequestedToneMappingMode) -> Self {
212        match mode {
213            RequestedToneMappingMode::Automatic | RequestedToneMappingMode::Clamp => Self::Clip,
214            RequestedToneMappingMode::Reinhard => Self::RollOff,
215        }
216    }
217
218    /// The fit an output transform applies for `strategy`.
219    pub(crate) const fn for_output(
220        strategy: OutputStrategy,
221        mode: RequestedToneMappingMode,
222    ) -> Self {
223        match strategy {
224            OutputStrategy::HdrNativeSurface { .. } => Self::None,
225            _ => Self::for_tone_mapping(mode),
226        }
227    }
228
229    pub(crate) const fn shader_value(self) -> u32 {
230        match self {
231            Self::None => 0,
232            Self::Clip => 1,
233            Self::RollOff => 2,
234        }
235    }
236
237    pub(crate) fn apply(self, color: [f32; 3]) -> [f32; 3] {
238        let peak = color[0].max(color[1]).max(color[2]);
239        if self == Self::None || peak <= 1.0 {
240            return color;
241        }
242        let hue = color.map(|channel| channel / peak);
243        match self {
244            Self::RollOff => {
245                let toward_white = 1.0 - 1.0 / peak;
246                hue.map(|channel| channel + (1.0 - channel) * toward_white)
247            }
248            _ => hue,
249        }
250    }
251}
252
253/// Whether draws into `format` keep extended-range values, so they need no
254/// fit before the output transform.
255pub(crate) fn target_keeps_extended_range(format: wgpu::TextureFormat) -> bool {
256    matches!(
257        format,
258        wgpu::TextureFormat::Rgba16Float | wgpu::TextureFormat::Rgba32Float
259    )
260}
261
262pub const DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS: f32 = 203.0;
263pub(crate) const SCRGB_REFERENCE_WHITE_NITS: f32 = 80.0;
264
265#[derive(Debug, Clone, Copy, PartialEq)]
266pub struct ColorManagementMode {
267    pub mode: RequestedColorManagementMode,
268    pub output_primaries: RequestedOutputColorPrimaries,
269    pub dynamic_range: RequestedDynamicRangeMode,
270    pub tone_mapping: RequestedToneMappingMode,
271    pub sdr_content_brightness_nits: f32,
272}
273
274impl Default for ColorManagementMode {
275    fn default() -> Self {
276        Self {
277            mode: RequestedColorManagementMode::Automatic,
278            output_primaries: RequestedOutputColorPrimaries::Automatic,
279            dynamic_range: RequestedDynamicRangeMode::Automatic,
280            tone_mapping: RequestedToneMappingMode::Automatic,
281            sdr_content_brightness_nits: DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS,
282        }
283    }
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
287pub enum OutputStrategy {
288    SdrSurface {
289        format: wgpu::TextureFormat,
290    },
291    WideGamutSurface {
292        format: wgpu::TextureFormat,
293        primaries: DisplayColorPrimaries,
294    },
295    HdrNativeSurface {
296        format: wgpu::TextureFormat,
297        primaries: DisplayColorPrimaries,
298        transfer: DisplayTransferFunction,
299    },
300    /// Debug/offscreen-only path for inspecting HDR scene values on SDR outputs.
301    ///
302    /// Normal presentation should choose native HDR when the environment can present
303    /// HDR end-to-end; otherwise it should render SDR instead of tone mapping HDR.
304    HdrIntermediateThenToneMap {
305        intermediate_format: wgpu::TextureFormat,
306        surface_format: wgpu::TextureFormat,
307        primaries: DisplayColorPrimaries,
308    },
309}
310
311impl OutputStrategy {
312    pub const fn surface_format(self) -> wgpu::TextureFormat {
313        match self {
314            Self::SdrSurface { format }
315            | Self::WideGamutSurface { format, .. }
316            | Self::HdrNativeSurface { format, .. } => format,
317            Self::HdrIntermediateThenToneMap { surface_format, .. } => surface_format,
318        }
319    }
320
321    /// The colors this output shows on a display with `capabilities`.
322    ///
323    /// Outputs clip colors to their primaries, except native HDR, which
324    /// keeps extended range: colors beyond its primaries reach the display,
325    /// which shows as many as it can.
326    pub fn gamut(self, capabilities: &DisplayCapabilities) -> OutputGamut {
327        let clipped_to = |primaries| match primaries {
328            DisplayColorPrimaries::Srgb => OutputGamut::Srgb,
329            DisplayColorPrimaries::DisplayP3 => OutputGamut::DisplayP3,
330        };
331        match self {
332            Self::SdrSurface { .. } => OutputGamut::Srgb,
333            Self::WideGamutSurface { primaries, .. }
334            | Self::HdrIntermediateThenToneMap { primaries, .. } => clipped_to(primaries),
335            Self::HdrNativeSurface { primaries, .. } => {
336                if capabilities.supports_wide_gamut {
337                    OutputGamut::Display
338                } else {
339                    clipped_to(primaries)
340                }
341            }
342        }
343    }
344}
345
346/// The colors an output shows.
347#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
348pub enum OutputGamut {
349    /// sRGB colors; others are clipped to sRGB.
350    #[default]
351    Srgb,
352    /// Display P3 colors; others are clipped to Display P3.
353    DisplayP3,
354    /// The display's own gamut: colors beyond sRGB reach the display
355    /// unclipped, and it shows as many as it can, as with native HDR output
356    /// (scRGB) on a wide-gamut display.
357    Display,
358}
359
360impl OutputGamut {
361    /// Whether colors beyond sRGB reach the display.
362    pub const fn is_wide(self) -> bool {
363        !matches!(self, Self::Srgb)
364    }
365}
366
367#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
368pub enum DebugCaptureStage {
369    HdrIntermediate,
370    #[default]
371    FinalComposed,
372}
373
374impl DebugCaptureStage {
375    pub const fn is_hdr_capable(self) -> bool {
376        matches!(self, Self::HdrIntermediate)
377    }
378
379    pub const fn uses_hdr_intermediate(self) -> bool {
380        matches!(self, Self::HdrIntermediate)
381    }
382}
383
384#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
385pub enum DebugSdrVisualization {
386    #[default]
387    ToneMappedColor,
388    LuminanceHeatmap,
389    HeadroomHeatmap,
390    ClipMask,
391}
392
393#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
394pub enum DebugCaptureEncoding {
395    Exr,
396    #[default]
397    Png,
398}
399
400#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
401pub struct DebugCaptureRequest {
402    pub stage: DebugCaptureStage,
403    pub encoding: DebugCaptureEncoding,
404    pub sdr_visualization: DebugSdrVisualization,
405}
406
407#[repr(C)]
408#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
409pub(crate) struct OutputTransformUniform {
410    pub(crate) tone_mapping_mode: u32,
411    pub(crate) encode_srgb: u32,
412    pub(crate) output_primaries: u32,
413    pub(crate) _padding0: u32,
414    pub(crate) sdr_content_scale: f32,
415    pub(crate) _padding1: [u32; 3],
416}
417
418pub(crate) struct CachedOutputTransform {
419    pub(crate) source_view: wgpu::TextureView,
420    pub(crate) uniform: OutputTransformUniform,
421    pub(crate) buffer: wgpu::Buffer,
422    pub(crate) bind_group: wgpu::BindGroup,
423}
424
425impl OutputTransformUniform {
426    pub(crate) const fn new(
427        tone_mapping_mode: u32,
428        encode_srgb: bool,
429        output_primaries: DisplayColorPrimaries,
430        sdr_content_scale: f32,
431    ) -> Self {
432        Self {
433            tone_mapping_mode,
434            encode_srgb: encode_srgb as u32,
435            output_primaries: match output_primaries {
436                DisplayColorPrimaries::Srgb => 0,
437                DisplayColorPrimaries::DisplayP3 => 1,
438            },
439            _padding0: 0,
440            sdr_content_scale,
441            _padding1: [0; 3],
442        }
443    }
444}
445impl WgpuRenderer {
446    pub(crate) fn render_debug_capture_stage(
447        &mut self,
448        frame: &SceneFrame,
449        size: (u32, u32),
450        request: DebugCaptureRequest,
451    ) -> Result<RendererFrameStats> {
452        match request.stage {
453            DebugCaptureStage::HdrIntermediate => self.render_offscreen(frame, size),
454            DebugCaptureStage::FinalComposed
455                if request.encoding == DebugCaptureEncoding::Png
456                    && request.sdr_visualization == DebugSdrVisualization::ToneMappedColor =>
457            {
458                self.render_offscreen(frame, size)
459            }
460            DebugCaptureStage::FinalComposed => self.render_final_composed_offscreen(frame, size),
461        }
462    }
463
464    pub(crate) fn render_final_composed_offscreen(
465        &mut self,
466        frame: &SceneFrame,
467        size: (u32, u32),
468    ) -> Result<RendererFrameStats> {
469        self.ensure_shared(None)?;
470
471        let Some(strategy) = self.window_output_strategy(frame.window_id) else {
472            return self.render_offscreen(frame, size);
473        };
474        let color_management = self.window_color_management(frame.window_id);
475        let requested_tone_mapping = color_management.tone_mapping;
476        let sdr_content_brightness_nits = color_management.sdr_content_brightness_nits;
477        let display_sdr_white_nits = self
478            .window_display_capabilities(frame.window_id)
479            .and_then(|capabilities| capabilities.sdr_white_nits);
480        let final_format = strategy.surface_format();
481        let final_view = self.ensure_offscreen_target(frame.window_id, size, final_format)?;
482        let prepared = self.prepare_scene_submission(frame)?;
483
484        if output_transform_requires_intermediate(strategy) {
485            let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
486            let (intermediate_format, intermediate_texture) = self
487                .intermediate_targets
488                .get(&frame.window_id)
489                .map(|target| (target.format, target.texture.clone()))
490                .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
491            let mut encoder = self.frame_encoder();
492            let mut frame_stats = self.encode_prepared_scene(
493                prepared,
494                intermediate_format,
495                &intermediate_view,
496                &mut encoder,
497                Some((frame.window_id, &intermediate_texture)),
498            )?;
499            self.encode_output_transform_pass(
500                frame.window_id,
501                &intermediate_view,
502                &final_view,
503                final_format,
504                strategy,
505                requested_tone_mapping,
506                sdr_content_brightness_nits,
507                display_sdr_white_nits,
508                &mut frame_stats,
509                &mut encoder,
510            )?;
511            self.submit_frame_encoder(encoder, &mut frame_stats);
512            Ok(frame_stats)
513        } else {
514            self.shared
515                .as_mut()
516                .expect("renderer shared state initialized")
517                .sdr_fit = SdrFit::for_tone_mapping(requested_tone_mapping);
518            // Drawn elsewhere, so the persistent target no longer shows the
519            // latest frame.
520            self.frame_resources
521                .target_contents
522                .remove(&frame.window_id);
523            self.submit_prepared_scene(prepared, final_format, &final_view)
524        }
525    }
526
527    pub(crate) fn render_offscreen(
528        &mut self,
529        frame: &SceneFrame,
530        size: (u32, u32),
531    ) -> Result<RendererFrameStats> {
532        self.ensure_shared(None)?;
533
534        let final_format = wgpu::TextureFormat::Bgra8UnormSrgb;
535        let target_started = self.runtime_diagnostics_enabled.then(Instant::now);
536        let final_view = self.ensure_offscreen_target(frame.window_id, size, final_format)?;
537        let mut target_us =
538            target_started.map_or(0, |started| started.elapsed().as_micros() as u64);
539        let prepared = self.prepare_scene_submission(frame)?;
540        let target_started = self.runtime_diagnostics_enabled.then(Instant::now);
541        let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
542        let (intermediate_format, intermediate_texture) = self
543            .intermediate_targets
544            .get(&frame.window_id)
545            .map(|target| (target.format, target.texture.clone()))
546            .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
547        target_us += target_started.map_or(0, |started| started.elapsed().as_micros() as u64);
548        let mut encoder = self.frame_encoder();
549        let mut frame_stats = self.encode_prepared_scene(
550            prepared,
551            intermediate_format,
552            &intermediate_view,
553            &mut encoder,
554            Some((frame.window_id, &intermediate_texture)),
555        )?;
556        self.encode_output_transform_pass(
557            frame.window_id,
558            &intermediate_view,
559            &final_view,
560            final_format,
561            OutputStrategy::SdrSurface {
562                format: final_format,
563            },
564            // Fit highlights as the window's own SDR output would.
565            self.window_color_management(frame.window_id).tone_mapping,
566            ColorManagementMode::default().sdr_content_brightness_nits,
567            None,
568            &mut frame_stats,
569            &mut encoder,
570        )?;
571        self.submit_frame_encoder(encoder, &mut frame_stats);
572        frame_stats.target_prepare_time_us = target_us;
573        Ok(frame_stats)
574    }
575
576    /// The persistent frame a native SDR window redraws partially before
577    /// copying it to its swapchain, in the swapchain's format.
578    pub(crate) fn ensure_swapchain_frame(
579        &mut self,
580        window_id: WindowId,
581        size: (u32, u32),
582        format: wgpu::TextureFormat,
583    ) -> Result<(wgpu::TextureView, wgpu::Texture)> {
584        let recreate = self
585            .swapchain_frames
586            .get(&window_id)
587            .is_none_or(|target| target.size != size || target.format != format);
588        if recreate {
589            // A new target shows nothing yet.
590            self.frame_resources.target_contents.remove(&window_id);
591            let texture = self
592                .shared
593                .as_ref()
594                .expect("renderer shared state initialized")
595                .device
596                .create_texture(&wgpu::TextureDescriptor {
597                    label: Some("SUI persistent swapchain frame"),
598                    size: wgpu::Extent3d {
599                        width: size.0,
600                        height: size.1,
601                        depth_or_array_layers: 1,
602                    },
603                    mip_level_count: 1,
604                    sample_count: 1,
605                    dimension: wgpu::TextureDimension::D2,
606                    format,
607                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
608                    view_formats: &[],
609                });
610            self.swapchain_frames.insert(
611                window_id,
612                OffscreenTarget {
613                    view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
614                    texture,
615                    format,
616                    size,
617                },
618            );
619        }
620        let target = &self.swapchain_frames[&window_id];
621        Ok((target.view.clone(), target.texture.clone()))
622    }
623
624    pub(crate) fn ensure_offscreen_target(
625        &mut self,
626        window_id: WindowId,
627        size: (u32, u32),
628        format: wgpu::TextureFormat,
629    ) -> Result<wgpu::TextureView> {
630        let recreate = self
631            .offscreen_targets
632            .get(&window_id)
633            .is_none_or(|target| target.size != size || target.format != format);
634        if recreate {
635            let shared = self
636                .shared
637                .as_ref()
638                .expect("renderer shared state initialized");
639            let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
640                label: Some("SUI offscreen frame"),
641                size: wgpu::Extent3d {
642                    width: size.0,
643                    height: size.1,
644                    depth_or_array_layers: 1,
645                },
646                mip_level_count: 1,
647                sample_count: 1,
648                dimension: wgpu::TextureDimension::D2,
649                format,
650                usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
651                view_formats: &[],
652            });
653            self.offscreen_targets.insert(
654                window_id,
655                OffscreenTarget {
656                    view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
657                    texture,
658                    format,
659                    size,
660                },
661            );
662        }
663        self.offscreen_targets
664            .get(&window_id)
665            .map(|target| target.view.clone())
666            .ok_or_else(|| Error::new(format!("missing target for window {}", window_id.get())))
667    }
668
669    pub(crate) fn ensure_intermediate_target(
670        &mut self,
671        window_id: WindowId,
672        size: (u32, u32),
673    ) -> Result<wgpu::TextureView> {
674        let format = wgpu::TextureFormat::Rgba16Float;
675        let recreate = self
676            .intermediate_targets
677            .get(&window_id)
678            .is_none_or(|target| target.size != size || target.format != format);
679        if recreate {
680            // A new target shows nothing yet.
681            self.frame_resources.target_contents.remove(&window_id);
682            let shared = self
683                .shared
684                .as_ref()
685                .expect("renderer shared state initialized");
686            let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
687                label: Some("SUI HDR intermediate frame"),
688                size: wgpu::Extent3d {
689                    width: size.0,
690                    height: size.1,
691                    depth_or_array_layers: 1,
692                },
693                mip_level_count: 1,
694                sample_count: 1,
695                dimension: wgpu::TextureDimension::D2,
696                format,
697                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
698                    | wgpu::TextureUsages::TEXTURE_BINDING
699                    | wgpu::TextureUsages::COPY_SRC,
700                view_formats: &[],
701            });
702            self.intermediate_targets.insert(
703                window_id,
704                OffscreenTarget {
705                    view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
706                    texture,
707                    format,
708                    size,
709                },
710            );
711        }
712        self.intermediate_targets
713            .get(&window_id)
714            .map(|target| target.view.clone())
715            .ok_or_else(|| Error::new(format!("missing target for window {}", window_id.get())))
716    }
717
718    #[cfg(test)]
719    #[allow(clippy::too_many_arguments)]
720    pub(crate) fn submit_output_transform_pass(
721        &mut self,
722        window_id: WindowId,
723        source: &wgpu::TextureView,
724        destination: &wgpu::TextureView,
725        format: wgpu::TextureFormat,
726        strategy: OutputStrategy,
727        tone: RequestedToneMappingMode,
728        brightness: f32,
729        white: Option<f32>,
730        stats: &mut RendererFrameStats,
731    ) -> Result<()> {
732        let mut encoder = self.frame_encoder();
733        self.encode_output_transform_pass(
734            window_id,
735            source,
736            destination,
737            format,
738            strategy,
739            tone,
740            brightness,
741            white,
742            stats,
743            &mut encoder,
744        )?;
745        self.submit_frame_encoder(encoder, stats);
746        Ok(())
747    }
748
749    pub(crate) fn encode_output_transform_pass(
750        &mut self,
751        window_id: WindowId,
752        source_view: &wgpu::TextureView,
753        destination_view: &wgpu::TextureView,
754        destination_format: wgpu::TextureFormat,
755        strategy: OutputStrategy,
756        requested_tone_mapping: RequestedToneMappingMode,
757        sdr_content_brightness_nits: f32,
758        display_sdr_white_nits: Option<f32>,
759        frame_stats: &mut RendererFrameStats,
760        encoder: &mut wgpu::CommandEncoder,
761    ) -> Result<()> {
762        let prepare_started = self.runtime_diagnostics_enabled.then(Instant::now);
763        let resolved_tone_mapping =
764            SdrFit::for_output(strategy, requested_tone_mapping).shader_value();
765        let shared = self
766            .shared
767            .as_mut()
768            .expect("renderer shared state initialized");
769        let sdr_content_scale = crate::output::output_sdr_content_scale(
770            strategy,
771            sdr_content_brightness_nits,
772            display_sdr_white_nits,
773        );
774        let encode_srgb = matches!(
775            destination_format,
776            wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm
777        ) || matches!(
778            strategy,
779            OutputStrategy::HdrNativeSurface {
780                transfer: DisplayTransferFunction::Srgb,
781                ..
782            }
783        );
784        let uniform = OutputTransformUniform::new(
785            resolved_tone_mapping,
786            encode_srgb,
787            crate::output::output_primaries(strategy),
788            sdr_content_scale,
789        );
790        let cache = &mut self.frame_resources.output_transforms;
791        let recreate = cache
792            .get(&window_id)
793            .is_none_or(|cached| cached.source_view != *source_view);
794        if recreate {
795            let uniform_buffer = shared.device.create_buffer(&wgpu::BufferDescriptor {
796                label: Some("SUI output transform uniform"),
797                size: std::mem::size_of::<OutputTransformUniform>() as u64,
798                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
799                mapped_at_creation: false,
800            });
801            let bind_group = shared.device.create_bind_group(&wgpu::BindGroupDescriptor {
802                label: Some("SUI output transform bind group"),
803                layout: &shared.output_transform_bind_group_layout,
804                entries: &[
805                    wgpu::BindGroupEntry {
806                        binding: 0,
807                        resource: wgpu::BindingResource::TextureView(source_view),
808                    },
809                    wgpu::BindGroupEntry {
810                        binding: 1,
811                        resource: uniform_buffer.as_entire_binding(),
812                    },
813                ],
814            });
815            cache.insert(
816                window_id,
817                CachedOutputTransform {
818                    source_view: source_view.clone(),
819                    uniform,
820                    buffer: uniform_buffer,
821                    bind_group,
822                },
823            );
824        }
825        let cached = cache
826            .get_mut(&window_id)
827            .expect("output transform resources allocated");
828        if recreate || cached.uniform != uniform {
829            self.frame_resources.uploads.write_buffer(
830                &shared.device,
831                &cached.buffer,
832                0,
833                bytemuck::bytes_of(&uniform),
834            );
835            cached.uniform = uniform;
836        }
837        let bind_group = cached.bind_group.clone();
838        if let Some(started) = prepare_started {
839            frame_stats.gpu_upload_time_us += started.elapsed().as_micros() as u64;
840        }
841        let encode_started = self.runtime_diagnostics_enabled.then(Instant::now);
842        {
843            let pipeline = shared.output_transform_pipeline(destination_format);
844            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
845                label: Some("SUI output transform pass"),
846                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
847                    view: destination_view,
848                    depth_slice: None,
849                    resolve_target: None,
850                    ops: wgpu::Operations {
851                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
852                        store: wgpu::StoreOp::Store,
853                    },
854                })],
855                depth_stencil_attachment: None,
856                occlusion_query_set: None,
857                timestamp_writes: None,
858                multiview_mask: None,
859            });
860            pass.set_pipeline(pipeline);
861            pass.set_bind_group(0, &bind_group, &[]);
862            pass.draw(0..3, 0..1);
863        }
864        if let Some(started) = encode_started {
865            frame_stats.pass_encode_time_us += started.elapsed().as_micros() as u64;
866        }
867        frame_stats.pass_count += 1;
868        Ok(())
869    }
870}
871
872pub(crate) fn shader_color(color: Color) -> [f32; 4] {
873    let linear = color.to_linear_srgb();
874    [
875        linear.red,
876        linear.green,
877        linear.blue,
878        linear.alpha.clamp(0.0, 1.0),
879    ]
880}
881
882pub(crate) fn preferred_surface_format(
883    formats: &[wgpu::TextureFormat],
884) -> Option<wgpu::TextureFormat> {
885    formats
886        .iter()
887        .copied()
888        .find(wgpu::TextureFormat::is_srgb)
889        .or_else(|| formats.first().copied())
890}
891
892pub(crate) fn preferred_hdr_surface_format(
893    formats: &[wgpu::TextureFormat],
894) -> Option<wgpu::TextureFormat> {
895    formats
896        .iter()
897        .copied()
898        .find(|format| matches!(format, wgpu::TextureFormat::Rgba16Float))
899}
900
901pub(crate) fn output_transform_requires_intermediate(strategy: OutputStrategy) -> bool {
902    match strategy {
903        OutputStrategy::HdrNativeSurface { .. }
904        | OutputStrategy::HdrIntermediateThenToneMap { .. } => true,
905        OutputStrategy::WideGamutSurface { format, primaries } => {
906            !format.is_srgb() || !matches!(primaries, DisplayColorPrimaries::Srgb)
907        }
908        OutputStrategy::SdrSurface { format } => !format.is_srgb(),
909    }
910}
911
912/// LCD coverage is tied to the final RGB channels. A gamut conversion or HDR
913/// presentation/tone map after blending cannot preserve that interpretation.
914pub(crate) fn output_allows_lcd(strategy: OutputStrategy) -> bool {
915    matches!(
916        strategy,
917        OutputStrategy::SdrSurface { .. }
918            | OutputStrategy::WideGamutSurface {
919                primaries: DisplayColorPrimaries::Srgb,
920                ..
921            }
922    )
923}
924
925pub(crate) fn output_primaries(strategy: OutputStrategy) -> DisplayColorPrimaries {
926    match strategy {
927        OutputStrategy::SdrSurface { .. } => DisplayColorPrimaries::Srgb,
928        OutputStrategy::WideGamutSurface { primaries, .. }
929        | OutputStrategy::HdrNativeSurface { primaries, .. }
930        | OutputStrategy::HdrIntermediateThenToneMap { primaries, .. } => primaries,
931    }
932}
933
934pub(crate) fn output_sdr_content_scale(
935    strategy: OutputStrategy,
936    brightness_nits: f32,
937    _display_sdr_white_nits: Option<f32>,
938) -> f32 {
939    let sanitized = if brightness_nits.is_finite() && brightness_nits > 0.0 {
940        brightness_nits
941    } else {
942        DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS
943    };
944
945    match strategy {
946        // Native HDR is presented as linear scRGB: 1.0 is the 80 nit scRGB
947        // reference, so SDR reference white must be lifted to the requested
948        // SDR-content brightness before presentation.
949        OutputStrategy::HdrNativeSurface { .. } => sanitized / SCRGB_REFERENCE_WHITE_NITS,
950        OutputStrategy::SdrSurface { .. }
951        | OutputStrategy::WideGamutSurface { .. }
952        | OutputStrategy::HdrIntermediateThenToneMap { .. } => 1.0,
953    }
954}
955
956#[cfg(test)]
957pub(crate) fn apply_output_transform_for_testing(
958    color: [f32; 4],
959    strategy: OutputStrategy,
960    mode: RequestedToneMappingMode,
961    sdr_content_brightness_nits: f32,
962    display_sdr_white_nits: Option<f32>,
963) -> [f32; 4] {
964    let scale = output_sdr_content_scale(
965        strategy,
966        sdr_content_brightness_nits,
967        display_sdr_white_nits,
968    );
969    let scaled = [
970        color[0] * scale,
971        color[1] * scale,
972        color[2] * scale,
973        color[3],
974    ];
975
976    let fit = SdrFit::for_output(strategy, mode);
977    let mut output = linear_srgb_to_output_primaries([scaled[0], scaled[1], scaled[2]], strategy);
978    if fit != SdrFit::None {
979        output = output.map(|channel| channel.max(0.0));
980    }
981    let [red, green, blue] = fit.apply(output);
982    [red, green, blue, scaled[3].clamp(0.0, 1.0)]
983}
984
985#[cfg(test)]
986pub(crate) fn linear_srgb_to_output_primaries(
987    color: [f32; 3],
988    strategy: OutputStrategy,
989) -> [f32; 3] {
990    match output_primaries(strategy) {
991        DisplayColorPrimaries::Srgb => color,
992        DisplayColorPrimaries::DisplayP3 => [
993            (0.822_461_96 * color[0]) + (0.177_538_02 * color[1]),
994            (0.033_194_2 * color[0]) + (0.966_805_76 * color[1]),
995            (0.017_082_63 * color[0]) + (0.072_397_43 * color[1]) + (0.910_519_96 * color[2]),
996        ],
997    }
998}
999
1000pub(crate) fn requested_output_primaries(
1001    capabilities: DisplayCapabilities,
1002    requested: ColorManagementMode,
1003) -> DisplayColorPrimaries {
1004    match requested.output_primaries {
1005        RequestedOutputColorPrimaries::Automatic => {
1006            if capabilities.supports_wide_gamut {
1007                capabilities.preferred_primaries
1008            } else {
1009                DisplayColorPrimaries::Srgb
1010            }
1011        }
1012        RequestedOutputColorPrimaries::Srgb => DisplayColorPrimaries::Srgb,
1013        RequestedOutputColorPrimaries::DisplayP3 => {
1014            if capabilities.supports_wide_gamut {
1015                DisplayColorPrimaries::DisplayP3
1016            } else {
1017                DisplayColorPrimaries::Srgb
1018            }
1019        }
1020    }
1021}
1022
1023pub(crate) fn select_output_strategy(
1024    formats: &[wgpu::TextureFormat],
1025    capabilities: DisplayCapabilities,
1026    requested: ColorManagementMode,
1027) -> OutputStrategy {
1028    let sdr_format =
1029        preferred_surface_format(formats).unwrap_or(wgpu::TextureFormat::Bgra8UnormSrgb);
1030    let primaries = requested_output_primaries(capabilities.clone(), requested);
1031    let native_hdr_format = preferred_hdr_surface_format(formats);
1032    let native_hdr_available =
1033        capabilities.native_hdr_presentation_supported && native_hdr_format.is_some();
1034
1035    if matches!(requested.mode, RequestedColorManagementMode::ForceSdr) {
1036        return OutputStrategy::SdrSurface { format: sdr_format };
1037    }
1038
1039    let wants_hdr = match requested.dynamic_range {
1040        RequestedDynamicRangeMode::HighDynamicRange => true,
1041        RequestedDynamicRangeMode::StandardDynamicRange => false,
1042        RequestedDynamicRangeMode::Automatic => match requested.mode {
1043            RequestedColorManagementMode::PreferHdr => true,
1044            RequestedColorManagementMode::Automatic => {
1045                native_hdr_available
1046                    || capabilities.supports_hdr
1047                    || matches!(
1048                        capabilities.preferred_dynamic_range,
1049                        DynamicRangeMode::HighDynamicRange
1050                    )
1051            }
1052            RequestedColorManagementMode::ForceSdr
1053            | RequestedColorManagementMode::PreferWideGamut => false,
1054        },
1055    };
1056    let wants_wide_gamut = match requested.output_primaries {
1057        RequestedOutputColorPrimaries::DisplayP3 => true,
1058        RequestedOutputColorPrimaries::Srgb => false,
1059        RequestedOutputColorPrimaries::Automatic => match requested.mode {
1060            RequestedColorManagementMode::PreferWideGamut
1061            | RequestedColorManagementMode::PreferHdr => true,
1062            RequestedColorManagementMode::Automatic => capabilities.supports_wide_gamut,
1063            RequestedColorManagementMode::ForceSdr => false,
1064        },
1065    };
1066
1067    if wants_hdr {
1068        if native_hdr_available && let Some(format) = native_hdr_format {
1069            let uses_linear_sc_rgb = capabilities.native_hdr_presentation_supported
1070                && matches!(
1071                    capabilities.preferred_primaries,
1072                    DisplayColorPrimaries::Srgb
1073                );
1074            let transfer = if uses_linear_sc_rgb {
1075                DisplayTransferFunction::LinearExtended
1076            } else {
1077                DisplayTransferFunction::Srgb
1078            };
1079            return OutputStrategy::HdrNativeSurface {
1080                format,
1081                primaries: DisplayColorPrimaries::Srgb,
1082                transfer,
1083            };
1084        }
1085
1086        // If HDR cannot be presented end-to-end, normal presentation stays SDR.
1087        // HdrIntermediateThenToneMap is reserved for debug captures and explicit
1088        // diagnostics where seeing HDR scene values on an SDR display is useful.
1089        return OutputStrategy::SdrSurface { format: sdr_format };
1090    }
1091
1092    if wants_wide_gamut && capabilities.supports_wide_gamut {
1093        return OutputStrategy::WideGamutSurface {
1094            format: sdr_format,
1095            primaries,
1096        };
1097    }
1098
1099    OutputStrategy::SdrSurface { format: sdr_format }
1100}