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