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 pub supports_wide_gamut: bool,
56 pub supports_hdr: bool,
57 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 pub text_subpixel_order: TextSubpixelOrder,
71 pub notes: String,
72}
73
74impl DisplayCapabilities {
75 pub fn sdr() -> Self {
77 Self {
78 notes: "Simulated SDR display".to_string(),
79 ..Self::default()
80 }
81 }
82
83 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 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#[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
181pub enum RequestedToneMappingMode {
182 #[default]
184 Automatic,
185 Clamp,
188 Reinhard,
192}
193
194pub fn fit_to_sdr(color: [f32; 3], mode: RequestedToneMappingMode) -> [f32; 3] {
197 SdrFit::for_tone_mapping(mode).apply(color)
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
202pub(crate) enum SdrFit {
203 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 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
253pub(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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
348pub enum OutputGamut {
349 #[default]
351 Srgb,
352 DisplayP3,
354 Display,
358}
359
360impl OutputGamut {
361 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 = self
487 .intermediate_targets
488 .get(&frame.window_id)
489 .map(|target| target.format)
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 )?;
498 self.encode_output_transform_pass(
499 frame.window_id,
500 &intermediate_view,
501 &final_view,
502 final_format,
503 strategy,
504 requested_tone_mapping,
505 sdr_content_brightness_nits,
506 display_sdr_white_nits,
507 &mut frame_stats,
508 &mut encoder,
509 )?;
510 self.submit_frame_encoder(encoder, &mut frame_stats);
511 Ok(frame_stats)
512 } else {
513 self.shared
514 .as_mut()
515 .expect("renderer shared state initialized")
516 .sdr_fit = SdrFit::for_tone_mapping(requested_tone_mapping);
517 self.submit_prepared_scene(prepared, final_format, &final_view)
518 }
519 }
520
521 pub(crate) fn render_offscreen(
522 &mut self,
523 frame: &SceneFrame,
524 size: (u32, u32),
525 ) -> Result<RendererFrameStats> {
526 self.ensure_shared(None)?;
527
528 let final_format = wgpu::TextureFormat::Bgra8UnormSrgb;
529 let target_started = self.runtime_diagnostics_enabled.then(Instant::now);
530 let final_view = self.ensure_offscreen_target(frame.window_id, size, final_format)?;
531 let mut target_us =
532 target_started.map_or(0, |started| started.elapsed().as_micros() as u64);
533 let prepared = self.prepare_scene_submission(frame)?;
534 let target_started = self.runtime_diagnostics_enabled.then(Instant::now);
535 let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
536 let intermediate_format = self
537 .intermediate_targets
538 .get(&frame.window_id)
539 .map(|target| target.format)
540 .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
541 target_us += target_started.map_or(0, |started| started.elapsed().as_micros() as u64);
542 let mut encoder = self.frame_encoder();
543 let mut frame_stats = self.encode_prepared_scene(
544 prepared,
545 intermediate_format,
546 &intermediate_view,
547 &mut encoder,
548 )?;
549 self.encode_output_transform_pass(
550 frame.window_id,
551 &intermediate_view,
552 &final_view,
553 final_format,
554 OutputStrategy::SdrSurface {
555 format: final_format,
556 },
557 self.window_color_management(frame.window_id).tone_mapping,
559 ColorManagementMode::default().sdr_content_brightness_nits,
560 None,
561 &mut frame_stats,
562 &mut encoder,
563 )?;
564 self.submit_frame_encoder(encoder, &mut frame_stats);
565 frame_stats.target_prepare_time_us = target_us;
566 Ok(frame_stats)
567 }
568
569 pub(crate) fn ensure_offscreen_target(
570 &mut self,
571 window_id: WindowId,
572 size: (u32, u32),
573 format: wgpu::TextureFormat,
574 ) -> Result<wgpu::TextureView> {
575 let recreate = self
576 .offscreen_targets
577 .get(&window_id)
578 .is_none_or(|target| target.size != size || target.format != format);
579 if recreate {
580 let shared = self
581 .shared
582 .as_ref()
583 .expect("renderer shared state initialized");
584 let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
585 label: Some("SUI offscreen frame"),
586 size: wgpu::Extent3d {
587 width: size.0,
588 height: size.1,
589 depth_or_array_layers: 1,
590 },
591 mip_level_count: 1,
592 sample_count: 1,
593 dimension: wgpu::TextureDimension::D2,
594 format,
595 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
596 view_formats: &[],
597 });
598 self.offscreen_targets.insert(
599 window_id,
600 OffscreenTarget {
601 view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
602 texture,
603 format,
604 size,
605 },
606 );
607 }
608 self.offscreen_targets
609 .get(&window_id)
610 .map(|target| target.view.clone())
611 .ok_or_else(|| Error::new(format!("missing target for window {}", window_id.get())))
612 }
613
614 pub(crate) fn ensure_intermediate_target(
615 &mut self,
616 window_id: WindowId,
617 size: (u32, u32),
618 ) -> Result<wgpu::TextureView> {
619 let format = wgpu::TextureFormat::Rgba16Float;
620 let recreate = self
621 .intermediate_targets
622 .get(&window_id)
623 .is_none_or(|target| target.size != size || target.format != format);
624 if recreate {
625 let shared = self
626 .shared
627 .as_ref()
628 .expect("renderer shared state initialized");
629 let texture = shared.device.create_texture(&wgpu::TextureDescriptor {
630 label: Some("SUI HDR intermediate frame"),
631 size: wgpu::Extent3d {
632 width: size.0,
633 height: size.1,
634 depth_or_array_layers: 1,
635 },
636 mip_level_count: 1,
637 sample_count: 1,
638 dimension: wgpu::TextureDimension::D2,
639 format,
640 usage: wgpu::TextureUsages::RENDER_ATTACHMENT
641 | wgpu::TextureUsages::TEXTURE_BINDING
642 | wgpu::TextureUsages::COPY_SRC,
643 view_formats: &[],
644 });
645 self.intermediate_targets.insert(
646 window_id,
647 OffscreenTarget {
648 view: texture.create_view(&wgpu::TextureViewDescriptor::default()),
649 texture,
650 format,
651 size,
652 },
653 );
654 }
655 self.intermediate_targets
656 .get(&window_id)
657 .map(|target| target.view.clone())
658 .ok_or_else(|| Error::new(format!("missing target for window {}", window_id.get())))
659 }
660
661 #[cfg(test)]
662 #[allow(clippy::too_many_arguments)]
663 pub(crate) fn submit_output_transform_pass(
664 &mut self,
665 window_id: WindowId,
666 source: &wgpu::TextureView,
667 destination: &wgpu::TextureView,
668 format: wgpu::TextureFormat,
669 strategy: OutputStrategy,
670 tone: RequestedToneMappingMode,
671 brightness: f32,
672 white: Option<f32>,
673 stats: &mut RendererFrameStats,
674 ) -> Result<()> {
675 let mut encoder = self.frame_encoder();
676 self.encode_output_transform_pass(
677 window_id,
678 source,
679 destination,
680 format,
681 strategy,
682 tone,
683 brightness,
684 white,
685 stats,
686 &mut encoder,
687 )?;
688 self.submit_frame_encoder(encoder, stats);
689 Ok(())
690 }
691
692 pub(crate) fn encode_output_transform_pass(
693 &mut self,
694 window_id: WindowId,
695 source_view: &wgpu::TextureView,
696 destination_view: &wgpu::TextureView,
697 destination_format: wgpu::TextureFormat,
698 strategy: OutputStrategy,
699 requested_tone_mapping: RequestedToneMappingMode,
700 sdr_content_brightness_nits: f32,
701 display_sdr_white_nits: Option<f32>,
702 frame_stats: &mut RendererFrameStats,
703 encoder: &mut wgpu::CommandEncoder,
704 ) -> Result<()> {
705 let prepare_started = self.runtime_diagnostics_enabled.then(Instant::now);
706 let resolved_tone_mapping =
707 SdrFit::for_output(strategy, requested_tone_mapping).shader_value();
708 let shared = self
709 .shared
710 .as_mut()
711 .expect("renderer shared state initialized");
712 let sdr_content_scale = crate::output::output_sdr_content_scale(
713 strategy,
714 sdr_content_brightness_nits,
715 display_sdr_white_nits,
716 );
717 let encode_srgb = matches!(
718 destination_format,
719 wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm
720 ) || matches!(
721 strategy,
722 OutputStrategy::HdrNativeSurface {
723 transfer: DisplayTransferFunction::Srgb,
724 ..
725 }
726 );
727 let uniform = OutputTransformUniform::new(
728 resolved_tone_mapping,
729 encode_srgb,
730 crate::output::output_primaries(strategy),
731 sdr_content_scale,
732 );
733 let cache = &mut self.frame_resources.output_transforms;
734 let recreate = cache
735 .get(&window_id)
736 .is_none_or(|cached| cached.source_view != *source_view);
737 if recreate {
738 let uniform_buffer = shared.device.create_buffer(&wgpu::BufferDescriptor {
739 label: Some("SUI output transform uniform"),
740 size: std::mem::size_of::<OutputTransformUniform>() as u64,
741 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
742 mapped_at_creation: false,
743 });
744 let bind_group = shared.device.create_bind_group(&wgpu::BindGroupDescriptor {
745 label: Some("SUI output transform bind group"),
746 layout: &shared.output_transform_bind_group_layout,
747 entries: &[
748 wgpu::BindGroupEntry {
749 binding: 0,
750 resource: wgpu::BindingResource::TextureView(source_view),
751 },
752 wgpu::BindGroupEntry {
753 binding: 1,
754 resource: uniform_buffer.as_entire_binding(),
755 },
756 ],
757 });
758 cache.insert(
759 window_id,
760 CachedOutputTransform {
761 source_view: source_view.clone(),
762 uniform,
763 buffer: uniform_buffer,
764 bind_group,
765 },
766 );
767 }
768 let cached = cache
769 .get_mut(&window_id)
770 .expect("output transform resources allocated");
771 if recreate || cached.uniform != uniform {
772 self.frame_resources.uploads.write_buffer(
773 &shared.device,
774 &cached.buffer,
775 0,
776 bytemuck::bytes_of(&uniform),
777 );
778 cached.uniform = uniform;
779 }
780 let bind_group = cached.bind_group.clone();
781 if let Some(started) = prepare_started {
782 frame_stats.gpu_upload_time_us += started.elapsed().as_micros() as u64;
783 }
784 let encode_started = self.runtime_diagnostics_enabled.then(Instant::now);
785 {
786 let pipeline = shared.output_transform_pipeline(destination_format);
787 let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
788 label: Some("SUI output transform pass"),
789 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
790 view: destination_view,
791 depth_slice: None,
792 resolve_target: None,
793 ops: wgpu::Operations {
794 load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
795 store: wgpu::StoreOp::Store,
796 },
797 })],
798 depth_stencil_attachment: None,
799 occlusion_query_set: None,
800 timestamp_writes: None,
801 multiview_mask: None,
802 });
803 pass.set_pipeline(pipeline);
804 pass.set_bind_group(0, &bind_group, &[]);
805 pass.draw(0..3, 0..1);
806 }
807 if let Some(started) = encode_started {
808 frame_stats.pass_encode_time_us += started.elapsed().as_micros() as u64;
809 }
810 frame_stats.pass_count += 1;
811 Ok(())
812 }
813}
814
815pub(crate) fn shader_color(color: Color) -> [f32; 4] {
816 let linear = color.to_linear_srgb();
817 [
818 linear.red,
819 linear.green,
820 linear.blue,
821 linear.alpha.clamp(0.0, 1.0),
822 ]
823}
824
825pub(crate) fn preferred_surface_format(
826 formats: &[wgpu::TextureFormat],
827) -> Option<wgpu::TextureFormat> {
828 formats
829 .iter()
830 .copied()
831 .find(wgpu::TextureFormat::is_srgb)
832 .or_else(|| formats.first().copied())
833}
834
835pub(crate) fn preferred_hdr_surface_format(
836 formats: &[wgpu::TextureFormat],
837) -> Option<wgpu::TextureFormat> {
838 formats
839 .iter()
840 .copied()
841 .find(|format| matches!(format, wgpu::TextureFormat::Rgba16Float))
842}
843
844pub(crate) fn output_transform_requires_intermediate(strategy: OutputStrategy) -> bool {
845 match strategy {
846 OutputStrategy::HdrNativeSurface { .. }
847 | OutputStrategy::HdrIntermediateThenToneMap { .. } => true,
848 OutputStrategy::WideGamutSurface { format, primaries } => {
849 !format.is_srgb() || !matches!(primaries, DisplayColorPrimaries::Srgb)
850 }
851 OutputStrategy::SdrSurface { format } => !format.is_srgb(),
852 }
853}
854
855pub(crate) fn output_allows_lcd(strategy: OutputStrategy) -> bool {
858 matches!(
859 strategy,
860 OutputStrategy::SdrSurface { .. }
861 | OutputStrategy::WideGamutSurface {
862 primaries: DisplayColorPrimaries::Srgb,
863 ..
864 }
865 )
866}
867
868pub(crate) fn output_primaries(strategy: OutputStrategy) -> DisplayColorPrimaries {
869 match strategy {
870 OutputStrategy::SdrSurface { .. } => DisplayColorPrimaries::Srgb,
871 OutputStrategy::WideGamutSurface { primaries, .. }
872 | OutputStrategy::HdrNativeSurface { primaries, .. }
873 | OutputStrategy::HdrIntermediateThenToneMap { primaries, .. } => primaries,
874 }
875}
876
877pub(crate) fn output_sdr_content_scale(
878 strategy: OutputStrategy,
879 brightness_nits: f32,
880 _display_sdr_white_nits: Option<f32>,
881) -> f32 {
882 let sanitized = if brightness_nits.is_finite() && brightness_nits > 0.0 {
883 brightness_nits
884 } else {
885 DEFAULT_SDR_CONTENT_BRIGHTNESS_NITS
886 };
887
888 match strategy {
889 OutputStrategy::HdrNativeSurface { .. } => sanitized / SCRGB_REFERENCE_WHITE_NITS,
893 OutputStrategy::SdrSurface { .. }
894 | OutputStrategy::WideGamutSurface { .. }
895 | OutputStrategy::HdrIntermediateThenToneMap { .. } => 1.0,
896 }
897}
898
899#[cfg(test)]
900pub(crate) fn apply_output_transform_for_testing(
901 color: [f32; 4],
902 strategy: OutputStrategy,
903 mode: RequestedToneMappingMode,
904 sdr_content_brightness_nits: f32,
905 display_sdr_white_nits: Option<f32>,
906) -> [f32; 4] {
907 let scale = output_sdr_content_scale(
908 strategy,
909 sdr_content_brightness_nits,
910 display_sdr_white_nits,
911 );
912 let scaled = [
913 color[0] * scale,
914 color[1] * scale,
915 color[2] * scale,
916 color[3],
917 ];
918
919 let fit = SdrFit::for_output(strategy, mode);
920 let mut output = linear_srgb_to_output_primaries([scaled[0], scaled[1], scaled[2]], strategy);
921 if fit != SdrFit::None {
922 output = output.map(|channel| channel.max(0.0));
923 }
924 let [red, green, blue] = fit.apply(output);
925 [red, green, blue, scaled[3].clamp(0.0, 1.0)]
926}
927
928#[cfg(test)]
929pub(crate) fn linear_srgb_to_output_primaries(
930 color: [f32; 3],
931 strategy: OutputStrategy,
932) -> [f32; 3] {
933 match output_primaries(strategy) {
934 DisplayColorPrimaries::Srgb => color,
935 DisplayColorPrimaries::DisplayP3 => [
936 (0.822_461_96 * color[0]) + (0.177_538_02 * color[1]),
937 (0.033_194_2 * color[0]) + (0.966_805_76 * color[1]),
938 (0.017_082_63 * color[0]) + (0.072_397_43 * color[1]) + (0.910_519_96 * color[2]),
939 ],
940 }
941}
942
943pub(crate) fn requested_output_primaries(
944 capabilities: DisplayCapabilities,
945 requested: ColorManagementMode,
946) -> DisplayColorPrimaries {
947 match requested.output_primaries {
948 RequestedOutputColorPrimaries::Automatic => {
949 if capabilities.supports_wide_gamut {
950 capabilities.preferred_primaries
951 } else {
952 DisplayColorPrimaries::Srgb
953 }
954 }
955 RequestedOutputColorPrimaries::Srgb => DisplayColorPrimaries::Srgb,
956 RequestedOutputColorPrimaries::DisplayP3 => {
957 if capabilities.supports_wide_gamut {
958 DisplayColorPrimaries::DisplayP3
959 } else {
960 DisplayColorPrimaries::Srgb
961 }
962 }
963 }
964}
965
966pub(crate) fn select_output_strategy(
967 formats: &[wgpu::TextureFormat],
968 capabilities: DisplayCapabilities,
969 requested: ColorManagementMode,
970) -> OutputStrategy {
971 let sdr_format =
972 preferred_surface_format(formats).unwrap_or(wgpu::TextureFormat::Bgra8UnormSrgb);
973 let primaries = requested_output_primaries(capabilities.clone(), requested);
974 let native_hdr_format = preferred_hdr_surface_format(formats);
975 let native_hdr_available =
976 capabilities.native_hdr_presentation_supported && native_hdr_format.is_some();
977
978 if matches!(requested.mode, RequestedColorManagementMode::ForceSdr) {
979 return OutputStrategy::SdrSurface { format: sdr_format };
980 }
981
982 let wants_hdr = match requested.dynamic_range {
983 RequestedDynamicRangeMode::HighDynamicRange => true,
984 RequestedDynamicRangeMode::StandardDynamicRange => false,
985 RequestedDynamicRangeMode::Automatic => match requested.mode {
986 RequestedColorManagementMode::PreferHdr => true,
987 RequestedColorManagementMode::Automatic => {
988 native_hdr_available
989 || capabilities.supports_hdr
990 || matches!(
991 capabilities.preferred_dynamic_range,
992 DynamicRangeMode::HighDynamicRange
993 )
994 }
995 RequestedColorManagementMode::ForceSdr
996 | RequestedColorManagementMode::PreferWideGamut => false,
997 },
998 };
999 let wants_wide_gamut = match requested.output_primaries {
1000 RequestedOutputColorPrimaries::DisplayP3 => true,
1001 RequestedOutputColorPrimaries::Srgb => false,
1002 RequestedOutputColorPrimaries::Automatic => match requested.mode {
1003 RequestedColorManagementMode::PreferWideGamut
1004 | RequestedColorManagementMode::PreferHdr => true,
1005 RequestedColorManagementMode::Automatic => capabilities.supports_wide_gamut,
1006 RequestedColorManagementMode::ForceSdr => false,
1007 },
1008 };
1009
1010 if wants_hdr {
1011 if native_hdr_available && let Some(format) = native_hdr_format {
1012 let uses_linear_sc_rgb = capabilities.native_hdr_presentation_supported
1013 && matches!(
1014 capabilities.preferred_primaries,
1015 DisplayColorPrimaries::Srgb
1016 );
1017 let transfer = if uses_linear_sc_rgb {
1018 DisplayTransferFunction::LinearExtended
1019 } else {
1020 DisplayTransferFunction::Srgb
1021 };
1022 return OutputStrategy::HdrNativeSurface {
1023 format,
1024 primaries: DisplayColorPrimaries::Srgb,
1025 transfer,
1026 };
1027 }
1028
1029 return OutputStrategy::SdrSurface { format: sdr_format };
1033 }
1034
1035 if wants_wide_gamut && capabilities.supports_wide_gamut {
1036 return OutputStrategy::WideGamutSurface {
1037 format: sdr_format,
1038 primaries,
1039 };
1040 }
1041
1042 OutputStrategy::SdrSurface { format: sdr_format }
1043}